fallow-extract 3.46.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
//! 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};

use super::type_flow::TypeFlow;

/// 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);
    }

    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.
    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
    }

    /// Record the type flow of a module-level variable. A variable without a
    /// type annotation gets the whole type flow of its initializer, with its
    /// held names and the flow of each static property path. A function
    /// initializer also gives the flow of its return type under `name()`.
    pub(super) fn record_module_variable_signature_refs(
        &mut self,
        declarator: &VariableDeclarator<'_>,
    ) {
        let satisfies_refs = Self::collect_variable_satisfies_refs(declarator);
        if let (BindingPattern::BindingIdentifier(id), None, Some(init)) = (
            &declarator.id,
            declarator.type_annotation.as_deref(),
            &declarator.init,
        ) {
            let parts = match Self::strip_satisfies_clauses(init).without_parentheses() {
                Expression::ArrowFunctionExpression(arrow) => Some(TypeFlow::of_arrow_parts(arrow)),
                Expression::FunctionExpression(function) => {
                    Some(TypeFlow::of_function_parts(function))
                }
                _ => None,
            };
            if let Some((whole, returned)) = parts {
                self.record_type_flow(&id.name, whole);
                self.record_type_flow(
                    &format!("{}{}", id.name, super::type_flow::CALL_RESULT_SUFFIX),
                    returned,
                );
            } else {
                self.record_type_flow(&id.name, TypeFlow::of_initializer(init));
            }
            self.record_local_satisfies_refs(&id.name, satisfies_refs);
            return;
        }
        let refs = Self::collect_annotated_variable_signature_refs(declarator);
        for id in declarator.id.get_binding_identifiers() {
            self.record_local_signature_refs(&id.name, refs.clone());
            self.record_local_satisfies_refs(&id.name, satisfies_refs.clone());
        }
    }

    /// The signature type references of a variable with a type annotation or
    /// a destructuring pattern. The annotation sets the type. A function, a
    /// call, `new` or a type assertion as the initializer adds the types of
    /// its own signature, for example `memo(function C(p: Props) {})`.
    fn collect_annotated_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 {
            let init = Self::strip_satisfies_clauses(init);
            let mut inner = init.without_parentheses();
            while let Expression::TSNonNullExpression(non_null) = inner {
                inner = non_null.expression.without_parentheses();
            }
            if matches!(
                inner,
                Expression::ArrowFunctionExpression(_)
                    | Expression::FunctionExpression(_)
                    | Expression::CallExpression(_)
                    | Expression::NewExpression(_)
                    | Expression::TSAsExpression(_)
                    | Expression::TSTypeAssertion(_)
            ) {
                refs.extend(TypeFlow::of_module_expression(inner).refs);
            }
        }
        refs
    }

    /// 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[]`.
    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);
            }
        }
    }

    /// The type flow of a class: its heritage, the signatures of its public
    /// methods, and the type of each public property. A property without a
    /// type annotation gets the type flow of its initializer.
    pub(super) fn collect_class_type_flow(class: &Class<'_>) -> TypeFlow {
        let mut collector = SignatureTypeCollector::default();
        let mut flow = TypeFlow::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;
                    }
                    let method_flow = TypeFlow::of_function(&method.value);
                    collector.refs.extend(method_flow.refs);
                    flow.held.extend(method_flow.held);
                }
                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);
                    } else if let Some(value) = &prop.value {
                        let value_flow = TypeFlow::of_module_expression(value);
                        collector.refs.extend(value_flow.refs);
                        flow.held.extend(value_flow.held);
                    }
                }
                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(_) => {}
            }
        }
        super::type_flow::remove_type_parameter_refs(
            &mut collector.refs,
            class.type_parameters.as_deref(),
        );
        flow.refs = collector.refs;
        flow
    }

    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);
        super::type_flow::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);
        super::type_flow::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()));
            }
        }
    }
}

/// 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,
    }
}