tsv_ts 0.8.0

TypeScript/JS formatter, type stripper and acorn-compatible parser — part of tsv
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
// Expression dispatcher: emit each `Expression` variant's wire JSON.

use super::declarations::write_class_expression;
use super::functions::{
    call_callee_flags, write_arrow_function_expression, write_await_expression,
    write_call_expression_tail, write_conditional_expression, write_function_expression,
    write_member_expression_tail, write_new_expression, write_yield_expression,
};
use super::patterns::{
    write_assignment_pattern, write_object_pattern, write_property, write_rest_element,
    write_template_literal,
};
use super::types::{write_type, write_type_parameter_instantiation};
use super::{
    CommentAttach, CommentMode, Ctx, JsonWriter, close_node, node_header, write_array,
    write_bare_node, write_identifier_parts, write_identifier_plain, write_literal,
    write_name_field, write_type_annotation_field, write_type_arguments_field,
};
use crate::ast;
use smallvec::SmallVec;
use tsv_lang::Span;

/// What a call/member/non-null node has inherited from its parent about the
/// optional chain it sits on.
///
/// The two decided states are the opposite verdicts of the same question, so
/// they are one value rather than two flags — a node reaches at most one, and
/// both let it skip the `has_optional_in_chain` walk entirely.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(super) enum ChainState {
    /// Nothing inherited — the node resolves the question for itself. A
    /// parenthesized child seals its own chain and lands here.
    #[default]
    Unresolved,
    /// The node emits inside an optional chain a `ChainExpression` already
    /// wraps further up the spine.
    InChain,
    /// The node's spine is already known optional-free: the parent's own walk
    /// covered it and reached it unsealed, so the answer would be the tail of a
    /// walk already run. Without this, every spine node re-walks its own suffix
    /// and an `n`-deep chain costs `O(n²)`.
    KnownFree,
}

/// Emission-time expression state.
///
/// `chain` is the inherited optional-chain verdict (see [`ChainState`]). The
/// two flags are pre-computed decisions that adjust the `optional` field along
/// a call/member spine:
///
/// - `force_optional` — the acorn `?.<T>(...)` quirk: the callee node of an
///   optional call with type arguments is itself marked optional.
/// - `strip_optional` — the unparenthesized-decorator quirk: `optional` is
///   omitted along the call/member spine.
///
/// Both flags survive a `CommentBoundPair` unwrap (they act on the unwrapped inner
/// expression) and die at a `ChainExpression` wrap ([`flags_after_wrap`]).
/// `force_optional` is read by the call/member arms and by the `Identifier` arm — the
/// bare callee of `a?.<T>(x)` is the node it marks optional — and `strip_optional` by
/// the call/member arms alone. Every other arm drops both, save `TSInstantiationExpression`,
/// which passes `strip_optional` through to its expression (a call-less decorator
/// `@a.b<T>` wraps its member spine in one). `chain` does *not* survive the unwrap: a
/// cast's parens seal the chain.
#[derive(Clone, Copy, Default)]
pub(super) struct ExprFlags {
    pub(super) chain: ChainState,
    pub(super) force_optional: bool,
    pub(super) strip_optional: bool,
}

/// Emit an expression's wire JSON in a fresh context (not inside a chain).
pub(super) fn write_expression(w: &mut JsonWriter, expr: &ast::Expression<'_>, ctx: &Ctx<'_>) {
    write_expression_inner(w, expr, ctx, ExprFlags::default());
}

/// Emit a JSON array of expressions (params, arguments, elements without
/// holes) — the writer's most common list shape.
pub(super) fn write_expressions<'a, 'arena: 'a>(
    w: &mut JsonWriter,
    items: impl IntoIterator<Item = &'a ast::Expression<'arena>>,
    ctx: &Ctx<'_>,
) {
    write_array(w, items, |w, e| write_expression(w, e, ctx));
}

