fallow-extract 3.45.0

AST extraction engine for fallow codebase intelligence (parser, complexity, SFC / Astro / MDX / CSS)
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
//! Type-signature and typed-binding helpers for the visitor implementation.

use super::visit_helpers::*;
use super::*;
use crate::js_text::JsText;
use crate::{SemanticFact, TypeAliasSurfaceTargetFact};

/// A local in a class method that holds the result of a `this.<name>()` call,
/// such as `table` in `const table = this.find()`. The extractor keeps the
/// locals of one name in declaration order, the outer local first.
#[derive(Debug, Clone)]
pub(in crate::visitor) struct ThisResultLocal {
    /// The `scoped_direct_object_binding_roots` frame that declares the local.
    /// A binding with the same name in a deeper frame hides the local.
    frame: usize,
    /// `this.find()` when a base class declares the method (issue #4183).
    /// `None` when the class itself declares the return type (issue #4033).
    inherited_source: Option<String>,
    /// The deeper frame that binds the same name to a class of its own. A read
    /// in that frame resolves through the class binding, not through the local.
    rebound_frame: Option<usize>,
    /// The deeper frames that hold a copy of an outer binding of the name,
    /// such as the branch of an `instanceof` guard. A copy declares nothing.
    forked_frames: Vec<usize>,
}

/// The visitor state that a method body replaces and its end restores.
pub(super) struct MethodVisitState {
    span: Option<Span>,
    independent_this_depth: usize,
    this_result_locals: FxHashMap<String, Vec<ThisResultLocal>>,
}

impl ModuleInfoExtractor {
    fn collect_type_alias_surface_targets(
        ty: &TSType<'_>,
        type_parameters: &FxHashSet<&str>,
        targets: &mut Vec<String>,
    ) {
        match ty {
            TSType::TSTypeReference(reference) => {
                // `ReturnType<typeof useFooStore>`: a member read through an
                // imported alias credits the store factory.
                if let Some(factory) = Self::store_factory_from_return_type(ty) {
                    targets.push(factory);
                    return;
                }
                let Some((name, _)) = type_name_root(&reference.type_name) else {
                    return;
                };
                if matches!(
                    name.as_str(),
                    "Pick" | "Omit" | "Partial" | "Required" | "Readonly" | "NonNullable"
                ) {
                    if let Some(first) = reference
                        .type_arguments
                        .as_deref()
                        .and_then(|arguments| arguments.params.first())
                    {
                        Self::collect_type_alias_surface_targets(first, type_parameters, targets);
                    }
                } else if !type_parameters.contains(name.as_str()) {
                    targets.push(name);
                }
            }
            TSType::TSUnionType(union) => {
                for branch in &union.types {
                    Self::collect_type_alias_surface_targets(branch, type_parameters, targets);
                }
            }
            TSType::TSIntersectionType(intersection) => {
                for branch in &intersection.types {
                    Self::collect_type_alias_surface_targets(branch, type_parameters, targets);
                }
            }
            TSType::TSParenthesizedType(parenthesized) => {
                Self::collect_type_alias_surface_targets(
                    &parenthesized.type_annotation,
                    type_parameters,
                    targets,
                );
            }
            _ => {}
        }
    }

    fn collect_literal_type_strings(ty: &TSType<'_>, values: &mut Vec<String>) {
        match ty {
            TSType::TSLiteralType(literal) => {
                if let TSLiteral::StringLiteral(value) = &literal.literal {
                    values.push(value.value.text().into_owned());
                }
            }
            TSType::TSUnionType(union) => {
                for branch in &union.types {
                    Self::collect_literal_type_strings(branch, values);
                }
            }
            TSType::TSParenthesizedType(parenthesized) => {
                Self::collect_literal_type_strings(&parenthesized.type_annotation, values);
            }
            _ => {}
        }
    }

    fn collect_pick_member_accesses(
        ty: &TSType<'_>,
        type_parameters: &FxHashSet<&str>,
        accesses: &mut Vec<MemberAccess>,
    ) {
        match ty {
            TSType::TSTypeReference(reference) => {
                let Some((name, _)) = type_name_root(&reference.type_name) else {
                    return;
                };
                if name != "Pick" {
                    if matches!(
                        name.as_str(),
                        "Partial" | "Required" | "Readonly" | "NonNullable"
                    ) && let Some(first) = reference
                        .type_arguments
                        .as_deref()
                        .and_then(|arguments| arguments.params.first())
                    {
                        Self::collect_pick_member_accesses(first, type_parameters, accesses);
                    }
                    return;
                }
                let Some(arguments) = reference.type_arguments.as_deref() else {
                    return;
                };
                let (Some(target), Some(keys)) =
                    (arguments.params.first(), arguments.params.get(1))
                else {
                    return;
                };
                let mut targets = Vec::new();
                Self::collect_type_alias_surface_targets(target, type_parameters, &mut targets);
                let mut members = Vec::new();
                Self::collect_literal_type_strings(keys, &mut members);
                accesses.extend(targets.into_iter().flat_map(|object| {
                    members.iter().cloned().map(move |member| MemberAccess {
                        object: object.clone(),
                        member,
                    })
                }));
            }
            TSType::TSUnionType(union) => {
                for branch in &union.types {
                    Self::collect_pick_member_accesses(branch, type_parameters, accesses);
                }
            }
            TSType::TSIntersectionType(intersection) => {
                for branch in &intersection.types {
                    Self::collect_pick_member_accesses(branch, type_parameters, accesses);
                }
            }
            TSType::TSParenthesizedType(parenthesized) => {
                Self::collect_pick_member_accesses(
                    &parenthesized.type_annotation,
                    type_parameters,
                    accesses,
                );
            }
            _ => {}
        }
    }

