Skip to main content

js_parse/
parser.rs

1//! The parser: tokens to [`crate::ast`].
2//!
3//! A recursive-descent parser with precedence climbing for expressions. It
4//! follows the specification's grammar productions closely, which keeps the
5//! early errors next to the code that can detect them.
6//!
7//! Two productions need backtracking / reinterpretation, exactly as in an
8//! engine:
9//!
10//! * **arrow functions** use the cover grammar. `(` starts either a
11//!   parenthesized expression or a parameter list; the parser speculatively
12//!   parses a parameter list and commits only if `=>` follows, otherwise it
13//!   restores the lexer and parses an expression.
14//! * **`let`** at statement start is a declaration keyword when followed by a
15//!   binding, otherwise an identifier.
16//!
17//! Automatic semicolon insertion is implemented where the grammar allows it
18//! (`Stmt` terminators, `do…while`, `return`/`throw` restricted productions,
19//! postfix `++`/`--`, `async` before arrow parameters, `yield`/`await`).
20//!
21//! Early errors implemented here (not at run time):
22//!
23//! * `with`, legacy octal literals/escapes, `delete identifier`,
24//!   `eval`/`arguments` as binding or assignment target — strict mode only;
25//! * `super` outside a method, `super()` outside a derived constructor,
26//!   `new.target` outside a function;
27//! * `await`/`yield` used as identifiers where they are reserved;
28//! * duplicate `__proto__` in an object literal, duplicate private names;
29//! * `break`/`continue` target validity, `return` outside a function;
30//! * `??` mixed with `&&`/`||` without parentheses, `-x ** y`, assignment to a
31//!   non-assignable target, `new` on an optional chain;
32//! * duplicate parameter names (always for arrows/methods/non-simple lists).
33//!
34//! Not implemented yet (tracked for M1b.2): scope-analysis early errors such as
35//! `let x; let x;` in the same block, and parameter/`var` conflicts.
36
37use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41
42/// Everything that has to be saved to backtrack.
43struct Snapshot<'a> {
44    lexer: Lexer<'a>,
45    current: Token,
46    prev_end: Position,
47    strict: bool,
48    allow_in: bool,
49    ctx: FnCtx,
50    loop_depth: u32,
51    switch_depth: u32,
52    labels: Vec<Label>,
53    private: Vec<PrivateEnv>,
54    top_level: bool,
55    cover_inits: Vec<Span>,
56    pending_exports: Vec<(String, Span)>,
57    current_legacy_octal: bool,
58    scopes: Vec<Scope>,
59}
60
61/// Context of the function currently being parsed.
62#[derive(Debug, Clone, Copy, Default)]
63struct FnCtx {
64    in_function: bool,
65    in_generator: bool,
66    in_async: bool,
67    /// Inside a method (or a nested arrow in one): `super.x` is legal.
68    in_method: bool,
69    /// Inside a derived class constructor: `super()` is legal.
70    in_derived_constructor: bool,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74enum LabelKind {
75    /// Labels a loop.
76    Iteration,
77    /// Labels any other statement.
78    Other,
79}
80
81#[derive(Debug, Clone)]
82struct Label {
83    name: String,
84    kind: LabelKind,
85}
86
87/// Private names declared by the class currently being parsed.
88#[derive(Debug, Clone, Default)]
89struct PrivateEnv {
90    names: Vec<PrivateName>,
91}
92
93#[derive(Debug, Clone)]
94struct PrivateName {
95    name: String,
96    has_get: bool,
97    has_set: bool,
98}
99
100impl PrivateEnv {
101    /// Register a private name. `get #x` + `set #x` is the only legal pair;
102    /// every other duplicate (including `get #x` twice) is an early error.
103    fn declare(&mut self, name: &str, accessor: Option<MethodKind>) -> bool {
104        if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
105            return match accessor {
106                Some(MethodKind::Get) if !existing.has_get => {
107                    existing.has_get = true;
108                    true
109                }
110                Some(MethodKind::Set) if !existing.has_set => {
111                    existing.has_set = true;
112                    true
113                }
114                _ => false,
115            };
116        }
117        let mut entry = PrivateName {
118            name: name.to_string(),
119            has_get: false,
120            has_set: false,
121        };
122        match accessor {
123            Some(MethodKind::Get) => entry.has_get = true,
124            Some(MethodKind::Set) => entry.has_set = true,
125            _ => {}
126        }
127        self.names.push(entry);
128        true
129    }
130
131    fn contains(&self, name: &str) -> bool {
132        self.names.iter().any(|n| n.name == name)
133    }
134}
135
136/// One lexical scope, used for the declaration-conflict early errors.
137#[derive(Debug, Clone)]
138struct Scope {
139    /// Whether this is a function/module scope (where `var` lands).
140    is_var_scope: bool,
141    /// `var`-declared names.
142    var_names: Vec<String>,
143    /// `let`/`const`/`class`/`import` names declared directly in this scope.
144    lex_names: Vec<String>,
145    /// Function-declaration names declared directly in this scope.
146    ///
147    /// Tracked apart from `var_names` because engines treat them differently:
148    /// two function declarations may share a name, a function at the top level
149    /// does not clash with an earlier `let`, and a function inside a block is
150    /// scoped to that block instead of hoisting.
151    fn_names: Vec<String>,
152    /// Names of *simple* (identifier) parameters, if this is a function body.
153    params: Vec<String>,
154}
155
156impl Scope {
157    fn block() -> Scope {
158        Scope {
159            is_var_scope: false,
160            var_names: Vec::new(),
161            lex_names: Vec::new(),
162            fn_names: Vec::new(),
163            params: Vec::new(),
164        }
165    }
166
167    fn function(params: Vec<String>) -> Scope {
168        Scope {
169            is_var_scope: true,
170            var_names: Vec::new(),
171            lex_names: Vec::new(),
172            fn_names: Vec::new(),
173            params,
174        }
175    }
176}
177
178/// Which kind of target a pattern is being built for.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180enum TargetKind {
181    /// `let x = 1`, `function f(x)`, `catch (x)` — binds new names.
182    Binding,
183    /// `x = 1`, `[a, b] = c` — assigns to existing bindings.
184    Assignment,
185}
186
187/// The arrow head produced by a successful speculative parse.
188struct ArrowHead {
189    params: Vec<Pattern>,
190    is_async: bool,
191    span: Span,
192    params_span: Span,
193}
194
195/// Default nesting limit.
196///
197/// QuickJS stops at roughly 700 nested parentheses, because it compares the real
198/// stack pointer against `--stack-size` (1 MiB by default). This port cannot do
199/// that portably, so it counts recursion depth instead; the depth a given stack
200/// can hold depends on the frame size, which differs a lot between build
201/// profiles (measured on an 8 MiB stack: ~220 levels in debug, ~1500 in release).
202/// The limit is therefore profile-dependent and deliberately leaves headroom, so
203/// that over-deep input produces a `SyntaxError: stack overflow` — exactly what
204/// QuickJS reports — instead of aborting the process.
205///
206/// [`Parser::set_max_depth`] raises it for callers that know they have a bigger
207/// stack (or a release build).
208pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
209
210/// ECMAScript 2025 parser.
211pub struct Parser<'a> {
212    lexer: Lexer<'a>,
213    current: Token,
214    prev_end: Position,
215    strict: bool,
216    module: bool,
217    allow_in: bool,
218    ctx: FnCtx,
219    loop_depth: u32,
220    switch_depth: u32,
221    labels: Vec<Label>,
222    private: Vec<PrivateEnv>,
223    top_level: bool,
224    /// Whether the token currently held by the parser contains an Annex B octal
225    /// literal or escape (checked again when strictness is switched on).
226    current_legacy_octal: bool,
227    /// Current recursion depth, and the limit that turns it into a
228    /// `SyntaxError` instead of a stack overflow.
229    depth: u32,
230    max_depth: u32,
231
232    /// Spans of `{a = 1}` object-literal shorthands. They are only legal when
233    /// the object is converted to a destructuring pattern, so any entry left
234    /// over at the end of a statement is a syntax error.
235    cover_inits: Vec<Span>,
236    /// `export {name}` clauses whose local binding still has to be checked
237    /// against the module's declared names (forward references are legal).
238    pending_exports: Vec<(String, Span)>,
239    /// Open lexical scopes, innermost last.
240    scopes: Vec<Scope>,
241}
242
243/// Parse `src` as a `Script`.
244pub fn parse_script(src: &str) -> Result<Program> {
245    Parser::new(src, false)?.parse_program()
246}
247
248/// Parse `src` as a `Module`.
249pub fn parse_module(src: &str) -> Result<Program> {
250    Parser::new(src, true)?.parse_program()
251}
252
253/// Parse `src` as a `Script` whose code is strict from the first token.
254///
255/// This is what a *direct* `eval` needs: the eval'd code inherits strictness from the
256/// code that called it, so `eval("x = 1")` inside a strict function is a
257/// `ReferenceError` rather than an implicit global. Prepending a `"use strict"`
258/// directive instead would shift every column on the first line, and the positions are
259/// exactly what a stack trace has to report.
260pub fn parse_script_strict(src: &str) -> Result<Program> {
261    let mut parser = Parser::new(src, false)?;
262    parser.enter_strict()?;
263    parser.parse_program()
264}
265
266/// Parse `src` as a direct `eval` body, inheriting `new.target` from the caller.
267///
268/// `eval("new.target")` is legal inside a function because the eval'd code runs in the
269/// caller's function context, even though the source being parsed is a bare script with
270/// no function of its own. `strict` is the caller's mode, which a sloppy eval does not
271/// derive from its own text.
272pub fn parse_eval_script(src: &str, strict: bool) -> Result<Program> {
273    parse_eval_script_in(src, strict, EvalContext::default())
274}
275
276/// What the code that called a direct `eval` allows its body to use.
277#[derive(Debug, Clone, Copy, Default)]
278pub struct EvalContext {
279    /// The caller is a method (or a nested arrow in one), so `super.x` is legal — the
280    /// eval'd code runs with the caller's `[[HomeObject]]`.
281    pub in_method: bool,
282    /// The caller is a derived class constructor, so `super()` is legal too.
283    pub in_derived_constructor: bool,
284}
285
286/// Parse `src` as a direct `eval` body with the caller's privileges.
287///
288/// An eval'd body is not a function of its own, but it runs *inside* one: `eval("super.f()")`
289/// is legal in a method, and `eval("new.target")` is legal in any function. The parser has
290/// to be told, because the source text alone has no way to know.
291pub fn parse_eval_script_in(src: &str, strict: bool, context: EvalContext) -> Result<Program> {
292    let mut parser = Parser::new(src, false)?;
293    parser.ctx.in_function = true;
294    parser.ctx.in_method = context.in_method;
295    parser.ctx.in_derived_constructor = context.in_derived_constructor;
296    if strict {
297        parser.enter_strict()?;
298    }
299    parser.parse_program()
300}
301
302/// Parse `src` as a single `Expression` (used by tests and by `eval`-like entry
303/// points that need the expression grammar only).
304pub fn parse_expression(src: &str) -> Result<Expr> {
305    let mut parser = Parser::new(src, false)?;
306    let expr = parser.parse_expression(true)?;
307    if !parser.current.is_eof() {
308        return Err(parser.unexpected());
309    }
310    Ok(expr)
311}
312
313impl<'a> Parser<'a> {
314    /// Create a parser over `src`. A module is always strict.
315    pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
316        let mut lexer = Lexer::new(src);
317        lexer.set_strict(module);
318        let current = lexer.next_token()?;
319        let current_legacy_octal = lexer.had_legacy_octal();
320        if module && current_legacy_octal {
321            return Err(SyntaxError::new(
322                "octal literals and octal escape sequences are not allowed in strict mode",
323                current.span,
324            ));
325        }
326        Ok(Parser {
327            lexer,
328            current,
329            prev_end: Position::START,
330            strict: module,
331            module,
332            allow_in: true,
333            ctx: FnCtx::default(),
334            loop_depth: 0,
335            switch_depth: 0,
336            labels: Vec::new(),
337            private: Vec::new(),
338            top_level: true,
339            current_legacy_octal,
340            depth: 0,
341            max_depth: DEFAULT_MAX_DEPTH,
342
343            cover_inits: Vec::new(),
344            pending_exports: Vec::new(),
345            scopes: vec![Scope::function(Vec::new())],
346        })
347    }
348
349    /// Raise or lower the nesting limit.
350    pub fn set_max_depth(&mut self, depth: u32) {
351        self.max_depth = depth;
352    }
353
354    /// Enter one level of recursion.
355    fn enter(&mut self) -> Result<()> {
356        self.depth += 1;
357        if self.depth > self.max_depth {
358            return Err(SyntaxError::new("stack overflow", self.current.span));
359        }
360        Ok(())
361    }
362
363    fn leave(&mut self) {
364        self.depth -= 1;
365    }
366
367    /// Parse the whole source.
368    pub fn parse_program(&mut self) -> Result<Program> {
369        let start = self.current.span.start;
370        let mut body = Vec::new();
371        let mut prologue = true;
372        while !self.current.is_eof() {
373            let stmt = self.parse_statement_list_item()?;
374            if prologue {
375                match self.directive_value(&stmt) {
376                    Some(directive) if directive == "use strict" => self.enter_strict()?,
377                    Some(_) => {}
378                    None => prologue = false,
379                }
380            }
381            body.push(stmt);
382        }
383        if self.module {
384            self.check_module_exports(&body)?;
385        }
386        Ok(Program {
387            kind: if self.module {
388                ProgramKind::Module
389            } else {
390                ProgramKind::Script
391            },
392            body,
393            span: Span::new(start, self.prev_end),
394            strict: self.strict,
395        })
396    }
397
398    /// `export {a}` requires `a` to be declared somewhere in the module (forward
399    /// references are legal, so this can only run once the whole body is known).
400    fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
401        if self.pending_exports.is_empty() {
402            return Ok(());
403        }
404        let mut declared: Vec<String> = Vec::new();
405        for stmt in body {
406            collect_module_binding(stmt, &mut declared);
407        }
408        let pending = std::mem::take(&mut self.pending_exports);
409        for (name, span) in pending {
410            if !declared.contains(&name) {
411                return Err(
412                    self.error_at(format!("exported variable '{name}' does not exist"), span)
413                );
414            }
415        }
416        Ok(())
417    }
418
419    // -- declaration tracking (early errors) -------------------------------
420
421    fn push_scope(&mut self, scope: Scope) {
422        self.scopes.push(scope);
423    }
424
425    fn pop_scope(&mut self) {
426        self.scopes.pop();
427    }
428
429    /// Declare a `let`/`const`/`class`/`import` name in the current scope.
430    ///
431    /// Conflicts are per scope: a lexical declaration clashes with another
432    /// lexical declaration, a `var`/function declaration or a simple parameter
433    /// *of the same scope*. `var a; { let a; }` is legal, `{ let a; { var a; } }`
434    /// is not (the `var` hoists past the `let`, which `declare_var` checks).
435    fn declare_lexical(&mut self, name: &str, span: Span) -> Result<()> {
436        let Some(scope) = self.scopes.last() else {
437            return Ok(());
438        };
439        let clashes = scope.lex_names.iter().any(|n| n == name)
440            || scope.var_names.iter().any(|n| n == name)
441            || scope.fn_names.iter().any(|n| n == name)
442            || scope.params.iter().any(|n| n == name);
443        if clashes {
444            return Err(self.duplicate_declaration(name, span));
445        }
446        if let Some(scope) = self.scopes.last_mut() {
447            scope.lex_names.push(name.to_string());
448        }
449        Ok(())
450    }
451
452    /// Declare a `var` or function-declaration name: it hoists to the nearest
453    /// function scope, but may not collide with a lexical name on the way up.
454    fn declare_var(&mut self, name: &str, span: Span) -> Result<()> {
455        for scope in self.scopes.iter().rev() {
456            if scope.lex_names.iter().any(|n| n == name) {
457                return Err(self.duplicate_declaration(name, span));
458            }
459            if scope.is_var_scope {
460                break;
461            }
462        }
463        let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
464            return Ok(());
465        };
466        // Record it in every scope it passes through: `{ var a; let a; }` is an
467        // early error because the block's VarDeclaredNames contain `a`.
468        for scope in &mut self.scopes[index..] {
469            if !scope.var_names.iter().any(|n| n == name) {
470                scope.var_names.push(name.to_string());
471            }
472        }
473        Ok(())
474    }
475
476    /// Declare a function declaration name.
477    ///
478    /// See [`Scope::fn_names`] for why this is not the same as a `var`.
479    fn declare_function(&mut self, name: &str, span: Span) -> Result<()> {
480        let in_var_scope = self.scopes.last().is_none_or(|s| s.is_var_scope);
481        if !in_var_scope {
482            let clashes = self
483                .scopes
484                .last()
485                .is_some_and(|s| s.lex_names.iter().any(|n| n == name));
486            if clashes {
487                return Err(self.duplicate_declaration(name, span));
488            }
489        } else if let Some(scope) = self.scopes.last_mut() {
490            if !scope.var_names.iter().any(|n| n == name) {
491                scope.var_names.push(name.to_string());
492            }
493        }
494        if let Some(scope) = self.scopes.last_mut() {
495            if !scope.fn_names.iter().any(|n| n == name) {
496                scope.fn_names.push(name.to_string());
497            }
498        }
499        Ok(())
500    }
501
502    fn duplicate_declaration(&self, name: &str, span: Span) -> SyntaxError {
503        self.error_at(
504            format!("identifier '{name}' has already been declared"),
505            span,
506        )
507    }
508
509    /// Declare every name bound by a pattern.
510    fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
511        let mut names = Vec::new();
512        pattern.bound_names(&mut names);
513        for name in names {
514            if is_var {
515                self.declare_var(&name.name, name.span)?;
516            } else {
517                self.declare_lexical(&name.name, name.span)?;
518            }
519        }
520        Ok(())
521    }
522
523    // -- token helpers -----------------------------------------------------
524
525    fn snapshot(&self) -> Snapshot<'a> {
526        Snapshot {
527            lexer: self.lexer.clone(),
528            current: self.current.clone(),
529            prev_end: self.prev_end,
530            strict: self.strict,
531            allow_in: self.allow_in,
532            ctx: self.ctx,
533            loop_depth: self.loop_depth,
534            switch_depth: self.switch_depth,
535            labels: self.labels.clone(),
536            private: self.private.clone(),
537            top_level: self.top_level,
538            cover_inits: self.cover_inits.clone(),
539            pending_exports: self.pending_exports.clone(),
540            current_legacy_octal: self.current_legacy_octal,
541            scopes: self.scopes.clone(),
542        }
543    }
544
545    fn restore(&mut self, snap: Snapshot<'a>) {
546        self.lexer = snap.lexer;
547        self.current = snap.current;
548        self.prev_end = snap.prev_end;
549        self.strict = snap.strict;
550        self.allow_in = snap.allow_in;
551        self.ctx = snap.ctx;
552        self.loop_depth = snap.loop_depth;
553        self.switch_depth = snap.switch_depth;
554        self.labels = snap.labels;
555        self.private = snap.private;
556        self.top_level = snap.top_level;
557        self.cover_inits = snap.cover_inits;
558        self.pending_exports = snap.pending_exports;
559        self.current_legacy_octal = snap.current_legacy_octal;
560        self.scopes = snap.scopes;
561    }
562
563    fn bump(&mut self) -> Result<()> {
564        self.prev_end = self.current.span.end;
565        self.current = self.lexer.next_token()?;
566        self.current_legacy_octal = self.lexer.had_legacy_octal();
567        if self.strict && self.current_legacy_octal {
568            return Err(SyntaxError::new(
569                "octal literals and octal escape sequences are not allowed in strict mode",
570                self.current.span,
571            ));
572        }
573        Ok(())
574    }
575
576    fn peek(&self) -> Result<Token> {
577        let mut lexer = self.lexer.clone();
578        lexer.next_token()
579    }
580
581    fn enter_strict(&mut self) -> Result<()> {
582        self.strict = true;
583        self.lexer.set_strict(true);
584        // The token after the `"use strict"` directive has already been scanned
585        // with the old (sloppy) rules.
586        if self.current_legacy_octal {
587            return Err(SyntaxError::new(
588                "octal literals and octal escape sequences are not allowed in strict mode",
589                self.current.span,
590            ));
591        }
592        Ok(())
593    }
594
595    fn at_punct(&self, p: Punct) -> bool {
596        matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
597    }
598
599    fn at_keyword(&self, k: Keyword) -> bool {
600        matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
601    }
602
603    fn at_contextual(&self, name: &str) -> bool {
604        self.at_ident(name)
605    }
606
607    fn at_ident(&self, name: &str) -> bool {
608        matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
609    }
610
611    fn eat_punct(&mut self, p: Punct) -> Result<bool> {
612        if self.at_punct(p) {
613            self.bump()?;
614            return Ok(true);
615        }
616        Ok(false)
617    }
618
619    fn expect_punct(&mut self, p: Punct) -> Result<()> {
620        if self.eat_punct(p)? {
621            Ok(())
622        } else {
623            Err(self.unexpected())
624        }
625    }
626
627    fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
628        if self.at_keyword(k) {
629            self.bump()?;
630            return Ok(true);
631        }
632        Ok(false)
633    }
634
635    fn eat_contextual(&mut self, name: &str) -> Result<bool> {
636        if self.at_ident(name) {
637            self.bump()?;
638            return Ok(true);
639        }
640        Ok(false)
641    }
642
643    fn unexpected(&self) -> SyntaxError {
644        SyntaxError::new(
645            format!("unexpected token: {}", self.current.kind.describe()),
646            self.current.span,
647        )
648    }
649
650    fn error(&self, message: impl Into<String>) -> SyntaxError {
651        SyntaxError::new(message, self.current.span)
652    }
653
654    fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
655        SyntaxError::new(message, span)
656    }
657
658    fn span_from(&self, start: Position) -> Span {
659        Span::new(start, self.prev_end)
660    }
661
662    /// Read an identifier that *binds* a name, applying the binding rules
663    /// (`eval`/`arguments`/`let` are restricted in strict mode).
664    fn expect_binding_ident(&mut self) -> Result<Ident> {
665        let ident = self.expect_ident()?;
666        self.check_binding_name(&ident.name, ident.span)?;
667        Ok(ident)
668    }
669
670    /// Read an identifier, rejecting reserved words.
671    fn expect_ident(&mut self) -> Result<Ident> {
672        match self.current.kind.clone() {
673            TokenKind::Ident(name) => {
674                let span = self.current.span;
675                self.check_identifier(&name, span)?;
676                self.bump()?;
677                Ok(Ident { name, span })
678            }
679            _ => Err(self.error(format!(
680                "expecting a variable name, got {}",
681                self.current.kind.describe()
682            ))),
683        }
684    }
685
686    /// Reject words that may not appear as an `IdentifierReference` here.
687    fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
688        if Keyword::lookup(name).is_some() {
689            return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
690        }
691        if self.strict && Keyword::is_strict_reserved(name) {
692            return Err(self.error_at(
693                format!("invalid use of strict mode reserved word '{name}'"),
694                span,
695            ));
696        }
697        if self.ctx.in_generator && name == "yield" {
698            return Err(self.error_at(
699                "invalid use of 'yield' identifier in a generator function",
700                span,
701            ));
702        }
703        if self.ctx.in_async && name == "await" {
704            return Err(self.error_at("unexpected 'await' identifier in an async function", span));
705        }
706        Ok(())
707    }
708
709    /// A declarative name (`let`, `class`, `function`, parameter): stricter than
710    /// an identifier reference because `let` is reserved in strict mode.
711    fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
712        self.check_identifier(name, span)?;
713        if self.strict && (name == "eval" || name == "arguments") {
714            return Err(self.error_at(
715                format!("invalid use of '{name}' as a binding in strict mode"),
716                span,
717            ));
718        }
719        if self.strict && name == "let" {
720            return Err(self.error_at(
721                "invalid use of 'let' as a variable name in strict mode",
722                span,
723            ));
724        }
725        Ok(())
726    }
727
728    /// The value of an expression statement that is a string literal with no
729    /// escape sequences (a directive prologue candidate).
730    fn directive_value(&self, stmt: &Stmt) -> Option<String> {
731        let StmtKind::Expr(expr) = &stmt.kind else {
732            return None;
733        };
734        let ExprKind::String(value) = &expr.unparen().kind else {
735            return None;
736        };
737        let raw = self.slice(expr.span);
738        if !raw.starts_with('"') && !raw.starts_with('\'') {
739            return None;
740        }
741        if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
742            return None;
743        }
744        Some(value.clone())
745    }
746
747    fn slice(&self, span: Span) -> &'a str {
748        let src = self.lexer.source();
749        let start = span.start.offset as usize;
750        let end = (span.end.offset as usize).min(src.len());
751        src.get(start..end).unwrap_or("")
752    }
753
754    // -- automatic semicolon insertion ------------------------------------
755
756    fn can_insert_semicolon(&self) -> bool {
757        self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
758    }
759
760    fn semicolon(&mut self) -> Result<()> {
761        if self.eat_punct(Punct::Semicolon)? {
762            return Ok(());
763        }
764        if self.can_insert_semicolon() {
765            return Ok(());
766        }
767        Err(self.unexpected())
768    }
769
770    // -- statements --------------------------------------------------------
771
772    fn parse_statement_list_item(&mut self) -> Result<Stmt> {
773        self.enter()?;
774        let result = self.parse_statement_list_item_guarded();
775        self.leave();
776        result
777    }
778
779    fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
780        let cover_mark = self.cover_inits.len();
781        let stmt = self.parse_statement_list_item_inner()?;
782        if self.cover_inits.len() > cover_mark {
783            let span = self.cover_inits[cover_mark];
784            self.cover_inits.truncate(cover_mark);
785            return Err(self.error_at("expecting '}'", span));
786        }
787        Ok(stmt)
788    }
789
790    fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
791        if self.at_keyword(Keyword::Function) {
792            let start = self.current.span.start;
793            let func = self.parse_function(FunctionForm::Declaration, false)?;
794            if let Some(name) = &func.name {
795                self.declare_function(&name.name, name.span)?;
796            }
797            return Ok(Stmt::new(
798                StmtKind::FuncDecl(Box::new(func)),
799                self.span_from(start),
800            ));
801        }
802        if self.at_ident("async") {
803            let peek = self.peek()?;
804            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
805                let start = self.current.span.start;
806                self.bump()?; // async
807                let func = self.parse_function(FunctionForm::Declaration, true)?;
808                if let Some(name) = &func.name {
809                    self.declare_function(&name.name, name.span)?;
810                }
811                return Ok(Stmt::new(
812                    StmtKind::FuncDecl(Box::new(func)),
813                    self.span_from(start),
814                ));
815            }
816        }
817        if self.at_keyword(Keyword::Class) {
818            let start = self.current.span.start;
819            let class = self.parse_class(false)?;
820            if let Some(name) = &class.name {
821                self.declare_lexical(&name.name, name.span)?;
822            }
823            return Ok(Stmt::new(
824                StmtKind::ClassDecl(Box::new(class)),
825                self.span_from(start),
826            ));
827        }
828        if self.at_keyword(Keyword::Var) {
829            let start = self.current.span.start;
830            let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
831            self.semicolon()?;
832            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
833        }
834        if self.at_keyword(Keyword::Const) {
835            let start = self.current.span.start;
836            let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
837            self.semicolon()?;
838            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
839        }
840        if self.at_ident("let") && self.let_starts_declaration()? {
841            let start = self.current.span.start;
842            let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
843            self.semicolon()?;
844            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
845        }
846        // `await using x = …` is one declaration; `await` is only a keyword here when the
847        // enclosing code may await at all, which is the same rule `await` expressions use.
848        if self.at_ident("await")
849            && (self.ctx.in_async || self.module)
850            && self.await_using_follows()?
851        {
852            let start = self.current.span.start;
853            if self.top_level && !self.module {
854                return Err(self.error_at(
855                    "using declaration is not allowed at the top level of a script",
856                    self.span_from(start),
857                ));
858            }
859            self.bump()?; // await
860            let decl = self.parse_var_decl_with_keyword(VarDeclKind::AwaitUsing, "using")?;
861            self.semicolon()?;
862            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
863        }
864        if self.at_ident("using") && self.using_starts_declaration()? {
865            let start = self.current.span.start;
866            // A script's top level has no block to end, so there would be nowhere to
867            // dispose. The reference rejects it for the same reason; a module, whose
868            // top level *is* a scope, does not.
869            if self.top_level && !self.module {
870                return Err(self.error_at(
871                    "using declaration is not allowed at the top level of a script",
872                    self.span_from(start),
873                ));
874            }
875            let decl = self.parse_var_decl(VarDeclKind::Using, false, true)?;
876            self.semicolon()?;
877            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
878        }
879        if self.module && self.at_keyword(Keyword::Import) {
880            let peek = self.peek()?;
881            // `import(` and `import.meta` are expressions, not declarations.
882            if !matches!(
883                peek.kind,
884                TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
885            ) {
886                return self.parse_import_decl();
887            }
888        }
889        if self.module && self.at_keyword(Keyword::Export) {
890            return self.parse_export_decl();
891        }
892        self.parse_statement()
893    }
894
895    /// `let` is a declaration keyword when followed by a binding or a pattern.
896    fn let_starts_declaration(&self) -> Result<bool> {
897        let peek = self.peek()?;
898        Ok(matches!(
899            peek.kind,
900            TokenKind::Ident(_)
901                | TokenKind::Punct(Punct::LBracket)
902                | TokenKind::Punct(Punct::LBrace)
903        ))
904    }
905
906    /// The token after a `using` declaration head's binding name, if a head starts here.
907    ///
908    /// `skip` is how many words come before `using` — `1` for `await using`. Returns `None`
909    /// when the shape is not a declaration head at all: the binding must be a plain
910    /// identifier with no line terminator before it.
911    fn using_head_tail(&self, skip: usize) -> Result<Option<Token>> {
912        let mut lexer = self.lexer.clone();
913        // The lexer is already positioned after the current token, so the first
914        // `next_token` yields the token that follows it. `using` itself is `skip` words in,
915        // and the binding is the token after it.
916        let mut binding = None;
917        for _ in 0..=skip {
918            binding = Some(lexer.next_token()?);
919        }
920        let Some(binding) = binding else {
921            return Ok(None);
922        };
923        if binding.newline_before || !matches!(binding.kind, TokenKind::Ident(_)) {
924            return Ok(None);
925        }
926        Ok(Some(lexer.next_token()?))
927    }
928
929    /// Whether `await using` starts a declaration here.
930    ///
931    /// `await` is followed by `using`, which is in turn followed by a binding name and `=`.
932    /// Anything else — `await using(x)` where `using` is a function — is an `await`
933    /// expression over an ordinary call.
934    fn await_using_follows(&self) -> Result<bool> {
935        Ok(matches!(
936            self.using_head_tail(1)?.map(|token| token.kind),
937            Some(TokenKind::Punct(Punct::Eq))
938        ))
939    }
940
941    /// Whether the `using` at the current token begins a declaration.
942    ///
943    /// `using` is a contextual keyword, not a reserved word: `using = 1`, `using(x)` and
944    /// `using.f` are all ordinary expressions over a variable named `using`. The spec's
945    /// rule is `using [no LineTerminator] BindingIdentifier =`, so the binding name has to
946    /// be followed by `=`.
947    ///
948    /// Patterns are excluded on purpose: `using {a} = …` is not a using declaration, and
949    /// the grammar forbids it, so it stays an expression statement that fails to parse as
950    /// one.
951    fn using_starts_declaration(&self) -> Result<bool> {
952        Ok(matches!(
953            self.using_head_tail(0)?.map(|token| token.kind),
954            Some(TokenKind::Punct(Punct::Eq))
955        ))
956    }
957
958    /// Whether `using x of …` starts a `for` head here.
959    ///
960    /// The head has no initialiser, so the token after the binding is `of` (or `in`, which
961    /// the caller then rejects: a `using` may only iterate a `for`-`of`).
962    fn using_starts_for_head(&self) -> Result<bool> {
963        Ok(matches!(
964            self.using_head_tail(0)?.map(|token| token.kind),
965            Some(TokenKind::Ident(name)) if name == "of" || name == "in"
966        ))
967    }
968
969    /// Whether `await using x of …` starts a `for` head here.
970    fn await_using_starts_for_head(&self) -> Result<bool> {
971        Ok(matches!(
972            self.using_head_tail(1)?.map(|token| token.kind),
973            Some(TokenKind::Ident(name)) if name == "of" || name == "in"
974        ))
975    }
976
977    fn parse_statement(&mut self) -> Result<Stmt> {
978        let start = self.current.span.start;
979        if self.at_punct(Punct::Semicolon) {
980            self.bump()?;
981            return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
982        }
983        if self.at_punct(Punct::LBrace) {
984            let body = self.parse_block()?;
985            return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
986        }
987        if self.at_keyword(Keyword::If) {
988            return self.parse_if();
989        }
990        if self.at_keyword(Keyword::Do) {
991            return self.parse_do_while();
992        }
993        if self.at_keyword(Keyword::While) {
994            return self.parse_while();
995        }
996        if self.at_keyword(Keyword::For) {
997            return self.parse_for();
998        }
999        if self.at_keyword(Keyword::Switch) {
1000            return self.parse_switch();
1001        }
1002        if self.at_keyword(Keyword::Try) {
1003            return self.parse_try();
1004        }
1005        if self.at_keyword(Keyword::Return) {
1006            return self.parse_return();
1007        }
1008        if self.at_keyword(Keyword::Throw) {
1009            return self.parse_throw();
1010        }
1011        if self.at_keyword(Keyword::Break) {
1012            return self.parse_break_continue(true);
1013        }
1014        if self.at_keyword(Keyword::Continue) {
1015            return self.parse_break_continue(false);
1016        }
1017        if self.at_keyword(Keyword::With) {
1018            return self.parse_with();
1019        }
1020        if self.at_keyword(Keyword::Debugger) {
1021            self.bump()?;
1022            self.semicolon()?;
1023            return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
1024        }
1025        if self.at_keyword(Keyword::Function) {
1026            // Annex B: function declarations in statement position are legal in
1027            // sloppy mode (`if (x) function f() {}`).
1028            if self.strict {
1029                return Err(
1030                    self.error("invalid 'function' declaration in a single statement context")
1031                );
1032            }
1033            let func = self.parse_function(FunctionForm::Declaration, false)?;
1034            if let Some(name) = &func.name {
1035                self.declare_function(&name.name, name.span)?;
1036            }
1037            return Ok(Stmt::new(
1038                StmtKind::FuncDecl(Box::new(func)),
1039                self.span_from(start),
1040            ));
1041        }
1042        if self.at_keyword(Keyword::Class) {
1043            return Err(self.error("invalid 'class' declaration in a single statement context"));
1044        }
1045        if self.at_keyword(Keyword::Import) {
1046            return Err(self.error("'import' can only appear at the top level of a module"));
1047        }
1048        if self.at_keyword(Keyword::Export) {
1049            return Err(self.error("'export' can only appear at the top level of a module"));
1050        }
1051        // Labelled statement.
1052        if matches!(self.current.kind, TokenKind::Ident(_)) {
1053            let peek = self.peek()?;
1054            if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1055                return self.parse_labeled();
1056            }
1057        }
1058        self.parse_expression_statement()
1059    }
1060
1061    fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1062        self.expect_punct(Punct::LBrace)?;
1063        self.push_scope(Scope::block());
1064        let result = self.parse_block_body();
1065        self.pop_scope();
1066        let body = result?;
1067        self.bump()?; // }
1068        Ok(body)
1069    }
1070
1071    /// `{ … }` of a `catch` clause: parsed in the scope holding its parameter.
1072    fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1073        self.expect_punct(Punct::LBrace)?;
1074        let body = self.parse_block_body()?;
1075        self.bump()?; // }
1076        Ok(body)
1077    }
1078
1079    fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1080        let mut body = Vec::new();
1081        while !self.at_punct(Punct::RBrace) {
1082            if self.current.is_eof() {
1083                return Err(self.unexpected());
1084            }
1085            body.push(self.parse_statement_list_item()?);
1086        }
1087        Ok(body)
1088    }
1089
1090    fn parse_expression_statement(&mut self) -> Result<Stmt> {
1091        let start = self.current.span.start;
1092        let expr = self.parse_expression(true)?;
1093        self.semicolon()?;
1094        Ok(Stmt::new(
1095            StmtKind::Expr(Box::new(expr)),
1096            self.span_from(start),
1097        ))
1098    }
1099
1100    fn parse_if(&mut self) -> Result<Stmt> {
1101        let start = self.current.span.start;
1102        self.bump()?; // if
1103        self.expect_punct(Punct::LParen)?;
1104        let test = self.parse_expression(true)?;
1105        self.expect_punct(Punct::RParen)?;
1106        let cons = self.parse_statement()?;
1107        let alt = if self.eat_keyword(Keyword::Else)? {
1108            Some(Box::new(self.parse_statement()?))
1109        } else {
1110            None
1111        };
1112        Ok(Stmt::new(
1113            StmtKind::If {
1114                test: Box::new(test),
1115                cons: Box::new(cons),
1116                alt,
1117            },
1118            self.span_from(start),
1119        ))
1120    }
1121
1122    fn parse_do_while(&mut self) -> Result<Stmt> {
1123        let start = self.current.span.start;
1124        self.bump()?; // do
1125        self.loop_depth += 1;
1126        let body = self.parse_statement();
1127        self.loop_depth -= 1;
1128        let body = body?;
1129        if !self.eat_keyword(Keyword::While)? {
1130            return Err(self.unexpected());
1131        }
1132        self.expect_punct(Punct::LParen)?;
1133        let test = self.parse_expression(true)?;
1134        self.expect_punct(Punct::RParen)?;
1135        // `do … while (x)` allows a missing semicolon even without a newline.
1136        let _ = self.eat_punct(Punct::Semicolon)?;
1137        Ok(Stmt::new(
1138            StmtKind::DoWhile {
1139                body: Box::new(body),
1140                test: Box::new(test),
1141            },
1142            self.span_from(start),
1143        ))
1144    }
1145
1146    fn parse_while(&mut self) -> Result<Stmt> {
1147        let start = self.current.span.start;
1148        self.bump()?; // while
1149        self.expect_punct(Punct::LParen)?;
1150        let test = self.parse_expression(true)?;
1151        self.expect_punct(Punct::RParen)?;
1152        self.loop_depth += 1;
1153        let body = self.parse_statement();
1154        self.loop_depth -= 1;
1155        Ok(Stmt::new(
1156            StmtKind::While {
1157                test: Box::new(test),
1158                body: Box::new(body?),
1159            },
1160            self.span_from(start),
1161        ))
1162    }
1163
1164    fn parse_for(&mut self) -> Result<Stmt> {
1165        let start = self.current.span.start;
1166        self.bump()?; // for
1167        self.push_scope(Scope::block());
1168        let result = self.parse_for_inner(start);
1169        self.pop_scope();
1170        result
1171    }
1172
1173    fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1174        let mut is_await = false;
1175        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
1176            let peek = self.peek()?;
1177            if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1178                is_await = true;
1179                self.bump()?;
1180            }
1181        }
1182        self.expect_punct(Punct::LParen)?;
1183
1184        // `for (;;)`
1185        if self.at_punct(Punct::Semicolon) {
1186            self.bump()?;
1187            return self.parse_for_classic(start, None);
1188        }
1189
1190        // Declaration head.
1191        let decl_kind = if self.at_keyword(Keyword::Var) {
1192            Some(VarDeclKind::Var)
1193        } else if self.at_keyword(Keyword::Const) {
1194            Some(VarDeclKind::Const)
1195        } else if self.at_ident("let") && self.let_starts_declaration()? {
1196            Some(VarDeclKind::Let)
1197        } else if self.at_ident("using") && self.using_starts_for_head()? {
1198            Some(VarDeclKind::Using)
1199        } else if self.at_ident("await")
1200            && (self.ctx.in_async || self.module)
1201            && self.await_using_starts_for_head()?
1202        {
1203            self.bump()?; // await, leaving `using` as the keyword
1204            Some(VarDeclKind::AwaitUsing)
1205        } else {
1206            None
1207        };
1208        if let Some(kind) = decl_kind {
1209            let decl_start = self.current.span.start;
1210            let decl = self.parse_var_decl(kind, true, false)?;
1211            if self.at_for_head_keyword() {
1212                let is_of = self.at_contextual("of");
1213                if !is_of && decl.declarators.len() != 1 {
1214                    return Err(self.error_at(
1215                        "only one binding allowed in a for-in loop",
1216                        self.span_from(decl_start),
1217                    ));
1218                }
1219                if is_of && decl.declarators.len() != 1 {
1220                    return Err(self.error_at(
1221                        "only one binding allowed in a for-of loop",
1222                        self.span_from(decl_start),
1223                    ));
1224                }
1225                if let Some(declarator) = decl.declarators.first() {
1226                    if declarator.init.is_some() {
1227                        // `for (var x = 1 in y)` is legacy in sloppy mode only.
1228                        if is_of || kind.is_lexical() || self.strict {
1229                            return Err(self.error_at(
1230                                "for-in/of loop variable declaration may not have an initializer",
1231                                declarator.span,
1232                            ));
1233                        }
1234                    }
1235                }
1236                if is_await && !is_of {
1237                    return Err(self.error("for await is only valid with 'of'"));
1238                }
1239                self.bump()?; // in / of
1240                let right = self.parse_expression(true)?;
1241                self.expect_punct(Punct::RParen)?;
1242                self.loop_depth += 1;
1243                let body = self.parse_statement();
1244                self.loop_depth -= 1;
1245                let head = ForHead::VarDecl(decl);
1246                let span = self.span_from(start);
1247                return Ok(Stmt::new(
1248                    if is_of {
1249                        StmtKind::ForOf {
1250                            is_await,
1251                            left: head,
1252                            right: Box::new(right),
1253                            body: Box::new(body?),
1254                        }
1255                    } else {
1256                        StmtKind::ForIn {
1257                            left: head,
1258                            right: Box::new(right),
1259                            body: Box::new(body?),
1260                        }
1261                    },
1262                    span,
1263                ));
1264            }
1265            self.expect_punct(Punct::Semicolon)?;
1266            return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1267        }
1268
1269        // Expression head.
1270        let expr_start = self.current.span.start;
1271        let expr = self.parse_expression(false)?;
1272        if self.at_for_head_keyword() {
1273            let is_of = self.at_contextual("of");
1274            if is_await && !is_of {
1275                return Err(self.error("for await is only valid with 'of'"));
1276            }
1277            let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1278            self.bump()?; // in / of
1279            let right = self.parse_expression(true)?;
1280            self.expect_punct(Punct::RParen)?;
1281            self.loop_depth += 1;
1282            let body = self.parse_statement();
1283            self.loop_depth -= 1;
1284            let head = ForHead::Assign(Box::new(target));
1285            let span = self.span_from(start);
1286            return Ok(Stmt::new(
1287                if is_of {
1288                    StmtKind::ForOf {
1289                        is_await,
1290                        left: head,
1291                        right: Box::new(right),
1292                        body: Box::new(body?),
1293                    }
1294                } else {
1295                    StmtKind::ForIn {
1296                        left: head,
1297                        right: Box::new(right),
1298                        body: Box::new(body?),
1299                    }
1300                },
1301                span,
1302            ));
1303        }
1304        let _ = expr_start;
1305        self.expect_punct(Punct::Semicolon)?;
1306        self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1307    }
1308
1309    /// Whether the `for` head continues with `in` (a keyword) or `of` (a
1310    /// contextual keyword).
1311    fn at_for_head_keyword(&self) -> bool {
1312        self.at_keyword(Keyword::In) || self.at_contextual("of")
1313    }
1314
1315    fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1316        let test = if self.at_punct(Punct::Semicolon) {
1317            None
1318        } else {
1319            Some(Box::new(self.parse_expression(true)?))
1320        };
1321        self.expect_punct(Punct::Semicolon)?;
1322        let update = if self.at_punct(Punct::RParen) {
1323            None
1324        } else {
1325            Some(Box::new(self.parse_expression(true)?))
1326        };
1327        self.expect_punct(Punct::RParen)?;
1328        self.loop_depth += 1;
1329        let body = self.parse_statement();
1330        self.loop_depth -= 1;
1331        Ok(Stmt::new(
1332            StmtKind::For {
1333                init,
1334                test,
1335                update,
1336                body: Box::new(body?),
1337            },
1338            self.span_from(start),
1339        ))
1340    }
1341
1342    fn parse_switch(&mut self) -> Result<Stmt> {
1343        let start = self.current.span.start;
1344        self.bump()?; // switch
1345        self.expect_punct(Punct::LParen)?;
1346        let discriminant = self.parse_expression(true)?;
1347        self.expect_punct(Punct::RParen)?;
1348        self.expect_punct(Punct::LBrace)?;
1349        self.switch_depth += 1;
1350        self.push_scope(Scope::block());
1351        let mut cases = Vec::new();
1352        let mut seen_default = false;
1353        while !self.at_punct(Punct::RBrace) {
1354            if self.current.is_eof() {
1355                self.switch_depth -= 1;
1356                return Err(self.unexpected());
1357            }
1358            let case_start = self.current.span.start;
1359            let test = if self.eat_keyword(Keyword::Case)? {
1360                Some(Box::new(self.parse_expression(true)?))
1361            } else if self.eat_keyword(Keyword::Default)? {
1362                if seen_default {
1363                    self.switch_depth -= 1;
1364                    return Err(self.error("duplicate 'default' clause in switch statement"));
1365                }
1366                seen_default = true;
1367                None
1368            } else {
1369                self.switch_depth -= 1;
1370                return Err(self.unexpected());
1371            };
1372            self.expect_punct(Punct::Colon)?;
1373            let mut body = Vec::new();
1374            while !self.at_punct(Punct::RBrace)
1375                && !self.at_keyword(Keyword::Case)
1376                && !self.at_keyword(Keyword::Default)
1377            {
1378                if self.current.is_eof() {
1379                    self.switch_depth -= 1;
1380                    return Err(self.unexpected());
1381                }
1382                body.push(self.parse_statement_list_item()?);
1383            }
1384            cases.push(SwitchCase {
1385                test,
1386                body,
1387                span: self.span_from(case_start),
1388            });
1389        }
1390        self.switch_depth -= 1;
1391        self.bump()?; // }
1392        Ok(Stmt::new(
1393            StmtKind::Switch {
1394                discriminant: Box::new(discriminant),
1395                cases,
1396            },
1397            self.span_from(start),
1398        ))
1399    }
1400
1401    fn parse_try(&mut self) -> Result<Stmt> {
1402        let start = self.current.span.start;
1403        self.bump()?; // try
1404        let block = self.parse_block()?;
1405        let mut handler = None;
1406        let mut finalizer = None;
1407        if self.at_keyword(Keyword::Catch) {
1408            let catch_start = self.current.span.start;
1409            self.bump()?;
1410            // The catch parameter and the body share one scope, so `catch (e) {
1411            // let e; }` is an early error. A *simple* parameter is exempt from
1412            // the `var` check (`catch (e) { var e; }` is legal), a destructured
1413            // one is not (`catch ({e}) { var e; }` is rejected) — this matches
1414            // the reference engine.
1415            let param = if self.eat_punct(Punct::LParen)? {
1416                let pattern = self.parse_binding_target()?;
1417                self.expect_punct(Punct::RParen)?;
1418                Some(pattern)
1419            } else {
1420                None
1421            };
1422            self.push_scope(Scope::block());
1423            let body = match &param {
1424                // A simple parameter shares the body's scope: `catch (e) { let e;
1425                // }` is an error, `catch (e) { var e; }` is not.
1426                Some(Pattern {
1427                    kind: PatternKind::Ident(id),
1428                    ..
1429                }) => {
1430                    if let Some(scope) = self.scopes.last_mut() {
1431                        scope.params.push(id.name.clone());
1432                    }
1433                    self.parse_catch_body()
1434                }
1435                // A destructuring parameter is declared lexically in the clause's
1436                // own scope, with the body nested inside it: `catch ({e}) { var
1437                // e; }` is an error (the `var` hoists past the binding) while
1438                // `catch ({e}) { let e; }` is not.
1439                Some(pattern) => {
1440                    self.declare_pattern(pattern, false)?;
1441                    self.parse_block()
1442                }
1443                None => self.parse_catch_body(),
1444            };
1445            self.pop_scope();
1446            let body = body?;
1447            handler = Some(CatchClause {
1448                param,
1449                body,
1450                span: self.span_from(catch_start),
1451            });
1452        }
1453        if self.eat_keyword(Keyword::Finally)? {
1454            finalizer = Some(self.parse_block()?);
1455        }
1456        if handler.is_none() && finalizer.is_none() {
1457            return Err(self.error("expecting catch or finally"));
1458        }
1459        Ok(Stmt::new(
1460            StmtKind::Try {
1461                block,
1462                handler,
1463                finalizer,
1464            },
1465            self.span_from(start),
1466        ))
1467    }
1468
1469    fn parse_return(&mut self) -> Result<Stmt> {
1470        let start = self.current.span.start;
1471        let span = self.current.span;
1472        if !self.ctx.in_function {
1473            return Err(self.error_at("invalid return statement outside of a function", span));
1474        }
1475        self.bump()?;
1476        let argument = if self.at_punct(Punct::Semicolon)
1477            || self.at_punct(Punct::RBrace)
1478            || self.current.is_eof()
1479            || self.current.newline_before
1480        {
1481            None
1482        } else {
1483            Some(Box::new(self.parse_expression(true)?))
1484        };
1485        self.semicolon()?;
1486        Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
1487    }
1488
1489    fn parse_throw(&mut self) -> Result<Stmt> {
1490        let start = self.current.span.start;
1491        self.bump()?; // throw
1492        if self.current.newline_before {
1493            return Err(self.error("line terminator not allowed after 'throw'"));
1494        }
1495        let argument = self.parse_expression(true)?;
1496        self.semicolon()?;
1497        Ok(Stmt::new(
1498            StmtKind::Throw(Box::new(argument)),
1499            self.span_from(start),
1500        ))
1501    }
1502
1503    fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
1504        let start = self.current.span.start;
1505        let keyword_span = self.current.span;
1506        self.bump()?;
1507        let label = if matches!(self.current.kind, TokenKind::Ident(_))
1508            && !self.current.newline_before
1509        {
1510            let ident = self.expect_ident()?;
1511            let found = self.labels.iter().rev().find(|l| l.name == ident.name);
1512            match found {
1513                None => {
1514                    return Err(
1515                        self.error_at(format!("label '{}' not found", ident.name), ident.span)
1516                    );
1517                }
1518                Some(label) => {
1519                    if !is_break && label.kind != LabelKind::Iteration {
1520                        return Err(self.error_at(
1521                            format!("continue must be inside of a loop (label '{}')", ident.name),
1522                            ident.span,
1523                        ));
1524                    }
1525                }
1526            }
1527            Some(ident)
1528        } else {
1529            if !is_break && self.loop_depth == 0 {
1530                return Err(self.error_at("continue must be inside of a loop", keyword_span));
1531            }
1532            if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
1533            {
1534                return Err(self.error_at("break must be inside of a loop or switch", keyword_span));
1535            }
1536            None
1537        };
1538        self.semicolon()?;
1539        Ok(Stmt::new(
1540            if is_break {
1541                StmtKind::Break(label)
1542            } else {
1543                StmtKind::Continue(label)
1544            },
1545            self.span_from(start),
1546        ))
1547    }
1548
1549    fn parse_with(&mut self) -> Result<Stmt> {
1550        let start = self.current.span.start;
1551        let span = self.current.span;
1552        if self.strict {
1553            return Err(self.error_at("invalid 'with' statement in strict mode", span));
1554        }
1555        self.bump()?; // with
1556        self.expect_punct(Punct::LParen)?;
1557        let object = self.parse_expression(true)?;
1558        self.expect_punct(Punct::RParen)?;
1559        let body = self.parse_statement()?;
1560        Ok(Stmt::new(
1561            StmtKind::With {
1562                object: Box::new(object),
1563                body: Box::new(body),
1564            },
1565            self.span_from(start),
1566        ))
1567    }
1568
1569    fn parse_labeled(&mut self) -> Result<Stmt> {
1570        let start = self.current.span.start;
1571        let label = self.expect_ident()?;
1572        self.expect_punct(Punct::Colon)?;
1573        if self.labels.iter().any(|l| l.name == label.name) {
1574            return Err(self.error_at(
1575                format!("label '{}' already declared", label.name),
1576                label.span,
1577            ));
1578        }
1579        let kind = if self.at_keyword(Keyword::For)
1580            || self.at_keyword(Keyword::While)
1581            || self.at_keyword(Keyword::Do)
1582        {
1583            LabelKind::Iteration
1584        } else {
1585            LabelKind::Other
1586        };
1587        self.labels.push(Label {
1588            name: label.name.clone(),
1589            kind,
1590        });
1591        let body = self.parse_statement();
1592        self.labels.pop();
1593        Ok(Stmt::new(
1594            StmtKind::Labeled {
1595                label,
1596                body: Box::new(body?),
1597            },
1598            self.span_from(start),
1599        ))
1600    }
1601
1602    // -- declarations ------------------------------------------------------
1603
1604    fn parse_var_decl(
1605        &mut self,
1606        kind: VarDeclKind,
1607        in_for_head: bool,
1608        require_init: bool,
1609    ) -> Result<VarDecl> {
1610        let start = self.current.span.start;
1611        self.bump()?; // var / let / const / using
1612        self.parse_var_declarators(kind, in_for_head, require_init, start)
1613    }
1614
1615    /// A declaration whose leading keyword has already been consumed by the caller.
1616    ///
1617    /// `await using x = …` is written with two words, so the `await` is read first and only
1618    /// the `using` is left here.
1619    fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
1620        let start = self.current.span.start;
1621        if !self.at_ident(keyword) {
1622            return Err(self.error(format!("expected '{keyword}'")));
1623        }
1624        self.bump()?;
1625        self.parse_var_declarators(kind, false, true, start)
1626    }
1627
1628    fn parse_var_declarators(
1629        &mut self,
1630        kind: VarDeclKind,
1631        in_for_head: bool,
1632        require_init: bool,
1633        start: Position,
1634    ) -> Result<VarDecl> {
1635        let mut declarators = Vec::new();
1636        loop {
1637            let declarator_start = self.current.span.start;
1638            let target = self.parse_binding_target()?;
1639            // `using` disposes a value, so it binds a name and nothing else: a pattern has
1640            // no single resource to dispose.
1641            if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
1642                return Err(self.error_at(
1643                    "binding patterns are not allowed in using declarations",
1644                    target.span,
1645                ));
1646            }
1647            let init = if self.eat_punct(Punct::Eq)? {
1648                // `for (var x = a in b;;)` must not parse `a in b` as the
1649                // initialiser: the head uses AssignmentExpression[~In].
1650                Some(Box::new(self.parse_assignment(!in_for_head)?))
1651            } else {
1652                None
1653            };
1654            if init.is_none() && require_init {
1655                if kind == VarDeclKind::Const {
1656                    return Err(self.error("missing initializer in const declaration"));
1657                }
1658                if kind.is_using() {
1659                    return Err(self.error("missing initializer in using declaration"));
1660                }
1661                if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
1662                    return Err(self.error_at(
1663                        "missing initializer in destructuring declaration",
1664                        target.span,
1665                    ));
1666                }
1667            }
1668            if kind.is_lexical() {
1669                let mut names = Vec::new();
1670                target.bound_names(&mut names);
1671                if let Some(name) = names.iter().find(|n| n.name == "let") {
1672                    return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
1673                }
1674            }
1675            self.declare_pattern(&target, !kind.is_lexical())?;
1676            declarators.push(Declarator {
1677                target,
1678                init,
1679                span: self.span_from(declarator_start),
1680            });
1681            if !self.eat_punct(Punct::Comma)? {
1682                break;
1683            }
1684        }
1685        Ok(VarDecl {
1686            kind,
1687            declarators,
1688            span: self.span_from(start),
1689        })
1690    }
1691
1692    /// A binding element: `target` or `target = default`. Used for parameters and
1693    /// for elements of array/object patterns.
1694    fn parse_binding_element(&mut self) -> Result<Pattern> {
1695        let pattern = self.parse_binding_target()?;
1696        if self.eat_punct(Punct::Eq)? {
1697            let start = pattern.span.start;
1698            let default = self.parse_assignment(self.allow_in)?;
1699            return Ok(Pattern::new(
1700                PatternKind::Assign {
1701                    target: Box::new(pattern),
1702                    default: Box::new(default),
1703                },
1704                self.span_from(start),
1705            ));
1706        }
1707        Ok(pattern)
1708    }
1709
1710    /// A binding target: `Ident`, `[ … ]` or `{ … }`, with no default value.
1711    /// Used for declarators, `catch` parameters, rest elements and `for` heads.
1712    fn parse_binding_target(&mut self) -> Result<Pattern> {
1713        self.enter()?;
1714        let result = self.parse_binding_target_unguarded();
1715        self.leave();
1716        result
1717    }
1718
1719    fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
1720        let start = self.current.span.start;
1721        if self.at_punct(Punct::LBracket) {
1722            return self.parse_array_pattern(start);
1723        }
1724        if self.at_punct(Punct::LBrace) {
1725            return self.parse_object_pattern(start);
1726        }
1727        let ident = self.expect_binding_ident()?;
1728        Ok(Pattern::new(
1729            PatternKind::Ident(ident),
1730            self.span_from(start),
1731        ))
1732    }
1733
1734    fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
1735        self.expect_punct(Punct::LBracket)?;
1736        let mut elements = Vec::new();
1737        let mut rest = None;
1738        loop {
1739            if self.at_punct(Punct::RBracket) {
1740                break;
1741            }
1742            if self.at_punct(Punct::Comma) {
1743                self.bump()?;
1744                elements.push(None);
1745                continue;
1746            }
1747            if self.at_punct(Punct::Ellipsis) {
1748                self.bump()?;
1749                let target = self.parse_binding_target()?;
1750                if self.at_punct(Punct::Comma) {
1751                    return Err(self.error("rest element must be last"));
1752                }
1753                rest = Some(Box::new(RestElement::Pattern(target)));
1754                break;
1755            }
1756            let element_start = self.current.span.start;
1757            let element = self.parse_binding_element()?;
1758            let span = self.span_from(element_start);
1759            elements.push(Some(PatternElement::Pattern(element)));
1760            let _ = span;
1761            if !self.eat_punct(Punct::Comma)? {
1762                break;
1763            }
1764        }
1765        self.expect_punct(Punct::RBracket)?;
1766        Ok(Pattern::new(
1767            PatternKind::Array { elements, rest },
1768            self.span_from(start),
1769        ))
1770    }
1771
1772    fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
1773        self.expect_punct(Punct::LBrace)?;
1774        let mut properties = Vec::new();
1775        let mut rest = None;
1776        loop {
1777            if self.at_punct(Punct::RBrace) {
1778                break;
1779            }
1780            if self.at_punct(Punct::Ellipsis) {
1781                self.bump()?;
1782                let target = self.parse_binding_target()?;
1783                rest = Some(Box::new(RestElement::Pattern(target)));
1784                if self.at_punct(Punct::Comma) {
1785                    return Err(self.error("rest element must be last"));
1786                }
1787                break;
1788            }
1789            let property_start = self.current.span.start;
1790            let key = self.parse_property_key()?;
1791            if self.eat_punct(Punct::Colon)? {
1792                let value = self.parse_binding_element()?;
1793                properties.push(Some(PatternElement::Property {
1794                    key,
1795                    value,
1796                    shorthand: false,
1797                    span: self.span_from(property_start),
1798                }));
1799            } else {
1800                let PropName::Literal(PropKey::Str(name)) = &key else {
1801                    return Err(
1802                        self.error("expecting ':' after a computed or numeric property key")
1803                    );
1804                };
1805                let span = self.span_from(property_start);
1806                let ident = Ident {
1807                    name: name.clone(),
1808                    span,
1809                };
1810                self.check_binding_name(&ident.name, ident.span)?;
1811                let mut value = Pattern::new(PatternKind::Ident(ident), span);
1812                if self.eat_punct(Punct::Eq)? {
1813                    let default = self.parse_assignment(self.allow_in)?;
1814                    value = Pattern::new(
1815                        PatternKind::Assign {
1816                            target: Box::new(value),
1817                            default: Box::new(default),
1818                        },
1819                        span,
1820                    );
1821                }
1822                properties.push(Some(PatternElement::Property {
1823                    key,
1824                    value,
1825                    shorthand: true,
1826                    span,
1827                }));
1828            }
1829            if !self.eat_punct(Punct::Comma)? {
1830                break;
1831            }
1832        }
1833        self.expect_punct(Punct::RBrace)?;
1834        Ok(Pattern::new(
1835            PatternKind::Object { properties, rest },
1836            self.span_from(start),
1837        ))
1838    }
1839
1840    /// A property key: identifier, string, number, computed or `#private`.
1841    fn parse_property_key(&mut self) -> Result<PropName> {
1842        match self.current.kind.clone() {
1843            TokenKind::Ident(name) => {
1844                self.bump()?;
1845                Ok(PropName::Literal(PropKey::Str(name)))
1846            }
1847            TokenKind::Keyword(kw) => {
1848                // Reserved words are valid property names (`{ if: 1 }`).
1849                self.bump()?;
1850                Ok(PropName::Literal(PropKey::Str(kw.as_str().to_string())))
1851            }
1852            TokenKind::String(value) => {
1853                self.bump()?;
1854                Ok(PropName::Literal(PropKey::Str(value)))
1855            }
1856            TokenKind::Number(NumberLiteral::Int(v)) => {
1857                self.bump()?;
1858                Ok(PropName::Literal(PropKey::Num(v as f64)))
1859            }
1860            TokenKind::Number(NumberLiteral::Float(v)) => {
1861                self.bump()?;
1862                Ok(PropName::Literal(PropKey::Num(v)))
1863            }
1864            TokenKind::BigInt(big) => Err(self.error(format!(
1865                "BigInt property keys are not supported ('{}n')",
1866                big.digits
1867            ))),
1868            TokenKind::Punct(Punct::LBracket) => {
1869                self.bump()?;
1870                let expr = self.parse_assignment(true)?;
1871                self.expect_punct(Punct::RBracket)?;
1872                Ok(PropName::Computed(Box::new(expr)))
1873            }
1874            TokenKind::Punct(Punct::Hash) => {
1875                self.bump()?;
1876                let ident = self.expect_ident()?;
1877                Ok(PropName::Private(ident))
1878            }
1879            _ => Err(self.error("expecting a property name")),
1880        }
1881    }
1882
1883    // -- functions ---------------------------------------------------------
1884
1885    fn parse_function(&mut self, form: FunctionForm, is_async: bool) -> Result<Function> {
1886        let start = self.current.span.start;
1887        self.bump()?; // function
1888        let is_generator = self.eat_punct(Punct::Star)?;
1889        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
1890            let ident = if form == FunctionForm::Declaration {
1891                self.expect_binding_ident()?
1892            } else {
1893                self.expect_ident()?
1894            };
1895            if is_generator && ident.name == "yield" {
1896                return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
1897            }
1898            if is_async && ident.name == "await" {
1899                return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
1900            }
1901            Some(ident)
1902        } else {
1903            if form == FunctionForm::Declaration {
1904                return Err(self.error("expecting a function name"));
1905            }
1906            None
1907        };
1908        let saved = self.ctx;
1909        self.ctx = FnCtx {
1910            in_function: true,
1911            in_generator: is_generator,
1912            in_async: is_async,
1913            in_method: false,
1914            in_derived_constructor: false,
1915        };
1916        let saved_top = self.top_level;
1917        self.top_level = false;
1918        // Strictness is per function: `function f(){ "use strict"; }` must leave the
1919        // code *after* it sloppy. Without this save the directive leaked outwards, the
1920        // enclosing script was compiled as strict, and a later `function g(){}` lost its
1921        // declaration status — `typeof g` then raised instead of answering, because an
1922        // implicit global is not a declaration.
1923        let params_result = self.parse_formal_parameters();
1924        let result = match params_result {
1925            Ok(params) => self.parse_function_body(params, is_generator, is_async),
1926            Err(err) => Err(err),
1927        };
1928        self.ctx = saved;
1929        self.top_level = saved_top;
1930        let (params, params_span, body, strict) = result?;
1931        Ok(Function {
1932            name,
1933            params,
1934            body,
1935            is_async,
1936            is_generator,
1937            strict,
1938            is_arrow: false,
1939            span: self.span_from(start),
1940            params_span,
1941        })
1942    }
1943
1944    fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
1945        self.expect_punct(Punct::LParen)?;
1946        let mut params = Vec::new();
1947        loop {
1948            if self.at_punct(Punct::RParen) {
1949                break;
1950            }
1951            if self.at_punct(Punct::Ellipsis) {
1952                self.bump()?;
1953                let target = self.parse_binding_target()?;
1954                if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
1955                    return Err(self.error_at("rest parameter may not have a default", target.span));
1956                }
1957                params.push(Pattern::new(
1958                    PatternKind::Rest(Box::new(target.clone())),
1959                    target.span,
1960                ));
1961                if self.at_punct(Punct::Comma) {
1962                    return Err(self.error("rest parameter must be last"));
1963                }
1964                break;
1965            }
1966            let param = self.parse_binding_element()?;
1967            self.check_parameter(&param)?;
1968            params.push(param);
1969            if !self.eat_punct(Punct::Comma)? {
1970                break;
1971            }
1972        }
1973        self.expect_punct(Punct::RParen)?;
1974        Ok(params)
1975    }
1976
1977    fn check_parameter(&self, param: &Pattern) -> Result<()> {
1978        match &param.kind {
1979            PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
1980            PatternKind::Assign { target, .. } => self.check_parameter(target),
1981            _ => Ok(()),
1982        }
1983    }
1984
1985    fn parse_function_body(
1986        &mut self,
1987        params: Vec<Pattern>,
1988        is_generator: bool,
1989        is_async: bool,
1990    ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
1991        let params_span = self.prev_end;
1992        // Strictness is per function, so the body saves and restores it itself rather
1993        // than trusting every caller to do so: `function f(){ "use strict" }` must
1994        // leave the code after it sloppy, and the enclosing scope may well have been
1995        // strict too. The returned flag is the body's own mode.
1996        let saved_strict = self.strict;
1997        if !self.at_punct(Punct::LBrace) {
1998            return Err(self.unexpected());
1999        }
2000        let param_names = simple_parameter_names(&params);
2001        let simple_params = params
2002            .iter()
2003            .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2004        let mut body = Vec::new();
2005        let mut prologue = true;
2006        let mut strict_seen = false;
2007        self.bump()?; // {
2008        self.push_scope(Scope::function(param_names));
2009        while !self.at_punct(Punct::RBrace) {
2010            if self.current.is_eof() {
2011                return Err(self.unexpected());
2012            }
2013            let stmt = self.parse_statement_list_item()?;
2014            if prologue {
2015                match self.directive_value(&stmt) {
2016                    Some(directive) if directive == "use strict" => {
2017                        strict_seen = true;
2018                        self.enter_strict()?;
2019                    }
2020                    Some(_) => {}
2021                    None => prologue = false,
2022                }
2023            }
2024            body.push(stmt);
2025        }
2026        self.pop_scope();
2027        self.bump()?; // }
2028        // The body's own mode, still in force while the early errors below are
2029        // checked; the enclosing mode is restored once they are done.
2030        let body_strict = self.strict;
2031        if strict_seen && !simple_params {
2032            return Err(self.error_at(
2033                "'use strict' directive is not allowed with non-simple parameters",
2034                Span::new(params_span, params_span),
2035            ));
2036        }
2037        // Duplicate parameter names: always illegal for non-simple lists and in
2038        // strict mode; in sloppy simple lists they are allowed (last wins).
2039        if body_strict || !simple_params || is_generator || is_async {
2040            let mut seen: Vec<String> = Vec::new();
2041            for param in &params {
2042                let mut names = Vec::new();
2043                param.bound_names(&mut names);
2044                for name in names {
2045                    if seen.contains(&name.name) {
2046                        return Err(self.error_at(
2047                            format!("duplicate parameter name '{}'", name.name),
2048                            name.span,
2049                        ));
2050                    }
2051                    seen.push(name.name);
2052                }
2053            }
2054        }
2055        let params_span_value = Span::new(params_span, params_span);
2056        self.strict = saved_strict;
2057        self.lexer.set_strict(saved_strict);
2058        Ok((
2059            params,
2060            params_span_value,
2061            FunctionBody::Block(body),
2062            body_strict,
2063        ))
2064    }
2065
2066    // -- classes -----------------------------------------------------------
2067
2068    fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2069        let start = self.current.span.start;
2070        self.bump()?; // class
2071        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2072            if is_expression {
2073                Some(self.expect_ident()?)
2074            } else {
2075                Some(self.expect_binding_ident()?)
2076            }
2077        } else {
2078            if !is_expression {
2079                return Err(self.error("expecting a class name"));
2080            }
2081            None
2082        };
2083        let super_class = if self.eat_keyword(Keyword::Extends)? {
2084            Some(Box::new(self.parse_lhs_expression()?))
2085        } else {
2086            None
2087        };
2088        let has_super = super_class.is_some();
2089        self.private.push(PrivateEnv::default());
2090        self.expect_punct(Punct::LBrace)?;
2091        let mut elements = Vec::new();
2092        let mut seen_constructor = false;
2093        let result = (|| -> Result<()> {
2094            while !self.at_punct(Punct::RBrace) {
2095                if self.current.is_eof() {
2096                    return Err(self.unexpected());
2097                }
2098                if self.eat_punct(Punct::Semicolon)? {
2099                    continue;
2100                }
2101                elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2102            }
2103            Ok(())
2104        })();
2105        self.private.pop();
2106        result?;
2107        self.bump()?; // }
2108        Ok(Class {
2109            name,
2110            super_class,
2111            elements,
2112            span: self.span_from(start),
2113        })
2114    }
2115
2116    fn parse_class_element(
2117        &mut self,
2118        has_super: bool,
2119        seen_constructor: &mut bool,
2120    ) -> Result<ClassElement> {
2121        let start = self.current.span.start;
2122        let mut is_static = false;
2123        if self.at_ident("static") {
2124            let peek = self.peek()?;
2125            let is_modifier = !matches!(
2126                peek.kind,
2127                TokenKind::Punct(Punct::LParen)
2128                    | TokenKind::Punct(Punct::Eq)
2129                    | TokenKind::Punct(Punct::Semicolon)
2130                    | TokenKind::Punct(Punct::RBrace)
2131            );
2132            if is_modifier {
2133                if matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
2134                    self.bump()?; // static
2135                    let body = self.parse_block()?;
2136                    return Ok(ClassElement::StaticBlock {
2137                        body,
2138                        span: self.span_from(start),
2139                    });
2140                }
2141                self.bump()?; // static
2142                is_static = true;
2143                if self.at_punct(Punct::LBrace) {
2144                    let body = self.parse_block()?;
2145                    return Ok(ClassElement::StaticBlock {
2146                        body,
2147                        span: self.span_from(start),
2148                    });
2149                }
2150            }
2151        }
2152
2153        // Modifiers: async, get, set, *
2154        let mut is_async = false;
2155        let mut is_generator = false;
2156        let mut accessor: Option<MethodKind> = None;
2157        if self.at_ident("async") {
2158            let peek = self.peek()?;
2159            let is_modifier = !matches!(
2160                peek.kind,
2161                TokenKind::Punct(Punct::LParen)
2162                    | TokenKind::Punct(Punct::Eq)
2163                    | TokenKind::Punct(Punct::Semicolon)
2164                    | TokenKind::Punct(Punct::RBrace)
2165            ) && !peek.newline_before;
2166            if is_modifier {
2167                self.bump()?;
2168                is_async = true;
2169            }
2170        }
2171        if self.at_punct(Punct::Star) {
2172            self.bump()?;
2173            is_generator = true;
2174        }
2175        if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2176            let is_get = self.at_ident("get");
2177            let peek = self.peek()?;
2178            if is_property_key_start(&peek.kind) {
2179                self.bump()?;
2180                accessor = Some(if is_get {
2181                    MethodKind::Get
2182                } else {
2183                    MethodKind::Set
2184                });
2185            }
2186        }
2187        let key = self.parse_property_key()?;
2188
2189        // Private names must be registered (duplicates are early errors).
2190        if let PropName::Private(ident) = &key {
2191            if let Some(env) = self.private.last_mut() {
2192                if !env.declare(&ident.name, accessor) {
2193                    return Err(self.error_at(
2194                        format!("duplicate private name '#{}'", ident.name),
2195                        ident.span,
2196                    ));
2197                }
2198            }
2199        }
2200
2201        if self.at_punct(Punct::LParen) {
2202            let kind = match accessor {
2203                Some(kind) => kind,
2204                None => {
2205                    let is_constructor = !is_static
2206                        && !is_generator
2207                        && !is_async
2208                        && matches!(&key, PropName::Literal(PropKey::Str(s)) if s == "constructor");
2209                    if is_constructor {
2210                        if *seen_constructor {
2211                            return Err(self.error_at(
2212                                "property constructor appears more than once",
2213                                self.span_from(start),
2214                            ));
2215                        }
2216                        *seen_constructor = true;
2217                        MethodKind::Constructor
2218                    } else {
2219                        MethodKind::Method
2220                    }
2221                }
2222            };
2223            if kind == MethodKind::Constructor && (is_generator || is_async) {
2224                return Err(self.error("a constructor may not be a generator or async"));
2225            }
2226            let saved = self.ctx;
2227            self.ctx = FnCtx {
2228                in_function: true,
2229                in_generator: is_generator,
2230                in_async: is_async,
2231                in_method: true,
2232                in_derived_constructor: kind == MethodKind::Constructor && has_super,
2233            };
2234            let saved_top = self.top_level;
2235            self.top_level = false;
2236            let result = (|| -> Result<Function> {
2237                let params = self.parse_formal_parameters()?;
2238                let (params, params_span, body, strict) =
2239                    self.parse_function_body(params, is_generator, is_async)?;
2240                Ok(Function {
2241                    name: None,
2242                    params,
2243                    body,
2244                    is_async,
2245                    is_generator,
2246                    strict,
2247                    is_arrow: false,
2248                    span: self.span_from(start),
2249                    params_span,
2250                })
2251            })();
2252            self.ctx = saved;
2253            self.top_level = saved_top;
2254            let func = result?;
2255            if is_static {
2256                if let PropName::Literal(PropKey::Str(name)) = &key {
2257                    if name == "prototype" {
2258                        return Err(self.error_at("invalid method name 'prototype'", func.span));
2259                    }
2260                }
2261            }
2262            if kind == MethodKind::Get && !func.params.is_empty() {
2263                return Err(self.error_at("getter must have no arguments", func.span));
2264            }
2265            if kind == MethodKind::Set && func.params.len() != 1 {
2266                return Err(self.error_at("setter must have exactly one argument", func.span));
2267            }
2268            return Ok(ClassElement::Method {
2269                key,
2270                is_static,
2271                kind,
2272                func: Box::new(func),
2273                span: self.span_from(start),
2274            });
2275        }
2276
2277        // Field definition.
2278        if accessor.is_some() {
2279            return Err(self.error("expecting '(' after an accessor name"));
2280        }
2281        if let PropName::Literal(PropKey::Str(name)) = &key {
2282            if name == "constructor" && !is_static {
2283                return Err(self.error("classes may not have a field named 'constructor'"));
2284            }
2285            if name == "prototype" && is_static {
2286                return Err(self.error("classes may not have a static property named 'prototype'"));
2287            }
2288        }
2289        let value = if self.eat_punct(Punct::Eq)? {
2290            Some(Box::new(self.parse_assignment(true)?))
2291        } else {
2292            None
2293        };
2294        // Fields are terminated by `;`, `}` or a line break.
2295        self.semicolon()?;
2296        Ok(ClassElement::Field {
2297            key,
2298            is_static,
2299            value,
2300            span: self.span_from(start),
2301        })
2302    }
2303
2304    // -- modules -----------------------------------------------------------
2305
2306    fn parse_import_decl(&mut self) -> Result<Stmt> {
2307        let start = self.current.span.start;
2308        self.bump()?; // import
2309        let mut specifiers = Vec::new();
2310        if let TokenKind::String(source) = self.current.kind.clone() {
2311            self.bump()?;
2312            let attributes = self.parse_import_attributes()?;
2313            self.semicolon()?;
2314            return Ok(Stmt::new(
2315                StmtKind::Import(Box::new(ImportDecl {
2316                    specifiers,
2317                    source,
2318                    attributes,
2319                    span: self.span_from(start),
2320                })),
2321                self.span_from(start),
2322            ));
2323        }
2324        // Default import.
2325        if matches!(self.current.kind, TokenKind::Ident(_)) {
2326            let local = self.expect_ident()?;
2327            specifiers.push(ImportSpecifier::Default(local));
2328            if !self.eat_punct(Punct::Comma)? {
2329                return self.finish_import(start, specifiers);
2330            }
2331        }
2332        if self.at_punct(Punct::Star) {
2333            self.bump()?;
2334            if !self.eat_contextual("as")? {
2335                return Err(self.unexpected());
2336            }
2337            let local = self.expect_ident()?;
2338            specifiers.push(ImportSpecifier::Namespace(local));
2339            return self.finish_import(start, specifiers);
2340        }
2341        if self.at_punct(Punct::LBrace) {
2342            self.bump()?;
2343            while !self.at_punct(Punct::RBrace) {
2344                let imported = self.parse_module_name()?;
2345                let local = if self.eat_contextual("as")? {
2346                    self.expect_ident()?
2347                } else {
2348                    match &imported {
2349                        ModuleName::Ident(id) => id.clone(),
2350                        ModuleName::Str(_) => {
2351                            return Err(self.error_at(
2352                                "a string module name must be followed by 'as'",
2353                                self.current.span,
2354                            ));
2355                        }
2356                    }
2357                };
2358                specifiers.push(ImportSpecifier::Named { imported, local });
2359                if !self.eat_punct(Punct::Comma)? {
2360                    break;
2361                }
2362            }
2363            self.expect_punct(Punct::RBrace)?;
2364        } else if !specifiers.is_empty() {
2365            return Err(self.unexpected());
2366        } else if self.at_punct(Punct::LBrace) {
2367            unreachable!("handled above");
2368        } else {
2369            return Err(self.unexpected());
2370        }
2371        self.finish_import(start, specifiers)
2372    }
2373
2374    fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
2375        if !self.eat_contextual("from")? {
2376            return Err(self.unexpected());
2377        }
2378        let TokenKind::String(source) = self.current.kind.clone() else {
2379            return Err(self.error("expecting a module name string"));
2380        };
2381        self.bump()?;
2382        let attributes = self.parse_import_attributes()?;
2383        self.semicolon()?;
2384        let span = self.span_from(start);
2385        for specifier in &specifiers {
2386            let local = match specifier {
2387                ImportSpecifier::Default(id) => id,
2388                ImportSpecifier::Namespace(id) => id,
2389                ImportSpecifier::Named { local, .. } => local,
2390            };
2391            self.declare_lexical(&local.name, local.span)?;
2392        }
2393        Ok(Stmt::new(
2394            StmtKind::Import(Box::new(ImportDecl {
2395                specifiers,
2396                source,
2397                attributes,
2398                span,
2399            })),
2400            span,
2401        ))
2402    }
2403
2404    fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
2405        let mut attributes = Vec::new();
2406        let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
2407        if !has_with {
2408            return Ok(attributes);
2409        }
2410        let peek = self.peek()?;
2411        if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
2412            return Ok(attributes);
2413        }
2414        self.bump()?; // with / assert
2415        self.expect_punct(Punct::LBrace)?;
2416        while !self.at_punct(Punct::RBrace) {
2417            let attr_start = self.current.span.start;
2418            let key = match self.current.kind.clone() {
2419                TokenKind::Ident(name) => name,
2420                TokenKind::String(value) => value,
2421                _ => return Err(self.error("expecting an import attribute name")),
2422            };
2423            self.bump()?;
2424            self.expect_punct(Punct::Colon)?;
2425            let TokenKind::String(value) = self.current.kind.clone() else {
2426                return Err(self.error("expecting an import attribute value string"));
2427            };
2428            self.bump()?;
2429            attributes.push(ImportAttribute {
2430                key,
2431                value,
2432                span: self.span_from(attr_start),
2433            });
2434            if !self.eat_punct(Punct::Comma)? {
2435                break;
2436            }
2437        }
2438        self.expect_punct(Punct::RBrace)?;
2439        Ok(attributes)
2440    }
2441
2442    fn parse_module_name(&mut self) -> Result<ModuleName> {
2443        match self.current.kind.clone() {
2444            TokenKind::String(value) => {
2445                self.bump()?;
2446                Ok(ModuleName::Str(value))
2447            }
2448            TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
2449            TokenKind::Keyword(kw) => {
2450                let span = self.current.span;
2451                self.bump()?;
2452                Ok(ModuleName::Ident(Ident {
2453                    name: kw.as_str().to_string(),
2454                    span,
2455                }))
2456            }
2457            _ => Err(self.error("expecting an export name")),
2458        }
2459    }
2460
2461    fn parse_export_decl(&mut self) -> Result<Stmt> {
2462        let start = self.current.span.start;
2463        self.bump()?; // export
2464        if self.at_punct(Punct::Star) {
2465            self.bump()?;
2466            let mut exported = None;
2467            if self.eat_contextual("as")? {
2468                exported = Some(self.parse_module_name()?);
2469            }
2470            if !self.eat_contextual("from")? {
2471                return Err(self.error("expecting 'from' after 'export *'"));
2472            }
2473            let TokenKind::String(source) = self.current.kind.clone() else {
2474                return Err(self.error("expecting a module name string"));
2475            };
2476            self.bump()?;
2477            let attributes = self.parse_import_attributes()?;
2478            self.semicolon()?;
2479            let span = self.span_from(start);
2480            return Ok(Stmt::new(
2481                StmtKind::Export(Box::new(ExportDecl {
2482                    kind: ExportKind::All {
2483                        source,
2484                        exported,
2485                        attributes,
2486                    },
2487                    span,
2488                })),
2489                span,
2490            ));
2491        }
2492        if self.eat_keyword(Keyword::Default)? {
2493            let value = if self.at_keyword(Keyword::Function) {
2494                let func = self.parse_function(FunctionForm::Expression, false)?;
2495                Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2496            } else if self.at_ident("async") {
2497                let peek = self.peek()?;
2498                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
2499                    self.bump()?;
2500                    let func = self.parse_function(FunctionForm::Expression, true)?;
2501                    Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2502                } else {
2503                    self.parse_assignment(true)?
2504                }
2505            } else if self.at_keyword(Keyword::Class) {
2506                let class = self.parse_class(true)?;
2507                Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
2508            } else {
2509                let expr = self.parse_assignment(true)?;
2510                self.semicolon()?;
2511                expr
2512            };
2513            let span = self.span_from(start);
2514            return Ok(Stmt::new(
2515                StmtKind::Export(Box::new(ExportDecl {
2516                    kind: ExportKind::Default(Box::new(value)),
2517                    span,
2518                })),
2519                span,
2520            ));
2521        }
2522        if self.at_keyword(Keyword::Var)
2523            || self.at_keyword(Keyword::Const)
2524            || self.at_keyword(Keyword::Function)
2525            || self.at_keyword(Keyword::Class)
2526            || (self.at_ident("let") && self.let_starts_declaration()?)
2527        {
2528            let decl = self.parse_statement_list_item()?;
2529            let span = self.span_from(start);
2530            return Ok(Stmt::new(
2531                StmtKind::Export(Box::new(ExportDecl {
2532                    kind: ExportKind::Declaration(Box::new(decl)),
2533                    span,
2534                })),
2535                span,
2536            ));
2537        }
2538        if self.at_ident("async") {
2539            let peek = self.peek()?;
2540            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
2541                let decl = self.parse_statement_list_item()?;
2542                let span = self.span_from(start);
2543                return Ok(Stmt::new(
2544                    StmtKind::Export(Box::new(ExportDecl {
2545                        kind: ExportKind::Declaration(Box::new(decl)),
2546                        span,
2547                    })),
2548                    span,
2549                ));
2550            }
2551        }
2552        if self.at_punct(Punct::LBrace) {
2553            self.bump()?;
2554            let mut specifiers = Vec::new();
2555            let mut source = None;
2556            while !self.at_punct(Punct::RBrace) {
2557                let spec_start = self.current.span.start;
2558                let local = self.parse_module_name()?;
2559                let exported = if self.eat_contextual("as")? {
2560                    self.parse_module_name()?
2561                } else {
2562                    local.clone()
2563                };
2564                if source.is_none() {
2565                    if let ModuleName::Ident(id) = &local {
2566                        self.pending_exports.push((id.name.clone(), id.span));
2567                    }
2568                }
2569                specifiers.push(ExportSpecifier {
2570                    local,
2571                    exported,
2572                    span: self.span_from(spec_start),
2573                });
2574                if !self.eat_punct(Punct::Comma)? {
2575                    break;
2576                }
2577            }
2578            self.expect_punct(Punct::RBrace)?;
2579            let mut attributes = Vec::new();
2580            if self.eat_contextual("from")? {
2581                let TokenKind::String(value) = self.current.kind.clone() else {
2582                    return Err(self.error("expecting a module name string"));
2583                };
2584                self.bump()?;
2585                source = Some(value);
2586                attributes = self.parse_import_attributes()?;
2587            }
2588            self.semicolon()?;
2589            let span = self.span_from(start);
2590            return Ok(Stmt::new(
2591                StmtKind::Export(Box::new(ExportDecl {
2592                    kind: ExportKind::Named {
2593                        specifiers,
2594                        source,
2595                        attributes,
2596                    },
2597                    span,
2598                })),
2599                span,
2600            ));
2601        }
2602        Err(self.unexpected())
2603    }
2604
2605    // -- patterns from expressions ----------------------------------------
2606
2607    fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
2608        self.expr_to_pattern_inner(expr, kind, false)
2609    }
2610
2611    fn expr_to_pattern_inner(
2612        &mut self,
2613        expr: Expr,
2614        kind: TargetKind,
2615        nested: bool,
2616    ) -> Result<Pattern> {
2617        let span = expr.span;
2618        match expr.kind {
2619            ExprKind::Ident(ident) => {
2620                if kind == TargetKind::Binding {
2621                    self.check_binding_name(&ident.name, ident.span)?;
2622                } else {
2623                    self.check_identifier(&ident.name, ident.span)?;
2624                    if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2625                        return Err(self.error_at(
2626                            format!("invalid assignment to '{}' in strict mode", ident.name),
2627                            ident.span,
2628                        ));
2629                    }
2630                }
2631                Ok(Pattern::new(PatternKind::Ident(ident), span))
2632            }
2633            ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
2634            ExprKind::Array { elements } => {
2635                let mut out = Vec::new();
2636                let mut rest = None;
2637                let count = elements.len();
2638                for (index, element) in elements.into_iter().enumerate() {
2639                    match element {
2640                        None => out.push(None),
2641                        Some(ArrayElement::Expr(expr)) => {
2642                            let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
2643                            out.push(Some(PatternElement::Pattern(pattern)));
2644                        }
2645                        Some(ArrayElement::Spread(expr)) => {
2646                            if index + 1 != count {
2647                                return Err(self.error_at("rest element must be last", expr.span));
2648                            }
2649                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2650                        }
2651                    }
2652                }
2653                Ok(Pattern::new(
2654                    PatternKind::Array {
2655                        elements: out,
2656                        rest,
2657                    },
2658                    span,
2659                ))
2660            }
2661            ExprKind::Object(properties) => {
2662                self.cover_inits
2663                    .retain(|cover| !span_contains(span, *cover));
2664                let mut out = Vec::new();
2665                let mut rest = None;
2666                let count = properties.len();
2667                for (index, property) in properties.into_iter().enumerate() {
2668                    match property {
2669                        ObjectProperty::Spread(expr) => {
2670                            if index + 1 != count {
2671                                return Err(self.error_at("rest element must be last", expr.span));
2672                            }
2673                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2674                        }
2675                        ObjectProperty::Property {
2676                            key,
2677                            value,
2678                            kind: _,
2679                            shorthand,
2680                            span,
2681                        } => {
2682                            let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
2683                            out.push(Some(PatternElement::Property {
2684                                key,
2685                                value: pattern,
2686                                shorthand,
2687                                span,
2688                            }));
2689                        }
2690                    }
2691                }
2692                Ok(Pattern::new(
2693                    PatternKind::Object {
2694                        properties: out,
2695                        rest,
2696                    },
2697                    span,
2698                ))
2699            }
2700            ExprKind::Assign { op, target, value } if op.is_simple() => {
2701                // `{a = 1}` inside a pattern: the target must itself be a pattern.
2702                let target = match target.kind {
2703                    PatternKind::Ident(ident) => {
2704                        Pattern::new(PatternKind::Ident(ident), target.span)
2705                    }
2706                    other => {
2707                        let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
2708                        self.expr_to_pattern_inner(expr, kind, nested)?
2709                    }
2710                };
2711                Ok(Pattern::new(
2712                    PatternKind::Assign {
2713                        target: Box::new(target),
2714                        default: value,
2715                    },
2716                    span,
2717                ))
2718            }
2719            ExprKind::Member {
2720                object,
2721                property,
2722                optional,
2723            } => {
2724                if kind == TargetKind::Binding {
2725                    return Err(self.error_at("invalid binding pattern", span));
2726                }
2727                if optional {
2728                    return Err(self.error_at("invalid assignment target", span));
2729                }
2730                let op_pos = expr.op_pos;
2731                Ok(Pattern::new(
2732                    PatternKind::Member(Box::new(MemberPattern {
2733                        object,
2734                        property,
2735                        span,
2736                        op_pos,
2737                    })),
2738                    span,
2739                ))
2740            }
2741            ExprKind::OptionalChain(_) => {
2742                Err(self.error_at("invalid assignment left-hand side", span))
2743            }
2744            // QuickJS reports `a() = 1` at run time (it evaluates the callee
2745            // first, then rejects the reference) but rejects the same thing
2746            // inside a destructuring pattern at parse time. Every other
2747            // non-assignable expression is rejected here.
2748            other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
2749                Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
2750            ),
2751            _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
2752            _ => Err(self.error_at("invalid destructuring target", span)),
2753        }
2754    }
2755
2756    fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
2757        // Array and object literals wrap their spread elements, so the target is
2758        // one level in.
2759        let expr = match expr.kind {
2760            ExprKind::Spread(inner) => *inner,
2761            other => Expr::new(other, expr.span),
2762        };
2763        if kind == TargetKind::Binding {
2764            return Ok(RestElement::Pattern(
2765                self.expr_to_pattern_inner(expr, kind, true)?,
2766            ));
2767        }
2768        match &expr.kind {
2769            ExprKind::Member { optional, .. } => {
2770                if *optional {
2771                    return Err(self.error_at("invalid assignment target", expr.span));
2772                }
2773                match self.expr_to_pattern_inner(expr, kind, true)?.kind {
2774                    PatternKind::Member(member) => Ok(RestElement::Member(member)),
2775                    _ => unreachable!("member expressions convert to member patterns"),
2776                }
2777            }
2778            _ => Ok(RestElement::Pattern(
2779                self.expr_to_pattern_inner(expr, kind, true)?,
2780            )),
2781        }
2782    }
2783
2784    // -- expressions -------------------------------------------------------
2785
2786    /// `Expression` (comma separated).
2787    fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
2788        self.enter()?;
2789        let result = self.parse_expression_unguarded(allow_in);
2790        self.leave();
2791        result
2792    }
2793
2794    fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
2795        let start = self.current.span.start;
2796        let first = self.parse_assignment(allow_in)?;
2797        if !self.at_punct(Punct::Comma) {
2798            return Ok(first);
2799        }
2800        let mut items = vec![first];
2801        while self.eat_punct(Punct::Comma)? {
2802            items.push(self.parse_assignment(allow_in)?);
2803        }
2804        Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
2805    }
2806
2807    fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
2808        let start = self.current.span.start;
2809
2810        // `yield` in a generator.
2811        if self.ctx.in_generator && self.at_ident("yield") {
2812            return self.parse_yield(allow_in);
2813        }
2814
2815        let lhs = match self.try_parse_arrow(allow_in)? {
2816            Some(arrow) => return Ok(arrow),
2817            None => self.parse_conditional(allow_in)?,
2818        };
2819
2820        if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
2821            let op_pos = self.current.span.start;
2822            let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
2823            self.bump()?;
2824            let value = self.parse_assignment(allow_in)?;
2825            return Ok(Expr::at_operator(
2826                ExprKind::Assign {
2827                    op,
2828                    target: Box::new(target),
2829                    value: Box::new(value),
2830                },
2831                self.span_from(start),
2832                op_pos,
2833            ));
2834        }
2835        let _ = start;
2836        Ok(lhs)
2837    }
2838
2839    fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
2840        let start = self.current.span.start;
2841        self.bump()?; // yield
2842        let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
2843            self.bump()?;
2844            true
2845        } else {
2846            false
2847        };
2848        let argument = if delegate {
2849            Some(Box::new(self.parse_assignment(allow_in)?))
2850        } else if self.current.newline_before
2851            || self.at_punct(Punct::RParen)
2852            || self.at_punct(Punct::RBracket)
2853            || self.at_punct(Punct::RBrace)
2854            || self.at_punct(Punct::Comma)
2855            || self.at_punct(Punct::Semicolon)
2856            || self.at_punct(Punct::Colon)
2857            || self.current.is_eof()
2858        {
2859            None
2860        } else {
2861            Some(Box::new(self.parse_assignment(allow_in)?))
2862        };
2863        Ok(Expr::new(
2864            ExprKind::Yield { argument, delegate },
2865            self.span_from(start),
2866        ))
2867    }
2868
2869    fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
2870        let starts_paren = self.at_punct(Punct::LParen);
2871        let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
2872        if !starts_paren && !starts_ident {
2873            return Ok(None);
2874        }
2875        // `(` could be a parenthesised expression instead of a parameter list.
2876        // Scanning ahead for the matching `)` and looking for `=>` avoids the
2877        // speculative parse (and its stack cost) in the common case.
2878        if starts_paren && !self.arrow_follows_paren()? {
2879            return Ok(None);
2880        }
2881        let snapshot = self.snapshot();
2882        let head = match self.parse_arrow_head() {
2883            Ok(head) => head,
2884            Err(_) => {
2885                self.restore(snapshot);
2886                return Ok(None);
2887            }
2888        };
2889        let Some(head) = head else {
2890            self.restore(snapshot);
2891            return Ok(None);
2892        };
2893        // Committed: `=>` has been consumed, so errors from here on are real.
2894        // Arrow parameter lists may never repeat a name, in any mode.
2895        {
2896            let mut seen: Vec<String> = Vec::new();
2897            for param in &head.params {
2898                let mut names = Vec::new();
2899                param.bound_names(&mut names);
2900                for name in names {
2901                    if seen.contains(&name.name) {
2902                        return Err(self.error_at(
2903                            format!(
2904                                "duplicate argument names not allowed in this context ('{}')",
2905                                name.name
2906                            ),
2907                            name.span,
2908                        ));
2909                    }
2910                    seen.push(name.name);
2911                }
2912            }
2913        }
2914        let saved_ctx = self.ctx;
2915        let saved_loop = self.loop_depth;
2916        let saved_switch = self.switch_depth;
2917        let saved_labels = std::mem::take(&mut self.labels);
2918        let saved_top = self.top_level;
2919        self.ctx = FnCtx {
2920            in_function: true,
2921            in_generator: false,
2922            in_async: head.is_async,
2923            in_method: saved_ctx.in_method,
2924            in_derived_constructor: saved_ctx.in_derived_constructor,
2925        };
2926        self.loop_depth = 0;
2927        self.switch_depth = 0;
2928        self.top_level = false;
2929        let body_start = self.current.span.start;
2930        let (body, strict) = if self.at_punct(Punct::LBrace) {
2931            let (block, strict) = self.parse_arrow_block(&head.params)?;
2932            (block, (self.prev_end, strict))
2933        } else {
2934            let expr = self.parse_assignment(allow_in)?;
2935            let end = expr.span.end;
2936            // An expression body has no directive prologue, so it inherits.
2937            let strict = self.strict;
2938            (FunctionBody::Expr(Box::new(expr)), (end, strict))
2939        };
2940        self.ctx = saved_ctx;
2941        self.loop_depth = saved_loop;
2942        self.switch_depth = saved_switch;
2943        self.labels = saved_labels;
2944        self.top_level = saved_top;
2945        let _ = body_start;
2946        let (body, (end, strict)) = (body, strict);
2947        let span = Span::new(head.span.start, end);
2948        Ok(Some(Expr::new(
2949            ExprKind::Arrow(Box::new(Function {
2950                name: None,
2951                params: head.params,
2952                body,
2953                is_async: head.is_async,
2954                is_generator: false,
2955                strict,
2956                is_arrow: true,
2957                span,
2958                params_span: head.params_span,
2959            })),
2960            span,
2961        )))
2962    }
2963
2964    /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
2965    fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
2966        // Like a function body: the arrow's own directive governs the arrow, and the
2967        // enclosing scope's mode is restored afterwards.
2968        let saved_strict = self.strict;
2969        self.expect_punct(Punct::LBrace)?;
2970        self.push_scope(Scope::function(simple_parameter_names(params)));
2971        let result = (|| -> Result<Vec<Stmt>> {
2972            let mut body = Vec::new();
2973            let mut prologue = true;
2974            while !self.at_punct(Punct::RBrace) {
2975                if self.current.is_eof() {
2976                    return Err(self.unexpected());
2977                }
2978                let stmt = self.parse_statement_list_item()?;
2979                if prologue {
2980                    match self.directive_value(&stmt) {
2981                        Some(directive) if directive == "use strict" => self.enter_strict()?,
2982                        Some(_) => {}
2983                        None => prologue = false,
2984                    }
2985                }
2986                body.push(stmt);
2987            }
2988            Ok(body)
2989        })();
2990        self.pop_scope();
2991        let body_strict = self.strict;
2992        self.strict = saved_strict;
2993        self.lexer.set_strict(saved_strict);
2994        let body = result?;
2995        self.bump()?;
2996        Ok((FunctionBody::Block(body), body_strict))
2997    }
2998
2999    /// Whether the parenthesis at the current token is the parameter list of an
3000    /// arrow function, i.e. the matching `)` is followed by `=>`.
3001    ///
3002    /// This is a plain token walk with a bracket counter: no recursion, so it
3003    /// costs a clone of the lexer and nothing else.
3004    fn arrow_follows_paren(&self) -> Result<bool> {
3005        let mut lexer = self.lexer.clone();
3006        // The opening `(` was already consumed by the caller.
3007        let mut depth = 1usize;
3008        loop {
3009            let token = lexer.next_token()?;
3010            match token.kind {
3011                TokenKind::Eof => return Ok(false),
3012                TokenKind::Punct(Punct::LParen)
3013                | TokenKind::Punct(Punct::LBracket)
3014                | TokenKind::Punct(Punct::LBrace) => depth += 1,
3015                TokenKind::Punct(Punct::RParen)
3016                | TokenKind::Punct(Punct::RBracket)
3017                | TokenKind::Punct(Punct::RBrace) => {
3018                    if depth == 0 {
3019                        // Unbalanced input: the caller reports it.
3020                        return Ok(false);
3021                    }
3022                    depth -= 1;
3023                    if depth == 0 {
3024                        // The current token is the opening `(`, so the matching
3025                        // `)` is the token that brought us back to zero.
3026                        let next = lexer.next_token()?;
3027                        return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3028                            && !next.newline_before);
3029                    }
3030                }
3031                _ => {}
3032            }
3033        }
3034    }
3035
3036    /// Speculatively parse an arrow head, consuming `=>` on success.
3037    fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3038        let start = self.current.span.start;
3039        let mut is_async = false;
3040        if self.at_ident("async") {
3041            let peek = self.peek()?;
3042            if peek.newline_before {
3043                return Ok(None);
3044            }
3045            let plausible =
3046                matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3047            if !plausible {
3048                return Ok(None);
3049            }
3050            self.bump()?;
3051            is_async = true;
3052        }
3053        let params_start = self.current.span.start;
3054        let params = if self.at_punct(Punct::LParen) {
3055            self.parse_formal_parameters()?
3056        } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3057            let ident = self.expect_ident()?;
3058            vec![Pattern::new(
3059                PatternKind::Ident(ident),
3060                self.span_from(params_start),
3061            )]
3062        } else {
3063            return Ok(None);
3064        };
3065        let params_span = self.span_from(params_start);
3066        if !self.at_punct(Punct::Arrow) || self.current.newline_before {
3067            return Ok(None);
3068        }
3069        self.bump()?; // =>
3070        Ok(Some(ArrowHead {
3071            params,
3072            is_async,
3073            span: self.span_from(start),
3074            params_span,
3075        }))
3076    }
3077
3078    fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
3079        let start = self.current.span.start;
3080        let test = self.parse_binary(allow_in, 0)?;
3081        if !self.at_punct(Punct::Question) {
3082            return Ok(test);
3083        }
3084        self.bump()?;
3085        let consequent = self.parse_assignment(true)?;
3086        self.expect_punct(Punct::Colon)?;
3087        let alternate = self.parse_assignment(allow_in)?;
3088        Ok(Expr::new(
3089            ExprKind::Conditional {
3090                test: Box::new(test),
3091                cons: Box::new(consequent),
3092                alt: Box::new(alternate),
3093            },
3094            self.span_from(start),
3095        ))
3096    }
3097
3098    fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
3099        let start = self.current.span.start;
3100        let mut lhs = self.parse_unary()?;
3101        while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
3102            if prec < min_prec {
3103                break;
3104            }
3105            let op_pos = self.current.span.start;
3106            self.bump()?;
3107            let next_min = if op.is_right_associative() {
3108                prec
3109            } else {
3110                prec + 1
3111            };
3112            let rhs = self.parse_binary(allow_in, next_min)?;
3113            lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
3114        }
3115        Ok(lhs)
3116    }
3117
3118    /// Unary and postfix operators. `in` is handled by the binary layer, so no
3119    /// `allow_in` flag is needed here.
3120    fn parse_unary(&mut self) -> Result<Expr> {
3121        let start = self.current.span.start;
3122        // Unary operators.
3123        let unary = match &self.current.kind {
3124            TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
3125            TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
3126            TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
3127            TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
3128            TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
3129            TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
3130            TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
3131            _ => None,
3132        };
3133        if let Some(op) = unary {
3134            let op_pos = self.current.span.start;
3135            self.bump()?;
3136            let argument = self.parse_unary()?;
3137            if op == UnaryOp::Delete && self.strict {
3138                if let ExprKind::Ident(ident) = &argument.unparen().kind {
3139                    return Err(
3140                        self.error_at("cannot delete a variable in strict mode", ident.span)
3141                    );
3142                }
3143            }
3144            let expr = Expr::at_operator(
3145                ExprKind::Unary {
3146                    op,
3147                    argument: Box::new(argument),
3148                },
3149                self.span_from(start),
3150                op_pos,
3151            );
3152            if self.at_punct(Punct::StarStar) {
3153                return Err(self.error(
3154                    "unexpected token '**': a unary expression may not be the base of '**'",
3155                ));
3156            }
3157            return Ok(expr);
3158        }
3159        // Prefix increment/decrement.
3160        if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
3161            let op_pos = self.current.span.start;
3162            let op = if self.at_punct(Punct::PlusPlus) {
3163                UpdateOp::Increment
3164            } else {
3165                UpdateOp::Decrement
3166            };
3167            self.bump()?;
3168            let argument = self.parse_unary()?;
3169            self.check_simple_target(&argument)?;
3170            return Ok(Expr::at_operator(
3171                ExprKind::Update {
3172                    op,
3173                    argument: Box::new(argument),
3174                    prefix: true,
3175                },
3176                self.span_from(start),
3177                op_pos,
3178            ));
3179        }
3180        // `await` in async contexts (and at a module's top level).
3181        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
3182            let peek = self.peek()?;
3183            let starts_expression = !matches!(
3184                peek.kind,
3185                TokenKind::Punct(Punct::RParen)
3186                    | TokenKind::Punct(Punct::RBracket)
3187                    | TokenKind::Punct(Punct::RBrace)
3188                    | TokenKind::Punct(Punct::Comma)
3189                    | TokenKind::Punct(Punct::Semicolon)
3190                    | TokenKind::Punct(Punct::Colon)
3191                    | TokenKind::Punct(Punct::Eq)
3192                    | TokenKind::Punct(Punct::Arrow)
3193                    | TokenKind::Punct(Punct::Dot)
3194                    | TokenKind::Punct(Punct::QuestionDot)
3195                    | TokenKind::Punct(Punct::LBracket)
3196            ) && !peek.newline_before;
3197            if starts_expression {
3198                self.bump()?;
3199                let argument = self.parse_unary()?;
3200                return Ok(Expr::new(
3201                    ExprKind::Await(Box::new(argument)),
3202                    self.span_from(start),
3203                ));
3204            }
3205        }
3206        let expr = self.parse_lhs_expression()?;
3207        // Postfix increment/decrement (no line break allowed before the operator).
3208        let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3209            && !self.current.newline_before
3210        {
3211            let op_pos = self.current.span.start;
3212            let op = if self.at_punct(Punct::PlusPlus) {
3213                UpdateOp::Increment
3214            } else {
3215                UpdateOp::Decrement
3216            };
3217            self.check_simple_target(&expr)?;
3218            self.bump()?;
3219            Expr::at_operator(
3220                ExprKind::Update {
3221                    op,
3222                    argument: Box::new(expr),
3223                    prefix: false,
3224                },
3225                self.span_from(start),
3226                op_pos,
3227            )
3228        } else {
3229            expr
3230        };
3231        Ok(result)
3232    }
3233
3234    fn check_simple_target(&self, expr: &Expr) -> Result<()> {
3235        match &expr.unparen().kind {
3236            ExprKind::Ident(_) => Ok(()),
3237            ExprKind::Member {
3238                optional: false, ..
3239            } => Ok(()),
3240            _ => Err(self.error_at("invalid assignment left-hand side", expr.span)),
3241        }
3242    }
3243
3244    fn parse_lhs_expression(&mut self) -> Result<Expr> {
3245        let start = self.current.span.start;
3246        let mut expr = if self.at_keyword(Keyword::New) {
3247            self.parse_new_expression()?
3248        } else {
3249            self.parse_primary()?
3250        };
3251        let mut saw_optional = false;
3252        loop {
3253            // The position of the punctuator that follows the base expression: a
3254            // failed `.`, `[` or `(` is blamed on that token, not on the base.
3255            let op_pos = self.current.span.start;
3256            match self.current.kind.clone() {
3257                TokenKind::Punct(Punct::Dot) => {
3258                    self.bump()?;
3259                    let property = self.parse_member_property()?;
3260                    expr = Expr::at_operator(
3261                        ExprKind::Member {
3262                            object: Box::new(expr),
3263                            property,
3264                            optional: false,
3265                        },
3266                        self.span_from(start),
3267                        op_pos,
3268                    );
3269                }
3270                TokenKind::Punct(Punct::QuestionDot) => {
3271                    saw_optional = true;
3272                    self.bump()?;
3273                    if self.at_punct(Punct::LParen) {
3274                        let arguments = self.parse_arguments()?;
3275                        expr = Expr::at_operator(
3276                            ExprKind::Call {
3277                                callee: Box::new(expr),
3278                                arguments,
3279                                optional: true,
3280                            },
3281                            self.span_from(start),
3282                            op_pos,
3283                        );
3284                    } else if self.at_punct(Punct::LBracket) {
3285                        self.bump()?;
3286                        let index = self.parse_expression(true)?;
3287                        self.expect_punct(Punct::RBracket)?;
3288                        expr = Expr::at_operator(
3289                            ExprKind::Member {
3290                                object: Box::new(expr),
3291                                property: MemberProp::Computed(Box::new(index)),
3292                                optional: true,
3293                            },
3294                            self.span_from(start),
3295                            op_pos,
3296                        );
3297                    } else {
3298                        let property = self.parse_member_property()?;
3299                        expr = Expr::at_operator(
3300                            ExprKind::Member {
3301                                object: Box::new(expr),
3302                                property,
3303                                optional: true,
3304                            },
3305                            self.span_from(start),
3306                            op_pos,
3307                        );
3308                    }
3309                }
3310                TokenKind::Punct(Punct::LBracket) => {
3311                    self.bump()?;
3312                    let index = self.parse_expression(true)?;
3313                    self.expect_punct(Punct::RBracket)?;
3314                    expr = Expr::at_operator(
3315                        ExprKind::Member {
3316                            object: Box::new(expr),
3317                            property: MemberProp::Computed(Box::new(index)),
3318                            optional: false,
3319                        },
3320                        self.span_from(start),
3321                        op_pos,
3322                    );
3323                }
3324                TokenKind::Punct(Punct::LParen) => {
3325                    let arguments = self.parse_arguments()?;
3326                    expr = Expr::at_operator(
3327                        ExprKind::Call {
3328                            callee: Box::new(expr),
3329                            arguments,
3330                            optional: false,
3331                        },
3332                        self.span_from(start),
3333                        op_pos,
3334                    );
3335                }
3336                TokenKind::Template(_) => {
3337                    if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
3338                        return Err(
3339                            self.error("tagged template cannot be used in an optional chain")
3340                        );
3341                    }
3342                    let quasi = self.parse_template()?;
3343                    expr = Expr::new(
3344                        ExprKind::TaggedTemplate {
3345                            tag: Box::new(expr),
3346                            quasi: Box::new(quasi),
3347                        },
3348                        self.span_from(start),
3349                    );
3350                }
3351                _ => break,
3352            }
3353        }
3354        if saw_optional {
3355            expr = Expr::new(
3356                ExprKind::OptionalChain(Box::new(expr)),
3357                self.span_from(start),
3358            );
3359        }
3360        Ok(expr)
3361    }
3362
3363    fn parse_member_property(&mut self) -> Result<MemberProp> {
3364        if self.at_punct(Punct::Hash) {
3365            self.bump()?;
3366            let ident = self.expect_ident()?;
3367            if !self.private.iter().any(|env| env.contains(&ident.name)) {
3368                return Err(self.error_at(
3369                    format!(
3370                        "private field '#{}' must be declared in an enclosing class",
3371                        ident.name
3372                    ),
3373                    ident.span,
3374                ));
3375            }
3376            return Ok(MemberProp::Private(ident));
3377        }
3378        match self.current.kind.clone() {
3379            TokenKind::Ident(name) => {
3380                let span = self.current.span;
3381                self.bump()?;
3382                Ok(MemberProp::Ident(Ident { name, span }))
3383            }
3384            TokenKind::Keyword(kw) => {
3385                let span = self.current.span;
3386                self.bump()?;
3387                Ok(MemberProp::Ident(Ident {
3388                    name: kw.as_str().to_string(),
3389                    span,
3390                }))
3391            }
3392            _ => Err(self.error("expecting a property name")),
3393        }
3394    }
3395
3396    fn parse_new_expression(&mut self) -> Result<Expr> {
3397        let start = self.current.span.start;
3398        self.bump()?; // new
3399        if self.at_punct(Punct::Dot) {
3400            self.bump()?;
3401            if !self.at_ident("target") {
3402                return Err(self.error("expecting 'target' after 'new.'"));
3403            }
3404            if !self.ctx.in_function {
3405                return Err(self.error("invalid use of 'new.target' outside of a function"));
3406            }
3407            self.bump()?;
3408            return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
3409        }
3410        let mut callee = if self.at_keyword(Keyword::New) {
3411            self.parse_new_expression()?
3412        } else {
3413            self.parse_primary()?
3414        };
3415        // Member accesses bind tighter than `new`, calls do not.
3416        loop {
3417            let op_pos = self.current.span.start;
3418            match self.current.kind.clone() {
3419                TokenKind::Punct(Punct::Dot) => {
3420                    self.bump()?;
3421                    let property = self.parse_member_property()?;
3422                    callee = Expr::at_operator(
3423                        ExprKind::Member {
3424                            object: Box::new(callee),
3425                            property,
3426                            optional: false,
3427                        },
3428                        self.span_from(start),
3429                        op_pos,
3430                    );
3431                }
3432                TokenKind::Punct(Punct::LBracket) => {
3433                    self.bump()?;
3434                    let index = self.parse_expression(true)?;
3435                    self.expect_punct(Punct::RBracket)?;
3436                    callee = Expr::at_operator(
3437                        ExprKind::Member {
3438                            object: Box::new(callee),
3439                            property: MemberProp::Computed(Box::new(index)),
3440                            optional: false,
3441                        },
3442                        self.span_from(start),
3443                        op_pos,
3444                    );
3445                }
3446                TokenKind::Punct(Punct::QuestionDot) => {
3447                    return Err(self.error("new keyword cannot be used with an optional chain"));
3448                }
3449                _ => break,
3450            }
3451        }
3452        if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
3453            return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
3454        }
3455        let arguments = if self.at_punct(Punct::LParen) {
3456            // `new C(...)`: a failure in the constructor call is blamed on the `(`.
3457            let op_pos = self.current.span.start;
3458            let arguments = Some(self.parse_arguments()?);
3459            return Ok(Expr::at_operator(
3460                ExprKind::New {
3461                    callee: Box::new(callee),
3462                    arguments,
3463                },
3464                self.span_from(start),
3465                op_pos,
3466            ));
3467        } else {
3468            None
3469        };
3470        Ok(Expr::new(
3471            ExprKind::New {
3472                callee: Box::new(callee),
3473                arguments,
3474            },
3475            self.span_from(start),
3476        ))
3477    }
3478
3479    fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
3480        self.expect_punct(Punct::LParen)?;
3481        let mut arguments = Vec::new();
3482        while !self.at_punct(Punct::RParen) {
3483            if self.at_punct(Punct::Ellipsis) {
3484                let start = self.current.span.start;
3485                self.bump()?;
3486                let argument = self.parse_assignment(true)?;
3487                arguments.push(Expr::new(
3488                    ExprKind::Spread(Box::new(argument)),
3489                    self.span_from(start),
3490                ));
3491            } else {
3492                arguments.push(self.parse_assignment(true)?);
3493            }
3494            if !self.eat_punct(Punct::Comma)? {
3495                break;
3496            }
3497        }
3498        self.expect_punct(Punct::RParen)?;
3499        Ok(arguments)
3500    }
3501
3502    /// Primary expressions.
3503    ///
3504    /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
3505    /// so that this function — which sits on every nesting level — keeps a small
3506    /// stack frame. That directly raises how deeply a program may nest before
3507    /// the stack limit is hit (debug builds get ~4x more depth out of it).
3508    fn parse_primary(&mut self) -> Result<Expr> {
3509        let start = self.current.span.start;
3510        match self.current.kind.clone() {
3511            TokenKind::Number(NumberLiteral::Int(value)) => {
3512                self.bump()?;
3513                Ok(Expr::new(
3514                    ExprKind::Number(value as f64),
3515                    self.span_from(start),
3516                ))
3517            }
3518            TokenKind::Number(NumberLiteral::Float(value)) => {
3519                self.bump()?;
3520                Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
3521            }
3522            TokenKind::String(value) => {
3523                self.bump()?;
3524                Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
3525            }
3526            TokenKind::Ident(name) if name == "async" => {
3527                let peek = self.peek()?;
3528                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
3529                    && !peek.newline_before
3530                {
3531                    self.bump()?; // async
3532                    let func = self.parse_function(FunctionForm::Expression, true)?;
3533                    return Ok(Expr::new(
3534                        ExprKind::Function(Box::new(func)),
3535                        self.span_from(start),
3536                    ));
3537                }
3538                let span = self.current.span;
3539                self.bump()?;
3540                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3541            }
3542            TokenKind::Ident(name) => {
3543                let span = self.current.span;
3544                self.check_identifier(&name, span)?;
3545                self.bump()?;
3546                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3547            }
3548            TokenKind::Keyword(Keyword::This) => {
3549                self.bump()?;
3550                Ok(Expr::new(ExprKind::This, self.span_from(start)))
3551            }
3552            TokenKind::Keyword(Keyword::Null) => {
3553                self.bump()?;
3554                Ok(Expr::new(ExprKind::Null, self.span_from(start)))
3555            }
3556            TokenKind::Keyword(Keyword::True) => {
3557                self.bump()?;
3558                Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
3559            }
3560            TokenKind::Keyword(Keyword::False) => {
3561                self.bump()?;
3562                Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
3563            }
3564            TokenKind::Punct(Punct::LParen) => {
3565                self.bump()?;
3566                let inner = self.parse_expression(true)?;
3567                self.expect_punct(Punct::RParen)?;
3568                Ok(Expr::new(
3569                    ExprKind::Paren(Box::new(inner)),
3570                    self.span_from(start),
3571                ))
3572            }
3573            TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3574                self.parse_regex_literal(start)
3575            }
3576            _ => self.parse_primary_complex(start),
3577        }
3578    }
3579
3580    /// The primary expressions that need a lot of code: literals with structure,
3581    /// functions, classes, `import`, `super`, `#x in y`.
3582    #[inline(never)]
3583    fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
3584        match self.current.kind.clone() {
3585            TokenKind::BigInt(literal) => {
3586                self.bump()?;
3587                Ok(Expr::new(
3588                    ExprKind::BigInt {
3589                        digits: literal.digits,
3590                        radix: literal.radix,
3591                    },
3592                    self.span_from(start),
3593                ))
3594            }
3595            TokenKind::Template(_) => {
3596                let template = self.parse_template()?;
3597                Ok(Expr::new(
3598                    ExprKind::Template(Box::new(template)),
3599                    self.span_from(start),
3600                ))
3601            }
3602            TokenKind::Keyword(Keyword::Function) => {
3603                let func = self.parse_function(FunctionForm::Expression, false)?;
3604                Ok(Expr::new(
3605                    ExprKind::Function(Box::new(func)),
3606                    self.span_from(start),
3607                ))
3608            }
3609            TokenKind::Keyword(Keyword::Class) => {
3610                let class = self.parse_class(true)?;
3611                Ok(Expr::new(
3612                    ExprKind::Class(Box::new(class)),
3613                    self.span_from(start),
3614                ))
3615            }
3616            TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
3617            TokenKind::Keyword(Keyword::Super) => self.parse_super(),
3618            TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
3619            TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
3620            TokenKind::Punct(Punct::Hash) => self.parse_private_in(start),
3621            _ => Err(self.unexpected()),
3622        }
3623    }
3624
3625    /// `super` or `super(...)`.
3626    #[inline(never)]
3627    fn parse_super(&mut self) -> Result<Expr> {
3628        let start = self.current.span.start;
3629        self.bump()?;
3630        if self.at_punct(Punct::LParen) {
3631            if !self.ctx.in_derived_constructor {
3632                return Err(self.error_at(
3633                    "invalid use of 'super' in a non-derived constructor",
3634                    self.span_from(start),
3635                ));
3636            }
3637            let arguments = self.parse_arguments()?;
3638            return Ok(Expr::new(
3639                ExprKind::SuperCall(arguments),
3640                self.span_from(start),
3641            ));
3642        }
3643        if !self.ctx.in_method {
3644            return Err(self.error_at(
3645                "invalid use of 'super' outside of a method",
3646                self.span_from(start),
3647            ));
3648        }
3649        Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
3650    }
3651
3652    /// `#name in object`.
3653    #[inline(never)]
3654    fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
3655        self.bump()?;
3656        let ident = self.expect_ident()?;
3657        if !self.private.iter().any(|env| env.contains(&ident.name)) {
3658            return Err(self.error_at(
3659                format!(
3660                    "private field '#{}' must be declared in an enclosing class",
3661                    ident.name
3662                ),
3663                ident.span,
3664            ));
3665        }
3666        if !self.at_keyword(Keyword::In) {
3667            return Err(self.error("expecting 'in' after a private name"));
3668        }
3669        self.bump()?;
3670        let object = self.parse_unary()?;
3671        Ok(Expr::new(
3672            ExprKind::PrivateIn {
3673                name: ident,
3674                object: Box::new(object),
3675            },
3676            self.span_from(start),
3677        ))
3678    }
3679
3680    /// A regular expression literal: the lexer produced `/` (or `/=`), so the
3681    /// token has to be re-scanned from that position.
3682    #[inline(never)]
3683    fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
3684        let token = self.lexer.re_scan_regex(self.current.span.start)?;
3685        self.current = token;
3686        let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
3687            unreachable!("re_scan_regex returns a RegExp token")
3688        };
3689        self.bump()?;
3690        Ok(Expr::new(
3691            ExprKind::RegExp { pattern, flags },
3692            self.span_from(start),
3693        ))
3694    }
3695
3696    fn parse_import_expression(&mut self) -> Result<Expr> {
3697        let start = self.current.span.start;
3698        self.bump()?; // import
3699        if self.at_punct(Punct::Dot) {
3700            if !self.module {
3701                return Err(self.error_at(
3702                    "invalid use of 'import.meta' outside of a module",
3703                    self.span_from(start),
3704                ));
3705            }
3706            self.bump()?;
3707            if !self.at_ident("meta") {
3708                return Err(self.error("expecting 'meta' after 'import.'"));
3709            }
3710            self.bump()?;
3711            return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
3712        }
3713        if self.at_punct(Punct::LParen) {
3714            self.bump()?;
3715            let specifier = self.parse_assignment(true)?;
3716            if self.at_punct(Punct::Comma) {
3717                return Err(self.error("import() takes exactly one argument"));
3718            }
3719            self.expect_punct(Punct::RParen)?;
3720            return Ok(Expr::new(
3721                ExprKind::ImportCall(Box::new(specifier)),
3722                self.span_from(start),
3723            ));
3724        }
3725        Err(self.unexpected())
3726    }
3727
3728    fn parse_array_literal(&mut self) -> Result<Expr> {
3729        let start = self.current.span.start;
3730        self.expect_punct(Punct::LBracket)?;
3731        let mut elements = Vec::new();
3732        while !self.at_punct(Punct::RBracket) {
3733            if self.at_punct(Punct::Comma) {
3734                self.bump()?;
3735                elements.push(None);
3736                continue;
3737            }
3738            if self.at_punct(Punct::Ellipsis) {
3739                let spread_start = self.current.span.start;
3740                self.bump()?;
3741                let argument = self.parse_assignment(true)?;
3742                elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
3743                    ExprKind::Spread(Box::new(argument)),
3744                    self.span_from(spread_start),
3745                )))));
3746            } else {
3747                let expr = self.parse_assignment(true)?;
3748                elements.push(Some(ArrayElement::Expr(Box::new(expr))));
3749            }
3750            if !self.eat_punct(Punct::Comma)? {
3751                break;
3752            }
3753        }
3754        self.expect_punct(Punct::RBracket)?;
3755        Ok(Expr::new(
3756            ExprKind::Array { elements },
3757            self.span_from(start),
3758        ))
3759    }
3760
3761    fn parse_object_literal(&mut self) -> Result<Expr> {
3762        let start = self.current.span.start;
3763        self.expect_punct(Punct::LBrace)?;
3764        let mut properties: Vec<ObjectProperty> = Vec::new();
3765        let mut proto_count = 0;
3766        while !self.at_punct(Punct::RBrace) {
3767            let property_start = self.current.span.start;
3768            if self.at_punct(Punct::Ellipsis) {
3769                self.bump()?;
3770                let argument = self.parse_assignment(true)?;
3771                properties.push(ObjectProperty::Spread(Box::new(argument)));
3772            } else {
3773                let mut is_async = false;
3774                let mut is_generator = false;
3775                let mut accessor: Option<MethodKind> = None;
3776                if self.at_ident("async") {
3777                    let peek = self.peek()?;
3778                    let is_modifier = !matches!(
3779                        peek.kind,
3780                        TokenKind::Punct(Punct::LParen)
3781                            | TokenKind::Punct(Punct::Colon)
3782                            | TokenKind::Punct(Punct::Comma)
3783                            | TokenKind::Punct(Punct::RBrace)
3784                            | TokenKind::Punct(Punct::Eq)
3785                    ) && !peek.newline_before;
3786                    if is_modifier {
3787                        self.bump()?;
3788                        is_async = true;
3789                    }
3790                }
3791                if self.at_punct(Punct::Star) {
3792                    self.bump()?;
3793                    is_generator = true;
3794                }
3795                if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3796                    let is_get = self.at_ident("get");
3797                    let peek = self.peek()?;
3798                    if is_property_key_start(&peek.kind) {
3799                        self.bump()?;
3800                        accessor = Some(if is_get {
3801                            MethodKind::Get
3802                        } else {
3803                            MethodKind::Set
3804                        });
3805                    }
3806                }
3807                let key = self.parse_property_key()?;
3808                let is_computed = matches!(key, PropName::Computed(_));
3809                if self.at_punct(Punct::LParen) {
3810                    let saved = self.ctx;
3811                    self.ctx = FnCtx {
3812                        in_function: true,
3813                        in_generator: is_generator,
3814                        in_async: is_async,
3815                        in_method: true,
3816                        in_derived_constructor: false,
3817                    };
3818                    let saved_top = self.top_level;
3819                    self.top_level = false;
3820                    let func_result = (|| -> Result<Function> {
3821                        let params = self.parse_formal_parameters()?;
3822                        let (params, params_span, body, strict) =
3823                            self.parse_function_body(params, is_generator, is_async)?;
3824                        Ok(Function {
3825                            name: None,
3826                            params,
3827                            body,
3828                            is_async,
3829                            is_generator,
3830                            strict,
3831                            is_arrow: false,
3832                            span: self.span_from(property_start),
3833                            params_span,
3834                        })
3835                    })();
3836                    self.ctx = saved;
3837                    self.top_level = saved_top;
3838                    let func = func_result?;
3839                    let kind = match accessor {
3840                        Some(kind) => {
3841                            if is_generator || is_async {
3842                                return Err(self.error_at(
3843                                    "accessors may not be generators or async",
3844                                    func.span,
3845                                ));
3846                            }
3847                            if kind == MethodKind::Get && !func.params.is_empty() {
3848                                return Err(
3849                                    self.error_at("getter must have no arguments", func.span)
3850                                );
3851                            }
3852                            if kind == MethodKind::Set && func.params.len() != 1 {
3853                                return Err(self
3854                                    .error_at("setter must have exactly one argument", func.span));
3855                            }
3856                            match kind {
3857                                MethodKind::Get => PropertyKind::Get,
3858                                MethodKind::Set => PropertyKind::Set,
3859                                MethodKind::Method | MethodKind::Constructor => {
3860                                    PropertyKind::Method
3861                                }
3862                            }
3863                        }
3864                        None => PropertyKind::Method,
3865                    };
3866                    let span = self.span_from(property_start);
3867                    properties.push(ObjectProperty::Property {
3868                        key,
3869                        value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
3870                        kind,
3871                        shorthand: false,
3872                        span,
3873                    });
3874                } else if self.eat_punct(Punct::Colon)? {
3875                    let value = self.parse_assignment(true)?;
3876                    if !is_computed {
3877                        if let Some(PropKeyRef::Str("__proto__")) = key.static_name() {
3878                            proto_count += 1;
3879                            if proto_count > 1 {
3880                                return Err(self.error_at(
3881                                    "duplicate __proto__ fields are not allowed in object literals",
3882                                    self.span_from(property_start),
3883                                ));
3884                            }
3885                        }
3886                    }
3887                    properties.push(ObjectProperty::Property {
3888                        key,
3889                        value: Box::new(value),
3890                        kind: PropertyKind::Value,
3891                        shorthand: false,
3892                        span: self.span_from(property_start),
3893                    });
3894                } else {
3895                    // Shorthand `{a}` / `{a = 1}` (the latter only inside a
3896                    // destructuring pattern).
3897                    let PropName::Literal(PropKey::Str(name)) = &key else {
3898                        return Err(self.error("expecting ':' after a property name"));
3899                    };
3900                    let ident_span = self.span_from(property_start);
3901                    let ident = Ident {
3902                        name: name.clone(),
3903                        span: ident_span,
3904                    };
3905                    self.check_identifier(&ident.name, ident.span)?;
3906                    let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
3907                    if self.at_punct(Punct::Eq) {
3908                        // CoverInitializedName: only legal once the object turns
3909                        // out to be a destructuring pattern.
3910                        self.cover_inits.push(ident_span);
3911                        self.bump()?;
3912                        let default = self.parse_assignment(true)?;
3913                        let target = Pattern::new(PatternKind::Ident(ident), ident_span);
3914                        value = Expr::new(
3915                            ExprKind::Assign {
3916                                op: AssignOp::Assign,
3917                                target: Box::new(target),
3918                                value: Box::new(default),
3919                            },
3920                            ident_span,
3921                        );
3922                    }
3923                    properties.push(ObjectProperty::Property {
3924                        key,
3925                        value: Box::new(value),
3926                        kind: PropertyKind::Value,
3927                        shorthand: true,
3928                        span: ident_span,
3929                    });
3930                }
3931            }
3932            if !self.eat_punct(Punct::Comma)? {
3933                break;
3934            }
3935        }
3936        self.expect_punct(Punct::RBrace)?;
3937        Ok(Expr::new(
3938            ExprKind::Object(properties),
3939            self.span_from(start),
3940        ))
3941    }
3942
3943    fn parse_template(&mut self) -> Result<TemplateLiteral> {
3944        let mut quasis = Vec::new();
3945        let mut expressions = Vec::new();
3946        loop {
3947            let (cooked, raw, kind) = match self.current.kind.clone() {
3948                TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
3949                _ => return Err(self.error("expecting a template literal")),
3950            };
3951            let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
3952            quasis.push(TemplateChunk { cooked, raw, tail });
3953            if tail {
3954                self.bump()?;
3955                break;
3956            }
3957            self.bump()?; // move to the first token of the substitution
3958            let expr = self.parse_expression(true)?;
3959            expressions.push(expr);
3960            if !self.at_punct(Punct::RBrace) {
3961                return Err(self.error("expecting '}' in a template substitution"));
3962            }
3963            let brace = self.current.span.start;
3964            let token = self.lexer.re_scan_template_continue(brace)?;
3965            self.current = token;
3966        }
3967        Ok(TemplateLiteral {
3968            quasis,
3969            expressions,
3970        })
3971    }
3972}
3973
3974/// Which kind of function is being parsed (affects whether a name is required).
3975#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3976enum FunctionForm {
3977    Declaration,
3978    Expression,
3979}
3980
3981/// Names of the parameters that participate in declaration-conflict checks.
3982///
3983/// Engines only check *simple* (identifier) parameters against the body's
3984/// lexical declarations: `function f(a) { let a; }` is an early error, but
3985/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
3986/// deliberately follows the reference rather than ES2025 §10.2.1).
3987fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
3988    params
3989        .iter()
3990        .filter_map(|param| match &param.kind {
3991            PatternKind::Ident(id) => Some(id.name.clone()),
3992            _ => None,
3993        })
3994        .collect()
3995}
3996
3997/// Collect the names a top-level module item declares, for the exported-name
3998/// check.
3999fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
4000    match &stmt.kind {
4001        StmtKind::VarDecl(decl) => {
4002            for declarator in &decl.declarators {
4003                let mut names = Vec::new();
4004                declarator.target.bound_names(&mut names);
4005                out.extend(names.into_iter().map(|n| n.name));
4006            }
4007        }
4008        StmtKind::FuncDecl(func) => {
4009            if let Some(name) = &func.name {
4010                out.push(name.name.clone());
4011            }
4012        }
4013        StmtKind::ClassDecl(class) => {
4014            if let Some(name) = &class.name {
4015                out.push(name.name.clone());
4016            }
4017        }
4018        StmtKind::Import(decl) => {
4019            for specifier in &decl.specifiers {
4020                match specifier {
4021                    ImportSpecifier::Default(id) => out.push(id.name.clone()),
4022                    ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
4023                    ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
4024                }
4025            }
4026        }
4027        StmtKind::Export(decl) => match &decl.kind {
4028            ExportKind::Declaration(inner) => collect_module_binding(inner, out),
4029            ExportKind::Default(expr) => match &expr.unparen().kind {
4030                ExprKind::Function(func) => {
4031                    if let Some(name) = &func.name {
4032                        out.push(name.name.clone());
4033                    }
4034                }
4035                ExprKind::Class(class) => {
4036                    if let Some(name) = &class.name {
4037                        out.push(name.name.clone());
4038                    }
4039                }
4040                _ => {}
4041            },
4042            _ => {}
4043        },
4044        _ => {}
4045    }
4046}
4047
4048/// Whether `inner` is fully inside `outer` (byte offset comparison only).
4049fn span_contains(outer: Span, inner: Span) -> bool {
4050    inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
4051}
4052
4053fn is_property_key_start(kind: &TokenKind) -> bool {
4054    matches!(
4055        kind,
4056        TokenKind::Ident(_)
4057            | TokenKind::Keyword(_)
4058            | TokenKind::String(_)
4059            | TokenKind::Number(_)
4060            | TokenKind::Punct(Punct::LBracket)
4061            | TokenKind::Punct(Punct::Hash)
4062    )
4063}
4064
4065/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
4066#[derive(Debug, Clone, Copy)]
4067enum BinOp {
4068    Binary(BinaryOp),
4069    Logical(LogicalOp),
4070}
4071
4072impl BinOp {
4073    fn is_right_associative(self) -> bool {
4074        matches!(self, BinOp::Binary(BinaryOp::Pow))
4075    }
4076}
4077
4078fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
4079    use BinaryOp as B;
4080    use LogicalOp as L;
4081    let result = match kind {
4082        TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
4083        TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
4084        TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
4085        TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
4086        TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
4087        TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
4088        TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
4089        TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
4090        TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
4091        TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
4092        TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
4093        TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
4094        TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
4095        TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
4096        TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
4097        TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
4098        TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
4099        TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
4100        TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
4101        TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
4102        TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
4103        TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
4104        TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
4105        TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
4106        TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
4107        _ => return None,
4108    };
4109    Some(result)
4110}
4111
4112fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
4113    match op {
4114        BinOp::Binary(op) => Ok(Expr::at_operator(
4115            ExprKind::Binary {
4116                op,
4117                left: Box::new(left),
4118                right: Box::new(right),
4119            },
4120            span,
4121            op_pos,
4122        )),
4123        BinOp::Logical(op) => {
4124            // `??` may not be mixed with `&&`/`||` without parentheses.
4125            // A parenthesised operand is visibly a different production, so the
4126            // check must look at the raw node, not through `Paren`.
4127            let mixes = |expr: &Expr, op: LogicalOp| {
4128                matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
4129                    if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
4130            };
4131            if mixes(&left, op) || mixes(&right, op) {
4132                return Err(SyntaxError::new(
4133                    "cannot mix '??' with '&&' or '||' without parentheses",
4134                    span,
4135                ));
4136            }
4137            Ok(Expr::at_operator(
4138                ExprKind::Logical {
4139                    op,
4140                    left: Box::new(left),
4141                    right: Box::new(right),
4142                },
4143                span,
4144                op_pos,
4145            ))
4146        }
4147    }
4148}
4149
4150/// Rebuild an expression from a pattern (used when a pattern has to go back
4151/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
4152fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
4153    match pattern.kind {
4154        PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
4155        PatternKind::Assign { target, default } => Expr::new(
4156            ExprKind::Assign {
4157                op: AssignOp::Assign,
4158                target,
4159                value: default,
4160            },
4161            span,
4162        ),
4163        PatternKind::Array { elements, rest } => {
4164            let mut out = Vec::new();
4165            for element in elements {
4166                match element {
4167                    Some(PatternElement::Pattern(pattern)) => {
4168                        let span = pattern.span;
4169                        out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
4170                            pattern, span,
4171                        )))));
4172                    }
4173                    Some(PatternElement::Property { .. }) | None => out.push(None),
4174                }
4175            }
4176            if let Some(rest) = rest {
4177                let RestElement::Pattern(pattern) = *rest else {
4178                    return Expr::new(ExprKind::Null, span);
4179                };
4180                let span = pattern.span;
4181                out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
4182                    pattern, span,
4183                )))));
4184            }
4185            Expr::new(ExprKind::Array { elements: out }, span)
4186        }
4187        _ => Expr::new(ExprKind::Null, span),
4188    }
4189}
4190
4191impl Pattern {
4192    /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
4193    /// this keeps call sites uniform with [`Expr::unparen`]).
4194    fn unparen_kind(&self) -> &PatternKind {
4195        &self.kind
4196    }
4197}