/// Emit a JSON array of hole-carrying elements (`[a, , b]` — `None` is `null`).
///
/// `ArrayPattern` only: `ArrayExpression` takes `write_body_array_holes`, which is
/// this plus the last-in-body mark acorn's trailing rule reads.
fn write_expression_holes<'a, 'arena: 'a>(
    w: &mut JsonWriter,
    items: impl IntoIterator<Item = &'a Option<ast::Expression<'arena>>>,
    ctx: &Ctx<'_>,
) {
    write_array(w, items, |w, e| match e {
        Some(expr) => write_expression(w, expr, ctx),
        None => w.null(),
    });
}

/// Emit an expression's wire JSON, dispatching on its variant (chain flags
/// threaded via `ExprFlags`).
///
/// The dispatch's front: the two leaf kinds — a literal and an identifier, more than
/// half of all calls — are answered here, and every other kind goes on to
/// [`write_expression_full_dispatch`], whose arms share one frame and six callee-saved
/// registers that a leaf arm handing off to its writer would set up and tear down for
/// nothing.
///
/// ⚠️ Out of line, and every arm a tail call, for one reason: the dispatch IS the
/// expression recursion, so this function must add nothing to its frames.
#[inline(never)]
pub(super) fn write_expression_inner(
    w: &mut JsonWriter,
    expr: &ast::Expression<'_>,
    ctx: &Ctx<'_>,
    flags: ExprFlags,
) {
    match &expr.kind {
        ast::ExpressionKind::Literal(lit) => write_literal(w, lit, ctx),
        // A variable reference — no `?` (its own or a forced one), no binding extra — is
        // the bare node `write_identifier_plain` writes, in a smaller frame than the
        // general form.
        ast::ExpressionKind::Identifier(id)
            if id.extra.is_none() && !id.optional && !flags.force_optional =>
        {
            write_identifier_plain(w, id, ctx);
        }
        ast::ExpressionKind::Identifier(id) => {
            write_expression_identifier(w, id, flags.force_optional, ctx);
        }
        _ => write_expression_full_dispatch(w, expr, ctx, flags),
    }
}

/// A JSDoc cast in an island whose canonical reader discards grouping pairs
/// (`CommentAttach::removes_parens`): acorn's walk entered the cast's
/// `ParenthesizedExpression` before its inner node, so the pair runs as a **silent frame**
/// around the inner emission — it takes the comments the pair took (the cast's own
/// `@type` comment among them, which leads the pair) and the inner sees the pair's `)` as
/// its parent's end — and emits nothing, since `remove_parens` discards the pair with
/// whatever it claimed.
#[cold]
#[inline(never)]
fn write_comment_bound_pair_paren_frame(
    w: &mut JsonWriter,
    span: Span,
    inner: &ast::Expression<'_>,
    ctx: &Ctx<'_>,
    flags: ExprFlags,
    attach: &CommentAttach<'_>,
) {
    attach.paren_open(span);
    write_expression_inner(w, inner, ctx, flags);
    attach.paren_close(span);
}

/// An `Identifier` in expression position — the arm both dispatches share.
/// `force_optional` is the acorn `?.<T>(...)` quirk ([`ExprFlags::force_optional`]).
// Out of line so the front stays frameless: inlined, this arm's frame is set up on entry
// to the front, ahead of its kind test, by every kind.
#[inline(never)]
fn write_expression_identifier(
    w: &mut JsonWriter,
    id: &ast::Identifier<'_>,
    force_optional: bool,
    ctx: &Ctx<'_>,
) {
    write_identifier_parts(
        w,
        id.span,
        id.ident_name(),
        id.optional || force_optional,
        id.type_annotation(),
        id.decorators(),
        ctx,
    );
}

