fallow-extract 3.37.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
//! Class member credit for destructures that read an instance.
//!
//! `const { m } = instance`, `({ m } = instance)` and `({ m }: Service) => ...`
//! each read `m` from a class instance. The binding that holds the read is a
//! plain local, so no later `m` access resolves to the class. These helpers
//! record the access at the destructure site.

#[allow(clippy::wildcard_imports, reason = "many destructure AST types used")]
use oxc_ast::ast::*;

use std::borrow::Cow;
use std::cell::Cell;

use super::super::{BindingTarget, ModuleInfoExtractor};
use super::{static_member_object_name, unwrap_static_expr};
use crate::MemberAccess;
use crate::js_text::static_name_text;
use crate::visitor::helpers::extract_type_reference_name;

impl<'a> ModuleInfoExtractor {
    pub(in crate::visitor) fn record_declarator_member_destructuring(
        &mut self,
        declarator: &VariableDeclarator<'a>,
        init: &Expression<'a>,
    ) {
        // `const { member } = instance` reads the class member directly. The
        // binding itself is a plain identifier, so no later `member` access
        // can be resolved through `binding_target_names`; record the access at
        // the destructuring site instead. This is the object-pattern parity
        // of the existing `instance.member` path (see #2560).
        let steps = DestructureSteps::default();
        let depth = DefaultDepth::new(&steps);
        match &declarator.id {
            BindingPattern::ObjectPattern(pattern) => {
                self.record_object_destructure(DestructureObject::Binding(pattern), init, depth);
            }
            BindingPattern::ArrayPattern(pattern) => {
                self.record_array_destructure(pattern, init, depth);
            }
            _ => {}
        }
    }

    /// Credit the members that a binding pattern element reads from `source`.
    /// A default value is a second possible source.
    fn record_binding_destructure(
        &mut self,
        pattern: &BindingPattern<'a>,
        source: &Expression<'a>,
        depth: DefaultDepth<'_>,
    ) {
        if !depth.take() {
            return;
        }
        match pattern {
            BindingPattern::ObjectPattern(pattern) => {
                self.record_object_destructure(DestructureObject::Binding(pattern), source, depth);
            }
            BindingPattern::ArrayPattern(pattern) => {
                self.record_array_destructure(pattern, source, depth);
            }
            BindingPattern::AssignmentPattern(assignment) => {
                self.record_binding_destructure(&assignment.left, source, depth);
                if let Some(depth) = depth.into_default() {
                    self.record_binding_destructure(&assignment.left, &assignment.right, depth);
                }
            }
            BindingPattern::BindingIdentifier(_) => {}
        }
    }

    /// `const [{ m }] = [instance]` reads `m` from the element at the same
    /// index of an array literal. A spread can move each later element to
    /// another index, so no element at or after a spread is a source. A
    /// default value stays a source at each index.
    fn record_array_destructure(
        &mut self,
        pattern: &ArrayPattern<'a>,
        source: &Expression<'a>,
        depth: DefaultDepth<'_>,
    ) {
        if !depth.take() {
            return;
        }
        let values = match unwrap_static_expr(source) {
            Expression::ArrayExpression(array) => &array.elements[..],
            _ => &[],
        };
        let mut after_spread = false;
        for (index, element) in pattern.elements.iter().enumerate() {
            if !depth.take() {
                return;
            }
            let value = values.get(index);
            after_spread |= matches!(value, Some(ArrayExpressionElement::SpreadElement(_)));
            let Some(element) = element else {
                continue;
            };
            match value.and_then(ArrayExpressionElement::as_expression) {
                Some(value) if !after_spread => {
                    self.record_binding_destructure(element, value, depth.nested());
                }
                _ => {
                    if let BindingPattern::AssignmentPattern(assignment) = element
                        && let Some(depth) = depth.into_default()
                    {
                        self.record_binding_destructure(&assignment.left, &assignment.right, depth);
                    }
                }
            }
        }
    }

    /// `({ member } = instance)` is the assignment form of
    /// `const { member } = instance` and reads the same class members.
    pub(in crate::visitor) fn record_assignment_member_destructuring(
        &mut self,
        expr: &AssignmentExpression<'a>,
    ) {
        if let AssignmentTarget::ObjectAssignmentTarget(target) = &expr.left {
            self.record_object_destructure(
                DestructureObject::Assignment(target),
                &expr.right,
                DefaultDepth::new(&DestructureSteps::default()),
            );
        }
    }

    /// Credit the members that `pattern` reads from `source`. A nested pattern
    /// follows the source into an object literal property, a static member
    /// path (`{ k: { m } } = holder` reads `holder.k.m`) and a default value
    /// (`{ k: { m } = instance }` can read `instance.m`).
    fn record_object_destructure(
        &mut self,
        pattern: DestructureObject<'_, 'a>,
        source: &Expression<'a>,
        depth: DefaultDepth<'_>,
    ) {
        if !depth.take() {
            return;
        }
        let source = unwrap_static_expr(source);
        if let Expression::ObjectExpression(object) = source {
            self.record_literal_destructure(pattern, object, depth);
            return;
        }
        let Some(path) = static_member_object_name(source) else {
            self.record_nested_entries(&pattern.entries(), None, depth);
            return;
        };
        let ident = match source {
            Expression::Identifier(ident) => Some(&**ident),
            _ => None,
        };
        self.record_source_path_destructure(pattern, &path, ident, depth);
    }

    /// `const { m } = holder` reads `holder.m`. A local class instance credits
    /// its class directly. Any other static path, such as an imported instance
    /// or `this.svc`, records the same `path.key` accesses as the equivalent
    /// member expression, so the later binding resolution finds the class.
    fn record_source_path_destructure(
        &mut self,
        pattern: DestructureObject<'_, 'a>,
        path: &str,
        source: Option<&IdentifierReference<'_>>,
        depth: DefaultDepth<'_>,
    ) {
        let entries = pattern.entries();
        if let Some(BindingTarget::Class(class_name)) = self.resolve_bound_object_name(path) {
            let keys: Vec<_> = entries.iter().map(|entry| entry.key.clone()).collect();
            self.credit_destructured_class_members(&class_name, source, &keys, pattern.has_rest());
            self.record_nested_entries(&entries, Some(path), depth);
            return;
        }
        if pattern.has_rest() || entries.iter().any(|entry| entry.key.is_none()) {
            // Rest copies unknown members, and a dynamic key can select any
            // member, the same as an opaque use of the source. The opaque use
            // covers each key, so only the nested patterns need a record.
            if !self.imported_root_is_shadowed(path) {
                self.record_whole_object_identifier_use(path);
            }
            self.record_nested_entries(&entries, Some(path), depth);
            return;
        }
        self.record_path_destructure(pattern, path, depth);
    }

    /// Whether the root of `path` is an import local that a nested declaration
    /// shadows. The analysis resolves an opaque use of `shared` through the
    /// import of `shared`, so a shadowed root must not record one.
    fn imported_root_is_shadowed(&self, path: &str) -> bool {
        let root = path.split('.').next().unwrap_or(path);
        self.nested_scope_shadows(root)
            && self.imports.iter().any(|import| import.local_name == root)
    }

    /// Credit the nested patterns of `entries`. Each one reads its default and,
    /// when the source has a static `path`, the member `path.key`.
    fn record_nested_entries(
        &mut self,
        entries: &[DestructureEntry<'_, 'a>],
        path: Option<&str>,
        depth: DefaultDepth<'_>,
    ) {
        for entry in entries {
            if !depth.take() {
                return;
            }
            let Some(nested) = entry.nested else {
                continue;
            };
            if let Some(default) = entry.default
                && let Some(depth) = depth.into_default()
            {
                self.record_object_destructure(nested, default, depth);
            }
            if let (Some(path), Some(key)) = (path, entry.key.as_deref()) {
                self.record_path_destructure(nested, &format!("{path}.{key}"), depth.nested());
            }
        }
    }

    /// `{ k: { m } } = { k: instance }` reads `m` from the literal value of `k`.
    /// The literal itself has no class members, so only nested patterns and
    /// their defaults can read one. A spread `{ ...source }` can supply any
    /// key, so the pattern also destructures each spread argument.
    fn record_literal_destructure(
        &mut self,
        pattern: DestructureObject<'_, 'a>,
        object: &ObjectExpression<'a>,
        depth: DefaultDepth<'_>,
    ) {
        for property in &object.properties {
            if !depth.take() {
                return;
            }
            if let ObjectPropertyKind::SpreadProperty(spread) = property {
                self.record_object_destructure(pattern, &spread.argument, depth);
            }
        }
        for entry in pattern.entries() {
            if !depth.take() {
                return;
            }
            let Some(nested) = entry.nested else {
                continue;
            };
            if let Some(default) = entry.default
                && let Some(depth) = depth.into_default()
            {
                self.record_object_destructure(nested, default, depth);
            }
            if let Some(value) = entry
                .key
                .as_deref()
                .and_then(|key| object_literal_property_value(object, key))
            {
                self.record_object_destructure(nested, value, depth.nested());
            }
        }
    }

    /// A nested pattern under a static source path reads the same members as
    /// the equivalent member expression, so each key goes through the
    /// `path.key` access path that `visit_static_member_expression` uses.
    fn record_path_destructure(
        &mut self,
        pattern: DestructureObject<'_, 'a>,
        path: &str,
        depth: DefaultDepth<'_>,
    ) {
        if !depth.take() {
            return;
        }
        for entry in pattern.entries() {
            if !depth.take() {
                return;
            }
            if let (Some(nested), Some(default)) = (entry.nested, entry.default)
                && let Some(depth) = depth.into_default()
            {
                self.record_object_destructure(nested, default, depth);
            }
            let Some(key) = entry.key.as_deref() else {
                continue;
            };
            self.record_named_member_access(path, key);
            if let Some(nested) = entry.nested {
                self.record_path_destructure(nested, &format!("{path}.{key}"), depth.nested());
            }
        }
    }

    /// A signature without a body (overload, `declare function`, abstract
    /// method) never runs, so its destructured keys read nothing.
    pub(in crate::visitor) fn record_function_member_destructuring(&mut self, func: &Function<'a>) {
        if func.body.is_some() {
            self.record_parameter_member_destructuring(&func.params);
        }
    }

    /// `({ m }: Service) => ...` and `({ m } = instance) => ...` read `m`
    /// from the annotated type or from the default value of the parameter.
    pub(in crate::visitor) fn record_parameter_member_destructuring(
        &mut self,
        params: &FormalParameters<'a>,
    ) {
        for param in &params.items {
            let BindingPattern::ObjectPattern(pattern) = &param.pattern else {
                continue;
            };
            if let Some(type_annotation) = param.type_annotation.as_deref() {
                self.record_typed_member_destructuring(pattern, &type_annotation.type_annotation);
            }
            if let Some(initializer) = param.initializer.as_deref() {
                self.record_object_destructure(
                    DestructureObject::Binding(pattern),
                    initializer,
                    DefaultDepth::new(&DestructureSteps::default()),
                );
            }
        }
    }

    /// `for (const { m } of items)` reads `m` from each element. An array
    /// literal gives each element as a source, and a spread in it gives the
    /// elements of the spread iterable.
    pub(in crate::visitor) fn record_for_of_member_destructuring(
        &mut self,
        stmt: &ForOfStatement<'a>,
    ) {
        let pattern = match &stmt.left {
            ForStatementLeft::VariableDeclaration(declaration) => {
                match declaration
                    .declarations
                    .first()
                    .map(|declarator| &declarator.id)
                {
                    Some(BindingPattern::ObjectPattern(pattern)) => {
                        DestructureObject::Binding(pattern)
                    }
                    Some(BindingPattern::ArrayPattern(pattern)) => {
                        self.record_for_of_array_destructure(pattern, &stmt.right);
                        return;
                    }
                    _ => return,
                }
            }
            ForStatementLeft::ObjectAssignmentTarget(target) => {
                DestructureObject::Assignment(target)
            }
            _ => return,
        };
        let steps = DestructureSteps::default();
        let depth = DefaultDepth::new(&steps);
        let iterable = unwrap_static_expr(&stmt.right);
        let Expression::ArrayExpression(array) = iterable else {
            self.record_iterable_element_destructure(pattern, iterable);
            return;
        };
        for element in &array.elements {
            if let ArrayExpressionElement::SpreadElement(spread) = element {
                self.record_iterable_element_destructure(pattern, &spread.argument);
            } else if let Some(element) = element.as_expression() {
                self.record_object_destructure(pattern, element, depth);
            }
        }
    }

    /// `for (const [{ m }] of [[instance]])` destructures each element of an
    /// array literal with the array pattern.
    fn record_for_of_array_destructure(
        &mut self,
        pattern: &ArrayPattern<'a>,
        iterable: &Expression<'a>,
    ) {
        let Expression::ArrayExpression(array) = unwrap_static_expr(iterable) else {
            return;
        };
        let steps = DestructureSteps::default();
        let depth = DefaultDepth::new(&steps);
        for element in &array.elements {
            if let Some(element) = element.as_expression() {
                self.record_array_destructure(pattern, element, depth);
            }
        }
    }

    /// Credit the members that `pattern` reads from each element of a typed
    /// iterable, such as `items: Service[]`.
    fn record_iterable_element_destructure(
        &mut self,
        pattern: DestructureObject<'_, 'a>,
        iterable: &Expression<'a>,
    ) {
        let Some(receiver) = static_member_object_name(unwrap_static_expr(iterable)) else {
            return;
        };
        let receiver = self.qualify_this_scope(&receiver);
        if let Some(class_name) = self.iterable_element_type_for(&receiver) {
            let keys: Vec<_> = pattern
                .entries()
                .into_iter()
                .map(|entry| entry.key)
                .collect();
            self.credit_destructured_class_members(&class_name, None, &keys, pattern.has_rest());
        }
    }

    /// `({ k: { m } }: typeof holder)` destructures the type of the value
    /// `holder`, so it reads the same members as `const { k: { m } } = holder`.
    fn record_typeof_destructure(&mut self, pattern: &ObjectPattern<'a>, path: &str) {
        self.record_source_path_destructure(
            DestructureObject::Binding(pattern),
            path,
            None,
            DefaultDepth::new(&DestructureSteps::default()),
        );
    }

    /// `({ member }: Service) => ...` reads `Service.member`. The annotation is
    /// the only class evidence, so only a named type reference or a type
    /// literal property that names one credits members. A nested pattern
    /// recurses only through a type literal, because the property types of a
    /// named type are not known here.
    fn record_typed_member_destructuring(&mut self, pattern: &ObjectPattern<'a>, ty: &TSType<'_>) {
        if let TSType::TSTypeLiteral(type_lit) = ty {
            for property in &pattern.properties {
                let Some(key) = property.key.static_name() else {
                    continue;
                };
                let value = match &property.value {
                    BindingPattern::AssignmentPattern(assignment) => &assignment.left,
                    value => value,
                };
                let BindingPattern::ObjectPattern(inner) = value else {
                    continue;
                };
                let Some(property_type) = type_lit.members.iter().find_map(|member| {
                    let TSSignature::TSPropertySignature(signature) = member else {
                        return None;
                    };
                    (signature.key.static_name().as_ref() == Some(&key))
                        .then_some(signature.type_annotation.as_deref())
                        .flatten()
                }) else {
                    continue;
                };
                self.record_typed_member_destructuring(inner, &property_type.type_annotation);
            }
            return;
        }
        if let TSType::TSTypeQuery(query) = ty {
            if query.type_arguments.is_none()
                && let Some(path) = type_query_path(&query.expr_name)
            {
                self.record_typeof_destructure(pattern, &path);
            }
            return;
        }
        // Store types keep their own destructure credit in the Pinia path.
        if self.store_factory_for_type(ty).is_some() {
            return;
        }
        let Some(class_name) =
            extract_type_reference_name(ty).and_then(|name| self.resolve_class_type_param(&name))
        else {
            return;
        };
        let keys: Vec<_> = pattern
            .properties
            .iter()
            .map(|property| property.key.static_name().map(static_name_text))
            .collect();
        self.credit_destructured_class_members(&class_name, None, &keys, pattern.rest.is_some());
    }

    /// Credit each statically named destructured key as a member access on
    /// `class_name`. `source` is the destructured instance binding, when one
    /// exists, so subclass proofs can follow it.
    fn credit_destructured_class_members(
        &mut self,
        class_name: &str,
        source: Option<&IdentifierReference<'_>>,
        keys: &[Option<Cow<'_, str>>],
        has_rest: bool,
    ) {
        if has_rest || keys.iter().any(Option::is_none) {
            // Rest copies unknown members, and a dynamic key can select any
            // member. Keep the same conservative credit as an opaque use.
            self.whole_object_uses.push(class_name.to_string());
        }
        for member in keys.iter().flatten() {
            if let Some(source) = source {
                self.capture_subclass_binding_access(
                    source.name.as_str(),
                    Some(source.span),
                    member,
                );
            }
            self.member_accesses.push(MemberAccess {
                object: class_name.to_string(),
                member: member.to_string(),
            });
        }
    }
}

