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            // `import(...)` and `import.meta` are *expressions*, so they are an ordinary
1047            // expression statement here. Only a declaration is restricted to the top
1048            // level of a module.
1049            let peek = self.peek()?;
1050            let expression = matches!(
1051                peek.kind,
1052                TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
1053            );
1054            if !expression {
1055                return Err(self.error("'import' can only appear at the top level of a module"));
1056            }
1057        }
1058        if self.at_keyword(Keyword::Export) {
1059            return Err(self.error("'export' can only appear at the top level of a module"));
1060        }
1061        // Labelled statement.
1062        if matches!(self.current.kind, TokenKind::Ident(_)) {
1063            let peek = self.peek()?;
1064            if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
1065                return self.parse_labeled();
1066            }
1067        }
1068        self.parse_expression_statement()
1069    }
1070
1071    fn parse_block(&mut self) -> Result<Vec<Stmt>> {
1072        self.expect_punct(Punct::LBrace)?;
1073        self.push_scope(Scope::block());
1074        let result = self.parse_block_body();
1075        self.pop_scope();
1076        let body = result?;
1077        self.bump()?; // }
1078        Ok(body)
1079    }
1080
1081    /// `{ … }` of a `catch` clause: parsed in the scope holding its parameter.
1082    fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
1083        self.expect_punct(Punct::LBrace)?;
1084        let body = self.parse_block_body()?;
1085        self.bump()?; // }
1086        Ok(body)
1087    }
1088
1089    fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
1090        let mut body = Vec::new();
1091        while !self.at_punct(Punct::RBrace) {
1092            if self.current.is_eof() {
1093                return Err(self.unexpected());
1094            }
1095            body.push(self.parse_statement_list_item()?);
1096        }
1097        Ok(body)
1098    }
1099
1100    fn parse_expression_statement(&mut self) -> Result<Stmt> {
1101        let start = self.current.span.start;
1102        let expr = self.parse_expression(true)?;
1103        self.semicolon()?;
1104        Ok(Stmt::new(
1105            StmtKind::Expr(Box::new(expr)),
1106            self.span_from(start),
1107        ))
1108    }
1109
1110    fn parse_if(&mut self) -> Result<Stmt> {
1111        let start = self.current.span.start;
1112        self.bump()?; // if
1113        self.expect_punct(Punct::LParen)?;
1114        let test = self.parse_expression(true)?;
1115        self.expect_punct(Punct::RParen)?;
1116        let cons = self.parse_statement()?;
1117        let alt = if self.eat_keyword(Keyword::Else)? {
1118            Some(Box::new(self.parse_statement()?))
1119        } else {
1120            None
1121        };
1122        Ok(Stmt::new(
1123            StmtKind::If {
1124                test: Box::new(test),
1125                cons: Box::new(cons),
1126                alt,
1127            },
1128            self.span_from(start),
1129        ))
1130    }
1131
1132    fn parse_do_while(&mut self) -> Result<Stmt> {
1133        let start = self.current.span.start;
1134        self.bump()?; // do
1135        self.loop_depth += 1;
1136        let body = self.parse_statement();
1137        self.loop_depth -= 1;
1138        let body = body?;
1139        if !self.eat_keyword(Keyword::While)? {
1140            return Err(self.unexpected());
1141        }
1142        self.expect_punct(Punct::LParen)?;
1143        let test = self.parse_expression(true)?;
1144        self.expect_punct(Punct::RParen)?;
1145        // `do … while (x)` allows a missing semicolon even without a newline.
1146        let _ = self.eat_punct(Punct::Semicolon)?;
1147        Ok(Stmt::new(
1148            StmtKind::DoWhile {
1149                body: Box::new(body),
1150                test: Box::new(test),
1151            },
1152            self.span_from(start),
1153        ))
1154    }
1155
1156    fn parse_while(&mut self) -> Result<Stmt> {
1157        let start = self.current.span.start;
1158        self.bump()?; // while
1159        self.expect_punct(Punct::LParen)?;
1160        let test = self.parse_expression(true)?;
1161        self.expect_punct(Punct::RParen)?;
1162        self.loop_depth += 1;
1163        let body = self.parse_statement();
1164        self.loop_depth -= 1;
1165        Ok(Stmt::new(
1166            StmtKind::While {
1167                test: Box::new(test),
1168                body: Box::new(body?),
1169            },
1170            self.span_from(start),
1171        ))
1172    }
1173
1174    fn parse_for(&mut self) -> Result<Stmt> {
1175        let start = self.current.span.start;
1176        self.bump()?; // for
1177        self.push_scope(Scope::block());
1178        let result = self.parse_for_inner(start);
1179        self.pop_scope();
1180        result
1181    }
1182
1183    fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1184        let mut is_await = false;
1185        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
1186            let peek = self.peek()?;
1187            if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1188                is_await = true;
1189                self.bump()?;
1190            }
1191        }
1192        self.expect_punct(Punct::LParen)?;
1193
1194        // `for (;;)`
1195        if self.at_punct(Punct::Semicolon) {
1196            self.bump()?;
1197            return self.parse_for_classic(start, None);
1198        }
1199
1200        // Declaration head.
1201        let decl_kind = if self.at_keyword(Keyword::Var) {
1202            Some(VarDeclKind::Var)
1203        } else if self.at_keyword(Keyword::Const) {
1204            Some(VarDeclKind::Const)
1205        } else if self.at_ident("let") && self.let_starts_declaration()? {
1206            Some(VarDeclKind::Let)
1207        } else if self.at_ident("using") && self.using_starts_for_head()? {
1208            Some(VarDeclKind::Using)
1209        } else if self.at_ident("await")
1210            && (self.ctx.in_async || self.module)
1211            && self.await_using_starts_for_head()?
1212        {
1213            self.bump()?; // await, leaving `using` as the keyword
1214            Some(VarDeclKind::AwaitUsing)
1215        } else {
1216            None
1217        };
1218        if let Some(kind) = decl_kind {
1219            let decl_start = self.current.span.start;
1220            let decl = self.parse_var_decl(kind, true, false)?;
1221            if self.at_for_head_keyword() {
1222                let is_of = self.at_contextual("of");
1223                if !is_of && decl.declarators.len() != 1 {
1224                    return Err(self.error_at(
1225                        "only one binding allowed in a for-in loop",
1226                        self.span_from(decl_start),
1227                    ));
1228                }
1229                if is_of && decl.declarators.len() != 1 {
1230                    return Err(self.error_at(
1231                        "only one binding allowed in a for-of loop",
1232                        self.span_from(decl_start),
1233                    ));
1234                }
1235                if let Some(declarator) = decl.declarators.first() {
1236                    if declarator.init.is_some() {
1237                        // `for (var x = 1 in y)` is legacy in sloppy mode only.
1238                        if is_of || kind.is_lexical() || self.strict {
1239                            return Err(self.error_at(
1240                                "for-in/of loop variable declaration may not have an initializer",
1241                                declarator.span,
1242                            ));
1243                        }
1244                    }
1245                }
1246                if is_await && !is_of {
1247                    return Err(self.error("for await is only valid with 'of'"));
1248                }
1249                self.bump()?; // in / of
1250                let right = self.parse_expression(true)?;
1251                self.expect_punct(Punct::RParen)?;
1252                self.loop_depth += 1;
1253                let body = self.parse_statement();
1254                self.loop_depth -= 1;
1255                let head = ForHead::VarDecl(decl);
1256                let span = self.span_from(start);
1257                return Ok(Stmt::new(
1258                    if is_of {
1259                        StmtKind::ForOf {
1260                            is_await,
1261                            left: head,
1262                            right: Box::new(right),
1263                            body: Box::new(body?),
1264                        }
1265                    } else {
1266                        StmtKind::ForIn {
1267                            left: head,
1268                            right: Box::new(right),
1269                            body: Box::new(body?),
1270                        }
1271                    },
1272                    span,
1273                ));
1274            }
1275            self.expect_punct(Punct::Semicolon)?;
1276            return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1277        }
1278
1279        // Expression head.
1280        let expr_start = self.current.span.start;
1281        let expr = self.parse_expression(false)?;
1282        if self.at_for_head_keyword() {
1283            let is_of = self.at_contextual("of");
1284            if is_await && !is_of {
1285                return Err(self.error("for await is only valid with 'of'"));
1286            }
1287            let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1288            self.bump()?; // in / of
1289            let right = self.parse_expression(true)?;
1290            self.expect_punct(Punct::RParen)?;
1291            self.loop_depth += 1;
1292            let body = self.parse_statement();
1293            self.loop_depth -= 1;
1294            let head = ForHead::Assign(Box::new(target));
1295            let span = self.span_from(start);
1296            return Ok(Stmt::new(
1297                if is_of {
1298                    StmtKind::ForOf {
1299                        is_await,
1300                        left: head,
1301                        right: Box::new(right),
1302                        body: Box::new(body?),
1303                    }
1304                } else {
1305                    StmtKind::ForIn {
1306                        left: head,
1307                        right: Box::new(right),
1308                        body: Box::new(body?),
1309                    }
1310                },
1311                span,
1312            ));
1313        }
1314        let _ = expr_start;
1315        self.expect_punct(Punct::Semicolon)?;
1316        self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1317    }
1318
1319    /// Whether the `for` head continues with `in` (a keyword) or `of` (a
1320    /// contextual keyword).
1321    fn at_for_head_keyword(&self) -> bool {
1322        self.at_keyword(Keyword::In) || self.at_contextual("of")
1323    }
1324
1325    fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1326        let test = if self.at_punct(Punct::Semicolon) {
1327            None
1328        } else {
1329            Some(Box::new(self.parse_expression(true)?))
1330        };
1331        self.expect_punct(Punct::Semicolon)?;
1332        let update = if self.at_punct(Punct::RParen) {
1333            None
1334        } else {
1335            Some(Box::new(self.parse_expression(true)?))
1336        };
1337        self.expect_punct(Punct::RParen)?;
1338        self.loop_depth += 1;
1339        let body = self.parse_statement();
1340        self.loop_depth -= 1;
1341        Ok(Stmt::new(
1342            StmtKind::For {
1343                init,
1344                test,
1345                update,
1346                body: Box::new(body?),
1347            },
1348            self.span_from(start),
1349        ))
1350    }
1351
1352    fn parse_switch(&mut self) -> Result<Stmt> {
1353        let start = self.current.span.start;
1354        self.bump()?; // switch
1355        self.expect_punct(Punct::LParen)?;
1356        let discriminant = self.parse_expression(true)?;
1357        self.expect_punct(Punct::RParen)?;
1358        self.expect_punct(Punct::LBrace)?;
1359        self.switch_depth += 1;
1360        self.push_scope(Scope::block());
1361        let mut cases = Vec::new();
1362        let mut seen_default = false;
1363        while !self.at_punct(Punct::RBrace) {
1364            if self.current.is_eof() {
1365                self.switch_depth -= 1;
1366                return Err(self.unexpected());
1367            }
1368            let case_start = self.current.span.start;
1369            let test = if self.eat_keyword(Keyword::Case)? {
1370                Some(Box::new(self.parse_expression(true)?))
1371            } else if self.eat_keyword(Keyword::Default)? {
1372                if seen_default {
1373                    self.switch_depth -= 1;
1374                    return Err(self.error("duplicate 'default' clause in switch statement"));
1375                }
1376                seen_default = true;
1377                None
1378            } else {
1379                self.switch_depth -= 1;
1380                return Err(self.unexpected());
1381            };
1382            self.expect_punct(Punct::Colon)?;
1383            let mut body = Vec::new();
1384            while !self.at_punct(Punct::RBrace)
1385                && !self.at_keyword(Keyword::Case)
1386                && !self.at_keyword(Keyword::Default)
1387            {
1388                if self.current.is_eof() {
1389                    self.switch_depth -= 1;
1390                    return Err(self.unexpected());
1391                }
1392                body.push(self.parse_statement_list_item()?);
1393            }
1394            cases.push(SwitchCase {
1395                test,
1396                body,
1397                span: self.span_from(case_start),
1398            });
1399        }
1400        self.switch_depth -= 1;
1401        self.bump()?; // }
1402        // The switch body's block scope has to be popped here. Leaving it pushed leaked one
1403        // scope per `switch` for the rest of the file, so everything after a switch was
1404        // declared into a *stale* scope: `function f(value){ switch(value){} } let value=9`
1405        // was rejected as "identifier 'value' has already been declared", and the `value`
1406        // it clashed with was the function's own parameter. That made the parser refuse
1407        // valid programs — and it never showed up on its own, only when a top-level `let`
1408        // happened to reuse a name used inside an earlier switch.
1409        self.pop_scope();
1410        Ok(Stmt::new(
1411            StmtKind::Switch {
1412                discriminant: Box::new(discriminant),
1413                cases,
1414            },
1415            self.span_from(start),
1416        ))
1417    }
1418
1419    fn parse_try(&mut self) -> Result<Stmt> {
1420        let start = self.current.span.start;
1421        self.bump()?; // try
1422        let block = self.parse_block()?;
1423        let mut handler = None;
1424        let mut finalizer = None;
1425        if self.at_keyword(Keyword::Catch) {
1426            let catch_start = self.current.span.start;
1427            self.bump()?;
1428            // The catch parameter and the body share one scope, so `catch (e) {
1429            // let e; }` is an early error. A *simple* parameter is exempt from
1430            // the `var` check (`catch (e) { var e; }` is legal), a destructured
1431            // one is not (`catch ({e}) { var e; }` is rejected) — this matches
1432            // the reference engine.
1433            let param = if self.eat_punct(Punct::LParen)? {
1434                let pattern = self.parse_binding_target()?;
1435                self.expect_punct(Punct::RParen)?;
1436                Some(pattern)
1437            } else {
1438                None
1439            };
1440            self.push_scope(Scope::block());
1441            let body = match &param {
1442                // A simple parameter shares the body's scope: `catch (e) { let e;
1443                // }` is an error, `catch (e) { var e; }` is not.
1444                Some(Pattern {
1445                    kind: PatternKind::Ident(id),
1446                    ..
1447                }) => {
1448                    if let Some(scope) = self.scopes.last_mut() {
1449                        scope.params.push(id.name.clone());
1450                    }
1451                    self.parse_catch_body()
1452                }
1453                // A destructuring parameter is declared lexically in the clause's
1454                // own scope, with the body nested inside it: `catch ({e}) { var
1455                // e; }` is an error (the `var` hoists past the binding) while
1456                // `catch ({e}) { let e; }` is not.
1457                Some(pattern) => {
1458                    self.declare_pattern(pattern, false)?;
1459                    self.parse_block()
1460                }
1461                None => self.parse_catch_body(),
1462            };
1463            self.pop_scope();
1464            let body = body?;
1465            handler = Some(CatchClause {
1466                param,
1467                body,
1468                span: self.span_from(catch_start),
1469            });
1470        }
1471        if self.eat_keyword(Keyword::Finally)? {
1472            finalizer = Some(self.parse_block()?);
1473        }
1474        if handler.is_none() && finalizer.is_none() {
1475            return Err(self.error("expecting catch or finally"));
1476        }
1477        Ok(Stmt::new(
1478            StmtKind::Try {
1479                block,
1480                handler,
1481                finalizer,
1482            },
1483            self.span_from(start),
1484        ))
1485    }
1486
1487    fn parse_return(&mut self) -> Result<Stmt> {
1488        let start = self.current.span.start;
1489        let span = self.current.span;
1490        if !self.ctx.in_function {
1491            return Err(self.error_at("invalid return statement outside of a function", span));
1492        }
1493        self.bump()?;
1494        let argument = if self.at_punct(Punct::Semicolon)
1495            || self.at_punct(Punct::RBrace)
1496            || self.current.is_eof()
1497            || self.current.newline_before
1498        {
1499            None
1500        } else {
1501            Some(Box::new(self.parse_expression(true)?))
1502        };
1503        self.semicolon()?;
1504        Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
1505    }
1506
1507    fn parse_throw(&mut self) -> Result<Stmt> {
1508        let start = self.current.span.start;
1509        self.bump()?; // throw
1510        if self.current.newline_before {
1511            return Err(self.error("line terminator not allowed after 'throw'"));
1512        }
1513        let argument = self.parse_expression(true)?;
1514        self.semicolon()?;
1515        Ok(Stmt::new(
1516            StmtKind::Throw(Box::new(argument)),
1517            self.span_from(start),
1518        ))
1519    }
1520
1521    fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
1522        let start = self.current.span.start;
1523        let keyword_span = self.current.span;
1524        self.bump()?;
1525        let label = if matches!(self.current.kind, TokenKind::Ident(_))
1526            && !self.current.newline_before
1527        {
1528            let ident = self.expect_ident()?;
1529            let found = self.labels.iter().rev().find(|l| l.name == ident.name);
1530            match found {
1531                None => {
1532                    return Err(
1533                        self.error_at(format!("label '{}' not found", ident.name), ident.span)
1534                    );
1535                }
1536                Some(label) => {
1537                    if !is_break && label.kind != LabelKind::Iteration {
1538                        return Err(self.error_at(
1539                            format!("continue must be inside of a loop (label '{}')", ident.name),
1540                            ident.span,
1541                        ));
1542                    }
1543                }
1544            }
1545            Some(ident)
1546        } else {
1547            if !is_break && self.loop_depth == 0 {
1548                return Err(self.error_at("continue must be inside of a loop", keyword_span));
1549            }
1550            if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
1551            {
1552                return Err(self.error_at("break must be inside of a loop or switch", keyword_span));
1553            }
1554            None
1555        };
1556        self.semicolon()?;
1557        Ok(Stmt::new(
1558            if is_break {
1559                StmtKind::Break(label)
1560            } else {
1561                StmtKind::Continue(label)
1562            },
1563            self.span_from(start),
1564        ))
1565    }
1566
1567    fn parse_with(&mut self) -> Result<Stmt> {
1568        let start = self.current.span.start;
1569        let span = self.current.span;
1570        if self.strict {
1571            return Err(self.error_at("invalid 'with' statement in strict mode", span));
1572        }
1573        self.bump()?; // with
1574        self.expect_punct(Punct::LParen)?;
1575        let object = self.parse_expression(true)?;
1576        self.expect_punct(Punct::RParen)?;
1577        let body = self.parse_statement()?;
1578        Ok(Stmt::new(
1579            StmtKind::With {
1580                object: Box::new(object),
1581                body: Box::new(body),
1582            },
1583            self.span_from(start),
1584        ))
1585    }
1586
1587    fn parse_labeled(&mut self) -> Result<Stmt> {
1588        let start = self.current.span.start;
1589        let label = self.expect_ident()?;
1590        self.expect_punct(Punct::Colon)?;
1591        if self.labels.iter().any(|l| l.name == label.name) {
1592            return Err(self.error_at(
1593                format!("label '{}' already declared", label.name),
1594                label.span,
1595            ));
1596        }
1597        let kind = if self.at_keyword(Keyword::For)
1598            || self.at_keyword(Keyword::While)
1599            || self.at_keyword(Keyword::Do)
1600        {
1601            LabelKind::Iteration
1602        } else {
1603            LabelKind::Other
1604        };
1605        self.labels.push(Label {
1606            name: label.name.clone(),
1607            kind,
1608        });
1609        let body = self.parse_statement();
1610        self.labels.pop();
1611        Ok(Stmt::new(
1612            StmtKind::Labeled {
1613                label,
1614                body: Box::new(body?),
1615            },
1616            self.span_from(start),
1617        ))
1618    }
1619
1620    // -- declarations ------------------------------------------------------
1621
1622    fn parse_var_decl(
1623        &mut self,
1624        kind: VarDeclKind,
1625        in_for_head: bool,
1626        require_init: bool,
1627    ) -> Result<VarDecl> {
1628        let start = self.current.span.start;
1629        self.bump()?; // var / let / const / using
1630        self.parse_var_declarators(kind, in_for_head, require_init, start)
1631    }
1632
1633    /// A declaration whose leading keyword has already been consumed by the caller.
1634    ///
1635    /// `await using x = …` is written with two words, so the `await` is read first and only
1636    /// the `using` is left here.
1637    fn parse_var_decl_with_keyword(&mut self, kind: VarDeclKind, keyword: &str) -> Result<VarDecl> {
1638        let start = self.current.span.start;
1639        if !self.at_ident(keyword) {
1640            return Err(self.error(format!("expected '{keyword}'")));
1641        }
1642        self.bump()?;
1643        self.parse_var_declarators(kind, false, true, start)
1644    }
1645
1646    fn parse_var_declarators(
1647        &mut self,
1648        kind: VarDeclKind,
1649        in_for_head: bool,
1650        require_init: bool,
1651        start: Position,
1652    ) -> Result<VarDecl> {
1653        let mut declarators = Vec::new();
1654        loop {
1655            let declarator_start = self.current.span.start;
1656            let target = self.parse_binding_target()?;
1657            // `using` disposes a value, so it binds a name and nothing else: a pattern has
1658            // no single resource to dispose.
1659            if kind.is_using() && !matches!(target.unparen_kind(), PatternKind::Ident(_)) {
1660                return Err(self.error_at(
1661                    "binding patterns are not allowed in using declarations",
1662                    target.span,
1663                ));
1664            }
1665            let init = if self.eat_punct(Punct::Eq)? {
1666                // `for (var x = a in b;;)` must not parse `a in b` as the
1667                // initialiser: the head uses AssignmentExpression[~In].
1668                Some(Box::new(self.parse_assignment(!in_for_head)?))
1669            } else {
1670                None
1671            };
1672            if init.is_none() && require_init {
1673                if kind == VarDeclKind::Const {
1674                    return Err(self.error("missing initializer in const declaration"));
1675                }
1676                if kind.is_using() {
1677                    return Err(self.error("missing initializer in using declaration"));
1678                }
1679                if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
1680                    return Err(self.error_at(
1681                        "missing initializer in destructuring declaration",
1682                        target.span,
1683                    ));
1684                }
1685            }
1686            if kind.is_lexical() {
1687                let mut names = Vec::new();
1688                target.bound_names(&mut names);
1689                if let Some(name) = names.iter().find(|n| n.name == "let") {
1690                    return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
1691                }
1692            }
1693            self.declare_pattern(&target, !kind.is_lexical())?;
1694            declarators.push(Declarator {
1695                target,
1696                init,
1697                span: self.span_from(declarator_start),
1698            });
1699            if !self.eat_punct(Punct::Comma)? {
1700                break;
1701            }
1702        }
1703        Ok(VarDecl {
1704            kind,
1705            declarators,
1706            span: self.span_from(start),
1707        })
1708    }
1709
1710    /// A binding element: `target` or `target = default`. Used for parameters and
1711    /// for elements of array/object patterns.
1712    fn parse_binding_element(&mut self) -> Result<Pattern> {
1713        let pattern = self.parse_binding_target()?;
1714        if self.eat_punct(Punct::Eq)? {
1715            let start = pattern.span.start;
1716            let default = self.parse_assignment(self.allow_in)?;
1717            return Ok(Pattern::new(
1718                PatternKind::Assign {
1719                    target: Box::new(pattern),
1720                    default: Box::new(default),
1721                },
1722                self.span_from(start),
1723            ));
1724        }
1725        Ok(pattern)
1726    }
1727
1728    /// A binding target: `Ident`, `[ … ]` or `{ … }`, with no default value.
1729    /// Used for declarators, `catch` parameters, rest elements and `for` heads.
1730    fn parse_binding_target(&mut self) -> Result<Pattern> {
1731        self.enter()?;
1732        let result = self.parse_binding_target_unguarded();
1733        self.leave();
1734        result
1735    }
1736
1737    fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
1738        let start = self.current.span.start;
1739        if self.at_punct(Punct::LBracket) {
1740            return self.parse_array_pattern(start);
1741        }
1742        if self.at_punct(Punct::LBrace) {
1743            return self.parse_object_pattern(start);
1744        }
1745        let ident = self.expect_binding_ident()?;
1746        Ok(Pattern::new(
1747            PatternKind::Ident(ident),
1748            self.span_from(start),
1749        ))
1750    }
1751
1752    fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
1753        self.expect_punct(Punct::LBracket)?;
1754        let mut elements = Vec::new();
1755        let mut rest = None;
1756        loop {
1757            if self.at_punct(Punct::RBracket) {
1758                break;
1759            }
1760            if self.at_punct(Punct::Comma) {
1761                self.bump()?;
1762                elements.push(None);
1763                continue;
1764            }
1765            if self.at_punct(Punct::Ellipsis) {
1766                self.bump()?;
1767                let target = self.parse_binding_target()?;
1768                if self.at_punct(Punct::Comma) {
1769                    return Err(self.error("rest element must be last"));
1770                }
1771                rest = Some(Box::new(RestElement::Pattern(target)));
1772                break;
1773            }
1774            let element_start = self.current.span.start;
1775            let element = self.parse_binding_element()?;
1776            let span = self.span_from(element_start);
1777            elements.push(Some(PatternElement::Pattern(element)));
1778            let _ = span;
1779            if !self.eat_punct(Punct::Comma)? {
1780                break;
1781            }
1782        }
1783        self.expect_punct(Punct::RBracket)?;
1784        Ok(Pattern::new(
1785            PatternKind::Array { elements, rest },
1786            self.span_from(start),
1787        ))
1788    }
1789
1790    fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
1791        self.expect_punct(Punct::LBrace)?;
1792        let mut properties = Vec::new();
1793        let mut rest = None;
1794        loop {
1795            if self.at_punct(Punct::RBrace) {
1796                break;
1797            }
1798            if self.at_punct(Punct::Ellipsis) {
1799                self.bump()?;
1800                let target = self.parse_binding_target()?;
1801                rest = Some(Box::new(RestElement::Pattern(target)));
1802                if self.at_punct(Punct::Comma) {
1803                    return Err(self.error("rest element must be last"));
1804                }
1805                break;
1806            }
1807            let property_start = self.current.span.start;
1808            let key = self.parse_property_key()?;
1809            if self.eat_punct(Punct::Colon)? {
1810                let value = self.parse_binding_element()?;
1811                properties.push(Some(PatternElement::Property {
1812                    key,
1813                    value,
1814                    shorthand: false,
1815                    span: self.span_from(property_start),
1816                }));
1817            } else {
1818                let PropName::Literal(PropKey::Str(name)) = &key else {
1819                    return Err(
1820                        self.error("expecting ':' after a computed or numeric property key")
1821                    );
1822                };
1823                let span = self.span_from(property_start);
1824                let ident = Ident {
1825                    name: name.clone(),
1826                    span,
1827                };
1828                self.check_binding_name(&ident.name, ident.span)?;
1829                let mut value = Pattern::new(PatternKind::Ident(ident), span);
1830                if self.eat_punct(Punct::Eq)? {
1831                    let default = self.parse_assignment(self.allow_in)?;
1832                    value = Pattern::new(
1833                        PatternKind::Assign {
1834                            target: Box::new(value),
1835                            default: Box::new(default),
1836                        },
1837                        span,
1838                    );
1839                }
1840                properties.push(Some(PatternElement::Property {
1841                    key,
1842                    value,
1843                    shorthand: true,
1844                    span,
1845                }));
1846            }
1847            if !self.eat_punct(Punct::Comma)? {
1848                break;
1849            }
1850        }
1851        self.expect_punct(Punct::RBrace)?;
1852        Ok(Pattern::new(
1853            PatternKind::Object { properties, rest },
1854            self.span_from(start),
1855        ))
1856    }
1857
1858    /// A property key: identifier, string, number, computed or `#private`.
1859    fn parse_property_key(&mut self) -> Result<PropName> {
1860        match self.current.kind.clone() {
1861            TokenKind::Ident(name) => {
1862                self.bump()?;
1863                Ok(PropName::Literal(PropKey::Str(name)))
1864            }
1865            TokenKind::Keyword(kw) => {
1866                // Reserved words are valid property names (`{ if: 1 }`).
1867                self.bump()?;
1868                Ok(PropName::Literal(PropKey::Str(kw.as_str().to_string())))
1869            }
1870            TokenKind::String(value) => {
1871                self.bump()?;
1872                Ok(PropName::Literal(PropKey::Str(value)))
1873            }
1874            TokenKind::Number(NumberLiteral::Int(v)) => {
1875                self.bump()?;
1876                Ok(PropName::Literal(PropKey::Num(v as f64)))
1877            }
1878            TokenKind::Number(NumberLiteral::Float(v)) => {
1879                self.bump()?;
1880                Ok(PropName::Literal(PropKey::Num(v)))
1881            }
1882            TokenKind::BigInt(big) => Err(self.error(format!(
1883                "BigInt property keys are not supported ('{}n')",
1884                big.digits
1885            ))),
1886            TokenKind::Punct(Punct::LBracket) => {
1887                self.bump()?;
1888                let expr = self.parse_assignment(true)?;
1889                self.expect_punct(Punct::RBracket)?;
1890                Ok(PropName::Computed(Box::new(expr)))
1891            }
1892            TokenKind::Punct(Punct::Hash) => {
1893                self.bump()?;
1894                let ident = self.expect_ident()?;
1895                Ok(PropName::Private(ident))
1896            }
1897            _ => Err(self.error("expecting a property name")),
1898        }
1899    }
1900
1901    // -- functions ---------------------------------------------------------
1902
1903    fn parse_function(&mut self, form: FunctionForm, is_async: bool) -> Result<Function> {
1904        let start = self.current.span.start;
1905        self.bump()?; // function
1906        let is_generator = self.eat_punct(Punct::Star)?;
1907        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
1908            let ident = if form == FunctionForm::Declaration {
1909                self.expect_binding_ident()?
1910            } else {
1911                self.expect_ident()?
1912            };
1913            if is_generator && ident.name == "yield" {
1914                return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
1915            }
1916            if is_async && ident.name == "await" {
1917                return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
1918            }
1919            Some(ident)
1920        } else {
1921            if form == FunctionForm::Declaration {
1922                return Err(self.error("expecting a function name"));
1923            }
1924            None
1925        };
1926        let saved = self.ctx;
1927        self.ctx = FnCtx {
1928            in_function: true,
1929            in_generator: is_generator,
1930            in_async: is_async,
1931            in_method: false,
1932            in_derived_constructor: false,
1933        };
1934        let saved_top = self.top_level;
1935        self.top_level = false;
1936        // Strictness is per function: `function f(){ "use strict"; }` must leave the
1937        // code *after* it sloppy. Without this save the directive leaked outwards, the
1938        // enclosing script was compiled as strict, and a later `function g(){}` lost its
1939        // declaration status — `typeof g` then raised instead of answering, because an
1940        // implicit global is not a declaration.
1941        let params_result = self.parse_formal_parameters();
1942        let result = match params_result {
1943            Ok(params) => self.parse_function_body(params, is_generator, is_async),
1944            Err(err) => Err(err),
1945        };
1946        self.ctx = saved;
1947        self.top_level = saved_top;
1948        let (params, params_span, body, strict) = result?;
1949        Ok(Function {
1950            name,
1951            params,
1952            body,
1953            is_async,
1954            is_generator,
1955            strict,
1956            is_arrow: false,
1957            span: self.span_from(start),
1958            params_span,
1959        })
1960    }
1961
1962    fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
1963        self.expect_punct(Punct::LParen)?;
1964        let mut params = Vec::new();
1965        loop {
1966            if self.at_punct(Punct::RParen) {
1967                break;
1968            }
1969            if self.at_punct(Punct::Ellipsis) {
1970                self.bump()?;
1971                let target = self.parse_binding_target()?;
1972                if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
1973                    return Err(self.error_at("rest parameter may not have a default", target.span));
1974                }
1975                params.push(Pattern::new(
1976                    PatternKind::Rest(Box::new(target.clone())),
1977                    target.span,
1978                ));
1979                if self.at_punct(Punct::Comma) {
1980                    return Err(self.error("rest parameter must be last"));
1981                }
1982                break;
1983            }
1984            let param = self.parse_binding_element()?;
1985            self.check_parameter(&param)?;
1986            params.push(param);
1987            if !self.eat_punct(Punct::Comma)? {
1988                break;
1989            }
1990        }
1991        self.expect_punct(Punct::RParen)?;
1992        Ok(params)
1993    }
1994
1995    fn check_parameter(&self, param: &Pattern) -> Result<()> {
1996        match &param.kind {
1997            PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
1998            PatternKind::Assign { target, .. } => self.check_parameter(target),
1999            _ => Ok(()),
2000        }
2001    }
2002
2003    fn parse_function_body(
2004        &mut self,
2005        params: Vec<Pattern>,
2006        is_generator: bool,
2007        is_async: bool,
2008    ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2009        let params_span = self.prev_end;
2010        // Strictness is per function, so the body saves and restores it itself rather
2011        // than trusting every caller to do so: `function f(){ "use strict" }` must
2012        // leave the code after it sloppy, and the enclosing scope may well have been
2013        // strict too. The returned flag is the body's own mode.
2014        let saved_strict = self.strict;
2015        if !self.at_punct(Punct::LBrace) {
2016            return Err(self.unexpected());
2017        }
2018        let param_names = simple_parameter_names(&params);
2019        let simple_params = params
2020            .iter()
2021            .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2022        let mut body = Vec::new();
2023        let mut prologue = true;
2024        let mut strict_seen = false;
2025        self.bump()?; // {
2026        self.push_scope(Scope::function(param_names));
2027        while !self.at_punct(Punct::RBrace) {
2028            if self.current.is_eof() {
2029                return Err(self.unexpected());
2030            }
2031            let stmt = self.parse_statement_list_item()?;
2032            if prologue {
2033                match self.directive_value(&stmt) {
2034                    Some(directive) if directive == "use strict" => {
2035                        strict_seen = true;
2036                        self.enter_strict()?;
2037                    }
2038                    Some(_) => {}
2039                    None => prologue = false,
2040                }
2041            }
2042            body.push(stmt);
2043        }
2044        self.pop_scope();
2045        self.bump()?; // }
2046        // The body's own mode, still in force while the early errors below are
2047        // checked; the enclosing mode is restored once they are done.
2048        let body_strict = self.strict;
2049        if strict_seen && !simple_params {
2050            return Err(self.error_at(
2051                "'use strict' directive is not allowed with non-simple parameters",
2052                Span::new(params_span, params_span),
2053            ));
2054        }
2055        // Duplicate parameter names: always illegal for non-simple lists and in
2056        // strict mode; in sloppy simple lists they are allowed (last wins).
2057        if body_strict || !simple_params || is_generator || is_async {
2058            let mut seen: Vec<String> = Vec::new();
2059            for param in &params {
2060                let mut names = Vec::new();
2061                param.bound_names(&mut names);
2062                for name in names {
2063                    if seen.contains(&name.name) {
2064                        return Err(self.error_at(
2065                            format!("duplicate parameter name '{}'", name.name),
2066                            name.span,
2067                        ));
2068                    }
2069                    seen.push(name.name);
2070                }
2071            }
2072        }
2073        let params_span_value = Span::new(params_span, params_span);
2074        self.strict = saved_strict;
2075        self.lexer.set_strict(saved_strict);
2076        Ok((
2077            params,
2078            params_span_value,
2079            FunctionBody::Block(body),
2080            body_strict,
2081        ))
2082    }
2083
2084    // -- classes -----------------------------------------------------------
2085
2086    fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2087        let start = self.current.span.start;
2088        self.bump()?; // class
2089        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2090            if is_expression {
2091                Some(self.expect_ident()?)
2092            } else {
2093                Some(self.expect_binding_ident()?)
2094            }
2095        } else {
2096            if !is_expression {
2097                return Err(self.error("expecting a class name"));
2098            }
2099            None
2100        };
2101        let super_class = if self.eat_keyword(Keyword::Extends)? {
2102            Some(Box::new(self.parse_lhs_expression()?))
2103        } else {
2104            None
2105        };
2106        let has_super = super_class.is_some();
2107        self.private.push(PrivateEnv::default());
2108        self.expect_punct(Punct::LBrace)?;
2109        let mut elements = Vec::new();
2110        let mut seen_constructor = false;
2111        let result = (|| -> Result<()> {
2112            while !self.at_punct(Punct::RBrace) {
2113                if self.current.is_eof() {
2114                    return Err(self.unexpected());
2115                }
2116                if self.eat_punct(Punct::Semicolon)? {
2117                    continue;
2118                }
2119                elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2120            }
2121            Ok(())
2122        })();
2123        self.private.pop();
2124        result?;
2125        self.bump()?; // }
2126        Ok(Class {
2127            name,
2128            super_class,
2129            elements,
2130            span: self.span_from(start),
2131        })
2132    }
2133
2134    fn parse_class_element(
2135        &mut self,
2136        has_super: bool,
2137        seen_constructor: &mut bool,
2138    ) -> Result<ClassElement> {
2139        let start = self.current.span.start;
2140        let mut is_static = false;
2141        if self.at_ident("static") {
2142            let peek = self.peek()?;
2143            let is_modifier = !matches!(
2144                peek.kind,
2145                TokenKind::Punct(Punct::LParen)
2146                    | TokenKind::Punct(Punct::Eq)
2147                    | TokenKind::Punct(Punct::Semicolon)
2148                    | TokenKind::Punct(Punct::RBrace)
2149            );
2150            if is_modifier {
2151                if matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
2152                    self.bump()?; // static
2153                    let body = self.parse_block()?;
2154                    return Ok(ClassElement::StaticBlock {
2155                        body,
2156                        span: self.span_from(start),
2157                    });
2158                }
2159                self.bump()?; // static
2160                is_static = true;
2161                if self.at_punct(Punct::LBrace) {
2162                    let body = self.parse_block()?;
2163                    return Ok(ClassElement::StaticBlock {
2164                        body,
2165                        span: self.span_from(start),
2166                    });
2167                }
2168            }
2169        }
2170
2171        // Modifiers: async, get, set, *
2172        let mut is_async = false;
2173        let mut is_generator = false;
2174        let mut accessor: Option<MethodKind> = None;
2175        if self.at_ident("async") {
2176            let peek = self.peek()?;
2177            let is_modifier = !matches!(
2178                peek.kind,
2179                TokenKind::Punct(Punct::LParen)
2180                    | TokenKind::Punct(Punct::Eq)
2181                    | TokenKind::Punct(Punct::Semicolon)
2182                    | TokenKind::Punct(Punct::RBrace)
2183            ) && !peek.newline_before;
2184            if is_modifier {
2185                self.bump()?;
2186                is_async = true;
2187            }
2188        }
2189        if self.at_punct(Punct::Star) {
2190            self.bump()?;
2191            is_generator = true;
2192        }
2193        if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2194            let is_get = self.at_ident("get");
2195            let peek = self.peek()?;
2196            if is_property_key_start(&peek.kind) {
2197                self.bump()?;
2198                accessor = Some(if is_get {
2199                    MethodKind::Get
2200                } else {
2201                    MethodKind::Set
2202                });
2203            }
2204        }
2205        let key = self.parse_property_key()?;
2206
2207        // Private names must be registered (duplicates are early errors).
2208        if let PropName::Private(ident) = &key {
2209            if let Some(env) = self.private.last_mut() {
2210                if !env.declare(&ident.name, accessor) {
2211                    return Err(self.error_at(
2212                        format!("duplicate private name '#{}'", ident.name),
2213                        ident.span,
2214                    ));
2215                }
2216            }
2217        }
2218
2219        if self.at_punct(Punct::LParen) {
2220            let kind = match accessor {
2221                Some(kind) => kind,
2222                None => {
2223                    let is_constructor = !is_static
2224                        && !is_generator
2225                        && !is_async
2226                        && matches!(&key, PropName::Literal(PropKey::Str(s)) if s == "constructor");
2227                    if is_constructor {
2228                        if *seen_constructor {
2229                            return Err(self.error_at(
2230                                "property constructor appears more than once",
2231                                self.span_from(start),
2232                            ));
2233                        }
2234                        *seen_constructor = true;
2235                        MethodKind::Constructor
2236                    } else {
2237                        MethodKind::Method
2238                    }
2239                }
2240            };
2241            if kind == MethodKind::Constructor && (is_generator || is_async) {
2242                return Err(self.error("a constructor may not be a generator or async"));
2243            }
2244            let saved = self.ctx;
2245            self.ctx = FnCtx {
2246                in_function: true,
2247                in_generator: is_generator,
2248                in_async: is_async,
2249                in_method: true,
2250                in_derived_constructor: kind == MethodKind::Constructor && has_super,
2251            };
2252            let saved_top = self.top_level;
2253            self.top_level = false;
2254            let result = (|| -> Result<Function> {
2255                let params = self.parse_formal_parameters()?;
2256                let (params, params_span, body, strict) =
2257                    self.parse_function_body(params, is_generator, is_async)?;
2258                Ok(Function {
2259                    name: None,
2260                    params,
2261                    body,
2262                    is_async,
2263                    is_generator,
2264                    strict,
2265                    is_arrow: false,
2266                    span: self.span_from(start),
2267                    params_span,
2268                })
2269            })();
2270            self.ctx = saved;
2271            self.top_level = saved_top;
2272            let func = result?;
2273            if is_static {
2274                if let PropName::Literal(PropKey::Str(name)) = &key {
2275                    if name == "prototype" {
2276                        return Err(self.error_at("invalid method name 'prototype'", func.span));
2277                    }
2278                }
2279            }
2280            if kind == MethodKind::Get && !func.params.is_empty() {
2281                return Err(self.error_at("getter must have no arguments", func.span));
2282            }
2283            if kind == MethodKind::Set && func.params.len() != 1 {
2284                return Err(self.error_at("setter must have exactly one argument", func.span));
2285            }
2286            return Ok(ClassElement::Method {
2287                key,
2288                is_static,
2289                kind,
2290                func: Box::new(func),
2291                span: self.span_from(start),
2292            });
2293        }
2294
2295        // Field definition.
2296        if accessor.is_some() {
2297            return Err(self.error("expecting '(' after an accessor name"));
2298        }
2299        if let PropName::Literal(PropKey::Str(name)) = &key {
2300            if name == "constructor" && !is_static {
2301                return Err(self.error("classes may not have a field named 'constructor'"));
2302            }
2303            if name == "prototype" && is_static {
2304                return Err(self.error("classes may not have a static property named 'prototype'"));
2305            }
2306        }
2307        let value = if self.eat_punct(Punct::Eq)? {
2308            Some(Box::new(self.parse_assignment(true)?))
2309        } else {
2310            None
2311        };
2312        // Fields are terminated by `;`, `}` or a line break.
2313        self.semicolon()?;
2314        Ok(ClassElement::Field {
2315            key,
2316            is_static,
2317            value,
2318            span: self.span_from(start),
2319        })
2320    }
2321
2322    // -- modules -----------------------------------------------------------
2323
2324    fn parse_import_decl(&mut self) -> Result<Stmt> {
2325        let start = self.current.span.start;
2326        self.bump()?; // import
2327        let mut specifiers = Vec::new();
2328        if let TokenKind::String(source) = self.current.kind.clone() {
2329            self.bump()?;
2330            let attributes = self.parse_import_attributes()?;
2331            self.semicolon()?;
2332            return Ok(Stmt::new(
2333                StmtKind::Import(Box::new(ImportDecl {
2334                    specifiers,
2335                    source,
2336                    attributes,
2337                    span: self.span_from(start),
2338                })),
2339                self.span_from(start),
2340            ));
2341        }
2342        // Default import.
2343        if matches!(self.current.kind, TokenKind::Ident(_)) {
2344            let local = self.expect_ident()?;
2345            specifiers.push(ImportSpecifier::Default(local));
2346            if !self.eat_punct(Punct::Comma)? {
2347                return self.finish_import(start, specifiers);
2348            }
2349        }
2350        if self.at_punct(Punct::Star) {
2351            self.bump()?;
2352            if !self.eat_contextual("as")? {
2353                return Err(self.unexpected());
2354            }
2355            let local = self.expect_ident()?;
2356            specifiers.push(ImportSpecifier::Namespace(local));
2357            return self.finish_import(start, specifiers);
2358        }
2359        if self.at_punct(Punct::LBrace) {
2360            self.bump()?;
2361            while !self.at_punct(Punct::RBrace) {
2362                let imported = self.parse_module_name()?;
2363                let local = if self.eat_contextual("as")? {
2364                    self.expect_ident()?
2365                } else {
2366                    match &imported {
2367                        ModuleName::Ident(id) => id.clone(),
2368                        ModuleName::Str(_) => {
2369                            return Err(self.error_at(
2370                                "a string module name must be followed by 'as'",
2371                                self.current.span,
2372                            ));
2373                        }
2374                    }
2375                };
2376                specifiers.push(ImportSpecifier::Named { imported, local });
2377                if !self.eat_punct(Punct::Comma)? {
2378                    break;
2379                }
2380            }
2381            self.expect_punct(Punct::RBrace)?;
2382        } else if !specifiers.is_empty() {
2383            return Err(self.unexpected());
2384        } else if self.at_punct(Punct::LBrace) {
2385            unreachable!("handled above");
2386        } else {
2387            return Err(self.unexpected());
2388        }
2389        self.finish_import(start, specifiers)
2390    }
2391
2392    fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
2393        if !self.eat_contextual("from")? {
2394            return Err(self.unexpected());
2395        }
2396        let TokenKind::String(source) = self.current.kind.clone() else {
2397            return Err(self.error("expecting a module name string"));
2398        };
2399        self.bump()?;
2400        let attributes = self.parse_import_attributes()?;
2401        self.semicolon()?;
2402        let span = self.span_from(start);
2403        for specifier in &specifiers {
2404            let local = match specifier {
2405                ImportSpecifier::Default(id) => id,
2406                ImportSpecifier::Namespace(id) => id,
2407                ImportSpecifier::Named { local, .. } => local,
2408            };
2409            self.declare_lexical(&local.name, local.span)?;
2410        }
2411        Ok(Stmt::new(
2412            StmtKind::Import(Box::new(ImportDecl {
2413                specifiers,
2414                source,
2415                attributes,
2416                span,
2417            })),
2418            span,
2419        ))
2420    }
2421
2422    fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
2423        let mut attributes = Vec::new();
2424        let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
2425        if !has_with {
2426            return Ok(attributes);
2427        }
2428        let peek = self.peek()?;
2429        if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
2430            return Ok(attributes);
2431        }
2432        self.bump()?; // with / assert
2433        self.expect_punct(Punct::LBrace)?;
2434        while !self.at_punct(Punct::RBrace) {
2435            let attr_start = self.current.span.start;
2436            let key = match self.current.kind.clone() {
2437                TokenKind::Ident(name) => name,
2438                TokenKind::String(value) => value,
2439                _ => return Err(self.error("expecting an import attribute name")),
2440            };
2441            self.bump()?;
2442            self.expect_punct(Punct::Colon)?;
2443            let TokenKind::String(value) = self.current.kind.clone() else {
2444                return Err(self.error("expecting an import attribute value string"));
2445            };
2446            self.bump()?;
2447            attributes.push(ImportAttribute {
2448                key,
2449                value,
2450                span: self.span_from(attr_start),
2451            });
2452            if !self.eat_punct(Punct::Comma)? {
2453                break;
2454            }
2455        }
2456        self.expect_punct(Punct::RBrace)?;
2457        Ok(attributes)
2458    }
2459
2460    fn parse_module_name(&mut self) -> Result<ModuleName> {
2461        match self.current.kind.clone() {
2462            TokenKind::String(value) => {
2463                self.bump()?;
2464                Ok(ModuleName::Str(value))
2465            }
2466            TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
2467            TokenKind::Keyword(kw) => {
2468                let span = self.current.span;
2469                self.bump()?;
2470                Ok(ModuleName::Ident(Ident {
2471                    name: kw.as_str().to_string(),
2472                    span,
2473                }))
2474            }
2475            _ => Err(self.error("expecting an export name")),
2476        }
2477    }
2478
2479    fn parse_export_decl(&mut self) -> Result<Stmt> {
2480        let start = self.current.span.start;
2481        self.bump()?; // export
2482        if self.at_punct(Punct::Star) {
2483            self.bump()?;
2484            let mut exported = None;
2485            if self.eat_contextual("as")? {
2486                exported = Some(self.parse_module_name()?);
2487            }
2488            if !self.eat_contextual("from")? {
2489                return Err(self.error("expecting 'from' after 'export *'"));
2490            }
2491            let TokenKind::String(source) = self.current.kind.clone() else {
2492                return Err(self.error("expecting a module name string"));
2493            };
2494            self.bump()?;
2495            let attributes = self.parse_import_attributes()?;
2496            self.semicolon()?;
2497            let span = self.span_from(start);
2498            return Ok(Stmt::new(
2499                StmtKind::Export(Box::new(ExportDecl {
2500                    kind: ExportKind::All {
2501                        source,
2502                        exported,
2503                        attributes,
2504                    },
2505                    span,
2506                })),
2507                span,
2508            ));
2509        }
2510        if self.eat_keyword(Keyword::Default)? {
2511            let value = if self.at_keyword(Keyword::Function) {
2512                let func = self.parse_function(FunctionForm::Expression, false)?;
2513                Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2514            } else if self.at_ident("async") {
2515                let peek = self.peek()?;
2516                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
2517                    self.bump()?;
2518                    let func = self.parse_function(FunctionForm::Expression, true)?;
2519                    Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2520                } else {
2521                    self.parse_assignment(true)?
2522                }
2523            } else if self.at_keyword(Keyword::Class) {
2524                let class = self.parse_class(true)?;
2525                Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
2526            } else {
2527                let expr = self.parse_assignment(true)?;
2528                self.semicolon()?;
2529                expr
2530            };
2531            let span = self.span_from(start);
2532            return Ok(Stmt::new(
2533                StmtKind::Export(Box::new(ExportDecl {
2534                    kind: ExportKind::Default(Box::new(value)),
2535                    span,
2536                })),
2537                span,
2538            ));
2539        }
2540        if self.at_keyword(Keyword::Var)
2541            || self.at_keyword(Keyword::Const)
2542            || self.at_keyword(Keyword::Function)
2543            || self.at_keyword(Keyword::Class)
2544            || (self.at_ident("let") && self.let_starts_declaration()?)
2545        {
2546            let decl = self.parse_statement_list_item()?;
2547            let span = self.span_from(start);
2548            return Ok(Stmt::new(
2549                StmtKind::Export(Box::new(ExportDecl {
2550                    kind: ExportKind::Declaration(Box::new(decl)),
2551                    span,
2552                })),
2553                span,
2554            ));
2555        }
2556        if self.at_ident("async") {
2557            let peek = self.peek()?;
2558            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
2559                let decl = self.parse_statement_list_item()?;
2560                let span = self.span_from(start);
2561                return Ok(Stmt::new(
2562                    StmtKind::Export(Box::new(ExportDecl {
2563                        kind: ExportKind::Declaration(Box::new(decl)),
2564                        span,
2565                    })),
2566                    span,
2567                ));
2568            }
2569        }
2570        if self.at_punct(Punct::LBrace) {
2571            self.bump()?;
2572            let mut specifiers = Vec::new();
2573            let mut candidates: Vec<(String, Span)> = Vec::new();
2574            let mut source = None;
2575            while !self.at_punct(Punct::RBrace) {
2576                let spec_start = self.current.span.start;
2577                let local = self.parse_module_name()?;
2578                let exported = if self.eat_contextual("as")? {
2579                    self.parse_module_name()?
2580                } else {
2581                    local.clone()
2582                };
2583                // Deferred: whether these name *local* bindings (and so have to be
2584                // checked against the module's declarations) depends on whether a
2585                // `from` follows, which is not known until the closing brace.
2586                if let ModuleName::Ident(id) = &local {
2587                    candidates.push((id.name.clone(), id.span));
2588                }
2589                specifiers.push(ExportSpecifier {
2590                    local,
2591                    exported,
2592                    span: self.span_from(spec_start),
2593                });
2594                if !self.eat_punct(Punct::Comma)? {
2595                    break;
2596                }
2597            }
2598            self.expect_punct(Punct::RBrace)?;
2599            let mut attributes = Vec::new();
2600            let has_from = self.eat_contextual("from")?;
2601            if !has_from {
2602                // `export { a }` re-exports a binding of this module and must name one;
2603                // `export { a } from "m"` names an export of `m` and is checked when the
2604                // module is linked, not here.
2605                self.pending_exports.extend(candidates);
2606            }
2607            if has_from {
2608                let TokenKind::String(value) = self.current.kind.clone() else {
2609                    return Err(self.error("expecting a module name string"));
2610                };
2611                self.bump()?;
2612                source = Some(value);
2613                attributes = self.parse_import_attributes()?;
2614            }
2615            self.semicolon()?;
2616            let span = self.span_from(start);
2617            return Ok(Stmt::new(
2618                StmtKind::Export(Box::new(ExportDecl {
2619                    kind: ExportKind::Named {
2620                        specifiers,
2621                        source,
2622                        attributes,
2623                    },
2624                    span,
2625                })),
2626                span,
2627            ));
2628        }
2629        Err(self.unexpected())
2630    }
2631
2632    // -- patterns from expressions ----------------------------------------
2633
2634    fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
2635        self.expr_to_pattern_inner(expr, kind, false)
2636    }
2637
2638    fn expr_to_pattern_inner(
2639        &mut self,
2640        expr: Expr,
2641        kind: TargetKind,
2642        nested: bool,
2643    ) -> Result<Pattern> {
2644        let span = expr.span;
2645        match expr.kind {
2646            ExprKind::Ident(ident) => {
2647                if kind == TargetKind::Binding {
2648                    self.check_binding_name(&ident.name, ident.span)?;
2649                } else {
2650                    self.check_identifier(&ident.name, ident.span)?;
2651                    if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2652                        return Err(self.error_at(
2653                            format!("invalid assignment to '{}' in strict mode", ident.name),
2654                            ident.span,
2655                        ));
2656                    }
2657                }
2658                Ok(Pattern::new(PatternKind::Ident(ident), span))
2659            }
2660            ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
2661            ExprKind::Array { elements } => {
2662                let mut out = Vec::new();
2663                let mut rest = None;
2664                let count = elements.len();
2665                for (index, element) in elements.into_iter().enumerate() {
2666                    match element {
2667                        None => out.push(None),
2668                        Some(ArrayElement::Expr(expr)) => {
2669                            let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
2670                            out.push(Some(PatternElement::Pattern(pattern)));
2671                        }
2672                        Some(ArrayElement::Spread(expr)) => {
2673                            if index + 1 != count {
2674                                return Err(self.error_at("rest element must be last", expr.span));
2675                            }
2676                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2677                        }
2678                    }
2679                }
2680                Ok(Pattern::new(
2681                    PatternKind::Array {
2682                        elements: out,
2683                        rest,
2684                    },
2685                    span,
2686                ))
2687            }
2688            ExprKind::Object(properties) => {
2689                self.cover_inits
2690                    .retain(|cover| !span_contains(span, *cover));
2691                let mut out = Vec::new();
2692                let mut rest = None;
2693                let count = properties.len();
2694                for (index, property) in properties.into_iter().enumerate() {
2695                    match property {
2696                        ObjectProperty::Spread(expr) => {
2697                            if index + 1 != count {
2698                                return Err(self.error_at("rest element must be last", expr.span));
2699                            }
2700                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2701                        }
2702                        ObjectProperty::Property {
2703                            key,
2704                            value,
2705                            kind: _,
2706                            shorthand,
2707                            span,
2708                        } => {
2709                            let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
2710                            out.push(Some(PatternElement::Property {
2711                                key,
2712                                value: pattern,
2713                                shorthand,
2714                                span,
2715                            }));
2716                        }
2717                    }
2718                }
2719                Ok(Pattern::new(
2720                    PatternKind::Object {
2721                        properties: out,
2722                        rest,
2723                    },
2724                    span,
2725                ))
2726            }
2727            ExprKind::Assign { op, target, value } if op.is_simple() => {
2728                // `{a = 1}` inside a pattern: the target must itself be a pattern.
2729                let target = match target.kind {
2730                    PatternKind::Ident(ident) => {
2731                        Pattern::new(PatternKind::Ident(ident), target.span)
2732                    }
2733                    other => {
2734                        let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
2735                        self.expr_to_pattern_inner(expr, kind, nested)?
2736                    }
2737                };
2738                Ok(Pattern::new(
2739                    PatternKind::Assign {
2740                        target: Box::new(target),
2741                        default: value,
2742                    },
2743                    span,
2744                ))
2745            }
2746            ExprKind::Member {
2747                object,
2748                property,
2749                optional,
2750            } => {
2751                if kind == TargetKind::Binding {
2752                    return Err(self.error_at("invalid binding pattern", span));
2753                }
2754                if optional {
2755                    return Err(self.error_at("invalid assignment target", span));
2756                }
2757                let op_pos = expr.op_pos;
2758                Ok(Pattern::new(
2759                    PatternKind::Member(Box::new(MemberPattern {
2760                        object,
2761                        property,
2762                        span,
2763                        op_pos,
2764                    })),
2765                    span,
2766                ))
2767            }
2768            ExprKind::OptionalChain(_) => {
2769                Err(self.error_at("invalid assignment left-hand side", span))
2770            }
2771            // QuickJS reports `a() = 1` at run time (it evaluates the callee
2772            // first, then rejects the reference) but rejects the same thing
2773            // inside a destructuring pattern at parse time. Every other
2774            // non-assignable expression is rejected here.
2775            other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
2776                Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
2777            ),
2778            _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
2779            _ => Err(self.error_at("invalid destructuring target", span)),
2780        }
2781    }
2782
2783    fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
2784        // Array and object literals wrap their spread elements, so the target is
2785        // one level in.
2786        let expr = match expr.kind {
2787            ExprKind::Spread(inner) => *inner,
2788            other => Expr::new(other, expr.span),
2789        };
2790        if kind == TargetKind::Binding {
2791            return Ok(RestElement::Pattern(
2792                self.expr_to_pattern_inner(expr, kind, true)?,
2793            ));
2794        }
2795        match &expr.kind {
2796            ExprKind::Member { optional, .. } => {
2797                if *optional {
2798                    return Err(self.error_at("invalid assignment target", expr.span));
2799                }
2800                match self.expr_to_pattern_inner(expr, kind, true)?.kind {
2801                    PatternKind::Member(member) => Ok(RestElement::Member(member)),
2802                    _ => unreachable!("member expressions convert to member patterns"),
2803                }
2804            }
2805            _ => Ok(RestElement::Pattern(
2806                self.expr_to_pattern_inner(expr, kind, true)?,
2807            )),
2808        }
2809    }
2810
2811    // -- expressions -------------------------------------------------------
2812
2813    /// `Expression` (comma separated).
2814    fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
2815        self.enter()?;
2816        let result = self.parse_expression_unguarded(allow_in);
2817        self.leave();
2818        result
2819    }
2820
2821    fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
2822        let start = self.current.span.start;
2823        let first = self.parse_assignment(allow_in)?;
2824        if !self.at_punct(Punct::Comma) {
2825            return Ok(first);
2826        }
2827        let mut items = vec![first];
2828        while self.eat_punct(Punct::Comma)? {
2829            items.push(self.parse_assignment(allow_in)?);
2830        }
2831        Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
2832    }
2833
2834    fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
2835        let start = self.current.span.start;
2836
2837        // `yield` in a generator.
2838        if self.ctx.in_generator && self.at_ident("yield") {
2839            return self.parse_yield(allow_in);
2840        }
2841
2842        let lhs = match self.try_parse_arrow(allow_in)? {
2843            Some(arrow) => return Ok(arrow),
2844            None => self.parse_conditional(allow_in)?,
2845        };
2846
2847        if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
2848            let op_pos = self.current.span.start;
2849            let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
2850            self.bump()?;
2851            let value = self.parse_assignment(allow_in)?;
2852            return Ok(Expr::at_operator(
2853                ExprKind::Assign {
2854                    op,
2855                    target: Box::new(target),
2856                    value: Box::new(value),
2857                },
2858                self.span_from(start),
2859                op_pos,
2860            ));
2861        }
2862        let _ = start;
2863        Ok(lhs)
2864    }
2865
2866    fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
2867        let start = self.current.span.start;
2868        self.bump()?; // yield
2869        let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
2870            self.bump()?;
2871            true
2872        } else {
2873            false
2874        };
2875        let argument = if delegate {
2876            Some(Box::new(self.parse_assignment(allow_in)?))
2877        } else if self.current.newline_before
2878            || self.at_punct(Punct::RParen)
2879            || self.at_punct(Punct::RBracket)
2880            || self.at_punct(Punct::RBrace)
2881            || self.at_punct(Punct::Comma)
2882            || self.at_punct(Punct::Semicolon)
2883            || self.at_punct(Punct::Colon)
2884            || self.current.is_eof()
2885        {
2886            None
2887        } else {
2888            Some(Box::new(self.parse_assignment(allow_in)?))
2889        };
2890        Ok(Expr::new(
2891            ExprKind::Yield { argument, delegate },
2892            self.span_from(start),
2893        ))
2894    }
2895
2896    fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
2897        let starts_paren = self.at_punct(Punct::LParen);
2898        let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
2899        if !starts_paren && !starts_ident {
2900            return Ok(None);
2901        }
2902        // `(` could be a parenthesised expression instead of a parameter list.
2903        // Scanning ahead for the matching `)` and looking for `=>` avoids the
2904        // speculative parse (and its stack cost) in the common case.
2905        if starts_paren && !self.arrow_follows_paren()? {
2906            return Ok(None);
2907        }
2908        let snapshot = self.snapshot();
2909        let head = match self.parse_arrow_head() {
2910            Ok(head) => head,
2911            Err(_) => {
2912                self.restore(snapshot);
2913                return Ok(None);
2914            }
2915        };
2916        let Some(head) = head else {
2917            self.restore(snapshot);
2918            return Ok(None);
2919        };
2920        // Committed: `=>` has been consumed, so errors from here on are real.
2921        // Arrow parameter lists may never repeat a name, in any mode.
2922        {
2923            let mut seen: Vec<String> = Vec::new();
2924            for param in &head.params {
2925                let mut names = Vec::new();
2926                param.bound_names(&mut names);
2927                for name in names {
2928                    if seen.contains(&name.name) {
2929                        return Err(self.error_at(
2930                            format!(
2931                                "duplicate argument names not allowed in this context ('{}')",
2932                                name.name
2933                            ),
2934                            name.span,
2935                        ));
2936                    }
2937                    seen.push(name.name);
2938                }
2939            }
2940        }
2941        let saved_ctx = self.ctx;
2942        let saved_loop = self.loop_depth;
2943        let saved_switch = self.switch_depth;
2944        let saved_labels = std::mem::take(&mut self.labels);
2945        let saved_top = self.top_level;
2946        self.ctx = FnCtx {
2947            in_function: true,
2948            in_generator: false,
2949            in_async: head.is_async,
2950            in_method: saved_ctx.in_method,
2951            in_derived_constructor: saved_ctx.in_derived_constructor,
2952        };
2953        self.loop_depth = 0;
2954        self.switch_depth = 0;
2955        self.top_level = false;
2956        let body_start = self.current.span.start;
2957        let (body, strict) = if self.at_punct(Punct::LBrace) {
2958            let (block, strict) = self.parse_arrow_block(&head.params)?;
2959            (block, (self.prev_end, strict))
2960        } else {
2961            let expr = self.parse_assignment(allow_in)?;
2962            let end = expr.span.end;
2963            // An expression body has no directive prologue, so it inherits.
2964            let strict = self.strict;
2965            (FunctionBody::Expr(Box::new(expr)), (end, strict))
2966        };
2967        self.ctx = saved_ctx;
2968        self.loop_depth = saved_loop;
2969        self.switch_depth = saved_switch;
2970        self.labels = saved_labels;
2971        self.top_level = saved_top;
2972        let _ = body_start;
2973        let (body, (end, strict)) = (body, strict);
2974        let span = Span::new(head.span.start, end);
2975        Ok(Some(Expr::new(
2976            ExprKind::Arrow(Box::new(Function {
2977                name: None,
2978                params: head.params,
2979                body,
2980                is_async: head.is_async,
2981                is_generator: false,
2982                strict,
2983                is_arrow: true,
2984                span,
2985                params_span: head.params_span,
2986            })),
2987            span,
2988        )))
2989    }
2990
2991    /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
2992    fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
2993        // Like a function body: the arrow's own directive governs the arrow, and the
2994        // enclosing scope's mode is restored afterwards.
2995        let saved_strict = self.strict;
2996        self.expect_punct(Punct::LBrace)?;
2997        self.push_scope(Scope::function(simple_parameter_names(params)));
2998        let result = (|| -> Result<Vec<Stmt>> {
2999            let mut body = Vec::new();
3000            let mut prologue = true;
3001            while !self.at_punct(Punct::RBrace) {
3002                if self.current.is_eof() {
3003                    return Err(self.unexpected());
3004                }
3005                let stmt = self.parse_statement_list_item()?;
3006                if prologue {
3007                    match self.directive_value(&stmt) {
3008                        Some(directive) if directive == "use strict" => self.enter_strict()?,
3009                        Some(_) => {}
3010                        None => prologue = false,
3011                    }
3012                }
3013                body.push(stmt);
3014            }
3015            Ok(body)
3016        })();
3017        self.pop_scope();
3018        let body_strict = self.strict;
3019        self.strict = saved_strict;
3020        self.lexer.set_strict(saved_strict);
3021        let body = result?;
3022        self.bump()?;
3023        Ok((FunctionBody::Block(body), body_strict))
3024    }
3025
3026    /// Whether the parenthesis at the current token is the parameter list of an
3027    /// arrow function, i.e. the matching `)` is followed by `=>`.
3028    ///
3029    /// This is a plain token walk with a bracket counter: no recursion, so it
3030    /// costs a clone of the lexer and nothing else.
3031    fn arrow_follows_paren(&self) -> Result<bool> {
3032        let mut lexer = self.lexer.clone();
3033        // The opening `(` was already consumed by the caller.
3034        let mut depth = 1usize;
3035        loop {
3036            let token = lexer.next_token()?;
3037            match token.kind {
3038                TokenKind::Eof => return Ok(false),
3039                TokenKind::Punct(Punct::LParen)
3040                | TokenKind::Punct(Punct::LBracket)
3041                | TokenKind::Punct(Punct::LBrace) => depth += 1,
3042                TokenKind::Punct(Punct::RParen)
3043                | TokenKind::Punct(Punct::RBracket)
3044                | TokenKind::Punct(Punct::RBrace) => {
3045                    if depth == 0 {
3046                        // Unbalanced input: the caller reports it.
3047                        return Ok(false);
3048                    }
3049                    depth -= 1;
3050                    if depth == 0 {
3051                        // The current token is the opening `(`, so the matching
3052                        // `)` is the token that brought us back to zero.
3053                        let next = lexer.next_token()?;
3054                        return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3055                            && !next.newline_before);
3056                    }
3057                }
3058                _ => {}
3059            }
3060        }
3061    }
3062
3063    /// Speculatively parse an arrow head, consuming `=>` on success.
3064    fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3065        let start = self.current.span.start;
3066        let mut is_async = false;
3067        if self.at_ident("async") {
3068            let peek = self.peek()?;
3069            if peek.newline_before {
3070                return Ok(None);
3071            }
3072            let plausible =
3073                matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3074            if !plausible {
3075                return Ok(None);
3076            }
3077            self.bump()?;
3078            is_async = true;
3079        }
3080        let params_start = self.current.span.start;
3081        let params = if self.at_punct(Punct::LParen) {
3082            self.parse_formal_parameters()?
3083        } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3084            let ident = self.expect_ident()?;
3085            vec![Pattern::new(
3086                PatternKind::Ident(ident),
3087                self.span_from(params_start),
3088            )]
3089        } else {
3090            return Ok(None);
3091        };
3092        let params_span = self.span_from(params_start);
3093        if !self.at_punct(Punct::Arrow) || self.current.newline_before {
3094            return Ok(None);
3095        }
3096        self.bump()?; // =>
3097        Ok(Some(ArrowHead {
3098            params,
3099            is_async,
3100            span: self.span_from(start),
3101            params_span,
3102        }))
3103    }
3104
3105    fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
3106        let start = self.current.span.start;
3107        let test = self.parse_binary(allow_in, 0)?;
3108        if !self.at_punct(Punct::Question) {
3109            return Ok(test);
3110        }
3111        self.bump()?;
3112        let consequent = self.parse_assignment(true)?;
3113        self.expect_punct(Punct::Colon)?;
3114        let alternate = self.parse_assignment(allow_in)?;
3115        Ok(Expr::new(
3116            ExprKind::Conditional {
3117                test: Box::new(test),
3118                cons: Box::new(consequent),
3119                alt: Box::new(alternate),
3120            },
3121            self.span_from(start),
3122        ))
3123    }
3124
3125    fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
3126        let start = self.current.span.start;
3127        let mut lhs = self.parse_unary()?;
3128        while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
3129            if prec < min_prec {
3130                break;
3131            }
3132            let op_pos = self.current.span.start;
3133            self.bump()?;
3134            let next_min = if op.is_right_associative() {
3135                prec
3136            } else {
3137                prec + 1
3138            };
3139            let rhs = self.parse_binary(allow_in, next_min)?;
3140            lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
3141        }
3142        Ok(lhs)
3143    }
3144
3145    /// Unary and postfix operators. `in` is handled by the binary layer, so no
3146    /// `allow_in` flag is needed here.
3147    fn parse_unary(&mut self) -> Result<Expr> {
3148        let start = self.current.span.start;
3149        // Unary operators.
3150        let unary = match &self.current.kind {
3151            TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
3152            TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
3153            TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
3154            TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
3155            TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
3156            TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
3157            TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
3158            _ => None,
3159        };
3160        if let Some(op) = unary {
3161            let op_pos = self.current.span.start;
3162            self.bump()?;
3163            let argument = self.parse_unary()?;
3164            if op == UnaryOp::Delete && self.strict {
3165                if let ExprKind::Ident(ident) = &argument.unparen().kind {
3166                    return Err(
3167                        self.error_at("cannot delete a variable in strict mode", ident.span)
3168                    );
3169                }
3170            }
3171            let expr = Expr::at_operator(
3172                ExprKind::Unary {
3173                    op,
3174                    argument: Box::new(argument),
3175                },
3176                self.span_from(start),
3177                op_pos,
3178            );
3179            if self.at_punct(Punct::StarStar) {
3180                return Err(self.error(
3181                    "unexpected token '**': a unary expression may not be the base of '**'",
3182                ));
3183            }
3184            return Ok(expr);
3185        }
3186        // Prefix increment/decrement.
3187        if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
3188            let op_pos = self.current.span.start;
3189            let op = if self.at_punct(Punct::PlusPlus) {
3190                UpdateOp::Increment
3191            } else {
3192                UpdateOp::Decrement
3193            };
3194            self.bump()?;
3195            let argument = self.parse_unary()?;
3196            self.check_simple_target(&argument)?;
3197            return Ok(Expr::at_operator(
3198                ExprKind::Update {
3199                    op,
3200                    argument: Box::new(argument),
3201                    prefix: true,
3202                },
3203                self.span_from(start),
3204                op_pos,
3205            ));
3206        }
3207        // `await` in async contexts (and at a module's top level).
3208        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
3209            let peek = self.peek()?;
3210            let starts_expression = !matches!(
3211                peek.kind,
3212                TokenKind::Punct(Punct::RParen)
3213                    | TokenKind::Punct(Punct::RBracket)
3214                    | TokenKind::Punct(Punct::RBrace)
3215                    | TokenKind::Punct(Punct::Comma)
3216                    | TokenKind::Punct(Punct::Semicolon)
3217                    | TokenKind::Punct(Punct::Colon)
3218                    | TokenKind::Punct(Punct::Eq)
3219                    | TokenKind::Punct(Punct::Arrow)
3220                    | TokenKind::Punct(Punct::Dot)
3221                    | TokenKind::Punct(Punct::QuestionDot)
3222                    | TokenKind::Punct(Punct::LBracket)
3223            ) && !peek.newline_before;
3224            if starts_expression {
3225                self.bump()?;
3226                let argument = self.parse_unary()?;
3227                return Ok(Expr::new(
3228                    ExprKind::Await(Box::new(argument)),
3229                    self.span_from(start),
3230                ));
3231            }
3232        }
3233        let expr = self.parse_lhs_expression()?;
3234        // Postfix increment/decrement (no line break allowed before the operator).
3235        let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3236            && !self.current.newline_before
3237        {
3238            let op_pos = self.current.span.start;
3239            let op = if self.at_punct(Punct::PlusPlus) {
3240                UpdateOp::Increment
3241            } else {
3242                UpdateOp::Decrement
3243            };
3244            self.check_simple_target(&expr)?;
3245            self.bump()?;
3246            Expr::at_operator(
3247                ExprKind::Update {
3248                    op,
3249                    argument: Box::new(expr),
3250                    prefix: false,
3251                },
3252                self.span_from(start),
3253                op_pos,
3254            )
3255        } else {
3256            expr
3257        };
3258        Ok(result)
3259    }
3260
3261    fn check_simple_target(&self, expr: &Expr) -> Result<()> {
3262        match &expr.unparen().kind {
3263            ExprKind::Ident(_) => Ok(()),
3264            ExprKind::Member {
3265                optional: false, ..
3266            } => Ok(()),
3267            _ => Err(self.error_at("invalid assignment left-hand side", expr.span)),
3268        }
3269    }
3270
3271    fn parse_lhs_expression(&mut self) -> Result<Expr> {
3272        let start = self.current.span.start;
3273        let mut expr = if self.at_keyword(Keyword::New) {
3274            self.parse_new_expression()?
3275        } else {
3276            self.parse_primary()?
3277        };
3278        let mut saw_optional = false;
3279        loop {
3280            // The position of the punctuator that follows the base expression: a
3281            // failed `.`, `[` or `(` is blamed on that token, not on the base.
3282            let op_pos = self.current.span.start;
3283            match self.current.kind.clone() {
3284                TokenKind::Punct(Punct::Dot) => {
3285                    self.bump()?;
3286                    let property = self.parse_member_property()?;
3287                    expr = Expr::at_operator(
3288                        ExprKind::Member {
3289                            object: Box::new(expr),
3290                            property,
3291                            optional: false,
3292                        },
3293                        self.span_from(start),
3294                        op_pos,
3295                    );
3296                }
3297                TokenKind::Punct(Punct::QuestionDot) => {
3298                    saw_optional = true;
3299                    self.bump()?;
3300                    if self.at_punct(Punct::LParen) {
3301                        let arguments = self.parse_arguments()?;
3302                        expr = Expr::at_operator(
3303                            ExprKind::Call {
3304                                callee: Box::new(expr),
3305                                arguments,
3306                                optional: true,
3307                            },
3308                            self.span_from(start),
3309                            op_pos,
3310                        );
3311                    } else if self.at_punct(Punct::LBracket) {
3312                        self.bump()?;
3313                        let index = self.parse_expression(true)?;
3314                        self.expect_punct(Punct::RBracket)?;
3315                        expr = Expr::at_operator(
3316                            ExprKind::Member {
3317                                object: Box::new(expr),
3318                                property: MemberProp::Computed(Box::new(index)),
3319                                optional: true,
3320                            },
3321                            self.span_from(start),
3322                            op_pos,
3323                        );
3324                    } else {
3325                        let property = self.parse_member_property()?;
3326                        expr = Expr::at_operator(
3327                            ExprKind::Member {
3328                                object: Box::new(expr),
3329                                property,
3330                                optional: true,
3331                            },
3332                            self.span_from(start),
3333                            op_pos,
3334                        );
3335                    }
3336                }
3337                TokenKind::Punct(Punct::LBracket) => {
3338                    self.bump()?;
3339                    let index = self.parse_expression(true)?;
3340                    self.expect_punct(Punct::RBracket)?;
3341                    expr = Expr::at_operator(
3342                        ExprKind::Member {
3343                            object: Box::new(expr),
3344                            property: MemberProp::Computed(Box::new(index)),
3345                            optional: false,
3346                        },
3347                        self.span_from(start),
3348                        op_pos,
3349                    );
3350                }
3351                TokenKind::Punct(Punct::LParen) => {
3352                    let arguments = self.parse_arguments()?;
3353                    expr = Expr::at_operator(
3354                        ExprKind::Call {
3355                            callee: Box::new(expr),
3356                            arguments,
3357                            optional: false,
3358                        },
3359                        self.span_from(start),
3360                        op_pos,
3361                    );
3362                }
3363                TokenKind::Template(_) => {
3364                    if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
3365                        return Err(
3366                            self.error("tagged template cannot be used in an optional chain")
3367                        );
3368                    }
3369                    let quasi = self.parse_template()?;
3370                    expr = Expr::new(
3371                        ExprKind::TaggedTemplate {
3372                            tag: Box::new(expr),
3373                            quasi: Box::new(quasi),
3374                        },
3375                        self.span_from(start),
3376                    );
3377                }
3378                _ => break,
3379            }
3380        }
3381        if saw_optional {
3382            expr = Expr::new(
3383                ExprKind::OptionalChain(Box::new(expr)),
3384                self.span_from(start),
3385            );
3386        }
3387        Ok(expr)
3388    }
3389
3390    fn parse_member_property(&mut self) -> Result<MemberProp> {
3391        if self.at_punct(Punct::Hash) {
3392            self.bump()?;
3393            let ident = self.expect_ident()?;
3394            if !self.private.iter().any(|env| env.contains(&ident.name)) {
3395                return Err(self.error_at(
3396                    format!(
3397                        "private field '#{}' must be declared in an enclosing class",
3398                        ident.name
3399                    ),
3400                    ident.span,
3401                ));
3402            }
3403            return Ok(MemberProp::Private(ident));
3404        }
3405        match self.current.kind.clone() {
3406            TokenKind::Ident(name) => {
3407                let span = self.current.span;
3408                self.bump()?;
3409                Ok(MemberProp::Ident(Ident { name, span }))
3410            }
3411            TokenKind::Keyword(kw) => {
3412                let span = self.current.span;
3413                self.bump()?;
3414                Ok(MemberProp::Ident(Ident {
3415                    name: kw.as_str().to_string(),
3416                    span,
3417                }))
3418            }
3419            _ => Err(self.error("expecting a property name")),
3420        }
3421    }
3422
3423    fn parse_new_expression(&mut self) -> Result<Expr> {
3424        let start = self.current.span.start;
3425        self.bump()?; // new
3426        if self.at_punct(Punct::Dot) {
3427            self.bump()?;
3428            if !self.at_ident("target") {
3429                return Err(self.error("expecting 'target' after 'new.'"));
3430            }
3431            if !self.ctx.in_function {
3432                return Err(self.error("invalid use of 'new.target' outside of a function"));
3433            }
3434            self.bump()?;
3435            return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
3436        }
3437        let mut callee = if self.at_keyword(Keyword::New) {
3438            self.parse_new_expression()?
3439        } else {
3440            self.parse_primary()?
3441        };
3442        // Member accesses bind tighter than `new`, calls do not.
3443        loop {
3444            let op_pos = self.current.span.start;
3445            match self.current.kind.clone() {
3446                TokenKind::Punct(Punct::Dot) => {
3447                    self.bump()?;
3448                    let property = self.parse_member_property()?;
3449                    callee = Expr::at_operator(
3450                        ExprKind::Member {
3451                            object: Box::new(callee),
3452                            property,
3453                            optional: false,
3454                        },
3455                        self.span_from(start),
3456                        op_pos,
3457                    );
3458                }
3459                TokenKind::Punct(Punct::LBracket) => {
3460                    self.bump()?;
3461                    let index = self.parse_expression(true)?;
3462                    self.expect_punct(Punct::RBracket)?;
3463                    callee = Expr::at_operator(
3464                        ExprKind::Member {
3465                            object: Box::new(callee),
3466                            property: MemberProp::Computed(Box::new(index)),
3467                            optional: false,
3468                        },
3469                        self.span_from(start),
3470                        op_pos,
3471                    );
3472                }
3473                TokenKind::Punct(Punct::QuestionDot) => {
3474                    return Err(self.error("new keyword cannot be used with an optional chain"));
3475                }
3476                _ => break,
3477            }
3478        }
3479        if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
3480            return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
3481        }
3482        let arguments = if self.at_punct(Punct::LParen) {
3483            // `new C(...)`: a failure in the constructor call is blamed on the `(`.
3484            let op_pos = self.current.span.start;
3485            let arguments = Some(self.parse_arguments()?);
3486            return Ok(Expr::at_operator(
3487                ExprKind::New {
3488                    callee: Box::new(callee),
3489                    arguments,
3490                },
3491                self.span_from(start),
3492                op_pos,
3493            ));
3494        } else {
3495            None
3496        };
3497        Ok(Expr::new(
3498            ExprKind::New {
3499                callee: Box::new(callee),
3500                arguments,
3501            },
3502            self.span_from(start),
3503        ))
3504    }
3505
3506    fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
3507        self.expect_punct(Punct::LParen)?;
3508        let mut arguments = Vec::new();
3509        while !self.at_punct(Punct::RParen) {
3510            if self.at_punct(Punct::Ellipsis) {
3511                let start = self.current.span.start;
3512                self.bump()?;
3513                let argument = self.parse_assignment(true)?;
3514                arguments.push(Expr::new(
3515                    ExprKind::Spread(Box::new(argument)),
3516                    self.span_from(start),
3517                ));
3518            } else {
3519                arguments.push(self.parse_assignment(true)?);
3520            }
3521            if !self.eat_punct(Punct::Comma)? {
3522                break;
3523            }
3524        }
3525        self.expect_punct(Punct::RParen)?;
3526        Ok(arguments)
3527    }
3528
3529    /// Primary expressions.
3530    ///
3531    /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
3532    /// so that this function — which sits on every nesting level — keeps a small
3533    /// stack frame. That directly raises how deeply a program may nest before
3534    /// the stack limit is hit (debug builds get ~4x more depth out of it).
3535    fn parse_primary(&mut self) -> Result<Expr> {
3536        let start = self.current.span.start;
3537        match self.current.kind.clone() {
3538            TokenKind::Number(NumberLiteral::Int(value)) => {
3539                self.bump()?;
3540                Ok(Expr::new(
3541                    ExprKind::Number(value as f64),
3542                    self.span_from(start),
3543                ))
3544            }
3545            TokenKind::Number(NumberLiteral::Float(value)) => {
3546                self.bump()?;
3547                Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
3548            }
3549            TokenKind::String(value) => {
3550                self.bump()?;
3551                Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
3552            }
3553            TokenKind::Ident(name) if name == "async" => {
3554                let peek = self.peek()?;
3555                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
3556                    && !peek.newline_before
3557                {
3558                    self.bump()?; // async
3559                    let func = self.parse_function(FunctionForm::Expression, true)?;
3560                    return Ok(Expr::new(
3561                        ExprKind::Function(Box::new(func)),
3562                        self.span_from(start),
3563                    ));
3564                }
3565                let span = self.current.span;
3566                self.bump()?;
3567                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3568            }
3569            TokenKind::Ident(name) => {
3570                let span = self.current.span;
3571                self.check_identifier(&name, span)?;
3572                self.bump()?;
3573                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3574            }
3575            TokenKind::Keyword(Keyword::This) => {
3576                self.bump()?;
3577                Ok(Expr::new(ExprKind::This, self.span_from(start)))
3578            }
3579            TokenKind::Keyword(Keyword::Null) => {
3580                self.bump()?;
3581                Ok(Expr::new(ExprKind::Null, self.span_from(start)))
3582            }
3583            TokenKind::Keyword(Keyword::True) => {
3584                self.bump()?;
3585                Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
3586            }
3587            TokenKind::Keyword(Keyword::False) => {
3588                self.bump()?;
3589                Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
3590            }
3591            TokenKind::Punct(Punct::LParen) => {
3592                self.bump()?;
3593                let inner = self.parse_expression(true)?;
3594                self.expect_punct(Punct::RParen)?;
3595                Ok(Expr::new(
3596                    ExprKind::Paren(Box::new(inner)),
3597                    self.span_from(start),
3598                ))
3599            }
3600            TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3601                self.parse_regex_literal(start)
3602            }
3603            _ => self.parse_primary_complex(start),
3604        }
3605    }
3606
3607    /// The primary expressions that need a lot of code: literals with structure,
3608    /// functions, classes, `import`, `super`, `#x in y`.
3609    #[inline(never)]
3610    fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
3611        match self.current.kind.clone() {
3612            TokenKind::BigInt(literal) => {
3613                self.bump()?;
3614                Ok(Expr::new(
3615                    ExprKind::BigInt {
3616                        digits: literal.digits,
3617                        radix: literal.radix,
3618                    },
3619                    self.span_from(start),
3620                ))
3621            }
3622            TokenKind::Template(_) => {
3623                let template = self.parse_template()?;
3624                Ok(Expr::new(
3625                    ExprKind::Template(Box::new(template)),
3626                    self.span_from(start),
3627                ))
3628            }
3629            TokenKind::Keyword(Keyword::Function) => {
3630                let func = self.parse_function(FunctionForm::Expression, false)?;
3631                Ok(Expr::new(
3632                    ExprKind::Function(Box::new(func)),
3633                    self.span_from(start),
3634                ))
3635            }
3636            TokenKind::Keyword(Keyword::Class) => {
3637                let class = self.parse_class(true)?;
3638                Ok(Expr::new(
3639                    ExprKind::Class(Box::new(class)),
3640                    self.span_from(start),
3641                ))
3642            }
3643            TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
3644            TokenKind::Keyword(Keyword::Super) => self.parse_super(),
3645            TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
3646            TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
3647            TokenKind::Punct(Punct::Hash) => self.parse_private_in(start),
3648            _ => Err(self.unexpected()),
3649        }
3650    }
3651
3652    /// `super` or `super(...)`.
3653    #[inline(never)]
3654    fn parse_super(&mut self) -> Result<Expr> {
3655        let start = self.current.span.start;
3656        self.bump()?;
3657        if self.at_punct(Punct::LParen) {
3658            if !self.ctx.in_derived_constructor {
3659                return Err(self.error_at(
3660                    "invalid use of 'super' in a non-derived constructor",
3661                    self.span_from(start),
3662                ));
3663            }
3664            let arguments = self.parse_arguments()?;
3665            return Ok(Expr::new(
3666                ExprKind::SuperCall(arguments),
3667                self.span_from(start),
3668            ));
3669        }
3670        if !self.ctx.in_method {
3671            return Err(self.error_at(
3672                "invalid use of 'super' outside of a method",
3673                self.span_from(start),
3674            ));
3675        }
3676        Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
3677    }
3678
3679    /// `#name in object`.
3680    #[inline(never)]
3681    fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
3682        self.bump()?;
3683        let ident = self.expect_ident()?;
3684        if !self.private.iter().any(|env| env.contains(&ident.name)) {
3685            return Err(self.error_at(
3686                format!(
3687                    "private field '#{}' must be declared in an enclosing class",
3688                    ident.name
3689                ),
3690                ident.span,
3691            ));
3692        }
3693        if !self.at_keyword(Keyword::In) {
3694            return Err(self.error("expecting 'in' after a private name"));
3695        }
3696        self.bump()?;
3697        let object = self.parse_unary()?;
3698        Ok(Expr::new(
3699            ExprKind::PrivateIn {
3700                name: ident,
3701                object: Box::new(object),
3702            },
3703            self.span_from(start),
3704        ))
3705    }
3706
3707    /// A regular expression literal: the lexer produced `/` (or `/=`), so the
3708    /// token has to be re-scanned from that position.
3709    #[inline(never)]
3710    fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
3711        let token = self.lexer.re_scan_regex(self.current.span.start)?;
3712        self.current = token;
3713        let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
3714            unreachable!("re_scan_regex returns a RegExp token")
3715        };
3716        self.bump()?;
3717        Ok(Expr::new(
3718            ExprKind::RegExp { pattern, flags },
3719            self.span_from(start),
3720        ))
3721    }
3722
3723    fn parse_import_expression(&mut self) -> Result<Expr> {
3724        let start = self.current.span.start;
3725        self.bump()?; // import
3726        if self.at_punct(Punct::Dot) {
3727            if !self.module {
3728                return Err(self.error_at(
3729                    "import.meta only valid in module code",
3730                    self.span_from(start),
3731                ));
3732            }
3733            self.bump()?;
3734            if !self.at_ident("meta") {
3735                return Err(self.error("expecting 'meta' after 'import.'"));
3736            }
3737            self.bump()?;
3738            return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
3739        }
3740        if self.at_punct(Punct::LParen) {
3741            self.bump()?;
3742            let specifier = self.parse_assignment(true)?;
3743            if self.at_punct(Punct::Comma) {
3744                return Err(self.error("import() takes exactly one argument"));
3745            }
3746            self.expect_punct(Punct::RParen)?;
3747            return Ok(Expr::new(
3748                ExprKind::ImportCall(Box::new(specifier)),
3749                self.span_from(start),
3750            ));
3751        }
3752        Err(self.unexpected())
3753    }
3754
3755    fn parse_array_literal(&mut self) -> Result<Expr> {
3756        let start = self.current.span.start;
3757        self.expect_punct(Punct::LBracket)?;
3758        let mut elements = Vec::new();
3759        while !self.at_punct(Punct::RBracket) {
3760            if self.at_punct(Punct::Comma) {
3761                self.bump()?;
3762                elements.push(None);
3763                continue;
3764            }
3765            if self.at_punct(Punct::Ellipsis) {
3766                let spread_start = self.current.span.start;
3767                self.bump()?;
3768                let argument = self.parse_assignment(true)?;
3769                elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
3770                    ExprKind::Spread(Box::new(argument)),
3771                    self.span_from(spread_start),
3772                )))));
3773            } else {
3774                let expr = self.parse_assignment(true)?;
3775                elements.push(Some(ArrayElement::Expr(Box::new(expr))));
3776            }
3777            if !self.eat_punct(Punct::Comma)? {
3778                break;
3779            }
3780        }
3781        self.expect_punct(Punct::RBracket)?;
3782        Ok(Expr::new(
3783            ExprKind::Array { elements },
3784            self.span_from(start),
3785        ))
3786    }
3787
3788    fn parse_object_literal(&mut self) -> Result<Expr> {
3789        let start = self.current.span.start;
3790        self.expect_punct(Punct::LBrace)?;
3791        let mut properties: Vec<ObjectProperty> = Vec::new();
3792        let mut proto_count = 0;
3793        while !self.at_punct(Punct::RBrace) {
3794            let property_start = self.current.span.start;
3795            if self.at_punct(Punct::Ellipsis) {
3796                self.bump()?;
3797                let argument = self.parse_assignment(true)?;
3798                properties.push(ObjectProperty::Spread(Box::new(argument)));
3799            } else {
3800                let mut is_async = false;
3801                let mut is_generator = false;
3802                let mut accessor: Option<MethodKind> = None;
3803                if self.at_ident("async") {
3804                    let peek = self.peek()?;
3805                    let is_modifier = !matches!(
3806                        peek.kind,
3807                        TokenKind::Punct(Punct::LParen)
3808                            | TokenKind::Punct(Punct::Colon)
3809                            | TokenKind::Punct(Punct::Comma)
3810                            | TokenKind::Punct(Punct::RBrace)
3811                            | TokenKind::Punct(Punct::Eq)
3812                    ) && !peek.newline_before;
3813                    if is_modifier {
3814                        self.bump()?;
3815                        is_async = true;
3816                    }
3817                }
3818                if self.at_punct(Punct::Star) {
3819                    self.bump()?;
3820                    is_generator = true;
3821                }
3822                if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3823                    let is_get = self.at_ident("get");
3824                    let peek = self.peek()?;
3825                    if is_property_key_start(&peek.kind) {
3826                        self.bump()?;
3827                        accessor = Some(if is_get {
3828                            MethodKind::Get
3829                        } else {
3830                            MethodKind::Set
3831                        });
3832                    }
3833                }
3834                let key = self.parse_property_key()?;
3835                let is_computed = matches!(key, PropName::Computed(_));
3836                if self.at_punct(Punct::LParen) {
3837                    let saved = self.ctx;
3838                    self.ctx = FnCtx {
3839                        in_function: true,
3840                        in_generator: is_generator,
3841                        in_async: is_async,
3842                        in_method: true,
3843                        in_derived_constructor: false,
3844                    };
3845                    let saved_top = self.top_level;
3846                    self.top_level = false;
3847                    let func_result = (|| -> Result<Function> {
3848                        let params = self.parse_formal_parameters()?;
3849                        let (params, params_span, body, strict) =
3850                            self.parse_function_body(params, is_generator, is_async)?;
3851                        Ok(Function {
3852                            name: None,
3853                            params,
3854                            body,
3855                            is_async,
3856                            is_generator,
3857                            strict,
3858                            is_arrow: false,
3859                            span: self.span_from(property_start),
3860                            params_span,
3861                        })
3862                    })();
3863                    self.ctx = saved;
3864                    self.top_level = saved_top;
3865                    let func = func_result?;
3866                    let kind = match accessor {
3867                        Some(kind) => {
3868                            if is_generator || is_async {
3869                                return Err(self.error_at(
3870                                    "accessors may not be generators or async",
3871                                    func.span,
3872                                ));
3873                            }
3874                            if kind == MethodKind::Get && !func.params.is_empty() {
3875                                return Err(
3876                                    self.error_at("getter must have no arguments", func.span)
3877                                );
3878                            }
3879                            if kind == MethodKind::Set && func.params.len() != 1 {
3880                                return Err(self
3881                                    .error_at("setter must have exactly one argument", func.span));
3882                            }
3883                            match kind {
3884                                MethodKind::Get => PropertyKind::Get,
3885                                MethodKind::Set => PropertyKind::Set,
3886                                MethodKind::Method | MethodKind::Constructor => {
3887                                    PropertyKind::Method
3888                                }
3889                            }
3890                        }
3891                        None => PropertyKind::Method,
3892                    };
3893                    let span = self.span_from(property_start);
3894                    properties.push(ObjectProperty::Property {
3895                        key,
3896                        value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
3897                        kind,
3898                        shorthand: false,
3899                        span,
3900                    });
3901                } else if self.eat_punct(Punct::Colon)? {
3902                    let value = self.parse_assignment(true)?;
3903                    if !is_computed {
3904                        if let Some(PropKeyRef::Str("__proto__")) = key.static_name() {
3905                            proto_count += 1;
3906                            if proto_count > 1 {
3907                                return Err(self.error_at(
3908                                    "duplicate __proto__ fields are not allowed in object literals",
3909                                    self.span_from(property_start),
3910                                ));
3911                            }
3912                        }
3913                    }
3914                    properties.push(ObjectProperty::Property {
3915                        key,
3916                        value: Box::new(value),
3917                        kind: PropertyKind::Value,
3918                        shorthand: false,
3919                        span: self.span_from(property_start),
3920                    });
3921                } else {
3922                    // Shorthand `{a}` / `{a = 1}` (the latter only inside a
3923                    // destructuring pattern).
3924                    let PropName::Literal(PropKey::Str(name)) = &key else {
3925                        return Err(self.error("expecting ':' after a property name"));
3926                    };
3927                    let ident_span = self.span_from(property_start);
3928                    let ident = Ident {
3929                        name: name.clone(),
3930                        span: ident_span,
3931                    };
3932                    self.check_identifier(&ident.name, ident.span)?;
3933                    let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
3934                    if self.at_punct(Punct::Eq) {
3935                        // CoverInitializedName: only legal once the object turns
3936                        // out to be a destructuring pattern.
3937                        self.cover_inits.push(ident_span);
3938                        self.bump()?;
3939                        let default = self.parse_assignment(true)?;
3940                        let target = Pattern::new(PatternKind::Ident(ident), ident_span);
3941                        value = Expr::new(
3942                            ExprKind::Assign {
3943                                op: AssignOp::Assign,
3944                                target: Box::new(target),
3945                                value: Box::new(default),
3946                            },
3947                            ident_span,
3948                        );
3949                    }
3950                    properties.push(ObjectProperty::Property {
3951                        key,
3952                        value: Box::new(value),
3953                        kind: PropertyKind::Value,
3954                        shorthand: true,
3955                        span: ident_span,
3956                    });
3957                }
3958            }
3959            if !self.eat_punct(Punct::Comma)? {
3960                break;
3961            }
3962        }
3963        self.expect_punct(Punct::RBrace)?;
3964        Ok(Expr::new(
3965            ExprKind::Object(properties),
3966            self.span_from(start),
3967        ))
3968    }
3969
3970    fn parse_template(&mut self) -> Result<TemplateLiteral> {
3971        let mut quasis = Vec::new();
3972        let mut expressions = Vec::new();
3973        loop {
3974            let (cooked, raw, kind) = match self.current.kind.clone() {
3975                TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
3976                _ => return Err(self.error("expecting a template literal")),
3977            };
3978            let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
3979            quasis.push(TemplateChunk { cooked, raw, tail });
3980            if tail {
3981                self.bump()?;
3982                break;
3983            }
3984            self.bump()?; // move to the first token of the substitution
3985            let expr = self.parse_expression(true)?;
3986            expressions.push(expr);
3987            if !self.at_punct(Punct::RBrace) {
3988                return Err(self.error("expecting '}' in a template substitution"));
3989            }
3990            let brace = self.current.span.start;
3991            let token = self.lexer.re_scan_template_continue(brace)?;
3992            self.current = token;
3993        }
3994        Ok(TemplateLiteral {
3995            quasis,
3996            expressions,
3997        })
3998    }
3999}
4000
4001/// Which kind of function is being parsed (affects whether a name is required).
4002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4003enum FunctionForm {
4004    Declaration,
4005    Expression,
4006}
4007
4008/// Names of the parameters that participate in declaration-conflict checks.
4009///
4010/// Engines only check *simple* (identifier) parameters against the body's
4011/// lexical declarations: `function f(a) { let a; }` is an early error, but
4012/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
4013/// deliberately follows the reference rather than ES2025 §10.2.1).
4014fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
4015    params
4016        .iter()
4017        .filter_map(|param| match &param.kind {
4018            PatternKind::Ident(id) => Some(id.name.clone()),
4019            _ => None,
4020        })
4021        .collect()
4022}
4023
4024/// Collect the names a top-level module item declares, for the exported-name
4025/// check.
4026fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
4027    match &stmt.kind {
4028        StmtKind::VarDecl(decl) => {
4029            for declarator in &decl.declarators {
4030                let mut names = Vec::new();
4031                declarator.target.bound_names(&mut names);
4032                out.extend(names.into_iter().map(|n| n.name));
4033            }
4034        }
4035        StmtKind::FuncDecl(func) => {
4036            if let Some(name) = &func.name {
4037                out.push(name.name.clone());
4038            }
4039        }
4040        StmtKind::ClassDecl(class) => {
4041            if let Some(name) = &class.name {
4042                out.push(name.name.clone());
4043            }
4044        }
4045        StmtKind::Import(decl) => {
4046            for specifier in &decl.specifiers {
4047                match specifier {
4048                    ImportSpecifier::Default(id) => out.push(id.name.clone()),
4049                    ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
4050                    ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
4051                }
4052            }
4053        }
4054        StmtKind::Export(decl) => match &decl.kind {
4055            ExportKind::Declaration(inner) => collect_module_binding(inner, out),
4056            ExportKind::Default(expr) => match &expr.unparen().kind {
4057                ExprKind::Function(func) => {
4058                    if let Some(name) = &func.name {
4059                        out.push(name.name.clone());
4060                    }
4061                }
4062                ExprKind::Class(class) => {
4063                    if let Some(name) = &class.name {
4064                        out.push(name.name.clone());
4065                    }
4066                }
4067                _ => {}
4068            },
4069            _ => {}
4070        },
4071        _ => {}
4072    }
4073}
4074
4075/// Whether `inner` is fully inside `outer` (byte offset comparison only).
4076fn span_contains(outer: Span, inner: Span) -> bool {
4077    inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
4078}
4079
4080fn is_property_key_start(kind: &TokenKind) -> bool {
4081    matches!(
4082        kind,
4083        TokenKind::Ident(_)
4084            | TokenKind::Keyword(_)
4085            | TokenKind::String(_)
4086            | TokenKind::Number(_)
4087            | TokenKind::Punct(Punct::LBracket)
4088            | TokenKind::Punct(Punct::Hash)
4089    )
4090}
4091
4092/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
4093#[derive(Debug, Clone, Copy)]
4094enum BinOp {
4095    Binary(BinaryOp),
4096    Logical(LogicalOp),
4097}
4098
4099impl BinOp {
4100    fn is_right_associative(self) -> bool {
4101        matches!(self, BinOp::Binary(BinaryOp::Pow))
4102    }
4103}
4104
4105fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
4106    use BinaryOp as B;
4107    use LogicalOp as L;
4108    let result = match kind {
4109        TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
4110        TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
4111        TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
4112        TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
4113        TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
4114        TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
4115        TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
4116        TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
4117        TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
4118        TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
4119        TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
4120        TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
4121        TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
4122        TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
4123        TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
4124        TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
4125        TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
4126        TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
4127        TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
4128        TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
4129        TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
4130        TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
4131        TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
4132        TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
4133        TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
4134        _ => return None,
4135    };
4136    Some(result)
4137}
4138
4139fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
4140    match op {
4141        BinOp::Binary(op) => Ok(Expr::at_operator(
4142            ExprKind::Binary {
4143                op,
4144                left: Box::new(left),
4145                right: Box::new(right),
4146            },
4147            span,
4148            op_pos,
4149        )),
4150        BinOp::Logical(op) => {
4151            // `??` may not be mixed with `&&`/`||` without parentheses.
4152            // A parenthesised operand is visibly a different production, so the
4153            // check must look at the raw node, not through `Paren`.
4154            let mixes = |expr: &Expr, op: LogicalOp| {
4155                matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
4156                    if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
4157            };
4158            if mixes(&left, op) || mixes(&right, op) {
4159                return Err(SyntaxError::new(
4160                    "cannot mix '??' with '&&' or '||' without parentheses",
4161                    span,
4162                ));
4163            }
4164            Ok(Expr::at_operator(
4165                ExprKind::Logical {
4166                    op,
4167                    left: Box::new(left),
4168                    right: Box::new(right),
4169                },
4170                span,
4171                op_pos,
4172            ))
4173        }
4174    }
4175}
4176
4177/// Rebuild an expression from a pattern (used when a pattern has to go back
4178/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
4179fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
4180    match pattern.kind {
4181        PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
4182        PatternKind::Assign { target, default } => Expr::new(
4183            ExprKind::Assign {
4184                op: AssignOp::Assign,
4185                target,
4186                value: default,
4187            },
4188            span,
4189        ),
4190        PatternKind::Array { elements, rest } => {
4191            let mut out = Vec::new();
4192            for element in elements {
4193                match element {
4194                    Some(PatternElement::Pattern(pattern)) => {
4195                        let span = pattern.span;
4196                        out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
4197                            pattern, span,
4198                        )))));
4199                    }
4200                    Some(PatternElement::Property { .. }) | None => out.push(None),
4201                }
4202            }
4203            if let Some(rest) = rest {
4204                let RestElement::Pattern(pattern) = *rest else {
4205                    return Expr::new(ExprKind::Null, span);
4206                };
4207                let span = pattern.span;
4208                out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
4209                    pattern, span,
4210                )))));
4211            }
4212            Expr::new(ExprKind::Array { elements: out }, span)
4213        }
4214        _ => Expr::new(ExprKind::Null, span),
4215    }
4216}
4217
4218impl Pattern {
4219    /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
4220    /// this keeps call sites uniform with [`Expr::unparen`]).
4221    fn unparen_kind(&self) -> &PatternKind {
4222        &self.kind
4223    }
4224}