Debian Codegraph @

expander/ppx_let_expander.ml

raw symbols SCIP
1 open Base
2 open Ppxlib
3 open Ast_builder.Default
4
5 let pexp_let ~loc rec_ bindings e =
6 match bindings with
7 | [] -> e
8 | _ :: _ -> pexp_let ~loc rec_ bindings e
9 ;;
10
11 module List = struct
12 include List
13
14 let reduce_exn l ~f =
15 match l with
16 | [] -> invalid_arg "List.reduce_exn"
17 | hd :: tl -> fold_left tl ~init:hd ~f
18 ;;
19 end
20
21 module Extension_kind = struct
22 type t =
23 { do_open : bool
24 ; collapse_binds : bool
25 }
26
27 let default = { do_open = false; collapse_binds = false }
28 let default_open = { do_open = true; collapse_binds = false }
29 let n = { do_open = false; collapse_binds = true }
30 let n_open = { do_open = true; collapse_binds = true }
31 end
32
33 module type Ext = sig
34 (* The base string of all the related extensions. For example, if the value
35 is "bind", then other extensions will include "bind_open", "bindn", and
36 "bindn_open" - all of which start with "bind" *)
37 val name : string
38 val with_location : bool
39 val prevent_tail_call : bool
40
41 (* Called before each expansion to ensure that the expression being expanded
42 is supported. *)
43 val disallow_expression : Extension_kind.t -> expression_desc -> (unit, string) Result.t
44
45 (* Called when expanding a let-binding (and indirectly, when expanding a
46 match-expression) to destructure [rhs]. The resulting expression should
47 make each variable in [lhs] available for use in [body]. If the result is
48 [None], then no special destructuring is necessary. *)
49 val destruct
50 : assume_exhaustive:bool
51 -> loc:location
52 -> modul:longident loc option
53 -> lhs:pattern
54 -> rhs:expression
55 -> body:expression
56 -> expression option
57
58 (* Expands any match%[name] expressions. It is also used when expanding
59 if%[name]. *)
60 val expand_match
61 : loc:location
62 -> modul:longident loc option
63 -> locality:[ `local | `global ]
64 -> expression
65 -> case list
66 -> expression
67
68 (* [expand] is the function that normally expands let%[name]. [wrap_expansion] can be
69 used to change the parameters given to [expand] and can also tranform the output of
70 [expand]. *)
71 val wrap_expansion
72 : loc:location
73 -> modul:longident loc option
74 -> value_binding list
75 -> expression
76 -> expand:(loc:location -> value_binding list -> expression -> expression)
77 -> expression
78 end
79
80 let wrap_expansion_identity ~loc ~modul:_ bindings expression ~expand =
81 expand ~loc bindings expression
82 ;;
83
84 (* When generating [local_] binds, we need to avoid tail calls so that local allocations
85 can be released. Determining precisely when to annotate [@nontail] is finicky. Instead,
86 we wrap the whole expression in a [let] to force calls to be non-tail. *)
87 let prevent_tail_calls ~loc expr =
88 let var = gen_symbol ~prefix:"__nontail" () in
89 pexp_let
90 ~loc
91 Nonrecursive
92 [ value_binding ~loc ~pat:(pvar ~loc var) ~expr ]
93 (evar ~loc var)
94 ;;
95
96 (* Wrap an expression in [local_] *)
97 let wrap_local ~loc expr = [%expr [%e prevent_tail_calls ~loc expr]]
98
99 let maybe_wrap_local ~loc ~locality expr =
100 match locality with
101 | `global -> expr
102 | `local -> wrap_local ~loc expr
103 ;;
104
105 type t = (module Ext)
106
107 let ext_full_name (module Ext : Ext) ~locality (kind : Extension_kind.t) =
108 let result = Ext.name in
109 let result =
110 match locality with
111 | `local -> String.concat [ result; "l" ]
112 | `global -> result
113 in
114 let result = if kind.collapse_binds then String.concat [ result; "n" ] else result in
115 if kind.do_open then String.concat [ result; "_open" ] else result
116 ;;
117
118 let let_syntax = "Let_syntax"
119
120 let let_syntax ~modul : Longident.t =
121 match modul with
122 | None -> Lident let_syntax
123 | Some id -> Ldot (Ldot (id.txt, let_syntax), let_syntax)
124 ;;
125
126 let open_on_rhs ~loc ~modul =
127 pmod_ident ~loc (Located.mk ~loc (Longident.Ldot (let_syntax ~modul, "Open_on_rhs")))
128 ;;
129
130 let eoperator ~loc ~modul func =
131 let lid : Longident.t = Ldot (let_syntax ~modul, func) in
132 pexp_ident ~loc (Located.mk ~loc lid)
133 ;;
134
135 let qualified_return ~loc ~modul expr =
136 pexp_apply ~loc (eoperator ~loc ~modul "return") [ Nolabel, expr ]
137 ;;
138
139 let location_arg ~loc = Labelled "here", Ppx_here_expander.lift_position ~loc
140
141 let nontail ~loc expr =
142 let attr = attribute ~loc ~name:{ txt = "nontail"; loc } ~payload:(PStr []) in
143 { expr with pexp_attributes = attr :: expr.pexp_attributes }
144 ;;
145
146 let bind_apply
147 ?(fn_label = "f")
148 ~prevent_tail_call
149 ~op_name
150 ~loc
151 ~modul
152 ~with_location
153 ~arg
154 ~fn
155 ()
156 =
157 let args =
158 if with_location
159 then [ location_arg ~loc; Nolabel, arg; Labelled fn_label, fn ]
160 else [ Nolabel, arg; Labelled fn_label, fn ]
161 in
162 let expr = pexp_apply ~loc (eoperator ~loc ~modul op_name) args in
163 if prevent_tail_call then nontail ~loc expr else expr
164 ;;
165
166 let do_not_enter_value vb =
167 let loc = vb.pvb_loc in
168 let attr =
169 { attr_loc = loc
170 ; attr_name = { loc; txt = Attribute.name Ast_traverse.do_not_enter_value_binding }
171 ; attr_payload = PStr []
172 }
173 in
174 { vb with pvb_attributes = attr :: vb.pvb_attributes }
175 ;;
176
177 let expand_with_tmp_vars ~loc bindings expr ~f =
178 match bindings with
179 | [ _ ] -> f ~loc bindings expr
180 | _ ->
181 (* s/rhs/tmp_var and s/lhs/tmp_var *)
182 let s_rhs_tmp_var, s_lhs_tmp_var =
183 List.map bindings ~f:(fun vb ->
184 let var = gen_symbol ~prefix:"__let_syntax" () in
185 let loc = { vb.pvb_expr.pexp_loc with loc_ghost = true } in
186 let rhs = { vb with pvb_expr = evar ~loc var } in
187 let lhs =
188 do_not_enter_value
189 { vb with
190 pvb_pat = pvar ~loc var
191 ; pvb_loc = { vb.pvb_loc with loc_ghost = true }
192 }
193 in
194 rhs, lhs)
195 |> List.unzip
196 in
197 pexp_let ~loc Nonrecursive s_lhs_tmp_var (f ~loc s_rhs_tmp_var expr)
198 ;;
199
200 let maybe_destruct ~destruct ~loc ~modul ~locality ~lhs ~body =
201 let whole_value_var = gen_symbol ~prefix:"__pattern_syntax" () in
202 let whole_value_pattern = ppat_var ~loc { txt = whole_value_var; loc } in
203 let whole_value_expr = pexp_ident ~loc { txt = Lident whole_value_var; loc } in
204 match destruct ~assume_exhaustive:true ~loc ~modul ~lhs ~rhs:whole_value_expr ~body with
205 | Some destruction ->
206 maybe_wrap_local ~loc ~locality destruction
207 |> pexp_fun ~loc Nolabel None whole_value_pattern
208 | None -> maybe_wrap_local ~loc ~locality body |> pexp_fun ~loc Nolabel None lhs
209 ;;
210
211 let expand_letn (module Ext : Ext) ~loc ~modul ~locality bindings body =
212 let n = List.length bindings in
213 let operator =
214 match n with
215 | 1 -> eoperator ~loc ~modul Ext.name
216 | n -> eoperator ~loc ~modul (Printf.sprintf "%s%d" Ext.name n)
217 in
218 let bindings_args =
219 bindings |> List.map ~f:(fun { pvb_expr; _ } -> Nolabel, pvb_expr)
220 in
221 let func =
222 List.fold_right
223 bindings
224 ~init:(maybe_wrap_local ~loc ~locality body)
225 ~f:(fun { pvb_pat; _ } lower ->
226 maybe_destruct
227 ~destruct:Ext.destruct
228 ~modul
229 ~locality:`global
230 ~loc
231 ~lhs:pvb_pat
232 ~body:lower)
233 in
234 let args =
235 bindings_args
236 @
237 if Ext.with_location
238 then [ location_arg ~loc; Labelled "f", func ]
239 else [ Labelled "f", func ]
240 in
241 pexp_apply ~loc operator args
242 ;;
243
244 let maybe_open ~(extension_kind : Extension_kind.t) ~to_open:module_to_open expr =
245 let loc = { expr.pexp_loc with loc_ghost = true } in
246 if extension_kind.do_open
247 then
248 pexp_open ~loc (open_infos ~loc ~override:Override ~expr:(module_to_open ~loc)) expr
249 else expr
250 ;;
251
252 let expand_let (module Ext : Ext) ~loc ~modul ~locality bindings body =
253 if List.length bindings = 0
254 then invalid_arg "expand_let: list of bindings must be non-empty";
255 (* Build expression [both E1 (both E2 (both ...))] *)
256 let nested_boths =
257 let rev_boths = List.rev_map bindings ~f:(fun vb -> vb.pvb_expr) in
258 List.reduce_exn rev_boths ~f:(fun acc e ->
259 let loc = { e.pexp_loc with loc_ghost = true } in
260 eapply ~loc (eoperator ~loc ~modul "both") [ e; acc ])
261 in
262 (* Build pattern [(P1, (P2, ...))] *)
263 let nested_patterns =
264 let rev_patts = List.rev_map bindings ~f:(fun vb -> vb.pvb_pat) in
265 let min_position, max_position =
266 match rev_patts with
267 | hd :: tl ->
268 let init = hd.ppat_loc.loc_start, hd.ppat_loc.loc_end in
269 List.fold ~init tl ~f:(fun (min, max) pattern ->
270 ( Location.min_pos pattern.ppat_loc.loc_start min
271 , Location.max_pos pattern.ppat_loc.loc_end max ))
272 | [] -> assert false
273 in
274 let tuple_loc =
275 { loc_start = min_position; loc_end = max_position; loc_ghost = true }
276 in
277 List.reduce_exn rev_patts ~f:(fun acc p -> ppat_tuple ~loc:tuple_loc [ p; acc ])
278 in
279 let fn =
280 maybe_destruct ~destruct:Ext.destruct ~loc ~modul ~locality ~lhs:nested_patterns ~body
281 in
282 bind_apply
283 ~op_name:Ext.name
284 ~loc
285 ~modul
286 ~with_location:Ext.with_location
287 ~arg:nested_boths
288 ~fn
289 ()
290 ;;
291
292 let expand_match (module Ext : Ext) ~extension_kind ~loc ~modul ~locality expr cases =
293 let expr = maybe_open ~extension_kind ~to_open:(open_on_rhs ~modul) expr in
294 Ext.expand_match ~loc ~modul ~locality expr cases
295 ;;
296
297 let expand_if t ~extension_kind ~loc ~modul ~locality expr then_ else_ =
298 expand_match
299 t
300 ~extension_kind
301 ~loc
302 ~modul
303 ~locality
304 expr
305 [ case ~lhs:(pbool ~loc true) ~guard:None ~rhs:then_
306 ; case ~lhs:(pbool ~loc false) ~guard:None ~rhs:else_
307 ]
308 ;;
309
310 let expand_while (module Ext : Ext) ~locality ~extension_kind ~loc ~modul ~cond ~body =
311 let loop_name = gen_symbol ~prefix:"__let_syntax_loop" () in
312 let ploop = pvar ~loc loop_name in
313 let eloop = evar ~loc loop_name in
314 let loop_call = pexp_apply ~loc eloop [ Nolabel, eunit ~loc ] in
315 let loop_body =
316 let then_ =
317 bind_apply
318 ~op_name:Ext.name
319 ~loc
320 ~modul
321 ~with_location:Ext.with_location
322 ~arg:body
323 ~fn:eloop
324 ~prevent_tail_call:Ext.prevent_tail_call
325 ()
326 in
327 let else_ = qualified_return ~loc ~modul (eunit ~loc) in
328 expand_if (module Ext) ~extension_kind ~modul ~locality ~loc cond then_ else_
329 in
330 let loop_body = maybe_wrap_local ~loc ~locality loop_body in
331 let loop_func = pexp_fun ~loc Nolabel None (punit ~loc) loop_body in
332 pexp_let
333 ~loc
334 Recursive
335 [ do_not_enter_value (value_binding ~loc ~pat:ploop ~expr:loop_func) ]
336 loop_call
337 ;;
338
339 let expand_function ~loc ~locality cases =
340 match locality with
341 | `global -> pexp_function_cases ~loc cases
342 | `local ->
343 let var = gen_symbol ~prefix:"__let_syntax" () in
344 pexp_match ~loc (evar ~loc var) cases
345 |> wrap_local ~loc
346 |> pexp_fun ~loc Nolabel None (pvar ~loc var)
347 ;;
348
349 module Map : Ext = struct
350 let name = "map"
351 let with_location = false
352 let wrap_expansion = wrap_expansion_identity
353 let prevent_tail_call = false
354
355 let disallow_expression _ = function
356 | Pexp_while (_, _) -> Error "while%%map is not supported. use while%%bind instead."
357 | _ -> Ok ()
358 ;;
359
360 let destruct ~assume_exhaustive:_ ~loc:_ ~modul:_ ~lhs:_ ~rhs:_ ~body:_ = None
361
362 let expand_match ~loc ~modul ~locality expr cases =
363 bind_apply
364 ~loc
365 ~modul
366 ~with_location
367 ~op_name:name
368 ~arg:expr
369 ~fn:(expand_function ~loc ~locality cases)
370 ~prevent_tail_call
371 ()
372 ;;
373 end
374
375 module Bind : Ext = struct
376 let name = "bind"
377 let with_location = false
378 let wrap_expansion = wrap_expansion_identity
379 let prevent_tail_call = false
380
381 let disallow_expression (extension_kind : Extension_kind.t) = function
382 | Pexp_while (_, _) when extension_kind.collapse_binds ->
383 Error "while%%bindn is not supported. use while%%bind instead."
384 | _ -> Ok ()
385 ;;
386
387 let destruct ~assume_exhaustive:_ ~loc:_ ~modul:_ ~lhs:_ ~rhs:_ ~body:_ = None
388
389 let expand_match ~loc ~modul ~locality expr cases =
390 bind_apply
391 ~loc
392 ~modul
393 ~with_location
394 ~op_name:name
395 ~arg:expr
396 ~fn:(expand_function ~loc ~locality cases)
397 ~prevent_tail_call
398 ()
399 ;;
400 end
401
402 let variables_of =
403 object
404 inherit [string Ppxlib.loc list] Ast_traverse.fold as super
405
406 method! pattern p acc =
407 let acc = super#pattern p acc in
408 match p.ppat_desc with
409 | Ppat_var var -> var :: acc
410 | Ppat_alias (_, var) -> var :: acc
411 | _ -> acc
412 end
413 ;;
414
415 let pattern_variables pattern =
416 List.dedup_and_sort
417 ~compare:(fun x y -> String.compare x.txt y.txt)
418 (variables_of#pattern pattern [])
419 ;;
420
421 let maybe_enter_value pat expr =
422 match pattern_variables pat with
423 | [ { loc; txt } ] ->
424 let loc = { loc with loc_ghost = true } in
425 let attr =
426 { attr_loc = loc
427 ; attr_name = { loc; txt = Attribute.name Ast_traverse.enter_value }
428 ; attr_payload = PStr [ pstr_eval ~loc (evar ~loc txt) [] ]
429 }
430 in
431 { expr with pexp_attributes = attr :: expr.pexp_attributes }
432 | [] | _ :: _ :: _ -> expr
433 ;;
434
435 let expand ((module Ext : Ext) as ext) extension_kind ~modul ~locality expr =
436 let loc = { expr.pexp_loc with loc_ghost = true } in
437 let expansion =
438 let expr_desc =
439 match Ext.disallow_expression extension_kind expr.pexp_desc with
440 | Error message -> Location.raise_errorf ~loc "%s" message
441 | Ok () -> expr.pexp_desc
442 in
443 match expr_desc with
444 | Pexp_let (Nonrecursive, bindings, expr) ->
445 let bindings =
446 List.map bindings ~f:(fun vb ->
447 let pvb_pat, pvb_expr =
448 (* Temporary hack tentatively detecting that the parser
449 has expanded `let x : t = e` into `let x : t = (e : t)`.
450
451 For reference, here is the relevant part of the parser:
452 https://github.com/ocaml/ocaml/blob/4.07/parsing/parser.mly#L1628 *)
453 match vb.pvb_pat.ppat_desc, vb.pvb_expr.pexp_desc with
454 | ( Ppat_constraint (p, { ptyp_desc = Ptyp_poly ([], t1); _ })
455 , Pexp_constraint (_, t2) )
456 when phys_equal t1 t2 || Poly.equal t1 t2 ->
457 ( p
458 , { vb.pvb_expr with
459 pexp_loc = { vb.pvb_expr.pexp_loc with loc_ghost = true }
460 } )
461 | _ -> vb.pvb_pat, vb.pvb_expr
462 in
463 { vb with
464 pvb_pat
465 ; pvb_expr =
466 maybe_open
467 ~extension_kind
468 ~to_open:(open_on_rhs ~modul)
469 (maybe_enter_value pvb_pat pvb_expr)
470 })
471 in
472 let f ~loc value_bindings expression =
473 let expand =
474 if extension_kind.collapse_binds
475 then expand_letn ext ~modul ~locality
476 else expand_let ext ~modul ~locality ~prevent_tail_call:Ext.prevent_tail_call
477 in
478 Ext.wrap_expansion ~loc ~modul value_bindings expression ~expand
479 in
480 expand_with_tmp_vars ~loc bindings expr ~f
481 | Pexp_let (Recursive, _, _) ->
482 let ext_full_name = ext_full_name ext ~locality extension_kind in
483 Location.raise_errorf ~loc "'let%%%s' may not be recursive" ext_full_name
484 | Pexp_match (expr, cases) ->
485 expand_match ext ~extension_kind ~loc ~modul ~locality expr cases
486 | Pexp_function (_, _, Pfunction_cases (cases, _, _)) ->
487 let temp_var = gen_symbol ~prefix:"__let_syntax" () in
488 let temp_pattern = ppat_var ~loc { txt = temp_var; loc } in
489 let temp_expr = pexp_ident ~loc { txt = Lident temp_var; loc } in
490 let match_expr =
491 expand_match ext ~extension_kind ~loc ~modul ~locality temp_expr cases
492 in
493 pexp_fun ~loc Nolabel None temp_pattern match_expr
494 | Pexp_ifthenelse (expr, then_, else_) ->
495 let else_ =
496 match else_ with
497 | Some else_ -> else_
498 | None ->
499 let ext_full_name = ext_full_name ext ~locality extension_kind in
500 Location.raise_errorf ~loc "'if%%%s' must include an else branch" ext_full_name
501 in
502 expand_if ext ~extension_kind ~loc ~modul ~locality expr then_ else_
503 | Pexp_while (cond, body) ->
504 expand_while ext ~extension_kind ~loc ~modul ~locality ~cond ~body
505 | _ ->
506 Location.raise_errorf
507 ~loc
508 "'%%%s' can only be used with 'let', 'match', 'while', and 'if'"
509 (ext_full_name ext ~locality extension_kind)
510 in
511 { expansion with pexp_attributes = expr.pexp_attributes @ expansion.pexp_attributes }
512 ;;
513
514 let map = (module Map : Ext)
515 let bind = (module Bind : Ext)