/// The deepest nested pattern level at which a destructure walk still reads a
/// default. A pattern with a default is walked once for the source and once
/// for the default, so the walks of one sub-pattern double at each level that
/// has a default. Below this level, a sub-pattern reads only its source, so
/// the walks of one sub-pattern stay at most `2^MAX_DESTRUCTURE_DEFAULT_DEPTH`.
/// Sibling elements and properties do not double the walks, so they have no
/// limit.
const MAX_DESTRUCTURE_DEFAULT_DEPTH: usize = 8;

/// The most steps that one destructure statement takes. A step is one
/// pattern node or one sibling entry. The depth limit bounds the walks of one
/// sub-pattern, but a wide source or a source with many spreads still walks
/// the pattern many times. This cap bounds that total.
const MAX_DESTRUCTURE_STEPS: usize = 1 << 16;

/// The steps that one destructure statement has left.
struct DestructureSteps(Cell<usize>);

impl Default for DestructureSteps {
    fn default() -> Self {
        Self(Cell::new(MAX_DESTRUCTURE_STEPS))
    }
}

/// The nested pattern level of the current destructure walk, and the steps
/// that its destructure statement has left.
#[derive(Clone, Copy)]
struct DefaultDepth<'s> {
    level: usize,
    steps: &'s DestructureSteps,
}