    pub(super) fn record_type_alias_surface_targets(&mut self, alias: &TSTypeAliasDeclaration<'_>) {
        let type_parameters: FxHashSet<&str> = alias
            .type_parameters
            .as_deref()
            .into_iter()
            .flat_map(|parameters| &parameters.params)
            .map(|parameter| parameter.name.name.as_str())
            .collect();
        let mut targets = Vec::new();
        Self::collect_type_alias_surface_targets(
            &alias.type_annotation,
            &type_parameters,
            &mut targets,
        );
        targets.sort_unstable();
        targets.dedup();
        self.semantic_facts
            .extend(targets.into_iter().map(|target_name| {
                SemanticFact::TypeAliasSurfaceTarget(TypeAliasSurfaceTargetFact {
                    alias_name: alias.id.name.to_string(),
                    target_name,
                })
            }));
        let mut picked_members = Vec::new();
        Self::collect_pick_member_accesses(
            &alias.type_annotation,
            &type_parameters,
            &mut picked_members,
        );
        self.member_accesses.extend(picked_members);
    }

    fn remove_type_parameter_refs(
        refs: &mut Vec<(String, Span)>,
        type_parameters: Option<&TSTypeParameterDeclaration<'_>>,
    ) {
        let Some(type_parameters) = type_parameters else {
            return;
        };
        refs.retain(|(name, _)| {
            !type_parameters
                .params
                .iter()
                .any(|parameter| parameter.name.name == name.as_str())
        });
    }

    pub(super) fn record_local_type_declaration(&mut self, name: &str, span: Span) {
        self.local_type_declarations.push(LocalTypeDeclaration {
            name: name.to_string(),
            span,
        });
    }

    /// Keep the first declaration and source order while avoiding a growing
    /// linear scan for every declaration visited in large type-heavy modules.
    pub(crate) fn deduplicate_local_type_declarations(
        declarations: &mut Vec<LocalTypeDeclaration>,
    ) {
        let keep = {
            let mut seen = FxHashSet::default();
            seen.reserve(declarations.len());
            declarations
                .iter()
                .map(|declaration| seen.insert(declaration.name.as_str()))
                .collect::<Vec<_>>()
        };
        let mut keep = keep.into_iter();
        declarations.retain(|_| keep.next().unwrap_or(false));
    }

    pub(super) fn record_local_signature_refs(
        &mut self,
        owner_name: &str,
        refs: Vec<(String, Span)>,
    ) {
        self.push_local_signature_refs(owner_name, refs, false);
    }

    /// Record the types of a `satisfies` clause on a module-level binding.
    /// These types are in use, but they do not form the type of the binding.
    pub(super) fn record_local_satisfies_refs(
        &mut self,
        owner_name: &str,
        refs: Vec<(String, Span)>,
    ) {
        self.push_local_signature_refs(owner_name, refs, true);
    }

    fn push_local_signature_refs(
        &mut self,
        owner_name: &str,
        refs: Vec<(String, Span)>,
        from_satisfies: bool,
    ) {
        self.local_signature_type_references
            .extend(refs.into_iter().map(|(type_name, span)| {
                super::super::LocalSignatureTypeReference {
                    owner_name: owner_name.to_string(),
                    type_name,
                    span,
                    from_satisfies,
                }
            }));
    }

    pub(super) fn record_public_signature_refs(
        &mut self,
        export_name: &str,
        refs: Vec<(String, Span)>,
    ) {
        self.public_signature_type_references
            .extend(
                refs.into_iter()
                    .map(|(type_name, span)| PublicSignatureTypeReference {
                        export_name: export_name.to_string(),
                        type_name,
                        span,
                        from_satisfies: false,
                    }),
            );
    }

    fn collect_type_refs_from_annotation(annotation: &TSTypeAnnotation<'_>) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        collector.visit_ts_type_annotation(annotation);
        collector.refs
    }

