-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathtypetexp.ml
1457 lines (1350 loc) · 53.8 KB
/
typetexp.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, 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. *)
(* *)
(**************************************************************************)
(* typetexp.ml,v 1.34.4.9 2002/01/07 08:39:16 garrigue Exp *)
(* Typechecking of type expressions for the core language *)
open Asttypes
open Jane_asttypes
open Misc
open Parsetree
open Typedtree
open Types
open Mode
open Ctype
exception Already_bound
type value_loc =
Tuple | Poly_variant | Package_constraint | Object_field
type sort_loc =
Fun_arg | Fun_ret
type cannot_quantify_reason =
| Unified of type_expr
| Univar
| Scope_escape
(* a description of the jkind on an explicitly quantified universal
variable, containing whether the jkind was a default
(e.g. [let f : 'a. 'a -> 'a = ...]) or explicit
(e.g. [let f : ('a : immediate). ...]) and what the jkind was;
it is original as compared to the inferred jkind after processing
the body of the type *)
type jkind_info = { original_jkind : jkind; defaulted : bool }
type error =
| Unbound_type_variable of string * string list
| No_type_wildcards
| Undefined_type_constructor of Path.t
| Type_arity_mismatch of Longident.t * int * int
| Bound_type_variable of string
| Recursive_type
| Unbound_row_variable of Longident.t
| Type_mismatch of Errortrace.unification_error
| Alias_type_mismatch of Errortrace.unification_error
| Present_has_conjunction of string
| Present_has_no_type of string
| Constructor_mismatch of type_expr * type_expr
| Not_a_variant of type_expr
| Variant_tags of string * string
| Invalid_variable_name of string
| Cannot_quantify of string * cannot_quantify_reason
| Bad_univar_jkind of
{ name : string; jkind_info : jkind_info; inferred_jkind : jkind }
| Multiple_constraints_on_type of Longident.t
| Method_mismatch of string * type_expr * type_expr
| Opened_object of Path.t option
| Not_an_object of type_expr
| Unsupported_extension : _ Language_extension.t -> error
| Polymorphic_optional_param
| Non_value of
{vloc : value_loc; typ : type_expr; err : Jkind.Violation.t}
| Non_sort of
{vloc : sort_loc; typ : type_expr; err : Jkind.Violation.t}
| Bad_jkind_annot of type_expr * Jkind.Violation.t
| Did_you_mean_unboxed of Longident.t
exception Error of Location.t * Env.t * error
exception Error_forward of Location.error
module TyVarEnv : sig
val reset : unit -> unit
(* see mli file *)
val is_in_scope : string -> bool
val add : string -> type_expr -> unit
(* add a global type variable to the environment *)
val with_local_scope : (unit -> 'a) -> 'a
(* see mli file *)
type poly_univars
val with_univars : poly_univars -> (unit -> 'a) -> 'a
(* evaluate with a locally extended set of univars *)
val make_poly_univars : string Location.loc list -> poly_univars
(* a version of [make_poly_univars_jkinds] that doesn't take jkinds *)
val make_poly_univars_jkinds :
context:(string -> Jkind.annotation_context) ->
(string Location.loc * jkind_annotation option) list -> poly_univars
(* see mli file *)
val check_poly_univars : Env.t -> Location.t -> poly_univars -> type_expr list
(* see mli file *)
val instance_poly_univars :
Env.t -> Location.t -> poly_univars -> type_expr list
(* see mli file *)
type policy
val fixed_policy : policy (* no wildcards allowed *)
val extensible_policy : policy (* common case *)
val univars_policy : policy (* fresh variables are univars (in methods) *)
val new_any_var : Location.t -> Env.t -> Jkind.t -> policy -> type_expr
(* create a new variable to represent a _; fails for fixed_policy *)
val new_var : ?name:string -> Jkind.t -> policy -> type_expr
(* create a new variable according to the given policy *)
val add_pre_univar : type_expr -> policy -> unit
(* remember that a variable might become a univar if it isn't unified;
used for checking method types *)
val collect_univars : (unit -> 'a) -> 'a * type_expr list
(* collect univars during a computation; returns the univars.
The wrapped computation should use [univars_policy].
postcondition: the returned type_exprs are all Tunivar *)
val reset_locals : ?univars:poly_univars -> unit -> unit
(* clear out the local type variable env't; call this when starting
a new e.g. type signature. Optionally pass some univars that
are in scope. *)
val lookup_local :
row_context:type_expr option ref list -> string -> type_expr
(* look up a local type variable; throws Not_found if it isn't in scope *)
val remember_used : string -> type_expr -> Location.t -> unit
(* remember that a given name is bound to a given type *)
val globalize_used_variables : policy -> Env.t -> unit -> unit
(* after finishing with a type signature, used variables are unified to the
corresponding global type variables if they exist. Otherwise, in function
of the policy, fresh used variables are either
- added to the global type variable scope if they are not longer
variables under the {!fixed_policy}
- added to the global type variable scope under the {!extensible_policy}
- expected to be collected later by a call to `collect_univar` under the
{!universal_policy}
*)
end = struct
(** Map indexed by type variable names. *)
module TyVarMap = Misc.Stdlib.String.Map
let not_generic v = get_level v <> Btype.generic_level
(* These are the "global" type variables: they were in scope before
we started processing the current type.
*)
let type_variables = ref (TyVarMap.empty : type_expr TyVarMap.t)
(* These are variables that have been used in the currently-being-checked
type, possibly including the variables in [type_variables].
*)
let used_variables =
ref (TyVarMap.empty : (type_expr * Location.t) TyVarMap.t)
(* These are variables that will become univars when we're done with the
current type. Used to force free variables in method types to become
univars.
*)
let pre_univars = ref ([] : type_expr list)
let reset () =
reset_global_level ();
type_variables := TyVarMap.empty
let is_in_scope name =
TyVarMap.mem name !type_variables
let add name v =
assert (not_generic v);
type_variables := TyVarMap.add name v !type_variables
let narrow () =
(increase_global_level (), !type_variables)
let widen (gl, tv) =
restore_global_level gl;
type_variables := tv
let with_local_scope f =
let context = narrow () in
Fun.protect
f
~finally:(fun () -> widen context)
(* throws Not_found if the variable is not in scope *)
let lookup_global_type_variable name =
TyVarMap.find name !type_variables
let get_in_scope_names () =
let add_name name _ l = if name = "_" then l else ("'" ^ name) :: l in
TyVarMap.fold add_name !type_variables []
(*****)
(* These are variables we expect to become univars (they were introduced with
e.g. ['a .]), but we need to make sure they don't unify first. Why not
just birth them as univars? Because they might successfully unify with a
row variable in the ['a. < m : ty; .. > as 'a] idiom. They are like the
[used_variables], but will not be globalized in [globalize_used_variables].
*)
type pending_univar = {
univar: type_expr (** the univar itself *);
mutable associated: type_expr option ref list;
(** associated references to row variables that we want to generalize
if possible *)
jkind_info : jkind_info (** the original kind *)
}
type poly_univars = (string * pending_univar) list
let univars = ref ([] : poly_univars)
let assert_univars uvs =
assert (List.for_all (fun (_name, v) -> not_generic v.univar) uvs)
let rec find_poly_univars name = function
| [] -> raise Not_found
| (n, t) :: rest ->
if String.equal name n
then t
else find_poly_univars name rest
let with_univars new_ones f =
assert_univars new_ones;
let old_univars = !univars in
univars := new_ones @ !univars;
Fun.protect
f
~finally:(fun () -> univars := old_univars)
let mk_pending_univar name jkind jkind_info =
{ univar = newvar ~name jkind; associated = []; jkind_info }
let mk_poly_univars_tuple_with_jkind ~context var jkind =
let name = var.txt in
let original_jkind = Jkind.of_annotation ~context:(context name) jkind in
let jkind_info = { original_jkind; defaulted = false } in
name, mk_pending_univar name original_jkind jkind_info
let mk_poly_univars_tuple_without_jkind var =
let name = var.txt in
let original_jkind = Jkind.value ~why:Univar in
let jkind_info = { original_jkind; defaulted = true } in
name, mk_pending_univar name original_jkind jkind_info
let make_poly_univars vars =
List.map mk_poly_univars_tuple_without_jkind vars
let make_poly_univars_jkinds ~context vars_jkinds =
let mk_trip = function
| (v, None) -> mk_poly_univars_tuple_without_jkind v
| (v, Some l) -> mk_poly_univars_tuple_with_jkind ~context v l
in
List.map mk_trip vars_jkinds
let promote_generics_to_univars promoted vars =
List.fold_left
(fun acc v ->
match get_desc v with
| Tvar { name; jkind } when get_level v = Btype.generic_level ->
set_type_desc v (Tunivar { name; jkind });
v :: acc
| _ -> acc
)
promoted vars
let check_poly_univars env loc vars =
vars |> List.iter (fun (_, p) -> generalize p.univar);
let univars =
vars |> List.map (fun (name, {univar=ty1; jkind_info; _ }) ->
let v = Btype.proxy ty1 in
let cant_quantify reason =
raise (Error (loc, env, Cannot_quantify(name, reason)))
in
begin match get_desc v with
| Tvar { jkind } when
not (Jkind.equate jkind jkind_info.original_jkind) ->
let reason =
Bad_univar_jkind { name; jkind_info; inferred_jkind = jkind }
in
raise (Error (loc, env, reason))
| Tvar _ when get_level v <> Btype.generic_level ->
cant_quantify Scope_escape
| Tvar { name; jkind } ->
set_type_desc v (Tunivar { name; jkind })
| Tunivar _ ->
cant_quantify Univar
| _ ->
cant_quantify (Unified v)
end;
v)
in
(* Since we are promoting variables to univars in
{!promote_generics_to_univars}, even if a row variable is associated with
multiple univars we will promote it once, when checking the nearest
univar associated to this row variable.
*)
let promote_associated acc (_,v) =
let enclosed_rows = List.filter_map (!) v.associated in
promote_generics_to_univars acc enclosed_rows
in
List.fold_left promote_associated univars vars
let instance_poly_univars env loc vars =
let vs = check_poly_univars env loc vars in
vs |> List.iter (fun v ->
match get_desc v with
| Tunivar { name; jkind } ->
set_type_desc v (Tvar { name; jkind })
| _ -> assert false);
vs
(*****)
let reset_locals ?univars:(uvs=[]) () =
assert_univars uvs;
univars := uvs;
used_variables := TyVarMap.empty
let associate row_context p =
let add l x = if List.memq x l then l else x :: l in
p.associated <- List.fold_left add row_context p.associated
(* throws Not_found if the variable is not in scope *)
let lookup_local ~row_context name =
try
let p = find_poly_univars name !univars in
associate row_context p;
p.univar
with Not_found ->
instance (fst (TyVarMap.find name !used_variables))
(* This call to instance might be redundant; all variables
inserted into [used_variables] are non-generic, but some
might get generalized. *)
let remember_used name v loc =
assert (not_generic v);
used_variables := TyVarMap.add name (v, loc) !used_variables
type flavor = Unification | Universal
type extensibility = Extensible | Fixed
type policy = { flavor : flavor; extensibility : extensibility }
let fixed_policy = { flavor = Unification; extensibility = Fixed }
let extensible_policy = { flavor = Unification; extensibility = Extensible }
let univars_policy = { flavor = Universal; extensibility = Extensible }
let add_pre_univar tv = function
| { flavor = Universal } ->
assert (not_generic tv);
pre_univars := tv :: !pre_univars
| _ -> ()
let collect_univars f =
pre_univars := [];
let result = f () in
let univs = promote_generics_to_univars [] !pre_univars in
result, univs
let new_var ?name jkind policy =
let tv = Ctype.newvar ?name jkind in
add_pre_univar tv policy;
tv
let new_any_var loc env jkind = function
| { extensibility = Fixed } -> raise(Error(loc, env, No_type_wildcards))
| policy -> new_var jkind policy
let globalize_used_variables { flavor; extensibility } env =
let r = ref [] in
TyVarMap.iter
(fun name (ty, loc) ->
if flavor = Unification || is_in_scope name then
let v = new_global_var (Jkind.any ~why:Dummy_jkind) in
let snap = Btype.snapshot () in
if try unify env v ty; true with _ -> Btype.backtrack snap; false
then try
r := (loc, v, lookup_global_type_variable name) :: !r
with Not_found ->
if extensibility = Fixed && Btype.is_Tvar ty then
raise(Error(loc, env,
Unbound_type_variable ("'"^name,
get_in_scope_names ())));
let v2 = new_global_var (Jkind.any ~why:Dummy_jkind) in
r := (loc, v, v2) :: !r;
add name v2)
!used_variables;
used_variables := TyVarMap.empty;
fun () ->
List.iter
(function (loc, t1, t2) ->
try unify env t1 t2 with Unify err ->
raise (Error(loc, env, Type_mismatch err)))
!r
end
(* Support for first-class modules. *)
let transl_modtype_longident = ref (fun _ -> assert false)
let transl_modtype = ref (fun _ -> assert false)
let sort_constraints_no_duplicates loc env l =
List.sort
(fun (s1, _t1) (s2, _t2) ->
if s1.txt = s2.txt then
raise (Error (loc, env, Multiple_constraints_on_type s1.txt));
compare s1.txt s2.txt)
l
let create_package_mty loc p l =
List.fold_left
(fun mty (s, _) ->
let d = {ptype_name = mkloc (Longident.last s.txt) s.loc;
ptype_params = [];
ptype_cstrs = [];
ptype_kind = Ptype_abstract;
ptype_private = Asttypes.Public;
ptype_manifest = None;
ptype_attributes = [];
ptype_loc = loc} in
Ast_helper.Mty.mk ~loc
(Pmty_with (mty, [ Pwith_type ({ txt = s.txt; loc }, d) ]))
)
(Ast_helper.Mty.mk ~loc (Pmty_ident p))
l
(* Translation of type expressions *)
let generalize_ctyp typ = generalize typ.ctyp_type
let strict_ident c = (c = '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
let validate_name = function
None -> None
| Some name as s ->
if name <> "" && strict_ident name.[0] then s else None
let new_global_var ?name jkind =
new_global_var ?name:(validate_name name) jkind
let newvar ?name jkind =
newvar ?name:(validate_name name) jkind
let valid_tyvar_name name =
name <> "" && name.[0] <> '_'
let transl_type_param_var env loc attrs name_opt
(jkind : jkind) (jkind_annot : const_jkind option) =
let tvar = Ttyp_var (name_opt, jkind_annot) in
let name =
match name_opt with
| None -> "_"
| Some name ->
if not (valid_tyvar_name name) then
raise (Error (loc, Env.empty, Invalid_variable_name ("'" ^ name)));
if TyVarEnv.is_in_scope name then
raise Already_bound;
name
in
let ty = new_global_var ~name jkind in
Option.iter (fun name -> TyVarEnv.add name ty) name_opt;
{ ctyp_desc = tvar; ctyp_type = ty; ctyp_env = env;
ctyp_loc = loc; ctyp_attributes = attrs }
let transl_type_param_jst env loc attrs path :
Jane_syntax.Core_type.t -> _ =
function
| Jtyp_layout (Ltyp_var { name; jkind = annot }) ->
let jkind =
Jkind.of_annotation ~context:(Type_parameter (path, name)) annot
in
transl_type_param_var env loc attrs name jkind (Some annot.txt)
| Jtyp_layout (Ltyp_poly _ | Ltyp_alias _) ->
Misc.fatal_error "non-type-variable in transl_type_param_jst"
let transl_type_param env path styp =
let loc = styp.ptyp_loc in
match Jane_syntax.Core_type.of_ast styp with
| Some (etyp, attrs) -> transl_type_param_jst env loc attrs path etyp
| None ->
(* Our choice for now is that if you want a parameter of jkind any, you have
to ask for it with an annotation. Some restriction here seems necessary
for backwards compatibility (e.g., we wouldn't want [type 'a id = 'a] to
have jkind any). But it might be possible to infer any in some cases. *)
let jkind = Jkind.of_new_sort ~why:Unannotated_type_parameter in
let attrs = styp.ptyp_attributes in
match styp.ptyp_desc with
Ptyp_any -> transl_type_param_var env loc attrs None jkind None
| Ptyp_var name ->
transl_type_param_var env loc attrs (Some name) jkind None
| _ -> assert false
let transl_type_param env path styp =
(* Currently useless, since type parameters cannot hold attributes
(but this could easily be lifted in the future). *)
Builtin_attributes.warning_scope styp.ptyp_attributes
(fun () -> transl_type_param env path styp)
let get_type_param_jkind path styp =
match Jane_syntax.Core_type.of_ast styp with
| None -> Jkind.of_new_sort ~why:Unannotated_type_parameter
| Some (Jtyp_layout (Ltyp_var { name; jkind }), _attrs) ->
Jkind.of_annotation ~context:(Type_parameter (path, name)) jkind
| Some _ -> Misc.fatal_error "non-type-variable in get_type_param_jkind"
let get_type_param_name styp =
(* We don't need to check for jane-syntax here, just to get the
name. *)
match styp.ptyp_desc with
| Ptyp_any -> None
| Ptyp_var name -> Some name
| _ -> Misc.fatal_error "non-type-variable in get_type_param_name"
let get_alloc_mode styp =
let locality =
match Builtin_attributes.has_local styp.ptyp_attributes with
| Ok true -> Locality.Const.Local
| Ok false -> Locality.Const.Global
| Error () ->
raise (Error(styp.ptyp_loc, Env.empty, Unsupported_extension Local))
in
let uniqueness =
match Builtin_attributes.has_unique styp.ptyp_attributes with
| Ok true -> Uniqueness.Const.Unique
| Ok false -> Uniqueness.Const.Shared
| Error () ->
raise (Error(styp.ptyp_loc, Env.empty, Unsupported_extension Unique))
in
let linearity =
match Builtin_attributes.has_once styp.ptyp_attributes with
| Ok true -> Linearity.Const.Once
| Ok false -> Linearity.Const.Many
| Error () ->
raise (Error(styp.ptyp_loc, Env.empty, Unsupported_extension Unique))
in
{ locality = locality; uniqueness; linearity }
let rec extract_params styp =
let final styp =
[], styp, get_alloc_mode styp
in
match styp.ptyp_desc with
| Ptyp_arrow (l, a, r) ->
let arg_mode = get_alloc_mode a in
let params, ret, ret_mode =
if Builtin_attributes.has_curry r.ptyp_attributes then final r
else extract_params r
in
(l, arg_mode, a) :: params, ret, ret_mode
| _ -> final styp
let check_arg_type styp =
if not (Language_extension.is_enabled Polymorphic_parameters) then begin
match styp.ptyp_desc with
| Ptyp_poly _ ->
raise (Error (styp.ptyp_loc, Env.empty,
Unsupported_extension Polymorphic_parameters))
| _ -> ()
end
(* translate the ['a 'b ('c : immediate) .] part of a polytype,
returning something suitable as the first argument of Ttyp_poly and
a [poly_univars] *)
let transl_bound_vars : (_, _) Either.t -> _ =
let mk_one v = v.txt, None in
let mk_pair (v, l) = v.txt, Option.map Location.get_txt l in
function
| Left vars_only -> List.map mk_one vars_only,
TyVarEnv.make_poly_univars vars_only
| Right vars_jkinds -> List.map mk_pair vars_jkinds,
TyVarEnv.make_poly_univars_jkinds
~context:(fun v -> Univar v) vars_jkinds
let rec transl_type env ~policy ?(aliased=false) ~row_context mode styp =
Builtin_attributes.warning_scope styp.ptyp_attributes
(fun () -> transl_type_aux env ~policy ~aliased ~row_context mode styp)
and transl_type_aux env ~row_context ~aliased ~policy mode styp =
let loc = styp.ptyp_loc in
let ctyp ctyp_desc ctyp_type =
{ ctyp_desc; ctyp_type; ctyp_env = env;
ctyp_loc = loc; ctyp_attributes = styp.ptyp_attributes }
in
match Jane_syntax.Core_type.of_ast styp with
| Some (etyp, attrs) ->
let desc, typ =
transl_type_aux_jst env ~policy ~row_context mode attrs loc etyp
in
ctyp desc typ
| None ->
match styp.ptyp_desc with
Ptyp_any ->
let ty =
TyVarEnv.new_any_var loc env (Jkind.any ~why:Wildcard) policy
in
ctyp (Ttyp_var (None, None)) ty
| Ptyp_var name ->
let desc, typ =
transl_type_var env ~policy ~row_context styp.ptyp_loc name None
in
ctyp desc typ
| Ptyp_arrow _ ->
let args, ret, ret_mode = extract_params styp in
let rec loop acc_mode args =
match args with
| (l, arg_mode, arg) :: rest ->
check_arg_type arg;
let arg_cty = transl_type env ~policy ~row_context arg_mode arg in
let acc_mode =
Alloc.Const.join
(Alloc.Const.close_over arg_mode)
(Alloc.Const.partial_apply acc_mode)
in
let acc_mode =
Alloc.Const.join acc_mode
(Alloc.Const.min_with_uniqueness Uniqueness.Const.Shared)
in
let ret_mode =
match rest with
| [] -> ret_mode
| _ :: _ -> acc_mode
in
let ret_cty = loop acc_mode rest in
let arg_ty = arg_cty.ctyp_type in
let arg_ty =
if Btype.is_Tpoly arg_ty then arg_ty else newmono arg_ty
in
let arg_ty =
if not (Btype.is_optional l) then arg_ty
else begin
if not (Btype.tpoly_is_mono arg_ty) then
raise (Error (arg.ptyp_loc, env, Polymorphic_optional_param));
newmono
(newconstr Predef.path_option [Btype.tpoly_get_mono arg_ty])
end
in
let arg_mode = Alloc.of_const arg_mode in
let ret_mode = Alloc.of_const ret_mode in
let arrow_desc = (l, arg_mode, ret_mode) in
(* CR layouts v3: For now, we require function arguments and returns
to have a representable jkind. See comment in
[Ctype.filter_arrow]. *)
begin match
Ctype.type_sort ~why:Function_argument env arg_ty,
Ctype.type_sort ~why:Function_result env ret_cty.ctyp_type
with
| Ok _, Ok _ -> ()
| Error e, _ ->
raise (Error(arg.ptyp_loc, env,
Non_sort {vloc = Fun_arg; err = e; typ = arg_ty}))
| _, Error e ->
raise (Error(ret.ptyp_loc, env,
Non_sort
{vloc = Fun_ret; err = e; typ = ret_cty.ctyp_type}))
end;
let ty =
newty (Tarrow(arrow_desc, arg_ty, ret_cty.ctyp_type, commu_ok))
in
ctyp (Ttyp_arrow (l, arg_cty, ret_cty)) ty
| [] -> transl_type env ~policy ~row_context ret_mode ret
in
loop mode args
| Ptyp_tuple stl ->
assert (List.length stl >= 2);
let ctys =
List.map (transl_type env ~policy ~row_context Alloc.Const.legacy) stl
in
List.iter (fun {ctyp_type; ctyp_loc} ->
(* CR layouts v5: remove value requirement *)
match
constrain_type_jkind
env ctyp_type (Jkind.value ~why:Tuple_element)
with
| Ok _ -> ()
| Error e ->
raise (Error(ctyp_loc, env,
Non_value {vloc = Tuple; err = e; typ = ctyp_type})))
ctys;
let ty = newty (Ttuple (List.map (fun ctyp -> ctyp.ctyp_type) ctys)) in
ctyp (Ttyp_tuple ctys) ty
| Ptyp_constr(lid, stl) ->
let (path, decl) = Env.lookup_type ~loc:lid.loc lid.txt env in
let stl =
match stl with
| [ {ptyp_desc=Ptyp_any} as t ] when decl.type_arity > 1 ->
List.map (fun _ -> t) decl.type_params
| _ -> stl
in
if List.length stl <> decl.type_arity then
raise(Error(styp.ptyp_loc, env,
Type_arity_mismatch(lid.txt, decl.type_arity,
List.length stl)));
let args =
List.map (transl_type env ~policy ~row_context Alloc.Const.legacy) stl
in
let params = instance_list decl.type_params in
let unify_param =
match decl.type_manifest with
None -> unify_var
| Some ty ->
if get_level ty = Btype.generic_level then unify_var else unify
in
List.iter2
(fun (sty, cty) ty' ->
try unify_param env ty' cty.ctyp_type with Unify err ->
let err = Errortrace.swap_unification_error err in
raise (Error(sty.ptyp_loc, env, Type_mismatch err))
)
(List.combine stl args) params;
let constr =
newconstr path (List.map (fun ctyp -> ctyp.ctyp_type) args) in
ctyp (Ttyp_constr (path, lid, args)) constr
| Ptyp_object (fields, o) ->
let ty, fields = transl_fields env ~policy ~row_context o fields in
ctyp (Ttyp_object (fields, o)) (newobj ty)
| Ptyp_class(lid, stl) ->
let (path, decl) =
match Env.lookup_cltype ~loc:lid.loc lid.txt env with
| (path, decl) -> (path, decl.clty_hash_type)
(* Raise a different error if it matches the name of an unboxed type *)
| exception
(Env.Error (Lookup_error (_, _, Unbound_cltype _)) as exn)
->
let unboxed_lid : Longident.t =
match lid.txt with
| Lident s -> Lident (s ^ "#")
| Ldot (l, s) -> Ldot (l, s ^ "#")
| Lapply _ -> fatal_error "Typetexp.transl_type"
in
match Env.find_type_by_name unboxed_lid env with
| exception Not_found -> raise exn
| (_ : _ * _) ->
raise (Error (styp.ptyp_loc, env, Did_you_mean_unboxed lid.txt))
in
if List.length stl <> decl.type_arity then
raise(Error(styp.ptyp_loc, env,
Type_arity_mismatch(lid.txt, decl.type_arity,
List.length stl)));
let args =
List.map (transl_type env ~policy ~row_context Alloc.Const.legacy) stl
in
let body = Option.get decl.type_manifest in
let (params, body) = instance_parameterized_type decl.type_params body in
List.iter2
(fun (sty, cty) ty' ->
try unify_var env ty' cty.ctyp_type with Unify err ->
let err = Errortrace.swap_unification_error err in
raise (Error(sty.ptyp_loc, env, Type_mismatch err))
)
(List.combine stl args) params;
let ty_args = List.map (fun ctyp -> ctyp.ctyp_type) args in
let ty = Ctype.apply ~use_current_level:true env params body ty_args in
let ty = match get_desc ty with
| Tobject (fi, _) ->
let _, tv = flatten_fields fi in
TyVarEnv.add_pre_univar tv policy;
ty
| _ ->
assert false
in
ctyp (Ttyp_class (path, lid, args)) ty
| Ptyp_alias(st, alias) ->
let desc, typ =
transl_type_alias env ~policy ~row_context mode loc st (Some alias) None
in
ctyp desc typ
| Ptyp_variant(fields, closed, present) ->
let name = ref None in
let mkfield l f =
newty (Tvariant (create_row ~fields:[l,f]
~more:(newvar (Jkind.value ~why:Row_variable))
~closed:true ~fixed:None ~name:None)) in
let hfields = Hashtbl.create 17 in
let add_typed_field loc l f =
let h = Btype.hash_variant l in
try
let (l',f') = Hashtbl.find hfields h in
(* Check for tag conflicts *)
if l <> l' then raise(Error(styp.ptyp_loc, env, Variant_tags(l, l')));
let ty = mkfield l f and ty' = mkfield l f' in
if is_equal env false [ty] [ty'] then () else
try unify env ty ty'
with Unify _trace ->
raise(Error(loc, env, Constructor_mismatch (ty,ty')))
with Not_found ->
Hashtbl.add hfields h (l,f)
in
let add_field row_context field =
let rf_loc = field.prf_loc in
let rf_attributes = field.prf_attributes in
let rf_desc = match field.prf_desc with
| Rtag (l, c, stl) ->
name := None;
let tl =
Builtin_attributes.warning_scope rf_attributes
(fun () ->
List.map
(transl_type env ~policy ~row_context Alloc.Const.legacy)
stl)
in
List.iter (fun {ctyp_type; ctyp_loc} ->
(* CR layouts: at some point we'll allow different jkinds in
polymorphic variants. *)
match
constrain_type_jkind env ctyp_type
(Jkind.value ~why:Polymorphic_variant_field)
with
| Ok _ -> ()
| Error e ->
raise (Error(ctyp_loc, env,
Non_value {vloc = Poly_variant; err = e;
typ = ctyp_type})))
tl;
let f = match present with
Some present when not (List.mem l.txt present) ->
let ty_tl = List.map (fun cty -> cty.ctyp_type) tl in
rf_either ty_tl ~no_arg:c ~matched:false
| _ ->
if List.length stl > 1 || c && stl <> [] then
raise(Error(styp.ptyp_loc, env,
Present_has_conjunction l.txt));
match tl with [] -> rf_present None
| st :: _ -> rf_present (Some st.ctyp_type)
in
add_typed_field styp.ptyp_loc l.txt f;
Ttag (l,c,tl)
| Rinherit sty ->
let cty =
transl_type env ~policy ~row_context Alloc.Const.legacy sty
in
let ty = cty.ctyp_type in
let nm =
match get_desc cty.ctyp_type with
Tconstr(p, tl, _) -> Some(p, tl)
| _ -> None
in
name := if Hashtbl.length hfields <> 0 then None else nm;
let fl = match get_desc (expand_head env cty.ctyp_type), nm with
Tvariant row, _ when Btype.static_row row ->
row_fields row
| Tvar _, Some(p, _) ->
raise(Error(sty.ptyp_loc, env, Undefined_type_constructor p))
| _ ->
raise(Error(sty.ptyp_loc, env, Not_a_variant ty))
in
List.iter
(fun (l, f) ->
let f = match present with
Some present when not (List.mem l present) ->
begin match row_field_repr f with
Rpresent oty -> rf_either_of oty
| _ -> assert false
end
| _ -> f
in
add_typed_field sty.ptyp_loc l f)
fl;
Tinherit cty
in
{ rf_desc; rf_loc; rf_attributes; }
in
let more_slot = ref None in
let row_context =
if aliased then row_context else more_slot :: row_context
in
let tfields = List.map (add_field row_context) fields in
let fields = List.rev (Hashtbl.fold (fun _ p l -> p :: l) hfields []) in
begin match present with None -> ()
| Some present ->
List.iter
(fun l -> if not (List.mem_assoc l fields) then
raise(Error(styp.ptyp_loc, env, Present_has_no_type l)))
present
end;
let name = !name in
let make_row more =
create_row ~fields ~more ~closed:(closed = Closed) ~fixed:None ~name
in
let more =
if Btype.static_row
(make_row (newvar (Jkind.value ~why:Row_variable)))
then newty Tnil
else TyVarEnv.new_var (Jkind.value ~why:Row_variable) policy
in
more_slot := Some more;
let ty = newty (Tvariant (make_row more)) in
ctyp (Ttyp_variant (tfields, closed, present)) ty
| Ptyp_poly(vars, st) ->
let desc, typ =
transl_type_poly env ~policy ~row_context mode styp.ptyp_loc
(Either.Left vars) st
in
ctyp desc typ
| Ptyp_package (p, l) ->
(* CR layouts: right now we're doing a real gross hack where we demand
everything in a package type with constraint be value.
An alternative is to walk into the constrained module, using the
longidents, and find the actual things that need jkind checking.
See [Typemod.package_constraints_sig] for code that does a
similar traversal from a longident.
*)
(* CR layouts: and in the long term, rewrite all of this to eliminate
the [create_package_mty] hack that constructs fake source code. *)
let loc = styp.ptyp_loc in
let l = sort_constraints_no_duplicates loc env l in
let mty = create_package_mty loc p l in
let mty =
TyVarEnv.with_local_scope (fun () -> !transl_modtype env mty) in
let ptys =
List.map (fun (s, pty) ->
s, transl_type env ~policy ~row_context Alloc.Const.legacy pty
) l
in
List.iter (fun (s,{ctyp_type=ty}) ->
match
Ctype.constrain_type_jkind env ty (Jkind.value ~why:Package_hack)
with
| Ok _ -> ()
| Error e ->
raise (Error(s.loc,env,
Non_value {vloc=Package_constraint; typ=ty; err=e})))
ptys;
let path = !transl_modtype_longident loc env p.txt in
let ty = newty (Tpackage (path,
List.map (fun (s, cty) -> (s.txt, cty.ctyp_type)) ptys))
in
ctyp (Ttyp_package {
pack_path = path;
pack_type = mty.mty_type;
pack_fields = ptys;
pack_txt = p;
}) ty
| Ptyp_extension ext ->
raise (Error_forward (Builtin_attributes.error_of_extension ext))
and transl_type_aux_jst env ~policy ~row_context mode _attrs loc :
Jane_syntax.Core_type.t -> _ = function
| Jtyp_layout typ ->
transl_type_aux_jst_layout env ~policy ~row_context mode loc typ
and transl_type_aux_jst_layout env ~policy ~row_context mode loc :
Jane_syntax.Layouts.core_type -> _ = function
| Ltyp_var { name = None; jkind } ->
let tjkind = Jkind.of_annotation ~context:(Type_wildcard loc) jkind in
Ttyp_var (None, Some jkind.txt),
TyVarEnv.new_any_var loc env tjkind policy
| Ltyp_var { name = Some name; jkind } ->
transl_type_var env ~policy ~row_context loc name (Some jkind)
| Ltyp_poly { bound_vars; inner_type } ->
transl_type_poly env ~policy ~row_context mode loc (Either.Right bound_vars)
inner_type
| Ltyp_alias { aliased_type; name; jkind } ->
transl_type_alias env ~policy ~row_context mode loc aliased_type name
(Some jkind)
and transl_type_var env ~policy ~row_context loc name jkind_annot_opt =
let print_name = "'" ^ name in
if not (valid_tyvar_name name) then
raise (Error (loc, env, Invalid_variable_name print_name));
let of_annot = Jkind.of_annotation ~context:(Type_variable print_name) in
let ty = try
let ty = TyVarEnv.lookup_local ~row_context name in
begin match jkind_annot_opt with
| None -> ()
| Some jkind_annot ->
let jkind = of_annot jkind_annot in
match constrain_type_jkind env ty jkind with
| Ok () -> ()
| Error err ->
raise (Error(jkind_annot.loc, env, Bad_jkind_annot (ty, err)))
end;
ty
with Not_found ->
let jkind = match jkind_annot_opt with
| None -> Jkind.any ~why:Unification_var
| Some jkind_annot -> of_annot jkind_annot
in
let ty = TyVarEnv.new_var ~name jkind policy in
TyVarEnv.remember_used name ty loc;
ty
in
Ttyp_var (Some name, Option.map Location.get_txt jkind_annot_opt), ty