impl<'s> DefaultDepth<'s> {
    const fn new(steps: &'s DestructureSteps) -> Self {
        Self { level: 0, steps }
    }

    /// The level of a nested pattern one level further down.
    const fn nested(self) -> Self {
        Self {
            level: self.level.saturating_add(1),
            steps: self.steps,
        }
    }

    /// The level for a walk of a default one level further down, or `None`
    /// below the deepest level that reads a default.
    fn into_default(self) -> Option<Self> {
        (self.level < MAX_DESTRUCTURE_DEFAULT_DEPTH).then(|| self.nested())
    }

    /// Use one step. Returns `false` when the statement has no step left.
    fn take(self) -> bool {
        let left = self.steps.0.get();
        if left == 0 {
            return false;
        }
        self.steps.0.set(left - 1);
        true
    }
}

/// An object destructure in binding (`const { .. } =`) or assignment
/// (`({ .. } =)`) form.
#[derive(Clone, Copy)]
enum DestructureObject<'b, 'a> {
    Binding(&'b ObjectPattern<'a>),
    Assignment(&'b ObjectAssignmentTarget<'a>),
}

/// One property of a destructure: its static key, the nested object pattern
/// that its value destructures, and the default value of that property.
struct DestructureEntry<'b, 'a> {
    key: Option<Cow<'b, str>>,
    nested: Option<DestructureObject<'b, 'a>>,
    default: Option<&'b Expression<'a>>,
}

