forked from formal-land/coq-of-ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp.ml
1852 lines (1811 loc) · 75.6 KB
/
exp.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
open Typedtree
(** An expression. *)
open SmartPrint
open Monad.Notations
module Header = struct
type t = {
name : Name.t;
typ_vars : VarEnv.t;
args : (Name.t * Type.t) list;
structs : string list;
typ : Type.t;
is_notation : bool;
}
let to_coq_structs (header : t) : SmartPrint.t =
match header.structs with
| [] -> empty
| _ :: _ ->
let structs = separate space (List.map (fun s -> !^s) header.structs) in
braces (nest (!^"struct" ^^ structs))
end
module Definition = struct
type 'a t = { is_rec : Recursivity.t; cases : (Header.t * 'a) list }
end
type match_existential_cast = {
new_typ_vars : VarEnv.t;
bound_vars : (Name.t * Type.t) list;
return_typ : Type.t;
use_axioms : bool;
cast_result : bool;
enable : bool;
}
type dependent_pattern_match = {
cast : Type.t;
motive : Type.t;
args : Type.t list;
}
(** The simplified OCaml AST we use. We do not use a mutualy recursive type to
simplify the importation in Coq. *)
type t =
| Constant of Constant.t
| Variable of MixedPath.t * string list
| Tuple of t list (** A tuple of expressions. *)
| Constructor of PathName.t * string list * t list
(** A constructor name, some implicits, and a list of arguments. *)
| ConstructorExtensible of string * Type.t * t
(** A constructor of an extensible type, with a tag and a payload. *)
| Apply of t * t option list (** An application. *)
| Return of string * t (** Application specialized for a return operation. *)
| InfixOperator of string * t * t
(** Application specialized for an infix operator.
An argument name, an optional type and a body. *)
| Function of Name.t * Type.t option * t
| Functions of Name.t list * t (** An argument names and a body. *)
| LetVar of string option * Name.t * Name.t list * t * t
(** The let of a variable, with optionally a list of polymorphic variables.
We optionally specify the symbol of the let operator as it may be
non-standard for monadic binds. *)
| LetFun of t option Definition.t * t
| LetTyp of Name.t * Name.t list * Type.t * t
(** The definition of a type. It is used to represent module values. *)
| LetModuleUnpack of Name.t * PathName.t * t
(** Open a first-class module. *)
| Match of
t
* dependent_pattern_match option
* (Pattern.t * match_existential_cast option * t) list
* bool (** Match an expression to a list of patterns. *)
| MatchExtensible of t * ((string * Pattern.t * Type.t) option * t) list
(** Match an expression on a list of extensible type patterns. *)
| Record of (PathName.t * int * t) list
(** Construct a record giving an expression for each field. *)
| Field of t * PathName.t (** Access to a field of a record. *)
| IfThenElse of t * t * t (** The "else" part may be unit. *)
| Module of (PathName.t * int * t) list
(** The value of a first-class module. *)
| ModulePack of (int Tree.t * t) (** Pack a module. *)
| Functor of Name.t * Type.t * t (** A functor. *)
| Cast of t * Type.t (** Force the cast to a type (with an axiom). *)
| TypAnnotation of t * Type.t (** Annotate an expression by its type. *)
| Assert of Type.t * t (** The assert keyword. *)
| Error of string (** An error message for unhandled expressions. *)
| ErrorArray of t list (** An error produced by an array of elements. *)
| ErrorTyp of Type.t (** An error composed of a type. *)
| ErrorMessage of t * string
(** An expression together with an error message. *)
| Ltac of ltac
and ltac = Subst | Discriminate | Exact of t | Concat of ltac * ltac
(** Take a function expression and make explicit the list of arguments and
the body. *)
let rec open_function (e : t) : Name.t list * t =
match e with
| Function (x, _, e) ->
let xs, e = open_function e in
(x :: xs, e)
| _ -> ([], e)
let error_message (e : t) (category : Error.Category.t) (message : string) :
t Monad.t =
raise (ErrorMessage (e, message)) category message
let error_message_in_module (field : Name.t option) (e : t)
(category : Error.Category.t) (message : string) :
(string option * Name.t option * t) option Monad.t =
raise (Some (Some message, field, e)) category message
module ModuleTypValues = struct
type t = Module of Name.t * int | Value of Name.t * int
let get (typ_vars : Name.t Name.Map.t) (module_typ : Types.module_type) :
t list Monad.t =
get_env >>= fun env ->
match Env.scrape_alias env module_typ with
| Mty_signature signature ->
signature
|> Monad.List.filter_map (fun item ->
match item with
| Types.Sig_value (ident, { val_type; _ }, _) ->
let* ident = Name.of_ident true ident in
Type.of_typ_expr true typ_vars val_type
>>= fun (_, _, new_typ_vars) ->
return (Some (Value (ident, List.length new_typ_vars)))
| Sig_module (ident, _, { Types.md_type; _ }, _, _) ->
let* name = Name.of_ident false ident in
let* arity =
ModuleTypParams.get_functor_nb_free_vars_params md_type
in
return (Some (Module (name, arity)))
| _ -> return None)
| _ -> raise [] Unexpected "Module type signature not found"
end
let dependent_transform (e : t) (dep_match : dependent_pattern_match option) =
match dep_match with
| None -> e
| Some { args; _ } ->
let args =
args
|> List.mapi (fun i _ -> "eq" ^ string_of_int i |> Name.of_string_raw)
in
let e = Ltac (Concat (Subst, Exact e)) in
Functions (args, e)
let rec any_patterns_with_ith_true (is_guarded : bool) (i : int) (n : int) :
Pattern.t list =
if n = 0 then []
else
let head =
if i = 0 && is_guarded then Pattern.Constructor (PathName.true_value, [])
else Pattern.Any
in
head :: any_patterns_with_ith_true is_guarded (i - 1) (n - 1)
let rec get_include_name (module_expr : module_expr) : Name.t Monad.t =
match module_expr.mod_desc with
| Tmod_apply (applied_expr, _, _) -> (
match applied_expr.mod_desc with
| Tmod_ident (path, _)
| Tmod_constraint ({ mod_desc = Tmod_ident (path, _); _ }, _, _, _) ->
let* path_name = PathName.of_path_with_convert false path in
let* name = PathName.to_name false path_name in
return (Name.suffix_by_include name)
| _ -> get_include_name applied_expr)
| Tmod_constraint (module_expr, _, _, _) -> get_include_name module_expr
| _ ->
raise
(Name.of_string_raw "nameless_include")
NotSupported
("Cannot find a name for this module expression.\n\n"
^ "Try to first give a name to this module before doing the include.")
let build_module (_ : int Tree.t) (values : ModuleTypValues.t list)
(signature_path : Path.t)
(mixed_path_of_value_or_typ : Name.t -> MixedPath.t Monad.t) : t Monad.t =
let* fields =
values
|> Monad.List.map (function
| ModuleTypValues.Value (value, nb_free_vars) ->
let* field_name =
PathName.of_path_and_name_with_convert signature_path value
in
let* mixed_path = mixed_path_of_value_or_typ value in
return (field_name, nb_free_vars, Variable (mixed_path, []))
| Module (name, arity) ->
let* field_name =
PathName.of_path_and_name_with_convert signature_path name
in
let* mixed_path = mixed_path_of_value_or_typ name in
return (field_name, arity, Variable (mixed_path, [])))
in
return (Module fields)
let rec bind_existentials (existentials : Name.t list) (typ : Type.t) : Type.t =
let name = Name.of_string_raw "fst" in
let fst = Type.build_apply_from_name MixedPath.prim_proj_fst name in
let snd = Type.build_apply_from_name MixedPath.prim_proj_snd name in
match existentials with
| [] -> typ
| [ x ] -> Type.Let (x, Variable name, typ)
| [ x; y ] -> Type.Let (x, snd, Type.Let (y, fst, typ))
| x :: xs ->
let typ = bind_existentials xs typ in
Type.Let (x, snd, Type.Let (name, fst, typ))
let build_existential_return (existentials : Name.t list) (typ : Type.t) :
Type.t =
let fst = Name.of_string_raw "fst" in
let exi = Name.of_string_raw "exi" in
let exityp = Type.build_apply_from_name MixedPath.projT1 exi in
let typ = bind_existentials (List.rev existentials) typ in
Type.Let (fst, exityp, typ)
let rec smart_return (operator : string) (e : t) : t Monad.t =
match e with
| Return (operator2, e2) -> (
let* configuration = get_configuration in
match
Configuration.is_in_merge_returns configuration operator operator2
with
| None -> return (Return (operator, e))
| Some target -> return (Return (target, e2)))
| LetVar (None, x, typ_params, e1, e2) ->
let* e2 = smart_return operator e2 in
return (LetVar (None, x, typ_params, e1, e2))
| Match (e, dep_match, cases, is_with_default_case) ->
let* cases =
cases
|> Monad.List.map (fun (p, existential_cast, e) ->
let* e = smart_return operator e in
return (p, existential_cast, e))
in
return (Match (e, dep_match, cases, is_with_default_case))
| _ -> return (Return (operator, e))
(** Import an OCaml expression. *)
let rec of_expression (typ_vars : Name.t Name.Map.t) (e : expression) :
t Monad.t =
set_env e.exp_env
(set_loc e.exp_loc
(let* attributes = Attribute.of_attributes e.exp_attributes in
let typ = e.exp_type in
(* We do not indent here to preserve the diff. *)
let* e =
match e.exp_desc with
| Texp_ident (path, _, _) ->
let implicits = Attribute.get_implicits attributes in
let* x = MixedPath.of_path true path in
return (Variable (x, implicits))
| Texp_constant constant ->
Constant.of_constant constant >>= fun constant ->
return (Constant constant)
| Texp_let (is_rec, cases, e2) ->
of_expression typ_vars e2 >>= fun e2 ->
of_let typ_vars is_rec cases e2
| Texp_function
{
cases =
[
{
c_lhs = { pat_desc = Tpat_var (x, _); pat_type; _ };
c_rhs = e;
_;
};
];
_;
}
| Texp_function
{
cases =
[
{
c_lhs =
{
pat_desc =
Tpat_alias ({ pat_desc = Tpat_any; _ }, x, _);
pat_type;
_;
};
c_rhs = e;
_;
};
];
_;
} ->
let* x = Name.of_ident true x in
let* typ, _, _ = Type.of_typ_expr true typ_vars pat_type in
of_expression typ_vars e >>= fun e ->
return (Function (x, Some typ, e))
| Texp_function { cases; _ } ->
let is_gadt_match =
Attribute.has_match_gadt attributes
|| Attribute.has_match_gadt_with_result attributes
in
let is_tagged_match = Attribute.has_tagged_match attributes in
let do_cast_results =
Attribute.has_match_gadt_with_result attributes
in
let is_with_default_case =
Attribute.has_match_with_default attributes
in
let is_grab_existentials =
Attribute.has_grab_existentials attributes
in
let* x, typ, e =
open_cases typ_vars cases is_gadt_match is_tagged_match
do_cast_results is_with_default_case is_grab_existentials
in
return (Function (x, typ, e))
| Texp_apply (e_f, e_xs) -> (
of_expression typ_vars e_f >>= fun e_f ->
e_xs
|> Monad.List.map (fun (_, e_x) ->
match e_x with
| Some e_x ->
of_expression typ_vars e_x >>= fun e_x ->
return (Some e_x)
| None -> return None)
>>= fun e_xs ->
(* We consider the OCaml's [@@] and [|>] operators as syntactic sugar. *)
let e_f, e_xs =
match (e_f, e_xs) with
| ( Variable
( MixedPath.PathName
{
PathName.path =
[ Name.Make ("Pervasives" | "Stdlib") ];
base = Name.Make "op_atat";
},
[] ),
[ Some f; x ] ) ->
(f, [ x ])
| ( Variable
( MixedPath.PathName
{
PathName.path =
[ Name.Make ("Pervasives" | "Stdlib") ];
base = Name.Make "op_pipegt";
},
[] ),
[ x; Some f ] ) ->
(f, [ x ])
| _ -> (e_f, e_xs)
in
(* We introduce a monadic notation according to the configuration. *)
let* configuration = get_configuration in
let apply_with_let =
match (e_f, e_xs) with
| ( Variable (MixedPath.PathName path_name, []),
[ Some e1; Some (Function (x, _, e2)) ] ) -> (
let name = PathName.to_string path_name in
match Configuration.is_monadic_let configuration name with
| Some let_symbol ->
Some (LetVar (Some let_symbol, x, [], e1, e2))
| None -> None)
| _ -> None
in
let* apply_with_let_return =
match (e_f, e_xs) with
| ( Variable (MixedPath.PathName path_name, []),
[ Some e1; Some (Function (x, _, e2)) ] ) -> (
let name = PathName.to_string path_name in
match
Configuration.is_monadic_let_return configuration name
with
| Some (let_symbol, return_notation) ->
let* return_e2 = smart_return return_notation e2 in
return
(Some (LetVar (Some let_symbol, x, [], e1, return_e2)))
| None -> return None)
| _ -> return None
in
let* apply_with_return =
match (e_f, e_xs) with
| Variable (MixedPath.PathName path_name, []), [ Some e ] -> (
let name = PathName.to_string path_name in
match
Configuration.is_monadic_return configuration name
with
| Some return_notation ->
let* return_e = smart_return return_notation e in
return (Some return_e)
| None -> return None)
| _ -> return None
in
let* apply_with_return_let =
match (e_f, e_xs) with
| ( Variable (MixedPath.PathName path_name, []),
[ Some e1; Some (Function (x, _, e2)) ] ) -> (
let name = PathName.to_string path_name in
match
Configuration.is_monadic_return_let configuration name
with
| Some (return_notation, let_symbol) ->
let* return_e1 = smart_return return_notation e1 in
return
(Some (LetVar (Some let_symbol, x, [], return_e1, e2)))
| None -> return None)
| _ -> return None
in
let apply_with_infix_operator =
match (e_f, e_xs) with
| Variable (mixed_path, []), [ Some e1; Some e2 ] -> (
let name = MixedPath.to_string mixed_path in
match
Configuration.is_operator_infix configuration name
with
| None -> None
| Some operator -> Some (InfixOperator (operator, e1, e2)))
| _ -> None
in
let applies =
[
apply_with_let;
apply_with_let_return;
apply_with_return;
apply_with_return_let;
apply_with_infix_operator;
]
in
match List.find_map (fun x -> x) applies with
| Some apply -> return apply
| None -> return (Apply (e_f, e_xs)))
| Texp_match (e, cases, _) ->
let is_gadt_match =
Attribute.has_match_gadt attributes
|| Attribute.has_match_gadt_with_result attributes
in
let is_tagged_match = Attribute.has_tagged_match attributes in
let do_cast_results =
Attribute.has_match_gadt_with_result attributes
in
let is_with_default_case =
Attribute.has_match_with_default attributes
in
let is_grab_existential =
Attribute.has_grab_existentials attributes
in
let* e = of_expression typ_vars e in
of_match typ_vars e cases is_gadt_match is_tagged_match
do_cast_results is_with_default_case is_grab_existential
| Texp_tuple es ->
Monad.List.map (of_expression typ_vars) es >>= fun es ->
return (Tuple es)
| Texp_construct (_, constructor_description, es) -> (
let* es' = Monad.List.map (of_expression typ_vars) es in
match constructor_description.cstr_tag with
| Cstr_extension (path, _) ->
let* typs =
es
|> Monad.List.map (fun { exp_type; _ } ->
Type.of_type_expr_without_free_vars exp_type)
in
let typ = Type.Tuple typs in
let e = Tuple es' in
return (ConstructorExtensible (Path.last path, typ, e))
| _ ->
let implicits = Attribute.get_implicits attributes in
let* x =
PathName.of_constructor_description constructor_description
in
return (Constructor (x, implicits, es')))
| Texp_variant (label, e) -> (
let* path_name = PathName.constructor_of_variant label in
let constructor = Variable (MixedPath.PathName path_name, []) in
match e with
| None -> return constructor
| Some e ->
let* e = of_expression typ_vars e in
return (Apply (constructor, [ Some e ])))
| Texp_record { fields; extended_expression; _ } -> (
Array.to_list fields
|> Monad.List.filter_map (fun (label_description, definition) ->
(match definition with
| Kept _ -> return None
| Overridden (_, e) ->
PathName.of_label_description label_description
>>= fun x ->
let* typ =
Type.of_type_expr_without_free_vars
label_description.lbl_arg
in
let arity = Type.nb_forall_typs typ in
return (Some (x, arity, e)))
>>= fun x_e ->
match x_e with
| None -> return None
| Some (x, arity, e) ->
of_expression typ_vars e >>= fun e ->
return (Some (x, arity, e)))
>>= fun fields ->
match extended_expression with
| None -> return (Record fields)
| Some extended_expression ->
of_expression typ_vars extended_expression
>>= fun extended_e ->
return
(List.fold_left
(fun extended_e (x, _, e) ->
Apply
( Variable
( MixedPath.PathName (PathName.prefix_by_with x),
[] ),
[ Some e; Some extended_e ] ))
extended_e fields))
| Texp_field (e, _, label_description) ->
PathName.of_label_description label_description >>= fun x ->
of_expression typ_vars e >>= fun e -> return (Field (e, x))
| Texp_ifthenelse (e1, e2, e3) ->
of_expression typ_vars e1 >>= fun e1 ->
of_expression typ_vars e2 >>= fun e2 ->
(match e3 with
| None -> return (Tuple [])
| Some e3 -> of_expression typ_vars e3)
>>= fun e3 -> return (IfThenElse (e1, e2, e3))
| Texp_sequence (e1, e2) ->
let* e1 = of_expression typ_vars e1 in
let* e2 = of_expression typ_vars e2 in
return (Match (e1, None, [ (Pattern.Any, None, e2) ], false))
| Texp_try (e, cases) -> (
let* e = of_expression typ_vars e in
let default_error =
error_message (Error "typ_with_with_non_trivial_matching")
SideEffect
("Use a trivial matching for the `with` clause, like:\n"
^ "\n" ^ " try ... with exn -> ...\n" ^ "\n"
^ "You can do a second matching on `exn` in the error handler \
if needed.")
in
match cases with
| [ { c_lhs; c_rhs; _ } ] -> (
let* name =
match c_lhs.pat_desc with
| Tpat_var (ident, _) ->
let* name = Name.of_ident true ident in
return (Some name)
| Tpat_any -> return (Some Name.Nameless)
| _ -> return None
in
match name with
| Some name ->
let* error_handler = of_expression typ_vars c_rhs in
error_message
(Apply
( Variable
( MixedPath.of_name
(Name.of_string_raw "try_with"),
[] ),
[
Some (Function (Name.Nameless, None, e));
Some (Function (name, None, error_handler));
] ))
SideEffect
("Try-with are not handled\n\n"
^ "Alternative: use sum types (\"option\", \"result\", \
...) to represent an error case.")
| None -> default_error)
| _ -> default_error)
| Texp_setfield (e_record, _, { lbl_name; _ }, e) ->
of_expression typ_vars e_record >>= fun e_record ->
of_expression typ_vars e >>= fun e ->
error_message
(Apply
( Error "set_record_field",
[
Some e_record;
Some (Constant (Constant.String lbl_name));
Some e;
] ))
SideEffect "Set record field not handled."
| Texp_array es ->
Monad.List.map (of_expression typ_vars) es >>= fun es ->
error_message (ErrorArray es) NotSupported "Arrays not handled."
| Texp_while _ ->
error_message (Error "while") SideEffect
"While loops not handled."
| Texp_for _ ->
error_message (Error "for") SideEffect "For loops not handled."
| Texp_send _ ->
error_message (Error "send") NotSupported
"Sending method message is not handled"
| Texp_new _ ->
error_message (Error "new") NotSupported
"Creation of new objects is not handled"
| Texp_instvar _ ->
error_message (Error "instance_variable") NotSupported
"Creating an instance variable is not handled"
| Texp_setinstvar _ ->
error_message (Error "set_instance_variable") SideEffect
"Setting an instance variable is not handled"
| Texp_override _ ->
error_message (Error "override") NotSupported
"Overriding is not handled"
| Texp_letmodule
( x,
_,
_,
{
mod_desc =
Tmod_unpack ({ exp_desc = Texp_ident (path, _, _); _ }, _);
_;
},
e ) ->
let* x = Name.of_optional_ident true x in
PathName.of_path_with_convert false path >>= fun path_name ->
of_expression typ_vars e >>= fun e ->
return (LetModuleUnpack (x, path_name, e))
| Texp_letmodule (x, _, _, module_expr, e) ->
let* x = Name.of_optional_ident true x in
push_env
( of_module_expr typ_vars module_expr None >>= fun value ->
set_env e.exp_env
(push_env
( of_expression typ_vars e >>= fun e ->
return (LetVar (None, x, [], value, e)) )) )
| Texp_letexception _ ->
error_message (Error "let_exception") SideEffect
"Let of exception is not handled"
| Texp_assert e' ->
Type.of_typ_expr false typ_vars e.exp_type >>= fun (typ, _, _) ->
of_expression typ_vars e' >>= fun e' ->
error_message
(Assert (typ, e'))
SideEffect "Assert instruction is not handled."
| Texp_lazy e ->
of_expression typ_vars e >>= fun e ->
error_message
(Apply (Error "lazy", [ Some e ]))
SideEffect "Lazy expressions are not handled"
| Texp_object _ ->
error_message (Error "object") NotSupported
"Creation of objects is not handled"
| Texp_pack module_expr ->
let* module_typ_params =
ModuleTypParams.get_module_typ_typ_params_arity
module_expr.mod_type
in
push_env (of_module_expr typ_vars module_expr None) >>= fun e ->
return (ModulePack (module_typ_params, e))
| Texp_letop
{
let_ = { bop_op_path; bop_exp; _ };
ands;
body = { c_lhs; c_rhs; _ };
_;
} -> (
match ands with
| [] -> (
let let_symbol = Path.last bop_op_path in
let* pattern = Pattern.of_pattern c_lhs in
let* e1 = of_expression typ_vars bop_exp in
let* e2 = of_expression typ_vars c_rhs in
match pattern with
| Some (Variable name) ->
return (LetVar (Some let_symbol, name, [], e1, e2))
| _ ->
let cases =
match pattern with
| None -> []
| Some pattern -> [ (pattern, None, e2) ]
in
return
(LetVar
( Some let_symbol,
Name.FunctionParameter,
[],
e1,
Match
( Variable
( MixedPath.PathName
{
PathName.path = [];
base = Name.FunctionParameter;
},
[] ),
None,
cases,
false ) )))
| _ :: _ ->
error_message (Error "let_op_and") NotSupported
"We do not support let operators with and")
| Texp_unreachable ->
error_message (Error "unreachable") NotSupported
"Unreachable expressions are not supported"
| Texp_extension_constructor _ ->
error_message (Error "extension") NotSupported
"Construction of extensions is not handled"
| Texp_open (_, e) -> of_expression typ_vars e
in
if Attribute.has_cast attributes then
let* typ, _, _ = Type.of_typ_expr false typ_vars typ in
return (Cast (e, typ))
else if Attribute.has_typ_annotation attributes then
let* typ, _, _ = Type.of_typ_expr false typ_vars typ in
return (TypAnnotation (e, typ))
else return e))
and of_match :
type k.
Name.t Name.Map.t ->
t ->
k case list ->
bool ->
bool ->
bool ->
bool ->
bool ->
t Monad.t =
fun typ_vars e cases is_gadt_match is_tagged_match do_cast_results
is_with_default_case is_grab_existentials ->
let is_extensible_type_match =
cases
|> List.map (fun { c_lhs; _ } -> c_lhs)
|> Pattern.are_extensible_patterns_or_any true
in
if is_extensible_type_match then of_match_extensible typ_vars e cases
else
let* (dep_match : dependent_pattern_match option) =
match cases with
| [] -> return None
| { c_lhs; c_rhs; _ } :: _ ->
if not is_tagged_match then return None
else
let* cast, _, new_typ_vars =
Type.of_typ_expr true Name.Map.empty c_lhs.pat_type
in
let* motive, _, new_typ_vars' =
Type.of_typ_expr true Name.Map.empty c_rhs.exp_type
in
let new_typ_vars = VarEnv.union new_typ_vars new_typ_vars' in
let* cast = Type.decode_var_tags new_typ_vars false cast in
let* motive = Type.decode_var_tags new_typ_vars false motive in
let cast, args = Type.normalize_constructor cast in
(* Only generates dependent pattern matching for actual gadts *)
if List.length args = 0 || Type.is_native_type cast then return None
else return (Some { cast; args; motive })
in
cases
|> Monad.List.filter_map (fun { c_lhs; c_guard; c_rhs } ->
set_loc c_lhs.pat_loc
(let* bound_vars =
Typedtree.pat_bound_idents c_lhs
|> List.rev
|> Monad.List.map (fun ident ->
let { Types.val_type; _ } =
Env.find_value (Path.Pident ident) c_rhs.exp_env
in
let* name = Name.of_ident true ident in
return (name, val_type))
in
let typs = List.map snd bound_vars in
let tag_list = Type.tag_no_args typs in
let* new_typ_vars =
Type.typed_existential_typs_of_typs typs tag_list
in
Monad.List.map
(fun (name, typ) ->
Type.of_typ_expr true typ_vars typ >>= fun (typ, _, _) ->
return (name, typ))
bound_vars
>>= fun bound_vars ->
let env_has_tag =
List.exists (fun (_, ki) -> ki = Kind.Tag) new_typ_vars
in
let new_typ_vars =
if is_gadt_match then new_typ_vars
else
let free_vars =
Type.local_typ_constructors_of_typs
(List.map snd bound_vars)
|> Name.Set.elements
in
let tag_vars =
new_typ_vars
|> List.filter_map (fun (name, ki) ->
if ki = Kind.Tag then Some name else None)
in
VarEnv.keep_only (free_vars @ tag_vars) new_typ_vars
in
let* bound_vars =
Monad.List.map
(fun (x, ty) ->
let* ty = Type.decode_var_tags new_typ_vars false ty in
return (x, ty))
bound_vars
in
let* typ =
if is_gadt_match || do_cast_results || not env_has_tag then
let* typ, _, _ =
Type.of_typ_expr true typ_vars c_rhs.exp_type
in
return typ
else
(* Only expand type if you really need to. It may cause the translation to break *)
let typ = Ctype.full_expand c_rhs.exp_env c_rhs.exp_type in
let* typ, _, _ = Type.of_typ_expr true typ_vars typ in
return typ
in
let existential_cast =
Some
{
new_typ_vars;
bound_vars;
return_typ = typ;
use_axioms = is_gadt_match;
cast_result = do_cast_results;
enable = is_grab_existentials || is_gadt_match;
}
in
(match c_guard with
| Some guard ->
of_expression typ_vars guard >>= fun guard ->
return (Some guard)
| None -> return None)
>>= fun guard ->
Pattern.of_pattern c_lhs >>= fun pattern ->
match c_rhs.exp_desc with
| Texp_unreachable -> return None
| _ ->
of_expression typ_vars c_rhs >>= fun e ->
let e = dependent_transform e dep_match in
return
(pattern
|> Option.map (fun pattern ->
(pattern, existential_cast, guard, e)))))
>>= fun cases_with_guards ->
let guards =
cases_with_guards
|> List.filter_map (function
| p, _, Some guard, _ -> Some (p, guard)
| _ -> None)
in
let guard_checks =
guards
|> List.map (fun (p, guard) ->
let is_pattern_always_true =
match p with
| Pattern.Any | Pattern.Variable _ -> true
| _ -> false
in
let cases =
[ (p, None, guard) ]
@
if is_pattern_always_true then []
else
[
( Pattern.Any,
None,
Variable (MixedPath.PathName PathName.false_value, []) );
]
in
Match (e, None, cases, false))
in
let e = match guards with [] -> e | _ :: _ -> Tuple (e :: guard_checks) in
let i = ref (-1) in
let nb_guards = List.length guard_checks in
let cases =
cases_with_guards
|> List.map (fun (p, existential_cast, guard, rhs) ->
let is_guarded =
match guard with Some _ -> true | None -> false
in
if is_guarded then i := !i + 1;
let p =
if nb_guards = 0 then p
else
Pattern.Tuple
(p :: any_patterns_with_ith_true is_guarded !i nb_guards)
in
(p, existential_cast, rhs))
in
let t = Match (e, dep_match, cases, is_with_default_case) in
(* If its a deppendent pattern matching then add eq_refl at the end of the match *)
match dep_match with
| None -> return t
| Some dep_match ->
let eq_refl = "eq_refl" |> Name.of_string_raw |> MixedPath.of_name in
let ts =
List.map (fun _ -> Some (Variable (eq_refl, []))) dep_match.args
in
return (Apply (t, ts))
(** We suppose that we know that we have a match of extensible types. *)
and of_match_extensible :
type kind. Name.t Name.Map.t -> t -> kind case list -> t Monad.t =
fun (typ_vars : Name.t Name.Map.t) (e : t) (cases : kind case list) ->
let* cases =
cases
|> Monad.List.map (fun { c_lhs; c_rhs; _ } ->
set_loc c_lhs.pat_loc
(let* p = Pattern.of_extensible_pattern c_lhs in
let* e = of_expression typ_vars c_rhs in
return (p, e)))
in
return (MatchExtensible (e, cases))
(** Generate a variable and a "match" on this variable from a list of
patterns. *)
and open_cases (type pattern_kind) (typ_vars : Name.t Name.Map.t)
(cases : pattern_kind case list) (is_gadt_match : bool)
(is_tagged_match : bool) (do_cast_results : bool)
(is_with_default_case : bool) (is_grab_existentials : bool) :
(Name.t * Type.t option * t) Monad.t =
let name = Name.FunctionParameter in
let* typ =
match cases with
| [] -> return None
| { c_lhs = { pat_type; _ }; _ } :: _ ->
let* typ, _, _ = Type.of_typ_expr true typ_vars pat_type in
return (Some typ)
in
let e = Variable (MixedPath.of_name name, []) in
let* e =
of_match typ_vars e cases is_gadt_match is_tagged_match do_cast_results
is_with_default_case is_grab_existentials
in
return (name, typ, e)
and import_let_fun (typ_vars : Name.t Name.Map.t) (at_top_level : bool)
(is_rec : Asttypes.rec_flag) (cases : value_binding list) :
t option Definition.t Monad.t =
let is_rec = Recursivity.of_rec_flag is_rec in
cases
|> Monad.List.filter_map (fun { vb_pat = p; vb_expr; vb_attributes; _ } ->
Attribute.of_attributes vb_attributes >>= fun attributes ->
let is_axiom = Attribute.has_axiom_with_reason attributes in
let structs = Attribute.get_structs attributes in
set_env vb_expr.exp_env
(set_loc p.pat_loc
( Pattern.of_pattern p >>= fun p ->
(match p with
| Some Pattern.Any -> return None
| Some (Pattern.Variable x) -> return (Some x)
| _ ->
raise None Unexpected
"A variable name instead of a pattern was expected")
>>= fun x ->
let predefined_variables =
List.map snd (Name.Map.bindings typ_vars)
in
let exp_type =
(* Special case for functions whose type is given by a type
synonym at the end rather than with a type on each
parameter or an explicit arrow type. *)
match (vb_expr.exp_desc, vb_expr.exp_type.desc) with
| Texp_function _, Tconstr (path, _, _) -> (
match Env.find_type path vb_expr.exp_env with
| { type_manifest = Some ty; _ } -> ty
| _ | (exception _) -> vb_expr.exp_type)
| _ -> vb_expr.exp_type
in
Type.of_typ_expr true typ_vars exp_type
>>= fun (e_typ, typ_vars, new_typ_vars) ->
let* e_typ = Type.decode_var_tags new_typ_vars false e_typ in
let new_typ_vars =
VarEnv.remove predefined_variables new_typ_vars
in
match x with
| None -> return None
| Some x ->
let* args_names, e_body =
if not is_axiom then
let* e = of_expression typ_vars vb_expr in
let args_names, e_body = open_function e in
return (args_names, Some e_body)
else return ([], None)
in
let* args_typs, e_body_typ =
Type.open_type e_typ (List.length args_names)
in
let header =
{
Header.name = x;
typ_vars = new_typ_vars;
args = List.combine args_names args_typs;
structs;
typ = e_body_typ;
is_notation =
Attribute.has_mutual_as_notation attributes;
}
in
return (Some (header, e_body)) )))
>>= fun cases ->
let result = { Definition.is_rec; cases } in
match (at_top_level, result) with
| false, { is_rec = true; cases = _ :: _ :: _ } ->
raise result NotSupported
"Mutually recursive definition are only handled at top-level"
| _ -> return result