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