/// A binary or logical expression and the binaries down its left spine, written without
/// recursing down that spine — the chain's length is bounded only by `SPINE_LIMIT`, so a
/// recursion per link would spend a frame per operator. Each binary's header and `left`
/// key outermost first, then the leftmost operand, then each binary's operator, right
/// operand and close innermost first: the bytes, and the order of the comment-attach
/// node events, of the recursion down the left.
#[inline(never)]
fn write_binary_chain(
    w: &mut JsonWriter,
    binary: &ast::BinaryExpression<'_>,
    span: Span,
    ctx: &Ctx<'_>,
) {
    // LogicalExpression for `&&`/`||`/`??`, BinaryExpression otherwise.
    fn node_type(operator: ast::BinaryOperator) -> &'static str {
        match operator {
            ast::BinaryOperator::AmpersandAmpersand
            | ast::BinaryOperator::PipePipe
            | ast::BinaryOperator::QuestionQuestion => "LogicalExpression",
            _ => "BinaryExpression",
        }
    }
    let mut spine: SmallVec<[(&ast::BinaryExpression<'_>, Span); 8]> = SmallVec::new();
    let (mut node, mut node_span) = (binary, span);
    loop {
        node_header(w, node_type(node.operator), node_span, ctx);
        w.raw(",\"left\":");
        spine.push((node, node_span));
        match &node.left.kind {
            ast::ExpressionKind::BinaryExpression(left) => {
                node_span = node.left.span;
                node = left;
            }
            _ => {
                write_expression(w, node.left, ctx);
                break;
            }
        }
    }
    for &(node, node_span) in spine.iter().rev() {
        w.raw(",\"operator\":\"");
        w.raw(node.operator.as_str());
        w.raw("\",\"right\":");
        write_expression(w, node.right, ctx);
        close_node(w, node_type(node.operator), node_span, ctx);
    }
}

/// Every expression kind's arm, the leaf kinds' included, so this is a total answer on
/// its own; [`write_expression_inner`] answers the leaves before reaching it.
// Out of line: inlined into its front, its frame would be paid by the leaf kinds the
// front answers first.
#[inline(never)]
fn write_expression_full_dispatch(
    w: &mut JsonWriter,
    expr: &ast::Expression<'_>,
    ctx: &Ctx<'_>,
    flags: ExprFlags,
) {
    match &expr.kind {
        // JSDoc cast is internal-only: emit the inner expression (paren-free
        // public AST). `chain: ChainState::Unresolved` — the cast's parens seal any chain;
        // force/strip pass through (they act on the converted inner).
        ast::ExpressionKind::CommentBoundPair(cast) => {
            let flags = ExprFlags {
                // The cast's parens seal the chain, so the inner
                // expression inherits no verdict — `/** @type {T} */
                // (a?.b)` still opens its own wrap.
                chain: ChainState::Unresolved,
                ..flags
            };
            if let CommentMode::Attach(attach) = ctx.comments
                && attach.removes_parens()
            {
                write_comment_bound_pair_paren_frame(w, expr.span, cast.inner, ctx, flags, attach);
            } else {
                write_expression_inner(w, cast.inner, ctx, flags);
            }
        }
        // Preserved grouping parens (snippet parameters): emit the wrapper with
        // its paren-covering span, then the inner expression. Only produced under
        // the parser's `preserve_parens` mode, so it never appears elsewhere.
        ast::ExpressionKind::ParenthesizedExpression(paren) => {
            node_header(w, "ParenthesizedExpression", expr.span, ctx);
            w.raw(",\"expression\":");
            write_expression(w, paren.expression, ctx);
            close_node(w, "ParenthesizedExpression", expr.span, ctx);
        }
        // Unreachable through the front (this function's only caller), which answers both
        // kinds first; kept so the match stays total. Leaf behavior belongs in the front
        // and the shared writers, or it never runs.
        ast::ExpressionKind::Literal(lit) => write_literal(w, lit, ctx),
        ast::ExpressionKind::Identifier(id) => {
            write_expression_identifier(w, id, flags.force_optional, ctx);
        }
        ast::ExpressionKind::PrivateIdentifier(pid) => {
            node_header(w, "PrivateIdentifier", expr.span, ctx);
            // The name excludes the leading `#` (the public shape): the
            // trailing `raw_len` bytes of the span.
            write_name_field(w, pid.name, expr.span.end - pid.name.raw_len as u32, ctx);
            close_node(w, "PrivateIdentifier", expr.span, ctx);
        }
        ast::ExpressionKind::ObjectExpression(obj) => {
            node_header(w, "ObjectExpression", expr.span, ctx);
            w.raw(",\"properties\":");
            super::write_body_array(w, obj.properties, ctx, |w, p| {
                write_object_property(w, p, ctx);
            });
            close_node(w, "ObjectExpression", expr.span, ctx);
        }
        ast::ExpressionKind::ArrayExpression(arr) => {
            node_header(w, "ArrayExpression", expr.span, ctx);
            w.raw(",\"elements\":");
            super::write_body_array_holes(w, arr.elements, ctx, |w, e| {
                write_expression(w, e, ctx);
            });
            close_node(w, "ArrayExpression", expr.span, ctx);
        }
        ast::ExpressionKind::UnaryExpression(unary) => {
            node_header(w, "UnaryExpression", unary.span, ctx);
            w.raw(",\"operator\":\"");
            w.raw(unary.operator.as_str());
            // Constant: acorn's `UnaryExpression` is always prefix (postfix
            // `++`/`--` is an `UpdateExpression`).
            w.raw_fixed(b"\",\"prefix\":true,\"argument\":");
            write_expression(w, unary.argument, ctx);
            close_node(w, "UnaryExpression", unary.span, ctx);
        }
        ast::ExpressionKind::UpdateExpression(update) => {
            node_header(w, "UpdateExpression", expr.span, ctx);
            w.raw(",\"operator\":\"");
            w.raw(update.operator.as_str());
            w.raw_pick(
                update.prefix,
                b"\",\"prefix\":true,\"argument\":",
                b"\",\"prefix\":false,\"argument\":",
            );
            write_expression(w, update.argument, ctx);
            close_node(w, "UpdateExpression", expr.span, ctx);
        }
        ast::ExpressionKind::BinaryExpression(binary) => {
            write_binary_chain(w, binary, expr.span, ctx);
        }
        ast::ExpressionKind::ArrowFunctionExpression(arrow) => {
            write_arrow_function_expression(w, arrow, expr.span, ctx);
        }
        ast::ExpressionKind::FunctionExpression(func) => {
            write_function_expression(w, func, ctx, false);
        }
        ast::ExpressionKind::ClassExpression(class_expr) => {
            write_class_expression(w, class_expr, expr.span, ctx);
        }
        ast::ExpressionKind::SpreadElement(spread) => {
            node_header(w, "SpreadElement", spread.span, ctx);
            w.raw(",\"argument\":");
            write_expression(w, spread.argument, ctx);
            close_node(w, "SpreadElement", spread.span, ctx);
        }
        ast::ExpressionKind::CallExpression(_)
        | ast::ExpressionKind::MemberExpression(_)
        | ast::ExpressionKind::TSNonNullExpression(_) => write_chain(w, expr, ctx, flags),
        ast::ExpressionKind::NewExpression(new_expr) => {
            write_new_expression(w, new_expr, expr.span, ctx);
        }
        ast::ExpressionKind::ConditionalExpression(cond) => {
            write_conditional_expression(w, cond, expr.span, ctx);
        }
        ast::ExpressionKind::TemplateLiteral(template) => {
            write_template_literal(w, template, ctx);
        }
        ast::ExpressionKind::TaggedTemplateExpression(tagged) => {
            node_header(w, "TaggedTemplateExpression", expr.span, ctx);
            w.raw(",\"tag\":");
            write_expression(w, tagged.tag, ctx);
            w.raw(",\"quasi\":");
            write_template_literal(w, &tagged.quasi, ctx);
            write_type_arguments_field(w, tagged.type_arguments.as_ref(), ctx);
            close_node(w, "TaggedTemplateExpression", expr.span, ctx);
        }
        ast::ExpressionKind::AwaitExpression(await_expr) => {
            write_await_expression(w, await_expr, expr.span, ctx);
        }
        ast::ExpressionKind::YieldExpression(yield_expr) => {
            write_yield_expression(w, yield_expr, expr.span, ctx);
        }
        ast::ExpressionKind::SequenceExpression(seq) => {
            node_header(w, "SequenceExpression", expr.span, ctx);
            w.raw(",\"expressions\":");
            write_expressions(w, seq.expressions.iter().copied(), ctx);
            close_node(w, "SequenceExpression", expr.span, ctx);
        }
        ast::ExpressionKind::RegexLiteral(regex) => {
            // Regex uses "Literal" type in acorn/Svelte AST; `value` is `{}`.
            node_header(w, "Literal", expr.span, ctx);
            w.raw(",\"value\":{},\"raw\":");
            w.string(expr.span.extract(ctx.source));
            w.raw(",\"regex\":{\"pattern\":");
            w.string(regex.pattern(ctx.source));
            w.raw(",\"flags\":");
            w.string(regex.flags(ctx.source));
            // Close the inner `regex` object, then the `Literal` node.
            w.raw("}");
            close_node(w, "Literal", expr.span, ctx);
        }
        ast::ExpressionKind::ThisExpression(_) => {
            write_bare_node(w, "ThisExpression", expr.span, ctx);
        }
        ast::ExpressionKind::Super(_) => {
            write_bare_node(w, "Super", expr.span, ctx);
        }
        ast::ExpressionKind::AssignmentExpression(assign) => {
            // The `=` left keeps its type-assertion wrapper (`(x as T) = 1` →
            // `TSAsExpression`): acorn-typescript's `toAssignable` validates through the
            // assertion but preserves the node. A JSDoc cast is not an assertion node at
            // all in the public AST, and `write_expression` already peels it.
            node_header(w, "AssignmentExpression", expr.span, ctx);
            w.raw(",\"operator\":\"");
            w.raw(assign.operator.as_str());
            w.raw("\",\"left\":");
            write_expression(w, assign.left, ctx);
            w.raw(",\"right\":");
            write_expression(w, assign.right, ctx);
            close_node(w, "AssignmentExpression", expr.span, ctx);
        }
        ast::ExpressionKind::ObjectPattern(obj) => {
            write_object_pattern(w, obj, expr.span, ctx);
        }
        ast::ExpressionKind::ArrayPattern(arr) => {
            super::patterns::pattern_header(
                w,
                "ArrayPattern",
                expr.span,
                arr.type_annotation.as_ref(),
                ctx,
            );
            w.raw(",\"elements\":");
            write_expression_holes(w, arr.elements, ctx);
            if arr.optional {
                w.raw(",\"optional\":true");
            }
            write_type_annotation_field(w, arr.type_annotation.as_ref(), ctx);
            super::declarations::write_decorators_field(w, arr.decorators, ctx);
            close_node(w, "ArrayPattern", expr.span, ctx);
        }
        ast::ExpressionKind::AssignmentPattern(pattern) => {
            write_assignment_pattern(w, pattern, ctx, expr.span);
        }
        ast::ExpressionKind::RestElement(rest) => {
            write_rest_element(w, rest, ctx);
        }
        ast::ExpressionKind::TSTypeAssertion(type_assert) => {
            node_header(w, "TSTypeAssertion", expr.span, ctx);
            w.raw(",\"typeAnnotation\":");
            write_type(w, type_assert.type_annotation, ctx);
            w.raw(",\"expression\":");
            write_expression(w, type_assert.expression, ctx);
            close_node(w, "TSTypeAssertion", expr.span, ctx);
        }
        ast::ExpressionKind::TSAsExpression(as_expr) => {
            node_header(w, "TSAsExpression", expr.span, ctx);
            w.raw(",\"expression\":");
            write_expression(w, as_expr.expression, ctx);
            w.raw(",\"typeAnnotation\":");
            write_type(w, as_expr.type_annotation, ctx);
            close_node(w, "TSAsExpression", expr.span, ctx);
        }
        ast::ExpressionKind::TSSatisfiesExpression(sat_expr) => {
            node_header(w, "TSSatisfiesExpression", expr.span, ctx);
            w.raw(",\"expression\":");
            write_expression(w, sat_expr.expression, ctx);
            w.raw(",\"typeAnnotation\":");
            write_type(w, sat_expr.type_annotation, ctx);
            close_node(w, "TSSatisfiesExpression", expr.span, ctx);
        }
        ast::ExpressionKind::TSInstantiationExpression(inst_expr) => {
            node_header(w, "TSInstantiationExpression", expr.span, ctx);
            w.raw(",\"expression\":");
            write_expression_inner(
                w,
                inst_expr.expression,
                ctx,
                ExprFlags {
                    chain: ChainState::Unresolved,
                    force_optional: false,
                    // A call-less decorator (`@a.b<T>`) wraps its member spine in one
                    // of these, so the strip walks through it too.
                    strip_optional: flags.strip_optional,
                },
            );
            w.raw(",\"typeArguments\":");
            write_type_parameter_instantiation(w, &inst_expr.type_arguments, ctx);
            close_node(w, "TSInstantiationExpression", expr.span, ctx);
        }
        ast::ExpressionKind::ImportExpression(import_expr) => {
            node_header(w, "ImportExpression", expr.span, ctx);
            w.raw(",\"source\":");
            write_expression(w, import_expr.source, ctx);
            if let Some(phase) = import_expr.phase.as_str() {
                w.raw(",\"phase\":");
                w.token(phase);
            }
            // The two parser variants spell the second argument differently, and
            // each spells it exclusively. Vanilla acorn (a Svelte non-`lang="ts"`
            // script) is ESTree: the argument IS `options`, always emitted and
            // `null` when absent, with no `arguments` field. acorn-typescript uses
            // its own dialect instead: a single-element `arguments` array,
            // skip-if-empty, with no `options` field.
            if ctx.vanilla_acorn {
                w.raw(",\"options\":");
                match &import_expr.options {
                    Some(opts) => write_expression(w, opts, ctx),
                    None => w.raw("null"),
                }
            } else if let Some(opts) = &import_expr.options {
                w.raw(",\"arguments\":[");
                write_expression(w, opts, ctx);
                w.raw("]");
            }
            close_node(w, "ImportExpression", expr.span, ctx);
        }
        ast::ExpressionKind::MetaProperty(meta) => {
            node_header(w, "MetaProperty", expr.span, ctx);
            w.raw(",\"meta\":");
            write_identifier_plain(w, &meta.meta, ctx);
            w.raw(",\"property\":");
            write_identifier_plain(w, &meta.property, ctx);
            close_node(w, "MetaProperty", expr.span, ctx);
        }
        ast::ExpressionKind::TSParameterProperty(param_prop) => {
            // acorn quirk: when the parameter is an AssignmentPattern whose left
            // has no type annotation, its span/loc expand to include the
            // accessibility modifier keyword (the whole parameter property).
            let param = param_prop.parameter.unwrap_comment_bound_pairs();
            let override_ap = if let ast::ExpressionKind::AssignmentPattern(ap) = &param.kind {
                let has_type_ann = match &ap.left.unwrap_comment_bound_pairs().kind {
                    ast::ExpressionKind::Identifier(id) => id.type_annotation().is_some(),
                    ast::ExpressionKind::ArrayPattern(arr) => arr.type_annotation.is_some(),
                    ast::ExpressionKind::ObjectPattern(obj) => obj.type_annotation.is_some(),
                    _ => false,
                };
                (!has_type_ann).then_some(ap)
            } else {
                None
            };
            node_header(w, "TSParameterProperty", expr.span, ctx);
            if let Some(acc) = param_prop.accessibility {
                w.raw(",\"accessibility\":");
                w.token(acc.as_str());
            }
            if param_prop.readonly {
                w.raw(",\"readonly\":true");
            }
            if param_prop.r#override {
                w.raw(",\"override\":true");
            }
            w.raw(",\"parameter\":");
            if let Some(ap) = override_ap {
                write_assignment_pattern(w, ap, ctx, expr.span);
            } else {
                write_expression(w, param_prop.parameter, ctx);
            }
            close_node(w, "TSParameterProperty", expr.span, ctx);
        }
    }
}

