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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
// Control flow statement parsing (if, for, while, switch, try, throw, break, continue, labeled)

use crate::ast::*;
use crate::lexer::{KeywordKind, TokenKind};
use crate::parser::expression_assignable::AssignableContext;
use tsv_lang::{Error, Span};

use super::super::{Parser, RootEnd};

impl<'a, 'arena> Parser<'a, 'arena> {
    /// Parse if statement: `if (test) consequent` or `if (test) consequent else alternate`
    pub(super) fn parse_if_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'if' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::If)
        ));
        self.advance()?;

        let arena = self.arena;

        // Parse condition: (test)
        self.expect(&TokenKind::ParenOpen)?;
        let test = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        // Parse consequent (can be any statement, including block)
        let consequent = arena.alloc(self.parse_nested_statement()?);

        // Check for optional else clause
        let (alternate, end) =
            if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Else)) {
                self.advance()?; // consume 'else'
                let alt = self.parse_nested_statement()?;
                let alt_end = alt.span().end;
                (Some(&*arena.alloc(alt)), alt_end)
            } else {
                (None, consequent.span().end)
            };

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::IfStatement(IfStatement {
                test,
                consequent,
                alternate,
            }),
        })
    }

    /// Parse for statement: `for (init; test; update) body` or `for (left in/of right) body`
    /// Also handles `for await (left of right) body`
    pub(super) fn parse_for_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'for' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::For)
        ));
        self.advance()?;

        // Check for 'await' keyword: `for await (...)`
        let is_await = matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Await));
        // the keyword's own position: where a non-of head reports its rejection
        let await_at = if is_await {
            Some(self.current_pos().0)
        } else {
            None
        };
        if let Some(at) = await_at {
            // `for await` is an `[+Await]` production. At `Script` goal a position a module
            // would take it in — the top level, and the blocks under it — refuses it, and the
            // refusal is a goal gate: only a module holds the loop there, so the format
            // fallback reads the file as one (`parse_with_goal_or_fallback`). A non-async
            // function body takes it at neither goal and stays the deferred early error.
            if !self.in_await && self.in_await_if_module {
                return Err(self.error_goal_gate_at(
                    "'for await' at the top level is only allowed in a module",
                    at,
                ));
            }
            self.advance()?;
        }

        self.expect(&TokenKind::ParenOpen)?;

        // Parse init/left part - could be:
        // 1. Empty (for (;;))
        // 2. Variable declaration (for (let x = 0; ...))
        // 3. Expression (for (x = 0; ...))
        // 4. Variable declaration for-in/of (for (let x of ...))
        // 5. Expression pattern for-in/of (for (x of ...))

        if self.check(&TokenKind::Semicolon) {
            // Empty init: `for (;;)`. The for-await bar is read at each of the three
            // non-of grammar exits, always before the exit's own `;` — see
            // `reject_for_await_without_of`.
            self.reject_for_await_without_of(await_at)?;
            self.advance()?;
            return self.parse_for_standard(start, None);
        }

        // Read ahead of the head's parse: the for-of `[lookahead ∉ { let, … }]` below
        // is a rule about the head's leftmost token, whatever the head turns out to be.
        let starts_with_let = matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Let));

        if let Some(kind) = self.for_head_declaration_kind(starts_with_let) {
            let var_decl = self.parse_for_head_declaration(kind)?;

            let Some(form) = self.for_in_of_separator() else {
                // Standard for loop with a declaration as init.
                return self.parse_c_style_for(
                    start,
                    await_at,
                    Some(self.arena.alloc(ForInit::VariableDeclaration(var_decl))),
                );
            };

            // The rules a declaration owes a for-in/of head, stated once here — the
            // one place a declaration reaches `parse_for_in` / `parse_for_of` from.
            //
            // `ForDeclaration` is a single `ForBinding`, so a head binds exactly one
            // declarator; `for (let a, b of …)` is a syntax error (acorn reports an
            // unexpected token at the `in`/`of`).
            if var_decl.declarations.len() != 1 {
                return Err(self.error_expected_found("a single binding in a for-in/of header"));
            }
            if form == ForInOf::In
                && matches!(
                    kind,
                    VariableDeclarationKind::Using | VariableDeclarationKind::AwaitUsing
                )
            {
                return Err(self.error_msg(&format!(
                    "'{}' declarations are not allowed in for-in loops",
                    kind.as_str()
                )));
            }
            // A `ForBinding` carries no `Initializer` either. A default *inside* a
            // binding pattern (`for (const {x = 1} of [])`) is a pattern default, not
            // a declarator initializer, and stays valid. The one extension is Annex
            // B's for-in `var` head (`for (var x = 1 in o)`, sloppy, a plain
            // identifier), out of scope at both goals — so every keyword and both
            // forms reject, as acorn and prettier do. The initializer's own `[~In]`
            // (`DeclaratorSite::ForHead`) is what brings a for-in head here at all
            // rather than letting the initializer swallow the `in`.
            if var_decl.declarations[0].init.is_some() {
                return Err(self.error_msg(&format!(
                    "{} loop variable declaration may not have an initializer",
                    form.loop_name()
                )));
            }

            self.advance()?;
            let left = self.arena.alloc(ForInOfLeft::VariableDeclaration(var_decl));
            return match form {
                ForInOf::In => self.parse_for_in(start, await_at, left),
                ForInOf::Of => self.parse_for_of(start, left, is_await),
            };
        }

        // `for await (async of …)` — here `async` is a plain IdentifierReference
        // LHS, not the start of an `async … =>` arrow (which the generic
        // expression path would assume on seeing `async` followed by `of`). The
        // for-of `[lookahead ∉ { async of }]` restriction applies ONLY to the
        // non-await for-of, so this is gated on `is_await`; plain
        // `for (async of …)` keeps falling through to the normal path and stays
        // rejected (matching acorn).
        if is_await
            && matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Async))
            && self.peek_is_identifier()
            && self.peek_value() == "of"
        {
            let (id_start, id_end) = self.current_pos();
            let name = self.current_ident_name();
            self.advance()?; // consume 'async'
            let async_ident = Expression::from_identifier(Identifier::simple(
                name,
                Span::new(id_start as u32, id_end as u32),
            ));
            self.advance()?; // consume 'of'
            return self.parse_for_of(
                start,
                self.arena.alloc(ForInOfLeft::Pattern(async_ident)),
                is_await,
            );
        }

        // Parse expression (could be init or left-hand side)
        // Use parse_expression_no_in to prevent `in` from being parsed as binary operator
        // a bare assignment as the init prints bare ([`Parser::self_pair`])
        let expr = self.pair_free_root(RootEnd::ForClause, Self::parse_expression_no_in)?;

        // A no-declaration for-in/of LHS is refined through `refine_assignable` (the
        // cover-grammar conversion): per the spec an `ObjectLiteral`/`ArrayLiteral` LHS
        // must cover an `AssignmentPattern` (enforcing the rest constraints + producing
        // the deep internal pattern, `ArrayExpression` → `ArrayPattern`), and any other
        // LHS must have a valid (non-`invalid`) assignment-target type — and, as the
        // WHOLE head, never an `AssignmentPattern` (`for ((a = b) of xs)`).
        let Some(form) = self.for_in_of_separator() else {
            // Standard for loop with expression init.
            return self.parse_c_style_for(
                start,
                await_at,
                Some(self.arena.alloc(ForInit::Expression(expr))),
            );
        };
        // `ForInOfStatement`'s of-forms carry `[lookahead ∉ { let, async of }]` (and
        // `[lookahead ≠ let]` for the for-await form), a restriction on the head's
        // leftmost TOKEN whatever shape follows it: `for (let of x)`, `for (let.x of y)`
        // and `for (let[0] of a)` are all syntax errors, and only `for ((let) … of x)`
        // says what they mean. The in-form restricts only `let [` (`[lookahead ≠ let
        // []`), so `for (let in o)` and `for (let.x in o)` are legal there while
        // `for (let[0] in o)` is not. acorn spells this the same way, off the token it
        // recorded before parsing the head. Of the three of-heads only `let.x` reaches
        // this check — `let of` reads as a declaration of `of` and dies at the missing
        // `;`, `let[0]` as an invalid binding pattern.
        if form == ForInOf::Of && starts_with_let {
            return Err(
                self.error_msg("The left-hand side of a for-of loop may not start with 'let'")
            );
        }
        // the pair the printer keeps around a `let` heading the clause (`for ((let) in o)`),
        // a level of the output's nesting
        if starts_with_let {
            self.printer_pair()?;
        }
        self.advance()?;
        let left = self.refine_whole_assignable(expr, AssignableContext::ForHead)?;
        let left = self.arena.alloc(ForInOfLeft::Pattern(left));
        match form {
            ForInOf::In => self.parse_for_in(start, await_at, left),
            ForInOf::Of => self.parse_for_of(start, left, is_await),
        }
    }

    /// The declaration keyword a `for` head opens with, if it opens with one —
    /// `starts_with_let` is whether its first token is `let`.
    ///
    /// Every declaration keyword takes the same three heads, and one dispatch states
    /// them: the for-of `ForDeclaration` and the C-style init for all of them, the
    /// for-in `ForDeclaration` for `var`/`let`/`const` alone. A using declaration is a
    /// `LexicalDeclaration`, so it is the `let` case minus for-in, which the proposal's
    /// `ForInOfStatement` reserves for `let`/`const`; tsc parses both of its heads, and
    /// acorn does from ES2026, one edition past the oracle's pin (a cataloged
    /// divergence).
    ///
    /// `const` and `var` are declaration keywords outright; `let` is one only when a
    /// binding follows it ([`Parser::at_let_declaration`]) — `for (let in o)`,
    /// `for (let; ;)`, `for (let = 3; ;)` and `for (let.x in o)` are expression heads
    /// whose leftmost token happens to be the `IdentifierReference` `let`.
    ///
    /// The shared dispatch predicates own the using heads' `[no LineTerminator here]`
    /// restrictions; a head adds one rule of its own — the for-of form's `[lookahead ≠
    /// using of]`, which makes `for (using of items)` a for-of whose LHS is the plain
    /// identifier `using`. It restricts the for-of `ForDeclaration` alone, so a
    /// C-style init may still bind `of` (`for (using of = a; ; )`): one token past
    /// `of` decides, as tsc reads it
    /// ([`Parser::peek_followed_by_declarator_continuation`]).
    fn for_head_declaration_kind(
        &mut self,
        starts_with_let: bool,
    ) -> Option<VariableDeclarationKind> {
        if matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Const | KeywordKind::Var)
        ) || (starts_with_let && self.at_let_declaration())
        {
            Some(self.current_variable_kind())
        } else if self.at_await_using_declaration() {
            Some(VariableDeclarationKind::AwaitUsing)
        } else if self.at_using_declaration()
            && (self.peek_value() != "of" || self.peek_followed_by_declarator_continuation())
        {
            Some(VariableDeclarationKind::Using)
        } else {
            None
        }
    }

    /// The for-in/of separator the head's left side stopped at, if any — `None` is
    /// a C-style head.
    fn for_in_of_separator(&self) -> Option<ForInOf> {
        if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::In)) {
            Some(ForInOf::In)
        } else if self.current_value() == "of" {
            Some(ForInOf::Of)
        } else {
            None
        }
    }

    /// `for await` heads exactly one production: `ForInOfStatement`'s
    /// `for await ( … of AssignmentExpression ) Statement` and its two binding
    /// spellings. There is no for-await-in head and no for-await C-style head, so every
    /// head that fails to reach a for-of rejects — and the head parse has exactly three
    /// such exits, each of which asks here **before** consuming anything of its own: the
    /// empty init (`for (;;)`), the C-style separator ([`Self::parse_c_style_for`], both
    /// spellings of the init), and the for-in head ([`Self::parse_for_in`], whose entry
    /// *is* its exit).
    ///
    /// "Before" is the load-bearing word, and it is a **diagnostic** requirement rather
    /// than a grammatical one: a malformed head (`for await (a b)`) dies on the separator
    /// first, and that error would report at the stray token instead of on the `await`
    /// keyword acorn puts it on. Pinned by `tests/for_await_rejection.rs`.
    ///
    /// The rejection is a **content** obligation as much as a grammar one: `await` is
    /// printed off the `ForOfStatement`'s own flag, and a `ForInStatement` /
    /// `ForStatement` carries no such field, so a head accepted here would format to
    /// `for (x in o)` with the keyword simply gone. acorn spells the same bar as an
    /// `unexpected(awaitAt)` at each of its exits, and the error lands on the `await`
    /// keyword here too.
    fn reject_for_await_without_of(&self, await_at: Option<usize>) -> Result<(), Error> {
        if let Some(at) = await_at {
            return Err(self.error_msg_at("'for await' can only be used in for-of loops", at));
        }
        Ok(())
    }

    /// The C-style exit shared by both init spellings: reject a `for await` head, then
    /// take the separator the exit owes and build. Split out so the two callers cannot
    /// disagree about that order — the rejection has to precede the `expect`, per
    /// [`Self::reject_for_await_without_of`].
    fn parse_c_style_for(
        &mut self,
        start: usize,
        await_at: Option<usize>,
        init: Option<&'arena ForInit<'arena>>,
    ) -> Result<Statement<'arena>, Error> {
        self.reject_for_await_without_of(await_at)?;
        self.expect(&TokenKind::Semicolon)?;
        self.parse_for_standard(start, init)
    }

    /// Parse standard for loop: `for (init; test; update) body`. Carries no `await_at`:
    /// a `for await` head is barred at each of the three exits that reach a non-for-of
    /// builder, all of them before this is called
    /// ([`Self::reject_for_await_without_of`]).
    fn parse_for_standard(
        &mut self,
        start: usize,
        init: Option<&'arena ForInit<'arena>>,
    ) -> Result<Statement<'arena>, Error> {
        // Parse test (optional)
        let test = if self.check(&TokenKind::Semicolon) {
            None
        } else {
            Some(self.parse_expression_ref()?)
        };
        self.expect(&TokenKind::Semicolon)?;

        // Parse update (optional)
        let update = if self.check(&TokenKind::ParenClose) {
            None
        } else {
            // a bare assignment as the update prints bare ([`Parser::self_pair`])
            Some(self.pair_free_root(RootEnd::ForClause, Self::parse_expression_ref)?)
        };
        self.expect(&TokenKind::ParenClose)?;

        // Parse body
        let body = self.arena.alloc(self.parse_nested_statement()?);
        let end = body.span().end;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::ForStatement(ForStatement {
                init,
                test,
                update,
                body,
            }),
        })
    }

    /// Parse for-in loop: `for (left in right) body`. `await_at` is the head's `await`
    /// keyword if it had one — rejected here, since this is not a for-of
    /// (`reject_for_await_without_of`).
    fn parse_for_in(
        &mut self,
        start: usize,
        await_at: Option<usize>,
        left: &'arena ForInOfLeft<'arena>,
    ) -> Result<Statement<'arena>, Error> {
        self.reject_for_await_without_of(await_at)?;

        let right = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        let body = self.arena.alloc(self.parse_nested_statement()?);
        let end = body.span().end;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::ForInStatement(ForInStatement { left, right, body }),
        })
    }

    /// Parse for-of loop: `for (left of right) body`
    fn parse_for_of(
        &mut self,
        start: usize,
        left: &'arena ForInOfLeft<'arena>,
        r#await: bool,
    ) -> Result<Statement<'arena>, Error> {
        let right = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        let body = self.arena.alloc(self.parse_nested_statement()?);
        let end = body.span().end;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::ForOfStatement(ForOfStatement {
                left,
                right,
                r#await,
                body,
            }),
        })
    }

    /// Parse while statement: `while (test) body`
    pub(super) fn parse_while_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (test, body, span) = self.parse_paren_head_statement(KeywordKind::While)?;
        Ok(Statement {
            span,
            kind: StatementKind::WhileStatement(WhileStatement { test, body }),
        })
    }

    /// Parse with statement: `with (object) body`
    ///
    /// Sloppy-mode Script code only — the caller reads `Parser::strict` and rejects
    /// ahead of this. Its shape is `while`'s exactly, which is also how prettier
    /// prints it (one printer keyed on the node type).
    pub(super) fn parse_with_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (object, body, span) = self.parse_paren_head_statement(KeywordKind::With)?;
        Ok(Statement {
            span,
            kind: StatementKind::WithStatement(WithStatement { object, body }),
        })
    }

    /// Parse the `keyword (expression) body` shape shared by `while` and `with` — the
    /// two statements whose head is one parenthesized expression and whose body is a
    /// single statement. Returns the head expression, the body, and the whole span.
    fn parse_paren_head_statement(
        &mut self,
        keyword: KeywordKind,
    ) -> Result<(&'arena Expression<'arena>, &'arena Statement<'arena>, Span), Error> {
        let (start, _) = self.current_pos();

        debug_assert_eq!(self.current_kind(), &TokenKind::Keyword(keyword));
        self.advance()?;

        // Parse the head: (expression)
        self.expect(&TokenKind::ParenOpen)?;
        let head = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        // Parse body
        let body = self.arena.alloc(self.parse_nested_statement()?);
        let end = body.span().end;

        Ok((head, body, Span::new(start as u32, end)))
    }

    /// Parse do-while statement: `do body while (test);`
    pub(super) fn parse_do_while_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'do' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Do)
        ));
        self.advance()?;

        // Parse body
        let body = self.arena.alloc(self.parse_nested_statement()?);

        // Expect 'while'
        if !matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::While)) {
            return Err(self.error_expected_after("'while'", "do statement body"));
        }
        self.advance()?;

        // The test stands past the body, which is a statement of its own: its `<` regions
        // do not reach it (`Parser::lt_regions_statement_base`).
        self.reset_lt_region_for_statement();

        // Parse condition: (test)
        self.expect(&TokenKind::ParenOpen)?;
        let test = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        // A semicolon is automatically inserted after a do-while's `)`
        // *unconditionally* (ASI rule 1, third bullet) — unlike ordinary
        // statement termination it needs no preceding line terminator and no
        // `}`/EOF lookahead, so this never errors. Consume an explicit `;` if
        // present; otherwise insert one implicitly. Local to do-while, so the
        // shared `semicolon()` helper stays restricted.
        self.eat(TokenKind::Semicolon)?;
        let end = self.prev_token_end() as u32;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::DoWhileStatement(DoWhileStatement { body, test }),
        })
    }

    /// Parse switch statement: `switch (discriminant) { cases }`
    pub(super) fn parse_switch_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'switch' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Switch)
        ));
        self.advance()?;

        // Parse discriminant: (expr)
        self.expect(&TokenKind::ParenOpen)?;
        let discriminant = self.parse_expression_ref()?;
        self.expect(&TokenKind::ParenClose)?;

        // Parse cases: { case ... }
        self.expect(&TokenKind::BraceOpen)?;
        // The clauses stand past the discriminant's `) {`: its `<` regions do not reach
        // their tests (`Parser::lt_regions_statement_base`).
        self.reset_lt_region_for_statement();
        let mut cases = self.bvec();

        // the cases are siblings (`ListFrame`)
        let mut frame = self.list_frame();
        while !matches!(self.current_kind(), TokenKind::BraceClose | TokenKind::Eof) {
            frame.element(self, cases.len());
            // one wire level: the `SwitchCase` (the depth limit's count)
            cases.push(self.nested(1, Self::parse_switch_case)?);
        }
        frame.close(self);

        let (_, end) = self.current_pos();
        self.expect(&TokenKind::BraceClose)?;

        Ok(Statement {
            span: Span::new(start as u32, end as u32),
            kind: StatementKind::SwitchStatement(SwitchStatement {
                discriminant,
                cases: cases.into_bump_slice(),
            }),
        })
    }

    /// Parse switch case: `case test: consequent` or `default: consequent`
    fn parse_switch_case(&mut self) -> Result<SwitchCase<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Check for 'case' or 'default'
        let test = if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Case)) {
            self.advance()?;
            Some(self.parse_expression_ref()?)
        } else if matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Default)
        ) {
            self.advance()?;
            None
        } else {
            return Err(self.error_expected("'case' or 'default'"));
        };

        self.expect(&TokenKind::Colon)?;
        let colon_end = self.prev_token_end();

        // Parse consequent statements until next case/default or closing brace
        let consequent = self.statement_list(1, |p, frame| {
            let mut consequent = p.bvec();
            while !matches!(
                p.current_kind(),
                TokenKind::Keyword(KeywordKind::Case)
                    | TokenKind::Keyword(KeywordKind::Default)
                    | TokenKind::BraceClose
                    | TokenKind::Eof
            ) {
                consequent.push(p.parse_statement()?);
                frame.next(p);
            }
            Ok(consequent)
        })?;
        // The next clause's test stands past this clause's statements, whose `<` regions
        // do not reach it. A clause with NO statement ends none: only a `:` and a keyword
        // part its test from the next one, and tsv's own type-argument scan reads through
        // both (`case a < b < c:⏎case d >> (e):` is a list to it), so those two tests
        // stay one region.
        if !consequent.is_empty() {
            self.reset_lt_region_for_statement();
        }

        let end = consequent
            .last()
            .map_or(colon_end, |s| s.span().end_usize());

        Ok(SwitchCase {
            test,
            consequent: consequent.into_bump_slice(),
            span: Span::new(start as u32, end as u32),
        })
    }

    /// Parse try statement: `try { block } catch (param) { handler } finally { finalizer }`
    pub(super) fn parse_try_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'try' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Try)
        ));
        self.advance()?;

        // Parse try block
        let block = self.parse_block_statement()?;

        // Parse optional catch clause
        let handler = if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Catch)) {
            // one wire level: the `CatchClause` over its parameter and block
            Some(&*self.arena.alloc(self.nested(1, Self::parse_catch_clause)?))
        } else {
            None
        };

        // Parse optional finally clause
        let finalizer = if matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Finally)
        ) {
            self.advance()?;
            Some(self.parse_block_statement()?)
        } else {
            None
        };

        // Must have at least catch or finally
        if handler.is_none() && finalizer.is_none() {
            return Err(self.error_msg("Missing catch or finally after try"));
        }

        let end = finalizer.as_ref().map_or_else(
            || handler.map_or(block.span.end, |h| h.span.end),
            |f| f.span.end,
        );

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::TryStatement(TryStatement {
                block,
                handler,
                finalizer,
            }),
        })
    }

    /// Parse catch clause: `catch (param) { body }` or `catch { body }`
    fn parse_catch_clause(&mut self) -> Result<CatchClause<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'catch' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Catch)
        ));
        self.advance()?;

        // Parse optional parameter: (param) or (param: type) or ({destructuring}) or ({destructuring}: Type)
        let param = if self.eat(TokenKind::ParenOpen)? {
            // A catch binding is a `BindingIdentifier` — a plain identifier, a
            // contextual type keyword (`catch (any)`), or `await` at Script
            // `[~Await]` (all covered by `try_binding_name`) — with an optional
            // `: type` annotation; or a destructuring pattern.
            let param = if let Some(name) = self.try_binding_name() {
                let (id_start, id_end) = self.current_pos();
                self.advance()?;

                // Check for type annotation: param: type
                let (extra, param_end) = if self.check(&TokenKind::Colon) {
                    let ta = self.parse_type_annotation()?;
                    let end = ta.span.end as usize;
                    (Some(self.typed_extra(ta)), end)
                } else {
                    (None, id_end)
                };

                Expression::from_identifier(Identifier {
                    escaped_name: name.escaped,
                    name_len: name.raw_len,
                    name_plain_ascii: name.plain_ascii,
                    optional: false,
                    extra,
                    span: Span::new(id_start as u32, param_end as u32),
                })
            } else {
                match self.current_kind() {
                    // Destructuring binding with an optional type annotation:
                    // catch ({message}) / catch ([x, y]) / catch ({message}: ErrorType).
                    // A catch binding takes no optional `?` marker.
                    TokenKind::BraceOpen | TokenKind::BracketOpen => {
                        self.parse_destructured_binding(false)?
                    }
                    _ => {
                        return Err(self.error_expected("catch parameter"));
                    }
                }
            };

            self.expect(&TokenKind::ParenClose)?;
            Some(param)
        } else {
            None
        };

        // Parse body
        let body = self.parse_block_statement()?;
        let end = body.span.end;

        Ok(CatchClause {
            param,
            body,
            span: Span::new(start as u32, end),
        })
    }

    /// Parse throw statement: `throw expr;`
    pub(super) fn parse_throw_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'throw' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Throw)
        ));
        self.advance()?;

        // throw must have an argument (no line terminator allowed between throw and expr)
        // ASI: `throw\nexpr` is a syntax error, not `throw; expr;`
        if self.can_insert_semicolon() {
            return Err(self.error_msg("Illegal newline after throw"));
        }

        let argument_token = self.current_pos().0;
        let argument = self.parse_expression_ref()?;
        self.restricted_argument_pair(argument, argument_token)?;
        let end = self.semicolon_end()?;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::ThrowStatement(ThrowStatement { argument }),
        })
    }

    /// Take the optional `LabelIdentifier` of a `break` / `continue`, or `None`
    /// when ASI ends the statement first (`break [no LineTerminator here]
    /// LabelIdentifier`, so a newline means the label-less form).
    ///
    /// The label set is [`Parser::at_reference_name`] — plain identifiers, the contextual
    /// keywords the lexer turns into `Keyword` tokens (`break async`, `continue
    /// string`), `let` (barred only by the deferred strict-mode early error), `await`
    /// exactly where the goal axis makes it an identifier (`break await` at Script
    /// `[~Await]`, reserved at Module), and `yield` only outside a generator. A bare
    /// `TokenKind::Identifier` test saw only the first group, so a label the
    /// *declaration* site accepted could not be referenced.
    ///
    /// Shared by both statements so the two cannot drift. The *declaration* side
    /// asks the same predicate, but at the statement dispatcher rather than inside
    /// [`Parser::parse_labeled_statement`] — see that function's note.
    fn take_optional_label_reference(&mut self) -> Result<Option<Identifier<'arena>>, Error> {
        if self.can_insert_semicolon() || !self.at_reference_name() {
            return Ok(None);
        }
        let (label_start, label_end) = self.current_pos();
        let name = self.current_ident_name_or_await();
        self.advance()?;
        Ok(Some(Identifier::simple(
            name,
            Span::new(label_start as u32, label_end as u32),
        )))
    }

    pub(super) fn parse_break_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'break' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Break)
        ));
        self.advance()?;

        let label = self.take_optional_label_reference()?;

        let end = self.semicolon_end()?;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::BreakStatement(BreakStatement { label }),
        })
    }

    /// Parse continue statement: `continue;` or `continue label;`
    pub(super) fn parse_continue_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        // Consume 'continue' keyword
        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Continue)
        ));
        self.advance()?;

        let label = self.take_optional_label_reference()?;

        let end = self.semicolon_end()?;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::ContinueStatement(ContinueStatement { label }),
        })
    }

    /// Parse debugger statement: `debugger;`
    pub(super) fn parse_debugger_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, _) = self.current_pos();

        debug_assert!(matches!(
            self.current_kind(),
            TokenKind::Keyword(KeywordKind::Debugger)
        ));
        self.advance()?;

        let end = self.semicolon_end()?;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::DebuggerStatement(DebuggerStatement),
        })
    }

    /// Parse labeled statement: `label: statement`
    pub(super) fn parse_labeled_statement(&mut self) -> Result<Statement<'arena>, Error> {
        let (start, label_end) = self.current_pos();

        // Parse the label identifier. The `LabelIdentifier` set is
        // `Parser::at_reference_name` — plain identifiers plus every keyword-lexed word
        // the lexer produces that may still be a name here (`async:`, `string:`,
        // `let:`, `await:` at Script `[~Await]`, `yield:` only outside a generator).
        //
        // ⚠️ The gate lives at the *caller* — `parse_statement` dispatches here only
        // when `at_reference_name()` holds — and `try_ident_or_contextual_name` below is
        // a name-BUILDING channel, strictly wider: it applies neither the goal axis
        // to `await` nor the `[~Yield]` production guard to `yield`. So a second
        // caller that skipped the gate would accept `function* g() { yield: ; }`,
        // which must reject. The assert pins that contract at the one caller there
        // is (mirroring `expression_arrow.rs`'s `at_binding_name` assert);
        // `at_reference_name` is a pure `&self` predicate, so it is safe here.
        debug_assert!(self.at_reference_name());
        let name = self
            .try_ident_or_contextual_name()
            .ok_or_else(|| self.error_expected("label"))?;
        self.advance()?;

        let label = Identifier::simple(name, Span::new(start as u32, label_end as u32));

        // Consume ':'
        self.expect(&TokenKind::Colon)?;

        // Parse the labeled statement
        let body_stmt = self.parse_nested_statement()?;

        // `LabelledItem : Statement | FunctionDeclaration`. A lexical declaration
        // (`let`/`const`) and a class declaration are not labelable statements, and
        // neither is a function declaration: the `FunctionDeclaration` arm carries the
        // "It is a Syntax Error if any source text is matched by this production"
        // early error, and the relaxation that lifts it is Annex B §B.3.2 (Labelled
        // Function Declarations) — normative but optional for a non-browser host, and
        // out of tsv's grammar at both goals. So the rejection holds in strict code by
        // the core early error and in sloppy code for want of the carve-out (acorn
        // reports an unexpected token). A `var` statement and ordinary statements are
        // fine; TS declarations (`enum`/`interface`/`type`/`namespace`)
        // acorn-typescript accepts, so they pass through.
        let label_target_invalid = match &body_stmt.kind {
            StatementKind::ClassDeclaration(_) | StatementKind::FunctionDeclaration(_) => true,
            StatementKind::VariableDeclaration(decl) => {
                !matches!(decl.kind, VariableDeclarationKind::Var)
            }
            _ => false,
        };
        if label_target_invalid {
            return Err(self.error_msg_at(
                "A label can only precede a statement, not a declaration",
                body_stmt.span().start as usize,
            ));
        }

        let body = self.arena.alloc(body_stmt);
        let end = body.span().end;

        Ok(Statement {
            span: Span::new(start as u32, end),
            kind: StatementKind::LabeledStatement(LabeledStatement { label, body }),
        })
    }
}

/// The two for-in/of heads a `for` head's left side can end at
/// ([`Parser::for_in_of_separator`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum ForInOf {
    In,
    Of,
}

impl ForInOf {
    /// The loop's name, for a diagnostic.
    const fn loop_name(self) -> &'static str {
        match self {
            Self::In => "for-in",
            Self::Of => "for-of",
        }
    }
}