impl<'b, 'a> DestructureObject<'b, 'a> {
    fn has_rest(self) -> bool {
        match self {
            Self::Binding(pattern) => pattern.rest.is_some(),
            Self::Assignment(target) => target.rest.is_some(),
        }
    }

    fn entries(self) -> Vec<DestructureEntry<'b, 'a>> {
        match self {
            Self::Binding(pattern) => pattern
                .properties
                .iter()
                .map(|property| {
                    let (value, default) = match &property.value {
                        BindingPattern::AssignmentPattern(assignment) => {
                            (&assignment.left, Some(&assignment.right))
                        }
                        value => (value, None),
                    };
                    let nested = match value {
                        BindingPattern::ObjectPattern(inner) => Some(Self::Binding(inner)),
                        _ => None,
                    };
                    DestructureEntry {
                        key: property.key.static_name().map(static_name_text),
                        nested,
                        default: nested.and(default),
                    }
                })
                .collect(),
            Self::Assignment(target) => target
                .properties
                .iter()
                .map(|property| match property {
                    AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(shorthand) => {
                        DestructureEntry {
                            key: Some(Cow::Borrowed(shorthand.binding.name.as_str())),
                            nested: None,
                            default: None,
                        }
                    }
                    AssignmentTargetProperty::AssignmentTargetPropertyProperty(property) => {
                        let (value, default) = match &property.binding {
                            AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(
                                with_default,
                            ) => (Some(&with_default.binding), Some(&with_default.init)),
                            value => (value.as_assignment_target(), None),
                        };
                        let nested = match value {
                            Some(AssignmentTarget::ObjectAssignmentTarget(inner)) => {
                                Some(Self::Assignment(inner))
                            }
                            _ => None,
                        };
                        DestructureEntry {
                            key: property.name.static_name().map(static_name_text),
                            nested,
                            default: nested.and(default),
                        }
                    }
                })
                .collect(),
        }
    }
}

