fallow-extract 3.32.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
//! Type-signature and typed-binding helpers for the visitor implementation.

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

impl ModuleInfoExtractor {
    fn collect_type_alias_surface_targets(
        ty: &TSType<'_>,
        type_parameters: &FxHashSet<&str>,
        targets: &mut Vec<String>,
    ) {
        match ty {
            TSType::TSTypeReference(reference) => {
                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.to_string());
                }
            }
            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
    }

    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)
        {
            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) in 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.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) {
                    self.insert_class_binding_target(local.clone(), factory);
                    self.store_instance_locals.insert(local);
                    continue;
                }
                self.insert_class_binding_target_if_absent(local, class_name.clone());
            }
        } else if let Some(type_name) = extract_type_annotation_name(type_annotation) {
            for (local, key) in bindings {
                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>) {}
}