    pub(super) fn collect_function_signature_refs(function: &Function<'_>) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        if let Some(type_parameters) = function.type_parameters.as_deref() {
            collector.visit_ts_type_parameter_declaration(type_parameters);
        }
        if let Some(this_param) = function.this_param.as_deref() {
            collector.visit_ts_this_parameter(this_param);
        }
        for param in &function.params.items {
            if let Some(annotation) = param.type_annotation.as_deref() {
                collector.visit_ts_type_annotation(annotation);
            }
        }
        if let Some(rest) = function.params.rest.as_deref()
            && let Some(annotation) = rest.type_annotation.as_deref()
        {
            collector.visit_ts_type_annotation(annotation);
        }
        if let Some(return_type) = function.return_type.as_deref() {
            collector.visit_ts_type_annotation(return_type);
        } else if let Some(body) = function.body.as_deref() {
            collect_inferred_return_refs(body, &mut collector.refs);
        }
        Self::remove_type_parameter_refs(&mut collector.refs, function.type_parameters.as_deref());
        collector.refs
    }

    fn collect_arrow_signature_refs(arrow: &ArrowFunctionExpression<'_>) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        if let Some(type_parameters) = arrow.type_parameters.as_deref() {
            collector.visit_ts_type_parameter_declaration(type_parameters);
        }
        for param in &arrow.params.items {
            if let Some(annotation) = param.type_annotation.as_deref() {
                collector.visit_ts_type_annotation(annotation);
            }
        }
        if let Some(rest) = arrow.params.rest.as_deref()
            && let Some(annotation) = rest.type_annotation.as_deref()
        {
            collector.visit_ts_type_annotation(annotation);
        }
        if let Some(return_type) = arrow.return_type.as_deref() {
            collector.visit_ts_type_annotation(return_type);
        } else if let Some(expression) = arrow.get_expression() {
            collect_returned_expression_refs(
                expression,
                &FxHashMap::default(),
                &mut collector.refs,
            );
        } else if let Some(body) = arrow.get_function_body() {
            collect_inferred_return_refs(body, &mut collector.refs);
        }
        Self::remove_type_parameter_refs(&mut collector.refs, arrow.type_parameters.as_deref());
        collector.refs
    }

    pub(super) fn collect_variable_signature_refs(
        declarator: &VariableDeclarator<'_>,
    ) -> Vec<(String, Span)> {
        let mut refs = Vec::new();
        if let Some(annotation) = declarator.type_annotation.as_deref() {
            refs.extend(Self::collect_type_refs_from_annotation(annotation));
        }
        if let Some(init) = &declarator.init {
            Self::collect_initializer_signature_refs(
                Self::strip_satisfies_clauses(init),
                &mut refs,
            );
        }
        refs
    }

    /// Collect the types that shape the inferred type of a variable
    /// initializer. A type assertion sets the type directly. A call or `new`
    /// wrapper takes its type from its type arguments and from the signature
    /// of a function argument, for example `memo(function C(p: Props) {})`.
    fn collect_initializer_signature_refs(init: &Expression<'_>, refs: &mut Vec<(String, Span)>) {
        match init {
            Expression::ParenthesizedExpression(parenthesized) => {
                Self::collect_initializer_signature_refs(&parenthesized.expression, refs);
            }
            Expression::TSNonNullExpression(non_null) => {
                Self::collect_initializer_signature_refs(&non_null.expression, refs);
            }
            Expression::TSAsExpression(assertion) => {
                Self::collect_asserted_type_refs(&assertion.type_annotation, refs);
            }
            Expression::TSTypeAssertion(assertion) => {
                Self::collect_asserted_type_refs(&assertion.type_annotation, refs);
            }
            Expression::ArrowFunctionExpression(arrow) => {
                refs.extend(Self::collect_arrow_signature_refs(arrow));
            }
            Expression::FunctionExpression(function) => {
                refs.extend(Self::collect_function_signature_refs(function));
            }
            Expression::CallExpression(call) => {
                Self::collect_wrapper_call_signature_refs(
                    call.type_arguments.as_deref(),
                    &call.arguments,
                    refs,
                );
            }
            Expression::NewExpression(new_expression) => {
                Self::collect_wrapper_call_signature_refs(
                    new_expression.type_arguments.as_deref(),
                    &new_expression.arguments,
                    refs,
                );
            }
            _ => {}
        }
    }

    fn collect_asserted_type_refs(ty: &TSType<'_>, refs: &mut Vec<(String, Span)>) {
        let mut collector = SignatureTypeCollector::default();
        collector.visit_ts_type(ty);
        refs.extend(collector.refs);
    }

    fn collect_wrapper_call_signature_refs(
        type_arguments: Option<&TSTypeParameterInstantiation<'_>>,
        arguments: &[Argument<'_>],
        refs: &mut Vec<(String, Span)>,
    ) {
        if let Some(type_arguments) = type_arguments {
            let mut collector = SignatureTypeCollector::default();
            collector.visit_ts_type_parameter_instantiation(type_arguments);
            refs.extend(collector.refs);
        }
        for argument in arguments {
            match argument {
                Argument::ArrowFunctionExpression(arrow) => {
                    refs.extend(Self::collect_arrow_signature_refs(arrow));
                }
                Argument::FunctionExpression(function) => {
                    refs.extend(Self::collect_function_signature_refs(function));
                }
                _ => {}
            }
        }
    }

    /// Return the value under any `satisfies` clauses and parentheses. A
    /// `satisfies` clause does not change the type of the value.
    fn strip_satisfies_clauses<'b>(init: &'b Expression<'b>) -> &'b Expression<'b> {
        match init.without_parentheses() {
            Expression::TSSatisfiesExpression(satisfies) => {
                Self::strip_satisfies_clauses(&satisfies.expression).without_parentheses()
            }
            _ => init,
        }
    }

    /// Collect the types of the `satisfies` clauses on a variable initializer,
    /// for example `Provider` in `["a"] as const satisfies readonly Provider[]`.
    pub(super) fn collect_variable_satisfies_refs(
        declarator: &VariableDeclarator<'_>,
    ) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        let mut current = declarator.init.as_ref();
        while let Some(expression) = current {
            current = match expression.without_parentheses() {
                Expression::TSSatisfiesExpression(satisfies) => {
                    collector.visit_ts_type(&satisfies.type_annotation);
                    Some(&satisfies.expression)
                }
                Expression::TSAsExpression(assertion) => Some(&assertion.expression),
                Expression::TSTypeAssertion(assertion) => Some(&assertion.expression),
                Expression::TSNonNullExpression(non_null) => Some(&non_null.expression),
                _ => None,
            };
        }
        collector.refs
    }

    /// Collect signature type references from a class's heritage clauses: type
    /// parameters, the `extends` super class plus its type arguments, and each
    /// `implements` interface plus its type arguments.
    fn collect_class_heritage_signature_refs(
        class: &Class<'_>,
        collector: &mut SignatureTypeCollector,
    ) {
        if let Some(type_parameters) = class.type_parameters.as_deref() {
            collector.visit_ts_type_parameter_declaration(type_parameters);
        }
        if let Some(heritage) = class.heritage.as_ref() {
            if let Some((name, span)) = expression_root_name(&heritage.expression) {
                collector.refs.push((name, span));
            }
            if let Some(type_arguments) = heritage.type_arguments.as_deref() {
                collector.visit_ts_type_parameter_instantiation(type_arguments);
            }
        }
        for implemented in &class.implements {
            if let Some((name, span)) = type_name_root(&implemented.expression) {
                collector.refs.push((name, span));
            }
            if let Some(type_arguments) = implemented.type_arguments.as_deref() {
                collector.visit_ts_type_parameter_instantiation(type_arguments);
            }
        }
    }

    pub(super) fn collect_class_signature_refs(class: &Class<'_>) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        Self::collect_class_heritage_signature_refs(class, &mut collector);
        for element in &class.body.body {
            match element {
                ClassElement::MethodDefinition(method) => {
                    if matches!(method.accessibility, Some(TSAccessibility::Private))
                        || is_private_member_key(&method.key)
                    {
                        continue;
                    }
                    collector
                        .refs
                        .extend(Self::collect_function_signature_refs(&method.value));
                }
                ClassElement::PropertyDefinition(prop) => {
                    if matches!(prop.accessibility, Some(TSAccessibility::Private))
                        || is_private_member_key(&prop.key)
                    {
                        continue;
                    }
                    if let Some(annotation) = prop.type_annotation.as_deref() {
                        collector.visit_ts_type_annotation(annotation);
                    }
                }
                ClassElement::AccessorProperty(prop) => {
                    if matches!(prop.accessibility, Some(TSAccessibility::Private))
                        || is_private_member_key(&prop.key)
                    {
                        continue;
                    }
                    if let Some(annotation) = prop.type_annotation.as_deref() {
                        collector.visit_ts_type_annotation(annotation);
                    }
                }
                ClassElement::TSIndexSignature(index) => {
                    collector.visit_ts_index_signature(index);
                }
                ClassElement::StaticBlock(_) => {}
            }
        }
        Self::remove_type_parameter_refs(&mut collector.refs, class.type_parameters.as_deref());
        collector.refs
    }

    pub(super) fn collect_interface_signature_refs(
        iface: &TSInterfaceDeclaration<'_>,
    ) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        if let Some(type_parameters) = iface.type_parameters.as_deref() {
            collector.visit_ts_type_parameter_declaration(type_parameters);
        }
        for heritage in &iface.extends {
            if let Some((name, span)) = type_name_root(&heritage.type_name) {
                collector.refs.push((name, span));
            }
            if let Some(type_arguments) = heritage.type_arguments.as_deref() {
                collector.visit_ts_type_parameter_instantiation(type_arguments);
            }
        }
        collector.visit_ts_interface_body(&iface.body);
        Self::remove_type_parameter_refs(&mut collector.refs, iface.type_parameters.as_deref());
        collector.refs
    }

    pub(super) fn collect_type_alias_signature_refs(
        alias: &TSTypeAliasDeclaration<'_>,
    ) -> Vec<(String, Span)> {
        let mut collector = SignatureTypeCollector::default();
        if let Some(type_parameters) = alias.type_parameters.as_deref() {
            collector.visit_ts_type_parameter_declaration(type_parameters);
        }
        collector.visit_ts_type(&alias.type_annotation);
        Self::remove_type_parameter_refs(&mut collector.refs, alias.type_parameters.as_deref());
        collector.refs
    }

    /// Record the class bindings that code can read before the declaration in
    /// source order: the element type of each typed array field or parameter
    /// property, and the `this` return binding of each method.
    pub(super) fn preseed_class_bindings(&mut self, class: &Class<'_>) {
        for element in &class.body.body {
            if let ClassElement::PropertyDefinition(prop) = element {
                if prop.r#static {
                    continue;
                }
                let name = prop.key.static_name().map_or_else(
                    || match &prop.key {
                        PropertyKey::PrivateIdentifier(id) => Some(format!("#{}", id.name)),
                        _ => None,
                    },
                    |name| Some(name.text().into_owned()),
                );
                if let Some(name) = name
                    && let Some(annotation) = prop.type_annotation.as_deref()
                    && let Some(element_type) =
                        array_element_type_from_type(&annotation.type_annotation)
                {
                    self.iterable_element_types
                        .insert(self.this_member_key(&name), element_type);
                }
                continue;
            }
            let ClassElement::MethodDefinition(method) = element else {
                continue;
            };
            self.record_this_return_binding(method);
            if method.kind != MethodDefinitionKind::Constructor {
                continue;
            }
            for param in &method.value.params.items {
                if param.accessibility.is_none() && !param.readonly {
                    continue;
                }
                let BindingPattern::BindingIdentifier(id) = &param.pattern else {
                    continue;
                };
                let Some(annotation) = param.type_annotation.as_deref() else {
                    continue;
                };
                if let Some(element_type) =
                    array_element_type_from_type(&annotation.type_annotation)
                {
                    self.iterable_element_types
                        .insert(self.this_member_key(id.name.as_str()), element_type);
                }
            }
        }
    }

    /// Prepare the visit of a method body. Set the method span, reset the
    /// independent `this` depth, and start an empty set of `this` result
    /// locals. Return the previous state, which the caller gives to
    /// `exit_method_definition` after the walk.
    pub(super) fn enter_method_definition(
        &mut self,
        method: &MethodDefinition<'_>,
    ) -> MethodVisitState {
        MethodVisitState {
            span: self.class_method_function_span.replace(method.value.span),
            independent_this_depth: std::mem::replace(&mut self.independent_this_depth, 0),
            this_result_locals: std::mem::take(&mut self.this_result_locals),
        }
    }

    /// Restore the state that `enter_method_definition` returned.
    pub(super) fn exit_method_definition(&mut self, previous: MethodVisitState) {
        self.class_method_function_span = previous.span;
        self.independent_this_depth = previous.independent_this_depth;
        self.this_result_locals = previous.this_result_locals;
    }

    /// Record a `this` binding for an instance method or getter that declares
    /// a named return type: `this.<name>()` for a method, `this.<name>` for a
    /// getter. A chain such as `this.current()?.onDown?.()` inside the class
    /// then credits `ReturnType.onDown` (issue #3960). The key is scoped to
    /// the enclosing class, and only code of that class reaches `this`, so a
    /// private or a `#`-private member also gives a binding. A static member
    /// gives no binding. A return type that names a type parameter of the
    /// method gives no binding, because that name has no meaning outside the
    /// method. The class visit calls this for each method before it walks the
    /// class body. Thus a local such as `const old = this.current()` resolves
    /// also when the method comes after the call site (issue #4033).
    fn record_this_return_binding(&mut self, method: &MethodDefinition<'_>) {
        let call_suffix = match method.kind {
            MethodDefinitionKind::Method => "()",
            MethodDefinitionKind::Get => "",
            _ => return,
        };
        if method.r#static || self.class_scope_stack.is_empty() {
            return;
        }
        let Some(type_annotation) = method.value.return_type.as_deref() else {
            return;
        };
        let name = match &method.key {
            PropertyKey::PrivateIdentifier(id) => format!("#{}", id.name),
            key => match key.static_name() {
                Some(name) => name.text().into_owned(),
                None => return,
            },
        };
        let names_method_type_param = extract_type_annotation_name(type_annotation)
            .zip(method.value.type_parameters.as_deref())
            .is_some_and(|(type_name, params)| {
                params
                    .params
                    .iter()
                    .any(|param| param.name.name.as_str() == type_name)
            });
        if names_method_type_param {
            return;
        }
        let key = self.this_member_key(&format!("{name}{call_suffix}"));
        self.record_typed_binding(&key, type_annotation);
    }

    /// Bind a local to the declared return type of a method of the enclosing
    /// class: `const old = this.current();` binds `old` to `Tool` when the
    /// class declares `current(): Tool | undefined`. A later
    /// `old?.deactivate?.()` then credits `Tool.deactivate`, as the direct
    /// `this.current()?.deactivate?.()` does (issue #4033).
    ///
    /// Only a call directly on `this` gives a binding. The arguments do not
    /// change the binding: `this.findBy(1)` binds to the return type of
    /// `findBy`, as the direct `this.findBy(1)?.reset()` does (issue #4199).
    /// A cast (`as`) and a call in a function with its own `this` give no
    /// binding.
    pub(super) fn record_this_method_result_alias(
        &mut self,
        declarator: &VariableDeclarator<'_>,
        init: &Expression<'_>,
    ) {
        let BindingPattern::BindingIdentifier(id) = &declarator.id else {
            return;
        };
        let frame = self.current_binding_frame();
        // A declaration in the frame of the local replaces it. A declaration
        // in a deeper frame is a shadow, which the frame roots record. The
        // outer local stays for the reads after the deeper frame ends.
        if let Some(locals) = self.this_result_locals.get_mut(id.name.as_str()) {
            locals.retain(|local| local.frame < frame);
        }
        self.mark_factory_local_rebound(id.name.as_str(), init);
        if self.class_scope_stack.is_empty() || self.independent_this_depth > 0 {
            return;
        }
        let Some(name) = this_method_call_name(init) else {
            return;
        };
        let key = self.this_member_key(&format!("{name}()"));
        let inherited_source = match self.binding_target_names.get(&key) {
            Some(BindingTarget::Class(type_name)) => {
                let type_name = type_name.clone();
                self.insert_class_binding_target(id.name.to_string(), type_name);
                None
            }
            // The class does not declare a typed `name()`, so a base class
            // can declare it (issue #4183). Keep the call spelling for the
            // local, so the analysis resolves it through the inherited
            // return type.
            None => Some(format!("this.{name}()")),
            Some(_) => return,
        };
        self.this_result_locals
            .entry(id.name.to_string())
            .or_default()
            .push(ThisResultLocal {
                frame,
                inherited_source,
                rebound_frame: None,
                forked_frames: Vec::new(),
            });
    }

    /// The index of the innermost `scoped_direct_object_binding_roots` frame.
    fn current_binding_frame(&self) -> usize {
        self.scoped_direct_object_binding_roots
            .len()
            .saturating_sub(1)
    }

    /// Whether a binding in a deeper frame hides the `this` result local
    /// `root` (issue #4198). A parameter, a loop head, a `catch` parameter and
    /// a block declaration with the same name hold another value. A deeper
    /// frame that binds the name to a class of its own does not count.
    pub(super) fn this_result_local_is_shadowed(&self, root: &str) -> bool {
        let Some(shadow) = self.this_result_local_shadow_frame(root) else {
            return false;
        };
        self.innermost_this_result_local(root)
            .is_some_and(|local| local.rebound_frame != Some(shadow))
    }

    /// The innermost open `this` result local with the name `root`.
    fn innermost_this_result_local(&self, root: &str) -> Option<&ThisResultLocal> {
        self.this_result_locals
            .get(root)
            .and_then(|locals| locals.last())
    }

    /// The innermost frame that declares `root` above the frame of the `this`
    /// result local `root`. A frame with a copy of an outer binding does not
    /// declare the name.
    fn this_result_local_shadow_frame(&self, root: &str) -> Option<usize> {
        let local = self.innermost_this_result_local(root)?;
        self.scoped_direct_object_binding_roots
            .iter()
            .enumerate()
            .rev()
            .find(|(index, roots)| roots.contains(root) && !local.forked_frames.contains(index))
            .map(|(index, _)| index)
            .filter(|&index| index > local.frame)
    }

    /// Whether `frame` takes a copy of the outer binding of `root` that the
    /// frame `owner` declares. A copy declares nothing, so the function also
    /// records it for a `this` result local with the name `root`.
    pub(super) fn admit_direct_object_binding_fork(
        &mut self,
        root: &str,
        frame: usize,
        owner: Option<usize>,
    ) -> bool {
        if owner.is_some_and(|index| index >= frame) {
            return false;
        }
        if let Some(local) = self
            .this_result_locals
            .get_mut(root)
            .and_then(|locals| locals.last_mut())
            && frame > local.frame
            && !local.forked_frames.contains(&frame)
        {
            local.forked_frames.push(frame);
        }
        true
    }

    /// A local from a bare call such as `const seat = makeSeat()` can hold
    /// a class that a same-file factory returns. The factory resolves after
    /// the walk, so the shadow of a `this` result local counts as a class
    /// binding of its own now. A callee that returns no class falls back to
    /// the module-flat binding of the name.
    fn mark_factory_local_rebound(&mut self, name: &str, init: &Expression<'_>) {
        if !self.this_result_locals.contains_key(name) {
            return;
        }
        let call = match init {
            Expression::AwaitExpression(await_expr) => &await_expr.argument,
            _ => init,
        };
        if Self::bare_call_callee_name(self.class_carrying_init(call)).is_some() {
            self.mark_this_result_local_rebound(name);
        }
    }

    /// Record that the shadow frame of the `this` result local `root` binds
    /// the name to a class of its own.
    pub(super) fn mark_this_result_local_rebound(&mut self, root: &str) {
        let Some(shadow) = self.this_result_local_shadow_frame(root) else {
            return;
        };
        if let Some(local) = self
            .this_result_locals
            .get_mut(root)
            .and_then(|locals| locals.last_mut())
        {
            local.rebound_frame = Some(shadow);
        }
    }

    /// Drop the `this` result locals of a closed frame, and the class
    /// rebinding of a closed shadow frame. `depth` is the number of open
    /// frames.
    pub(super) fn close_this_result_local_frames(&mut self, depth: usize) {
        if self.this_result_locals.is_empty() {
            return;
        }
        self.this_result_locals.retain(|_, locals| {
            locals.retain(|local| local.frame < depth);
            for local in locals.iter_mut() {
                if local.rebound_frame.is_some_and(|frame| frame >= depth) {
                    local.rebound_frame = None;
                }
                local.forked_frames.retain(|&frame| frame < depth);
            }
            !locals.is_empty()
        });
    }

    /// Record a read through a local that holds an inherited `this` method
    /// result also on the call spelling: `table.setVip` gives
    /// `this.find().setVip` for `const table = this.find()`. The analysis
    /// then credits `setVip` on the return type that a base class declares
    /// for `find()` (issue #4183).
    pub(super) fn record_inherited_this_result_access(&mut self, object_name: &str, member: &str) {
        let (root, rest) = object_name
            .split_once('.')
            .map_or((object_name, None), |(root, rest)| (root, Some(rest)));
        // Any binding in a deeper frame holds another value, also a binding
        // to a class of its own. Only the outer local reads the base class.
        if self.this_result_local_shadow_frame(root).is_some() {
            return;
        }
        let Some(source) = self
            .innermost_this_result_local(root)
            .and_then(|local| local.inherited_source.as_deref())
        else {
            return;
        };
        let source = match rest {
            Some(rest) => format!("{source}.{rest}"),
            None => source.to_string(),
        };
        let object = self.qualify_this_scope(&source);
        self.push_receiver_member_access(object, member.to_string());
    }

    pub(super) fn record_typed_binding(
        &mut self,
        binding_name: &str,
        type_annotation: &TSTypeAnnotation<'_>,
    ) {
        if let Some(factory) = self.store_factory_for_type(&type_annotation.type_annotation) {
            self.insert_class_binding_target(binding_name.to_string(), factory);
            self.store_instance_locals.insert(binding_name.to_string());
        } else if let Some(type_name) = extract_type_annotation_name(type_annotation)
            && let Some(resolved) = self.resolve_class_type_param(&type_name)
        {
            let origin = self.resolve_class_type_param_origin(
                &type_name,
                super::super::helpers::extract_type_reference_origin(
                    &type_annotation.type_annotation,
                ),
            );
            self.record_binding_class_proof(binding_name, &resolved, origin);
            self.insert_class_binding_target(binding_name.to_string(), resolved);
        }

        self.record_typed_nested_bindings(binding_name, type_annotation);
    }

    pub(super) fn record_typed_nested_bindings(
        &mut self,
        binding_name: &str,
        type_annotation: &TSTypeAnnotation<'_>,
    ) {
        for (property_path, type_name, origin) in
            super::super::helpers::extract_nested_type_bindings(type_annotation)
        {
            if let Some(factory) = self.store_factory_for_type_name(&type_name) {
                self.insert_class_binding_target(
                    format!("{binding_name}.{property_path}"),
                    factory,
                );
                continue;
            }
            let Some(resolved) = self.resolve_class_type_param(&type_name) else {
                continue;
            };
            self.record_binding_class_proof(
                &format!("{binding_name}.{property_path}"),
                &resolved,
                self.resolve_class_type_param_origin(&type_name, origin),
            );
            self.insert_class_binding_target(format!("{binding_name}.{property_path}"), resolved);
        }
    }

    /// Record destructured bindings with type annotations.
    pub(super) fn record_typed_destructure_binding(
        &mut self,
        pattern: &ObjectPattern<'_>,
        type_annotation: &TSTypeAnnotation<'_>,
    ) {
        let bindings = extract_object_pattern_bindings(pattern);
        if bindings.is_empty() {
            return;
        }
        if let TSType::TSTypeLiteral(type_lit) = &type_annotation.type_annotation {
            let properties = collect_object_type_property_types(&type_lit.members);
            for (local, key) in bindings {
                let Some(class_name) = properties.get(&key) else {
                    continue;
                };
                if let Some(factory) = self.store_factory_for_type_name(&class_name.name) {
                    self.insert_class_binding_target(local.clone(), factory);
                    self.store_instance_locals.insert(local);
                    continue;
                }
                let origin = super::super::helpers::extract_nested_type_bindings(type_annotation)
                    .into_iter()
                    .find(|(path, _, _)| path == &key)
                    .and_then(|(_, _, origin)| origin);
                self.record_binding_class_proof(&local, &class_name.name, origin);
                self.insert_class_binding_target_if_absent(local, class_name.name.clone());
            }
        } else if let Some(type_name) = extract_type_annotation_name(type_annotation) {
            for (local, key) in bindings {
                if let Some(target) = self
                    .interface_property_types
                    .get(&type_name)
                    .and_then(|properties| properties.get(&key))
                    .cloned()
                {
                    let owner_reference = super::super::helpers::extract_type_reference_origin(
                        &type_annotation.type_annotation,
                    );
                    if let (Some(reference), Some(owner)) = (owner_reference, target.owner_span) {
                        self.record_binding_class_proof(
                            &local,
                            &target.name,
                            target.reference_span,
                        );
                        self.add_direct_binding_requirement(&local, reference, owner);
                    }
                }
                self.pending_typed_destructures
                    .push((local, key, type_name.clone()));
            }
        }
    }
}

