-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ty_normalizer.ml
1735 lines (1545 loc) · 62.6 KB
/
ty_normalizer.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
(**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Pervasives
open Utils_js
open Reason
open Loc_collections
module Env = Ty_normalizer_env
module T = Type
module VSet = ISet
module File_sig = File_sig.With_ALoc
(* The type normalizer converts infered types (of type `Type.t`) under a context
cx to the simplified form of type `Ty.t`. It is called by various modules,
e.g. type-at-pos, coverage, dump-types, and so is parameterized by a
configuration struct, instantiated by the client.
The type normalizer should only be used on types arising from "fully merged"
contexts -- that is, contexts which have all dependencies copied in and
constraints evaluated.
*)
(* Error reporting *)
type error_kind =
| BadMethodType
| BadBoundT
| BadCallProp
| BadClassT
| BadThisClassT
| BadPoly
| BadTypeAlias
| BadTypeApp
| BadInternalT
| BadInstanceT
| BadEvalT
| BadUse
| ShadowTypeParam
| UnsupportedTypeCtor
| UnsupportedUseCtor
| TypeTooBig
type error = error_kind * string
let error_kind_to_string = function
| BadMethodType -> "Bad method type"
| BadBoundT -> "Unbound type parameter"
| BadCallProp -> "Bad call property"
| BadClassT -> "Bad class"
| BadThisClassT -> "Bad this class"
| BadPoly -> "Bad polymorphic type"
| BadTypeAlias -> "Bad type alias"
| BadTypeApp -> "Bad type application"
| BadInternalT -> "Bad internal type"
| BadInstanceT -> "Bad instance type"
| BadEvalT -> "Bad eval"
| BadUse -> "Bad use"
| ShadowTypeParam -> "Shadowed type parameters"
| UnsupportedTypeCtor -> "Unsupported type constructor"
| UnsupportedUseCtor -> "Unsupported use constructor"
| TypeTooBig -> "Type too big"
let error_to_string (kind, msg) =
spf "[%s] %s" (error_kind_to_string kind) msg
module NormalizerMonad : sig
module State : sig
type t
val empty: t
end
val run_type :
options:Env.options ->
genv:Env.genv ->
imported_names:Ty.imported_ident ALocMap.t ->
tparams:Type.typeparam list ->
State.t ->
Type.t ->
(Ty.t, error) result * State.t
val run_imports:
options:Env.options ->
genv:Env.genv ->
Ty.imported_ident ALocMap.t
end = struct
module State = struct
type t = {
(* Source of fresh ints for creating new Ty.tvar's *)
counter: int;
(* A cache for resolved type variables.
We cache the result even when the output is an error, to avoid
recomputing tvar resolution. This is mostly useful for the batch call
(`from_types`).
The key to this map is the Type.tvar `ident`.
*)
tvar_cache: (Ty.t, error) result IMap.t;
(* This set is useful for synthesizing recursive types. It holds the set
of type variables that are encountered "free". We say that a type
variable is free when it appears in the body of its own definition.
The process of calculating free variables in a type could be
implemented post-fact. The reason we prefer to keep this in the state
instead is performance, since it trivializes the "check if variable
appears free".
*)
free_tvars: VSet.t;
}
let empty = {
counter = 0;
tvar_cache = IMap.empty;
free_tvars = VSet.empty;
}
end
include StateResult.Make(State)
(* Monadic helper functions *)
let mapM f xs = all (Core_list.map ~f:f xs)
let optMapM f = function
| Some xs -> mapM f xs >>| fun ys -> Some ys
| None as y -> return y
let concat_fold_m f xs = mapM f xs >>| Core_list.concat
let fresh_num =
let open State in
get >>= fun st ->
let n = st.counter in
put { st with counter = n + 1 } >>| fun _ -> n
let terr ~kind ?msg t =
let t_str = Option.map t
~f:(fun t -> spf "Raised on type: %s" (Type.string_of_ctor t))
in
let msg = ListUtils.cat_maybes [msg; t_str] |> String.concat "\n" in
error (kind, msg)
(* Type caches *)
let update_tvar_cache i t =
let open State in
get >>= fun st ->
let tvar_cache = IMap.add i t st.tvar_cache in
put { st with tvar_cache }
let find_tvar root_id =
let open State in
get >>| fun st ->
IMap.get root_id st.tvar_cache
(* Lookup a type parameter T in the current environment. There are three outcomes:
1. T appears in env and for its first occurence locations match. This means it
is not shadowed by another parameter with the same name. In this case
return the type parameter.
2. T appears in env but is not the first occurence. This means that some other
type parameter shadows it. We split cases depending on the value of
Config.opt_flag_shadowed_type_params:
- true: flag a warning, since the type is not well-formed in this context.
- false: return the type normally ignoring the warning.
3. The type parameter is not in env. Do the default action.
*)
let lookup_tparam ~default env t tp_name tp_loc =
let open Type in
let pred { name; reason; _ } = (
name = tp_name &&
Reason.def_aloc_of_reason reason = tp_loc
) in
match List.find_opt pred env.Env.tparams with
| Some _ ->
(* If we care about shadowing of type params, then flag an error *)
if Env.flag_shadowed_type_params env then
let shadow_pred { name; _ } = (name = tp_name) in
match List.find_opt shadow_pred env.Env.tparams with
| Some { reason; _ }
when Reason.def_aloc_of_reason reason <> tp_loc ->
terr ~kind:ShadowTypeParam (Some t)
| Some _ ->
return (Ty.Bound (tp_loc, tp_name))
| None -> assert false
else
return (Ty.Bound (tp_loc, tp_name))
| None ->
default t
(**************)
(* Type ctors *)
(**************)
let generic_class name targs =
Ty.mk_generic_class name targs
let generic_interface name targs =
Ty.mk_generic_interface name targs
let generic_talias name targs =
Ty.mk_generic_talias name targs
let builtin_t name =
generic_talias (Ty.builtin_symbol name) None
let generic_builtin_t name ts =
generic_talias (Ty.builtin_symbol name) (Some ts)
let empty_type = Ty.Bot Ty.EmptyType
let empty_matching_prop_t = Ty.Bot Ty.EmptyMatchingPropT
let mk_empty bot_kind =
match bot_kind with
| Ty.EmptyType -> empty_type
| Ty.EmptyMatchingPropT -> empty_matching_prop_t
| Ty.EmptyTypeDestructorTriggerT _
| Ty.NoLowerWithUpper _ -> Ty.Bot bot_kind
(*********************)
(* Recursive types *)
(*********************)
(* There are three phases in resolving a type variable:
A. UNSEEN: Type variable has not been seen yet. It does not appear in the
type cache.
B. UNDER RESOLUTION: Variable has been seen at least once and it is set to
"under resolution". It appears in the type_cache as a mapping from
the original `Type.tvar` to a fresh `Ty.tvar`. This binding is important
for termination purposes as well as determining if the variable appears
free in a type context.
C. RESOLVED: All lower bounds of the variable have been normalized and so
the variable is considered resolved. The cache is updated with the final
type or an error message.
*)
module Recursive = struct
(* Helper functions *)
(* Replace a recursive type variable r with a symbol sym in the type t. *)
let subst =
let o = Ty.(object
inherit [_] map_ty as super
method! on_t env t =
let t = match t, env with
| TVar (i, ts), (r, sym) when r = i ->
generic_talias sym ts
| _ -> t in
super#on_t env t
end) in
fun r sym t ->
o#on_t (r, sym) t
(* We shouldn't really create bare Mu types for two reasons.
First, substitutions and type applications may replace the recursive variables with
a non-recursive type part, rendering the entire type non-recursive. When
`check_recursive` is set to true, we first perform the check.
Second, TypeAliases and Mu types can both imply recursion, so we have little
to gain from nesting them. Therefore, before creating a Mu type, we should check if
the type under the Mu is a TypeAlias and if it is then use that structure to
express the recursion. To do this we replace 'i' for 'ta_name' in the body of
the alias.
PV: The second one is a seemingly awkward fix. However, I am not very concerned as
`TypeAlias` is abusively treated as a type. Eventually, the goal is to include it
in a "module element" category rather than the Ty.t structure.
*)
let mk_mu ~definitely_appears i t =
let open Ty in
if definitely_appears ||
Ty_utils.tvar_appears_in_type ~is_toplevel:true (Ty.RVar i) t
then
match t with
| TypeAlias { ta_name; _ } -> subst (RVar i) ta_name t
| _ -> Mu (i, t)
else
t
(* When inferring recursive types, the top-level appearances of the recursive
variable should be eliminated. This visitor performs the following
transformations:
(recursive var: X , type: X ) ==> Bot
(recursive var: X , type: X | t ) ==> Bot | t
(recursive var: X , type: X & t ) ==> Top & t
(recursive var: X , type: mu Y . X | t) ==> mu Y . Bot | t
The visitor only descends down to the first concrete constructor
(e.g. Function, Class) and is applied to the subparts of unions,
intersections and recursive types.
It is expected to followed by type minimization, so that the introduced
Bot and Top can be eliminated.
*)
let remove_toplevel_tvar =
let open Ty in
let o = object (self)
inherit [_] endo_ty
method env_zero = function
| `Union -> Bot (NoLowerWithUpper NoUpper)
| `Inter -> Top
method! on_t env t =
match env, t with
| (v, _), Union (t0,t1,ts) ->
let t0' = self#on_t (v, `Union) t0 in
let ts' = self#on_list self#on_t (v, `Union) (t1::ts) in
if t0 == t0' && ts == ts' then t else Ty.mk_union (t0', ts')
| (v, _), Inter (t0,t1,ts) ->
let t0' = self#on_t (v, `Inter) t0 in
let ts' = self#on_list self#on_t (v, `Inter) (t1::ts) in
if t0 == t0' && ts == ts' then t else Ty.mk_inter (t0', ts')
| (v, mode), TVar (Ty.RVar v', _) when v = v' ->
self#env_zero mode
| _, Mu (v, rt) ->
let rt' = self#on_t env rt in
if rt == rt' then t
else mk_mu ~definitely_appears:false v rt'
| _, _ -> t
end in
fun v t -> o#on_t (v, `Union) t
(* Constructing recursive types.
This function is expected to be called after fully normalizing the lower
bounds of a type variable `v` and constructing a type `t`. `free_vars` is
the set of free variables appearing in `t`. This information is available
from the state of the monad.
To determine if we truly have a recursive type we take the following into
account:
- If `v` does NOT appear in `free_vars`, then `t` is NOT recursive, so
we return it as-is.
- If `v` appears in `free_vars`, we may be dealing with a recursive type
but we also might have a degenerate case like this one:
Mu (v, v | string)
which is not a recursive type. (It is equivalent to string.)
So, first we simplify the type by performing the "remove_top_level_tvar"
transformation and some subsequent simplifications. Then if the type
changed we check again if `v` is in the free variables.
NOTE that we need to recompute free vars since the simplifications might
have eliminated some of them. Here we use the FreeVars module. This is
an expensive pass, which is why we avoid doing it if it's definitely
not a recursive type.
*)
let make free_vars i t =
if not (VSet.mem i free_vars) then t else
(* Recursive, but still might be a degenerate case *)
let t' = remove_toplevel_tvar i t in
let changed = not (t == t') in
(* If not changed then all free_vars are still in, o.w. recompute free vars *)
mk_mu ~definitely_appears:(not changed) i t'
end
module Substitution = struct
open Ty
(* NOTE Traversing huge types may lead to merge-timeouts. We cut off the size
* of the recursion at 10K nodes. *)
let max_size = 10000
exception SizeCutOff
let size = ref 0
let init_env tparams types =
let rec step acc = function
| [], _ | _, [] -> acc
| p::ps, t::ts -> step (SMap.add p.tp_name t acc) (ps, ts)
in
step SMap.empty (tparams, types)
let remove_params env = function
| None -> env
| Some ps -> List.fold_left (fun e p -> SMap.remove p.tp_name e) env ps
let visitor = object
inherit [_] endo_ty as super
method! on_t env t =
size := !size + 1;
if !size > max_size then
raise SizeCutOff;
match t with
| TypeAlias { ta_tparams = ps; _ }
| Fun { fun_type_params = ps; _ } ->
let env = remove_params env ps in
super#on_t env t
| Bound (_, name) ->
begin match SMap.get name env with
| Some t' -> t'
| None -> super#on_t env t
end
| _ ->
super#on_t env t
end
(* Replace a list of type parameters with a list of types in the given type.
* These lists might not match exactly in length. *)
let run vs ts t =
let env = init_env vs ts in
size := 0;
match visitor#on_t env t with
| exception SizeCutOff -> terr ~kind:TypeTooBig None
| t' -> return t'
end
(***********************)
(* Construct built-ins *)
(***********************)
let opt_param = Ty.({ prm_optional = true })
let non_opt_param = Ty.({ prm_optional = false })
let mk_fun ?(params=[]) ?rest ?tparams ret = Ty.(
Fun {
fun_params = params;
fun_rest_param = rest;
fun_return = ret;
fun_type_params = tparams;
}
)
let mk_tparam ?bound ?(pol=Ty.Neutral) ?default name = Ty.({
tp_name = name;
tp_bound = bound;
tp_polarity = pol;
tp_default = default;
})
let symbol_from_loc env def_loc name =
let open File_key in
let symbol_source = ALoc.source def_loc in
let provenance = match symbol_source with
| Some LibFile _ ->
Ty.Library
| Some (SourceFile def_source) ->
let current_source = Env.(env.genv.file) in
if File_key.to_string current_source = def_source
then Ty.Local
else Ty.Remote {
Ty.imported_as = ALocMap.get def_loc env.Env.imported_names;
}
| Some (JsonFile _)
| Some (ResourceFile _) -> Ty.Local
| Some Builtins -> Ty.Builtin
| None -> Ty.Local
in
let anonymous = name = "<<anonymous class>>" in
{ Ty.provenance; name; anonymous; def_loc }
(* TODO due to repositioninig `reason_loc` may not point to the actual
location where `name` was defined. *)
let symbol_from_reason env reason name =
let def_loc = Reason.def_aloc_of_reason reason in
symbol_from_loc env def_loc name
let remove_targs_matching_defaults targs tparams =
let matches_default targ tparam =
Some targ = Ty.(tparam.tp_default)
in
let rec remove_if_able targ_lst tparam_lst =
match targ_lst, tparam_lst with
(* Recursive case. Recurse, then if this is now the last targ (if later ones were eliminated),
* remove it if it matches the tparam default. *)
| targ::targ_rst, tparam::tparam_rst ->
let targ_rst = remove_if_able targ_rst tparam_rst in
if ListUtils.is_empty targ_rst && matches_default targ tparam then
[]
else
targ::targ_rst
(* Base case *)
| [], []
(* This could happen when there are fewer targs than tparams to begin with *)
| [], _::_
(* This means there are more targs than tparams. This shouldn't happen. *)
| _::_, [] -> targ_lst
in
match targs, tparams with
| Some targ_lst, Some tparam_lst ->
Some (remove_if_able targ_lst tparam_lst)
| _ -> targs
(*************************)
(* Main transformation *)
(*************************)
let rec type__ ~env t = type_poly ~env t
(* Before we start pattern-matching on the structure of the input type, we can
reconstruct some types based on attached reasons. Two cases are of interest here:
- Type parameters: we use RPolyTest reasons for these
- Type aliases: we use RTypeAlias reasons for these *)
and type_poly ~env t =
(* The RPolyTest description is used for types that represent type parameters.
When normalizing, we want such types to be replaced by the type parameter,
whose name is part of the description, but only in the case that the parameter
is in scope. The reason we need to make this distinction is that bound tests
may exit the scope of the structure that introduced them, in which case we
do not perform the substitution. There instead we unfold the underlying type. *)
let reason = Type.reason_of_t t in
match desc_of_reason ~unwrap:false reason with
| RPolyTest (name, _) ->
let loc = Reason.def_aloc_of_reason reason in
let default t = type_with_alias_reason ~env t in
lookup_tparam ~default env t name loc
| _ ->
type_with_alias_reason ~env t
and type_with_alias_reason ~env t =
if Env.expand_type_aliases env then type_after_reason ~env t else
let reason = Type.reason_of_t t in
let open Type in
(* These type are treated as transparent when it comes to the type alias
annotation. *)
match t with
| OpenT _
(* TypeDestructorTriggerT might hold a type-app, so avoid using the type here.
* Instead do the fallback action which is to normalize to Bot. The trigger
* should have actually produced another concrete type as a lower bound. *)
| TypeDestructorTriggerT _ ->
type_after_reason ~env t
| EvalT _ when Env.evaluate_type_destructors env ->
type_after_reason ~env t
| _ ->
begin match desc_of_reason ~unwrap:false reason with
| RTypeAlias (name, true, _) ->
(* The default action is to avoid expansion by using the type alias name,
when this can be trusted. The one case where we want to skip this process
is when recovering the body of a type alias A. In that case the environment
field under_type_alias will be 'Some A'. If the type alias name in the reason
is also A, then we are still at the top-level of the type-alias, so we
proceed by expanding one level preserving the same environment. *)
let continue =
match env.Env.under_type_alias with
| Some name' -> name = name'
| None -> false
in
if continue then type_after_reason ~env t else
let symbol = symbol_from_reason env reason name in
return (generic_talias symbol None)
| _ ->
(* We are now beyond the point of the one-off expansion. Reset the environment
assigning None to under_type_alias, so that aliases are used in subsequent
invocations. *)
let env = Env.{ env with under_type_alias = None } in
type_after_reason ~env t
end
and type_after_reason ~env t =
let open Type in
let env = Env.descend env in
match t with
| OpenT (_, id) -> type_variable ~env id
| BoundT (reason, name, _) -> bound_t ~env reason name
| AnnotT (_, t, _) -> type__ ~env t
| EvalT (t, d, id) -> eval_t ~env t id d
| ExactT (_, t) -> exact_t ~env t
| CustomFunT (_, f) -> custom_fun ~env f
| InternalT i -> internal_t ~env t i
| MatchingPropT _ -> return (mk_empty Ty.EmptyMatchingPropT)
| AnyWithUpperBoundT t ->
type__ ~env t >>| fun t ->
Ty.Utility (Ty.Subtype t)
| AnyWithLowerBoundT t ->
type__ ~env t >>| fun t ->
Ty.Utility (Ty.Supertype t)
| DefT (_, _, MixedT _) -> return Ty.Top
| AnyT (_, Annotated) -> Ty.explicit_any |> return
| AnyT _ -> Ty.implicit_any |> return
| DefT (_, _, VoidT) -> return Ty.Void
| DefT (_, _, NumT (Literal (_, (_, x))))
when Env.preserve_inferred_literal_types env ->
return (Ty.Num (Some x))
| DefT (_, _, NumT (Truthy | AnyLiteral | Literal _)) ->
return (Ty.Num None)
| DefT (_, _, StrT (Literal (_, x)))
when Env.preserve_inferred_literal_types env ->
return (Ty.Str (Some x))
| DefT (_, _, StrT (Truthy | AnyLiteral | Literal _)) ->
return (Ty.Str None)
| DefT (_, _, BoolT (Some x))
when Env.preserve_inferred_literal_types env ->
return (Ty.Bool (Some x))
| DefT (_, _,BoolT _) -> return (Ty.Bool None)
| DefT (_, _, EmptyT _) -> return (mk_empty Ty.EmptyType)
| DefT (_, _,NullT) -> return Ty.Null
| DefT (_, _,SingletonNumT (_, lit)) -> return (Ty.NumLit lit)
| DefT (_, _,SingletonStrT lit) -> return (Ty.StrLit lit)
| DefT (_, _,SingletonBoolT lit) -> return (Ty.BoolLit lit)
| MaybeT (_, t) ->
type__ ~env t >>| fun t -> Ty.mk_union (Ty.Void, [Ty.Null; t])
| OptionalT (_, t) ->
type__ ~env t >>| fun t -> Ty.mk_union (Ty.Void, [t])
| DefT (_, _,FunT (_, _, f)) ->
fun_ty ~env f None >>| fun t -> Ty.Fun t
| DefT (r, _, ObjT o) -> obj_ty ~env r o
| DefT (r, _, ArrT a) -> arr_ty ~env r a
| UnionT (_, rep) ->
let t0, (t1, ts) = UnionRep.members_nel rep in
type__ ~env t0 >>= fun t0 ->
type__ ~env t1 >>= fun t1 ->
mapM (type__ ~env) ts >>| fun ts ->
Ty.mk_union (t0, t1::ts)
| IntersectionT (_, rep) ->
let t0, (t1, ts) = InterRep.members_nel rep in
type__ ~env t0 >>= fun t0 ->
type__ ~env t1 >>= fun t1 ->
mapM (type__ ~env) ts >>| fun ts ->
Ty.mk_inter (t0, t1::ts)
| DefT (_, _, PolyT (_, ps, t, _)) -> poly_ty ~env t ps
| DefT (r, _, TypeT (kind, t)) -> type_t ~env r kind t None
| DefT (_, _ ,TypeAppT (_, t, ts)) -> type_app ~env t (Some ts)
| DefT (r, _, InstanceT (_, _, _, t)) -> instance_t ~env r t
| DefT (_, _, ClassT t) -> class_t ~env t None
| DefT (_, _, IdxWrapper t) -> type__ ~env t
| DefT (_, _, ReactAbstractComponentT {config; instance}) ->
type__ ~env config >>= fun config ->
type__ ~env instance >>= fun instance ->
return @@ generic_talias (Ty_symbol.builtin_symbol "React$AbstractComponent")
(Some [config; instance])
| ThisClassT (_, t) -> this_class_t ~env t None
| ThisTypeAppT (_, c, _, ts) -> type_app ~env c ts
| KeysT (_, t) ->
type__ ~env t >>| fun ty ->
Ty.Utility (Ty.Keys ty)
| OpaqueT (r, o) -> opaque_t ~env r o
| ReposT (_, t) -> type__ ~env t
| ShapeT t ->
type__ ~env t >>| fun t ->
Ty.Utility (Ty.Shape t)
| TypeDestructorTriggerT (_, r, _, _, _) ->
let loc = Reason.def_aloc_of_reason r in
return (mk_empty (Ty.EmptyTypeDestructorTriggerT loc))
| MergedT (_, uses) -> merged_t ~env uses
| ExistsT _ -> return (Ty.Utility Ty.Exists)
| ObjProtoT _ -> return (Ty.TypeOf (["Object"], "prototype"))
| FunProtoT _ -> return (Ty.TypeOf (["Function"], "prototype"))
| OpenPredT (_, t, _, _) -> type__ ~env t
| FunProtoApplyT _ ->
if Env.expand_internal_types env then
(* Function.prototype.apply: (thisArg: any, argArray?: any): any *)
return Ty.(mk_fun
~params:[
(Some "thisArg", explicit_any, non_opt_param);
(Some "argArray", explicit_any, opt_param);
]
explicit_any)
else
return Ty.(TypeOf (["Function"; "prototype"], "apply"))
| FunProtoBindT _ ->
if Env.expand_internal_types env then
(* Function.prototype.bind: (thisArg: any, ...argArray: Array<any>): any *)
return Ty.(mk_fun
~params:[(Some "thisArg", explicit_any, non_opt_param)]
~rest:(Some "argArray", Arr {
arr_readonly = false;
arr_literal = false;
arr_elt_t = explicit_any
})
explicit_any)
else
return Ty.(TypeOf (["Function"; "prototype"], "bind"))
| FunProtoCallT _ ->
if Env.expand_internal_types env then
(* Function.prototype.call: (thisArg: any, ...argArray: Array<any>): any *)
return Ty.(mk_fun
~params:[(Some "thisArg", explicit_any, non_opt_param)]
~rest:(Some "argArray", Arr {
arr_readonly = false;
arr_literal = false;
arr_elt_t = explicit_any;
})
explicit_any)
else
return Ty.(TypeOf (["Function"; "prototype"], "call"))
| ModuleT (reason, _, _) -> module_t env reason t
| DefT (_, _, CharSetT _)
| NullProtoT _ ->
terr ~kind:UnsupportedTypeCtor (Some t)
(* Type variable normalization (input: a type variable `id`)
Step 1: Use `root_id` as a proxy for `id`.
Step 2: Check the cache in case root_id has been computed before. There are
several cases here:
a. The variable is "under resolution" state (recursive variable).
Exit with the cached result and add the variable to the free
variable set.
b. The variable is "resolved". Return the result.
c. The variable resolution led to an error. Propagate error.
d. The variable has never been seen before. Go to step 3.
Step 3: Start variable resolution.
*)
and type_variable ~env id =
let root_id, constraints = (* step 1 *)
Context.find_constraints Env.(env.genv.cx) id in
find_tvar root_id >>= function (* step 2 *)
| Some (Ok Ty.(TVar (Ty.RVar v, _) as t)) -> (* step 2a *)
modify State.(fun st -> { st with
free_tvars = VSet.add v st.free_tvars
}) >>= fun _ ->
return t
| Some (Ok t) -> return t (* step 2b *)
| Some (Error s) -> error s (* step 2c *)
| None -> (* step 2d *)
resolve_tvar ~env constraints root_id (* step 3 *)
(* Resolve a type variable (encountered for the first time)
Resolving a type variable can either succeed and return a Ty.t, or fail and
return an error. Since we are caching the result of this resolution we need
to save a `(Ty.t, error) result`. For this reason we isolate the execution
of the monad under the current state and cache the "monadic" result.
*)
and resolve_tvar ~env cons root_id =
let open State in
fresh_num >>= fun rid ->
let rvar = Ty.RVar rid in
(* Set current variable "under resolution" *)
update_tvar_cache root_id (Ok (Ty.TVar (rvar, None))) >>= fun _ ->
get >>= fun in_st ->
(* Resolve the tvar *)
let ty_res, out_st = run in_st (resolve_bounds ~env cons) in
(* Create a recursive type (if needed) *)
let ty_res = Core_result.map
~f:(Recursive.make out_st.free_tvars rid) ty_res
in
(* Reset state by removing the current tvar from the free vars set *)
let out_st =
{ out_st with free_tvars = VSet.remove rid out_st.free_tvars }
in
put out_st >>= fun _ ->
(* Update cache with final result *)
update_tvar_cache root_id ty_res >>= fun _ ->
(* Throw the error if one was encountered *)
match ty_res with
| Ok ty -> return ty
| Error e -> error e
(* Resolving a type variable amounts to normalizing its lower bounds and
taking their union.
*)
and resolve_bounds ~env = function
| Constraint.Resolved t
| Constraint.FullyResolved t ->
type__ ~env t
| Constraint.Unresolved bounds ->
resolve_from_lower_bounds ~env bounds >>= function
| [] -> empty_with_upper_bounds ~env bounds
| hd::tl -> return (Ty.mk_union ~flattened:true (hd, tl))
and resolve_from_lower_bounds ~env bounds =
T.TypeMap.keys bounds.Constraint.lower |>
mapM (fun t -> type__ ~env t >>| fun ty -> Nel.to_list (Ty.bk_union ty)) >>|
Core_list.concat >>|
Core_list.dedup
and empty_with_upper_bounds ~env bounds =
let uses = T.UseTypeMap.keys bounds.Constraint.upper in
uses_t ~env uses >>| fun use_kind ->
Ty.Bot (Ty.NoLowerWithUpper use_kind)
and bound_t ~env reason name =
let { Ty.def_loc; name; _ } = symbol_from_reason env reason name in
return (Ty.Bound (def_loc, name))
and fun_ty ~env f fun_type_params =
let {T.params; rest_param; return_t; _} = f in
mapM (fun_param ~env) params >>= fun fun_params ->
fun_rest_param_t ~env rest_param >>= fun fun_rest_param ->
type__ ~env return_t >>= fun fun_return ->
return {Ty.fun_params; fun_rest_param; fun_return; fun_type_params}
and method_ty ~env t =
let open Type in
match t with
| DefT (_, _, FunT (_, _, f)) ->
fun_ty ~env f None
| DefT (_, _, PolyT (_, ps, DefT (_, _, FunT (_, _, f)), _)) ->
mapM (type_param ~env) (Nel.to_list ps) >>= fun ps ->
fun_ty ~env f (Some ps)
| _ ->
terr ~kind:BadMethodType (Some t)
and fun_param ~env (x, t) =
opt_t ~env t >>= fun (t, prm_optional) ->
return (x, t, { Ty.prm_optional })
and fun_rest_param_t ~env = function
| Some (x, _, t) -> type__ ~env t >>| fun t -> Some (x,t)
| _ -> return None
and obj_ty ~env reason o =
let { T.flags; props_tmap; call_t; dict_t; _ } = o in
let { T.exact = obj_exact; T.frozen = obj_frozen; _ } = flags in
let obj_literal = match Reason.desc_of_reason reason with
| Reason.RObjectLit -> true
| _ -> false
in
obj_props ~env props_tmap call_t dict_t >>| fun obj_props ->
Ty.Obj { Ty.obj_exact; obj_frozen; obj_literal; obj_props }
and obj_prop ~env (x, p) =
match p with
| T.Field (_, t, polarity) ->
let fld_polarity = type_polarity polarity in
opt_t ~env t >>| fun (t, fld_optional) ->
[Ty.(NamedProp (x, Field (t, {fld_polarity; fld_optional})))]
| T.Method (_, t) ->
method_ty ~env t >>| fun t -> [Ty.NamedProp (x, Ty.Method t)]
| T.Get (_, t) ->
type__ ~env t >>| fun t -> [Ty.NamedProp (x, Ty.Get t)]
| T.Set (_, t) ->
type__ ~env t >>| fun t -> [Ty.NamedProp (x, Ty.Set t)]
| T.GetSet (loc1, t1, loc2, t2) ->
obj_prop ~env (x, T.Get (loc1, t1)) >>= fun p1 ->
obj_prop ~env (x, T.Set (loc2, t2)) >>| fun p2 ->
p1@p2
and call_prop_from_t ~env t =
let ts = match t with
| T.IntersectionT (_, rep) -> T.InterRep.members rep
| t -> [t]
in
mapM (method_ty ~env) ts >>| fun ts ->
Core_list.map ~f:(fun t -> Ty.CallProp t) ts
and obj_props =
(* call property *)
let do_calls ~env = function
| Some call_id ->
let cx = Env.get_cx env in
let ft = Context.find_call cx call_id in
call_prop_from_t ~env ft
| None ->
return []
in
let do_props ~env props =
concat_fold_m (obj_prop ~env) props
in
let do_dict ~env = function
| Some d ->
let {T.dict_polarity; dict_name; key; value} = d in
let dict_polarity = type_polarity dict_polarity in
type__ ~env key >>= fun dict_key ->
type__ ~env value >>| fun dict_value ->
[Ty.IndexProp {Ty.dict_polarity; dict_name; dict_key; dict_value}]
| None -> return []
in
fun ~env props_id call_id_opt dict ->
let cx = Env.get_cx env in
let props = SMap.bindings (Context.find_props cx props_id) in
do_calls ~env call_id_opt >>= fun call_props ->
do_props ~env props >>= fun props ->
do_dict ~env dict >>| fun dict ->
call_props @ props @ dict
and arr_ty ~env reason elt_t =
let arr_literal = match Reason.desc_of_reason reason with
| Reason.RArrayLit -> true
| _ -> false
in
match elt_t with
| T.ArrayAT (t, _) ->
type__ ~env t >>| fun t ->
Ty.Arr { Ty.arr_readonly = false; arr_literal; arr_elt_t = t }
| T.ROArrayAT t ->
type__ ~env t >>| fun t ->
Ty.Arr { Ty.arr_readonly = true; arr_literal; arr_elt_t = t }
| T.TupleAT (_, ts) ->
mapM (type__ ~env) ts >>| fun ts -> Ty.Tup ts
and name_of_instance_reason r =
(* This should cover all cases but throw an error just in case. *)
match desc_of_reason ~unwrap:false r with
| RType name
| RIdentifier name -> return name
| r ->
let msg = spf "could not extract name from reason: %s"
(Reason.string_of_desc r) in
terr ~kind:BadInstanceT ~msg None
(* Used for instances of React.createClass(..) *)
and react_component =
let react_props ~env ~default props name =
match SMap.find name props with
| exception Not_found -> return default
| Type.Field (_, t, _) -> type__ ~env t
| _ -> return default
in
let react_static_props ~env static =
let cx = Env.(env.genv.cx) in
match static with
| T.DefT (_, _, T.ObjT { T.props_tmap; _ }) ->
Context.find_props cx props_tmap |>
SMap.bindings |>
mapM (fun (name, p) -> obj_prop ~env (name, p)) >>|
List.concat
| _ -> return []
in
let inexactify = function
| Ty.Obj ({ Ty.obj_exact = true; _ } as obj) ->
Ty.Obj { obj with Ty.obj_exact = false }
| ty -> ty
in
fun ~env static own_props ->
let cx = Env.(env.genv.cx) in
let own_props = Context.find_props cx own_props in
react_props ~env ~default:Ty.implicit_any own_props "props" >>= fun props_ty ->
react_props ~env ~default:Ty.implicit_any own_props "state" >>= fun state_ty ->
react_static_props ~env static >>| fun static_flds ->
(* The inferred type for state is unsealed, which has its exact bit set.
* However, Ty.t does not account for unsealed and exact sealed objects are
* incompatible with exact and unsealed, so making state inexact here. *)
let state_ty = inexactify state_ty in
let parent_instance = generic_builtin_t "React$Component" [props_ty; state_ty] in
let parent_class = Ty.Utility (Ty.Class parent_instance) in
(*
* {
* +propTypes: {
* foo: React$PropType$Primitive$Required<string>,
* bar: React$PropType$Primitive<number>,
* },
* defaultProps: { ... },
* }
*)
let props_obj = Ty.Obj {
Ty.obj_exact = false;
obj_frozen = false;
obj_literal = false;
obj_props = static_flds;
} in
Ty.mk_inter (parent_class, [props_obj])
and instance_t ~env r inst =
let open Type in
name_of_instance_reason r >>= fun name ->
let symbol = symbol_from_reason env r name in
mapM (fun (_, _, t, _) -> type__ ~env t) inst.type_args >>| fun tys ->
let targs = match tys with [] -> None | _ -> Some tys in
if inst.structural
then generic_interface symbol targs
else generic_class symbol targs
and class_t =
let rec go ~env ps ty =
match ty with
| Ty.Generic (name, kind, _) ->
begin match kind with
| Ty.InterfaceKind -> return (Ty.InterfaceDecl (name, ps))
| Ty.TypeAliasKind -> return (Ty.Utility (Ty.Class ty))
| Ty.ClassKind ->
(* If some parameters have been passed, then we are in the `PolyT-ThisClassT`
* case of Flow_js.canonicalize_imported_type. This case should still be
* normalized to an abstract class declaration. If no parameters are passed
* then this is a `Class<T>` with an instance T. *)
begin match ps with
| Some _ -> return (Ty.ClassDecl (name, ps))
| None -> return (Ty.Utility (Ty.Class ty))
end