Debian Codegraph @

src/ppx_enumerate.ml

raw symbols SCIP
1 open Base
2 open Ppxlib
3 open Ast_builder.Default
4
5 let name_of_type_name = function
6 | "t" -> "all"
7 | type_name -> "all_of_" ^ type_name
8 ;;
9
10 let name_of_type_variable str = "_" ^ name_of_type_name str
11
12 (* Utility functions *)
13 let enumeration_type_of_td td =
14 let init =
15 let tp = core_type_of_type_declaration td in
16 let loc = tp.ptyp_loc in
17 [%type: [%t tp] list]
18 in
19 List.fold_right td.ptype_params ~init ~f:(fun (tp, _variance) acc ->
20 let loc = tp.ptyp_loc in
21 [%type: [%t tp] list -> [%t acc]])
22 ;;
23
24 let sig_of_td td =
25 let td = name_type_params_in_td td in
26 let enumeration_type = enumeration_type_of_td td in
27 let name = name_of_type_name td.ptype_name.txt in
28 let loc = td.ptype_loc in
29 psig_value
30 ~loc
31 (value_description ~loc ~name:(Located.mk ~loc name) ~type_:enumeration_type ~prim:[])
32 ;;
33
34 let sig_of_tds ~loc ~path:_ (_rec_flag, tds) =
35 let sg_name = "Ppx_enumerate_lib.Enumerable.S" in
36 match mk_named_sig tds ~loc ~sg_name ~handle_polymorphic_variant:true with
37 | Some include_infos -> [ psig_include ~loc include_infos ]
38 | None -> List.map tds ~f:sig_of_td
39 ;;
40
41 let gen_symbol = gen_symbol ~prefix:"enumerate"
42
43 let tuple loc exprs =
44 assert (List.length exprs >= 2);
45 pexp_tuple ~loc exprs
46 ;;
47
48 let patt_tuple loc pats =
49 assert (List.length pats >= 2);
50 ppat_tuple ~loc pats
51 ;;
52
53 let apply e el = eapply ~loc:e.pexp_loc e el
54
55 let labeled_tuple loc ltps exprs =
56 let ltuple = List.map2_exn ~f:(fun (lbl, _) exp -> lbl, exp) ltps exprs in
57 Ppxlib_jane.Jane_syntax.Expression.expr_of ~loc ~attrs:[] (Jexp_tuple ltuple)
58 ;;
59
60 let replace_variables_by_underscores =
61 let map =
62 object
63 inherit Ast_traverse.map as super
64
65 method! core_type_desc ty =
66 match super#core_type_desc ty with
67 | Ptyp_var _ -> Ptyp_any
68 | ty -> ty
69 end
70 in
71 map#core_type
72 ;;
73
74 let list_map loc l ~f =
75 let element = gen_symbol () in
76 let applied = f (evar ~loc element) in
77 [%expr
78 let rec map l acc =
79 match l with
80 | [] -> Ppx_enumerate_lib.List.rev acc
81 | [%p pvar ~loc element] :: l -> map l ([%e applied] :: acc)
82 in
83 map [%e l] []]
84 ;;
85
86 (* [cartesian_product_map l's f loc] takes a list of expressions of type list, and
87 returns code generating the Cartesian product of those lists, with [f] applied to each
88 tuple.
89 *)
90 let cartesian_product_map ~exhaust_check l's ~f loc =
91 match l's with
92 | [] -> Location.raise_errorf ~loc "cartesian_product_map passed list of zero length"
93 | [ l ] -> list_map loc l ~f:(fun x -> f [ x ])
94 | _ ->
95 let lid x = evar ~loc x in
96 let patt_lid x = pvar ~loc x in
97 let alias_vars = List.map l's ~f:(fun _ -> gen_symbol ()) in
98 let init =
99 let len = List.length l's in
100 let hd_vars = List.map l's ~f:(fun _ -> gen_symbol ()) in
101 let args_vars = List.map l's ~f:(fun _ -> gen_symbol ()) in
102 let tl_var = gen_symbol () in
103 let base_case =
104 let patts =
105 List.rev ([%pat? []] :: List.init (len - 1) ~f:(fun _ -> [%pat? _]))
106 in
107 case
108 ~guard:None
109 ~lhs:(patt_tuple loc patts)
110 ~rhs:[%expr Ppx_enumerate_lib.List.rev acc]
111 in
112 let apply_case =
113 let patts =
114 List.mapi hd_vars ~f:(fun i x ->
115 [%pat?
116 [%p pvar ~loc x] :: [%p if i = 0 then patt_lid tl_var else ppat_any ~loc]])
117 in
118 case
119 ~guard:None
120 ~lhs:(patt_tuple loc patts)
121 ~rhs:
122 (apply
123 [%expr loop ([%e f (List.map hd_vars ~f:lid)] :: acc)]
124 (evar ~loc tl_var :: List.map (List.tl_exn args_vars) ~f:lid))
125 in
126 let decrement_cases =
127 List.init (len - 1) ~f:(fun i ->
128 let patts =
129 List.init i ~f:(fun _ -> ppat_any ~loc)
130 @ [ [%pat? []]; [%pat? _ :: [%p pvar ~loc tl_var]] ]
131 @ List.init (len - i - 2) ~f:(fun _ -> ppat_any ~loc)
132 in
133 case
134 ~guard:None
135 ~lhs:(patt_tuple loc patts)
136 ~rhs:
137 (apply
138 [%expr loop acc]
139 (List.map ~f:lid (List.take alias_vars (i + 1))
140 @ (evar ~loc tl_var :: List.map ~f:lid (List.drop args_vars (i + 2))))))
141 in
142 let decrement_cases =
143 if exhaust_check
144 then decrement_cases
145 else
146 decrement_cases
147 @ [ case ~guard:None ~lhs:(ppat_any ~loc) ~rhs:[%expr assert false] ]
148 in
149 let match_exp =
150 pexp_match
151 ~loc
152 (tuple loc (List.map args_vars ~f:lid))
153 (base_case :: apply_case :: decrement_cases)
154 in
155 let match_exp =
156 if exhaust_check
157 then match_exp
158 else (
159 let loc = Location.none in
160 { match_exp with
161 pexp_attributes =
162 [ attribute
163 ~loc
164 ~name:Location.{ txt = "ocaml.warning"; loc }
165 ~payload:(PStr [ pstr_eval ~loc (estring ~loc "-11") [] ])
166 ]
167 })
168 in
169 [%expr
170 let rec loop acc =
171 [%e eabstract ~loc (List.map args_vars ~f:patt_lid) match_exp]
172 in
173 [%e apply [%expr loop []] (List.map ~f:lid alias_vars)]]
174 in
175 Stdlib.ListLabels.fold_right2 alias_vars l's ~init ~f:(fun alias_var input_list acc ->
176 [%expr
177 let [%p pvar ~loc alias_var] = [%e input_list] in
178 [%e acc]])
179 ;;
180
181 (* Here we do two things: simplify append on static lists, to make the generated code more
182 readable and rewrite (List.append (List.append a b) c) as (List.append a (List.append b
183 c)), to avoid a quadratic behaviour with long nesting to the left. *)
184 let rec list_append loc l1 l2 =
185 match l2 with
186 | [%expr []] -> l1
187 | _ ->
188 (match l1 with
189 | [%expr []] -> l2
190 | [%expr [%e? hd] :: [%e? tl]] -> [%expr [%e hd] :: [%e list_append loc tl l2]]
191 | [%expr Ppx_enumerate_lib.List.append [%e? ll] [%e? lr]] ->
192 list_append loc ll (list_append loc lr l2)
193 | _ -> [%expr Ppx_enumerate_lib.List.append [%e l1] [%e l2]])
194 ;;
195
196 let rec enum ~exhaust_check ~main_type ty =
197 let loc = { ty.ptyp_loc with loc_ghost = true } in
198 match Ppxlib_jane.Jane_syntax.Core_type.of_ast ty with
199 | Some (Jtyp_tuple ltps, _attrs) ->
200 product ~exhaust_check loc (List.map ~f:snd ltps) (fun exprs ->
201 labeled_tuple loc ltps exprs)
202 | Some (Jtyp_layout _, _) | None ->
203 (match ty.ptyp_desc with
204 | Ptyp_constr ({ txt = Lident "bool"; _ }, []) -> [%expr [ false; true ]]
205 | Ptyp_constr ({ txt = Lident "unit"; _ }, []) -> [%expr [ () ]]
206 | Ptyp_constr ({ txt = Lident "option"; _ }, [ tp ]) ->
207 [%expr
208 None
209 :: [%e
210 list_map loc (enum ~exhaust_check ~main_type:tp tp) ~f:(fun e ->
211 [%expr Some [%e e]])]]
212 | Ptyp_constr (id, args) ->
213 type_constr_conv
214 ~loc
215 id
216 ~f:name_of_type_name
217 (List.map args ~f:(fun t -> enum ~exhaust_check t ~main_type:t))
218 | Ptyp_tuple tps -> product ~exhaust_check loc tps (fun exprs -> tuple loc exprs)
219 | Ptyp_variant (row_fields, Closed, None) ->
220 List.fold_left row_fields ~init:[%expr []] ~f:(fun acc rf ->
221 list_append loc acc (variant_case ~exhaust_check loc rf ~main_type))
222 | Ptyp_var id -> evar ~loc (name_of_type_variable id)
223 | _ -> Location.raise_errorf ~loc "ppx_enumerate: unsupported type")
224
225 and variant_case ~exhaust_check loc row_field ~main_type =
226 match row_field.prf_desc with
227 | Rtag ({ txt = cnstr; _ }, true, _) | Rtag ({ txt = cnstr; _ }, _, []) ->
228 [%expr [ [%e pexp_variant ~loc cnstr None] ]]
229 | Rtag ({ txt = cnstr; _ }, false, tp :: _) ->
230 list_map loc (enum ~exhaust_check tp ~main_type:tp) ~f:(fun e ->
231 pexp_variant ~loc cnstr (Some e))
232 | Rinherit ty ->
233 let e = enum ~exhaust_check ~main_type ty in
234 [%expr ([%e e] :> [%t replace_variables_by_underscores main_type] list)]
235
236 and constructor_case ~exhaust_check loc cd =
237 match cd.pcd_args with
238 | Pcstr_tuple [] -> [%expr [ [%e econstruct cd None] ]]
239 | Pcstr_tuple tps ->
240 product ~exhaust_check loc tps (fun x -> econstruct cd (Some (pexp_tuple ~loc x)))
241 | Pcstr_record lds ->
242 enum_of_lab_decs ~exhaust_check ~loc lds ~k:(fun x -> econstruct cd (Some x))
243
244 and enum_of_lab_decs ~exhaust_check ~loc lds ~k =
245 let field_names, types =
246 List.unzip (List.map lds ~f:(fun ld -> ld.pld_name, ld.pld_type))
247 in
248 product ~exhaust_check loc types (function l ->
249 let fields =
250 List.map2_exn field_names l ~f:(fun field_name x ->
251 Located.map lident field_name, x)
252 in
253 k (pexp_record ~loc fields None))
254
255 and product ~exhaust_check loc tps f =
256 let all = List.map tps ~f:(fun tp -> enum ~exhaust_check ~main_type:tp tp) in
257 cartesian_product_map ~exhaust_check all loc ~f
258 ;;
259
260 let quantify loc tps typ =
261 match tps with
262 | [] -> typ
263 | _ -> ptyp_poly ~loc (List.map tps ~f:(fun x -> get_type_param_name x)) typ
264 ;;
265
266 let enum_of_td ~exhaust_check td =
267 let td = name_type_params_in_td td in
268 let loc = td.ptype_loc in
269 let all =
270 let main_type =
271 ptyp_constr
272 ~loc
273 (Located.map lident td.ptype_name)
274 (List.map td.ptype_params ~f:(fun _ -> ptyp_any ~loc))
275 in
276 match td.ptype_kind with
277 | Ptype_variant cds ->
278 (* Process [cd] elements in same order as camlp4 to avoid code-gen diffs caused by
279 different order of [gen_symbol] calls *)
280 List.fold_left cds ~init:[%expr []] ~f:(fun acc cd ->
281 list_append loc acc (constructor_case ~exhaust_check loc cd))
282 | Ptype_record lds -> enum_of_lab_decs ~exhaust_check ~loc lds ~k:(fun x -> x)
283 | Ptype_open -> Location.raise_errorf ~loc "ppx_enumerate: open types not supported"
284 | Ptype_abstract ->
285 (match td.ptype_manifest with
286 | None -> [%expr []]
287 | Some tp -> enum ~exhaust_check tp ~main_type)
288 in
289 let name = name_of_type_name td.ptype_name.txt in
290 let args =
291 List.map td.ptype_params ~f:(fun ((tp, _) as x) ->
292 let name = name_of_type_variable (get_type_param_name x).txt in
293 let loc = tp.ptyp_loc in
294 pvar ~loc name)
295 in
296 let enumeration_type =
297 let typ = enumeration_type_of_td td in
298 quantify loc td.ptype_params typ
299 in
300 let body = eabstract ~loc args all in
301 let zero_args = List.length args = 0 in
302 if zero_args (* constrain body rather than pattern *)
303 then [%str let [%p pvar ~loc name] = ([%e body] : [%t enumeration_type])]
304 else [%str let ([%p pvar ~loc name] : [%t enumeration_type]) = [%e body]]
305 ;;
306
307 let enumerate =
308 let str_args = Deriving.Args.(empty +> flag "no_exhaustiveness_check") in
309 Deriving.add
310 "enumerate"
311 ~str_type_decl:
312 (Deriving.Generator.make
313 str_args
314 (fun ~loc ~path:_ (_rec, tds) no_exhaustiveness_check ->
315 match tds with
316 | [ td ] -> enum_of_td ~exhaust_check:(not no_exhaustiveness_check) td
317 | _ ->
318 Location.raise_errorf
319 ~loc
320 "only one type at a time is support by ppx_enumerate"))
321 ~sig_type_decl:(Deriving.Generator.make Deriving.Args.empty sig_of_tds)
322 ;;
323
324 let () =
325 Deriving.add "all" ~extension:(fun ~loc:_ ~path:_ ty ->
326 enum ~exhaust_check:true ty ~main_type:ty)
327 |> Deriving.ignore
328 ;;