-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathtypedecl.ml
2942 lines (2764 loc) · 114 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 jkind_sort_loc = Cstr_tuple | Record | External
(* Our static analyses explore the set of type expressions "reachable"
from a type declaration, by expansion of definitions or by the
subterm relation (a type expression is syntactically contained
in another). *)
type reaching_type_path = reaching_type_step list
and reaching_type_step =
| Expands_to of type_expr * type_expr
| Contains of type_expr * type_expr
type error =
Repeated_parameter
| Duplicate_constructor of string
| Too_many_constructors
| Duplicate_label of string
| Recursive_abbrev of string * Env.t * reaching_type_path
| Cycle_in_def of string * Env.t * reaching_type_path
| 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;
reaching_path: reaching_type_path;
}
| 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
| Jkind_mismatch_of_type of type_expr * Jkind.Violation.t
| Jkind_mismatch_of_path of Path.t * Jkind.Violation.t
| Jkind_sort of
{ kloc : jkind_sort_loc
; typ : type_expr
; err : Jkind.Violation.t
}
| Jkind_empty_record
| Non_value_in_sig of Jkind.Violation.t * string
| Float64_in_block of type_expr * jkind_sort_loc
| Mixed_block
| Separability of Typedecl_separability.error
| Bad_unboxed_attribute of string
| Boxed_and_unboxed
| Nonrec_gadt
| Invalid_private_row_declaration of type_expr
| Local_not_enabled
| Layout_not_enabled of Jkind.const
open Typedtree
exception Error of Location.t * error
let jkind_of_attributes ~legacy_immediate ~context attrs =
match Jkind.of_attributes ~legacy_immediate ~context attrs with
| Ok l -> l
| Error { loc; txt } -> raise (Error (loc, Layout_not_enabled txt))
let jkind_of_attributes_default ~legacy_immediate ~context ~default attrs =
match Jkind.of_attributes_default ~legacy_immediate ~context ~default attrs with
| Ok l -> l
| Error { loc; txt } -> raise (Error (loc, Layout_not_enabled txt))
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
(* [make_params] creates sort variables - these can be defaulted away (as in
transl_type_decl) or unified with existing sort-variable-free types (as in
transl_with_constraint). *)
let make_params env path params =
TyVarEnv.reset (); (* [transl_type_param] binds type variables *)
let make_param (sty, v) =
try
(transl_type_param env path sty, v)
with Already_bound ->
raise(Error(sty.ptyp_loc, Repeated_parameter))
in
List.map make_param params
(* 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)
(* Add a dummy type declaration to the environment, with the given arity.
The [type_kind] is [Type_abstract], but there is a generic [type_manifest]
for abbreviations, to allow polymorphic expansion, except if
[abstract_abbrevs] is given along with a reason for not allowing expansion.
This function is only used in [transl_type_decl]. *)
let enter_type ?abstract_abbrevs 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
if not needed then env else
let arity = List.length sdecl.ptype_params in
let path = Path.Pident id in
(* There is some trickiness going on here with the jkind. It expands on an
old trick used in the manifest of [decl] below.
Consider a declaration like:
type t = foo list_of_values
and foo = Bar
When [enter_type] is called, we haven't yet analyzed anything about the
manifests and kinds of the declarations, so it's natural to give [t] and
[foo] jkind [Any]. But, while translating [t]'s manifest, we'll need to
know [foo] has jkind [value], because it is used as the argument to
[list_of_values]. And this check will occur before we've looked at [foo] at
all.
One can imagine solutions, like estimating the jkind based on the kind
(tricky for unboxed) or parameterizing the type_expr translation with an
option to not do full jkind checking in some cases and fix it up later
(ugly).
Instead, we build on an old trick that is used to handle constraints.
Consider declarations like:
type 'a t = 'a constraint 'a = ('b * 'c)
type s = r t
and r = int * string
Here we face a similar problem in the context of constraints. While
translating [s]'s manifest (which is [r t]), we'll need to know that [t]'s
constraint is satisfied (i.e., that [r] is a tuple). But we don't know
anything about [r] yet!
The solution, in three parts:
1) [enter_type], here, is used to construct [temp_env], an environment
where we set the manifest of recursively defined things like [s]
and [t] to just be a fresh type variable.
2) [transl_declaration] checks constraints in [temp_env]. This succeeds,
because [r]'s manifest is a variable and therefore unifies with
['b * 'c].
3) After we've built the real environment with the actual manifests
([new_env] in [transl_type_decl]), the function [update_type] checks
that the manifests from the old environment (here containing the
information that [r] must be some pair to satisfy the constraint) are
unified with the manifests from the new environment, ensuring the actual
definitions satisfy those constraints.
If [r] were, e.g., defined to be [int list], step 3 would fail.
To handle the original jkind example, we piggyback off that approach - the
jkind of the variable put in manifests here is updated when constraints
are checked and then unified with the real manifest and checked against the
kind. *)
let type_jkind =
(* We set ~legacy_immediate to true because we're looking at a declaration
that was already allowed to be [@@immediate] *)
jkind_of_attributes_default
~legacy_immediate:true ~context:(Type_declaration path)
~default:(Jkind.any ~why:Initial_typedecl_env)
sdecl.ptype_attributes
in
let abstract_reason, type_manifest =
match sdecl.ptype_manifest, abstract_abbrevs with
| (None, _ | Some _, None) -> Abstract_def, Some (Ctype.newvar type_jkind)
| Some _, Some reason -> reason, None
in
let type_params =
List.map (fun (param, _) ->
let name = get_type_param_name param in
let jkind = get_type_param_jkind path param in
Btype.newgenvar ?name jkind)
sdecl.ptype_params
in
let decl =
{ type_params;
type_arity = arity;
type_kind = Type_abstract abstract_reason;
type_jkind;
type_private = sdecl.ptype_private;
type_manifest;
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_unboxed_default = false;
type_uid = uid;
}
in
add_type ~check:true id decl env
(* [update_type] performs step 3 of the process described in the comment in
[enter_type]: We unify the manifest of each type with the definition of that
variable in [temp_env], which contains any requirements on the type implied
by its use in other mutually defined types.
In particular, we want to ensure that the manifest of this type has a jkind
compatible with its uses in mutually defined types. One subtlety is that we
don't actually perform those jkind checks here - we use
[Ctype.unify_delaying_jkind_checks] to record any needed jkind checks, but
don't perform them until slightly later in [transl_type_decl].
The reason for this delay is ill-formed, circular types. These haven't been
ruled out yet, and as a result jkind checking can fall into an infinite loop
where jkind checking expands types, and these type expansions in subst
trigger jkind checks that trigger type expansions that trigger jkind checks
that... These circular types are ruled out just after [update_type] in
[transl_type_decl], and then we perform the delayed checks.
*)
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 -> assert false
| Some ty ->
try
Ctype.(unify_delaying_jkind_checks env
(newconstr path decl.type_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. *)
(* CR layouts v2.5: Should we check for unboxed float here? Is a record with all
unboxed floats the same as a float record?
reisenberg: Yes. And actually a record mixing floats and unboxed floats is
also a float-record, and should be made to work. We'll have to make sure to
add the boxing operations in the right spot at projections, but that should
be possible.
*)
let is_float env ty =
match get_desc (Ctype.get_unboxed_type_approximation env ty) with
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
(* CR layouts upstreaming: The Ptyp_alias case also covers the case for a
jkind annotation, conveniently. When upstreaming jkinds, this
function will need a case for jkind-annotation aliases. *)
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 transl_global_flags loc attrs =
let transl_global_flag loc (r : (bool,unit) result) =
match r with
| Ok b -> b
| Error () -> raise(Error(loc, Local_not_enabled))
in
let global = transl_global_flag loc (Builtin_attributes.has_global attrs) in
match global with
| true -> Types.Global
| false -> Types.Unrestricted
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 Mode.Alloc.Const.legacy arg in
let gbl =
match mut with
| Mutable -> Types.Global
| Immutable -> transl_global_flags loc attrs
in
{ld_id = Ident.create_local name.txt;
ld_name = name; ld_mutable = mut; ld_global = gbl;
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_global = ld.ld_global;
ld_jkind = Jkind.any ~why:Dummy_jkind;
(* Updated by [update_label_jkinds] *)
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_types_gf env univars closed tyl =
let mk arg =
let cty = transl_simple_type env ?univars ~closed Mode.Alloc.Const.legacy arg in
let gf = transl_global_flags arg.ptyp_loc arg.ptyp_attributes in
(cty, gf)
in
let tyl_gfl = List.map mk tyl in
let tyl_gfl' = List.map (fun (cty, gf) -> cty.ctyp_type, gf) tyl_gfl in
tyl_gfl, tyl_gfl'
let transl_constructor_arguments env univars closed = function
| Pcstr_tuple l ->
let flds, flds' = transl_types_gf env univars closed l in
Types.Cstr_tuple flds',
Cstr_tuple flds
| Pcstr_record l ->
let lbls, lbls' = transl_labels env univars closed l in
Types.Cstr_record lbls',
Cstr_record lbls
(* Note that [make_constructor] does not fill in the [ld_jkind] field of any
computed record types, because it's called too early in the translation of a
type declaration to compute accurate jkinds in the presence of recursively
defined types. It is updated later by [update_constructor_arguments_jkinds]
*)
let make_constructor
env loc ~cstr_path ~type_path type_params (svars : _ Either.t)
sargs sret_type =
let tvars = match svars with
| Left vars_only -> List.map (fun v -> v.txt, None) vars_only
| Right vars_jkinds ->
List.map (fun (v, l) -> v.txt, Option.map Location.get_txt l) vars_jkinds
in
match sret_type with
| None ->
let args, targs =
transl_constructor_arguments env None true sargs
in
tvars, 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 *)
(* narrow and widen are now invoked through wrap_type_variable_scope *)
TyVarEnv.with_local_scope begin fun () ->
let closed =
match svars with
| Left [] | Right [] -> false
| _ -> true
in
let targs, tret_type, args, ret_type, _univars =
Ctype.with_local_level_if closed begin fun () ->
TyVarEnv.reset ();
let univar_list =
match svars with
| Left vars_only -> TyVarEnv.make_poly_univars vars_only
| Right vars_jkinds ->
TyVarEnv.make_poly_univars_jkinds
~context:(fun v -> Constructor_type_parameter (cstr_path, v))
vars_jkinds
in
let univars = if closed then Some univar_list else None in
let args, targs =
transl_constructor_arguments env univars closed sargs
in
let tret_type =
transl_simple_type env ?univars ~closed Mode.Alloc.Const.legacy
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;
(targs, tret_type, args, ret_type, univar_list)
end
~post: begin fun (_, _, args, ret_type, univars) ->
Btype.iter_type_expr_cstr_args Ctype.generalize args;
Ctype.generalize ret_type;
let _vars = TyVarEnv.instance_poly_univars env loc univars in
let set_level t = Ctype.enforce_current_level env t in
Btype.iter_type_expr_cstr_args set_level args;
set_level ret_type;
end
in
tvars, targs, Some tret_type, args, Some ret_type
end
let verify_unboxed_attr unboxed_attr sdecl =
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
(* Note [Default jkinds in transl_declaration]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For every type declaration we create in transl_declaration, we must
choose the jkind to use in the [type_jkind] field. Note that choices
2 and 3 below consult the jkinds of other types. In the case that these
types are declared in the same mutually recursive group, those jkinds
will be approximations; see the comments on [enter_type].
1. If there is a jkind annotation, use that. We might later compute a more
precise jkind for the type (e.g. [type t : value = int] or [type t :
value = A | B | C]); this will be updated in [update_decl_jkind] (updates
from the kind) or [check_coherence] (updates from the manifest), which
also ensures that the updated jkind is a subjkind of the annotated
jkind.
2. If there is no annotation but there is a manifest, use the jkind
of the manifest. This gets improved in [check_coherence], after
the manifest jkind might be more accurate.
3. If there is no annotation and no manifest, the default jkind
depends on the kind:
- Abstract types: In this case, we have a fully abstract type declaration,
like [type t]. We wish to default these to have jkind [value] for
backward compatibility.
- [@@unboxed] records and variants: We use [any] as the default.
This default gets updated in [update_decl_jkind], when we can
safely look up the jkind of the field. Recursive uses
of the unboxed type are OK, because [update_decl_jkind] uses
[Ctype.type_jkind], which looks through unboxed types (and thus
the choice of [any] is not observed on recursive occurrences).
- Other records and variants: The jkind of these depends on the jkinds
of their fields: an enumeration variant is an [immediate], and someday
(* CR layouts v5: today is the someday! *) we will allow records
comprising only [void]s, which will also be [immediate].
So we choose a default of [value], which gets updated in
[update_decl_jkind]. This default choice does get used when updating
the jkinds of other types that (recursively) mention the current type,
but that's OK: the update in [update_decl_jkind] can only change a
[value] to become [immediate], and yet that change can never affect
the decision of whether an outer record/variant is a [value] or
[immediate] (only choices of [void] can do that).
(Again, any unboxed records/variants are looked through by
[type_jkind], so a void one of those is OK.)
It is tempting to use [any] as the default here, but that causes
trouble around recursive occurrences in [update_decl_jkind].
- Extensible variants: These really are [value]s, so we just use
that as the default.
The jkinds in type declarations are always just upper bounds, as
we see in this example:
{[
type t7 = A | B | C | D of t7_void
and t7_2 = { x : t7 } [@@unboxed]
and t7_void [@@void]
type t7_3 = t7_2 [@@immediate]
]}
The proper jkind of [t7] is [immediate], but that's hard to know. Because
[t7] has no jkind annotation and no manifest, it gets a default jkind
of [value]. [t7_2] gets a default of [any]. We update [t7]'s jkind to be
[immediate] in [update_decl_jkind]. But when updating [t7_2]'s jkind, we
use the *original, default* jkind for [t7]: [value]. This means that the
jkind recorded for [t7_2] is actually [value]. The program above is still
accepted, because the jkind check in [check_coherence] uses [type_jkind],
which looks through unboxed types. So it's all OK for users, but it's
unfortunate that the stored jkind on [t7_2] is imprecise.
(* CR layouts: see if we can do better here. *)
*)
let transl_declaration env sdecl (id, uid) =
(* Bind type parameters *)
Ctype.with_local_level begin fun () ->
TyVarEnv.reset();
let path = Path.Pident id in
let tparams = make_params env path 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 ~closed:false Mode.Alloc.Const.legacy sty,
transl_simple_type env ~closed:false Mode.Alloc.Const.legacy sty', loc)
sdecl.ptype_cstrs
in
let unboxed_attr = get_unboxed_from_attributes sdecl in
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
verify_unboxed_attr unboxed_attr sdecl;
let jkind_annotation =
(* We set legacy_immediate to true because you were already allowed to write
[@@immediate] on declarations. *)
jkind_of_attributes ~legacy_immediate:true ~context:(Type_declaration path)
sdecl.ptype_attributes
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 ~closed:no_row Mode.Alloc.Const.legacy sty in
Some cty, Some cty.ctyp_type
in
let any = Jkind.any ~why:Initial_typedecl_env in
(* jkind_default is the jkind to use for now as the type_jkind when there
is no annotation and no manifest.
See Note [Default jkinds in transl_declaration].
*)
let (tkind, kind, jkind_default) =
match sdecl.ptype_kind with
| Ptype_abstract ->
Ttype_abstract, Type_abstract Abstract_def, Jkind.value ~why:Default_type_jkind
| 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 svars, attributes =
match Jane_syntax.Layouts.of_constructor_declaration scstr with
| None ->
Either.Left scstr.pcd_vars,
scstr.pcd_attributes
| Some (vars_jkinds, attributes) ->
Either.Right vars_jkinds,
attributes
in
let tvars, targs, tret_type, args, ret_type =
make_constructor env scstr.pcd_loc
~cstr_path:(Path.Pident name) ~type_path:path params
svars scstr.pcd_args scstr.pcd_res
in
let tcstr =
{ cd_id = name;
cd_name = scstr.pcd_name;
cd_vars = tvars;
cd_args = targs;
cd_res = tret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = attributes }
in
let cstr =
{ Types.cd_id = name;
cd_args = args;
cd_res = ret_type;
cd_loc = scstr.pcd_loc;
cd_attributes = 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 tcstrs, cstrs = List.split (List.map make_cstr scstrs) in
let rep, jkind =
if unbox then
Variant_unboxed, any
else
(* We mark all arg jkinds "any" here. They are updated later,
after the circular type checks make it safe to check jkinds. *)
Variant_boxed (
Array.map
(fun cstr ->
match Types.(cstr.cd_args) with
| Cstr_tuple args ->
Array.make (List.length args) any
| Cstr_record _ -> [| any |])
(Array.of_list cstrs)
),
Jkind.value ~why:Boxed_variant
in
Ttype_variant tcstrs, Type_variant (cstrs, rep), jkind
| Ptype_record lbls ->
let lbls, lbls' = transl_labels env None true lbls in
let rep, jkind =
if unbox then
Record_unboxed, any
else (if List.for_all (fun l -> is_float env l.Types.ld_type) lbls'
then Record_float
else Record_boxed (Array.make (List.length lbls) any)),
Jkind.value ~why:Boxed_record
in
Ttype_record lbls, Type_record(lbls', rep), jkind
| Ptype_open ->
Ttype_open, Type_open, Jkind.value ~why:Extensible_variant
in
let jkind =
(* - If there's an annotation, we use that. It's checked against
a kind in [update_decl_jkind] and the manifest in [check_coherence].
- If there's no annotation but there is a manifest, we estimate the
jkind based on the manifest here. This upper bound saves time
later by avoiding expanding the manifest in jkind checks, but it
would be sound to leave in `any`. We can't give a perfectly
accurate jkind here because we don't have access to the
manifests of mutually defined types (but we could one day consider
improving it at a later point in transl_type_decl).
- If there's no annotation and no manifest, we fill in with the
default calculated above here. It will get updated in
[update_decl_jkind]. See Note [Default jkinds in transl_declaration].
*)
(* CR layouts: Is the estimation mentioned in the second bullet above
doing anything for us? Abstract types are updated by
check_coherence and record/variant types are updated by
update_decl_jkind. *)
match jkind_annotation, man with
| Some annot, _ -> annot
| None, Some typ -> Ctype.estimate_type_jkind env typ
| None, None -> jkind_default
in
let arity = List.length params in
let decl =
{ type_params = params;
type_arity = arity;
type_kind = kind;
type_jkind = jkind;
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_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;
(* 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;
}
end
(* 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. *)
match Ctype.matches ~expand_error_trace:false env ty ty' with
| Unification_failure err ->
raise (Error(loc, Constraint_failed (env, err)))
| Jkind_mismatch { original_jkind; inferred_jkind; ty } ->
raise (Error(loc, Jkind_mismatch_of_type (ty,
(Jkind.Violation.of_ (Not_a_subjkind
(original_jkind, inferred_jkind))))))
| All_good -> ()
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
(* CR layouts v5: when we add the "mixed block restriction", we'll
probably want to check it here. *)
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
(*
Check that the type expression (if present) is compatible with the kind.
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.
If the kind is [Type_abstract], we need to check that [type_jkind] (where
we've stored the jkind annotation, if any) corresponds to the manifest
(e.g., in the case where [type_jkind] is immediate, we should check the
manifest is immediate). It would also be nice to store the best possible
jkind for this type in the kind, to avoid expansions later. So, we do the
relatively expensive thing of computing the best possible jkind for the
manifest, checking that it's a subjkind of [type_jkind], and then replacing
[type_jkind] with what we computed.
CR layouts: if easy, factor out the shared backtracking logic from here
and is_immediate.
*)
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)))
else
decl
with Not_found ->
raise(Error(loc, Unavailable_type_constructor path))
end
| _ -> raise(Error(loc, Definition_mismatch (ty, env, None)))
end
| { type_kind = Type_abstract _;
type_manifest = Some ty } ->
let jkind' =
if !Clflags.principal || Env.has_local_constraints env then