/// The value of the last `key` property in an object literal. A spread can
/// also set `key`, but the explicit value stays a possible source, so it keeps
/// its credit. A getter `get key() { return value }` gives `value` when its
/// body is that one return statement.
fn object_literal_property_value<'b, 'a>(
    object: &'b ObjectExpression<'a>,
    key: &str,
) -> Option<&'b Expression<'a>> {
    object.properties.iter().rev().find_map(|property| {
        let ObjectPropertyKind::ObjectProperty(property) = property else {
            return None;
        };
        if !property.key.static_name().is_some_and(|name| name == key) {
            return None;
        }
        object_property_value(property)
    })
}

/// The value that reading an object literal property gives: the value of a
/// plain property, or the value that a getter returns. A setter gives none.
pub(in crate::visitor) fn object_property_value<'b, 'a>(
    property: &'b ObjectProperty<'a>,
) -> Option<&'b Expression<'a>> {
    match property.kind {
        PropertyKind::Init => Some(&property.value),
        PropertyKind::Get => getter_return_value(&property.value),
        PropertyKind::Set => None,
    }
}

/// The value that a getter `get key() { return value }` gives, when its body
/// is that one return statement.
fn getter_return_value<'b, 'a>(value: &'b Expression<'a>) -> Option<&'b Expression<'a>> {
    let Expression::FunctionExpression(getter) = value else {
        return None;
    };
    match getter.body.as_deref()?.statements.as_slice() {
        [Statement::ReturnStatement(statement)] => statement.argument.as_ref(),
        _ => None,
    }
}

/// The dotted value path of a `typeof` query, such as `holder` or
/// `registry.holder`.
fn type_query_path(name: &TSTypeQueryExprName<'_>) -> Option<String> {
    fn type_name_path(name: &TSTypeName<'_>) -> Option<String> {
        match name {
            TSTypeName::IdentifierReference(ident) => Some(ident.name.to_string()),
            TSTypeName::QualifiedName(qualified) => Some(format!(
                "{}.{}",
                type_name_path(&qualified.left)?,
                qualified.right.name
            )),
            TSTypeName::ThisExpression(_) => None,
        }
    }
    type_name_path(name.as_ts_type_name()?)
}