forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctype.ml
5620 lines (5178 loc) · 197 KB
/
ctype.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 and Jerome Vouillon, 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 GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Operations on core types *)
open Misc
open Asttypes
open Types
open Btype
open Errortrace
open Local_store
(*
Type manipulation after type inference
======================================
If one wants to manipulate a type after type inference (for
instance, during code generation or in the debugger), one must
first make sure that the type levels are correct, using the
function [correct_levels]. Then, this type can be correctly
manipulated by [apply], [expand_head] and [moregeneral].
*)
(*
General notes
=============
- As much sharing as possible should be kept : it makes types
smaller and better abbreviated.
When necessary, some sharing can be lost. Types will still be
printed correctly (+++ TO DO...), and abbreviations defined by a
class do not depend on sharing thanks to constrained
abbreviations. (Of course, even if some sharing is lost, typing
will still be correct.)
- All nodes of a type have a level : that way, one knows whether a
node need to be duplicated or not when instantiating a type.
- Levels of a type are decreasing (generic level being considered
as greatest).
- The level of a type constructor is superior to the binding
time of its path.
- Recursive types without limitation should be handled (even if
there is still an occur check). This avoid treating specially the
case for objects, for instance. Furthermore, the occur check
policy can then be easily changed.
*)
(**** Errors ****)
(* There are two classes of errortrace-related exceptions: *traces* and
*errors*. The former, whose names end with [_trace], contain
[Errortrace.trace]s, representing traces that are currently being built; they
are local to this file. All the internal functions that implement
unification, type equality, and moregen raise trace exceptions. Once we are
done, in the top level functions such as [unify], [equal], and [moregen], we
catch the trace exceptions and transform them into the analogous error
exception. This indicates that we are done building the trace, and expect
the error to flow out of unification, type equality, or moregen into
surrounding code (with some few exceptions when these top-level functions are
used as building blocks elsewhere.) Only the error exceptions are exposed in
[ctype.mli]; the trace exceptions are an implementation detail. Any trace
exception that escapes from a function in this file is a bug. *)
exception Unify_trace of unification trace
exception Equality_trace of comparison trace
exception Moregen_trace of comparison trace
exception Unify of unification_error
exception Equality of equality_error
exception Moregen of moregen_error
exception Subtype of Subtype.error
exception Escape of type_expr escape
(* For local use: throw the appropriate exception. Can be passed into local
functions as a parameter *)
type _ trace_exn =
| Unify : unification trace_exn
| Moregen : comparison trace_exn
| Equality : comparison trace_exn
let raise_trace_for
(type variant)
(tr_exn : variant trace_exn)
(tr : variant trace) : 'a =
match tr_exn with
| Unify -> raise (Unify_trace tr)
| Equality -> raise (Equality_trace tr)
| Moregen -> raise (Moregen_trace tr)
(* Uses of this function are a bit suspicious, as we usually want to maintain
trace information; sometimes it makes sense, however, since we're maintaining
the trace at an outer exception handler. *)
let raise_unexplained_for tr_exn =
raise_trace_for tr_exn []
let raise_for tr_exn e =
raise_trace_for tr_exn [e]
(* Thrown from [moregen_kind] *)
exception Public_method_to_private_method
let escape kind = {kind; context = None}
let escape_exn kind = Escape (escape kind)
let scope_escape_exn ty = escape_exn (Equation ty)
let raise_escape_exn kind = raise (escape_exn kind)
let raise_scope_escape_exn ty = raise (scope_escape_exn ty)
exception Tags of label * label
let () =
let open Format_doc in
Location.register_error_of_exn
(function
| Tags (l, l') ->
let pp_tag ppf s = fprintf ppf "`%s" s in
let inline_tag = Misc.Style.as_inline_code pp_tag in
Some
Location.
(errorf ~loc:(in_file !input_name)
"In this program,@ variant constructors@ %a and %a@ \
have the same hash value.@ Change one of them."
inline_tag l inline_tag l'
)
| _ -> None
)
exception Cannot_expand
exception Cannot_apply
exception Cannot_subst
exception Cannot_unify_universal_variables
exception Matches_failure of Env.t * unification_error
exception Incompatible
(**** Type level management ****)
let current_level = s_ref 0
let nongen_level = s_ref 0
let global_level = s_ref 0
let saved_level = s_ref []
let get_current_level () = !current_level
let init_def level = current_level := level; nongen_level := level
let begin_def () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
incr current_level; nongen_level := !current_level
let begin_class_def () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
incr current_level
let raise_nongen_level () =
saved_level := (!current_level, !nongen_level) :: !saved_level;
nongen_level := !current_level
let end_def () =
let (cl, nl) = List.hd !saved_level in
saved_level := List.tl !saved_level;
current_level := cl; nongen_level := nl
let create_scope () =
init_def (!current_level + 1);
!current_level
let wrap_end_def f = Misc.try_finally f ~always:end_def
let with_local_level ?post f =
begin_def ();
let result = wrap_end_def f in
Option.iter (fun g -> g result) post;
result
let with_local_level_if cond f ~post =
if cond then with_local_level f ~post else f ()
let with_local_level_iter f ~post =
begin_def ();
let result, l = wrap_end_def f in
List.iter post l;
result
let with_local_level_iter_if cond f ~post =
if cond then with_local_level_iter f ~post else fst (f ())
let with_local_level_if_principal f ~post =
with_local_level_if !Clflags.principal f ~post
let with_local_level_iter_if_principal f ~post =
with_local_level_iter_if !Clflags.principal f ~post
let with_level ~level f =
begin_def (); init_def level;
let result = wrap_end_def f in
result
let with_level_if cond ~level f =
if cond then with_level ~level f else f ()
let with_local_level_for_class ?post f =
begin_class_def ();
let result = wrap_end_def f in
Option.iter (fun g -> g result) post;
result
let with_raised_nongen_level f =
raise_nongen_level ();
wrap_end_def f
let reset_global_level () =
global_level := !current_level
let increase_global_level () =
let gl = !global_level in
global_level := !current_level;
gl
let restore_global_level gl =
global_level := gl
(**** Control tracing of GADT instances *)
let trace_gadt_instances = ref false
let check_trace_gadt_instances env =
not !trace_gadt_instances && Env.has_local_constraints env &&
(trace_gadt_instances := true; cleanup_abbrev (); true)
let reset_trace_gadt_instances b =
if b then trace_gadt_instances := false
let wrap_trace_gadt_instances env f x =
let b = check_trace_gadt_instances env in
let y = f x in
reset_trace_gadt_instances b;
y
(**** Abbreviations without parameters ****)
(* Shall reset after generalizing *)
let simple_abbrevs = ref Mnil
let proper_abbrevs tl abbrev =
if tl <> [] || !trace_gadt_instances || !Clflags.principal
then abbrev
else simple_abbrevs
(**** Some type creators ****)
(* Re-export generic type creators *)
let newty desc = newty2 ~level:!current_level desc
let new_scoped_ty scope desc = newty3 ~level:!current_level ~scope desc
let newvar ?name () = newty2 ~level:!current_level (Tvar name)
let newvar2 ?name level = newty2 ~level:level (Tvar name)
let new_global_var ?name () = newty2 ~level:!global_level (Tvar name)
let newstub ~scope = newty3 ~level:!current_level ~scope (Tvar None)
let newobj fields = newty (Tobject (fields, ref None))
let newconstr path tyl = newty (Tconstr (path, tyl, ref Mnil))
let none = newty (Ttuple []) (* Clearly ill-formed type *)
(**** information for [Typecore.unify_pat_*] ****)
module Pattern_env : sig
type t = private
{ mutable env : Env.t;
equations_scope : int;
allow_recursive_equations : bool; }
val make: Env.t -> equations_scope:int -> allow_recursive_equations:bool -> t
val copy: ?equations_scope:int -> t -> t
val set_env: t -> Env.t -> unit
end = struct
type t =
{ mutable env : Env.t;
equations_scope : int;
allow_recursive_equations : bool; }
let make env ~equations_scope ~allow_recursive_equations =
{ env;
equations_scope;
allow_recursive_equations; }
let copy ?equations_scope penv =
let equations_scope =
match equations_scope with None -> penv.equations_scope | Some s -> s in
{ penv with equations_scope }
let set_env penv env = penv.env <- env
end
(**** unification mode ****)
type equations_generation =
| Forbidden
| Allowed of { equated_types : TypePairs.t }
type unification_environment =
| Expression of
{ env : Env.t;
in_subst : bool; }
(* normal unification mode *)
| Pattern of
{ penv : Pattern_env.t;
equations_generation : equations_generation;
assume_injective : bool;
unify_eq_set : TypePairs.t; }
(* GADT constraint unification mode:
only used for type indices of GADT constructors
during pattern matching.
This allows adding local constraints. *)
let get_env = function
| Expression {env} -> env
| Pattern {penv} -> penv.env
let set_env uenv env =
match uenv with
| Expression _ -> invalid_arg "Ctype.set_env"
| Pattern {penv} -> Pattern_env.set_env penv env
let in_pattern_mode = function
| Expression _ -> false
| Pattern _ -> true
let get_equations_scope = function
| Expression _ -> invalid_arg "Ctype.get_equations_scope"
| Pattern r -> r.penv.equations_scope
let order_type_pair t1 t2 =
if get_id t1 <= get_id t2 then (t1, t2) else (t2, t1)
let add_type_equality uenv t1 t2 =
match uenv with
| Expression _ -> invalid_arg "Ctype.add_type_equality"
| Pattern r -> TypePairs.add r.unify_eq_set (order_type_pair t1 t2)
let unify_eq uenv t1 t2 =
eq_type t1 t2 ||
match uenv with
| Expression _ -> false
| Pattern r -> TypePairs.mem r.unify_eq_set (order_type_pair t1 t2)
(* unification during type constructor expansion:
This mode disables the propagation of the level and scope of
the row variable to the whole type during the unification.
(see unify_{row, fields} and PR #11771) *)
let in_subst_mode = function
| Expression {in_subst} -> in_subst
| Pattern _ -> false
let can_generate_equations = function
| Expression _ | Pattern { equations_generation = Forbidden } -> false
| Pattern { equations_generation = Allowed _ } -> true
(* Can only be called when generate_equations is true *)
let record_equation uenv t1 t2 =
match uenv with
| Expression _ | Pattern { equations_generation = Forbidden } ->
invalid_arg "Ctype.record_equation"
| Pattern { equations_generation = Allowed { equated_types } } ->
TypePairs.add equated_types (t1, t2)
let can_assume_injective = function
| Expression _ -> false
| Pattern { assume_injective } -> assume_injective
let in_counterexample uenv =
match uenv with
| Expression _ -> false
| Pattern { penv } -> penv.allow_recursive_equations
let allow_recursive_equations uenv =
!Clflags.recursive_types || in_counterexample uenv
(* Though without_* functions can be in a direct style,
CPS clarifies the structure of the code better. *)
let without_assume_injective uenv f =
match uenv with
| Expression _ as uenv -> f uenv
| Pattern r -> f (Pattern { r with assume_injective = false })
let without_generating_equations uenv f =
match uenv with
| Expression _ as uenv -> f uenv
| Pattern r -> f (Pattern { r with equations_generation = Forbidden })
(*** Checks for type definitions ***)
let rec in_current_module = function
| Path.Pident _ -> true
| Path.Pdot _ | Path.Papply _ -> false
| Path.Pextra_ty (p, _) -> in_current_module p
let in_pervasives p =
in_current_module p &&
try ignore (Env.find_type p Env.initial); true
with Not_found -> false
let is_datatype decl=
match decl.type_kind with
Type_record _ | Type_variant _ | Type_open -> true
| Type_abstract _ -> false
(**********************************************)
(* Miscellaneous operations on object types *)
(**********************************************)
(* Note:
We need to maintain some invariants:
* cty_self must be a Tobject
* ...
*)
(**** Object field manipulation. ****)
let object_fields ty =
match get_desc ty with
Tobject (fields, _) -> fields
| _ -> assert false
let flatten_fields ty =
let rec flatten l ty =
match get_desc ty with
Tfield(s, k, ty1, ty2) ->
flatten ((s, k, ty1)::l) ty2
| _ ->
(l, ty)
in
let (l, r) = flatten [] ty in
(List.sort (fun (n, _, _) (n', _, _) -> compare n n') l, r)
let build_fields level =
List.fold_right
(fun (s, k, ty1) ty2 -> newty2 ~level (Tfield(s, k, ty1, ty2)))
let associate_fields fields1 fields2 =
let rec associate p s s' =
function
(l, []) ->
(List.rev p, (List.rev s) @ l, List.rev s')
| ([], l') ->
(List.rev p, List.rev s, (List.rev s') @ l')
| ((n, k, t)::r, (n', k', t')::r') when n = n' ->
associate ((n, k, t, k', t')::p) s s' (r, r')
| ((n, k, t)::r, ((n', _k', _t')::_ as l')) when n < n' ->
associate p ((n, k, t)::s) s' (r, l')
| (((_n, _k, _t)::_ as l), (n', k', t')::r') (* when n > n' *) ->
associate p s ((n', k', t')::s') (l, r')
in
associate [] [] [] (fields1, fields2)
(**** Check whether an object is open ****)
(* +++ The abbreviation should eventually be expanded *)
let rec object_row ty =
match get_desc ty with
Tobject (t, _) -> object_row t
| Tfield(_, _, _, t) -> object_row t
| _ -> ty
let opened_object ty =
match get_desc (object_row ty) with
| Tvar _ | Tunivar _ | Tconstr _ -> true
| _ -> false
let concrete_object ty =
match get_desc (object_row ty) with
| Tvar _ -> false
| _ -> true
(**** Row variable of an object type ****)
let rec fields_row_variable ty =
match get_desc ty with
| Tfield (_, _, _, ty) -> fields_row_variable ty
| Tvar _ -> ty
| _ -> assert false
(**** Object name manipulation ****)
(* +++ Bientot obsolete *)
let set_object_name id params ty =
match get_desc ty with
| Tobject (fi, nm) ->
let rv = fields_row_variable fi in
set_name nm (Some (Path.Pident id, rv::params))
| Tconstr (_, _, _) -> ()
| _ -> fatal_error "Ctype.set_object_name"
let remove_object_name ty =
match get_desc ty with
Tobject (_, nm) -> set_name nm None
| Tconstr (_, _, _) -> ()
| _ -> fatal_error "Ctype.remove_object_name"
(*******************************************)
(* Miscellaneous operations on row types *)
(*******************************************)
let sort_row_fields = List.sort (fun (p,_) (q,_) -> compare p q)
let rec merge_rf r1 r2 pairs fi1 fi2 =
match fi1, fi2 with
(l1,f1 as p1)::fi1', (l2,f2 as p2)::fi2' ->
if l1 = l2 then merge_rf r1 r2 ((l1,f1,f2)::pairs) fi1' fi2' else
if l1 < l2 then merge_rf (p1::r1) r2 pairs fi1' fi2 else
merge_rf r1 (p2::r2) pairs fi1 fi2'
| [], _ -> (List.rev r1, List.rev_append r2 fi2, pairs)
| _, [] -> (List.rev_append r1 fi1, List.rev r2, pairs)
let merge_row_fields fi1 fi2 =
match fi1, fi2 with
[], _ | _, [] -> (fi1, fi2, [])
| [p1], _ when not (List.mem_assoc (fst p1) fi2) -> (fi1, fi2, [])
| _, [p2] when not (List.mem_assoc (fst p2) fi1) -> (fi1, fi2, [])
| _ -> merge_rf [] [] [] (sort_row_fields fi1) (sort_row_fields fi2)
let rec filter_row_fields erase = function
[] -> []
| (_l,f as p)::fi ->
let fi = filter_row_fields erase fi in
match row_field_repr f with
Rabsent -> fi
| Reither(_,_,false) when erase ->
link_row_field_ext ~inside:f rf_absent; fi
| _ -> p :: fi
(**************************************)
(* Check genericity of type schemes *)
(**************************************)
type variable_kind = Row_variable | Type_variable
exception Non_closed of type_expr * variable_kind
(* [free_vars] collects the variables of the input type expression. It
is used for several different things in the type-checker, with the
following bells and whistles:
- If [env] is Some typing environment, types in the environment
are expanded to check whether the apparently-free variable would vanish
during expansion.
- We collect both type variables and row variables, paired with
a [variable_kind] to distinguish them.
- We do not count "virtual" free variables -- free variables stored in
the abbreviation of an object type that has been expanded (we store
the abbreviations for use when displaying the type).
[free_vars] returns a [(variable * bool) list], while
[free_variables] below drops the type/row information
and only returns a [variable list].
*)
let free_vars ?env mark ty =
let rec fv ~kind acc ty =
if not (try_mark_node mark ty) then acc
else match get_desc ty, env with
| Tvar _, _ ->
(ty, kind) :: acc
| Tconstr (path, tl, _), Some env ->
let acc =
match Env.find_type_expansion path env with
| exception Not_found -> acc
| (_, body, _) ->
if get_level body = generic_level then acc
else (ty, kind) :: acc
in
List.fold_left (fv ~kind:Type_variable) acc tl
| Tobject (ty, _), _ ->
(* ignoring the second parameter of [Tobject] amounts to not
counting "virtual free variables". *)
fv ~kind:Row_variable acc ty
| Tfield (_, _, ty1, ty2), _ ->
let acc = fv ~kind:Type_variable acc ty1 in
fv ~kind:Row_variable acc ty2
| Tvariant row, _ ->
let acc = fold_row (fv ~kind:Type_variable) acc row in
if static_row row then acc
else fv ~kind:Row_variable acc (row_more row)
| _ ->
fold_type_expr (fv ~kind) acc ty
in fv ~kind:Type_variable [] ty
let free_variables ?env ty =
with_type_mark (fun mark -> List.map fst (free_vars ?env mark ty))
let closed_type mark ty =
match free_vars mark ty with
[] -> ()
| (v, real) :: _ -> raise (Non_closed (v, real))
let closed_parameterized_type params ty =
with_type_mark begin fun mark ->
List.iter (mark_type mark) params;
try closed_type mark ty; true with Non_closed _ -> false
end
let closed_type_decl decl =
with_type_mark begin fun mark -> try
List.iter (mark_type mark) decl.type_params;
begin match decl.type_kind with
Type_abstract _ ->
()
| Type_variant (v, _rep) ->
List.iter
(fun {cd_args; cd_res; _} ->
match cd_res with
| Some _ -> ()
| None ->
match cd_args with
| Cstr_tuple l -> List.iter (closed_type mark) l
| Cstr_record l ->
List.iter (fun l -> closed_type mark l.ld_type) l
)
v
| Type_record(r, _rep) ->
List.iter (fun l -> closed_type mark l.ld_type) r
| Type_open -> ()
end;
begin match decl.type_manifest with
None -> ()
| Some ty -> closed_type mark ty
end;
None
with Non_closed (ty, _) ->
Some ty
end
let closed_extension_constructor ext =
with_type_mark begin fun mark -> try
List.iter (mark_type mark) ext.ext_type_params;
begin match ext.ext_ret_type with
| Some _ -> ()
| None -> iter_type_expr_cstr_args (closed_type mark) ext.ext_args
end;
None
with Non_closed (ty, _) ->
Some ty
end
type closed_class_failure = {
free_variable: type_expr * variable_kind;
meth: string;
meth_ty: type_expr;
}
exception CCFailure of closed_class_failure
let closed_class params sign =
with_type_mark begin fun mark ->
List.iter (mark_type mark) params;
ignore (try_mark_node mark sign.csig_self_row);
try
Meths.iter
(fun lab (priv, _, ty) ->
if priv = Mpublic then begin
try closed_type mark ty with Non_closed (ty0, variable_kind) ->
raise (CCFailure {
free_variable = (ty0, variable_kind);
meth = lab;
meth_ty = ty;
})
end)
sign.csig_meths;
None
with CCFailure reason ->
Some reason
end
(**********************)
(* Type duplication *)
(**********************)
(* Duplicate a type, preserving only type variables *)
let duplicate_type ty =
Subst.type_expr Subst.identity ty
(* Same, for class types *)
let duplicate_class_type ty =
Subst.class_type Subst.identity ty
(*****************************)
(* Type level manipulation *)
(*****************************)
(*
It would be a bit more efficient to remove abbreviation expansions
rather than generalizing them: these expansions will usually not be
used anymore. However, this is not possible in the general case, as
[expand_abbrev] (via [subst]) requires these expansions to be
preserved. Does it worth duplicating this code ?
*)
let rec generalize ty =
let level = get_level ty in
if (level > !current_level) && (level <> generic_level) then begin
set_level ty generic_level;
(* recur into abbrev for the speed *)
begin match get_desc ty with
Tconstr (_, _, abbrev) ->
iter_abbrev generalize !abbrev
| _ -> ()
end;
iter_type_expr generalize ty
end
let generalize ty =
simple_abbrevs := Mnil;
generalize ty
(* Generalize the structure and lower the variables *)
let rec generalize_structure ty =
let level = get_level ty in
if level <> generic_level then begin
if is_Tvar ty && level > !current_level then
set_level ty !current_level
else if level > !current_level then begin
begin match get_desc ty with
Tconstr (_, _, abbrev) ->
abbrev := Mnil
| _ -> ()
end;
set_level ty generic_level;
iter_type_expr generalize_structure ty
end
end
let generalize_structure ty =
simple_abbrevs := Mnil;
generalize_structure ty
(* Generalize the spine of a function, if the level >= !current_level *)
let rec generalize_spine ty =
let level = get_level ty in
if level < !current_level || level = generic_level then () else
match get_desc ty with
Tarrow (_, ty1, ty2, _) ->
set_level ty generic_level;
generalize_spine ty1;
generalize_spine ty2;
| Tpoly (ty', _) ->
set_level ty generic_level;
generalize_spine ty'
| Ttuple tyl ->
set_level ty generic_level;
List.iter generalize_spine tyl
| Tpackage (_, fl) ->
set_level ty generic_level;
List.iter (fun (_n, ty) -> generalize_spine ty) fl
| Tconstr (_, tyl, memo) ->
set_level ty generic_level;
memo := Mnil;
List.iter generalize_spine tyl
| _ -> ()
let forward_try_expand_safe = (* Forward declaration *)
ref (fun _env _ty -> assert false)
(*
Lower the levels of a type (assume [level] is not
[generic_level]).
*)
let rec normalize_package_path env p =
let t =
try (Env.find_modtype p env).mtd_type
with Not_found -> None
in
match t with
| Some (Mty_ident p) -> normalize_package_path env p
| Some (Mty_signature _ | Mty_functor _ | Mty_alias _) | None ->
match p with
Path.Pdot (p1, s) ->
(* For module aliases *)
let p1' = Env.normalize_module_path None env p1 in
if Path.same p1 p1' then p else
normalize_package_path env (Path.Pdot (p1', s))
| _ -> p
let rec check_scope_escape mark env level ty =
let orig_level = get_level ty in
if try_mark_node mark ty then begin
if level < get_scope ty then
raise_scope_escape_exn ty;
begin match get_desc ty with
| Tconstr (p, _, _) when level < Path.scope p ->
begin match !forward_try_expand_safe env ty with
| ty' ->
check_scope_escape mark env level ty'
| exception Cannot_expand ->
raise_escape_exn (Constructor p)
end
| Tpackage (p, fl) when level < Path.scope p ->
let p' = normalize_package_path env p in
if Path.same p p' then raise_escape_exn (Module_type p);
check_scope_escape mark env level
(newty2 ~level:orig_level (Tpackage (p', fl)))
| _ ->
iter_type_expr (check_scope_escape mark env level) ty
end;
end
let check_scope_escape env level ty =
with_type_mark begin fun mark -> try
check_scope_escape mark env level ty
with Escape e ->
raise (Escape { e with context = Some ty })
end
let rec update_scope scope ty =
if get_scope ty < scope then begin
if get_level ty < scope then raise_scope_escape_exn ty;
set_scope ty scope;
(* Only recurse in principal mode as this is not necessary for soundness *)
if !Clflags.principal then iter_type_expr (update_scope scope) ty
end
let update_scope_for tr_exn scope ty =
try
update_scope scope ty
with Escape e -> raise_for tr_exn (Escape e)
(* Note: the level of a type constructor must be greater than its binding
time. That way, a type constructor cannot escape the scope of its
definition, as would be the case in
let x = ref []
module M = struct type t let _ = (x : t list ref) end
(without this constraint, the type system would actually be unsound.)
*)
let rec update_level env level expand ty =
if get_level ty > level then begin
if level < get_scope ty then raise_scope_escape_exn ty;
match get_desc ty with
Tconstr(p, _tl, _abbrev) when level < Path.scope p ->
(* Try first to replace an abbreviation by its expansion. *)
begin try
let ty' = !forward_try_expand_safe env ty in
link_type ty ty';
update_level env level expand ty'
with Cannot_expand ->
raise_escape_exn (Constructor p)
end
| Tconstr(p, (_ :: _ as tl), _) ->
let variance =
try (Env.find_type p env).type_variance
with Not_found -> List.map (fun _ -> Variance.unknown) tl in
let needs_expand =
expand ||
List.exists2
(fun var ty -> var = Variance.null && get_level ty > level)
variance tl
in
begin try
if not needs_expand then raise Cannot_expand;
let ty' = !forward_try_expand_safe env ty in
link_type ty ty';
update_level env level expand ty'
with Cannot_expand ->
set_level ty level;
iter_type_expr (update_level env level expand) ty
end
| Tpackage (p, fl) when level < Path.scope p ->
let p' = normalize_package_path env p in
if Path.same p p' then raise_escape_exn (Module_type p);
set_type_desc ty (Tpackage (p', fl));
update_level env level expand ty
| Tobject (_, ({contents=Some(p, _tl)} as nm))
when level < Path.scope p ->
set_name nm None;
update_level env level expand ty
| Tvariant row ->
begin match row_name row with
| Some (p, _tl) when level < Path.scope p ->
set_type_desc ty (Tvariant (set_row_name row None))
| _ -> ()
end;
set_level ty level;
iter_type_expr (update_level env level expand) ty
| Tfield(lab, _, ty1, _)
when lab = dummy_method && level < get_scope ty1 ->
raise_escape_exn Self
| _ ->
set_level ty level;
(* XXX what about abbreviations in Tconstr ? *)
iter_type_expr (update_level env level expand) ty
end
(* First try without expanding, then expand everything,
to avoid combinatorial blow-up *)
let update_level env level ty =
if get_level ty > level then begin
let snap = snapshot () in
try
update_level env level false ty
with Escape _ ->
backtrack snap;
update_level env level true ty
end
let update_level_for tr_exn env level ty =
try
update_level env level ty
with Escape e -> raise_for tr_exn (Escape e)
(* Lower level of type variables inside contravariant branches *)
let rec lower_contravariant env var_level visited contra ty =
let must_visit =
get_level ty > var_level &&
match Hashtbl.find visited (get_id ty) with
| done_contra -> contra && not done_contra
| exception Not_found -> true
in
if must_visit then begin
Hashtbl.add visited (get_id ty) contra;
let lower_rec = lower_contravariant env var_level visited in
match get_desc ty with
Tvar _ -> if contra then set_level ty var_level
| Tconstr (_, [], _) -> ()
| Tconstr (path, tyl, _abbrev) ->
let variance, maybe_expand =
try
let typ = Env.find_type path env in
typ.type_variance,
type_kind_is_abstract typ
with Not_found ->
(* See testsuite/tests/typing-missing-cmi-2 for an example *)
List.map (fun _ -> Variance.unknown) tyl,
false
in
if List.for_all ((=) Variance.null) variance then () else
let not_expanded () =
List.iter2
(fun v t ->
if v = Variance.null then () else
if Variance.(mem May_weak v)
then lower_rec true t
else lower_rec contra t)
variance tyl in
if maybe_expand then (* we expand cautiously to avoid missing cmis *)
match !forward_try_expand_safe env ty with
| ty -> lower_rec contra ty
| exception Cannot_expand -> not_expanded ()
else not_expanded ()
| Tpackage (_, fl) ->
List.iter (fun (_n, ty) -> lower_rec true ty) fl
| Tarrow (_, t1, t2, _) ->
lower_rec true t1;
lower_rec contra t2
| _ ->
iter_type_expr (lower_rec contra) ty
end
let lower_variables_only env level ty =
simple_abbrevs := Mnil;
lower_contravariant env level (Hashtbl.create 7) true ty
let lower_contravariant env ty =
simple_abbrevs := Mnil;
lower_contravariant env !nongen_level (Hashtbl.create 7) false ty
let rec generalize_class_type' gen =
function
Cty_constr (_, params, cty) ->
List.iter gen params;
generalize_class_type' gen cty
| Cty_signature csig ->
gen csig.csig_self;
gen csig.csig_self_row;
Vars.iter (fun _ (_, _, ty) -> gen ty) csig.csig_vars;
Meths.iter (fun _ (_, _, ty) -> gen ty) csig.csig_meths
| Cty_arrow (_, ty, cty) ->
gen ty;
generalize_class_type' gen cty
let generalize_class_type cty =
generalize_class_type' generalize cty
let generalize_class_type_structure cty =
generalize_class_type' generalize_structure cty
(* Correct the levels of type [ty]. *)
let correct_levels ty =
duplicate_type ty
(* Only generalize the type ty0 in ty *)
let limited_generalize ty0 ty =
let graph = TypeHash.create 17 in
let roots = ref [] in
let rec inverse pty ty =
match TypeHash.find_opt graph ty with
| Some parents -> parents := pty @ !parents
| None ->
let level = get_level ty in
if level > !current_level then begin
TypeHash.add graph ty (ref pty);