forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
typecore.ml
2433 lines (2328 loc) · 86.9 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
(***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
(* 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. *)
(* *)
(***********************************************************************)
(* $Id$ *)
(* Typechecking for the core language *)
open Misc
open Asttypes
open Parsetree
open Types
open Typedtree
open Btype
open Ctype
type error =
Unbound_value of Longident.t
| Unbound_constructor of Longident.t
| Unbound_label of Longident.t
| Unbound_module of Longident.t
| Unbound_functor of Longident.t
| 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
| 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 Longident.t
| Label_missing of string list
| Label_not_mutable of Longident.t
| Incomplete_format of string
| Bad_conversion of string * int * char
| Undefined_method of type_expr * string
| Undefined_inherited_method of string
| Unbound_class of Longident.t
| 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 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
exception Error of Location.t * 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 Typeclass.class_structure *)
let type_object =
ref (fun env s -> assert false :
Env.t -> Location.t -> Parsetree.class_structure ->
class_structure * 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 =
Stypes.record (Stypes.Ti_expr node);
node
;;
let rp node =
Stypes.record (Stypes.Ti_pat node);
node
;;
(* Typing of constants *)
let type_constant = function
Const_int _ -> instance Predef.type_int
| Const_char _ -> instance Predef.type_char
| Const_string _ -> instance Predef.type_string
| Const_float _ -> instance Predef.type_float
| Const_int32 _ -> instance Predef.type_int32
| Const_int64 _ -> instance Predef.type_int64
| Const_nativeint _ -> instance 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 option_none ty loc =
let cnone = Env.lookup_constructor (Longident.Lident "None") Env.initial in
{ exp_desc = Texp_construct(cnone, []);
exp_type = ty; exp_loc = loc; exp_env = Env.initial }
let option_some texp =
let csome = Env.lookup_constructor (Longident.Lident "Some") Env.initial in
{ exp_desc = Texp_construct(csome, [texp]); exp_loc = texp.exp_loc;
exp_type = type_option texp.exp_type; exp_env = 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 rec extract_label_names sexp env ty =
let ty = repr ty in
match ty.desc with
| Tconstr (path, _, _) ->
let td = Env.find_type path env in
begin match td.type_kind with
| Type_record (fields, _) ->
List.map (fun (name, _, _) -> name) fields
| Type_abstract when td.type_manifest <> None ->
extract_label_names sexp env (expand_head env ty)
| _ -> assert false
end
| _ ->
assert false
(* Typing of patterns *)
(* Creating new conjunctive types is not allowed when typing patterns *)
let unify_pat env pat expected_ty =
try
unify env pat.pat_type expected_ty
with
Unify trace ->
raise(Error(pat.pat_loc, Pattern_type_clash(trace)))
| Tags(l1,l2) ->
raise(Typetexp.Error(pat.pat_loc, Typetexp.Variant_tags (l1, l2)))
(* 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.row_fixed ->
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 * Location.t) list)
let pattern_force = ref ([] : (unit -> unit) list)
let pattern_scope = ref (None : Annot.ident option);;
let reset_pattern scope =
pattern_variables := [];
pattern_force := [];
pattern_scope := scope;
;;
let enter_variable loc name ty =
if List.exists (fun (id, _, _) -> Ident.name id = name) !pattern_variables
then raise(Error(loc, Multiply_bound_variable name));
let id = Ident.create name in
pattern_variables := (id, ty, loc) :: !pattern_variables;
begin match !pattern_scope with
| None -> ()
| Some s -> Stypes.record (Stypes.An_ident (loc, name, s));
end;
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)::rem1, (x2,t2,l2)::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, Pattern_type_clash(trace)))
end ;
(x2,x1)::unify_vars rem1 rem2
end
| [],[] -> []
| (x,_,_)::_, [] -> raise (Error (loc, Orpat_vars x))
| [],(x,_,_)::_ -> raise (Error (loc, Orpat_vars x))
| (x,_,_)::_, (y,_,_)::_ ->
let min_var =
if Ident.name x < Ident.name y then x
else y in
raise (Error (loc, 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) ->
if cstr.cstr_private = Private 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 = fst(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 =
try Env.lookup_type lid env
with Not_found ->
raise(Typetexp.Error(loc, Typetexp.Unbound_type_constructor 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, 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})
:: 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})
pats
in
match pats with
[] -> raise(Error(loc, Not_a_variant_type lid))
| pat :: pats ->
let r =
List.fold_left
(fun pat pat0 -> {pat_desc=Tpat_or(pat0,pat,Some row0);
pat_loc=gloc; pat_env=env; pat_type=ty})
pat pats in
rp { r with pat_loc = loc }
let rec find_record_qual = function
| [] -> None
| (Longident.Ldot (modname, _), _) :: _ -> Some modname
| _ :: rest -> find_record_qual rest
let type_label_a_list type_lid_a lid_a_list =
match find_record_qual lid_a_list with
| None -> List.map type_lid_a lid_a_list
| Some modname ->
List.map
(function
| (Longident.Lident id), sarg ->
type_lid_a (Longident.Ldot (modname, id), sarg)
| lid_a -> type_lid_a lid_a)
lid_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, Label_multiply_defined
(Longident.Lident 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
(* Typing of patterns *)
let rec type_pat env sp =
let loc = sp.ppat_loc in
match sp.ppat_desc with
Ppat_any ->
rp {
pat_desc = Tpat_any;
pat_loc = loc;
pat_type = newvar();
pat_env = env }
| Ppat_var name ->
let ty = newvar() in
let id = enter_variable loc name ty in
rp {
pat_desc = Tpat_var id;
pat_loc = loc;
pat_type = ty;
pat_env = env }
| Ppat_constraint({ppat_desc=Ppat_var name; ppat_loc=loc},
({ptyp_desc=Ptyp_poly _} as sty)) ->
(* explicitly polymorphic type *)
let ty, force = Typetexp.transl_simple_type_delayed env sty in
pattern_force := force :: !pattern_force;
begin match ty.desc with
| Tpoly (body, tyl) ->
begin_def ();
let _, ty' = instance_poly false tyl body in
end_def ();
generalize ty';
let id = enter_variable loc name ty' in
rp { pat_desc = Tpat_var id;
pat_loc = loc;
pat_type = ty;
pat_env = env }
| _ -> assert false
end
| Ppat_alias(sq, name) ->
let q = type_pat env sq in
begin_def ();
let ty_var = build_as_type env q in
end_def ();
generalize ty_var;
let id = enter_variable loc name ty_var in
rp {
pat_desc = Tpat_alias(q, id);
pat_loc = loc;
pat_type = q.pat_type;
pat_env = env }
| Ppat_constant cst ->
rp {
pat_desc = Tpat_constant cst;
pat_loc = loc;
pat_type = type_constant cst;
pat_env = env }
| Ppat_tuple spl ->
let pl = List.map (type_pat env) spl in
rp {
pat_desc = Tpat_tuple pl;
pat_loc = loc;
pat_type = newty (Ttuple(List.map (fun p -> p.pat_type) pl));
pat_env = env }
| Ppat_construct(lid, sarg, explicit_arity) ->
let constr =
try
Env.lookup_constructor lid env
with Not_found ->
raise(Error(loc, Unbound_constructor lid)) in
let sargs =
match sarg with
None -> []
| Some {ppat_desc = Ppat_tuple spl} when explicit_arity -> spl
| Some {ppat_desc = Ppat_tuple spl} when constr.cstr_arity > 1 -> spl
| Some({ppat_desc = Ppat_any} as sp) when constr.cstr_arity <> 1 ->
replicate_list sp constr.cstr_arity
| Some sp -> [sp] in
if List.length sargs <> constr.cstr_arity then
raise(Error(loc, Constructor_arity_mismatch(lid,
constr.cstr_arity, List.length sargs)));
let args = List.map (type_pat env) sargs in
let (ty_args, ty_res) = instance_constructor constr in
List.iter2 (unify_pat env) args ty_args;
rp {
pat_desc = Tpat_construct(constr, args);
pat_loc = loc;
pat_type = ty_res;
pat_env = env }
| Ppat_variant(l, sarg) ->
let arg = may_map (type_pat env) sarg in
let arg_type = match arg with None -> [] | Some arg -> [arg.pat_type] in
let row = { row_fields =
[l, Reither(arg = None, arg_type, true, ref None)];
row_bound = ();
row_closed = false;
row_more = newvar ();
row_fixed = false;
row_name = None } in
rp {
pat_desc = Tpat_variant(l, arg, ref {row with row_more = newvar()});
pat_loc = loc;
pat_type = newty (Tvariant row);
pat_env = env }
| Ppat_record(lid_sp_list, closed) ->
let ty = newvar() in
let type_label_pat (lid, sarg) =
let label =
try
Env.lookup_label lid env
with Not_found ->
raise(Error(loc, Unbound_label lid)) in
begin_def ();
let (vars, ty_arg, ty_res) = instance_label false label in
if vars = [] then end_def ();
begin try
unify env ty_res ty
with Unify trace ->
raise(Error(loc, Label_mismatch(lid, trace)))
end;
let arg = type_pat env sarg in
unify_pat env arg ty_arg;
if vars <> [] then begin
end_def ();
generalize ty_arg;
List.iter generalize vars;
let instantiated tv =
let tv = expand_head env tv in
tv.desc <> Tvar || tv.level <> generic_level in
if List.exists instantiated vars then
raise (Error(loc, Polymorphic_label lid))
end;
(label, arg)
in
let lbl_pat_list = type_label_a_list type_label_pat lid_sp_list in
check_recordpat_labels loc lbl_pat_list closed;
rp {
pat_desc = Tpat_record lbl_pat_list;
pat_loc = loc;
pat_type = ty;
pat_env = env }
| Ppat_array spl ->
let pl = List.map (type_pat env) spl in
let ty_elt = newvar() in
List.iter (fun p -> unify_pat env p ty_elt) pl;
rp {
pat_desc = Tpat_array pl;
pat_loc = loc;
pat_type = instance (Predef.type_array ty_elt);
pat_env = env }
| Ppat_or(sp1, sp2) ->
let initial_pattern_variables = !pattern_variables in
let p1 = type_pat env sp1 in
let p1_variables = !pattern_variables in
pattern_variables := initial_pattern_variables ;
let p2 = type_pat env sp2 in
let p2_variables = !pattern_variables in
unify_pat env p2 p1.pat_type;
let alpha_env =
enter_orpat_variables loc env p1_variables p2_variables in
pattern_variables := p1_variables ;
rp {
pat_desc = Tpat_or(p1, alpha_pat alpha_env p2, None);
pat_loc = loc;
pat_type = p1.pat_type;
pat_env = env }
| Ppat_lazy sp1 ->
let p1 = type_pat env sp1 in
rp {
pat_desc = Tpat_lazy p1;
pat_loc = loc;
pat_type = instance (Predef.type_lazy_t p1.pat_type);
pat_env = env }
| Ppat_constraint(sp, sty) ->
let p = type_pat env sp in
let ty, force = Typetexp.transl_simple_type_delayed env sty in
unify_pat env p ty;
pattern_force := force :: !pattern_force;
p
| Ppat_type lid ->
build_or_pat env loc lid
let get_ref r =
let v = !r in r := []; v
let add_pattern_variables env =
let pv = get_ref pattern_variables in
List.fold_right
(fun (id, ty, loc) env ->
let e1 = Env.add_value id {val_type = ty; val_kind = Val_reg} env in
Env.add_annot id (Annot.Iref_internal loc) e1;
)
pv env
let type_pattern env spat scope =
reset_pattern scope;
let pat = type_pat env spat in
let new_env = add_pattern_variables env in
(pat, new_env, get_ref pattern_force)
let type_pattern_list env spatl scope =
reset_pattern scope;
let patl = List.map (type_pat env) spatl in
let new_env = add_pattern_variables env in
(patl, new_env, get_ref pattern_force)
let type_class_arg_pattern cl_num val_env met_env l spat =
reset_pattern None;
let pat = type_pat val_env spat in
if has_variants pat then begin
Parmatch.pressure_variants val_env [pat];
iter_pattern finalize_variant pat
end;
List.iter (fun f -> f()) (get_ref pattern_force);
if is_optional l then unify_pat val_env pat (type_option (newvar ()));
let (pv, met_env) =
List.fold_right
(fun (id, ty, _loc) (pv, env) ->
let id' = Ident.create (Ident.name id) in
((id', id, ty)::pv,
Env.add_value id' {val_type = ty;
val_kind = Val_ivar (Immutable, cl_num)}
env))
!pattern_variables ([], met_env)
in
let val_env = add_pattern_variables val_env in
(pat, pv, val_env, met_env)
let mkpat d = { ppat_desc = d; ppat_loc = Location.none }
let type_self_pattern cl_num privty val_env met_env par_env spat =
let spat =
mkpat (Ppat_alias (mkpat(Ppat_alias (spat, "selfpat-*")),
"selfpat-" ^ cl_num))
in
reset_pattern None;
let pat = type_pat val_env spat in
List.iter (fun f -> f()) (get_ref pattern_force);
let meths = ref Meths.empty in
let vars = ref Vars.empty in
let pv = !pattern_variables in
pattern_variables := [];
let (val_env, met_env, par_env) =
List.fold_right
(fun (id, ty, _loc) (val_env, met_env, par_env) ->
(Env.add_value id {val_type = ty; val_kind = Val_unbound} val_env,
Env.add_value id {val_type = ty;
val_kind = Val_self (meths, vars, cl_num, privty)}
met_env,
Env.add_value id {val_type = ty; val_kind = Val_unbound} par_env))
pv (val_env, met_env, par_env)
in
(pat, meths, vars, val_env, met_env, par_env)
let delayed_checks = ref []
let reset_delayed_checks () = delayed_checks := []
let add_delayed_check f = delayed_checks := f :: !delayed_checks
let force_delayed_checks () =
(* checks may change type levels *)
let snap = Btype.snapshot () in
List.iter (fun f -> f ()) (List.rev !delayed_checks);
reset_delayed_checks ();
Btype.backtrack snap
(* Generalization criterion for expressions *)
let rec is_nonexpansive exp =
match exp.exp_desc with
Texp_ident(_,_) -> true
| Texp_constant _ -> true
| Texp_let(rec_flag, pat_exp_list, body) ->
List.for_all (fun (pat, exp) -> is_nonexpansive exp) pat_exp_list &&
is_nonexpansive body
| Texp_function _ -> true
| Texp_apply(e, (None,_)::el) ->
is_nonexpansive e && List.for_all is_nonexpansive_opt (List.map fst el)
| Texp_tuple el ->
List.for_all is_nonexpansive el
| Texp_construct(_, el) ->
List.for_all is_nonexpansive el
| Texp_variant(_, arg) -> is_nonexpansive_opt arg
| Texp_record(lbl_exp_list, opt_init_exp) ->
List.for_all
(fun (lbl, exp) -> lbl.lbl_mut = Immutable && is_nonexpansive exp)
lbl_exp_list
&& is_nonexpansive_opt opt_init_exp
| Texp_field(exp, lbl) -> is_nonexpansive exp
| Texp_array [] -> true
| Texp_ifthenelse(cond, ifso, ifnot) ->
is_nonexpansive ifso && is_nonexpansive_opt ifnot
| Texp_sequence (e1, e2) -> is_nonexpansive e2 (* PR#4354 *)
| Texp_new (_, cl_decl) when Ctype.class_type_arity cl_decl.cty_type > 0 ->
true
(* Note: nonexpansive only means no _observable_ side effects *)
| Texp_lazy e -> is_nonexpansive e
| Texp_object ({cl_field=fields}, {cty_vars=vars}, _) ->
let count = ref 0 in
List.for_all
(function
Cf_meth _ -> true
| Cf_val (_,_,e,_) -> incr count; is_nonexpansive_opt e
| Cf_init e -> is_nonexpansive e
| Cf_inher _ | Cf_let _ -> false)
fields &&
Vars.fold (fun _ (mut,_,_) b -> decr count; b && mut = Immutable)
vars true &&
!count = 0
| _ -> false
and is_nonexpansive_opt = function
None -> true
| Some e -> is_nonexpansive e
(* Typing of printf formats.
(Handling of * modifiers contributed by Thorsten Ohl.) *)
external string_to_format :
string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
external format_to_string :
('a, 'b, 'c, 'd, 'e, 'f) format6 -> string = "%identity"
let type_format loc fmt =
let ty_arrow gty ty = newty (Tarrow ("", instance gty, ty, Cok)) in
let bad_conversion fmt i c =
raise (Error (loc, Bad_conversion (fmt, i, c))) in
let incomplete_format fmt =
raise (Error (loc, Incomplete_format fmt)) in
let range_closing_index fmt i =
let len = String.length fmt in
let find_closing j =
if j >= len then incomplete_format fmt else
try String.index_from fmt j ']' with
| Not_found -> incomplete_format fmt in
let skip_pos j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| ']' -> find_closing (j + 1)
| c -> find_closing j in
let rec skip_neg j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '^' -> skip_pos (j + 1)
| c -> skip_pos j in
find_closing (skip_neg (i + 1)) in
let rec type_in_format fmt =
let len = String.length fmt in
let ty_input = newvar ()
and ty_result = newvar ()
and ty_aresult = newvar ()
and ty_uresult = newvar () in
let meta = ref 0 in
let rec scan_format i =
if i >= len then
if !meta = 0
then ty_uresult, ty_result
else incomplete_format fmt else
match fmt.[i] with
| '%' -> scan_opts i (i + 1)
| _ -> scan_format (i + 1)
and scan_opts i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '_' -> scan_rest true i (j + 1)
| _ -> scan_rest false i j
and scan_rest skip i j =
let rec scan_flags i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '#' | '0' | '-' | ' ' | '+' -> scan_flags i (j + 1)
| _ -> scan_width i j
and scan_width i j = scan_width_or_prec_value scan_precision i j
and scan_decimal_string scan i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '0' .. '9' -> scan_decimal_string scan i (j + 1)
| _ -> scan i j
and scan_width_or_prec_value scan i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '*' ->
let ty_uresult, ty_result = scan i (j + 1) in
ty_uresult, ty_arrow Predef.type_int ty_result
| '-' | '+' -> scan_decimal_string scan i (j + 1)
| _ -> scan_decimal_string scan i j
and scan_precision i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '.' -> scan_width_or_prec_value scan_conversion i (j + 1)
| _ -> scan_conversion i j
and conversion j ty_arg =
let ty_uresult, ty_result = scan_format (j + 1) in
ty_uresult,
if skip then ty_result else ty_arrow ty_arg ty_result
and scan_conversion i j =
if j >= len then incomplete_format fmt else
match fmt.[j] with
| '%' | '!' -> scan_format (j + 1)
| 's' | 'S' -> conversion j Predef.type_string
| '[' ->
let j = range_closing_index fmt j in
conversion j Predef.type_string
| 'c' | 'C' -> conversion j Predef.type_char
| 'd' | 'i' | 'o' | 'x' | 'X' | 'u' | 'N' ->
conversion j Predef.type_int
| 'f' | 'e' | 'E' | 'g' | 'G' | 'F' -> conversion j Predef.type_float
| 'B' | 'b' -> conversion j Predef.type_bool
| 'a' ->
let ty_arg = newvar () in
let ty_a = ty_arrow ty_input (ty_arrow ty_arg ty_aresult) in
let ty_uresult, ty_result = conversion j ty_arg in
ty_uresult, ty_arrow ty_a ty_result
| 'r' ->
let ty_arg = newvar () in
let ty_r = ty_arrow ty_input ty_arg in
let ty_uresult, ty_result = conversion j ty_arg in
ty_arrow ty_r ty_uresult, ty_result
| 't' -> conversion j (ty_arrow ty_input ty_aresult)
| 'l' | 'n' | 'L' as c ->
let j = j + 1 in
if j >= len then conversion (j - 1) Predef.type_int else begin
match fmt.[j] with
| 'd' | 'i' | 'o' | 'x' | 'X' | 'u' ->
let ty_arg =
match c with
| 'l' -> Predef.type_int32
| 'n' -> Predef.type_nativeint
| _ -> Predef.type_int64 in
conversion j ty_arg
| c -> conversion (j - 1) Predef.type_int
end
| '{' | '(' as c ->
let j = j + 1 in
if j >= len then incomplete_format fmt else
let sj =
Printf.CamlinternalPr.Tformat.sub_format
(fun fmt -> incomplete_format (format_to_string fmt))
(fun fmt -> bad_conversion (format_to_string fmt))
c (string_to_format fmt) j in
let sfmt = String.sub fmt j (sj - 2 - j) in
let ty_sfmt = type_in_format sfmt in
begin match c with
| '{' -> conversion (sj - 1) ty_sfmt
| _ -> incr meta; conversion (j - 1) ty_sfmt end
| ')' when !meta > 0 -> decr meta; scan_format (j + 1)
| c -> bad_conversion fmt i c in
scan_flags i j in
let ty_ureader, ty_args = scan_format 0 in
newty
(Tconstr
(Predef.path_format6,
[ty_args; ty_input; ty_aresult; ty_ureader; ty_uresult; ty_result],
ref Mnil)) in
type_in_format fmt
(* Approximate the type of an expression, for better recursion *)
let rec approx_type env sty =
match sty.ptyp_desc with
Ptyp_arrow (p, _, sty) ->
let ty1 = if is_optional p then type_option (newvar ()) else newvar () in
newty (Tarrow (p, ty1, approx_type env sty, Cok))
| Ptyp_tuple args ->
newty (Ttuple (List.map (approx_type env) args))
| Ptyp_constr (lid, ctl) ->
begin try
let (path, decl) = Env.lookup_type lid env in
if List.length ctl <> decl.type_arity then raise Not_found;
let tyl = List.map (approx_type env) ctl in
newconstr path tyl
with Not_found -> newvar ()
end
| Ptyp_poly (_, sty) ->
approx_type env sty
| _ -> newvar ()
let rec type_approx env sexp =
match sexp.pexp_desc with
Pexp_let (_, _, e) -> type_approx env e
| Pexp_function (p,_,(_,e)::_) when is_optional p ->
newty (Tarrow(p, type_option (newvar ()), type_approx env e, Cok))
| Pexp_function (p,_,(_,e)::_) ->
newty (Tarrow(p, newvar (), type_approx env e, Cok))
| Pexp_match (_, (_,e)::_) -> type_approx env e
| Pexp_try (e, _) -> type_approx env e
| Pexp_tuple l -> newty (Ttuple(List.map (type_approx env) l))
| Pexp_ifthenelse (_,e,_) -> type_approx env e
| Pexp_sequence (_,e) -> type_approx env e
| Pexp_constraint (e, sty1, sty2) ->
let approx_ty_opt = function
| None -> newvar ()
| Some sty -> approx_type env sty
in
let ty = type_approx env e
and ty1 = approx_ty_opt sty1
and ty2 = approx_ty_opt sty2 in
begin try unify env ty ty1 with Unify trace ->
raise(Error(sexp.pexp_loc, Expr_type_clash trace))
end;
if sty2 = None then ty1 else ty2
| _ -> newvar ()
(* List labels in a function type, and whether return type is a variable *)
let rec list_labels_aux env visited ls ty_fun =
let ty = expand_head env ty_fun in
if List.memq ty visited then
List.rev ls, false
else match ty.desc with
Tarrow (l, _, ty_res, _) ->
list_labels_aux env (ty::visited) (l::ls) ty_res
| _ ->
List.rev ls, ty.desc = Tvar
let list_labels env ty = list_labels_aux env [] [] ty
(* Check that all univars are safe in a type *)
let check_univars env expans kind exp ty_expected vars =
if expans && not (is_nonexpansive exp) then
generalize_expansive env exp.exp_type;
(* need to expand twice? cf. Ctype.unify2 *)
let vars = List.map (expand_head env) vars in
let vars = List.map (expand_head env) vars in
let vars' =
List.filter
(fun t ->
let t = repr t in
generalize t;
if t.desc = Tvar && t.level = generic_level then
(log_type t; t.desc <- Tunivar; true)
else false)
vars in
if List.length vars = List.length vars' then () else
let ty = newgenty (Tpoly(repr exp.exp_type, vars'))
and ty_expected = repr ty_expected in
raise (Error (exp.exp_loc,
Less_general(kind, [ty, ty; ty_expected, ty_expected])))
(* Check that a type is not a function *)
let check_application_result env statement exp =
let loc = exp.exp_loc in
match (expand_head env exp.exp_type).desc with
| Tarrow _ ->
Location.prerr_warning exp.exp_loc Warnings.Partial_application
| Tvar -> ()
| Tconstr (p, _, _) when Path.same p Predef.path_unit -> ()
| _ ->
if statement then
Location.prerr_warning loc Warnings.Statement_type
(* Check that a type is generalizable at some level *)
let generalizable level ty =
let rec check ty =
let ty = repr ty in
if ty.level < lowest_level then () else
if ty.level <= level then raise Exit else
(mark_type_node ty; iter_type_expr check ty)
in
try check ty; unmark_type ty; true
with Exit -> unmark_type ty; false
(* Hack to allow coercion of self. Will clean-up later. *)
let self_coercion = ref ([] : (Path.t * Location.t list ref) list)
(* Helpers for packaged modules. *)
let create_package_type loc env (p, l) =
let s = !Typetexp.transl_modtype_longident loc env p in
newty (Tpackage (s,
List.map fst l,
List.map (Typetexp.transl_simple_type env false) (List.map snd l)))
(* Typing of expressions *)
let unify_exp env exp expected_ty =
(* Format.eprintf "@[%a@ %a@]@." Printtyp.raw_type_expr exp.exp_type
Printtyp.raw_type_expr expected_ty; *)
try
unify env exp.exp_type expected_ty
with
Unify trace ->
raise(Error(exp.exp_loc, Expr_type_clash(trace)))
| Tags(l1,l2) ->
raise(Typetexp.Error(exp.exp_loc, Typetexp.Variant_tags (l1, l2)))
let rec narrow_unbound_lid_error env make_error lid =
let module_is_bound mlid =
ignore (Env.lookup_module mlid env) in
match lid with
| Longident.Lident _ -> make_error lid
| Longident.Ldot (mlid, _) ->