/// A function-valued binding declared directly in a function body.
#[derive(Clone, Copy)]
enum LocalCallable<'b, 'a> {
    Function(&'b Function<'a>),
    Arrow(&'b ArrowFunctionExpression<'a>),
}

/// Collect type references that reach the inferred return type of a function
/// without a return annotation. Only the returned values count: inline
/// functions, `as` assertions, and local functions that a return statement
/// names. Type annotations on other body values stay private, so a type that
/// only annotates a local value keeps its unused finding.
fn collect_inferred_return_refs(body: &FunctionBody<'_>, refs: &mut Vec<(String, Span)>) {
    let locals = collect_local_callables(body);
    let mut collector = ReturnedValueCollector {
        locals: &locals,
        refs,
    };
    collector.visit_function_body(body);
}

fn collect_local_callables<'b, 'a>(
    body: &'b FunctionBody<'a>,
) -> FxHashMap<&'b str, LocalCallable<'b, 'a>> {
    let mut locals = FxHashMap::default();
    for statement in &body.statements {
        match statement {
            Statement::FunctionDeclaration(function) => {
                if let Some(id) = function.id.as_ref() {
                    locals.insert(id.name.as_str(), LocalCallable::Function(function));
                }
            }
            Statement::VariableDeclaration(declaration) => {
                for declarator in &declaration.declarations {
                    let (BindingPattern::BindingIdentifier(id), Some(init)) =
                        (&declarator.id, &declarator.init)
                    else {
                        continue;
                    };
                    let callable = match init.without_parentheses() {
                        Expression::ArrowFunctionExpression(arrow) => LocalCallable::Arrow(arrow),
                        Expression::FunctionExpression(function) => {
                            LocalCallable::Function(function)
                        }
                        _ => continue,
                    };
                    locals.insert(id.name.as_str(), callable);
                }
            }
            _ => {}
        }
    }
    locals
}

