-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypedecl.ml
1915 lines (1829 loc) · 70.3 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
module String = Misc.Stdlib.String
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 * Env.t * Includecore.type_mismatch option
| Constraint_failed of Env.t * Errortrace.unification_error
| Inconsistent_constraint of Env.t * Errortrace.unification_error
| Type_clash of Env.t * Errortrace.unification_error
| Non_regular of {
definition: Path.t;
used_as: type_expr;
defined_as: type_expr;
expansions: (type_expr * type_expr) list;
}
| 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 * Env.t * Includecore.type_mismatch
| Rebind_wrong_type of
Longident.t * Env.t * Errortrace.unification_error
| Rebind_mismatch of Longident.t * Path.t * Path.t
| Rebind_private of Longident.t
| Variance of Typedecl_variance.error
| Unavailable_type_constructor of Path.t
| Unbound_type_var_ext of type_expr * extension_constructor
| 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
| Immediacy of Typedecl_immediacy.error
| Separability of Typedecl_separability.error
| Bad_unboxed_attribute of string
| Boxed_and_unboxed
| Nonrec_gadt
| Invalid_private_row_declaration of type_expr
open Typedtree
exception Error of Location.t * error
let get_unboxed_from_attributes sdecl =
let unboxed = Builtin_attributes.has_unboxed sdecl.ptype_attributes in
let boxed = Builtin_attributes.has_boxed sdecl.ptype_attributes in
match boxed, unboxed with
| true, true -> raise (Error(sdecl.ptype_loc, Boxed_and_unboxed))
| true, false -> Some false
| false, true -> Some true
| false, false -> None
(* Enter all declared types in the environment as abstract types *)
let add_type ~check id decl env =
Builtin_attributes.warning_scope ~ppwarning:false decl.type_attributes
(fun () -> Env.add_type ~check id decl env)
let enter_type rec_flag env sdecl (id, uid) =
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
let arity = List.length sdecl.ptype_params in
if not needed then env else
let decl =
{ type_params =
List.map (fun _ -> Btype.newgenvar ()) sdecl.ptype_params;
type_arity = arity;
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 = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = false;
type_uid = uid;
}
in
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 err ->
raise (Error(loc, Type_clash (env, err)))
(* Determine if a type's values are represented by floats at run-time. *)
let is_float env ty =
match Typedecl_unboxed.get_unboxed_type_representation env ty with
Some ty' ->
begin match get_desc ty' with
Tconstr(p, _, _) -> Path.same p Predef.path_float
| _ -> false
end
| _ -> 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 to a fixed type in a private row type declaration.
(e.g. [ type t = private [< `A | `B ] ] or [type u = private < .. > ])
Require [is_fixed_type decl] as a precondition
*)
let set_private_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 get_desc tm with
Tvariant row ->
let Row {fields; more; closed; name} = row_repr row in
set_type_desc tm
(Tvariant (create_row ~fields ~more ~closed ~name
~fixed:(Some Fixed_private)));
if Btype.static_row row then
(* the syntax hinted at the existence of a row variable,
but there is in fact no row variable to make private, e.g.
[ type t = private [< `A > `A] ] *)
raise (Error(loc, Invalid_private_row_declaration tm))
else more
| Tobject (ty, _) ->
let r = snd (Ctype.flatten_fields ty) in
if not (Btype.is_Tvar r) then
(* a syntactically open object was closed by a constraint *)
raise (Error(loc, Invalid_private_row_declaration tm));
r
| _ -> assert false
in
set_type_desc rv (Tconstr (p, decl.type_params, ref Mnil))
(* Translate one type declaration *)
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 univars closed lbls =
assert (lbls <> []);
let all_labels = ref String.Set.empty in
List.iter
(fun {pld_name = {txt=name; loc}} ->
if String.Set.mem name !all_labels then
raise(Error(loc, Duplicate_label name));
all_labels := String.Set.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 ?univars closed arg in
{ld_id = Ident.create_local 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 get_desc ty 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;
ld_uid = Uid.mk ~current_unit:(Env.get_unit_name ());
}
)
lbls in
lbls, lbls'
let transl_constructor_arguments env univars closed = function
| Pcstr_tuple l ->
let l = List.map (transl_simple_type env ?univars 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 univars closed l in
Types.Cstr_record lbls',
Cstr_record lbls
let make_constructor env loc type_path type_params svars sargs sret_type =
match sret_type with
| None ->
let args, targs =
transl_constructor_arguments env None true sargs
in
targs, None, args, None
| 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 univars, closed =
match svars with
| [] -> None, false
| vs ->
Ctype.begin_def();
Some (make_poly_univars (List.map (fun v -> v.txt) vs)), true
in
let args, targs =
transl_constructor_arguments env univars closed sargs
in
let tret_type = transl_simple_type env ?univars closed sret_type in
let ret_type = tret_type.ctyp_type in
(* TODO add back type_path as a parameter ? *)
begin match get_desc ret_type with
| Tconstr (p', _, _) when Path.same type_path p' -> ()
| _ ->
let trace =
(* Expansion is not helpful here -- the restriction on GADT return
types is purely syntactic. (In the worst case, expansion
produces gibberish.) *)
[Ctype.unexpanded_diff
~got:ret_type
~expected:(Ctype.newconstr type_path type_params)]
in
raise (Error(sret_type.ptyp_loc,
Constraint_failed(env,
Errortrace.unification_error ~trace)))
end;
begin match univars with
| None -> ()
| Some univars ->
Ctype.end_def();
Btype.iter_type_expr_cstr_args Ctype.generalize args;
Ctype.generalize ret_type;
let _vars = instance_poly_univars env loc univars in
let set_level t = Ctype.unify_var env (Ctype.newvar()) t in
Btype.iter_type_expr_cstr_args set_level args;
set_level ret_type;
end;
widen z;
targs, Some tret_type, args, Some ret_type
let transl_declaration env sdecl (id, uid) =
(* 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 unboxed_attr = get_unboxed_from_attributes sdecl in
begin match unboxed_attr with
| (None | Some false) -> ()
| Some true ->
let bad msg = raise(Error(sdecl.ptype_loc, Bad_unboxed_attribute msg)) in
match sdecl.ptype_kind with
| Ptype_abstract -> bad "it is abstract"
| Ptype_open -> bad "extensible variant types cannot be unboxed"
| Ptype_record fields -> begin match fields with
| [] -> bad "it has no fields"
| _::_::_ -> bad "it has more than one field"
| [{pld_mutable = Mutable}] -> bad "it is mutable"
| [{pld_mutable = Immutable}] -> ()
end
| Ptype_variant constructors -> begin match constructors with
| [] -> bad "it has no constructor"
| (_::_::_) -> bad "it has more than one constructor"
| [c] -> begin match c.pcd_args with
| Pcstr_tuple [] ->
bad "its constructor has no argument"
| Pcstr_tuple (_::_::_) ->
bad "its constructor has more than one argument"
| Pcstr_tuple [_] ->
()
| Pcstr_record [] ->
bad "its constructor has no fields"
| Pcstr_record (_::_::_) ->
bad "its constructor has more than one field"
| Pcstr_record [{pld_mutable = Mutable}] ->
bad "it is mutable"
| Pcstr_record [{pld_mutable = Immutable}] ->
()
end
end
end;
let unbox, unboxed_default =
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; _}] ->
Option.value unboxed_attr ~default:!Clflags.unboxed_types,
Option.is_none unboxed_attr
| _ -> false, false (* Not unboxable, mark as boxed *)
in
let (tkind, kind) =
match sdecl.ptype_kind with
| Ptype_abstract -> Ttype_abstract, Type_abstract
| Ptype_variant 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 String.Set.empty in
List.iter
(fun {pcd_name = {txt = name}} ->
if String.Set.mem name !all_constrs then
raise(Error(sdecl.ptype_loc, Duplicate_constructor name));
all_constrs := String.Set.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_local scstr.pcd_name.txt in
let targs, tret_type, args, ret_type =
make_constructor env scstr.pcd_loc (Path.Pident id) params
scstr.pcd_vars scstr.pcd_args scstr.pcd_res
in
let tcstr =
{ cd_id = name;
cd_name = scstr.pcd_name;
cd_vars = scstr.pcd_vars;
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;
cd_uid = Uid.mk ~current_unit:(Env.get_unit_name ()) }
in
tcstr, cstr
in
let make_cstr scstr =
Builtin_attributes.warning_scope scstr.pcd_attributes
(fun () -> make_cstr scstr)
in
let rep = if unbox then Variant_unboxed else Variant_regular in
let tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
Ttype_variant tcstrs, Type_variant (cstrs, rep)
| Ptype_record lbls ->
let lbls, lbls' = transl_labels env None true lbls in
let rep =
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 arity = List.length params in
let decl =
{ type_params = params;
type_arity = arity;
type_kind = kind;
type_private = sdecl.ptype_private;
type_manifest = man;
type_variance = Variance.unknown_signature ~injective:false ~arity;
type_separability = Types.Separability.default_signature ~arity;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = sdecl.ptype_loc;
type_attributes = sdecl.ptype_attributes;
type_immediate = Unknown;
type_unboxed_default = unboxed_default;
type_uid = uid;
} 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 err ->
raise(Error(loc, Inconsistent_constraint (env, err))))
cstrs;
Ctype.end_def ();
(* Add abstract row *)
if is_fixed_type sdecl then begin
let p, _ =
try Env.find_type_by_name
(Longident.Lident(Ident.name id ^ "#row")) env
with Not_found -> assert false
in
set_private_row env sdecl.ptype_loc p decl
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 =
if TypeSet.mem ty !visited then () else begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr (path, args, _) ->
let decl =
try Env.find_type path env
with Not_found ->
raise (Error(loc, Unavailable_type_constructor path)) in
let ty' = Ctype.newconstr path (Ctype.instance_list decl.type_params) in
begin
(* We don't expand the error trace because that produces types that
*already* violate the constraints -- we need to report a problem with
the unexpanded types, or we get errors that talk about the same type
twice. This is generally true for constraint errors. *)
try Ctype.matches ~expand_error_trace:false env ty ty'
with Ctype.Matches_failure (env, err) ->
raise (Error(loc, Constraint_failed (env, err)))
end;
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
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
List.iter2
(fun (sty, _) ty -> check_constraints_rec env sty.ptyp_loc visited ty)
sdecl.ptype_params decl.type_params;
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant (l, _rep) ->
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 =
String.Map.add x.pcd_name.txt x acc
in
List.fold_left foldf String.Map.empty pl
in
List.iter
(fun {Types.cd_id=name; cd_args; cd_res} ->
let {pcd_args; pcd_res; _} =
try String.Map.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 dpath decl =
match decl with
{ type_kind = (Type_variant _ | Type_record _| Type_open);
type_manifest = Some ty } ->
begin match get_desc ty 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 Some Includecore.Arity
else begin
match Ctype.equal env false args decl.type_params with
| exception Ctype.Equality err ->
Some (Includecore.Constraint err)
| () ->
Includecore.type_declarations ~loc ~equality:true env
~mark:true
(Path.last path)
decl'
dpath
(Subst.type_declaration
(Subst.add_type_path dpath path Subst.identity) decl)
end
in
if err <> None then
raise(Error(loc, Definition_mismatch (ty, env, err)))
with Not_found ->
raise(Error(loc, Unavailable_type_constructor path))
end
| _ -> raise(Error(loc, Definition_mismatch (ty, env, None)))
end
| _ -> ()
let check_abbrev env sdecl (id, decl) =
check_coherence env sdecl.ptype_loc (Path.Pident 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 =
if TypeSet.mem ty parents then begin
(*Format.eprintf "@[%a@]@." Printtyp.raw_type_expr ty;*)
if match get_desc ty0 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 get_desc ty 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 get_desc ty with
| Tconstr(p, _, _) when arg_exn <> None || to_check p ->
if to_check p then Option.iter 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 -> Option.iter raise arg_exn
end
| _ -> Option.iter raise arg_exn
in
let snap = Btype.snapshot () in
try Ctype.wrap_trace_gadt_instances env (check ty TypeSet.empty) ty
with Ctype.Escape _ ->
(* 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.generic_instance_declaration decl)
(* Check for ill-defined abbrevs *)
let check_recursion ~orig_env 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 TypeSet.empty in
let rec check_regular cpath args prev_exp prev_expansions ty =
if not (TypeSet.mem ty !visited) then begin
visited := TypeSet.add ty !visited;
match get_desc ty with
| Tconstr(path', args', _) ->
if Path.same path path' then begin
if not (Ctype.is_equal orig_env false args args') then
raise (Error(loc,
Non_regular {
definition=path;
used_as=ty;
defined_as=Ctype.newconstr path args;
expansions=List.rev prev_expansions;
}))
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 orig_env) params args'
with Ctype.Unify err ->
raise (Error(loc, Constraint_failed (orig_env, err)));
end;
check_regular path' args
(path' :: prev_exp) ((ty,body) :: prev_expansions)
body
with Not_found -> ()
end;
List.iter (check_regular cpath args prev_exp prev_expansions) args'
| Tpoly (ty, tl) ->
let (_, ty) = Ctype.instance_poly ~keep_names:true false tl ty in
check_regular cpath args prev_exp prev_expansions ty
| _ ->
Btype.iter_type_expr
(check_regular cpath args prev_exp prev_expansions) ty
end in
Option.iter
(fun body ->
let (args, body) =
Ctype.instance_parameterized_type
~keep_names:true decl.type_params body in
List.iter (check_regular path args [] []) args;
check_regular path args [] [] body)
decl.type_manifest
let check_abbrev_recursion ~orig_env env id_loc_list to_check tdecl =
let decl = tdecl.typ_type in
let id = tdecl.typ_id in
check_recursion ~orig_env env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check
let check_duplicates sdecl_list =
let labels = Hashtbl.create 7 and constrs = Hashtbl.create 7 in
List.iter
(fun sdecl -> match sdecl.ptype_kind with
Ptype_variant cl ->
List.iter
(fun pcd ->
try
let name' = Hashtbl.find constrs pcd.pcd_name.txt in
Location.prerr_warning pcd.pcd_loc
(Warnings.Duplicate_definitions
("constructor", pcd.pcd_name.txt, name',
sdecl.ptype_name.txt))
with Not_found ->
Hashtbl.add constrs pcd.pcd_name.txt sdecl.ptype_name.txt)
cl
| Ptype_record fl ->
List.iter
(fun {pld_name=cname;pld_loc=loc} ->
try
let name' = Hashtbl.find labels cname.txt in
Location.prerr_warning loc
(Warnings.Duplicate_definitions
("label", cname.txt, name', sdecl.ptype_name.txt))
with Not_found -> Hashtbl.add labels cname.txt sdecl.ptype_name.txt)
fl
| Ptype_abstract -> ()
| Ptype_open -> ())
sdecl_list
(* Force recursion to go through id for private types*)
let name_recursion sdecl id decl =
match decl with
| { type_kind = Type_abstract;
type_manifest = Some ty;
type_private = Private; } when is_fixed_type sdecl ->
let ty' = newty2 ~level:(get_level ty) (get_desc ty) in
if Ctype.deep_occur ty ty' then
let td = Tconstr(Path.Pident id, decl.type_params, ref Mnil) in
link_type ty (newty2 ~level:(get_level ty) td);
{decl with type_manifest = Some ty'}
else decl
| _ -> decl
let name_recursion_decls sdecls decls =
List.map2 (fun sdecl (id, decl) -> (id, name_recursion sdecl id decl))
sdecls decls
(* Warn on definitions of type "type foo = ()" which redefine a different unit
type and are likely a mistake. *)
let check_redefined_unit (td: Parsetree.type_declaration) =
let open Parsetree in
let is_unit_constructor cd = cd.pcd_name.txt = "()" in
match td with
| { ptype_name = { txt = name };
ptype_manifest = None;
ptype_kind = Ptype_variant [ cd ] }
when is_unit_constructor cd ->
Location.prerr_warning td.ptype_loc (Warnings.Redefining_unit name)
| _ ->
()
let add_types_to_env decls env =
List.fold_right
(fun (id, decl) env -> add_type ~check:true id decl env)
decls env
(* Translate a set of type declarations, mutually recursive or not *)
let transl_type_decl env rec_flag sdecl_list =
List.iter check_redefined_unit sdecl_list;
(* Add dummy types for fixed rows *)
let fixed_types = List.filter is_fixed_type sdecl_list in
let sdecl_list =
List.map
(fun sdecl ->
let ptype_name =
let loc = { sdecl.ptype_name.loc with Location.loc_ghost = true } in
mkloc (sdecl.ptype_name.txt ^"#row") loc
in
let ptype_kind = Ptype_abstract in
let ptype_manifest = None in
let ptype_loc = { sdecl.ptype_loc with Location.loc_ghost = true } in
{sdecl with
ptype_name; ptype_kind; ptype_manifest; ptype_loc })
fixed_types
@ sdecl_list
in
(* Create identifiers. *)
let scope = Ctype.create_scope () in
let ids_list =
List.map (fun sdecl ->
Ident.create_scoped ~scope sdecl.ptype_name.txt,
Uid.mk ~current_unit:(Env.get_unit_name ())
) sdecl_list
in
Ctype.begin_def();
(* Enter types. *)
let temp_env =
List.fold_left2 (enter_type rec_flag) env sdecl_list ids_list in
(* Translate each declaration. *)
let current_slot = ref None in
let warn_unused = Warnings.is_active (Warnings.Unused_type_declaration "") in
let ids_slots (id, _uid as ids) =
match rec_flag with
| Asttypes.Recursive when warn_unused ->
(* See typecore.ml for a description of the algorithm used
to detect unused declarations in a set of recursive definitions. *)
let slot = ref [] in
let td = Env.find_type (Path.Pident id) temp_env in
Env.set_type_used_callback
td
(fun old_callback ->
match !current_slot with
| Some slot -> slot := td.type_uid :: !slot
| None ->
List.iter Env.mark_type_used (get_ref slot);
old_callback ()
);
ids, Some slot
| Asttypes.Recursive | Asttypes.Nonrecursive ->
ids, None
in
let transl_declaration name_sdecl (id, slot) =
current_slot := slot;
Builtin_attributes.warning_scope
name_sdecl.ptype_attributes
(fun () -> transl_declaration temp_env name_sdecl id)
in
let tdecls =
List.map2 transl_declaration sdecl_list (List.map ids_slots ids_list) in
let decls =
List.map (fun tdecl -> (tdecl.typ_id, tdecl.typ_type)) tdecls in
current_slot := None;
(* Check for duplicates *)
check_duplicates sdecl_list;
(* Build the final env. *)
let new_env = add_types_to_env decls env in
(* Update stubs *)
begin match rec_flag with
| Asttypes.Nonrecursive -> ()
| Asttypes.Recursive ->
List.iter2
(fun (id, _) sdecl -> update_type temp_env new_env id sdecl.ptype_loc)
ids_list sdecl_list
end;
(* Generalize type declarations. *)
Ctype.end_def();
List.iter (fun (_, decl) -> generalize_decl decl) decls;
(* Check for ill-formed abbrevs *)
let id_loc_list =
List.map2 (fun (id, _) sdecl -> (id, sdecl.ptype_loc))
ids_list sdecl_list
in
List.iter (fun (id, decl) ->
check_well_founded_manifest new_env (List.assoc id id_loc_list)
(Path.Pident id) decl)
decls;
let to_check =
function Path.Pident id -> List.mem_assoc id id_loc_list | _ -> false in
List.iter (fun (id, decl) ->
check_well_founded_decl new_env (List.assoc id id_loc_list) (Path.Pident id)
decl to_check)
decls;
List.iter
(check_abbrev_recursion ~orig_env:env new_env id_loc_list to_check) tdecls;
(* Check that all type variables are closed *)
List.iter2
(fun sdecl tdecl ->
let decl = tdecl.typ_type in
match Ctype.closed_type_decl decl with
Some ty -> raise(Error(sdecl.ptype_loc, Unbound_type_var(ty,decl)))
| None -> ())
sdecl_list tdecls;
(* Check that constraints are enforced *)
List.iter2 (check_constraints new_env) sdecl_list decls;
(* Add type properties to declarations *)
let decls =
try
decls
|> name_recursion_decls sdecl_list
|> Typedecl_variance.update_decls env sdecl_list
|> Typedecl_immediacy.update_decls env
|> Typedecl_separability.update_decls env
with
| Typedecl_variance.Error (loc, err) ->
raise (Error (loc, Variance err))
| Typedecl_immediacy.Error (loc, err) ->
raise (Error (loc, Immediacy err))
| Typedecl_separability.Error (loc, err) ->
raise (Error (loc, Separability err))
in
(* Compute the final environment with variance and immediacy *)
let final_env = add_types_to_env decls env in
(* Check re-exportation *)
List.iter2 (check_abbrev final_env) sdecl_list decls;
(* Keep original declaration *)
let final_decls =
List.map2
(fun tdecl (_id2, decl) ->
{ tdecl with typ_type = decl }
) tdecls decls
in
(* Done *)
(final_decls, final_env)
(* Translating type extensions *)
let transl_extension_constructor ~scope env type_path type_params
typext_params priv sext =
let id = Ident.create_scoped ~scope sext.pext_name.txt in
let args, ret_type, kind =
match sext.pext_kind with
Pext_decl(svars, sargs, sret_type) ->
let targs, tret_type, args, ret_type =
make_constructor env sext.pext_loc type_path typext_params
svars sargs sret_type
in
args, ret_type, Text_decl(svars, targs, tret_type)