Source file ppx_import.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
module Tt = Ppx_types_migrate
let lazy_env =
lazy
(
Ocaml_common.Clflags.recursive_types := true;
Compat.init_path ();
Ocaml_common.Compmisc.initial_env () )
let string_of_lid lid =
let rec print lid acc =
match lid with
| Longident.Lident s -> s :: acc
| Longident.Ldot (lid, id) -> print lid ("." :: id :: acc)
| Longident.Lapply (la, lb) -> print la ("(" :: print lb (")" :: acc))
in
String.concat "" (print lid [])
let try_find_module ~loc env lid =
try
let path = Compat.lookup_module ~loc lid env in
let module_decl = Ocaml_common.Env.find_module path env in
Some module_decl.md_type
with Not_found -> None
let try_find_module_type ~loc env lid =
try
let _path, modtype_decl = Ocaml_common.Env.lookup_modtype ~loc lid env in
Some
( match modtype_decl.mtd_type with
| None ->
Location.raise_errorf ~loc
"[%%import]: cannot access the signature of the abstract module %s"
(string_of_lid lid)
| Some module_type -> module_type )
with Not_found -> None
let rec try_open_module_type env module_type =
match Compat.migrate_module_type module_type with
| Mty_signature sig_items -> Some sig_items
| Mty_functor _ -> None
| Mty_ident path | Mty_alias (_, path) -> (
match
try Some (Ocaml_common.Env.find_module path env) with Not_found -> None
with
| None -> None
| Some module_decl -> try_open_module_type env module_decl.md_type )
let open_module_type ~loc env lid module_type =
match try_open_module_type env module_type with
| Some sig_items -> sig_items
| None ->
Location.raise_errorf ~loc "[%%import]: cannot find the components of %s"
(string_of_lid lid)
let locate_sig ~loc env lid =
let head, path =
match Ppxlib.Longident.flatten_exn lid with
| head :: path -> (Longident.Lident head, path)
| _ -> assert false
in
let head_module_type =
match
(try_find_module ~loc env head, lazy (try_find_module_type ~loc env head))
with
| Some mty, _ -> mty
| None, (lazy (Some mty)) -> mty
| None, (lazy None) ->
Location.raise_errorf ~loc "[%%import]: cannot locate module %s"
(string_of_lid lid)
in
let get_sub_module_type (lid, module_type) path_item =
let sig_items = open_module_type ~loc env lid module_type in
let rec loop sig_items =
match (sig_items : Compat.signature_item_407 list) with
| Sig_module (id, {md_type; _}, _) :: _ when Ident.name id = path_item ->
md_type
| Sig_modtype (id, {mtd_type = Some md_type; _}) :: _
when Ident.name id = path_item ->
md_type
| _ :: sig_items -> loop sig_items
| [] ->
Location.raise_errorf ~loc
"[%%import]: cannot find the signature of %s in %s" path_item
(string_of_lid lid)
in
let sub_module_type =
loop (List.map Compat.migrate_signature_item sig_items)
in
(Longident.Ldot (lid, path_item), sub_module_type)
in
let _lid, sub_module_type =
List.fold_left get_sub_module_type (head, head_module_type) path
in
open_module_type ~loc env lid sub_module_type
let try_get_tsig_item f ~loc:_ sig_items elem =
let rec loop sig_items =
match sig_items with
| item :: sig_items -> (
match f elem item with Some x -> Some x | None -> loop sig_items )
| [] -> None
in
loop sig_items
let get_type_decl ~loc sig_items parent_lid elem =
let select_type elem sigi =
match Compat.migrate_signature_item sigi with
| Sig_type (id, type_decl, _) when Ident.name id = elem -> Some type_decl
| _ -> None
in
match try_get_tsig_item select_type ~loc sig_items elem with
| None ->
Location.raise_errorf "[%%import]: cannot find the type %s in %s" elem
(string_of_lid parent_lid)
| Some decl -> decl
let get_modtype_decl ~loc sig_items parent_lid elem =
let select_modtype elem sigi =
match Compat.migrate_signature_item sigi with
| Sig_modtype (id, type_decl) when Ident.name id = elem -> Some type_decl
| _ -> None
in
match try_get_tsig_item select_modtype ~loc sig_items elem with
| None ->
Location.raise_errorf "[%%import]: cannot find the module type %s in %s"
elem (string_of_lid parent_lid)
| Some decl -> decl
let longident_of_path = Untypeast.lident_of_path
let mknoloc (txt : 'a) : 'a Ppxlib.Location.loc =
{txt; loc = Ppxlib.Location.none}
let rec core_type_of_type_expr ~subst (type_expr : Ocaml_common.Types.type_expr)
: Ppxlib.core_type =
match Compat.get_desc type_expr with
| Tvar None -> Ppxlib.Ast_helper.Typ.any ()
| Tvar (Some var) -> (
match List.assoc (`Var var) subst with
| typ -> typ
| exception Not_found -> Ppxlib.Ast_helper.Typ.var var )
| Tarrow (label, lhs, rhs, _) ->
let label = Tt.copy_arg_label label in
let lhs = core_type_of_type_expr ~subst lhs in
let lhs =
match label with
| Optional _ -> (
match lhs with [%type: [%t? lhs] option] -> lhs | _ -> assert false )
| _ -> lhs
in
Ppxlib.Ast_helper.Typ.arrow label lhs (core_type_of_type_expr ~subst rhs)
| Ttuple xs ->
Ppxlib.Ast_helper.Typ.tuple (List.map (core_type_of_type_expr ~subst) xs)
| Tconstr (path, args, _) -> (
let lid = longident_of_path path in
let args = List.map (core_type_of_type_expr ~subst) args in
match List.assoc (`Lid lid) subst with
| {ptyp_desc = Ptyp_constr (lid, _); _} as typ ->
{typ with ptyp_desc = Ptyp_constr (lid, args)}
| _ -> assert false
| exception Not_found ->
Ppxlib.Ast_helper.Typ.constr
{txt = longident_of_path path; loc = !Ppxlib.Ast_helper.default_loc}
args )
| Tvariant row_desc ->
let fields =
Compat.row_fields row_desc
|> List.map (fun (label, row_field) ->
let label = mknoloc label in
let desc =
match Compat.row_field_repr row_field with
| Types.Rpresent None -> Ppxlib.Rtag (label, true, [])
| Types.Rpresent (Some ttyp) ->
Ppxlib.Rtag (label, false, [core_type_of_type_expr ~subst ttyp])
| _ -> assert false
in
Ppxlib.
{ prf_desc = desc
; prf_loc = !Ppxlib.Ast_helper.default_loc
; prf_attributes = [] } )
in
Ppxlib.Ast_helper.Typ.variant fields Closed None
| _ -> assert false
let ptype_decl_of_ttype_decl ~manifest ~subst ptype_name
(ttype_decl : Ocaml_common.Types.type_declaration) : Ppxlib.type_declaration
=
let subst =
let open Ppxlib in
match manifest with
| Some {ptyp_desc = Ptyp_constr (_, ptype_args); ptyp_loc; _} -> (
subst
@
try
List.map2
(fun (tparam : Ocaml_common.Types.type_expr) pparam ->
match Compat.get_desc tparam with
| Tvar (Some var) -> [(`Var var, pparam)]
| Tvar None -> []
| _ -> assert false )
ttype_decl.type_params ptype_args
|> List.concat
with Invalid_argument _ ->
Location.raise_errorf ~loc:ptyp_loc
"Imported type has %d parameter(s), but %d are passed"
(List.length ttype_decl.type_params)
(List.length ptype_args) )
| None -> []
| _ -> assert false
in
let ptype_params =
List.map2
(fun param _variance ->
( core_type_of_type_expr ~subst param
,
(Ppxlib.Asttypes.NoVariance, Ppxlib.Asttypes.NoInjectivity) ) )
ttype_decl.type_params ttype_decl.type_variance
and ptype_kind =
let map_labels =
List.map (fun (ld : Ocaml_common.Types.label_declaration) ->
Ppxlib.
{ pld_name =
{txt = Ocaml_common.Ident.name ld.ld_id; loc = ld.ld_loc}
; pld_mutable = Tt.copy_mutable_flag ld.ld_mutable
; pld_type = core_type_of_type_expr ~subst ld.ld_type
; pld_loc = ld.ld_loc
; pld_attributes = Tt.copy_attributes ld.ld_attributes } )
in
Ppxlib.(
match Compat.migrate_type_kind ttype_decl.type_kind with
| Type_abstract -> Ptype_abstract
| Type_open -> Ptype_open
| Type_record (labels, _) -> Ptype_record (map_labels labels)
| Type_variant constrs ->
let map_args (constrs : Ocaml_common.Types.constructor_arguments) =
match constrs with
| Cstr_tuple args ->
Pcstr_tuple (List.map (core_type_of_type_expr ~subst) args)
| Cstr_record labels -> Pcstr_record (map_labels labels)
in
Ptype_variant
( constrs
|> List.map (fun (cd : Ocaml_common.Types.constructor_declaration) ->
let pcd_res =
match cd.cd_res with
| Some x -> Some (core_type_of_type_expr ~subst x)
| None -> None
in
{ pcd_name =
{txt = Ocaml_common.Ident.name cd.cd_id; loc = cd.cd_loc}
; pcd_args = map_args cd.cd_args
; pcd_res
; pcd_loc = cd.cd_loc
; pcd_attributes = Tt.copy_attributes cd.cd_attributes } ) ))
and ptype_manifest =
match ttype_decl.type_manifest with
| Some typ -> Some (core_type_of_type_expr ~subst typ)
| None -> manifest
in
{ ptype_name
; ptype_params
; ptype_kind
; ptype_manifest
; ptype_cstrs = []
; ptype_private = Tt.copy_private_flag ttype_decl.type_private
; ptype_attributes = Tt.copy_attributes ttype_decl.type_attributes
; ptype_loc = ttype_decl.type_loc }
let subst_of_manifest ({ptyp_attributes; ptyp_loc; _} : Ppxlib.core_type) =
let open Ppxlib in
let rec subst_of_expr expr =
match expr with
| [%expr
[%e? {pexp_desc = Pexp_ident {txt = src; _}; _}]
:= [%e?
{ pexp_desc = Pexp_ident dst
; pexp_attributes
; pexp_loc
; pexp_loc_stack }]] ->
[ ( `Lid src
, { ptyp_loc = pexp_loc
; ptyp_loc_stack = pexp_loc_stack
; ptyp_attributes = pexp_attributes
; ptyp_desc = Ptyp_constr (dst, []) } ) ]
| [%expr
[%e? {pexp_desc = Pexp_ident {txt = src; _}; _}]
:= [%e?
{ pexp_desc = Pexp_ident dst
; pexp_attributes
; pexp_loc
; pexp_loc_stack }];
[%e? rest]] ->
( `Lid src
, { ptyp_loc = pexp_loc
; ptyp_loc_stack = pexp_loc_stack
; ptyp_attributes = pexp_attributes
; ptyp_desc = Ptyp_constr (dst, []) } )
:: subst_of_expr rest
| {pexp_loc; _} ->
Location.raise_errorf ~loc:pexp_loc "Invalid [@with] syntax"
in
let find_attr s attrs =
try
Some (List.find (fun {attr_name = x; _} -> x.txt = s) attrs).attr_payload
with Not_found -> None
in
match find_attr "with" ptyp_attributes with
| None -> []
| Some (PStr [{pstr_desc = Pstr_eval (expr, []); _}]) -> subst_of_expr expr
| Some _ -> Location.raise_errorf ~loc:ptyp_loc "Invalid [@with] syntax"
let uncapitalize = String.uncapitalize_ascii
let is_self_reference ~input_name lid =
let fn =
input_name |> Filename.basename |> Filename.chop_extension |> uncapitalize
in
match lid with
| Ppxlib.Ldot _ ->
let mn = Ppxlib.Longident.flatten_exn lid |> List.hd |> uncapitalize in
fn = mn
| _ -> false
let type_declaration ~tool_name ~input_name (type_decl : Ppxlib.type_declaration)
=
let open Ppxlib in
match type_decl with
| { ptype_attributes
; ptype_name
; ptype_manifest =
Some {ptyp_desc = Ptyp_extension ({txt = "import"; loc}, payload); _}
; _ } -> (
match payload with
| PTyp ({ptyp_desc = Ptyp_constr ({txt = lid; loc}, _); _} as manifest) ->
if tool_name = "ocamldep" then
if is_self_reference ~input_name lid then
{type_decl with ptype_manifest = None}
else {type_decl with ptype_manifest = Some manifest}
else
Ast_helper.with_default_loc loc (fun () ->
let ttype_decl =
let env = Lazy.force lazy_env in
match lid with
| Lapply _ ->
Location.raise_errorf ~loc
"[%%import] cannot import a functor application %s"
(string_of_lid lid)
| Lident _ as head_id ->
Compat.find_type env ~loc head_id |> snd
| Ldot (parent_id, elem) ->
let sig_items = locate_sig ~loc env parent_id in
get_type_decl ~loc sig_items parent_id elem
in
let m, s =
if is_self_reference ~input_name lid then (None, [])
else
let subst = subst_of_manifest manifest in
let subst =
subst
@ [ ( `Lid (Lident (Longident.last_exn lid))
, Ast_helper.Typ.constr
{txt = Lident ptype_name.txt; loc = ptype_name.loc}
[] ) ]
in
(Some manifest, subst)
in
let ptype_decl =
ptype_decl_of_ttype_decl ~manifest:m ~subst:s ptype_name
ttype_decl
in
{ptype_decl with ptype_attributes} )
| _ -> Location.raise_errorf ~loc "Invalid [%%import] syntax" )
| _ -> type_decl
let rec cut_tsig_block_of_rec_types accu (tsig : Compat.signature_item_407 list)
=
match tsig with
| Sig_type (id, ttype_decl, Trec_next) :: rest ->
cut_tsig_block_of_rec_types ((id, ttype_decl) :: accu) rest
| _ -> (List.rev accu, tsig)
let rec psig_of_tsig ~subst (tsig : Compat.signature_item_407 list) :
Ppxlib.signature_item list =
let open Ppxlib in
match tsig with
| Sig_type (id, ttype_decl, rec_flag) :: rest ->
let accu = [(id, ttype_decl)] in
let rec_flag, (block, rest) =
match rec_flag with
| Trec_not -> (Nonrecursive, (accu, rest))
| Trec_first -> (Recursive, cut_tsig_block_of_rec_types accu rest)
| Trec_next -> assert false
in
let block =
block
|> List.map (fun (id, ttype_decl) ->
ptype_decl_of_ttype_decl ~manifest:None ~subst
(mknoloc (Ocaml_common.Ident.name id))
ttype_decl )
in
let psig_desc = Psig_type (rec_flag, block) in
{psig_desc; psig_loc = Location.none} :: psig_of_tsig ~subst rest
| Sig_value (id, {val_type; val_kind; val_loc; val_attributes; _}) :: rest ->
let pval_prim =
match val_kind with
| Val_reg -> []
| Val_prim p ->
if p.prim_native_name <> "" then [p.prim_name; p.prim_native_name]
else [p.prim_name]
| _ -> assert false
in
{ psig_desc =
Psig_value
{ pval_name = mknoloc (Ocaml_common.Ident.name id)
; pval_loc = val_loc
; pval_attributes = Tt.copy_attributes val_attributes
; pval_prim
; pval_type = core_type_of_type_expr ~subst val_type }
; psig_loc = val_loc }
:: psig_of_tsig ~subst rest
| [] -> []
| _ -> assert false
let module_type ~tool_name ~input_name (package_type : Ppxlib.package_type) =
let open Ppxlib in
let ({txt = lid; loc} as alias), subst = package_type in
if tool_name = "ocamldep" then
if is_self_reference ~input_name lid then
Ast_helper.Mty.mk ~attrs:[] (Pmty_signature [])
else
Ast_helper.Mty.mk ~attrs:[] (Pmty_alias alias)
else
Ppxlib.Ast_helper.with_default_loc loc (fun () ->
let env = Lazy.force lazy_env in
let tmodtype_decl =
match lid with
| Longident.Lapply _ ->
Location.raise_errorf ~loc
"[%%import] cannot import a functor application %s"
(string_of_lid lid)
| Longident.Lident _ as head_id ->
Compat.find_modtype env ~loc head_id |> snd
| Longident.Ldot (parent_id, elem) ->
let sig_items = locate_sig ~loc env parent_id in
get_modtype_decl ~loc sig_items parent_id elem
in
match tmodtype_decl with
| {mtd_type = Some (Mty_signature tsig); _} ->
let subst = List.map (fun ({txt; _}, typ) -> (`Lid txt, typ)) subst in
let psig =
psig_of_tsig ~subst (List.map Compat.migrate_signature_item tsig)
in
Ast_helper.Mty.mk ~attrs:[] (Pmty_signature psig)
| {mtd_type = None; _} ->
Location.raise_errorf ~loc "Imported module is abstract"
| _ ->
Location.raise_errorf ~loc "Imported module is indirectly defined" )
let type_declaration_expand ~ctxt type_decl =
let tool_name = Ppxlib.Expansion_context.Extension.tool_name ctxt in
let input_name = Ppxlib.Expansion_context.Extension.input_name ctxt in
type_declaration ~tool_name ~input_name type_decl
let module_declaration_expand ~ctxt package_type =
let tool_name = Ppxlib.Expansion_context.Extension.tool_name ctxt in
let input_name = Ppxlib.Expansion_context.Extension.input_name ctxt in
module_type ~tool_name ~input_name package_type
let type_declaration_extension =
Ppxlib.Extension.__declare_ppx_import "import" type_declaration_expand
let module_declaration_extension =
Ppxlib.Extension.V3.declare "import" Ppxlib.Extension.Context.module_type
Ppxlib.Ast_pattern.(ptyp (ptyp_package __))
module_declaration_expand
let type_declaration_rule =
Ppxlib.Context_free.Rule.extension type_declaration_extension
let module_declaration_rule =
Ppxlib.Context_free.Rule.extension module_declaration_extension
let () =
Ppxlib.Driver.register_transformation
~rules:[type_declaration_rule; module_declaration_rule]
"ppx_import"