fn collect_returned_expression_refs(
    expression: &Expression<'_>,
    locals: &FxHashMap<&str, LocalCallable<'_, '_>>,
    refs: &mut Vec<(String, Span)>,
) {
    match expression {
        Expression::ParenthesizedExpression(inner) => {
            collect_returned_expression_refs(&inner.expression, locals, refs);
        }
        Expression::TSSatisfiesExpression(inner) => {
            collect_returned_expression_refs(&inner.expression, locals, refs);
        }
        Expression::TSNonNullExpression(inner) => {
            collect_returned_expression_refs(&inner.expression, locals, refs);
        }
        Expression::TSAsExpression(assertion) => {
            let mut collector = SignatureTypeCollector::default();
            collector.visit_ts_type(&assertion.type_annotation);
            refs.extend(collector.refs);
        }
        Expression::ArrowFunctionExpression(arrow) => {
            refs.extend(ModuleInfoExtractor::collect_arrow_signature_refs(arrow));
        }
        Expression::FunctionExpression(function) => {
            refs.extend(ModuleInfoExtractor::collect_function_signature_refs(
                function,
            ));
        }
        Expression::Identifier(identifier) => match locals.get(identifier.name.as_str()) {
            Some(LocalCallable::Function(function)) => {
                refs.extend(ModuleInfoExtractor::collect_function_signature_refs(
                    function,
                ));
            }
            Some(LocalCallable::Arrow(arrow)) => {
                refs.extend(ModuleInfoExtractor::collect_arrow_signature_refs(arrow));
            }
            None => {}
        },
        Expression::ObjectExpression(object) => {
            for property in &object.properties {
                if let ObjectPropertyKind::ObjectProperty(property) = property {
                    collect_returned_expression_refs(&property.value, locals, refs);
                }
            }
        }
        Expression::ArrayExpression(array) => {
            for element in &array.elements {
                if let Some(element) = element.as_expression() {
                    collect_returned_expression_refs(element, locals, refs);
                }
            }
        }
        Expression::ConditionalExpression(conditional) => {
            collect_returned_expression_refs(&conditional.consequent, locals, refs);
            collect_returned_expression_refs(&conditional.alternate, locals, refs);
        }
        Expression::LogicalExpression(logical) => {
            collect_returned_expression_refs(&logical.left, locals, refs);
            collect_returned_expression_refs(&logical.right, locals, refs);
        }
        _ => {}
    }
}

