-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
statement.ml
8515 lines (8340 loc) · 332 KB
/
statement.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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Tast_utils = Typed_ast_utils
(* This module contains the traversal functions which set up subtyping
constraints for every expression, statement, and declaration form in a
JavaScript AST; the subtyping constraints are themselves solved in module
Flow_js. *)
module Flow = Flow_js
open Utils_js
open Reason
open FlowSymbol
open Type
open TypeUtil
open Func_class_sig_types
open Type_operation_utils
module Eq_test = Eq_test.Make (Scope_api.With_ALoc) (Ssa_api.With_ALoc) (Env_api.With_ALoc)
module Make
(Destructuring : Destructuring_sig.S)
(Func_stmt_config : Func_stmt_config_sig.S with module Types := Func_stmt_config_types.Types)
(Component_declaration_config : Component_params_intf.Config
with module Types := Component_sig_types
.DeclarationParamConfig)
(Statement : Statement_sig.S) : Statement_sig.S = struct
module Anno = Type_annotation.Make (Statement)
module Class_type_sig = Anno.Class_type_sig
module Func_stmt_config = Func_stmt_config
module Component_declaration_config = Component_declaration_config
open Type_env.LookupMode
(*************)
(* Utilities *)
(*************)
module ChainingConf = struct
type ('a, 'b) t = {
refinement_action: ('a -> Type.t -> Type.t -> Type.t) option;
refine: unit -> Type.t option;
subexpressions: unit -> 'a * 'b;
get_result: 'a -> Reason.t -> Type.t -> Type.t;
get_opt_use: 'a -> Reason.t -> Type.opt_use_t;
get_reason: Type.t -> Reason.t;
}
end
type class_member_kind =
| Class_Member_Field
| Class_Member_Getter
| Class_Member_GetterSetter
| Class_Member_Method
| Class_Member_Setter
type seen_names = {
static_names: class_member_kind SMap.t;
instance_names: class_member_kind SMap.t;
}
let empty_seen_names = { static_names = SMap.empty; instance_names = SMap.empty }
type frozen_kind =
| NotFrozen
| FrozenProp
| FrozenDirect
module ObjectExpressionAcc = struct
type element =
| Spread of Type.t
| Slice of { slice_pmap: Type.Properties.t }
type t = {
obj_pmap: Type.Properties.t;
tail: element list;
proto: Type.t option;
obj_key_autocomplete: bool;
}
let empty _ =
{ obj_pmap = NameUtils.Map.empty; tail = []; proto = None; obj_key_autocomplete = false }
let empty_slice = Slice { slice_pmap = NameUtils.Map.empty }
let head_slice { obj_pmap; _ } =
if NameUtils.Map.is_empty obj_pmap then
None
else
Some (Slice { slice_pmap = obj_pmap })
let add_prop f acc = { acc with obj_pmap = f acc.obj_pmap }
let add_proto p acc = { acc with proto = Some p }
let add_spread t acc =
let tail =
match head_slice acc with
| None -> acc.tail
| Some slice -> slice :: acc.tail
in
{ acc with obj_pmap = NameUtils.Map.empty; tail = Spread t :: tail }
let set_obj_key_autocomplete acc = { acc with obj_key_autocomplete = true }
let obj_key_autocomplete acc = acc.obj_key_autocomplete
let elements_rev acc =
match head_slice acc with
| Some slice -> (slice, acc.tail)
| None ->
(match acc.tail with
| [] -> (empty_slice, [])
| x :: xs -> (x, xs))
let proto { proto; _ } = proto
let mk_object_from_spread_acc cx acc reason ~as_const ~frozen ~default_proto =
match elements_rev acc with
| (Slice { slice_pmap }, []) ->
let proto = Base.Option.value ~default:default_proto (proto acc) in
let obj_t = Obj_type.mk_with_proto cx reason ~obj_kind:Exact ~props:slice_pmap proto in
if obj_key_autocomplete acc then
let get_autocomplete_t () =
Tvar_resolver.mk_tvar_and_fully_resolve_where cx reason (fun tvar ->
Flow_js.flow_t cx (obj_t, tvar)
)
in
let (_, lazy_hint) = Type_env.get_hint cx (Reason.loc_of_reason reason) in
lazy_hint reason |> Type_hint.with_hint_result ~ok:Base.Fn.id ~error:get_autocomplete_t
else
obj_t
| os ->
let (t, ts, head_slice) =
let (t, ts) = os in
(* We don't need to do this recursively because every pair of slices must be separated
* by a spread *)
match (t, ts) with
| (Spread t, ts) ->
let ts =
Base.List.map
~f:(function
| Spread t -> Object.Spread.Type t
| Slice { slice_pmap } ->
Object.Spread.Slice
{
Object.Spread.reason;
prop_map = slice_pmap;
dict = None;
generics = Generic.spread_empty;
reachable_targs = [];
})
ts
in
(t, ts, None)
| (Slice { slice_pmap = prop_map }, Spread t :: ts) ->
let head_slice =
{
Type.Object.Spread.reason;
prop_map;
dict = None;
generics = Generic.spread_empty;
reachable_targs = [];
}
in
let ts =
Base.List.map
~f:(function
| Spread t -> Object.Spread.Type t
| Slice { slice_pmap } ->
Object.Spread.Slice
{
Object.Spread.reason;
prop_map = slice_pmap;
dict = None;
generics = Generic.spread_empty;
reachable_targs = [];
})
ts
in
(t, ts, Some head_slice)
| _ -> failwith "Invariant Violation: spread list has two slices in a row"
in
let target = Object.Spread.Value { make_seal = Obj_type.mk_seal ~frozen ~as_const } in
let tool = Object.Resolve Object.Next in
let state =
{
Object.Spread.todo_rev = ts;
acc =
Base.Option.value_map
~f:(fun x -> [Object.Spread.InlineSlice x])
~default:[]
head_slice;
spread_id = Reason.mk_id ();
union_reason = None;
curr_resolve_idx = 0;
}
in
let tout =
Tvar_resolver.mk_tvar_and_fully_resolve_where cx reason (fun tout ->
let use_op = Op (ObjectSpread { op = reason }) in
Flow.flow
cx
(t, ObjKitT (use_op, reason, tool, Type.Object.Spread (target, state), tout))
)
in
if obj_key_autocomplete acc then
let (_, lazy_hint) = Type_env.get_hint cx (Reason.loc_of_reason reason) in
lazy_hint reason |> Type_hint.with_hint_result ~ok:Base.Fn.id ~error:(fun () -> tout)
else
tout
end
let mk_ident ~comments name = { Ast.Identifier.name; comments }
let snd_fst ((_, x), _) = x
let translate_identifer_or_literal_key t =
let module P = Ast.Expression.Object.Property in
function
| P.Identifier (loc, name) -> P.Identifier ((loc, t), name)
| P.StringLiteral (loc, lit) -> P.StringLiteral ((loc, t), lit)
| P.NumberLiteral (loc, lit) -> P.NumberLiteral ((loc, t), lit)
| P.BigIntLiteral _
| P.PrivateName _
| P.Computed _ ->
assert_false "precondition not met"
let name_of_identifier_or_literal_key key =
let module P = Ast.Expression.Object.Property in
match key with
| P.Identifier (_, { Ast.Identifier.name; _ })
| P.StringLiteral (_, { Ast.StringLiteral.value = name; _ }) ->
Ok name
| P.NumberLiteral (loc, { Ast.NumberLiteral.value; _ }) ->
if Js_number.is_float_safe_integer value then
let name = Dtoa.ecma_string_of_float value in
Ok name
else
Error
(Error_message.EUnsupportedKeyInObject
{
loc;
obj_kind = `Literal;
key_error_kind = Flow_intermediate_error_types.InvalidObjKey.kind_of_num_value value;
}
)
| P.BigIntLiteral (loc, _)
| P.PrivateName (loc, _)
| P.Computed (loc, _) ->
Error
(Error_message.EUnsupportedKeyInObject
{
loc;
obj_kind = `Literal;
key_error_kind = Flow_intermediate_error_types.InvalidObjKey.Other;
}
)
let convert_call_targs =
let open Ast.Expression.CallTypeArg in
let rec loop ts tasts cx tparams_map = function
| [] -> (List.rev ts, List.rev tasts)
| ast :: asts -> begin
match ast with
| Explicit ast ->
let (((_, t), _) as tast) = Anno.convert cx tparams_map ast in
loop (ExplicitArg t :: ts) (Explicit tast :: tasts) cx tparams_map asts
| Implicit (loc, impl) ->
let reason = mk_reason RImplicitInstantiation loc in
let id = Tvar.mk_no_wrap cx reason in
loop
(ImplicitArg (reason, id) :: ts)
(Implicit ((loc, OpenT (reason, id)), impl) :: tasts)
cx
tparams_map
asts
end
in
fun cx tparams_map call_targs ->
let open Ast.Expression.CallTypeArgs in
let { arguments; comments } = call_targs in
let (ts, tasts) = loop [] [] cx tparams_map arguments in
(ts, { arguments = tasts; comments })
let convert_call_targs_opt cx = function
| None -> (None, None)
| Some (loc, args) ->
let (targts, targs_ast) = convert_call_targs cx Subst_name.Map.empty args in
(Some targts, Some (loc, targs_ast))
let convert_call_targs_opt' cx = function
| None -> None
| Some (_, args) ->
let (targts, _) = convert_call_targs cx Subst_name.Map.empty args in
Some targts
module ALoc_this_finder = This_finder.Make (Loc_collections.ALocSet)
let error_on_this_uses_in_object_methods cx =
let open Ast in
let open Expression in
Base.List.iter ~f:(function
| Object.Property (prop_loc, Object.Property.Method { key; value = (_, func); _ })
| Object.Property (prop_loc, Object.Property.Get { key; value = (_, func); _ })
| Object.Property (prop_loc, Object.Property.Set { key; value = (_, func); _ }) ->
let finder = new ALoc_this_finder.finder in
finder#eval (finder#function_ prop_loc) func
|> Loc_collections.ALocSet.iter (fun loc ->
let reason =
match key with
| Object.Property.Identifier (_, { Identifier.name; _ })
| Object.Property.PrivateName (_, { PrivateName.name; _ })
| Object.Property.StringLiteral (_, { StringLiteral.raw = name; _ }) ->
mk_reason (RMethod (Some name)) prop_loc
| _ -> mk_reason (RMethod None) prop_loc
in
Flow_js.add_output cx (Error_message.EObjectThisReference (loc, reason))
)
| _ -> ()
)
let error_on_this_uses_in_components cx { Ast.Statement.ComponentDeclaration.sig_loc; body; _ } =
let finder = new ALoc_this_finder.finder in
finder#eval finder#component_body body
|> Loc_collections.ALocSet.iter (fun this_loc ->
Flow_js.add_output
cx
(Error_message.EComponentThisReference { component_loc = sig_loc; this_loc })
)
(* Given the expression of a statement expression, returns a list of child
expressions which are _potentially_ unhandled promises. At this point,
we don't know if they are actually of type Promise. We will determine that
later, but we don't need to even check that if we can tell that the
expression is being handled ("used") syntactically here. *)
let rec syntactically_unhandled_promises ((_, expr_ast) as expr) =
let open Flow_ast.Expression in
match expr_ast with
| Assignment _
(* Call to `catch` or `finally` with one argument *)
| Call
{
Call.callee =
( _,
Member
{
Member.property =
Member.PropertyIdentifier
(_, { Flow_ast.Identifier.name = "catch" | "finally"; _ });
_;
}
);
arguments = (_, { ArgList.arguments = _ :: _; _ });
_;
}
| OptionalCall
{
OptionalCall.call =
{
Call.callee =
( _,
OptionalMember
{
OptionalMember.member =
{
Member.property =
Member.PropertyIdentifier
(_, { Flow_ast.Identifier.name = "catch" | "finally"; _ });
_;
};
_;
}
);
arguments = (_, { ArgList.arguments = _ :: _; _ });
_;
};
_;
}
(* Call to `then` with two arguments *)
| Call
{
Call.callee =
( _,
Member
{
Member.property =
Member.PropertyIdentifier (_, { Flow_ast.Identifier.name = "then"; _ });
_;
}
);
arguments = (_, { ArgList.arguments = _ :: _ :: _; _ });
_;
}
| OptionalCall
{
OptionalCall.call =
{
Call.callee =
( _,
OptionalMember
{
OptionalMember.member =
{
Member.property =
Member.PropertyIdentifier (_, { Flow_ast.Identifier.name = "then"; _ });
_;
};
_;
}
);
arguments = (_, { ArgList.arguments = _ :: _ :: _; _ });
_;
};
_;
} ->
[]
(* Recurse into logical operands for expressions like `condition && somePromise();` *)
| Logical { Logical.left; right; _ } ->
Base.List.unordered_append
(syntactically_unhandled_promises left)
(syntactically_unhandled_promises right)
(* Recurse into conditional operands for expressions like `b ? x : somePromise();` *)
| Conditional { Conditional.consequent; alternate; _ } ->
Base.List.unordered_append
(syntactically_unhandled_promises consequent)
(syntactically_unhandled_promises alternate)
| _ -> [expr]
module Func_stmt_params =
Func_params.Make (Func_stmt_config_types.Types) (Func_stmt_config) (Func_stmt_params_types)
module Func_stmt_sig =
Func_sig.Make (Statement) (Func_stmt_config_types.Types) (Func_stmt_config) (Func_stmt_params)
(Func_stmt_sig_types)
module Class_stmt_sig =
Class_sig.Make (Func_stmt_config_types.Types) (Func_stmt_config) (Func_stmt_params)
(Func_stmt_sig)
(Class_stmt_sig_types)
module Component_declaration_params =
Component_params.Make
(Component_sig_types.DeclarationParamConfig)
(Component_declaration_config)
(Component_sig_types.Component_declaration_params_types)
module Component_declaration_body =
Component_sig.Component_declaration_body (Statement) (Component_sig_types.DeclarationBodyConfig)
module Component_declaration_sig =
Component_sig.Make (Component_sig_types.DeclarationParamConfig) (Component_declaration_config)
(Component_declaration_params)
(Component_sig_types.DeclarationBodyConfig)
(Component_declaration_body)
(Component_sig_types.Component_declaration_sig_types)
(* In positions where an annotation may be present or an annotation can be pushed down,
* we should prefer the annotation over the pushed-down annotation. *)
let mk_inference_target_with_annots ~has_hint annot_or_inferred =
match (annot_or_inferred, has_hint) with
| (Annotated _, _) -> annot_or_inferred
| (_, true) -> Annotated (type_t_of_annotated_or_inferred annot_or_inferred)
| _ -> annot_or_inferred
(******************)
(* Constraint gen *)
(******************)
(* We assume that constructor functions return void
and constructions return objects.
TODO: This assumption does not always hold.
If construction functions return non-void values (e.g., functions),
then those values are returned by constructions.
*)
let new_call cx loc reason ~use_op class_ targs args =
let specialized_ctor = Context.new_specialized_callee cx in
let t =
Tvar_resolver.mk_tvar_and_fully_resolve_where cx reason (fun tout ->
Flow.flow
cx
( class_,
ConstructorT
{
use_op;
reason;
targs;
args;
tout;
return_hint = Type_env.get_hint cx loc;
specialized_ctor = Some specialized_ctor;
}
)
)
in
let ctor_t =
Flow_js_utils.CalleeRecorder.type_for_tast_opt reason specialized_ctor
|> Base.Option.value ~default:class_
in
(t, ctor_t)
let func_call_opt_use
cx loc reason ~use_op ?(call_strict_arity = true) targts argts specialized_callee =
let opt_app =
mk_opt_functioncalltype reason targts argts call_strict_arity specialized_callee
in
let return_hint = Type_env.get_hint cx loc in
OptCallT { use_op; reason; opt_funcalltype = opt_app; return_hint }
let func_call cx loc reason ~use_op ?(call_strict_arity = true) func_t targts argts t_callee =
let opt_use =
func_call_opt_use cx loc reason ~use_op ~call_strict_arity targts argts t_callee
in
Tvar_resolver.mk_tvar_and_fully_resolve_no_wrap_where cx reason (fun t ->
Flow.flow cx (func_t, apply_opt_use opt_use t)
)
let method_call_opt_use
cx
opt_state
~voided_out
reason
~use_op
~private_
?(call_strict_arity = true)
prop_loc
(expr, name)
chain_loc
targts
argts
specialized_callee =
let (expr_loc, _) = expr in
let prop_name = OrdinaryName name in
let reason_prop = mk_reason (RProperty (Some prop_name)) prop_loc in
let reason_expr = mk_reason (RProperty (Some prop_name)) expr_loc in
let opt_methodcalltype = mk_opt_methodcalltype targts argts call_strict_arity in
let propref = mk_named_prop ~reason:reason_prop prop_name in
let action =
match opt_state with
| NewChain ->
let exp_reason = mk_reason ROptionalChain chain_loc in
OptChainM
{
exp_reason;
lhs_reason = mk_expression_reason expr;
opt_methodcalltype;
voided_out;
return_hint = Type.hint_unavailable;
specialized_callee;
}
| _ ->
OptCallM
{ opt_methodcalltype; return_hint = Type_env.get_hint cx chain_loc; specialized_callee }
in
if private_ then
let class_entries = Type_env.get_class_entries cx in
OptPrivateMethodT (use_op, reason, reason_expr, name, class_entries, false, action)
else
OptMethodT (use_op, reason, reason_expr, propref, action)
(* returns (type of method itself, type returned from method) *)
let method_call
cx reason ~use_op ?(call_strict_arity = true) prop_loc (expr, obj_t, name) targts argts =
let (expr_loc, _) = expr in
match Refinement.get ~allow_optional:true cx expr (loc_of_reason reason) with
| Some f ->
(* note: the current state of affairs is that we understand
member expressions as having refined types, rather than
understanding receiver objects as carrying refined properties.
generalizing this properly is a todo, and will deliver goodness.
meanwhile, here we must hijack the property selection normally
performed by the flow algorithm itself. *)
( f,
Tvar_resolver.mk_tvar_and_fully_resolve_no_wrap_where cx reason (fun t ->
let app =
mk_boundfunctioncalltype
~call_kind:RegularCallKind
obj_t
targts
argts
t
~call_strict_arity
in
Flow.flow
cx
( f,
CallT
{
use_op;
reason;
call_action = Funcalltype app;
return_hint = Type.hint_unavailable;
}
)
)
)
| None ->
let name = OrdinaryName name in
let reason_prop = mk_reason (RProperty (Some name)) prop_loc in
let specialized_callee = Context.new_specialized_callee cx in
let out =
Tvar_resolver.mk_tvar_and_fully_resolve_no_wrap_where cx reason (fun t ->
let reason_expr = mk_reason (RProperty (Some name)) expr_loc in
let methodcalltype =
mk_methodcalltype targts argts t ~meth_strict_arity:call_strict_arity
in
let propref = mk_named_prop ~reason:reason_prop name in
Flow.flow
cx
( obj_t,
MethodT
( use_op,
reason,
reason_expr,
propref,
CallM
{
methodcalltype;
return_hint = Type.hint_unavailable;
specialized_callee = Some specialized_callee;
}
)
)
)
in
let prop_t = Flow_js_utils.CalleeRecorder.type_for_tast reason_prop specialized_callee in
(prop_t, out)
let elem_call_opt_use
opt_state
~voided_out
~use_op
~reason_call
~reason_lookup
~reason_expr
~reason_chain
targts
argts
elem_t
specialized_callee =
let opt_methodcalltype = mk_opt_methodcalltype targts argts true in
let action =
match opt_state with
| NewChain ->
OptChainM
{
exp_reason = reason_chain;
lhs_reason = reason_expr;
opt_methodcalltype;
voided_out;
return_hint = Type.hint_unavailable;
specialized_callee;
}
| _ ->
OptCallM { opt_methodcalltype; return_hint = Type.hint_unavailable; specialized_callee }
in
OptCallElemT (use_op, reason_call, reason_lookup, elem_t, action)
(**********)
(* Values *)
(**********)
let identifier_ cx name loc =
let get_checking_mode_type () =
let t = Type_env.var_ref ~lookup_mode:ForValue cx (OrdinaryName name) loc in
(* We want to make sure that the reason description for the type we return
* is always `RIdentifier name`. *)
match (desc_of_t t, t) with
| (RIdentifier name', _) when OrdinaryName name = name' -> t
| (_, OpenT _) ->
(* If this is an `OpenT` we can change its reason description directly. *)
mod_reason_of_t (replace_desc_new_reason (RIdentifier (OrdinaryName name))) t
(* If this is not an `OpenT` then create a new type variable with our
* desired reason and unify it with our type. This adds a level of
* indirection so that we don't modify the underlying reason of our type. *)
| _ ->
let reason = mk_reason (RIdentifier (OrdinaryName name)) loc in
Tvar_resolver.mk_tvar_and_fully_resolve_where cx reason (Flow.unify cx t)
in
if Type_inference_hooks_js.dispatch_id_hook cx name loc then
let reason = mk_reason RAutocompleteToken loc in
let (_, lazy_hint) = Type_env.get_hint cx loc in
lazy_hint reason |> Type_hint.with_hint_result ~ok:Base.Fn.id ~error:(fun () -> EmptyT.at loc)
else
get_checking_mode_type ()
let identifier cx { Ast.Identifier.name; comments = _ } loc =
let t = identifier_ cx name loc in
t
let string_literal_value cx ~singleton loc value =
if Type_inference_hooks_js.dispatch_literal_hook cx loc then
let (_, lazy_hint) = Type_env.get_hint cx loc in
let hint = lazy_hint (mk_reason RString loc) in
let error () = EmptyT.at loc in
Type_hint.with_hint_result hint ~ok:Base.Fn.id ~error
else if singleton then
let reason = mk_annot_reason (RStringLit (OrdinaryName value)) loc in
DefT (reason, SingletonStrT (OrdinaryName value))
else
(* It's too expensive to track literal information for large strings.*)
let max_literal_length = Context.max_literal_length cx in
if max_literal_length = 0 || String.length value <= max_literal_length then
let reason = mk_annot_reason RString loc in
DefT (reason, StrT (Literal (None, OrdinaryName value)))
else
let reason = mk_annot_reason (RLongStringLit max_literal_length) loc in
DefT (reason, StrT AnyLiteral)
let string_literal cx ~singleton loc { Ast.StringLiteral.value; _ } =
string_literal_value cx ~singleton loc value
let boolean_literal ~singleton loc { Ast.BooleanLiteral.value; _ } =
if singleton then
let reason = mk_annot_reason (RBooleanLit value) loc in
DefT (reason, SingletonBoolT value)
else
let reason = mk_annot_reason RBoolean loc in
DefT (reason, BoolT (Some value))
let null_literal loc = NullT.at loc
let number_literal ~singleton loc { Ast.NumberLiteral.value; raw; _ } =
if singleton then
let reason = mk_annot_reason (RNumberLit raw) loc in
DefT (reason, SingletonNumT (value, raw))
else
let reason = mk_annot_reason RNumber loc in
DefT (reason, NumT (Literal (None, (value, raw))))
let bigint_literal ~singleton loc { Ast.BigIntLiteral.value; raw; _ } =
if singleton then
let reason = mk_annot_reason (RBigIntLit raw) loc in
DefT (reason, SingletonBigIntT (value, raw))
else
let reason = mk_annot_reason RBigInt loc in
DefT (reason, BigIntT (Literal (None, (value, raw))))
let regexp_literal cx loc =
let reason = mk_annot_reason RRegExp loc in
Flow.get_builtin_type cx reason "RegExp"
let module_ref_literal cx loc lit =
let { Ast.ModuleRefLiteral.value; require_out; prefix_len; legacy_interop; _ } = lit in
let mref = Base.String.drop_prefix value prefix_len in
let module_t =
Import_export.get_module_t
cx
~import_kind_for_untyped_import_validation:(Some ImportValue)
(loc, mref)
in
let require_t =
Import_export.cjs_require_type
cx
(mk_reason (RModule mref) loc)
~namespace_symbol:(mk_module_symbol ~name:mref ~def_loc:loc)
~legacy_interop
module_t
in
let reason = mk_reason (RCustom "module reference") loc in
let t = Flow.get_builtin_typeapp cx reason "$Flow$ModuleRef" [require_t] in
(t, { lit with Ast.ModuleRefLiteral.require_out = (require_out, require_t) })
let check_const_assertion cx (loc, e) =
let open Ast.Expression in
if
match e with
| StringLiteral _
| BooleanLiteral _
| NumberLiteral _
| BigIntLiteral _
| RegExpLiteral _
| Array _
| Object _
| Unary { Unary.operator = Unary.Minus; argument = (_, NumberLiteral _); _ } ->
false
| _ -> true
then
Flow.add_output
cx
(Error_message.EUnsupportedSyntax (loc, Flow_intermediate_error_types.AsConstOnNonLiteral))
(*********)
(* Types *)
(*********)
let opaque_type
cx
loc
{
Ast.Statement.OpaqueType.id = (name_loc, ({ Ast.Identifier.name; comments = _ } as id));
tparams;
impltype;
supertype;
comments;
} =
let cache = Context.node_cache cx in
match Node_cache.get_opaque cache loc with
| Some info ->
Debug_js.Verbose.print_if_verbose_lazy
cx
(lazy [spf "Opaque type cache hit at %s" (ALoc.debug_to_string loc)]);
info
| None ->
let r = DescFormat.type_reason (OrdinaryName name) name_loc in
let (tparams, tparams_map, tparams_ast) = Anno.mk_type_param_declarations cx tparams in
let (underlying_t, impltype_ast) = Anno.convert_opt cx tparams_map impltype in
let (super_t, supertype_ast) = Anno.convert_opt cx tparams_map supertype in
begin
match tparams with
| None -> ()
| Some (_, tps) ->
(* TODO: use tparams_map *)
let tparams =
Nel.fold_left (fun acc tp -> Subst_name.Map.add tp.name tp acc) Subst_name.Map.empty tps
in
Base.Option.iter
underlying_t
~f:(Context.add_post_inference_polarity_check cx tparams Polarity.Positive);
Base.Option.iter
super_t
~f:(Context.add_post_inference_polarity_check cx tparams Polarity.Positive)
end;
let opaque_type_args =
Base.List.map
~f:(fun { name; reason; polarity; _ } ->
let t = Subst_name.Map.find name tparams_map in
(name, reason, t, polarity))
(TypeParams.to_list tparams)
in
let opaque_id = Opaque.UserDefinedOpaqueTypeId (Context.make_aloc_id cx name_loc) in
let opaquetype = { underlying_t; super_t; opaque_id; opaque_type_args; opaque_name = name } in
let t = OpaqueT (mk_reason (ROpaqueType name) name_loc, opaquetype) in
let type_ =
poly_type_of_tparams (Type.Poly.generate_id ()) tparams (DefT (r, TypeT (OpaqueKind, t)))
in
let () =
match (underlying_t, super_t) with
| (Some l, Some u) -> Context.add_post_inference_subtyping_check cx l unknown_use u
| _ -> ()
in
let opaque_type_ast =
{
Ast.Statement.OpaqueType.id = ((name_loc, type_), id);
tparams = tparams_ast;
impltype = impltype_ast;
supertype = supertype_ast;
comments;
}
in
(type_, opaque_type_ast)
(*****************)
(* Import/Export *)
(*****************)
let export_specifiers cx source export_kind =
let open Ast.Statement in
let module E = ExportNamedDeclaration in
let lookup_mode =
match export_kind with
| Ast.Statement.ExportValue -> ForValue
| Ast.Statement.ExportType -> ForType
in
(* [declare] export [type] {foo [as bar]}; *)
let export_ref loc local_name =
let t = Type_env.var_ref ~lookup_mode cx local_name loc in
match export_kind with
| Ast.Statement.ExportType -> Import_export.assert_export_is_type cx local_name t
| Ast.Statement.ExportValue -> t
in
(* [declare] export [type] {foo [as bar]} from 'module' *)
let export_from source_ns_t loc local_name =
let reason = mk_reason (RIdentifier local_name) loc in
Tvar_resolver.mk_tvar_and_fully_resolve_no_wrap_where cx reason (fun tout ->
let use_t =
match export_kind with
| Ast.Statement.ExportType ->
GetTypeFromNamespaceT
{ use_op = unknown_use; reason; prop_ref = (reason, local_name); tout }
| Ast.Statement.ExportValue ->
GetPropT
{
use_op = unknown_use;
reason;
id = None;
from_annot = false;
propref = mk_named_prop ~reason local_name;
tout;
hint = hint_unavailable;
}
in
Flow.flow cx (source_ns_t, use_t)
)
in
let export_specifier export (loc, { E.ExportSpecifier.local; exported }) =
let (local_loc, ({ Ast.Identifier.name = local_name; comments = _ } as local_id)) = local in
let local_name = OrdinaryName local_name in
let reconstruct_remote =
match exported with
| None -> Fun.const None
| Some (remote_loc, remote_id) -> (fun t -> Some ((remote_loc, t), remote_id))
in
let t = export local_loc local_name in
( loc,
{ E.ExportSpecifier.local = ((local_loc, t), local_id); exported = reconstruct_remote t }
)
in
function
(* [declare] export [type] {foo [as bar]} [from ...]; *)
| E.ExportSpecifiers specifiers ->
let export =
match source with
| Some ((source_loc, module_t), { Ast.StringLiteral.value = module_name; _ }) ->
let source_ns_t =
let reason = mk_reason (RModule module_name) source_loc in
let namespace_symbol = mk_module_symbol ~name:module_name ~def_loc:source_loc in
Import_export.get_module_namespace_type cx reason ~namespace_symbol module_t
in
export_from source_ns_t
| None -> export_ref
in
let specifiers = Base.List.map ~f:(export_specifier export) specifiers in
E.ExportSpecifiers specifiers
(* [declare] export [type] * as id from "source"; *)
| E.ExportBatchSpecifier (specifier_loc, Some (id_loc, ({ Ast.Identifier.name; _ } as id))) ->
let ((_, module_t), _) = Base.Option.value_exn source in
let reason = mk_reason (RIdentifier (OrdinaryName name)) id_loc in
let ns_t =
Import_export.get_module_namespace_type
cx
reason
~namespace_symbol:(mk_constant_symbol ~name ~def_loc:id_loc)
module_t
in
E.ExportBatchSpecifier (specifier_loc, Some ((id_loc, ns_t), id))
(* [declare] export [type] * from "source"; *)
| E.ExportBatchSpecifier (specifier_loc, None) -> E.ExportBatchSpecifier (specifier_loc, None)
let hook_check cx effect (loc, { Ast.Identifier.name; _ }) =
if effect = Ast.Function.Hook && not (Flow_ast_utils.hook_name name) then
Flow.add_output cx Error_message.(EHookNaming loc)
(************)
(* Visitors *)
(************)
(***************************************************************
* local inference pass: visit AST statement list, calling
* flow to check types/create graphs for merge-time checking
***************************************************************)
let rec statement cx ((loc, _) as stmt) =
let node_cache = Context.node_cache cx in
match Node_cache.get_statement node_cache loc with
| Some node ->
Debug_js.Verbose.print_if_verbose_lazy
cx
(lazy [spf "Statement cache hit at %s" (ALoc.debug_to_string loc)]);
node
| None -> statement_ cx stmt
and statement_ cx : (ALoc.t, ALoc.t) Ast.Statement.t -> (ALoc.t, ALoc.t * Type.t) Ast.Statement.t
=
let open Ast.Statement in
let variables cx decls =
VariableDeclaration.(
let { declarations; kind; comments } = decls in
let declarations =
Base.List.map
~f:(fun (loc, { Declarator.id; init }) ->
let (id, init) = variable cx kind id init in
(loc, { Declarator.id; init }))
declarations
in
{ declarations; kind; comments }
)
in
let catch_clause cx catch_clause =
let { Try.CatchClause.param; body = (b_loc, b); comments } = catch_clause in
let open Ast.Pattern in
match param with
| Some p ->
(match p with
| (loc, Identifier { Identifier.name = (name_loc, id); annot; optional }) ->
let (t, ast_annot) =
match annot with
| Ast.Type.Missing mloc ->
let t =
if Context.use_mixed_in_catch_variables cx then
MixedT.at loc
else
AnyT.why CatchAny (mk_reason RAnyImplicit loc)
in
(t, Ast.Type.Missing (mloc, t))
| Ast.Type.Available ((_, (_, (Ast.Type.Any _ | Ast.Type.Mixed _))) as annot) ->
(* Not relevant with our limited accepted annotations. *)
let tparams_map = Subst_name.Map.empty in
let (t, ast_annot) = Anno.mk_type_available_annotation cx tparams_map annot in
(t, Ast.Type.Available ast_annot)
| Ast.Type.Available (_, (loc, _)) ->