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