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