forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typecore.ml
3988 lines (3824 loc) · 149 KB
/
typecore.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
(***********************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. All rights reserved. This file is distributed *)
(* under the terms of the Q Public License version 1.0. *)
(* *)
(***********************************************************************)
(* Typechecking for the core language *)
open Misc
open Asttypes
open Parsetree
open Types
open Typedtree
open Btype
open Ctype
type error =
Polymorphic_label of Longident.t
| Constructor_arity_mismatch of Longident.t * int * int
| Label_mismatch of Longident.t * (type_expr * type_expr) list
| Pattern_type_clash of (type_expr * type_expr) list
| Or_pattern_type_clash of Ident.t * (type_expr * type_expr) list
| Multiply_bound_variable of string
| Orpat_vars of Ident.t
| Expr_type_clash of (type_expr * type_expr) list
| Apply_non_function of type_expr
| Apply_wrong_label of label * type_expr
| Label_multiply_defined of string
| Label_missing of Ident.t list
| Label_not_mutable of Longident.t
| Wrong_name of string * type_expr * string * Path.t * Longident.t
| Name_type_mismatch of
string * Longident.t * (Path.t * Path.t) * (Path.t * Path.t) list
| Invalid_format of string
| Undefined_method of type_expr * string
| Undefined_inherited_method of string
| Virtual_class of Longident.t
| Private_type of type_expr
| Private_label of Longident.t * type_expr
| Unbound_instance_variable of string
| Instance_variable_not_mutable of bool * string
| Not_subtype of (type_expr * type_expr) list * (type_expr * type_expr) list
| Outside_class
| Value_multiply_overridden of string
| Coercion_failure of
type_expr * type_expr * (type_expr * type_expr) list * bool
| Too_many_arguments of bool * type_expr
| Abstract_wrong_label of label * type_expr
| Scoping_let_module of string * type_expr
| Masked_instance_variable of Longident.t
| Not_a_variant_type of Longident.t
| Incoherent_label_order
| Less_general of string * (type_expr * type_expr) list
| Modules_not_allowed
| Cannot_infer_signature
| Not_a_packed_module of type_expr
| Recursive_local_constraint of (type_expr * type_expr) list
| Unexpected_existential
| Unqualified_gadt_pattern of Path.t * string
| Invalid_interval
| Invalid_for_loop_index
| No_value_clauses
| Exception_pattern_below_toplevel
exception Error of Location.t * Env.t * error
exception Error_forward of Location.error
(* Forward declaration, to be filled in by Typemod.type_module *)
let type_module =
ref ((fun env md -> assert false) :
Env.t -> Parsetree.module_expr -> Typedtree.module_expr)
(* Forward declaration, to be filled in by Typemod.type_open *)
let type_open =
ref (fun _ -> assert false)
(* Forward declaration, to be filled in by Typemod.type_package *)
let type_package =
ref (fun _ -> assert false)
(* Forward declaration, to be filled in by Typeclass.class_structure *)
let type_object =
ref (fun env s -> assert false :
Env.t -> Location.t -> Parsetree.class_structure ->
Typedtree.class_structure * Types.class_signature * string list)
(*
Saving and outputting type information.
We keep these function names short, because they have to be
called each time we create a record of type [Typedtree.expression]
or [Typedtree.pattern] that will end up in the typed AST.
*)
let re node =
Cmt_format.add_saved_type (Cmt_format.Partial_expression node);
Stypes.record (Stypes.Ti_expr node);
node
;;
let rp node =
Cmt_format.add_saved_type (Cmt_format.Partial_pattern node);
Stypes.record (Stypes.Ti_pat node);
node
;;
let fst3 (x, _, _) = x
let snd3 (_,x,_) = x
let case lhs rhs =
{c_lhs = lhs; c_guard = None; c_rhs = rhs}
(* Upper approximation of free identifiers on the parse tree *)
let iter_expression f e =
let rec expr e =
f e;
match e.pexp_desc with
| Pexp_extension _ (* we don't iterate under extension point *)
| Pexp_ident _
| Pexp_new _
| Pexp_constant _ -> ()
| Pexp_function pel -> List.iter case pel
| Pexp_fun (_, eo, _, e) -> may expr eo; expr e
| Pexp_apply (e, lel) -> expr e; List.iter (fun (_, e) -> expr e) lel
| Pexp_let (_, pel, e) -> expr e; List.iter binding pel
| Pexp_match (e, pel)
| Pexp_try (e, pel) -> expr e; List.iter case pel
| Pexp_array el
| Pexp_tuple el -> List.iter expr el
| Pexp_construct (_, eo)
| Pexp_variant (_, eo) -> may expr eo
| Pexp_record (iel, eo) ->
may expr eo; List.iter (fun (_, e) -> expr e) iel
| Pexp_open (_, _, e)
| Pexp_newtype (_, e)
| Pexp_poly (e, _)
| Pexp_lazy e
| Pexp_assert e
| Pexp_setinstvar (_, e)
| Pexp_send (e, _)
| Pexp_constraint (e, _)
| Pexp_coerce (e, _, _)
| Pexp_field (e, _) -> expr e
| Pexp_while (e1, e2)
| Pexp_sequence (e1, e2)
| Pexp_setfield (e1, _, e2) -> expr e1; expr e2
| Pexp_ifthenelse (e1, e2, eo) -> expr e1; expr e2; may expr eo
| Pexp_for (_, e1, e2, _, e3) -> expr e1; expr e2; expr e3
| Pexp_override sel -> List.iter (fun (_, e) -> expr e) sel
| Pexp_letmodule (_, me, e) -> expr e; module_expr me
| Pexp_object { pcstr_fields = fs } -> List.iter class_field fs
| Pexp_pack me -> module_expr me
and case {pc_lhs = _; pc_guard; pc_rhs} =
may expr pc_guard;
expr pc_rhs
and binding x =
expr x.pvb_expr
and module_expr me =
match me.pmod_desc with
| Pmod_extension _
| Pmod_ident _ -> ()
| Pmod_structure str -> List.iter structure_item str
| Pmod_constraint (me, _)
| Pmod_functor (_, _, me) -> module_expr me
| Pmod_apply (me1, me2) -> module_expr me1; module_expr me2
| Pmod_unpack e -> expr e
and structure_item str =
match str.pstr_desc with
| Pstr_eval (e, _) -> expr e
| Pstr_value (_, pel) -> List.iter binding pel
| Pstr_primitive _
| Pstr_type _
| Pstr_typext _
| Pstr_exception _
| Pstr_modtype _
| Pstr_open _
| Pstr_class_type _
| Pstr_attribute _
| Pstr_extension _ -> ()
| Pstr_include {pincl_mod = me}
| Pstr_module {pmb_expr = me} -> module_expr me
| Pstr_recmodule l -> List.iter (fun x -> module_expr x.pmb_expr) l
| Pstr_class cdl -> List.iter (fun c -> class_expr c.pci_expr) cdl
and class_expr ce =
match ce.pcl_desc with
| Pcl_constr _ -> ()
| Pcl_structure { pcstr_fields = fs } -> List.iter class_field fs
| Pcl_fun (_, eo, _, ce) -> may expr eo; class_expr ce
| Pcl_apply (ce, lel) ->
class_expr ce; List.iter (fun (_, e) -> expr e) lel
| Pcl_let (_, pel, ce) ->
List.iter binding pel; class_expr ce
| Pcl_constraint (ce, _) -> class_expr ce
| Pcl_extension _ -> ()
and class_field cf =
match cf.pcf_desc with
| Pcf_inherit (_, ce, _) -> class_expr ce
| Pcf_val (_, _, Cfk_virtual _)
| Pcf_method (_, _, Cfk_virtual _ ) | Pcf_constraint _ -> ()
| Pcf_val (_, _, Cfk_concrete (_, e))
| Pcf_method (_, _, Cfk_concrete (_, e)) -> expr e
| Pcf_initializer e -> expr e
| Pcf_attribute _ | Pcf_extension _ -> ()
in
expr e
let all_idents_cases el =
let idents = Hashtbl.create 8 in
let f = function
| {pexp_desc=Pexp_ident { txt = Longident.Lident id; _ }; _} ->
Hashtbl.replace idents id ()
| _ -> ()
in
List.iter
(fun cp ->
may (iter_expression f) cp.pc_guard;
iter_expression f cp.pc_rhs
)
el;
Hashtbl.fold (fun x () rest -> x :: rest) idents []
(* Typing of constants *)
let type_constant = function
Const_int _ -> instance_def Predef.type_int
| Const_char _ -> instance_def Predef.type_char
| Const_string _ -> instance_def Predef.type_string
| Const_float _ -> instance_def Predef.type_float
| Const_int32 _ -> instance_def Predef.type_int32
| Const_int64 _ -> instance_def Predef.type_int64
| Const_nativeint _ -> instance_def Predef.type_nativeint
(* Specific version of type_option, using newty rather than newgenty *)
let type_option ty =
newty (Tconstr(Predef.path_option,[ty], ref Mnil))
let mkexp exp_desc exp_type exp_loc exp_env =
{ exp_desc; exp_type; exp_loc; exp_env; exp_extra = []; exp_attributes = [] }
let option_none ty loc =
let lid = Longident.Lident "None"
and env = Env.initial_safe_string in
let cnone = Env.lookup_constructor lid env in
mkexp (Texp_construct(mknoloc lid, cnone, [])) ty loc env
let option_some texp =
let lid = Longident.Lident "Some" in
let csome = Env.lookup_constructor lid Env.initial_safe_string in
mkexp ( Texp_construct(mknoloc lid , csome, [texp]) )
(type_option texp.exp_type) texp.exp_loc texp.exp_env
let extract_option_type env ty =
match expand_head env ty with {desc = Tconstr(path, [ty], _)}
when Path.same path Predef.path_option -> ty
| _ -> assert false
let extract_concrete_record env ty =
match extract_concrete_typedecl env ty with
(p0, p, {type_kind=Type_record (fields, _)}) -> (p0, p, fields)
| _ -> raise Not_found
let extract_concrete_variant env ty =
match extract_concrete_typedecl env ty with
(p0, p, {type_kind=Type_variant cstrs}) -> (p0, p, cstrs)
| _ -> raise Not_found
let extract_label_names sexp env ty =
try
let (_, _,fields) = extract_concrete_record env ty in
List.map (fun l -> l.Types.ld_id) fields
with Not_found ->
assert false
let explicit_arity =
List.exists
(function
| ({txt="ocaml.explicit_arity"|"explicit_arity"; _}, _) -> true
| _ -> false
)
(* Typing of patterns *)
(* unification inside type_pat*)
let unify_pat_types loc env ty ty' =
try
unify env ty ty'
with
Unify trace ->
raise(Error(loc, env, Pattern_type_clash(trace)))
| Tags(l1,l2) ->
raise(Typetexp.Error(loc, env, Typetexp.Variant_tags (l1, l2)))
(* unification inside type_exp and type_expect *)
let unify_exp_types loc env ty expected_ty =
(* Format.eprintf "@[%a@ %a@]@." Printtyp.raw_type_expr exp.exp_type
Printtyp.raw_type_expr expected_ty; *)
try
unify env ty expected_ty
with
Unify trace ->
raise(Error(loc, env, Expr_type_clash(trace)))
| Tags(l1,l2) ->
raise(Typetexp.Error(loc, env, Typetexp.Variant_tags (l1, l2)))
(* level at which to create the local type declarations *)
let newtype_level = ref None
let get_newtype_level () =
match !newtype_level with
Some y -> y
| None -> assert false
let unify_pat_types_gadt loc env ty ty' =
let newtype_level =
match !newtype_level with
| None -> assert false
| Some x -> x
in
try
unify_gadt ~newtype_level env ty ty'
with
Unify trace ->
raise(Error(loc, !env, Pattern_type_clash(trace)))
| Tags(l1,l2) ->
raise(Typetexp.Error(loc, !env, Typetexp.Variant_tags (l1, l2)))
| Unification_recursive_abbrev trace ->
raise(Error(loc, !env, Recursive_local_constraint trace))
(* Creating new conjunctive types is not allowed when typing patterns *)
let unify_pat env pat expected_ty =
unify_pat_types pat.pat_loc env pat.pat_type expected_ty
(* make all Reither present in open variants *)
let finalize_variant pat =
match pat.pat_desc with
Tpat_variant(tag, opat, r) ->
let row =
match expand_head pat.pat_env pat.pat_type with
{desc = Tvariant row} -> r := row; row_repr row
| _ -> assert false
in
begin match row_field tag row with
| Rabsent -> () (* assert false *)
| Reither (true, [], _, e) when not row.row_closed ->
set_row_field e (Rpresent None)
| Reither (false, ty::tl, _, e) when not row.row_closed ->
set_row_field e (Rpresent (Some ty));
begin match opat with None -> assert false
| Some pat -> List.iter (unify_pat pat.pat_env pat) (ty::tl)
end
| Reither (c, l, true, e) when not (row_fixed row) ->
set_row_field e (Reither (c, [], false, ref None))
| _ -> ()
end;
(* Force check of well-formedness WHY? *)
(* unify_pat pat.pat_env pat
(newty(Tvariant{row_fields=[]; row_more=newvar(); row_closed=false;
row_bound=(); row_fixed=false; row_name=None})); *)
| _ -> ()
let rec iter_pattern f p =
f p;
iter_pattern_desc (iter_pattern f) p.pat_desc
let has_variants p =
try
iter_pattern (function {pat_desc=Tpat_variant _} -> raise Exit | _ -> ())
p;
false
with Exit ->
true
(* pattern environment *)
let pattern_variables = ref ([] :
(Ident.t * type_expr * string loc * Location.t * bool (* as-variable *)) list)
let pattern_force = ref ([] : (unit -> unit) list)
let pattern_scope = ref (None : Annot.ident option);;
let allow_modules = ref false
let module_variables = ref ([] : (string loc * Location.t) list)
let reset_pattern scope allow =
pattern_variables := [];
pattern_force := [];
pattern_scope := scope;
allow_modules := allow;
module_variables := [];
;;
let enter_variable ?(is_module=false) ?(is_as_variable=false) loc name ty =
if List.exists (fun (id, _, _, _, _) -> Ident.name id = name.txt)
!pattern_variables
then raise(Error(loc, Env.empty, Multiply_bound_variable name.txt));
let id = Ident.create name.txt in
pattern_variables :=
(id, ty, name, loc, is_as_variable) :: !pattern_variables;
if is_module then begin
(* Note: unpack patterns enter a variable of the same name *)
if not !allow_modules then
raise (Error (loc, Env.empty, Modules_not_allowed));
module_variables := (name, loc) :: !module_variables
end else
(* moved to genannot *)
may (fun s -> Stypes.record (Stypes.An_ident (name.loc, name.txt, s)))
!pattern_scope;
id
let sort_pattern_variables vs =
List.sort
(fun (x,_,_,_,_) (y,_,_,_,_) ->
Pervasives.compare (Ident.name x) (Ident.name y))
vs
let enter_orpat_variables loc env p1_vs p2_vs =
(* unify_vars operate on sorted lists *)
let p1_vs = sort_pattern_variables p1_vs
and p2_vs = sort_pattern_variables p2_vs in
let rec unify_vars p1_vs p2_vs = match p1_vs, p2_vs with
| (x1,t1,_,l1,a1)::rem1, (x2,t2,_,l2,a2)::rem2 when Ident.equal x1 x2 ->
if x1==x2 then
unify_vars rem1 rem2
else begin
begin try
unify env t1 t2
with
| Unify trace ->
raise(Error(loc, env, Or_pattern_type_clash(x1, trace)))
end;
(x2,x1)::unify_vars rem1 rem2
end
| [],[] -> []
| (x,_,_,_,_)::_, [] -> raise (Error (loc, env, Orpat_vars x))
| [],(x,_,_,_,_)::_ -> raise (Error (loc, env, Orpat_vars x))
| (x,_,_,_,_)::_, (y,_,_,_,_)::_ ->
let min_var =
if Ident.name x < Ident.name y then x
else y in
raise (Error (loc, env, Orpat_vars min_var)) in
unify_vars p1_vs p2_vs
let rec build_as_type env p =
match p.pat_desc with
Tpat_alias(p1,_, _) -> build_as_type env p1
| Tpat_tuple pl ->
let tyl = List.map (build_as_type env) pl in
newty (Ttuple tyl)
| Tpat_construct(_, cstr, pl) ->
let keep = cstr.cstr_private = Private || cstr.cstr_existentials <> [] in
if keep then p.pat_type else
let tyl = List.map (build_as_type env) pl in
let ty_args, ty_res = instance_constructor cstr in
List.iter2 (fun (p,ty) -> unify_pat env {p with pat_type = ty})
(List.combine pl tyl) ty_args;
ty_res
| Tpat_variant(l, p', _) ->
let ty = may_map (build_as_type env) p' in
newty (Tvariant{row_fields=[l, Rpresent ty]; row_more=newvar();
row_bound=(); row_name=None;
row_fixed=false; row_closed=false})
| Tpat_record (lpl,_) ->
let lbl = snd3 (List.hd lpl) in
if lbl.lbl_private = Private then p.pat_type else
let ty = newvar () in
let ppl = List.map (fun (_, l, p) -> l.lbl_pos, p) lpl in
let do_label lbl =
let _, ty_arg, ty_res = instance_label false lbl in
unify_pat env {p with pat_type = ty} ty_res;
let refinable =
lbl.lbl_mut = Immutable && List.mem_assoc lbl.lbl_pos ppl &&
match (repr lbl.lbl_arg).desc with Tpoly _ -> false | _ -> true in
if refinable then begin
let arg = List.assoc lbl.lbl_pos ppl in
unify_pat env {arg with pat_type = build_as_type env arg} ty_arg
end else begin
let _, ty_arg', ty_res' = instance_label false lbl in
unify env ty_arg ty_arg';
unify_pat env p ty_res'
end in
Array.iter do_label lbl.lbl_all;
ty
| Tpat_or(p1, p2, row) ->
begin match row with
None ->
let ty1 = build_as_type env p1 and ty2 = build_as_type env p2 in
unify_pat env {p2 with pat_type = ty2} ty1;
ty1
| Some row ->
let row = row_repr row in
newty (Tvariant{row with row_closed=false; row_more=newvar()})
end
| Tpat_any | Tpat_var _ | Tpat_constant _
| Tpat_array _ | Tpat_lazy _ -> p.pat_type
let build_or_pat env loc lid =
let path, decl = Typetexp.find_type env loc lid
in
let tyl = List.map (fun _ -> newvar()) decl.type_params in
let row0 =
let ty = expand_head env (newty(Tconstr(path, tyl, ref Mnil))) in
match ty.desc with
Tvariant row when static_row row -> row
| _ -> raise(Error(loc, env, Not_a_variant_type lid))
in
let pats, fields =
List.fold_left
(fun (pats,fields) (l,f) ->
match row_field_repr f with
Rpresent None ->
(l,None) :: pats,
(l, Reither(true,[], true, ref None)) :: fields
| Rpresent (Some ty) ->
(l, Some {pat_desc=Tpat_any; pat_loc=Location.none; pat_env=env;
pat_type=ty; pat_extra=[]; pat_attributes=[]})
:: pats,
(l, Reither(false, [ty], true, ref None)) :: fields
| _ -> pats, fields)
([],[]) (row_repr row0).row_fields in
let row =
{ row_fields = List.rev fields; row_more = newvar(); row_bound = ();
row_closed = false; row_fixed = false; row_name = Some (path, tyl) }
in
let ty = newty (Tvariant row) in
let gloc = {loc with Location.loc_ghost=true} in
let row' = ref {row with row_more=newvar()} in
let pats =
List.map
(fun (l,p) ->
{pat_desc=Tpat_variant(l,p,row'); pat_loc=gloc;
pat_env=env; pat_type=ty; pat_extra=[]; pat_attributes=[]})
pats
in
match pats with
[] -> raise(Error(loc, env, Not_a_variant_type lid))
| pat :: pats ->
let r =
List.fold_left
(fun pat pat0 ->
{pat_desc=Tpat_or(pat0,pat,Some row0); pat_extra=[];
pat_loc=gloc; pat_env=env; pat_type=ty; pat_attributes=[]})
pat pats in
(path, rp { r with pat_loc = loc },ty)
(* Type paths *)
let rec expand_path env p =
let decl =
try Some (Env.find_type p env) with Not_found -> None
in
match decl with
Some {type_manifest = Some ty} ->
begin match repr ty with
{desc=Tconstr(p,_,_)} -> expand_path env p
| _ -> p
(* PR#6394: recursive module may introduce incoherent manifest *)
end
| _ ->
let p' = Env.normalize_path None env p in
if Path.same p p' then p else expand_path env p'
let compare_type_path env tpath1 tpath2 =
Path.same (expand_path env tpath1) (expand_path env tpath2)
(* Records *)
module NameChoice(Name : sig
type t
val type_kind: string
val get_name: t -> string
val get_type: t -> type_expr
val get_descrs: Env.type_descriptions -> t list
val fold: (t -> 'a -> 'a) -> Longident.t option -> Env.t -> 'a -> 'a
val unbound_name_error: Env.t -> Longident.t loc -> 'a
end) = struct
open Name
let get_type_path env d =
match (get_type d).desc with
| Tconstr(p, _, _) -> p
| _ -> assert false
let spellcheck ppf env p lid =
Typetexp.spellcheck_simple ppf fold
(fun d ->
if compare_type_path env p (get_type_path env d)
then get_name d else "") env lid
let lookup_from_type env tpath lid =
let descrs = get_descrs (Env.find_type_descrs tpath env) in
Env.mark_type_used (Path.last tpath) (Env.find_type tpath env);
match lid.txt with
Longident.Lident s -> begin
try
List.find (fun nd -> get_name nd = s) descrs
with Not_found ->
raise (Error (lid.loc, env,
Wrong_name ("", newvar (), type_kind, tpath, lid.txt)))
end
| _ -> raise Not_found
let rec unique eq acc = function
[] -> List.rev acc
| x :: rem ->
if List.exists (eq x) acc then unique eq acc rem
else unique eq (x :: acc) rem
let ambiguous_types env lbl others =
let tpath = get_type_path env lbl in
let others =
List.map (fun (lbl, _) -> get_type_path env lbl) others in
let tpaths = unique (compare_type_path env) [tpath] others in
match tpaths with
[_] -> []
| _ -> List.map Printtyp.string_of_path tpaths
let disambiguate_by_type env tpath lbls =
let check_type (lbl, _) =
let lbl_tpath = get_type_path env lbl in
compare_type_path env tpath lbl_tpath
in
List.find check_type lbls
let disambiguate ?(warn=Location.prerr_warning) ?(check_lk=fun _ _ -> ())
?scope lid env opath lbls =
let scope = match scope with None -> lbls | Some l -> l in
let lbl = match opath with
None ->
begin match lbls with
[] -> unbound_name_error env lid
| (lbl, use) :: rest ->
use ();
let paths = ambiguous_types env lbl rest in
if paths <> [] then
warn lid.loc
(Warnings.Ambiguous_name ([Longident.last lid.txt],
paths, false));
lbl
end
| Some(tpath0, tpath, pr) ->
let warn_pr () =
let kind = if type_kind = "record" then "field" else "constructor" in
warn lid.loc
(Warnings.Not_principal
("this type-based " ^ kind ^ " disambiguation"))
in
try
let lbl, use = disambiguate_by_type env tpath scope in
use ();
if not pr then begin
(* Check if non-principal type is affecting result *)
match lbls with
[] -> warn_pr ()
| (lbl', use') :: rest ->
let lbl_tpath = get_type_path env lbl' in
if not (compare_type_path env tpath lbl_tpath) then warn_pr ()
else
let paths = ambiguous_types env lbl rest in
if paths <> [] then
warn lid.loc
(Warnings.Ambiguous_name ([Longident.last lid.txt],
paths, false))
end;
lbl
with Not_found -> try
let lbl = lookup_from_type env tpath lid in
check_lk tpath lbl;
let s = Printtyp.string_of_path tpath in
warn lid.loc
(Warnings.Name_out_of_scope (s, [Longident.last lid.txt], false));
if not pr then warn_pr ();
lbl
with Not_found ->
if lbls = [] then unbound_name_error env lid else
let tp = (tpath0, expand_path env tpath) in
let tpl =
List.map
(fun (lbl, _) ->
let tp0 = get_type_path env lbl in
let tp = expand_path env tp0 in
(tp0, tp))
lbls
in
raise (Error (lid.loc, env,
Name_type_mismatch (type_kind, lid.txt, tp, tpl)))
in
begin match scope with
(lab1,_)::_ when lab1 == lbl -> ()
| _ ->
Location.prerr_warning lid.loc
(Warnings.Disambiguated_name(get_name lbl))
end;
lbl
end
let wrap_disambiguate kind ty f x =
try f x with Error (loc, env, Wrong_name (_,_,tk,tp,lid)) ->
raise (Error (loc, env, Wrong_name (kind,ty,tk,tp,lid)))
module Label = NameChoice (struct
type t = label_description
let type_kind = "record"
let get_name lbl = lbl.lbl_name
let get_type lbl = lbl.lbl_res
let get_descrs = snd
let fold = Env.fold_labels
let unbound_name_error = Typetexp.unbound_label_error
end)
let disambiguate_label_by_ids keep env closed ids labels =
let check_ids (lbl, _) =
let lbls = Hashtbl.create 8 in
Array.iter (fun lbl -> Hashtbl.add lbls lbl.lbl_name ()) lbl.lbl_all;
List.for_all (Hashtbl.mem lbls) ids
and check_closed (lbl, _) =
(not closed || List.length ids = Array.length lbl.lbl_all)
in
let labels' = List.filter check_ids labels in
if keep && labels' = [] then (false, labels) else
let labels'' = List.filter check_closed labels' in
if keep && labels'' = [] then (false, labels') else (true, labels'')
(* Only issue warnings once per record constructor/pattern *)
let disambiguate_lid_a_list loc closed env opath lid_a_list =
let ids = List.map (fun (lid, _) -> Longident.last lid.txt) lid_a_list in
let w_pr = ref false and w_amb = ref []
and w_scope = ref [] and w_scope_ty = ref "" in
let warn loc msg =
let open Warnings in
match msg with
| Not_principal _ -> w_pr := true
| Ambiguous_name([s], l, _) -> w_amb := (s, l) :: !w_amb
| Name_out_of_scope(ty, [s], _) ->
w_scope := s :: !w_scope; w_scope_ty := ty
| _ -> Location.prerr_warning loc msg
in
let process_label lid =
(* Strategy for each field:
* collect all the labels in scope for that name
* if the type is known and principal, just eventually warn
if the real label was not in scope
* fail if there is no known type and no label found
* otherwise use other fields to reduce the list of candidates
* if there is no known type reduce it incrementally, so that
there is still at least one candidate (for error message)
* if the reduced list is valid, call Label.disambiguate
*)
let scope = Typetexp.find_all_labels env lid.loc lid.txt in
if opath = None && scope = [] then
Typetexp.unbound_label_error env lid;
let (ok, labels) =
match opath with
Some (_, _, true) -> (true, scope) (* disambiguate only checks scope *)
| _ -> disambiguate_label_by_ids (opath=None) env closed ids scope
in
if ok then Label.disambiguate lid env opath labels ~warn ~scope
else fst (List.hd labels) (* will fail later *)
in
let lbl_a_list =
List.map (fun (lid,a) -> lid, process_label lid, a) lid_a_list in
if !w_pr then
Location.prerr_warning loc
(Warnings.Not_principal "this type-based record disambiguation")
else begin
match List.rev !w_amb with
(_,types)::others as amb ->
let paths =
List.map (fun (_,lbl,_) -> Label.get_type_path env lbl) lbl_a_list in
let path = List.hd paths in
if List.for_all (compare_type_path env path) (List.tl paths) then
Location.prerr_warning loc
(Warnings.Ambiguous_name (List.map fst amb, types, true))
else
List.iter
(fun (s,l) -> Location.prerr_warning loc
(Warnings.Ambiguous_name ([s],l,false)))
amb
| _ -> ()
end;
if !w_scope <> [] then
Location.prerr_warning loc
(Warnings.Name_out_of_scope (!w_scope_ty, List.rev !w_scope, true));
lbl_a_list
let rec find_record_qual = function
| [] -> None
| ({ txt = Longident.Ldot (modname, _) }, _) :: _ -> Some modname
| _ :: rest -> find_record_qual rest
let type_label_a_list ?labels loc closed env type_lbl_a opath lid_a_list =
let lbl_a_list =
match lid_a_list, labels with
({txt=Longident.Lident s}, _)::_, Some labels when Hashtbl.mem labels s ->
(* Special case for rebuilt syntax trees *)
List.map
(function lid, a -> match lid.txt with
Longident.Lident s -> lid, Hashtbl.find labels s, a
| _ -> assert false)
lid_a_list
| _ ->
let lid_a_list =
match find_record_qual lid_a_list with
None -> lid_a_list
| Some modname ->
List.map
(fun (lid, a as lid_a) ->
match lid.txt with Longident.Lident s ->
{lid with txt=Longident.Ldot (modname, s)}, a
| _ -> lid_a)
lid_a_list
in
disambiguate_lid_a_list loc closed env opath lid_a_list
in
(* Invariant: records are sorted in the typed tree *)
let lbl_a_list =
List.sort
(fun (_,lbl1,_) (_,lbl2,_) -> compare lbl1.lbl_pos lbl2.lbl_pos)
lbl_a_list
in
List.map type_lbl_a lbl_a_list
;;
(* Checks over the labels mentioned in a record pattern:
no duplicate definitions (error); properly closed (warning) *)
let check_recordpat_labels loc lbl_pat_list closed =
match lbl_pat_list with
| [] -> () (* should not happen *)
| (_, label1, _) :: _ ->
let all = label1.lbl_all in
let defined = Array.make (Array.length all) false in
let check_defined (_, label, _) =
if defined.(label.lbl_pos)
then raise(Error(loc, Env.empty, Label_multiply_defined label.lbl_name))
else defined.(label.lbl_pos) <- true in
List.iter check_defined lbl_pat_list;
if closed = Closed
&& Warnings.is_active (Warnings.Non_closed_record_pattern "")
then begin
let undefined = ref [] in
for i = 0 to Array.length all - 1 do
if not defined.(i) then undefined := all.(i).lbl_name :: !undefined
done;
if !undefined <> [] then begin
let u = String.concat ", " (List.rev !undefined) in
Location.prerr_warning loc (Warnings.Non_closed_record_pattern u)
end
end
(* Constructors *)
module Constructor = NameChoice (struct
type t = constructor_description
let type_kind = "variant"
let get_name cstr = cstr.cstr_name
let get_type cstr = cstr.cstr_res
let get_descrs = fst
let fold = Env.fold_constructors
let unbound_name_error = Typetexp.unbound_constructor_error
end)
(* unification of a type with a tconstr with
freshly created arguments *)
let unify_head_only loc env ty constr =
let (_, ty_res) = instance_constructor constr in
match (repr ty_res).desc with
| Tconstr(p,args,m) ->
ty_res.desc <- Tconstr(p,List.map (fun _ -> newvar ()) args,m);
enforce_constraints env ty_res;
unify_pat_types loc env ty ty_res
| _ -> assert false
(* Typing of patterns *)
(* type_pat does not generate local constraints inside or patterns *)
type type_pat_mode =
| Normal
| Inside_or
(* type_pat propagates the expected type as well as maps for
constructors and labels.
Unification may update the typing environment. *)
let rec type_pat ~constrs ~labels ~no_existentials ~mode ~env sp expected_ty =
let type_pat ?(mode=mode) ?(env=env) =
type_pat ~constrs ~labels ~no_existentials ~mode ~env in
let loc = sp.ppat_loc in
match sp.ppat_desc with
Ppat_any ->
rp {
pat_desc = Tpat_any;
pat_loc = loc; pat_extra=[];
pat_type = expected_ty;
pat_attributes = sp.ppat_attributes;
pat_env = !env }
| Ppat_var name ->
let id = enter_variable loc name expected_ty in
rp {
pat_desc = Tpat_var (id, name);
pat_loc = loc; pat_extra=[];
pat_type = expected_ty;
pat_attributes = sp.ppat_attributes;
pat_env = !env }
| Ppat_unpack name ->
let id = enter_variable loc name expected_ty ~is_module:true in
rp {
pat_desc = Tpat_var (id, name);
pat_loc = sp.ppat_loc;
pat_extra=[Tpat_unpack, loc, sp.ppat_attributes];
pat_type = expected_ty;
pat_attributes = [];
pat_env = !env }
| Ppat_constraint({ppat_desc=Ppat_var name; ppat_loc=lloc},
({ptyp_desc=Ptyp_poly _} as sty)) ->
(* explicitly polymorphic type *)
let cty, force = Typetexp.transl_simple_type_delayed !env sty in
let ty = cty.ctyp_type in
unify_pat_types lloc !env ty expected_ty;
pattern_force := force :: !pattern_force;
begin match ty.desc with
| Tpoly (body, tyl) ->
begin_def ();
let _, ty' = instance_poly ~keep_names:true false tyl body in
end_def ();
generalize ty';
let id = enter_variable lloc name ty' in
rp {
pat_desc = Tpat_var (id, name);
pat_loc = lloc;
pat_extra = [Tpat_constraint cty, loc, sp.ppat_attributes];
pat_type = ty;
pat_attributes = [];
pat_env = !env
}
| _ -> assert false
end
| Ppat_alias(sq, name) ->
let q = type_pat sq expected_ty in
begin_def ();
let ty_var = build_as_type !env q in
end_def ();
generalize ty_var;
let id = enter_variable ~is_as_variable:true loc name ty_var in
rp {
pat_desc = Tpat_alias(q, id, name);
pat_loc = loc; pat_extra=[];
pat_type = q.pat_type;
pat_attributes = sp.ppat_attributes;
pat_env = !env }
| Ppat_constant cst ->
unify_pat_types loc !env (type_constant cst) expected_ty;
rp {
pat_desc = Tpat_constant cst;
pat_loc = loc; pat_extra=[];
pat_type = expected_ty;
pat_attributes = sp.ppat_attributes;
pat_env = !env }
| Ppat_interval (Const_char c1, Const_char c2) ->
let open Ast_helper.Pat in
let gloc = {loc with Location.loc_ghost=true} in
let rec loop c1 c2 =
if c1 = c2 then constant ~loc:gloc (Const_char c1)
else
or_ ~loc:gloc
(constant ~loc:gloc (Const_char c1))
(loop (Char.chr(Char.code c1 + 1)) c2)
in
let p = if c1 <= c2 then loop c1 c2 else loop c2 c1 in
let p = {p with ppat_loc=loc} in
type_pat p expected_ty
(* TODO: record 'extra' to remember about interval *)
| Ppat_interval _ ->
raise (Error (loc, !env, Invalid_interval))
| Ppat_tuple spl ->
let spl_ann = List.map (fun p -> (p,newvar ())) spl in
let ty = newty (Ttuple(List.map snd spl_ann)) in
unify_pat_types loc !env ty expected_ty;
let pl = List.map (fun (p,t) -> type_pat p t) spl_ann in
rp {
pat_desc = Tpat_tuple pl;
pat_loc = loc; pat_extra=[];