-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
typecore.re
3292 lines (3186 loc) 路 90.8 KB
/
typecore.re
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 Grain_parsing;
open Misc;
open Asttypes;
open Parsetree;
open Types;
open Typedtree;
open Btype;
open Ctype;
open Checkertypes;
open Typepat;
open Disambiguation;
type error =
| Arity_mismatch(type_expr, option(type_forcing_context))
| Polymorphic_label(Identifier.t)
| Constructor_arity_mismatch(Identifier.t, int, int)
| Label_mismatch(Identifier.t, list((type_expr, type_expr)))
| Pattern_type_clash(list((type_expr, type_expr)))
| Or_pattern_type_clash(Ident.t, list((type_expr, type_expr)))
| Multiply_bound_variable(string)
| Orpat_vars(Ident.t, list(Ident.t))
| Expr_type_clash(
list((type_expr, type_expr)),
option(type_forcing_context),
)
| Apply_non_function(type_expr)
| Apply_too_many_arguments(type_expr, list((argument_label, type_expr)))
| Apply_too_few_arguments(list((argument_label, type_expr)))
| Apply_unknown_label(string, list(string))
| Label_multiply_defined(string)
| Label_missing(list(Ident.t))
| Label_not_mutable(Identifier.t)
| Assign_not_mutable(Identifier.t)
| Wrong_name(string, type_expected, string, Path.t, string, list(string))
| Name_type_mismatch(
string,
Identifier.t,
(Path.t, Path.t),
list((Path.t, Path.t)),
)
| Invalid_format(string)
| Undefined_method(type_expr, string, option(list(string)))
| Undefined_inherited_method(string, list(string))
| Virtual_class(Identifier.t)
| Private_type(type_expr)
| Private_label(Identifier.t, type_expr)
| Unbound_instance_variable(string, list(string))
| Instance_variable_not_mutable(bool, string)
| Not_subtype(
list((type_expr, type_expr)),
list((type_expr, type_expr)),
)
| Outside_class
| Value_multiply_overridden(string)
| Coercion_failure(
type_expr,
type_expr,
list((type_expr, type_expr)),
bool,
)
| Not_a_function(type_expr, option(type_forcing_context))
| Function_label_mismatch({
got: argument_label,
expected: argument_label,
expected_type: type_expr,
explanation: option(type_forcing_context),
})
| Scoping_let_module(string, type_expr)
| Masked_instance_variable(Identifier.t)
| Not_a_variant_type(Identifier.t)
| Incoherent_label_order
| Less_general(string, list((type_expr, type_expr)))
| Modules_not_allowed
| Cannot_infer_signature
| Not_a_packed_module(type_expr)
| Recursive_local_constraint(list((type_expr, type_expr)))
| Unexpected_existential
| Unqualified_gadt_pattern(Path.t, string)
| Invalid_interval
| Invalid_for_loop_index
| No_value_clauses
| Exception_pattern_below_toplevel
| Inlined_record_escape
| Inlined_record_misuse(Identifier.t, string, string)
| Invalid_extension_constructor_payload
| Not_an_extension_constructor
| Literal_overflow(string)
| Unknown_literal(string, char)
| Illegal_letrec_pat
| Illegal_letrec_expr
| Illegal_class_expr
| Unbound_value_missing_rec(Identifier.t, Location.t);
exception Error(Location.t, Env.t, error);
exception Error_forward(Location.error);
type recarg =
| Allowed
| Required
| Rejected;
let grain_type_of_wasm_prim_type =
fun
| Wasm_int32 => Builtin_types.type_wasmi32
| Wasm_int64 => Builtin_types.type_wasmi64
| Wasm_float32 => Builtin_types.type_wasmf32
| Wasm_float64 => Builtin_types.type_wasmf64
| Grain_bool => Builtin_types.type_bool;
let prim_type = (args, ret) =>
newgenty(
TTyArrow(
List.map(
((name, ty)) => (Labeled(Location.mknoloc(name)), ty),
args,
),
ret,
TComOk,
),
);
let prim0_type =
fun
| AllocateInt32
| AllocateInt64
| AllocateUint32
| AllocateUint64
| AllocateFloat32
| AllocateFloat64
| AllocateRational
| WasmMemorySize
| HeapStart
| HeapTypeMetadata => prim_type([], Builtin_types.type_wasmi32)
| Unreachable => prim_type([], newgenvar(~name="a", ()));
let prim1_type =
fun
| AllocateArray
| AllocateTuple
| AllocateBytes
| AllocateString
| AllocateBigInt =>
prim_type(
[("size", Builtin_types.type_wasmi32)],
Builtin_types.type_wasmi32,
)
| StringSize
| BytesSize
| LoadAdtVariant =>
prim_type(
[("ptr", Builtin_types.type_wasmi32)],
Builtin_types.type_wasmi32,
)
| NewInt32 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_wasmi32,
)
| NewInt64 =>
prim_type(
[("int", Builtin_types.type_wasmi64)],
Builtin_types.type_wasmi32,
)
| NewUint32 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_wasmi32,
)
| NewUint64 =>
prim_type(
[("int", Builtin_types.type_wasmi64)],
Builtin_types.type_wasmi32,
)
| NewFloat32 =>
prim_type(
[("float", Builtin_types.type_wasmf32)],
Builtin_types.type_wasmi32,
)
| NewFloat64 =>
prim_type(
[("float", Builtin_types.type_wasmf64)],
Builtin_types.type_wasmi32,
)
| BuiltinId =>
prim_type(
[("str", Builtin_types.type_string)],
Builtin_types.type_number,
)
| TagSimpleNumber =>
prim_type(
[("num", Builtin_types.type_wasmi32)],
Builtin_types.type_number,
)
| UntagSimpleNumber =>
prim_type(
[("num", Builtin_types.type_number)],
Builtin_types.type_wasmi32,
)
| TagChar =>
prim_type(
[("char", Builtin_types.type_wasmi32)],
Builtin_types.type_char,
)
| UntagChar =>
prim_type(
[("char", Builtin_types.type_char)],
Builtin_types.type_wasmi32,
)
| TagInt8 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_int8,
)
| UntagInt8 =>
prim_type(
[("int", Builtin_types.type_int8)],
Builtin_types.type_wasmi32,
)
| TagInt16 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_int16,
)
| UntagInt16 =>
prim_type(
[("int", Builtin_types.type_int16)],
Builtin_types.type_wasmi32,
)
| TagUint8 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_uint8,
)
| UntagUint8 =>
prim_type(
[("int", Builtin_types.type_uint8)],
Builtin_types.type_wasmi32,
)
| TagUint16 =>
prim_type(
[("int", Builtin_types.type_wasmi32)],
Builtin_types.type_uint16,
)
| UntagUint16 =>
prim_type(
[("int", Builtin_types.type_uint16)],
Builtin_types.type_wasmi32,
)
| Not =>
prim_type([("bool", Builtin_types.type_bool)], Builtin_types.type_bool)
| Box
| BoxBind => {
let var = newgenvar(~name="a", ());
prim_type([("value", var)], Builtin_types.type_box(var));
}
| Unbox
| UnboxBind => {
let var = newgenvar(~name="a", ());
prim_type([("value", Builtin_types.type_box(var))], var);
}
| Ignore => {
let var = newgenvar(~name="a", ());
prim_type([("value", var)], Builtin_types.type_void);
}
| ArrayLength => {
let var = newgenvar(~name="a", ());
prim_type(
[("array", Builtin_types.type_array(var))],
Builtin_types.type_number,
);
}
| Assert =>
prim_type(
[("condition", Builtin_types.type_bool)],
Builtin_types.type_void,
)
| Throw =>
prim_type(
[("exn", Builtin_types.type_exception)],
newgenvar(~name="a", ()),
)
| Magic =>
prim_type(
[("value", newgenvar(~name="a", ()))],
newgenvar(~name="b", ()),
)
| WasmFromGrain =>
prim_type(
[("value", newgenvar(~name="a", ()))],
Builtin_types.type_wasmi32,
)
| WasmToGrain =>
prim_type(
[("value", Builtin_types.type_wasmi32)],
newgenvar(~name="a", ()),
)
| WasmUnaryI32({arg_type, ret_type})
| WasmUnaryI64({arg_type, ret_type})
| WasmUnaryF32({arg_type, ret_type})
| WasmUnaryF64({arg_type, ret_type}) =>
prim_type(
[("num", grain_type_of_wasm_prim_type(arg_type))],
grain_type_of_wasm_prim_type(ret_type),
)
| WasmMemoryGrow =>
prim_type(
[("size", Builtin_types.type_wasmi32)],
Builtin_types.type_wasmi32,
);
let prim2_type =
fun
| NewRational =>
prim_type(
[
("numerator", Builtin_types.type_wasmi32),
("denominator", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmi32,
)
| And
| Or =>
prim_type(
[
("left", Builtin_types.type_bool),
("right", Builtin_types.type_bool),
],
Builtin_types.type_bool,
)
| Is
| Eq => {
let v = newgenvar(~name="a", ());
prim_type([("left", v), ("right", v)], Builtin_types.type_bool);
}
| WasmBinaryI32({arg_types: (arg1_type, arg2_type), ret_type})
| WasmBinaryI64({arg_types: (arg1_type, arg2_type), ret_type})
| WasmBinaryF32({arg_types: (arg1_type, arg2_type), ret_type})
| WasmBinaryF64({arg_types: (arg1_type, arg2_type), ret_type}) =>
prim_type(
[
("left", grain_type_of_wasm_prim_type(arg1_type)),
("right", grain_type_of_wasm_prim_type(arg2_type)),
],
grain_type_of_wasm_prim_type(ret_type),
)
| WasmLoadI32(_) =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmi32,
)
| WasmLoadI64(_) =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmi64,
)
| WasmLoadF32 =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmf32,
)
| WasmLoadF64 =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmf64,
);
let primn_type =
fun
| WasmStoreI32(_) =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("value", Builtin_types.type_wasmi32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmStoreI64(_) =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("value", Builtin_types.type_wasmi64),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmStoreF32 =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("value", Builtin_types.type_wasmf32),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmStoreF64 =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("value", Builtin_types.type_wasmf64),
("offset", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmMemoryCopy =>
prim_type(
[
("source", Builtin_types.type_wasmi32),
("destination", Builtin_types.type_wasmi32),
("length", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmMemoryFill =>
prim_type(
[
("ptr", Builtin_types.type_wasmi32),
("value", Builtin_types.type_wasmi32),
("length", Builtin_types.type_wasmi32),
],
Builtin_types.type_void,
)
| WasmMemoryCompare =>
prim_type(
[
("ptr1", Builtin_types.type_wasmi32),
("ptr2", Builtin_types.type_wasmi32),
("length", Builtin_types.type_wasmi32),
],
Builtin_types.type_wasmi32,
);
let maybe_add_pattern_variables_ghost = (loc_let, env, pv) =>
List.fold_right(
((id, ty, _name, loc, _as_var), env) => {
let lid = Identifier.IdentName(mkloc(Ident.name(id), loc));
switch (Env.lookup_value(~mark=false, lid, env)) {
| _ => env
| exception Not_found =>
Env.add_value(
id,
{
val_type: ty,
val_repr: Type_utils.repr_of_type(env, ty),
val_internalpath: Path.PIdent(id),
val_fullpath: Path.PIdent(id),
val_kind: TValUnbound(ValUnboundGhostRecursive),
val_loc: loc_let,
val_mutable: false,
val_global: false,
},
env,
)
};
},
pv,
env,
);
let constant:
(Location.t, Parsetree.constant) =>
result(Asttypes.constant, Location.error) = (
Checkertypes.constant:
(Location.t, Parsetree.constant) =>
result(Asttypes.constant, Location.error)
);
let constant_or_raise = Checkertypes.constant_or_raise;
let mkexp = (exp_desc, exp_type, exp_loc, exp_env, exp_attributes) => {
exp_desc,
exp_type,
exp_loc,
exp_env,
exp_extra: [],
exp_attributes,
};
/* Specific version of type_option, using newty rather than newgenty */
let type_option = ty =>
newty(TTyConstr(Builtin_types.path_option, [ty], ref(TMemNil)));
let option_some = (env, texp) => {
let csome =
Env.find_constructor(Path.PIdent(Builtin_types.ident_some_cstr), env);
mkexp(
TExpConstruct(
mknoloc(Identifier.IdentName(mknoloc("Some"))),
csome,
TExpConstrTuple([texp]),
),
type_option(texp.exp_type),
texp.exp_loc,
texp.exp_env,
[],
);
};
let option_none = (env, ty, loc) => {
let cnone =
Env.find_constructor(Path.PIdent(Builtin_types.ident_none_cstr), env);
mkexp(
TExpConstruct(
mknoloc(Identifier.IdentName(mknoloc("None"))),
cnone,
TExpConstrTuple([]),
),
type_option(ty),
loc,
env,
[],
);
};
let extract_option_type = (env, ty) => {
switch (expand_head(env, ty).desc) {
| TTyConstr(path, [ty], _) when Path.same(path, Builtin_types.path_option) => ty
| _ => failwith("Impossible: option type was not an option")
};
};
/* Typing of patterns */
/* unification inside type_pat*/
let unify_pat_types = (loc, env, ty, ty') =>
try(unify(env, ty, ty')) {
| Unify(trace) => raise(Error(loc, env, Pattern_type_clash(trace)))
};
/* unification inside type_exp and type_expect */
let unify_exp_types = (loc, env, ty, expected_ty) =>
/*Format.eprintf ("Unifying: @[%a@ %a@]@.", Printtyp.raw_type_expr, ty,
Printtyp.raw_type_expr, expected_ty);*/
try(unify(env, ty, expected_ty)) {
| Unify(trace) => raise(Error(loc, env, Expr_type_clash(trace, None)))
};
/* level at which to create the local type declarations */
let newtype_level = ref(None);
let get_newtype_level = () =>
switch (newtype_level^) {
| Some(y) => y
| None => assert(false)
};
let rec last = lst =>
switch (lst) {
| [] => raise(Not_found)
| [e] => e
| [_, ...es] => last(es)
};
let rec final_subexpression = sexp =>
switch (sexp.pexp_desc) {
| PExpIf(_, e, _)
| PExpWhile(_, e)
| PExpMatch(_, {txt: [{pmb_body: e}, ..._]}) => final_subexpression(e)
| PExpBlock(es) =>
try(final_subexpression(last(es))) {
| Not_found => sexp
}
| _ => sexp
};
let rec is_nonexpansive = exp =>
switch (exp.exp_desc) {
| TExpIdent(_)
| TExpConstant(_)
| TExpLambda(_) => true
| TExpTuple(es) => List.for_all(is_nonexpansive, es)
| TExpLet(rec_flag, Immutable, binds) =>
List.for_all(vb => is_nonexpansive(vb.vb_expr), binds)
| TExpMatch(e, cases, _) =>
is_nonexpansive(e)
&& List.for_all(({mb_pat, mb_body}) => is_nonexpansive(mb_body), cases)
| TExpPrim1(_, e) => is_nonexpansive(e)
| TExpPrim2(_, e1, e2) => is_nonexpansive(e1) && is_nonexpansive(e2)
| TExpIf(c, t, f) => is_nonexpansive(t) && is_nonexpansive(f)
| TExpWhile(c, b) => is_nonexpansive(b)
| TExpBlock([_, ..._] as es) => is_nonexpansive(last(es))
| TExpConstruct(_, _, TExpConstrTuple(el)) =>
List.for_all(is_nonexpansive, el)
| _ => false
};
let maybe_expansive = e => !is_nonexpansive(e);
/* Approximate the type of an expression, for better recursion */
let rec approx_type = (env, sty) =>
switch (sty.ptyp_desc) {
| PTyArrow(args, ret) =>
newty(
TTyArrow(
List.map(x => (x.ptyp_arg_label, newvar()), args),
approx_type(env, ret),
TComOk,
),
)
| PTyTuple(args) => newty(TTyTuple(List.map(approx_type(env), args)))
| PTyConstr(id, args) =>
try({
let path = Env.lookup_type(id.txt, env);
let decl = Env.find_type(path, env);
if (List.length(args) != decl.type_arity) {
raise(Not_found);
};
let tyl = List.map(approx_type(env), args);
newconstr(path, tyl);
}) {
| Not_found => newvar()
}
| _ => newvar()
};
let rec type_approx = (env, sexp: Parsetree.expression) =>
switch (sexp.pexp_desc) {
| PExpLet(_, _, _) => Builtin_types.type_void
| PExpMatch(_, {txt: [{pmb_body: e}, ..._]}) => type_approx(env, e)
| PExpIf(_, e, _) => type_approx(env, e)
| PExpWhile(_, e) => type_approx(env, e)
| PExpLambda(args, e) =>
newty(
TTyArrow(
List.map(x => (x.pla_label, newvar()), args),
type_approx(env, e),
TComOk,
),
)
| PExpBlock([_, ..._] as es) => type_approx(env, last(es))
| _ => newvar()
};
/* Check that all univars are safe in a type */
let check_univars = (env, expans, kind, exp, ty_expected, vars) => {
if (expans && !is_nonexpansive(exp)) {
generalize_expansive(env, exp.exp_type);
};
/* need to expand twice? cf. Ctype.unify2 */
let vars = List.map(expand_head(env), vars);
let vars = List.map(expand_head(env), vars);
let vars' =
List.filter(
t => {
let t = repr(t);
generalize(t);
switch (t.desc) {
| TTyVar(name) when t.level == generic_level =>
log_type(t);
t.desc = TTyUniVar(name);
true;
| _ => false
};
},
vars,
);
if (List.length(vars) == List.length(vars')) {
();
} else {
let ty = newgenty(TTyPoly(repr(exp.exp_type), vars'))
and ty_expected = repr(ty_expected);
raise(
Error(
exp.exp_loc,
env,
Less_general(kind, [(ty, ty), (ty_expected, ty_expected)]),
),
);
};
};
/* Check that a type is generalizable at some level */
let generalizable = (level, ty) => {
let rec check = ty => {
let ty = repr(ty);
if (ty.level < lowest_level) {
();
} else if (ty.level <= level) {
raise(Exit);
} else {
mark_type_node(ty);
iter_type_expr(check, ty);
};
};
try(
{
check(ty);
unmark_type(ty);
true;
}
) {
| Exit =>
unmark_type(ty);
false;
};
};
/* Getting proper location of already typed expressions.
Used to avoid confusing locations on type error messages in presence of
type constraints.
For example:
(* Before patch *)
# let x : string = (5 : int);;
^
(* After patch *)
# let x : string = (5 : int);;
^^^^^^^^^
*/
let proper_exp_loc = exp => {
let rec aux =
fun
| [] => exp.exp_loc
/*| ((Texp_constraint _ | Texp_coerce _), loc, _) :: _ -> loc*/
| [_, ...rest] => aux(rest);
aux(exp.exp_extra);
};
/* To find reasonable names for let-bound and lambda-bound idents */
let rec name_pattern = default =>
fun
| [] => Ident.create(default)
| [{mb_pat: p, _}, ...rem] =>
switch (p.pat_desc) {
| TPatVar(id, _) => id
/*| Tpat_alias(_, id, _) -> id*/
| _ => name_pattern(default, rem)
};
/* Typing of expressions */
let unify_exp = (env, exp, expected_ty) => {
let loc = proper_exp_loc(exp);
/*Printf.eprintf "Typed (pre-unification): %s\n"
(Sexplib.Sexp.to_string_hum (Typedtree.sexp_of_expression exp));*/
unify_exp_types(loc, env, exp.exp_type, expected_ty);
};
let rec type_exp = (~in_function=?, ~recarg=?, env, sexp) =>
/* We now delegate everything to type_expect */
type_expect(~in_function?, ~recarg?, env, sexp, mk_expected(newvar()))
/* Typing of an expression with an expected type.
This provide better error messages, and allows controlled
propagation of return type information.
In the principal case, [type_expected'] may be at generic_level.
*/
and type_expect =
(~in_function=?, ~recarg=?, env, sexp, ty_expected_explained) => {
/*let previous_saved_types = Cmt_format.get_saved_types () in*/
let exp =
type_expect_(~in_function?, ~recarg?, env, sexp, ty_expected_explained);
/*Cmt_format.set_saved_types
(Cmt_format.Partial_expression exp :: previous_saved_types);*/
exp;
}
and with_explanation = (explanation, f) =>
switch (explanation) {
| None => f()
| Some(explanation) =>
try(f()) {
| Error(loc', env', Expr_type_clash(trace', None))
when !loc'.Location.loc_ghost =>
raise(Error(loc', env', Expr_type_clash(trace', Some(explanation))))
}
}
and type_expect_ =
(~in_function=?, ~recarg=Rejected, env, sexp, ty_expected_explained) => {
let {ty: ty_expected, explanation} = ty_expected_explained;
let loc = sexp.pexp_loc;
let core_loc = sexp.pexp_core_loc;
let attributes = Typetexp.type_attributes(sexp.pexp_attributes);
/* Record the expression type before unifying it with the expected type */
let type_expect = type_expect(~in_function?);
let type_exp = type_exp(~in_function?);
let with_explanation = with_explanation(explanation);
let rue = exp => {
with_explanation(() =>
unify_exp(env, re(exp), instance(env, ty_expected))
);
exp;
};
switch (sexp.pexp_desc) {
| PExpId(id) =>
let (path, desc) = Typetexp.find_value(env, id.loc, id.txt);
rue({
exp_desc:
switch (desc.val_kind) {
| TValUnbound(ValUnboundGhostRecursive) =>
raise(
Error(loc, env, Unbound_value_missing_rec(id.txt, desc.val_loc)),
)
| _ => TExpIdent(path, id, desc)
},
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: instance(env, desc.val_type),
exp_env: env,
});
| PExpConstant(cst) =>
let cst = constant_or_raise(env, loc, cst);
rue({
exp_desc: TExpConstant(cst),
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: type_constant(cst),
exp_env: env,
});
| PExpTuple(es) =>
let subtypes = List.map(_ => newgenvar(), es);
let to_unify = newgenty(TTyTuple(subtypes));
with_explanation(() => unify_exp_types(loc, env, to_unify, ty_expected));
let expl =
List.map2(
(body, ty) => type_expect(env, body, mk_expected(ty)),
es,
subtypes,
);
re({
exp_desc: TExpTuple(expl),
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: newty(TTyTuple(List.map(e => e.exp_type, expl))),
exp_env: env,
});
| PExpList(es) =>
let convert_list = (~loc, ~core_loc, ~attributes=?, a) => {
open Ast_helper;
let empty =
Expression.tuple_construct(~loc, ~core_loc, ident_empty, []);
let list =
switch (List.rev(a)) {
| [] => empty
| [base, ...rest] =>
let base =
switch (base) {
| ListItem(expr) =>
Expression.tuple_construct(
~loc,
~core_loc,
~attributes?,
ident_cons,
[expr, empty],
)
| ListSpread(expr, _) => expr
};
List.fold_left(
(acc, expr) => {
switch (expr) {
| ListItem(expr) =>
Expression.tuple_construct(
~loc,
~core_loc,
~attributes?,
ident_cons,
[expr, acc],
)
| ListSpread(_, loc) =>
raise(
SyntaxError(
loc,
"A list spread can only appear at the end of a list.",
),
)
}
},
base,
rest,
);
};
{...list, pexp_loc: loc};
};
type_expect(
env,
convert_list(~loc, ~core_loc, ~attributes=sexp.pexp_attributes, es),
ty_expected_explained,
);
| PExpArray(es) =>
let ty = newgenvar();
let to_unify = Builtin_types.type_array(ty);
with_explanation(() => unify_exp_types(loc, env, to_unify, ty_expected));
let expl =
List.map(sarg => type_expect(env, sarg, mk_expected(ty)), es);
re({
exp_desc: TExpArray(expl),
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: instance(env, ty_expected),
exp_env: env,
});
| PExpArrayGet(sarrexp, sidx) =>
let array_type = newvar(~name="a", ());
let arrexp =
type_expect(
env,
sarrexp,
mk_expected(
~explanation=Assign_not_array,
Builtin_types.type_array(array_type),
),
);
let idx =
type_expect(
env,
sidx,
mk_expected(
~explanation=Assign_not_array_index,
Builtin_types.type_number,
),
);
rue({
exp_desc: TExpArrayGet(arrexp, idx),
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: instance(env, array_type),
exp_env: env,
});
| PExpArraySet(sarrexp, sidx, se) =>
let array_type = newvar(~name="a", ());
let arrexp =
type_expect(
env,
sarrexp,
mk_expected(
~explanation=Assign_not_array,
Builtin_types.type_array(array_type),
),
);
let idx =
type_expect(
env,
sidx,
mk_expected(
~explanation=Assign_not_array_index,
Builtin_types.type_number,
),
);
let e = type_expect(env, se, mk_expected(array_type));
rue({
exp_desc: TExpArraySet(arrexp, idx, e),
exp_loc: loc,
exp_extra: [],
exp_attributes: attributes,
exp_type: Builtin_types.type_void,
exp_env: env,
});
| PExpRecord(b, es) =>
let opt_exp = Option.map(type_exp(env), b);
let (ty_record, opath) = {
let get_path = ty =>
try({
let (p0, p, _) = extract_concrete_record(env, ty);
let principal = repr(ty).level == generic_level;
Some((p0, p, principal));
}) {
| Not_found => None
};
let expected_opath = get_path(ty_expected);
let opt_exp_opath = Option.bind(opt_exp, exp => get_path(exp.exp_type));
switch (expected_opath, opt_exp_opath) {
| (None, None) => (newvar(), None)
| (Some(_), None)
| (Some((_, _, true)), Some(_)) => (ty_expected, expected_opath)
| (None | Some((_, _, false)), Some((_, p', _))) =>
let decl = Env.find_type(p', env);
begin_def();
let ty = newconstr(p', instance_list(env, decl.type_params));
end_def();
generalize_structure(ty);
(ty, opt_exp_opath);
};