Debian Codegraph @

ppx_globalize.ml

raw symbols SCIP
1 open! Base
2 open Ppxlib
3
4 (* Copies source syntax to be used in generated code. Strips attributes and ensures all
5 locations are marked as "ghost". *)
6 let copy =
7 object
8 inherit Ast_traverse.map
9 method! location loc = { loc with loc_ghost = true }
10 method! attributes _ = []
11 end
12 ;;
13
14 let error ~loc fmt = Location.raise_errorf ~loc (Stdlib.( ^^ ) "ppx_globalize: " fmt)
15
16 let is_global_field ld =
17 match ld.pld_mutable with
18 | Mutable -> true
19 | Immutable ->
20 (match Ppxlib_jane.Ast_builder.Default.get_label_declaration_modality ld with
21 | Some Global, _ -> true
22 | None, _ -> false)
23 ;;
24
25 (* Check if types are really recursive ignoring global and mutable
26 fields *)
27 class is_recursive rec_flag decls =
28 object
29 inherit type_is_recursive rec_flag decls as super
30
31 method! label_declaration ld =
32 if is_global_field ld then () else super#label_declaration ld
33 end
34
35 let really_recursive rec_flag decls = (new is_recursive rec_flag decls)#go ()
36
37 (* The name of the globalize function for a given type name as a string *)
38 let globalize_name type_name =
39 if String.equal type_name "t" then "globalize" else "globalize_" ^ type_name
40 ;;
41
42 (* The name of the globalize function for a given type name as a
43 longident *)
44 let globalize_lid = function
45 | Lident name -> Lident (globalize_name name)
46 | Ldot (p, name) -> Ldot (p, globalize_name name)
47 | Lapply _ -> assert false
48 ;;
49
50 module Env : sig
51 (* A mapping from type variables to globalize functions *)
52 type t
53
54 (* An empty mapping *)
55 val empty : t
56
57 type var =
58 | Universal
59 | Globalize of expression
60
61 (* Lookup a globalize function *)
62 val lookup : t -> string -> var option
63
64 (* Create a mapping for the type parameters of a type
65 declaration. Returns both the mapping and a list of names that
66 should be bound to the globalize functions of the parameters of the
67 type *)
68 val of_type_decl : (module Ast_builder.S) -> type_declaration -> t * string list
69
70 (* Update a mapping for the body of a variant constructor. In the
71 non-GADT case the mapping is unchanged. In the GADT case we need to
72 build the mapping by looking at the result type of the
73 constructor. *)
74 val enter_constructor_declaration
75 : (module Ast_builder.S)
76 -> t
77 -> constructor_declaration
78 -> t
79
80 (* Update a mapping for the body of a polytype. *)
81 val enter_poly : (module Ast_builder.S) -> t -> string loc list -> t
82 end = struct
83 type var =
84 | Universal
85 | Globalize of expression
86
87 type t =
88 { vars : var Map.M(String).t
89 ; params : string list
90 }
91
92 let empty = { vars = Map.empty (module String); params = [] }
93 let lookup t name = Map.find t.vars name
94
95 let of_type_decl builder decl =
96 let open (val builder : Ast_builder.S) in
97 let vars = Map.empty (module String) in
98 let params = [] in
99 let t =
100 List.fold_right
101 decl.ptype_params
102 ~init:{ vars; params }
103 ~f:(fun (typ, _) { vars; params } ->
104 let vars, sym =
105 match typ.ptyp_desc with
106 | Ptyp_var name ->
107 let prefix = "_globalize_" ^ name in
108 let sym = gen_symbol ~prefix () in
109 let vars = Map.add_exn vars ~key:name ~data:(Globalize (evar sym)) in
110 vars, sym
111 | _ ->
112 let prefix = "_globalize_param" in
113 let sym = gen_symbol ~prefix () in
114 vars, sym
115 in
116 let params = sym :: params in
117 { vars; params })
118 in
119 t, t.params
120 ;;
121
122 (* This is for GADTs; it finds the indices (as opposed to the
123 parameters) of the type and makes them their own globalize
124 parameters. Given a definition like:
125
126 {[
127 type ('a, 'b) t =
128 | Foo : ... -> ('c, 'd) t
129 ]}
130
131 we are making a mapping from ['c] and ['d] to the globalize
132 functions of the first and second parameters. [params] has the list
133 of globalize functions so we just fold2 along that list and the
134 list of arguments to [t] in the result type adding mappings for
135 it. This completely replaces the outer mapping, which would have
136 mapped ['a] and ['b] to those parameters.
137
138 If the index is not a variable, or if the variable has already
139 appeared for another index, then we don't add a mapping. *)
140 let enter_constructor_declaration builder { vars; params } cd =
141 let open (val builder : Ast_builder.S) in
142 let vars =
143 match cd.pcd_res with
144 | None -> vars
145 | Some ty ->
146 let vars = Map.empty (module String) in
147 (match ty.ptyp_desc with
148 | Ptyp_constr (_, args) when List.length params = List.length args ->
149 List.fold2_exn params args ~init:vars ~f:(fun vars param arg ->
150 match arg.ptyp_desc with
151 | Ptyp_var name | Ptyp_alias (_, { txt = name; loc = _ }) ->
152 (match Map.add vars ~key:name ~data:(Globalize (evar param)) with
153 | `Duplicate -> vars
154 | `Ok vars -> vars)
155 | _ -> vars)
156 | _ -> vars)
157 in
158 { vars; params }
159 ;;
160
161 let enter_poly _builder { vars; params } names =
162 let vars =
163 List.fold ~init:vars names ~f:(fun vars name ->
164 Map.set vars ~key:name.txt ~data:Universal)
165 in
166 { vars; params }
167 ;;
168 end
169
170 let globalize_arrow ~loc ty = [%type: [%t ty] -> [%t ty]]
171
172 (* Generate the type for a copier function for a given list of type
173 parameters and type name
174 *)
175 let generate_typ builder params type_name =
176 let open (val builder : Ast_builder.S) in
177 let globalize_arrow = globalize_arrow ~loc in
178 let type_lid = Located.lident type_name in
179 let type_ = ptyp_constr type_lid params in
180 List.fold_right params ~init:(globalize_arrow type_) ~f:(fun param acc ->
181 ptyp_arrow Nolabel (globalize_arrow param) acc)
182 ;;
183
184 (* Is an object field a polymorphic method? *)
185 let is_polymorphic_method field =
186 match field.pof_desc with
187 | Otag (_, ct) ->
188 (match ct.ptyp_desc with
189 | Ptyp_poly _ -> true
190 | _ -> false)
191 | Oinherit _ -> false
192 ;;
193
194 (* Strip a type to just its head for use in a coercion. This avoids
195 needing to worry about the scope of type variables. *)
196 let rec type_head builder typ =
197 let open (val builder : Ast_builder.S) in
198 match Ppxlib_jane.Jane_syntax.Core_type.of_ast typ with
199 | Some (Jtyp_tuple args, _) ->
200 let args = List.map ~f:(fun (lbl, _) -> lbl, ptyp_any) args in
201 Ppxlib_jane.Jane_syntax.Core_type.core_type_of ~loc ~attrs:[] (Jtyp_tuple args)
202 | Some (Jtyp_layout _, _) | None ->
203 (match typ.ptyp_desc with
204 | Ptyp_any | Ptyp_var _ | Ptyp_extension _ -> ptyp_any
205 | Ptyp_tuple args ->
206 let args = List.map ~f:(fun _ -> ptyp_any) args in
207 ptyp_tuple args
208 | Ptyp_constr (lid, []) -> ptyp_constr (Located.mk lid.txt) []
209 | Ptyp_constr (lid, _ :: _) -> ptyp_constr (Located.mk lid.txt) [ ptyp_any ]
210 | Ptyp_variant (fields, closed, labels) ->
211 let fields =
212 List.map fields ~f:(fun field ->
213 match field.prf_desc with
214 | Rtag (label, const, args) ->
215 rtag label const (List.map ~f:(fun _ -> ptyp_any) args)
216 | Rinherit typ -> rinherit (type_head builder typ))
217 in
218 ptyp_variant fields closed labels
219 | Ptyp_alias (typ, _) -> type_head builder typ
220 | Ptyp_arrow (lbl, _, _) -> ptyp_arrow lbl ptyp_any ptyp_any
221 | Ptyp_package (mty, constrs) ->
222 let constrs = List.map ~f:(fun (lid, _) -> lid, ptyp_any) constrs in
223 ptyp_package (mty, constrs)
224 | Ptyp_object (fields, closed) ->
225 if List.exists fields ~f:is_polymorphic_method
226 then ptyp_any
227 else (
228 let fields =
229 List.map fields ~f:(fun field ->
230 match field.pof_desc with
231 | Otag (lbl, _) -> otag lbl ptyp_any
232 | Oinherit typ -> oinherit (type_head builder typ))
233 in
234 ptyp_object fields closed)
235 | Ptyp_class (lid, args) ->
236 let args = List.map ~f:(fun _ -> ptyp_any) args in
237 ptyp_class (Located.mk lid.txt) args
238 | Ptyp_poly _ | Ptyp_open _ -> assert false)
239 ;;
240
241 let mode_crossing_attr_name = "globalized"
242
243 let mode_crossing_attr_core_type =
244 Attribute.declare
245 mode_crossing_attr_name
246 Attribute.Context.core_type
247 Ast_pattern.(pstr nil)
248 ()
249 ;;
250
251 let mode_crossing_attr_label_declaration =
252 Attribute.declare
253 mode_crossing_attr_name
254 Attribute.Context.label_declaration
255 Ast_pattern.(pstr nil)
256 ()
257 ;;
258
259 (* We generate a beta-redex to give a better error message
260 if the type does not cross modes. *)
261 let globalized_mode_crossing exp typ loc =
262 let loc = { loc with loc_ghost = true } in
263 let builder = Ast_builder.make loc in
264 let open (val builder : Ast_builder.S) in
265 pexp_apply
266 (pexp_constraint
267 (pexp_fun
268 Nolabel
269 None
270 (ppat_var { txt = "x"; loc })
271 (pexp_ident { txt = Lident "x"; loc }))
272 [%type: [%t typ] -> [%t copy#core_type typ]])
273 [ Nolabel, exp ]
274 ;;
275
276 (* Generate code to create a globalized copy of the value produced by
277 the expression [exp] of type [typ]. *)
278 let rec generate_globalized_for_typ builder env exp name_opt typ =
279 let open (val builder : Ast_builder.S) in
280 let typ_loc = typ.ptyp_loc in
281 match Attribute.consume mode_crossing_attr_core_type typ with
282 | Some (typ, ()) -> globalized_mode_crossing exp typ typ_loc
283 | None ->
284 (match Ppxlib_jane.Jane_syntax.Core_type.of_ast typ with
285 | Some (Jtyp_tuple args, _attrs) ->
286 let tpat, texp = generate_globalized_for_tuple_args builder env args in
287 pexp_let Nonrecursive [ value_binding ~pat:tpat ~expr:exp ] texp
288 | Some (Jtyp_layout _, _) | None ->
289 (match typ.ptyp_desc with
290 | Ptyp_var name ->
291 (match Env.lookup env name with
292 | Some (Globalize fn) -> eapply fn [ exp ]
293 | Some Universal ->
294 error
295 ~loc:typ.ptyp_loc
296 "Cannot generate globalize function for universal type variable '%s"
297 name
298 | None ->
299 error
300 ~loc:typ.ptyp_loc
301 "Cannot generate globalize function for unbound type variable '%s"
302 name)
303 | Ptyp_tuple args ->
304 let tpat, texp =
305 generate_globalized_for_tuple_args
306 builder
307 env
308 (List.map ~f:(fun arg -> None, arg) args)
309 in
310 pexp_let Nonrecursive [ value_binding ~pat:tpat ~expr:exp ] texp
311 | Ptyp_constr (lid, args) ->
312 let args =
313 List.map ~f:(generate_globalized_for_typ_as_function builder env None) args
314 in
315 let lid = globalize_lid lid.txt in
316 eapply (pexp_ident (Located.mk lid)) (args @ [ exp ])
317 | Ptyp_variant (fields, Closed, None) ->
318 let inherits, constants, nonconstants =
319 List.fold_right
320 fields
321 ~init:([], [], [])
322 ~f:(fun field (inherits, consts, nonconsts) ->
323 match field.prf_desc with
324 | Rtag (name, false, [ arg ]) ->
325 inherits, consts, (name.txt, arg) :: nonconsts
326 | Rtag (name, true, []) -> inherits, name.txt :: consts, nonconsts
327 | Rtag (_, _, _) ->
328 error
329 ~loc:typ.ptyp_loc
330 "Cannot generate globalize function for partial variant type"
331 | Rinherit typ ->
332 (match typ.ptyp_desc with
333 | Ptyp_constr (lid, _) -> (lid.txt, typ) :: inherits, consts, nonconsts
334 | _ ->
335 error
336 ~loc:typ.ptyp_loc
337 "Cannot generate globalize function for unnamed inherited variant \
338 constructors"))
339 in
340 let inherit_cases =
341 List.map inherits ~f:(fun (lid, inher) ->
342 let v = gen_symbol ~prefix:"x" () in
343 let lid = Located.mk lid in
344 let lhs = ppat_alias (ppat_type lid) (Located.mk v) in
345 let typ =
346 match name_opt with
347 | None -> typ
348 | Some typ -> typ
349 in
350 let rhs =
351 pexp_coerce
352 (generate_globalized_for_typ builder env (evar v) None inher)
353 (Some (type_head builder inher))
354 (type_head builder typ)
355 in
356 case ~lhs ~rhs ~guard:None)
357 in
358 let constants_case =
359 match constants with
360 | [] -> None
361 | first :: rest ->
362 let v = gen_symbol ~prefix:"x" () in
363 let first_pat = ppat_variant first None in
364 let lhs =
365 ppat_alias
366 (List.fold ~init:first_pat rest ~f:(fun acc name ->
367 ppat_or acc (ppat_variant name None)))
368 (Located.mk v)
369 in
370 let rhs = evar v in
371 Some (case ~lhs ~rhs ~guard:None)
372 in
373 let nonconstants_cases =
374 List.map nonconstants ~f:(fun (name, arg) ->
375 let v = gen_symbol ~prefix:"arg" () in
376 let lhs = ppat_variant name (Some (pvar v)) in
377 let arg = generate_globalized_for_typ builder env (evar v) None arg in
378 let rhs = pexp_variant name (Some arg) in
379 case ~lhs ~rhs ~guard:None)
380 in
381 let cases =
382 inherit_cases @ Option.to_list constants_case @ nonconstants_cases
383 in
384 pexp_match exp cases
385 | Ptyp_variant (_, Open, _) ->
386 error
387 ~loc:typ.ptyp_loc
388 "Cannot generate globalize function for open variant type"
389 | Ptyp_variant (_, Closed, Some _) ->
390 error
391 ~loc:typ.ptyp_loc
392 "Cannot generate globalize function for partial variant type"
393 | Ptyp_alias (typ, { txt = name; loc = _ }) ->
394 (match Env.lookup env name with
395 | Some (Globalize fn) -> eapply fn [ exp ]
396 | Some Universal | None ->
397 generate_globalized_for_typ builder env exp name_opt typ)
398 | Ptyp_poly (names, typ) ->
399 let env = Env.enter_poly builder env names in
400 generate_globalized_for_typ builder env exp None typ
401 | Ptyp_any ->
402 error ~loc:typ.ptyp_loc "Cannot generate globalize function for unknown type"
403 | Ptyp_arrow (_, _, _) ->
404 error ~loc:typ.ptyp_loc "Cannot generate globalize function for function type"
405 | Ptyp_object (_, _) ->
406 error ~loc:typ.ptyp_loc "Cannot generate globalize function for object type"
407 | Ptyp_class (_, _) ->
408 error ~loc:typ.ptyp_loc "Cannot generate globalize function for class type"
409 | Ptyp_package _ ->
410 error
411 ~loc:typ.ptyp_loc
412 "Cannot generate globalize function for first-class module type"
413 | Ptyp_extension _ ->
414 error
415 ~loc:typ.ptyp_loc
416 "Cannot generate globalize function for unknown extension"
417 | Ptyp_open _ -> assert false))
418
419 (* Generate code for a function to globalize values of type [type]. *)
420 and generate_globalized_for_typ_as_function builder env name_opt typ =
421 let open (val builder : Ast_builder.S) in
422 let v = gen_symbol ~prefix:"x" () in
423 let lhs = pvar v in
424 let rhs = generate_globalized_for_typ builder env (evar v) name_opt typ in
425 eta_reduce_if_possible (pexp_fun Nolabel None lhs rhs)
426
427 (* Generate code to create a globalized copy of the arguments of a tuple
428 with types [args]. Returns a pattern to match the tuple, an
429 expression to produce the copy, and some value bindings for
430 intermediate values. *)
431 and generate_globalized_for_tuple_args builder env args =
432 let open (val builder : Ast_builder.S) in
433 let pats, exps =
434 List.fold_right
435 ~init:([], [])
436 ~f:(fun (lbl, arg) (pats, exps) ->
437 let vin = gen_symbol ~prefix:"arg" () in
438 let pat = pvar vin in
439 let local_exp = evar vin in
440 let exp =
441 match Ppxlib_jane.Ast_builder.Default.get_tuple_field_modality arg with
442 | Some Global, _ -> local_exp
443 | None, _ -> generate_globalized_for_typ builder env local_exp None arg
444 in
445 (lbl, pat) :: pats, (lbl, exp) :: exps)
446 args
447 in
448 let pat =
449 match pats with
450 | [] | [ (Some _, _) ] -> assert false
451 | [ (None, pat) ] -> pat
452 | _ :: _ ->
453 Ppxlib_jane.Jane_syntax.Pattern.pat_of ~loc ~attrs:[] (Jpat_tuple (pats, Closed))
454 in
455 let exp =
456 match exps with
457 | [] | [ (Some _, _) ] -> assert false
458 | [ (None, exp) ] -> exp
459 | _ :: _ ->
460 Ppxlib_jane.Jane_syntax.Expression.expr_of ~loc ~attrs:[] (Jexp_tuple exps)
461 in
462 pat, exp
463 ;;
464
465 (* Generate code to create a globalized copy of the arguments of a
466 record with labels [lds]. Returns a pattern to match the record, an
467 expression to produce the copy, and some value bindings for
468 intermediate values. *)
469 let generate_globalized_for_record_args builder env lds =
470 let open (val builder : Ast_builder.S) in
471 let pats, exps =
472 List.fold_right
473 ~init:([], [])
474 ~f:(fun ld (pats, exps) ->
475 let name = ld.pld_name.txt in
476 let lid = Located.mk (Lident name) in
477 let vin = gen_symbol ~prefix:name () in
478 let pat = lid, pvar vin in
479 let local_exp = evar vin in
480 let ld_loc = ld.pld_loc in
481 let exp =
482 match Attribute.consume mode_crossing_attr_label_declaration ld with
483 | Some (ld, ()) -> globalized_mode_crossing local_exp ld.pld_type ld_loc
484 | None ->
485 if is_global_field ld
486 then local_exp
487 else generate_globalized_for_typ builder env local_exp None ld.pld_type
488 in
489 pat :: pats, (lid, exp) :: exps)
490 lds
491 in
492 ppat_record pats Closed, pexp_record exps None
493 ;;
494
495 (* Generate code to create a globalized copy of the value produced by
496 the expression [exp] of a type with record labels [lds]. *)
497 let generate_globalized_for_record builder env exp lds =
498 let open (val builder : Ast_builder.S) in
499 let rpat, rexp = generate_globalized_for_record_args builder env lds in
500 pexp_let Nonrecursive [ value_binding ~pat:rpat ~expr:exp ] rexp
501 ;;
502
503 (* Generate code to create a globalized copy of the value produced by
504 the expression [exp] of a type with variant constructors [cds]. *)
505 let generate_globalized_for_variant builder env exp cds =
506 let open (val builder : Ast_builder.S) in
507 let constants, nonconstants =
508 List.fold_right
509 cds
510 ~init:([], [])
511 ~f:(fun (cd : constructor_declaration) (consts, nonconsts) ->
512 (* We differentiate between constant cases for GADTs vs normal variants
513 because currently, the type checker does not allow the use of as-pattern
514 to rename an or-pattern of GADTs when it does allow us to do so for normal
515 variants.
516
517 This is fixed in an upstream PR: https://github.com/ocaml/ocaml/pull/11799
518
519 When this is merged we can collapse the constants case back into a singular
520 branch. *)
521 match cd.pcd_res, cd.pcd_args with
522 | None, Pcstr_tuple [] ->
523 let name = cd.pcd_name.txt in
524 let consts = name :: consts in
525 consts, nonconsts
526 | None, ((Pcstr_tuple _ | Pcstr_record _) as args)
527 | Some _, ((Pcstr_tuple _ | Pcstr_record _) as args) ->
528 let name = cd.pcd_name.txt in
529 let env = Env.enter_constructor_declaration builder env cd in
530 let nonconsts = (name, args, env) :: nonconsts in
531 consts, nonconsts)
532 in
533 let constants_case =
534 match constants with
535 | [] -> None
536 | first :: rest ->
537 let v = gen_symbol ~prefix:"x" () in
538 let first_lid = Located.mk (Lident first) in
539 let first_pat = ppat_construct first_lid None in
540 let lhs =
541 ppat_alias
542 (List.fold ~init:first_pat rest ~f:(fun acc name ->
543 let lid = Located.mk (Lident name) in
544 ppat_or acc (ppat_construct lid None)))
545 (Located.mk v)
546 in
547 let rhs = evar v in
548 Some (case ~lhs ~rhs ~guard:None)
549 in
550 let nonconstants_cases =
551 List.map nonconstants ~f:(fun (name, args, env) ->
552 let pat, exp =
553 match args with
554 | Pcstr_tuple [] -> None, None
555 | Pcstr_tuple args ->
556 let pat, exp =
557 generate_globalized_for_tuple_args
558 builder
559 env
560 (List.map ~f:(fun arg -> None, arg) args)
561 in
562 Some pat, Some exp
563 | Pcstr_record lds ->
564 let pat, exp = generate_globalized_for_record_args builder env lds in
565 Some pat, Some exp
566 in
567 let lid = Located.mk (Lident name) in
568 let lhs = ppat_construct lid pat in
569 let rhs = pexp_construct lid exp in
570 case ~lhs ~rhs ~guard:None)
571 in
572 let cases = Option.to_list constants_case @ nonconstants_cases in
573 pexp_match exp cases
574 ;;
575
576 (* Generate code to create a globalized copy of the value produced by
577 the expression [exp] of a type with declaration [decl]. *)
578 let generate_globalized_for_decl builder env exp name decl =
579 let open (val builder : Ast_builder.S) in
580 match decl.ptype_kind with
581 | Ptype_abstract ->
582 (match decl.ptype_manifest with
583 | Some typ ->
584 let name =
585 let args =
586 match decl.ptype_params with
587 | [] -> []
588 | _ :: _ -> [ ptyp_any ]
589 in
590 ptyp_constr (Located.lident name) args
591 in
592 generate_globalized_for_typ builder env exp (Some name) typ
593 | None -> error ~loc "Cannot generate globalize function for abstract type")
594 | Ptype_record lds -> generate_globalized_for_record builder env exp lds
595 | Ptype_variant cds -> generate_globalized_for_variant builder env exp cds
596 | Ptype_open -> error ~loc "Cannot generate globalize function for extensible variants"
597 ;;
598
599 (* Generate code for a function to globalize values of a type with
600 declaration [decl]. *)
601 let generate_globalized_for_decl_as_function builder env name decl =
602 let open (val builder : Ast_builder.S) in
603 let v = gen_symbol ~prefix:"x" () in
604 let lhs = pvar v in
605 let rhs = generate_globalized_for_decl builder env (evar v) name decl in
606 pexp_fun Nolabel None lhs rhs
607 ;;
608
609 (* Generate a value binding for a function to globalize values of a type with
610 declaration [decl]. *)
611 let generate_vb rec_flag decl =
612 let loc = { decl.ptype_loc with loc_ghost = true } in
613 let builder = Ast_builder.make loc in
614 let open (val builder : Ast_builder.S) in
615 let type_name = decl.ptype_name.txt in
616 let name = globalize_name type_name in
617 let pat = pvar name in
618 let param_names =
619 List.mapi decl.ptype_params ~f:(fun i (param, _) ->
620 match param.ptyp_desc with
621 | Ptyp_var name -> name
622 | _ -> "param" ^ Int.to_string i)
623 in
624 let external_params = List.map param_names ~f:(fun name -> ptyp_var name) in
625 let external_param_bindings = List.map param_names ~f:(fun name -> Located.mk name) in
626 let external_type =
627 ptyp_poly external_param_bindings (generate_typ builder external_params type_name)
628 in
629 let pat = ppat_constraint pat external_type in
630 let internal_param_names =
631 List.map param_names ~f:(fun name -> gen_symbol ~prefix:name ())
632 in
633 let internal_params =
634 List.map internal_param_names ~f:(fun name -> ptyp_constr (Located.lident name) [])
635 in
636 let internal_type = generate_typ builder internal_params type_name in
637 let env, params = Env.of_type_decl builder decl in
638 let fn = generate_globalized_for_decl_as_function builder env type_name decl in
639 let fn = eabstract (List.map ~f:pvar params) fn in
640 let fn = eta_reduce_if_possible_and_nonrec ~rec_flag fn in
641 let expr = pexp_constraint fn internal_type in
642 let expr =
643 List.fold_right
644 ~init:expr
645 ~f:(fun name acc -> pexp_newtype (Located.mk name) acc)
646 internal_param_names
647 in
648 value_binding ~pat ~expr
649 ;;
650
651 (* Generate a value declaration for a function to globalize values of a type
652 with declaration [decl]. *)
653 let generate_val decl =
654 let loc = { decl.ptype_loc with loc_ghost = true } in
655 let builder = Ast_builder.make loc in
656 let open (val builder : Ast_builder.S) in
657 let type_name = decl.ptype_name.txt in
658 let name = Located.mk (globalize_name type_name) in
659 let params = List.map decl.ptype_params ~f:(fun (param, _) -> param) in
660 let type_ = generate_typ builder params type_name in
661 let vd = value_description ~name ~type_ ~prim:[] in
662 psig_value vd
663 ;;
664
665 (* The deriver for types in structures *)
666 let generate_str ~ctxt:_ (rec_flag, decls) =
667 let rec_flag = really_recursive rec_flag decls in
668 let vbs = List.map ~f:(generate_vb rec_flag) decls in
669 [ Ast_builder.Default.pstr_value ~loc:Location.none rec_flag vbs ]
670 ;;
671
672 (* The deriver for types in signatures *)
673 let generate_sig ~ctxt:_ (_rec_flag, decls) = List.map ~f:generate_val decls
674
675 (* The implementation of `[%globalize: ...]` *)
676 let extension ~loc:_ ~path:_ typ =
677 let loc = { typ.ptyp_loc with loc_ghost = true } in
678 let builder = Ast_builder.make loc in
679 generate_globalized_for_typ_as_function builder Env.empty None typ
680 ;;
681
682 let extension_name = "globalize"
683
684 let globalize =
685 let str_type_decl = Deriving.Generator.V2.make_noarg generate_str in
686 let sig_type_decl = Deriving.Generator.V2.make_noarg generate_sig in
687 Deriving.add extension_name ~str_type_decl ~sig_type_decl ~extension
688 ;;