forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtypedecl.ml
2200 lines (2095 loc) · 79 KB
/
typedecl.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. *)
(* *)
(**************************************************************************)
(**** Typing of type definitions ****)
open Misc
open Asttypes
open Parsetree
open Primitive
open Types
open Typetexp
type native_repr_kind = Unboxed | Untagged
type error =
Repeated_parameter
| Duplicate_constructor of string
| Too_many_constructors
| Duplicate_label of string
| Recursive_abbrev of string
| Cycle_in_def of string * type_expr
| Definition_mismatch of type_expr * Includecore.type_mismatch list
| Constraint_failed of type_expr * type_expr
| Inconsistent_constraint of Env.t * (type_expr * type_expr) list
| Type_clash of Env.t * (type_expr * type_expr) list
| Parameters_differ of Path.t * type_expr * type_expr
| Null_arity_external
| Missing_native_external
| Unbound_type_var of type_expr * type_declaration
| Cannot_extend_private_type of Path.t
| Not_extensible_type of Path.t
| Extension_mismatch of Path.t * Includecore.type_mismatch list
| Rebind_wrong_type of Longident.t * Env.t * (type_expr * type_expr) list
| Rebind_mismatch of Longident.t * Path.t * Path.t
| Rebind_private of Longident.t
| Bad_variance of int * (bool * bool * bool) * (bool * bool * bool)
| Unavailable_type_constructor of Path.t
| Bad_fixed_type of string
| Unbound_type_var_ext of type_expr * extension_constructor
| Varying_anonymous
| Val_in_structure
| Multiple_native_repr_attributes
| Cannot_unbox_or_untag_type of native_repr_kind
| Deep_unbox_or_untag_attribute of native_repr_kind
| Bad_immediate_attribute
| Bad_unboxed_attribute of string
| Wrong_unboxed_type_float
| Boxed_and_unboxed
| Nonrec_gadt
open Typedtree
exception Error of Location.t * error
(* Note: do not factor the branches in the following pattern-matching:
the records must be constants for the compiler to do sharing on them.
*)
let get_unboxed_from_attributes sdecl =
#if true then
if !Clflags.bs_only then unboxed_false_default_false
else
#end
let unboxed = Builtin_attributes.has_unboxed sdecl.ptype_attributes in
let boxed = Builtin_attributes.has_boxed sdecl.ptype_attributes in
match boxed, unboxed, !Clflags.unboxed_types with
| true, true, _ -> raise (Error(sdecl.ptype_loc, Boxed_and_unboxed))
| true, false, _ -> unboxed_false_default_false
| false, true, _ -> unboxed_true_default_false
| false, false, false -> unboxed_false_default_true
| false, false, true -> unboxed_true_default_true
(* Enter all declared types in the environment as abstract types *)
let enter_type rec_flag env sdecl id =
let needed =
match rec_flag with
| Asttypes.Nonrecursive ->
begin match sdecl.ptype_kind with
| Ptype_variant scds ->
List.iter (fun cd ->
if cd.pcd_res <> None then raise (Error(cd.pcd_loc, Nonrec_gadt)))
scds
| _ -> ()
end;
Btype.is_row_name (Ident.name id)
| Asttypes.Recursive -> true
in
if not needed then env else
let decl =
{ type_params =
List.map (fun _ -> Btype.newgenvar ()) sdecl.ptype_params;
type_arity = List.length sdecl.ptype_params;
type_kind = Type_abstract;
type_private = sdecl.ptype_private;
type_manifest =
begin match sdecl.ptype_manifest with None -> None
| Some _ -> Some(Ctype.newvar ()) end;
type_variance = List.map (fun _ -> Variance.full) sdecl.ptype_params;
type_newtype_level = None;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = false;
type_unboxed = unboxed_false_default_false;
}
in
Env.add_type ~check:true id decl env
let update_type temp_env env id loc =
let path = Path.Pident id in
let decl = Env.find_type path temp_env in
match decl.type_manifest with None -> ()
| Some ty ->
let params = List.map (fun _ -> Ctype.newvar ()) decl.type_params in
try Ctype.unify env (Ctype.newconstr path params) ty
with Ctype.Unify trace ->
raise (Error(loc, Type_clash (env, trace)))
(* We use the Ctype.expand_head_opt version of expand_head to get access
to the manifest type of private abbreviations. *)
let rec get_unboxed_type_representation env ty fuel =
if fuel < 0 then None else
let ty = Ctype.repr (Ctype.expand_head_opt env ty) in
match ty.desc with
| Tconstr (p, args, _) ->
begin match Env.find_type p env with
| exception Not_found -> Some ty
| {type_unboxed = {unboxed = false}} -> Some ty
| {type_params; type_kind =
Type_record ([{ld_type = ty2; _}], _)
| Type_variant [{cd_args = Cstr_tuple [ty2]; _}]
| Type_variant [{cd_args = Cstr_record [{ld_type = ty2; _}]; _}]}
-> get_unboxed_type_representation env
(Ctype.apply env type_params ty2 args) (fuel - 1)
| {type_kind=Type_abstract} -> None
(* This case can occur when checking a recursive unboxed type
declaration. *)
| _ -> assert false (* only the above can be unboxed *)
end
| _ -> Some ty
let get_unboxed_type_representation env ty =
(* Do not give too much fuel: PR#7424 *)
get_unboxed_type_representation env ty 100
;;
(* Determine if a type's values are represented by floats at run-time. *)
let is_float env ty =
match get_unboxed_type_representation env ty with
Some {desc = Tconstr(p, _, _); _} -> Path.same p Predef.path_float
| _ -> false
(* Determine if a type definition defines a fixed type. (PW) *)
let is_fixed_type sd =
let rec has_row_var sty =
match sty.ptyp_desc with
Ptyp_alias (sty, _) -> has_row_var sty
| Ptyp_class _
| Ptyp_object (_, Open)
| Ptyp_variant (_, Open, _)
| Ptyp_variant (_, Closed, Some _) -> true
| _ -> false
in
match sd.ptype_manifest with
None -> false
| Some sty ->
sd.ptype_kind = Ptype_abstract &&
sd.ptype_private = Private &&
has_row_var sty
(* Set the row variable in a fixed type *)
let set_fixed_row env loc p decl =
let tm =
match decl.type_manifest with
None -> assert false
| Some t -> Ctype.expand_head env t
in
let rv =
match tm.desc with
Tvariant row ->
let row = Btype.row_repr row in
tm.desc <- Tvariant {row with row_fixed = true};
if Btype.static_row row then Btype.newgenty Tnil
else row.row_more
| Tobject (ty, _) ->
snd (Ctype.flatten_fields ty)
| _ ->
raise (Error (loc, Bad_fixed_type "is not an object or variant"))
in
if not (Btype.is_Tvar rv) then
raise (Error (loc, Bad_fixed_type "has no row variable"));
rv.desc <- Tconstr (p, decl.type_params, ref Mnil)
(* Translate one type declaration *)
module StringSet =
Set.Make(struct
type t = string
let compare (x:t) y = compare x y
end)
let make_params env params =
let make_param (sty, v) =
try
(transl_type_param env sty, v)
with Already_bound ->
raise(Error(sty.ptyp_loc, Repeated_parameter))
in
List.map make_param params
let transl_labels env closed lbls =
assert (lbls <> []);
if !Clflags.bs_only then
match !Builtin_attributes.check_duplicated_labels lbls with
| None -> ()
| Some {loc;txt=name} -> raise (Error(loc,Duplicate_label name))
else (
let all_labels = ref StringSet.empty in
List.iter
(fun {pld_name = {txt=name; loc}} ->
if StringSet.mem name !all_labels then
raise(Error(loc, Duplicate_label name));
all_labels := StringSet.add name !all_labels)
lbls);
let mk {pld_name=name;pld_mutable=mut;pld_type=arg;pld_loc=loc;
pld_attributes=attrs} =
Builtin_attributes.warning_scope attrs
(fun () ->
let arg = Ast_helper.Typ.force_poly arg in
let cty = transl_simple_type env closed arg in
{ld_id = Ident.create name.txt; ld_name = name; ld_mutable = mut;
ld_type = cty; ld_loc = loc; ld_attributes = attrs}
)
in
let lbls = List.map mk lbls in
let lbls' =
List.map
(fun ld ->
let ty = ld.ld_type.ctyp_type in
let ty = match ty.desc with Tpoly(t,[]) -> t | _ -> ty in
{Types.ld_id = ld.ld_id;
ld_mutable = ld.ld_mutable;
ld_type = ty;
ld_loc = ld.ld_loc;
ld_attributes = ld.ld_attributes
}
)
lbls in
lbls, lbls'
let transl_constructor_arguments env closed = function
| Pcstr_tuple l ->
let l = List.map (transl_simple_type env closed) l in
Types.Cstr_tuple (List.map (fun t -> t.ctyp_type) l),
Cstr_tuple l
| Pcstr_record l ->
let lbls, lbls' = transl_labels env closed l in
Types.Cstr_record lbls',
Cstr_record lbls
let make_constructor env type_path type_params sargs sret_type =
match sret_type with
| None ->
let args, targs =
transl_constructor_arguments env true sargs
in
targs, None, args, None, type_params
| Some sret_type ->
(* if it's a generalized constructor we must first narrow and
then widen so as to not introduce any new constraints *)
let z = narrow () in
reset_type_variables ();
let args, targs =
transl_constructor_arguments env false sargs
in
let tret_type = transl_simple_type env false sret_type in
let ret_type = tret_type.ctyp_type in
let params =
match (Ctype.repr ret_type).desc with
| Tconstr (p', params, _) when Path.same type_path p' ->
params
| _ ->
raise (Error (sret_type.ptyp_loc, Constraint_failed
(ret_type, Ctype.newconstr type_path type_params)))
in
widen z;
targs, Some tret_type, args, Some ret_type, params
(* Check that the variable [id] is present in the [univ] list. *)
let check_type_var loc univ id =
let f t = (Btype.repr t).id = id in
if not (List.exists f univ) then raise (Error (loc, Wrong_unboxed_type_float))
(* Check that all the variables found in [ty] are in [univ].
Because [ty] is the argument to an abstract type, the representation
of that abstract type could be any subexpression of [ty], in particular
any type variable present in [ty].
*)
let rec check_unboxed_abstract_arg loc univ ty =
match ty.desc with
| Tvar _ -> check_type_var loc univ ty.id
| Tarrow (_, t1, t2, _)
| Tfield (_, _, t1, t2) ->
check_unboxed_abstract_arg loc univ t1;
check_unboxed_abstract_arg loc univ t2
| Ttuple args
| Tconstr (_, args, _)
| Tpackage (_, _, args) ->
List.iter (check_unboxed_abstract_arg loc univ) args
| Tobject (fields, r) ->
check_unboxed_abstract_arg loc univ fields;
begin match !r with
| None -> ()
| Some (_, args) -> List.iter (check_unboxed_abstract_arg loc univ) args
end
| Tnil
| Tunivar _ -> ()
| Tlink e -> check_unboxed_abstract_arg loc univ e
| Tsubst _ -> assert false
| Tvariant { row_fields; row_more; row_name } ->
List.iter (check_unboxed_abstract_row_field loc univ) row_fields;
check_unboxed_abstract_arg loc univ row_more;
begin match row_name with
| None -> ()
| Some (_, args) -> List.iter (check_unboxed_abstract_arg loc univ) args
end
| Tpoly (t, _) -> check_unboxed_abstract_arg loc univ t
and check_unboxed_abstract_row_field loc univ (_, field) =
match field with
| Rpresent (Some ty) -> check_unboxed_abstract_arg loc univ ty
| Reither (_, args, _, r) ->
List.iter (check_unboxed_abstract_arg loc univ) args;
begin match !r with
| None -> ()
| Some f -> check_unboxed_abstract_row_field loc univ ("", f)
end
| Rabsent
| Rpresent None -> ()
(* Check that the argument to a GADT constructor is compatible with unboxing
the type, given the universal parameters of the type. *)
let rec check_unboxed_gadt_arg loc univ env ty =
match get_unboxed_type_representation env ty with
| Some {desc = Tvar _; id} -> check_type_var loc univ id
| Some {desc = Tarrow _ | Ttuple _ | Tpackage _ | Tobject _ | Tnil
| Tvariant _; _} ->
()
(* A comment in [Translcore.transl_exp0] claims the above cannot be
represented by floats. *)
| Some {desc = Tconstr (p, args, _); _} ->
let tydecl = Env.find_type p env in
assert (not tydecl.type_unboxed.unboxed);
if tydecl.type_kind = Type_abstract then
List.iter (check_unboxed_abstract_arg loc univ) args
| Some {desc = Tfield _ | Tlink _ | Tsubst _; _} -> assert false
| Some {desc = Tunivar _; _} -> ()
| Some {desc = Tpoly (t2, _); _} -> check_unboxed_gadt_arg loc univ env t2
| None -> ()
(* This case is tricky: the argument is another (or the same) type
in the same recursive definition. In this case we don't have to
check because we will also check that other type for correctness. *)
let transl_declaration env sdecl id =
(* Bind type parameters *)
reset_type_variables();
Ctype.begin_def ();
let tparams = make_params env sdecl.ptype_params in
let params = List.map (fun (cty, _) -> cty.ctyp_type) tparams in
let cstrs = List.map
(fun (sty, sty', loc) ->
transl_simple_type env false sty,
transl_simple_type env false sty', loc)
sdecl.ptype_cstrs
in
let raw_status = get_unboxed_from_attributes sdecl in
if raw_status.unboxed && not raw_status.default then begin
match sdecl.ptype_kind with
| Ptype_abstract ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"it is abstract"))
| Ptype_variant [{pcd_args = Pcstr_tuple []; _}] ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"its constructor has no argument"))
| Ptype_variant [{pcd_args = Pcstr_tuple [_]; _}] -> ()
| Ptype_variant [{pcd_args = Pcstr_tuple _; _}] ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"its constructor has more than one argument"))
| Ptype_variant [{pcd_args = Pcstr_record
[{pld_mutable=Immutable; _}]; _}] -> ()
| Ptype_variant [{pcd_args = Pcstr_record [{pld_mutable=Mutable; _}]; _}] ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute "it is mutable"))
| Ptype_variant [{pcd_args = Pcstr_record _; _}] ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"its constructor has more than one argument"))
| Ptype_variant _ ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"it has more than one constructor"))
| Ptype_record [{pld_mutable=Immutable; _}] -> ()
| Ptype_record [{pld_mutable=Mutable; _}] ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"it is mutable"))
| Ptype_record _ ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"it has more than one field"))
| Ptype_open ->
raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute
"extensible variant types cannot be unboxed"))
end;
let unboxed_status =
match sdecl.ptype_kind with
| Ptype_variant [{pcd_args = Pcstr_tuple [_]; _}]
| Ptype_variant [{pcd_args = Pcstr_record
[{pld_mutable = Immutable; _}]; _}]
| Ptype_record [{pld_mutable = Immutable; _}] ->
raw_status
| _ -> (* The type is not unboxable, mark it as boxed *)
unboxed_false_default_false
in
let unbox = unboxed_status.unboxed in
let (tkind, kind) =
match sdecl.ptype_kind with
| Ptype_abstract -> Ttype_abstract, Type_abstract
| Ptype_variant scstrs ->
assert (scstrs <> []);
if List.exists (fun cstr -> cstr.pcd_res <> None) scstrs then begin
match cstrs with
[] -> ()
| (_,_,loc)::_ ->
Location.prerr_warning loc Warnings.Constraint_on_gadt
end;
let all_constrs = ref StringSet.empty in
List.iter
(fun {pcd_name = {txt = name}} ->
if StringSet.mem name !all_constrs then
raise(Error(sdecl.ptype_loc, Duplicate_constructor name));
all_constrs := StringSet.add name !all_constrs)
scstrs;
if List.length
(List.filter (fun cd -> cd.pcd_args <> Pcstr_tuple []) scstrs)
> (Config.max_tag + 1) then
raise(Error(sdecl.ptype_loc, Too_many_constructors));
let make_cstr scstr =
let name = Ident.create scstr.pcd_name.txt in
let targs, tret_type, args, ret_type, cstr_params =
make_constructor env (Path.Pident id) params
scstr.pcd_args scstr.pcd_res
in
if Config.flat_float_array && unbox then begin
(* Cannot unbox a type when the argument can be both float and
non-float because it interferes with the dynamic float array
optimization. This can only happen when the type is a GADT
and the argument is an existential type variable or an
unboxed (or abstract) type constructor applied to some
existential type variable. Of course we also have to rule
out any abstract type constructor applied to anything that
might be an existential type variable.
There is a difficulty with existential variables created
out of thin air (rather than bound by the declaration).
See PR#7511 and GPR#1133 for details. *)
match Datarepr.constructor_existentials args ret_type with
| _, [] -> ()
| [argty], _ex ->
check_unboxed_gadt_arg sdecl.ptype_loc cstr_params env argty
| _ -> assert false
end;
let tcstr =
{ cd_id = name;
cd_name = scstr.pcd_name;
cd_args = targs;
cd_res = tret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes }
in
let cstr =
{ Types.cd_id = name;
cd_args = args;
cd_res = ret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = scstr.pcd_attributes }
in
tcstr, cstr
in
let make_cstr scstr =
Builtin_attributes.warning_scope scstr.pcd_attributes
(fun () -> make_cstr scstr)
in
let tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
Ttype_variant tcstrs, Type_variant cstrs
| Ptype_record lbls ->
let lbls, lbls' = transl_labels env true lbls in
let rep =
if !Clflags.bs_only then Record_regular else (* ATTENTION: revisit when we support @@unbox*)
if unbox then Record_unboxed false
else if List.for_all (fun l -> is_float env l.Types.ld_type) lbls'
then Record_float
else Record_regular
in
Ttype_record lbls, Type_record(lbls', rep)
| Ptype_open -> Ttype_open, Type_open
in
let (tman, man) = match sdecl.ptype_manifest with
None -> None, None
| Some sty ->
let no_row = not (is_fixed_type sdecl) in
let cty = transl_simple_type env no_row sty in
Some cty, Some cty.ctyp_type
in
let decl =
{ type_params = params;
type_arity = List.length params;
type_kind = kind;
type_private = sdecl.ptype_private;
type_manifest = man;
type_variance = List.map (fun _ -> Variance.full) params;
type_newtype_level = None;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = false;
type_unboxed = unboxed_status;
} in
(* Check constraints *)
List.iter
(fun (cty, cty', loc) ->
let ty = cty.ctyp_type in
let ty' = cty'.ctyp_type in
try Ctype.unify env ty ty' with Ctype.Unify tr ->
raise(Error(loc, Inconsistent_constraint (env, tr))))
cstrs;
Ctype.end_def ();
(* Add abstract row *)
if is_fixed_type sdecl then begin
let p =
try Env.lookup_type (Longident.Lident(Ident.name id ^ "#row")) env
with Not_found -> assert false in
set_fixed_row env sdecl.ptype_loc p decl
end;
(* Check for cyclic abbreviations *)
begin match decl.type_manifest with None -> ()
| Some ty ->
if Ctype.cyclic_abbrev env id ty then
raise(Error(sdecl.ptype_loc, Recursive_abbrev sdecl.ptype_name.txt));
end;
{
typ_id = id;
typ_name = sdecl.ptype_name;
typ_params = tparams;
typ_type = decl;
typ_cstrs = cstrs;
typ_loc = sdecl.ptype_loc;
typ_manifest = tman;
typ_kind = tkind;
typ_private = sdecl.ptype_private;
typ_attributes = sdecl.ptype_attributes;
}
(* Generalize a type declaration *)
let generalize_decl decl =
List.iter Ctype.generalize decl.type_params;
Btype.iter_type_expr_kind Ctype.generalize decl.type_kind;
begin match decl.type_manifest with
| None -> ()
| Some ty -> Ctype.generalize ty
end
(* Check that all constraints are enforced *)
module TypeSet = Btype.TypeSet
module TypeMap = Btype.TypeMap
let rec check_constraints_rec env loc visited ty =
let ty = Ctype.repr ty in
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match ty.desc with
| Tconstr (path, args, _) ->
let args' = List.map (fun _ -> Ctype.newvar ()) args in
let ty' = Ctype.newconstr path args' in
begin try Ctype.enforce_constraints env ty'
with Ctype.Unify _ -> assert false
| Not_found -> raise (Error(loc, Unavailable_type_constructor path))
end;
if not (Ctype.matches env ty ty') then
raise (Error(loc, Constraint_failed (ty, ty')));
List.iter (check_constraints_rec env loc visited) args
| Tpoly (ty, tl) ->
let _, ty = Ctype.instance_poly false tl ty in
check_constraints_rec env loc visited ty
| _ ->
Btype.iter_type_expr (check_constraints_rec env loc visited) ty
end
module SMap = Map.Make(String)
let check_constraints_labels env visited l pl =
let rec get_loc name = function
[] -> assert false
| pld :: tl ->
if name = pld.pld_name.txt then pld.pld_type.ptyp_loc
else get_loc name tl
in
List.iter
(fun {Types.ld_id=name; ld_type=ty} ->
check_constraints_rec env (get_loc (Ident.name name) pl) visited ty)
l
let check_constraints env sdecl (_, decl) =
let visited = ref TypeSet.empty in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant l ->
let find_pl = function
Ptype_variant pl -> pl
| Ptype_record _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
let pl_index =
let foldf acc x =
SMap.add x.pcd_name.txt x acc
in
List.fold_left foldf SMap.empty pl
in
List.iter
(fun {Types.cd_id=name; cd_args; cd_res} ->
let {pcd_args; pcd_res; _} =
try SMap.find (Ident.name name) pl_index
with Not_found -> assert false in
begin match cd_args, pcd_args with
| Cstr_tuple tyl, Pcstr_tuple styl ->
List.iter2
(fun sty ty ->
check_constraints_rec env sty.ptyp_loc visited ty)
styl tyl
| Cstr_record tyl, Pcstr_record styl ->
check_constraints_labels env visited tyl styl
| _ -> assert false
end;
match pcd_res, cd_res with
| Some sr, Some r ->
check_constraints_rec env sr.ptyp_loc visited r
| _ ->
() )
l
| Type_record (l, _) ->
let find_pl = function
Ptype_record pl -> pl
| Ptype_variant _ | Ptype_abstract | Ptype_open -> assert false
in
let pl = find_pl sdecl.ptype_kind in
check_constraints_labels env visited l pl
| Type_open -> ()
end;
begin match decl.type_manifest with
| None -> ()
| Some ty ->
let sty =
match sdecl.ptype_manifest with Some sty -> sty | _ -> assert false
in
check_constraints_rec env sty.ptyp_loc visited ty
end
(*
If both a variant/record definition and a type equation are given,
need to check that the equation refers to a type of the same kind
with the same constructors and labels.
*)
let check_coherence env loc id decl =
match decl with
{ type_kind = (Type_variant _ | Type_record _| Type_open);
type_manifest = Some ty } ->
begin match (Ctype.repr ty).desc with
Tconstr(path, args, _) ->
begin try
let decl' = Env.find_type path env in
let err =
if List.length args <> List.length decl.type_params
then [Includecore.Arity]
else if not (Ctype.equal env false args decl.type_params)
then [Includecore.Constraint]
else
Includecore.type_declarations ~loc ~equality:true env
(Path.last path)
decl'
id
(Subst.type_declaration
(Subst.add_type id path Subst.identity) decl)
in
if err <> [] then
raise(Error(loc, Definition_mismatch (ty, err)))
with Not_found ->
raise(Error(loc, Unavailable_type_constructor path))
end
| _ -> raise(Error(loc, Definition_mismatch (ty, [])))
end
| _ -> ()
let check_abbrev env sdecl (id, decl) =
check_coherence env sdecl.ptype_loc id decl
(* Check that recursion is well-founded *)
let check_well_founded env loc path to_check ty =
let visited = ref TypeMap.empty in
let rec check ty0 parents ty =
let ty = Btype.repr ty in
if TypeSet.mem ty parents then begin
(*Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;*)
if match ty0.desc with
| Tconstr (p, _, _) -> Path.same p path
| _ -> false
then raise (Error (loc, Recursive_abbrev (Path.name path)))
else raise (Error (loc, Cycle_in_def (Path.name path, ty0)))
end;
let (fini, parents) =
try
let prev = TypeMap.find ty !visited in
if TypeSet.subset parents prev then (true, parents) else
(false, TypeSet.union parents prev)
with Not_found ->
(false, parents)
in
if fini then () else
let rec_ok =
match ty.desc with
Tconstr(p,_,_) ->
!Clflags.recursive_types && Ctype.is_contractive env p
| Tobject _ | Tvariant _ -> true
| _ -> !Clflags.recursive_types
in
let visited' = TypeMap.add ty parents !visited in
let arg_exn =
try
visited := visited';
let parents =
if rec_ok then TypeSet.empty else TypeSet.add ty parents in
Btype.iter_type_expr (check ty0 parents) ty;
None
with e ->
visited := visited'; Some e
in
match ty.desc with
| Tconstr(p, _, _) when arg_exn <> None || to_check p ->
if to_check p then may raise arg_exn
else Btype.iter_type_expr (check ty0 TypeSet.empty) ty;
begin try
let ty' = Ctype.try_expand_once_opt env ty in
let ty0 = if TypeSet.is_empty parents then ty else ty0 in
check ty0 (TypeSet.add ty parents) ty'
with
Ctype.Cannot_expand -> may raise arg_exn
end
| _ -> may raise arg_exn
in
let snap = Btype.snapshot () in
try Ctype.wrap_trace_gadt_instances env (check ty TypeSet.empty) ty
with Ctype.Unify _ ->
(* Will be detected by check_recursion *)
Btype.backtrack snap
let check_well_founded_manifest env loc path decl =
if decl.type_manifest = None then () else
let args = List.map (fun _ -> Ctype.newvar()) decl.type_params in
check_well_founded env loc path (Path.same path) (Ctype.newconstr path args)
let check_well_founded_decl env loc path decl to_check =
let open Btype in
let it =
{type_iterators with
it_type_expr = (fun _ -> check_well_founded env loc path to_check)} in
it.it_type_declaration it (Ctype.instance_declaration decl)
(* Check for ill-defined abbrevs *)
let check_recursion env loc path decl to_check =
(* to_check is true for potentially mutually recursive paths.
(path, decl) is the type declaration to be checked. *)
if decl.type_params = [] then () else
let visited = ref [] in
let rec check_regular cpath args prev_exp ty =
let ty = Ctype.repr ty in
if not (List.memq ty !visited) then begin
visited := ty :: !visited;
match ty.desc with
| Tconstr(path', args', _) ->
if Path.same path path' then begin
if not (Ctype.equal env false args args') then
raise (Error(loc,
Parameters_differ(cpath, ty, Ctype.newconstr path args)))
end
(* Attempt to expand a type abbreviation if:
1- [to_check path'] holds
(otherwise the expansion cannot involve [path]);
2- we haven't expanded this type constructor before
(otherwise we could loop if [path'] is itself
a non-regular abbreviation). *)
else if to_check path' && not (List.mem path' prev_exp) then begin
try
(* Attempt expansion *)
let (params0, body0, _) = Env.find_type_expansion path' env in
let (params, body) =
Ctype.instance_parameterized_type params0 body0 in
begin
try List.iter2 (Ctype.unify env) params args'
with Ctype.Unify _ ->
raise (Error(loc, Constraint_failed
(ty, Ctype.newconstr path' params0)));
end;
check_regular path' args (path' :: prev_exp) body
with Not_found -> ()
end;
List.iter (check_regular cpath args prev_exp) args'
| Tpoly (ty, tl) ->
let (_, ty) = Ctype.instance_poly ~keep_names:true false tl ty in
check_regular cpath args prev_exp ty
| _ ->
Btype.iter_type_expr (check_regular cpath args prev_exp) ty
end in
Misc.may
(fun body ->
let (args, body) =
Ctype.instance_parameterized_type
~keep_names:true decl.type_params body in
check_regular path args [] body)
decl.type_manifest
let check_abbrev_recursion env id_loc_list to_check tdecl =
let decl = tdecl.typ_type in
let id = tdecl.typ_id in
check_recursion env (List.assoc id id_loc_list) (Path.Pident id) decl to_check
(* Compute variance *)
let get_variance ty visited =
try TypeMap.find ty !visited with Not_found -> Variance.null
let compute_variance env visited vari ty =
let rec compute_variance_rec vari ty =
(* Format.eprintf "%a: %x@." Printtyp.type_expr ty (Obj.magic vari); *)
let ty = Ctype.repr ty in
let vari' = get_variance ty visited in
if Variance.subset vari vari' then () else
let vari = Variance.union vari vari' in
visited := TypeMap.add ty vari !visited;
let compute_same = compute_variance_rec vari in
match ty.desc with
Tarrow (_, ty1, ty2, _) ->
let open Variance in
let v = conjugate vari in
let v1 =
if mem May_pos v || mem May_neg v
then set May_weak true v else v
in
compute_variance_rec v1 ty1;
compute_same ty2
| Ttuple tl ->
List.iter compute_same tl
| Tconstr (path, tl, _) ->
let open Variance in
if tl = [] then () else begin
try
let decl = Env.find_type path env in
let cvari f = mem f vari in
List.iter2
(fun ty v ->
let cv f = mem f v in
let strict =
cvari Inv && cv Inj || (cvari Pos || cvari Neg) && cv Inv
in
if strict then compute_variance_rec full ty else
let p1 = inter v vari
and n1 = inter v (conjugate vari) in
let v1 =
union (inter covariant (union p1 (conjugate p1)))
(inter (conjugate covariant) (union n1 (conjugate n1)))
and weak =
cvari May_weak && (cv May_pos || cv May_neg) ||
(cvari May_pos || cvari May_neg) && cv May_weak
in
let v2 = set May_weak weak v1 in
compute_variance_rec v2 ty)
tl decl.type_variance
with Not_found ->
List.iter (compute_variance_rec may_inv) tl
end
| Tobject (ty, _) ->
compute_same ty
| Tfield (_, _, ty1, ty2) ->
compute_same ty1;
compute_same ty2
| Tsubst ty ->
compute_same ty
| Tvariant row ->
let row = Btype.row_repr row in
List.iter
(fun (_,f) ->
match Btype.row_field_repr f with
Rpresent (Some ty) ->
compute_same ty
| Reither (_, tyl, _, _) ->
let open Variance in
let upper =
List.fold_left (fun s f -> set f true s)
null [May_pos; May_neg; May_weak]
in
let v = inter vari upper in
(* cf PR#7269:
if List.length tyl > 1 then upper else inter vari upper *)
List.iter (compute_variance_rec v) tyl
| _ -> ())
row.row_fields;
compute_same row.row_more
| Tpoly (ty, _) ->
compute_same ty
| Tvar _ | Tnil | Tlink _ | Tunivar _ -> ()
| Tpackage (_, _, tyl) ->
let v =
Variance.(if mem Pos vari || mem Neg vari then full else may_inv)
in
List.iter (compute_variance_rec v) tyl
in
compute_variance_rec vari ty
let make p n i =
let open Variance in
set May_pos p (set May_neg n (set May_weak n (set Inj i null)))
let compute_variance_type env check (required, loc) decl tyl =
(* Requirements *)
let required =
List.map (fun (c,n,i) -> if c || n then (c,n,i) else (true,true,i))
required
in
(* Prepare *)
let params = List.map Btype.repr decl.type_params in
let tvl = ref TypeMap.empty in
(* Compute occurrences in the body *)
let open Variance in
List.iter
(fun (cn,ty) ->
compute_variance env tvl (if cn then full else covariant) ty)
tyl;
if check then begin
(* Check variance of parameters *)
let pos = ref 0 in
List.iter2
(fun ty (c, n, i) ->
incr pos;
let var = get_variance ty tvl in
let (co,cn) = get_upper var and ij = mem Inj var in
if Btype.is_Tvar ty && (co && not c || cn && not n || not ij && i)
then raise (Error(loc, Bad_variance (!pos, (co,cn,ij), (c,n,i)))))
params required;
(* Check propagation from constrained parameters *)
let args = Btype.newgenty (Ttuple params) in
let fvl = Ctype.free_variables args in
let fvl = List.filter (fun v -> not (List.memq v params)) fvl in
(* If there are no extra variables there is nothing to do *)
if fvl = [] then () else
let tvl2 = ref TypeMap.empty in
List.iter2
(fun ty (p,n,_) ->
if Btype.is_Tvar ty then () else
let v =
if p then if n then full else covariant else conjugate covariant in
compute_variance env tvl2 v ty)
params required;
let visited = ref TypeSet.empty in
let rec check ty =
let ty = Ctype.repr ty in
if TypeSet.mem ty !visited then () else
let visited' = TypeSet.add ty !visited in
visited := visited';
let v1 = get_variance ty tvl in
let snap = Btype.snapshot () in
let v2 =
TypeMap.fold
(fun t vt v ->
if Ctype.equal env false [ty] [t] then union vt v else v)
!tvl2 null in
Btype.backtrack snap;
let (c1,n1) = get_upper v1 and (c2,n2,_,i2) = get_lower v2 in
if c1 && not c2 || n1 && not n2 then