/// The deferred half of one link [`write_chain`] walks down: what the node writes after
/// the child its walk continues into.
enum ChainTail<'e> {
    Call {
        call: &'e ast::CallExpression<'e>,
        callee_chain: ChainState,
        force: bool,
        strip: bool,
    },
    Member {
        member: &'e ast::MemberExpression<'e>,
        force: bool,
        strip: bool,
    },
    NonNull,
}

/// A call, member or non-null expression and the links of those kinds down its spine,
/// written without recursing down the spine — the chain's length is bounded only by
/// `SPINE_LIMIT`, so a recursion per link would spend a frame per link. Down the spine,
/// each link's `ChainExpression` wrap (where it opens one), its header and its child key;
/// then the spine's base through the dispatch, with the flags the last link hands it; then
/// each link's tail and closes, innermost first — the bytes, and the order of the
/// comment-attach node events, of the recursion down the spine. Each link reads the flags
/// its parent hands it exactly as the recursion did (`needs_chain_wrap`, `child_chain`,
/// `flags_after_wrap`).
#[inline(never)]
fn write_chain(w: &mut JsonWriter, expr: &ast::Expression<'_>, ctx: &Ctx<'_>, flags: ExprFlags) {
    let mut tails: SmallVec<[(ChainTail<'_>, Span, bool); 8]> = SmallVec::new();
    let (mut expr, mut flags) = (expr, flags);
    loop {
        let (child, child_flags, tail) = match &expr.kind {
            ast::ExpressionKind::CallExpression(call) => {
                let needs_chain = needs_chain_wrap(expr, flags);
                let callee_chain = child_chain(
                    expr.span.start,
                    call.callee.span().start,
                    needs_chain,
                    flags,
                );
                let (force, strip) = flags_after_wrap(flags, needs_chain);
                open_chain_link(
                    w,
                    needs_chain,
                    "CallExpression",
                    ",\"callee\":",
                    expr.span,
                    ctx,
                );
                (
                    call.callee,
                    call_callee_flags(call, callee_chain, strip),
                    (
                        ChainTail::Call {
                            call,
                            callee_chain,
                            force,
                            strip,
                        },
                        needs_chain,
                    ),
                )
            }
            ast::ExpressionKind::MemberExpression(member) => {
                let needs_chain = needs_chain_wrap(expr, flags);
                let object_chain = child_chain(
                    expr.span.start,
                    member.object.span().start,
                    needs_chain,
                    flags,
                );
                let (force, strip) = flags_after_wrap(flags, needs_chain);
                open_chain_link(
                    w,
                    needs_chain,
                    "MemberExpression",
                    ",\"object\":",
                    expr.span,
                    ctx,
                );
                (
                    member.object,
                    ExprFlags {
                        chain: object_chain,
                        force_optional: false,
                        strip_optional: strip,
                    },
                    (
                        ChainTail::Member {
                            member,
                            force,
                            strip,
                        },
                        needs_chain,
                    ),
                )
            }
            ast::ExpressionKind::TSNonNullExpression(non_null) => {
                let needs_chain = needs_chain_wrap(expr, flags);
                // A parenthesized inner chain seals at the parens, so the paren-aware
                // child check applies like it does for calls/members.
                let inner_chain = child_chain(
                    expr.span.start,
                    non_null.expression.span().start,
                    needs_chain,
                    flags,
                );
                open_chain_link(
                    w,
                    needs_chain,
                    "TSNonNullExpression",
                    ",\"expression\":",
                    expr.span,
                    ctx,
                );
                (
                    non_null.expression,
                    // force/strip die here: TSNonNullExpression is not a call/member
                    // spine node.
                    ExprFlags {
                        chain: inner_chain,
                        ..ExprFlags::default()
                    },
                    (ChainTail::NonNull, needs_chain),
                )
            }
            _ => {
                write_expression_inner(w, expr, ctx, flags);
                break;
            }
        };
        tails.push((tail.0, expr.span, tail.1));
        expr = child;
        flags = child_flags;
    }
    for (tail, span, needs_chain) in tails.into_iter().rev() {
        match tail {
            ChainTail::Call {
                call,
                callee_chain,
                force,
                strip,
            } => write_call_expression_tail(w, call, span, ctx, callee_chain, force, strip),
            ChainTail::Member {
                member,
                force,
                strip,
            } => write_member_expression_tail(w, member, span, ctx, force, strip),
            ChainTail::NonNull => close_node(w, "TSNonNullExpression", span, ctx),
        }
        if needs_chain {
            close_node(w, "ChainExpression", span, ctx);
        }
    }
}

/// Open one link of [`write_chain`]: its `ChainExpression` wrap where `needs_chain`, then
/// its own header and the key of the child the walk continues into.
fn open_chain_link(
    w: &mut JsonWriter,
    needs_chain: bool,
    node_type: &'static str,
    child_key: &'static str,
    span: Span,
    ctx: &Ctx<'_>,
) {
    if needs_chain {
        node_header(w, "ChainExpression", span, ctx);
        w.raw(",\"expression\":");
    }
    node_header(w, node_type, span, ctx);
    w.raw(child_key);
}

/// Whether this call/member/non-null node opens a `ChainExpression` wrap.
///
/// Only an [`ChainState::Unresolved`] node walks: the other two states are the
/// parent handing down an answer already established.
fn needs_chain_wrap(expr: &ast::Expression<'_>, flags: ExprFlags) -> bool {
    flags.chain == ChainState::Unresolved && expr.has_optional_in_chain()
}

/// What a member's object / a call's callee inherits about the current optional
/// chain: a parenthesized child seals its own chain (the span gap over the
/// stripped `(` is the signal), so it inherits nothing and resolves for itself.
///
/// An unsealed child inherits exactly one verdict. Sitting on an optional chain
/// (this node opened one, or was already inside one) puts the child in it.
/// Otherwise this node resolved `has_optional_in_chain` to `false` — by walking
/// or by inheritance — and an optional-free unsealed node has an optional-free
/// child.
fn child_chain(
    parent_start: u32,
    child_start: u32,
    needs_chain: bool,
    flags: ExprFlags,
) -> ChainState {
    if parent_start < child_start {
        return ChainState::Unresolved;
    }
    if needs_chain || flags.chain == ChainState::InChain {
        ChainState::InChain
    } else {
        ChainState::KnownFree
    }
}

/// The force/strip flags a call/member node keeps for itself: a
/// `ChainExpression` wrap kills both (the flags don't reach past the wrapper).
fn flags_after_wrap(flags: ExprFlags, needs_chain: bool) -> (bool, bool) {
    if needs_chain {
        (false, false)
    } else {
        (flags.force_optional, flags.strip_optional)
    }
}

/// Emit an object-literal property (a `Property` or a `SpreadElement`).
fn write_object_property(w: &mut JsonWriter, prop: &ast::ObjectProperty<'_>, ctx: &Ctx<'_>) {
    match prop {
        ast::ObjectProperty::Property(p) => write_property(w, p, ctx),
        ast::ObjectProperty::SpreadElement(s) => {
            node_header(w, "SpreadElement", s.span, ctx);
            w.raw(",\"argument\":");
            write_expression(w, s.argument, ctx);
            close_node(w, "SpreadElement", s.span, ctx);
        }
    }
}