-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
name_def_ordering.ml
1573 lines (1476 loc) · 62.5 KB
/
name_def_ordering.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.
*)
open Reason
open Loc_collections
open Name_def
open Dependency_sigs
module EnvMap = Env_api.EnvMap
module EnvSet = Env_api.EnvSet
module EnvMapToEnvSet = struct
type key = Env_api.EnvKey.t
type value = EnvSet.t
type t = ALoc.t Nel.t EnvMap.t EnvMap.t
let find key map = EnvMap.find key map |> EnvMap.keys |> EnvSet.of_list
end
module Tarjan =
Tarjan.Make
(struct
include Env_api.EnvKey
let to_string (_, l) = ALoc.debug_to_string l
end)
(EnvSet)
(EnvMapToEnvSet)
type 'k blame = {
payload: 'k;
reason: ALoc.t virtual_reason;
annot_locs: ALoc.t Env_api.annot_loc list;
recursion: ALoc.t list;
}
type element =
| Normal of Env_api.EnvKey.t
| Resolvable of Env_api.EnvKey.t
| Illegal of Env_api.EnvKey.t blame
type result =
| Singleton of element
| ResolvableSCC of element Nel.t
| IllegalSCC of (element blame * bool) Nel.t
let string_of_element graph =
let print_elt k =
match EnvMap.find_opt k graph with
| None -> "MISSING DEFINITION"
| Some (def, _, _, _) -> Print.string_of_source def
in
function
| Normal (k, l) ->
Utils_js.spf
"[%s (%s): %s]"
(ALoc.debug_to_string l)
(Env_api.show_def_loc_type k)
(print_elt (k, l))
| Resolvable (k, l) ->
Utils_js.spf
"[recursive %s (%s): %s]"
(ALoc.debug_to_string l)
(Env_api.show_def_loc_type k)
(print_elt (k, l))
| Illegal { payload = (k, l); _ } ->
Utils_js.spf
"[illegal %s (%s): %s]"
(ALoc.debug_to_string l)
(Env_api.show_def_loc_type k)
(print_elt (k, l))
let string_of_component graph = function
| Singleton elt -> string_of_element graph elt
| ResolvableSCC elts ->
Utils_js.spf
"{(recursive cycle)\n%s\n}"
(Nel.to_list elts |> Base.List.map ~f:(string_of_element graph) |> String.concat ",\n")
| IllegalSCC elts ->
Utils_js.spf
"{(illegal cycle)\n%s\n}"
(Nel.to_list elts
|> Base.List.map ~f:(fun ({ payload = elt; _ }, _) -> string_of_element graph elt)
|> String.concat ",\n"
)
class toplevel_expression_collector =
object (this)
inherit [(ALoc.t, ALoc.t) Ast.Expression.t list, ALoc.t] Flow_ast_visitor.visitor ~init:[]
method! expression expr =
this#update_acc (fun acc -> expr :: acc);
expr
method! class_ _ x = x
method! function_declaration _ x = x
method! function_expression _ x = x
method! arrow_function _ x = x
end
module type S = sig
type cx
val build_ordering :
cx ->
autocomplete_hooks:Env_api.With_ALoc.autocomplete_hooks ->
Env_api.env_info ->
(Name_def.def * 'a * ALoc.t list * ALoc.t Reason.virtual_reason) EnvMap.t ->
result Base.List.t
end
module Make (Context : C) (FlowAPIUtils : F with type cx = Context.t) : S with type cx = Context.t =
struct
type cx = Context.t
module FindDependencies : sig
val depends :
Context.t ->
autocomplete_hooks:Env_api.With_ALoc.autocomplete_hooks ->
EnvMap.key EnvMap.t ->
Env_api.env_info ->
Env_api.def_loc_type ->
ALoc.t ->
Name_def.def ->
ALoc.t Nel.t EnvMap.t
val recursively_resolvable : Name_def.def -> bool
end = struct
(* This analysis consumes variable defs and returns a map representing the variables that need to be
resolved before we can resolve this def.
Consider for example the program
1: var x = 42;
2: type T = typeof x;
And let's specifically look at the def `TypeAlias(type T = typeof x)`, which will be one of the
defs generated by the analysis in `name_def.ml`. Given this def, the question that this module
answers is what variable definitions need to be resolved before the `TypeAlias` def itself can be resolved.
We can see that the type alias depends on reading `x`, so in order to actually resolve the type alias, we
first need to know the type of `x`. In order to do that, we need to have resolved the writes that (according
to the name_resolver) reach this reference to `x`. That's what this analysis tells us--it will traverse the
TypeAlias def, find the read of `x`, and add the writes to `x` that reach that read to the set of defs that need to
be resolved before the type alias can be resolved. We'll ultimately use this to figure out the correct ordering
of nodes.
The actual output of this analysis is a map, whose keys are the locations of variables whose defs need to be resolved
before this def can be. The values of this map are the locations within the def itself that led us to those variable definitions--
in this case, the result will be [def of `x`] => [dereference of `x`]. This information is included for good error messages eventually,
but the more important bit for the correctness of the analysis is the keys of the map--it may be easier to think of the map
as a set and ignore the values.
*)
(* Helper class for the dependency analysis--traverse the AST nodes
in a def to determine which variables appear *)
class use_visitor
cx
~named_only_for_synthesis
this_super_dep_loc_map
({ Env_api.env_values; env_entries; providers; _ } as env)
init =
object (this)
inherit [ALoc.t Nel.t EnvMap.t, ALoc.t] Flow_ast_visitor.visitor ~init as super
val mutable seen : ALocSet.t = ALocSet.empty
method add ~why t =
if Env_api.has_assigning_write t env_entries then
this#update_acc (fun uses ->
EnvMap.update
t
(function
| None -> Some (Nel.one why)
| Some locs ->
Some
( if Nel.mem ~equal:ALoc.equal why locs then
locs
else
Nel.cons why locs
))
uses
)
method add_write_locs ~for_type write_locs =
let writes =
write_locs
|> Base.List.concat_map ~f:(Env_api.writes_of_write_loc ~for_type providers)
|> Base.List.map ~f:(fun kind_and_loc ->
EnvMap.find_opt kind_and_loc this_super_dep_loc_map
|> Base.Option.value ~default:kind_and_loc
)
in
let refinements =
Base.List.concat_map ~f:(Env_api.refinements_of_write_loc env) write_locs
in
let rec writes_of_refinement refi =
let open Env_api.Refi in
match refi with
| InstanceOfR exp -> ignore (this#expression exp)
| LatentR { func; targs; arguments; index = _ } ->
ignore @@ this#expression func;
ignore @@ Flow_ast_mapper.map_opt this#call_type_args targs;
ignore @@ this#arg_list arguments
| SentinelR (_prop, loc) -> this#add ~why:loc (Env_api.ExpressionLoc, loc)
| AndR (l, r)
| OrR (l, r) ->
writes_of_refinement l;
writes_of_refinement r
| NotR r -> writes_of_refinement r
| TruthyR
| NullR
| UndefinedR
| MaybeR
| IsArrayR
| BoolR _
| FunctionR
| NumberR _
| BigIntR _
| ObjectR
| StringR _
| SymbolR _
| SingletonBoolR _
| SingletonStrR _
| SingletonNumR _
| SingletonBigIntR _
| PropNullishR _
| PropExistsR _ ->
()
in
Base.List.iter ~f:writes_of_refinement refinements;
writes
method find_writes ~for_type ?(allow_missing = false) loc =
let write_locs =
try Env_api.write_locs_of_read_loc env_values loc with
| Not_found ->
if not allow_missing then
FlowAPIUtils.add_output cx Error_message.(EInternal (loc, MissingEnvRead loc));
[]
in
this#add_write_locs ~for_type write_locs
(* In order to resolve a def containing a variable read, the writes that the
Name_resolver determines reach the variable must be resolved *)
method! identifier ((loc, _) as id) =
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
id
method! type_identifier_reference ((loc, _) as id) =
let writes = this#find_writes ~for_type:true loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
id
(* In order to resolve a def containing a variable read, the writes that the
Name_resolver determines reach the variable must be resolved *)
method! yield loc yield =
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
super#yield loc yield
(* In order to resolve a def containing a variable write, the
write itself should first be resolved *)
method! pattern_identifier ?kind:_ ((loc, _) as id) =
( if Provider_api.is_provider providers loc then
(* If this is a provider, then we still need to have *all* providers,
for this location added, because type-at-pos will show their union. We
won't call this method directly when resolving an assignment--only when
resolving a larger name_def (e.g. an unsynthesizable function) that
includes an assignment expression. *)
let { Provider_api.providers = provider_entries; _ } =
Base.Option.value_exn (Provider_api.providers_of_def providers loc)
in
Base.List.iter
~f:(fun { Provider_api.reason = r; _ } ->
let key = (Env_api.OrdinaryNameLoc, Reason.loc_of_reason r) in
this#add ~why:loc key)
provider_entries
);
(* Ignore cases that don't have bindings in the environment, like `var x;`
and illegal or unreachable writes. *)
this#add ~why:loc (Env_api.OrdinaryNameLoc, loc);
id
method! binding_type_identifier ((loc, _) as id) =
this#add ~why:loc (Env_api.OrdinaryNameLoc, loc);
id
method! this_expression loc this_ =
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
this_
method! super_expression loc this_ =
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
this_
method! jsx_element_name_identifier (ident : (ALoc.t, ALoc.t) Ast.JSX.Identifier.t) =
let (loc, _) = ident in
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
super#jsx_identifier ident
method private jsx_function_call loc =
match (Context.react_runtime cx, Context.jsx cx) with
| (Options.ReactRuntimeClassic, Options.Jsx_react) ->
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes
| (_, Options.Jsx_pragma (_, (_, Ast.Expression.Identifier _))) ->
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes
| (Options.ReactRuntimeClassic, Options.Jsx_pragma (_, ast)) ->
ignore @@ this#expression ast
| _ -> ()
method! jsx_element loc expr =
let open Ast.JSX in
let { opening_element; closing_element; _ } = expr in
let loc =
match closing_element with
| None -> fst opening_element
| _ -> loc
in
this#jsx_function_call loc;
super#jsx_element loc expr
method! jsx_fragment loc expr =
this#jsx_function_call loc;
super#jsx_fragment loc expr
method component_ref_param_maybe param =
let (_, { Ast.Statement.ComponentDeclaration.Param.name; _ }) = param in
begin
match (name, Context.react_runtime cx, Context.jsx cx) with
| ( ( Ast.Statement.ComponentDeclaration.Param.Identifier
(loc, { Ast.Identifier.name = "ref"; _ })
| Ast.Statement.ComponentDeclaration.Param.StringLiteral
(loc, { Ast.StringLiteral.value = "ref"; _ }) ),
Options.ReactRuntimeClassic,
Options.Jsx_react
) ->
let writes = this#find_writes ~for_type:false loc in
Base.List.iter ~f:(this#add ~why:loc) writes
| _ -> ()
end
method! component_param param =
this#component_ref_param_maybe param;
super#component_param param
(* Skip names in function parameter types (e.g. declared functions) *)
method! function_param_type (fpt : ('loc, 'loc) Ast.Type.Function.Param.t) =
let open Ast.Type.Function.Param in
let (_, { annot; _ }) = fpt in
let _annot' = this#type_ annot in
fpt
method! member_property_identifier (id : (ALoc.t, ALoc.t) Ast.Identifier.t) = id
method! typeof_member_identifier ident = ident
method! member_type_identifier (id : (ALoc.t, ALoc.t) Ast.Identifier.t) = id
method! pattern_object_property_identifier_key ?kind:_ id = id
method! enum_member_identifier id = id
method! object_key_identifier (id : (ALoc.t, ALoc.t) Ast.Identifier.t) = id
method! remote_identifier ident = ident
method! component_param_name name = name
method! export_named_declaration_specifier
(spec : ('loc, 'loc) Ast.Statement.ExportNamedDeclaration.ExportSpecifier.t) =
let open Ast.Statement.ExportNamedDeclaration.ExportSpecifier in
(* Ignore renamed export *)
let (_, { local; exported = _ }) = spec in
let _local : (_, _) Ast.Identifier.t = this#identifier local in
spec
(* For classes/functions that are known to be fully annotated, we skip property bodies *)
method function_def ~fully_annotated (expr : ('loc, 'loc) Ast.Function.t) =
let { Ast.Function.params; body; predicate; return; tparams; _ } = expr in
let open Flow_ast_mapper in
let _ = this#function_return_annotation return in
let _ =
if fully_annotated then
(body, this#function_params_annotated params, predicate)
else
( this#function_body_any body,
this#function_params params,
map_opt this#predicate predicate
)
in
let _ = map_opt this#type_params tparams in
()
method component_def (expr : ('loc, 'loc) Ast.Statement.ComponentDeclaration.t) =
let { Ast.Statement.ComponentDeclaration.params; renders; tparams; _ } = expr in
let open Flow_ast_mapper in
let _ = this#component_renders_annotation renders in
let _ = this#component_params_annotated params in
let _ = map_opt this#type_params tparams in
()
method! declare_component _ (expr : ('loc, 'loc) Ast.Statement.DeclareComponent.t) =
let { Ast.Statement.DeclareComponent.params; renders; tparams; _ } = expr in
let open Flow_ast_mapper in
let _ = this#component_renders_annotation renders in
let _ = map_opt this#type_params tparams in
let _ = this#component_type_params params in
expr
method function_param_pattern_annotated (expr : ('loc, 'loc) Ast.Pattern.t) =
let open Ast.Pattern in
let open Flow_ast_mapper in
let (_, patt) = expr in
begin
match patt with
| Object { Object.properties; annot; comments = _ } ->
let _properties' =
map_list this#function_param_pattern_object_p_annotated properties
in
let _annot' = this#type_annotation_hint annot in
()
| Array { Array.elements; annot; comments = _ } ->
let _elements' = map_list this#function_param_pattern_array_e_annotated elements in
let _annot' = this#type_annotation_hint annot in
()
| Identifier { Identifier.name; annot; optional = _ } ->
let _name' = this#pattern_identifier name in
let _annot' = this#type_annotation_hint annot in
()
| Expression e -> ignore @@ id this#pattern_expression e patt (fun e -> Expression e)
end;
expr
method! function_param param =
let open Ast.Function.Param in
let (loc, { argument; default = _ }) = param in
if (not (Flow_ast_utils.pattern_has_binding argument)) && not (pattern_has_annot argument)
then
this#add ~why:loc (Env_api.FunctionParamLoc, loc);
super#function_param param
method visit_annotation_in_pattern (expr : ('loc, 'loc) Ast.Pattern.t) =
let open Ast.Pattern in
let (_, patt) = expr in
match patt with
| Object { Object.properties = _; annot; comments = _ }
| Array { Array.elements = _; annot; comments = _ }
| Identifier { Identifier.name = _; annot; optional = _ } ->
ignore @@ this#type_annotation_hint annot
| Expression _ -> ()
method function_param_pattern_object_p_annotated
(p : ('loc, 'loc) Ast.Pattern.Object.property) =
let open Ast.Pattern.Object in
let open Flow_ast_mapper in
match p with
| Property prop ->
id this#function_param_pattern_object_property_annotated prop p (fun prop ->
Property prop
)
| RestElement prop ->
id this#function_param_pattern_object_rest_property_annotated prop p (fun prop ->
RestElement prop
)
method function_param_pattern_object_property_annotated
(prop : ('loc, 'loc) Ast.Pattern.Object.Property.t) =
let open Ast.Pattern.Object.Property in
let (_, { key; pattern; default = _; shorthand = _ }) = prop in
let _key' = this#pattern_object_property_key key in
let _pattern' = this#function_param_pattern_annotated pattern in
(* Skip default *)
prop
method function_param_pattern_object_rest_property_annotated
(prop : ('loc, 'loc) Ast.Pattern.RestElement.t) =
let open Ast.Pattern.RestElement in
let (_, { argument; comments = _ }) = prop in
let _argument' = this#function_param_pattern_annotated argument in
prop
method function_param_pattern_array_e_annotated (e : ('loc, 'loc) Ast.Pattern.Array.element)
=
let open Ast.Pattern.Array in
let open Flow_ast_mapper in
match e with
| Hole _ -> e
| Element elem ->
id this#function_param_pattern_array_element_annotated elem e (fun elem -> Element elem)
| RestElement elem ->
id this#function_param_pattern_array_rest_element_annotated elem e (fun elem ->
RestElement elem
)
method function_param_pattern_array_element_annotated
(elem : ('loc, 'loc) Ast.Pattern.Array.Element.t) =
let open Ast.Pattern.Array.Element in
let (_, { argument; default = _ }) = elem in
let _argument' = this#function_param_pattern_annotated argument in
(* Skip default *)
elem
method function_param_pattern_array_rest_element_annotated
(elem : ('loc, 'loc) Ast.Pattern.RestElement.t) =
let open Ast.Pattern.RestElement in
let (_, { argument; comments = _ }) = elem in
let _argument' = this#function_param_pattern_annotated argument in
elem
method component_params_annotated
(params : ('loc, 'loc) Ast.Statement.ComponentDeclaration.Params.t) =
let open Flow_ast_mapper in
let open Ast.Statement.ComponentDeclaration in
let (_, { Params.params = params_list; rest; comments = _ }) = params in
let _ = map_list this#component_param_annotated params_list in
let _ = map_opt this#component_rest_param_annotated rest in
params
method component_param_annotated
(param : ('loc, 'loc) Ast.Statement.ComponentDeclaration.Param.t) =
let open Ast.Statement.ComponentDeclaration.Param in
let (_, { local; _ }) = param in
let _ = this#function_param_pattern_annotated local in
this#component_ref_param_maybe param;
param
method component_rest_param_annotated
(param : ('loc, 'loc) Ast.Statement.ComponentDeclaration.RestParam.t) =
let open Ast.Statement.ComponentDeclaration.RestParam in
let (_, { argument; _ }) = param in
let _ = this#function_param_pattern_annotated argument in
param
method function_params_annotated (params : ('loc, 'loc) Ast.Function.Params.t) =
let open Flow_ast_mapper in
let open Ast.Function in
let (_, { Params.params = params_list; rest; comments = _; this_ }) = params in
let _ = map_list this#function_param_annotated params_list in
let _ = map_opt this#function_rest_param_annotated rest in
let _ = map_opt this#function_this_param this_ in
params
method function_param_annotated (param : ('loc, 'loc) Ast.Function.Param.t) =
let open Ast.Function.Param in
let (loc, { argument; default = _ }) = param in
(* Skip default *)
let _ = this#function_param_pattern_annotated argument in
if (not (Flow_ast_utils.pattern_has_binding argument)) && not (pattern_has_annot argument)
then
this#add ~why:loc (Env_api.FunctionParamLoc, loc);
param
method function_rest_param_annotated (expr : ('loc, 'loc) Ast.Function.RestParam.t) =
let open Ast.Function.RestParam in
let (_, { argument; comments = _ }) = expr in
let _argument' = this#function_param_pattern_annotated argument in
expr
method! type_guard guard =
let open Ast.Type.TypeGuard in
let (_, { guard = (_x, t); _ }) = guard in
(* We don't need to include the type guard name here *)
let _ = Flow_ast_mapper.map_opt this#type_ t in
guard
method! function_ loc expr =
let { Ast.Function.id; params; return; _ } = expr in
if not named_only_for_synthesis then (
(match id with
| Some _ -> ()
| None -> this#add ~why:loc (Env_api.OrdinaryNameLoc, loc));
super#function_ loc expr
) else (
(* Even if we skip the body of the function,
we still need to collect dependencies on the signature of a function. *)
ignore @@ this#function_return_annotation return;
let (_, { Ast.Function.Params.params = params_list; rest; comments = _; this_ }) =
params
in
Base.List.iter params_list ~f:(fun (_, { Ast.Function.Param.argument; _ }) ->
this#visit_annotation_in_pattern argument
);
Base.Option.iter rest ~f:(fun (_, { Ast.Function.RestParam.argument; _ }) ->
this#visit_annotation_in_pattern argument
);
Base.Option.iter this_ ~f:(fun (_, { Ast.Function.ThisParam.annot; _ }) ->
ignore @@ this#type_annotation annot
);
expr
)
method class_extends_sig
((_, { Ast.Class.Extends.expr; targs; comments = _ }) : ('loc, 'loc) Ast.Class.Extends.t)
: unit =
Base.Option.iter targs ~f:(fun targs -> ignore @@ this#type_args targs);
(* We only visit expressions that is used to generate the class signature. *)
let rec visit_expr_for_sig ((_, expr') as expr) =
let open Ast.Expression in
match expr' with
| Identifier _ -> ignore @@ this#expression expr
| Member { Member._object; property = Member.PropertyIdentifier _; comments = _ } ->
visit_expr_for_sig _object
| AsExpression { AsExpression.expression = _; annot; comments = _ }
| TypeCast { TypeCast.expression = _; annot; comments = _ } ->
ignore @@ this#type_annotation annot
| _ -> ()
in
visit_expr_for_sig expr
method class_body_annotated (cls_body : ('loc, 'loc) Ast.Class.Body.t) =
let open Ast.Class.Body in
let (_, { body; comments = _ }) = cls_body in
Base.List.iter ~f:this#class_element_annotated body;
cls_body
method class_element_annotated (elem : ('loc, 'loc) Ast.Class.Body.element) =
let open Ast.Class.Body in
match elem with
| Method (_, meth) -> this#class_method_annotated meth
| Property (_, prop) -> this#class_property_annotated prop
| PrivateField (_, field) -> this#class_private_field_annotated field
method class_method_annotated (meth : ('loc, 'loc) Ast.Class.Method.t') =
let open Ast.Class.Method in
let { kind = _; key; value = (_, value); static = _; decorators; comments = _ } = meth in
let _ = Base.List.map ~f:this#class_decorator decorators in
let _ = this#object_key key in
let _ = this#function_def ~fully_annotated:true value in
()
method private class_property_value_annotated value =
let open Ast.Class.Property in
match value with
| Initialized
((_, Ast.Expression.ArrowFunction function_) | (_, Ast.Expression.Function function_))
->
this#function_def ~fully_annotated:true function_;
value
| Initialized _ -> value
| Declared -> value
| Uninitialized -> value
method class_property_annotated (prop : ('loc, 'loc) Ast.Class.Property.t') =
let open Ast.Class.Property in
let { key; value; annot; static = _; variance = _; decorators; comments = _ } = prop in
let _ = Base.List.map ~f:this#class_decorator decorators in
let _ = this#object_key key in
let _ = this#type_annotation_hint annot in
let _ =
match annot with
| Ast.Type.Missing _ -> this#class_property_value_annotated value
| Ast.Type.Available _ -> value
in
()
method class_private_field_annotated (prop : ('loc, 'loc) Ast.Class.PrivateField.t') =
let open Ast.Class.PrivateField in
let { key; value; annot; static = _; variance = _; decorators; comments = _ } = prop in
let _ = Base.List.map ~f:this#class_decorator decorators in
let _ = this#private_name key in
let _ = this#type_annotation_hint annot in
let _ =
match annot with
| Ast.Type.Missing _ -> this#class_property_value_annotated value
| Ast.Type.Available _ -> value
in
()
(* In order to resolve a def containing a read, the writes that the
Name_resolver determines reach the variable must be resolved *)
method! expression ((loc, _) as expr) =
if ALocSet.mem loc seen then
expr
else begin
seen <- ALocSet.add loc seen;
(* An expression might read an refined value. e.g. if (foo.bar) foo.bar.
Therefore, we need to record these writes. *)
let writes = this#find_writes ~for_type:false ~allow_missing:true loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
if not named_only_for_synthesis then (
this#add ~why:loc (Env_api.OrdinaryNameLoc, loc);
this#add ~why:loc (Env_api.ExpressionLoc, loc);
this#add ~why:loc (Env_api.ArrayProviderLoc, loc)
);
super#expression expr
end
method visit_expression_for_expression_writes ((loc, _) as expr) =
let writes = this#find_writes ~for_type:false ~allow_missing:true loc in
Base.List.iter ~f:(this#add ~why:loc) writes;
ignore @@ super#expression expr
end
(* For all the possible defs, explore the def's structure with the class above
to find what variables have to be resolved before this def itself can be resolved *)
let depends
cx
~autocomplete_hooks
this_super_dep_loc_map
({ Env_api.providers; env_entries; predicate_refinement_maps; _ } as env)
kind
id_loc =
let depends_of_node ?(named_only_for_synthesis = false) mk_visit state =
let visitor =
new use_visitor cx ~named_only_for_synthesis this_super_dep_loc_map env EnvMap.empty
in
visitor#set_acc state;
let node_visit () = mk_visit visitor in
visitor#eval node_visit ()
in
let depends_of_tparams_map tparams_map =
depends_of_node (fun visitor ->
ALocMap.iter
(fun loc _ -> visitor#add ~why:loc (Env_api.OrdinaryNameLoc, loc))
tparams_map
)
in
(* depends_of_annotation and of_expression take the `state` parameter from
`depends_of_node` above as an additional currried parameter. *)
let depends_of_annotation tparams_map anno state =
state
|> depends_of_tparams_map tparams_map
|> depends_of_node (fun visitor -> ignore @@ visitor#type_annotation anno)
in
let depends_of_expression
?(named_only_for_synthesis = false) ?(for_expression_writes = false) expr =
depends_of_node ~named_only_for_synthesis (fun visitor ->
if for_expression_writes then
visitor#visit_expression_for_expression_writes expr
else
ignore @@ visitor#expression expr
)
in
let rec depends_of_hint_node state = function
| AnnotationHint (tparams_map, anno) -> depends_of_annotation tparams_map anno state
| ValueHint e -> depends_of_expression e state
| ProvidersHint providers ->
Nel.fold_left
(fun state loc ->
depends_of_node
(fun visitor -> visitor#add ~why:loc (Env_api.OrdinaryNameLoc, loc))
state)
state
providers
| WriteLocHint (kind, loc) ->
depends_of_node (fun visitor -> visitor#add ~why:loc (kind, loc)) state
| StringLiteralType _ -> state
| BuiltinType _ -> state
| AnyErrorHint _ -> state
| ComposedArrayPatternHint (_, elements) ->
Base.List.fold elements ~init:state ~f:(fun state -> function
| ArrayElementPatternHint h
| ArrayRestElementPatternHint h ->
depends_of_hint_node state h
)
| ComposedObjectPatternHint (_, props) ->
Base.List.fold props ~init:state ~f:(fun state -> function
| ObjectPropPatternHint (_, _, h)
| ObjectSpreadPropPatternHint h ->
depends_of_hint_node state h
)
in
let rec depends_of_hint state = function
| Hint.Hint_Placeholder -> state
| Hint.Hint_t (hint_node, _) -> depends_of_hint_node state hint_node
| Hint.Hint_Decomp (ops, hint_node, _) ->
let depends_on_synthesizable_toplevel_expressions acc ~collect =
let collector = new toplevel_expression_collector in
collect collector;
Base.List.fold collector#acc ~init:acc ~f:(fun acc e ->
if Name_def.expression_is_definitely_synthesizable ~autocomplete_hooks e then
depends_of_expression e acc
else
depends_of_expression ~named_only_for_synthesis:true e acc
)
in
Nel.fold_left
(fun acc (_id, op) ->
match op with
| Hint.Decomp_ObjComputed r ->
let loc = loc_of_reason r in
depends_of_node
(fun visitor -> visitor#add ~why:loc (Env_api.ExpressionLoc, loc))
acc
| Hint.Decomp_SentinelRefinement checks ->
SMap.fold
(fun _ check acc ->
match check with
| Hint.Member r ->
let loc = loc_of_reason r in
depends_of_node
(fun visitor -> visitor#add ~why:loc (Env_api.ExpressionLoc, loc))
acc
| _ -> acc)
checks
acc
| Hint.Instantiate_Component { Hint.jsx_props; jsx_children; _ } ->
depends_on_synthesizable_toplevel_expressions acc ~collect:(fun collector ->
Base.List.iter jsx_props ~f:(fun prop ->
ignore @@ collector#jsx_opening_attribute prop
);
ignore @@ collector#jsx_children jsx_children
)
| Hint.Instantiate_Callee
{ Hint.return_hints; arg_list; arg_index; targs; reason = _ } ->
let acc =
depends_of_node
(fun collector ->
Base.Option.iter (Lazy.force targs) ~f:(fun targs ->
ignore @@ collector#call_type_args targs
))
acc
in
let rec loop acc i = function
| [] -> acc
| arg :: rest when i >= arg_index ->
let acc =
depends_on_synthesizable_toplevel_expressions acc ~collect:(fun collector ->
ignore @@ collector#expression_or_spread arg
)
in
loop acc (i + 1) rest
| arg :: rest ->
let acc =
depends_of_node
(fun visitor -> ignore @@ visitor#expression_or_spread arg)
acc
in
loop acc (i + 1) rest
in
let (_, { Ast.Expression.ArgList.arguments; comments = _ }) = Lazy.force arg_list in
loop (depends_of_hints acc (Lazy.force return_hints)) 0 arguments
| _ -> acc)
(depends_of_hint_node state hint_node)
ops
and depends_of_hints state = Base.List.fold ~init:state ~f:depends_of_hint in
let depends_of_fun synth tparams_map ~hints ~statics function_ state =
let (fully_annotated, state) =
match synth with
| FunctionSynthesizable -> (true, state)
| FunctionPredicateSynthesizable (loc, _) ->
let state =
match ALocMap.find_opt loc predicate_refinement_maps with
| None -> state
| Some (_, p_map, n_map) ->
depends_of_node
(fun visitor ->
SMap.iter
(fun _ ({ Env_api.write_locs; _ }, _, _) ->
let writes = visitor#add_write_locs ~for_type:false write_locs in
Base.List.iter ~f:(visitor#add ~why:loc) writes)
p_map;
SMap.iter
(fun _ ({ Env_api.write_locs; _ }, _, _) ->
let writes = visitor#add_write_locs ~for_type:false write_locs in
Base.List.iter ~f:(visitor#add ~why:loc) writes)
n_map)
state
in
(true, state)
| _ -> (false, state)
in
let state = depends_of_hints state hints in
let state =
depends_of_node
(fun visitor -> visitor#function_def ~fully_annotated function_)
(depends_of_tparams_map tparams_map state)
in
depends_of_node (fun visitor -> SMap.iter (fun _ -> visitor#add ~why:id_loc) statics) state
in
let depends_of_component tparams_map component state =
depends_of_node
(fun visitor -> visitor#component_def component)
(depends_of_tparams_map tparams_map state)
in
let depends_of_class
{ Ast.Class.id = _; body; tparams; extends; implements; class_decorators; comments = _ } =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = visitor#class_body_annotated body in
Base.Option.iter ~f:visitor#class_extends_sig extends;
let _ = map_opt visitor#class_implements implements in
let _ = map_list visitor#class_decorator class_decorators in
let _ = map_opt visitor#type_params tparams in
())
EnvMap.empty
in
let depends_of_declared_class
{
Ast.Statement.DeclareClass.id = _;
tparams;
body;
extends;
mixins;
implements;
comments = _;
} =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = map_opt visitor#type_params tparams in
let _ = map_loc visitor#object_type body in
let _ = map_opt (map_loc visitor#generic_type) extends in
let _ = map_list (map_loc visitor#generic_type) mixins in
let _ = map_opt visitor#class_implements implements in
())
EnvMap.empty
in
let depends_of_declared_component loc component =
depends_of_node
(fun visitor ->
let (_ : (_, _) Ast.Statement.DeclareComponent.t) =
visitor#declare_component loc component
in
())
EnvMap.empty
in
let depends_of_declared_namespace
{ Ast.Statement.DeclareNamespace.id = _; body; comments = _ } =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = map_loc visitor#block body in
())
EnvMap.empty
in
let depends_of_alias { Ast.Statement.TypeAlias.tparams; right; _ } =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = map_opt visitor#type_params tparams in
let _ = visitor#type_ right in
())
EnvMap.empty
in
let depends_of_opaque { Ast.Statement.OpaqueType.tparams; impltype; supertype; _ } =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = map_opt visitor#type_params tparams in
let _ = map_opt visitor#type_ impltype in
let _ = map_opt visitor#type_ supertype in
())
EnvMap.empty
in
let depends_of_tparam tparams_map (_, { Ast.Type.TypeParam.bound; variance; default; _ }) =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = visitor#type_annotation_hint bound in
let _ = visitor#variance_opt variance in
let _ = map_opt visitor#type_ default in
())
(depends_of_tparams_map tparams_map EnvMap.empty)
in
let depends_of_interface { Ast.Statement.Interface.tparams; extends; body; _ } =
depends_of_node
(fun visitor ->
let open Flow_ast_mapper in
let _ = map_opt visitor#type_params tparams in
let _ = map_list (map_loc visitor#generic_type) extends in
let _ = map_loc visitor#object_type body in
())
EnvMap.empty
in
let depends_of_hinted_expression ~for_expression_writes hints expr state =
let state = depends_of_expression ~for_expression_writes expr state in
depends_of_hints state hints
in
let depends_of_root state = function
| Annotation { annot; tparams_map; _ } -> depends_of_annotation tparams_map annot state
| Value { hints; expr } ->
let state = depends_of_hints state hints in
depends_of_expression expr state
| ObjectValue { obj; synthesizable = ObjectSynthesizable _; _ } ->
let open Ast.Expression.Object in
let open Ast.Expression.Object.Property in
let open Ast.Expression.Object.SpreadProperty in
let rec depends_of_synthesizable_expression state ((exp_loc, exp) as expression) =
match exp with
| Ast.Expression.Object obj -> loop state obj
| Ast.Expression.TypeCast { Ast.Expression.TypeCast.annot; _ }