/// Visit the return statements of one function body. Nested functions and
/// classes own their return statements, so the walk does not enter them.
struct ReturnedValueCollector<'r, 'b, 'a> {
    locals: &'r FxHashMap<&'b str, LocalCallable<'b, 'a>>,
    refs: &'r mut Vec<(String, Span)>,
}

impl<'a> Visit<'a> for ReturnedValueCollector<'_, '_, '_> {
    fn visit_return_statement(&mut self, statement: &ReturnStatement<'a>) {
        if let Some(argument) = &statement.argument {
            collect_returned_expression_refs(argument, self.locals, self.refs);
        }
    }

    fn visit_function(&mut self, _function: &Function<'a>, _flags: ScopeFlags) {}

    fn visit_arrow_function_expression(&mut self, _arrow: &ArrowFunctionExpression<'a>) {}

    fn visit_class(&mut self, _class: &Class<'a>) {}
}

/// The method name of a call on `this`: `current` for `this.current()`,
/// `this.current?.()` or `this.current(1)`, `#current` for `this.#current()`.
/// The arguments do not change the name. Parentheses and a non-null assertion
/// around the call are transparent. Any other expression, a cast included,
/// gives `None`.
fn this_method_call_name(init: &Expression<'_>) -> Option<String> {
    let mut expr = init;
    let call = loop {
        match expr {
            Expression::ParenthesizedExpression(wrapper) => expr = &wrapper.expression,
            Expression::TSNonNullExpression(wrapper) => expr = &wrapper.expression,
            Expression::CallExpression(call) => break call,
            Expression::ChainExpression(chain) => match &chain.expression {
                ChainElement::CallExpression(call) => break call,
                _ => return None,
            },
            _ => return None,
        }
    };
    match &call.callee {
        Expression::StaticMemberExpression(member)
            if matches!(member.object, Expression::ThisExpression(_)) =>
        {
            Some(member.property.name.to_string())
        }
        Expression::PrivateFieldExpression(member)
            if matches!(member.object, Expression::ThisExpression(_)) =>
        {
            Some(format!("#{}", member.field.name))
        }
        _ => None,
    }
}