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        })
2515    }
2516
2517    fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
2518        // Every parameter list, from every entry point (function declaration/expression,
2519        // method, arrow, dynamic `new Function`): the flag makes `yield`/`await` an early
2520        // error there, and is restored on the way out so a *nested* function's body — which
2521        // is also reached from inside a default expression — is unaffected.
2522        let saved = self.in_formal_parameters;
2523        self.in_formal_parameters = true;
2524        let result = self.parse_formal_parameters_inner();
2525        self.in_formal_parameters = saved;
2526        result
2527    }
2528
2529    fn parse_formal_parameters_inner(&mut self) -> Result<Vec<Pattern>> {
2530        self.expect_punct(Punct::LParen)?;
2531        let mut params = Vec::new();
2532        loop {
2533            if self.at_punct(Punct::RParen) {
2534                break;
2535            }
2536            if self.at_punct(Punct::Ellipsis) {
2537                self.bump()?;
2538                // The rest parameter's own binding needs the same check: `function f(...)`
2539                // is a missing parameter, not a malformed one.
2540                if !self.at_formal_parameter() {
2541                    return Err(self.error("missing formal parameter"));
2542                }
2543                let target = self.parse_binding_target()?;
2544                if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
2545                    return Err(
2546                        self.error_at("rest element cannot have a default value", target.span)
2547                    );
2548                }
2549                params.push(Pattern::new(
2550                    PatternKind::Rest(Box::new(target.clone())),
2551                    target.span,
2552                ));
2553                // A rest parameter ends the list, so the only thing that may follow is
2554                // `)`. The reference simply asks for it: `js_parse_expect(s, ')')`.
2555                if self.at_punct(Punct::Comma) {
2556                    return Err(self.error("expecting ')'"));
2557                }
2558                break;
2559            }
2560            if !self.at_formal_parameter() {
2561                return Err(self.error("missing formal parameter"));
2562            }
2563            let param = self.parse_binding_element()?;
2564            self.check_parameter(&param)?;
2565            params.push(param);
2566            if !self.eat_punct(Punct::Comma)? {
2567                break;
2568            }
2569        }
2570        self.expect_punct(Punct::RParen)?;
2571        Ok(params)
2572    }
2573
2574    fn check_parameter(&self, param: &Pattern) -> Result<()> {
2575        match &param.kind {
2576            PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
2577            PatternKind::Assign { target, .. } => self.check_parameter(target),
2578            _ => Ok(()),
2579        }
2580    }
2581
2582    fn parse_function_body(
2583        &mut self,
2584        params: Vec<Pattern>,
2585        is_method: bool,
2586    ) -> Result<(Vec<Pattern>, Span, FunctionBody, bool)> {
2587        let params_span = self.prev_end;
2588        // Strictness is per function, so the body saves and restores it itself rather
2589        // than trusting every caller to do so: `function f(){ "use strict" }` must
2590        // leave the code after it sloppy, and the enclosing scope may well have been
2591        // strict too. The returned flag is the body's own mode.
2592        let saved_strict = self.strict;
2593        if !self.at_punct(Punct::LBrace) {
2594            return Err(self.unexpected());
2595        }
2596        // A function body is one of the places a `using` may live, so a function defined
2597        // inside a `case` clause starts with a clean slate for that check.
2598        let saved_in_case = self.in_case_clause;
2599        self.in_case_clause = false;
2600        let param_names = simple_parameter_names(&params);
2601        let simple_params = params
2602            .iter()
2603            .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
2604        let mut body = Vec::new();
2605        let mut prologue = true;
2606        let mut strict_seen = false;
2607        self.bump()?; // {
2608        // Where the final duplicate-parameter check points: the reference runs it with the
2609        // body's first token as `s->token`, so an empty body reports the `}` and
2610        // `{ return 1 }` reports the `return`.
2611        let body_start = self.current.span;
2612        self.push_scope(Scope::function(param_names));
2613        while !self.at_punct(Punct::RBrace) {
2614            if self.current.is_eof() {
2615                return Err(self.unexpected());
2616            }
2617            let stmt = self.parse_statement_list_item()?;
2618            if prologue {
2619                match self.directive_value(&stmt) {
2620                    Some(directive) if directive == "use strict" => {
2621                        strict_seen = true;
2622                        self.enter_strict()?;
2623                    }
2624                    Some(_) => {}
2625                    None => prologue = false,
2626                }
2627            }
2628            body.push(stmt);
2629        }
2630        self.pop_scope();
2631        self.bump()?; // }
2632        // The body's own mode, still in force while the early errors below are
2633        // checked; the enclosing mode is restored once they are done.
2634        let body_strict = self.strict;
2635        if strict_seen && !simple_params {
2636            return Err(self.error_at(
2637                // The reference spells the directive with double quotes inside the message.
2638                "\"use strict\" not allowed in function with default or destructuring parameter",
2639                Span::new(params_span, params_span),
2640            ));
2641        }
2642        // Duplicate parameter names. Where they are illegal at all is the reference's
2643        // condition in `js_parse_function_args`: strict mode, a non-simple list, an arrow,
2644        // or a method. A plain sloppy `function f(a, a){}` is legal (last wins), and so is
2645        // a sloppy generator or `async function` — only an async *method* is covered.
2646        //
2647        // Which of the two messages is used depends on how the duplicate was reached, and
2648        // that is a different question: at *parameter-parse* time the reference checks each
2649        // name with `duplicate parameter names`, and it only gets there when the list holds
2650        // an `=` anywhere or the name sits inside a destructuring pattern. Everything else
2651        // waits for the check above, which says `duplicate argument names`.
2652        self.check_duplicate_parameters(
2653            &params,
2654            body_strict || !simple_params || is_method,
2655            body_start,
2656        )?;
2657        let params_span_value = Span::new(params_span, params_span);
2658        self.strict = saved_strict;
2659        self.lexer.set_strict(saved_strict);
2660        self.in_case_clause = saved_in_case;
2661        Ok((
2662            params,
2663            params_span_value,
2664            FunctionBody::Block(body),
2665            body_strict,
2666        ))
2667    }
2668
2669    // -- classes -----------------------------------------------------------
2670
2671    fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
2672        // "classes are parsed and executed in strict mode" — `js_parse_class` says so by
2673        // setting `JS_MODE_STRICT` before it consumes the `class` token, which makes the
2674        // *name*, the heritage and every member strict, not just the method bodies.
2675        //
2676        // Without this, a method body was parsed sloppy: `class C { m() { x = 1 } }` created
2677        // a global instead of throwing, and every method's `mode:` line in the disassembly
2678        // disagreed with the reference.
2679        let saved_strict = self.strict;
2680        let enter = self.enter_strict();
2681        let result = match enter {
2682            Ok(()) => self.parse_class_body(is_expression),
2683            Err(error) => Err(error),
2684        };
2685        self.strict = saved_strict;
2686        self.lexer.set_strict(saved_strict);
2687        result
2688    }
2689
2690    fn parse_class_body(&mut self, is_expression: bool) -> Result<Class> {
2691        let start = self.current.span.start;
2692        self.bump()?; // class
2693        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
2694            if is_expression {
2695                Some(self.expect_ident()?)
2696            } else {
2697                Some(self.expect_binding_ident()?)
2698            }
2699        } else {
2700            if !is_expression {
2701                return Err(self.error("class statement requires a name"));
2702            }
2703            None
2704        };
2705        let super_class = if self.eat_keyword(Keyword::Extends)? {
2706            Some(Box::new(self.parse_lhs_expression()?))
2707        } else {
2708            None
2709        };
2710        let has_super = super_class.is_some();
2711        self.private.push(PrivateEnv::default());
2712        self.expect_punct(Punct::LBrace)?;
2713        let mut elements = Vec::new();
2714        let mut seen_constructor = false;
2715        let result = (|| -> Result<()> {
2716            while !self.at_punct(Punct::RBrace) {
2717                // No end-of-input guard here: `class A {` must report `invalid property
2718                // name`, which is what falls out of asking for the element's name. An
2719                // early `unexpected()` would pre-empt that with a vaguer message.
2720                if self.eat_punct(Punct::Semicolon)? {
2721                    continue;
2722                }
2723                elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
2724            }
2725            Ok(())
2726        })();
2727        self.private.pop();
2728        result?;
2729        // The `}` itself, before it is consumed: a class with no written constructor gets
2730        // a synthetic one created *at* this token (see [`Class::body_end`]).
2731        let body_end = self.current.span.start;
2732        self.bump()?; // }
2733        Ok(Class {
2734            name,
2735            super_class,
2736            elements,
2737            span: self.span_from(start),
2738            body_end,
2739        })
2740    }
2741
2742    /// `static { … }`, with `static` already consumed and `{` the current token.
2743    ///
2744    /// The body is parsed in a context of its own. It is written as a block, but the
2745    /// reference compiles it as a function, and every early error below follows from
2746    /// that: `this` is the class, `super.x` resolves against the class's home object, but
2747    /// `super()` is not a thing a static block can do and `return` has no function to
2748    /// return from.
2749    fn parse_static_block(&mut self, start: Position) -> Result<ClassElement> {
2750        let saved = self.ctx;
2751        let saved_top = self.top_level;
2752        self.ctx = FnCtx {
2753            in_function: true,
2754            in_generator: false,
2755            in_async: false,
2756            // `super.x` is legal in a static block: its home object is the class.
2757            in_method: true,
2758            in_derived_constructor: false,
2759            in_static_block: true,
2760            arguments_allowed: false,
2761        };
2762        self.top_level = false;
2763        // A class body is strict, so everything in it is — including a static block. The
2764        // restore is unconditional, unlike a `"use strict"` directive's, because the block
2765        // cannot opt out of what the class already decided. `enter_strict` cannot fail
2766        // here (it only objects to an octal literal, and nothing has been scanned yet), but
2767        // it is spelled as a saved result so the context is restored either way.
2768        let saved_strict = self.strict;
2769        let enter = self.enter_strict();
2770        // A `break` or `continue` cannot escape a static block, so the label and loop
2771        // counters start empty.
2772        let saved_loop = self.loop_depth;
2773        let saved_switch = self.switch_depth;
2774        let saved_labels = std::mem::take(&mut self.labels);
2775        self.loop_depth = 0;
2776        self.switch_depth = 0;
2777        let body_start = self.current.span.start;
2778        let body = match enter {
2779            Ok(()) => self.parse_block(),
2780            Err(error) => Err(error),
2781        };
2782        self.strict = saved_strict;
2783        self.lexer.set_strict(saved_strict);
2784        self.ctx = saved;
2785        self.top_level = saved_top;
2786        self.loop_depth = saved_loop;
2787        self.switch_depth = saved_switch;
2788        self.labels = saved_labels;
2789        let body = body?;
2790        Ok(ClassElement::StaticBlock {
2791            body,
2792            body_start,
2793            span: self.span_from(start),
2794        })
2795    }
2796
2797    fn parse_class_element(
2798        &mut self,
2799        has_super: bool,
2800        seen_constructor: &mut bool,
2801    ) -> Result<ClassElement> {
2802        let start = self.current.span.start;
2803        let mut is_static = false;
2804        if self.at_ident("static") {
2805            let peek = self.peek()?;
2806            let is_modifier = !matches!(
2807                peek.kind,
2808                TokenKind::Punct(Punct::LParen)
2809                    | TokenKind::Punct(Punct::Eq)
2810                    | TokenKind::Punct(Punct::Semicolon)
2811                    | TokenKind::Punct(Punct::RBrace)
2812            );
2813            if is_modifier {
2814                self.bump()?; // static
2815                if self.at_punct(Punct::LBrace) {
2816                    return self.parse_static_block(start);
2817                }
2818                is_static = true;
2819            }
2820        }
2821
2822        // Modifiers: async, get, set, *
2823        let mut is_async = false;
2824        let mut is_generator = false;
2825        let mut accessor: Option<MethodKind> = None;
2826        if self.at_ident("async") {
2827            let peek = self.peek()?;
2828            let is_modifier = !matches!(
2829                peek.kind,
2830                TokenKind::Punct(Punct::LParen)
2831                    | TokenKind::Punct(Punct::Eq)
2832                    | TokenKind::Punct(Punct::Semicolon)
2833                    | TokenKind::Punct(Punct::RBrace)
2834            ) && !peek.newline_before;
2835            if is_modifier {
2836                self.bump()?;
2837                is_async = true;
2838            }
2839        }
2840        if self.at_punct(Punct::Star) {
2841            self.bump()?;
2842            is_generator = true;
2843        }
2844        if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
2845            let is_get = self.at_ident("get");
2846            let peek = self.peek()?;
2847            if is_property_key_start(&peek.kind) {
2848                self.bump()?;
2849                accessor = Some(if is_get {
2850                    MethodKind::Get
2851                } else {
2852                    MethodKind::Set
2853                });
2854            }
2855        }
2856        let key = self.parse_property_key()?;
2857
2858        // `#constructor` is not a name a private member may have, in any of its forms — a
2859        // method, an accessor or a field. Reported at the token after the name (`(`, `=`, `;`),
2860        // which is where the reference's `js_parse_error` points.
2861        if matches!(&key, PropName::Private(ident) if ident.name == "constructor") {
2862            return Err(self.error("invalid method name"));
2863        }
2864        // Nor may `constructor` carry a method modifier: `constructor` is the one member name
2865        // that has its own production, so a generator, an async method or an accessor called
2866        // `constructor` is `invalid method name`. A `static constructor` is an ordinary
2867        // method, and a field named `constructor` is rejected further down with its own
2868        // message.
2869        if !is_static
2870            && (is_generator || is_async || accessor.is_some())
2871            && matches!(&key, PropName::Literal(PropKey::Str(name)) if name.as_str() == Some("constructor"))
2872        {
2873            return Err(self.error("invalid method name"));
2874        }
2875
2876        // Private names must be registered (duplicates are early errors).
2877        if let PropName::Private(ident) = &key {
2878            if let Some(env) = self.private.last_mut() {
2879                if !env.declare(&ident.name, accessor, is_static) {
2880                    return Err(self.error_at(
2881                        // The reference words this without the name:
2882                        // `js_parse_error(s, "private class field is already defined")`.
2883                        "private class field is already defined".to_string(),
2884                        ident.span,
2885                    ));
2886                }
2887            }
2888        }
2889
2890        if self.at_punct(Punct::LParen) {
2891            let kind = match accessor {
2892                Some(kind) => kind,
2893                None => {
2894                    let is_constructor = !is_static
2895                        && !is_generator
2896                        && !is_async
2897                        && matches!(&key, PropName::Literal(PropKey::Str(s)) if s.as_str() == Some("constructor"));
2898                    if is_constructor {
2899                        if *seen_constructor {
2900                            return Err(self.error_at(
2901                                "property constructor appears more than once",
2902                                self.span_from(start),
2903                            ));
2904                        }
2905                        *seen_constructor = true;
2906                        MethodKind::Constructor
2907                    } else {
2908                        MethodKind::Method
2909                    }
2910                }
2911            };
2912            if kind == MethodKind::Constructor && (is_generator || is_async) {
2913                return Err(self.error("a constructor may not be a generator or async"));
2914            }
2915            let saved = self.ctx;
2916            self.ctx = FnCtx {
2917                in_function: true,
2918                in_generator: is_generator,
2919                in_async: is_async,
2920                in_method: true,
2921                in_derived_constructor: kind == MethodKind::Constructor && has_super,
2922                in_static_block: false,
2923                arguments_allowed: true,
2924            };
2925            let saved_top = self.top_level;
2926            self.top_level = false;
2927            let result = (|| -> Result<Function> {
2928                let params = self.parse_formal_parameters()?;
2929                let (params, params_span, body, strict) = self.parse_function_body(params, true)?;
2930                Ok(Function {
2931                    name: None,
2932                    params,
2933                    body,
2934                    is_async,
2935                    is_generator,
2936                    strict,
2937                    is_arrow: false,
2938                    span: self.span_from(start),
2939                    params_span,
2940                })
2941            })();
2942            self.ctx = saved;
2943            self.top_level = saved_top;
2944            let func = result?;
2945            if is_static {
2946                if let PropName::Literal(PropKey::Str(name)) = &key {
2947                    if name == "prototype" {
2948                        return Err(self.error_at("invalid method name", func.span));
2949                    }
2950                }
2951            }
2952            if kind == MethodKind::Get && !func.params.is_empty() {
2953                return Err(self.error_at(
2954                    "invalid number of arguments for getter or setter",
2955                    func.span,
2956                ));
2957            }
2958            if kind == MethodKind::Set && func.params.len() != 1 {
2959                return Err(self.error_at(
2960                    "invalid number of arguments for getter or setter",
2961                    func.span,
2962                ));
2963            }
2964            return Ok(ClassElement::Method {
2965                key,
2966                is_static,
2967                kind,
2968                func: Box::new(func),
2969                span: self.span_from(start),
2970            });
2971        }
2972
2973        // Field definition.
2974        if accessor.is_some() {
2975            return Err(self.error("expecting '(' after an accessor name"));
2976        }
2977        if let PropName::Literal(PropKey::Str(name)) = &key {
2978            if name == "constructor" && !is_static {
2979                return Err(self.error("classes may not have a field named 'constructor'"));
2980            }
2981            if name == "prototype" && is_static {
2982                return Err(self.error("classes may not have a static property named 'prototype'"));
2983            }
2984        }
2985        // The initialiser is its own function — it runs per instance, or once for a
2986        // static field, with the class's home object — so it gets its own context. That
2987        // is what makes `super.x` legal in a field but `arguments` and `super()` not.
2988        let saved = self.ctx;
2989        let saved_top = self.top_level;
2990        self.ctx = FnCtx {
2991            in_function: true,
2992            in_generator: false,
2993            in_async: false,
2994            in_method: true,
2995            in_derived_constructor: false,
2996            in_static_block: false,
2997            arguments_allowed: false,
2998        };
2999        self.top_level = false;
3000        let value = self
3001            .eat_punct(Punct::Eq)?
3002            .then(|| self.parse_assignment(true));
3003        self.ctx = saved;
3004        self.top_level = saved_top;
3005        let value = match value {
3006            Some(value) => Some(Box::new(value?)),
3007            None => None,
3008        };
3009        // Fields are terminated by `;`, `}` or a line break.
3010        self.semicolon()?;
3011        Ok(ClassElement::Field {
3012            key,
3013            is_static,
3014            value,
3015            span: self.span_from(start),
3016        })
3017    }
3018
3019    // -- modules -----------------------------------------------------------
3020
3021    fn parse_import_decl(&mut self) -> Result<Stmt> {
3022        let start = self.current.span.start;
3023        self.bump()?; // import
3024        let mut specifiers = Vec::new();
3025        if let TokenKind::String(source) = self.current.kind.clone() {
3026            let source = as_specifier(&source);
3027            self.bump()?;
3028            let attributes = self.parse_import_attributes()?;
3029            self.semicolon()?;
3030            return Ok(Stmt::new(
3031                StmtKind::Import(Box::new(ImportDecl {
3032                    specifiers,
3033                    source,
3034                    attributes,
3035                    span: self.span_from(start),
3036                })),
3037                self.span_from(start),
3038            ));
3039        }
3040        // Default import.
3041        if matches!(self.current.kind, TokenKind::Ident(_)) {
3042            let local = self.expect_ident()?;
3043            specifiers.push(ImportSpecifier::Default(local));
3044            if !self.eat_punct(Punct::Comma)? {
3045                return self.finish_import(start, specifiers);
3046            }
3047        }
3048        if self.at_punct(Punct::Star) {
3049            self.bump()?;
3050            if !self.eat_contextual("as")? {
3051                return Err(self.unexpected());
3052            }
3053            let local = self.expect_ident()?;
3054            specifiers.push(ImportSpecifier::Namespace(local));
3055            return self.finish_import(start, specifiers);
3056        }
3057        if self.at_punct(Punct::LBrace) {
3058            self.bump()?;
3059            while !self.at_punct(Punct::RBrace) {
3060                let imported = self.parse_module_name()?;
3061                let local = if self.eat_contextual("as")? {
3062                    self.expect_ident()?
3063                } else {
3064                    match &imported {
3065                        ModuleName::Ident(id) => id.clone(),
3066                        ModuleName::Str(_) => {
3067                            return Err(self.error_at(
3068                                "a string module name must be followed by 'as'",
3069                                self.current.span,
3070                            ));
3071                        }
3072                    }
3073                };
3074                specifiers.push(ImportSpecifier::Named { imported, local });
3075                if !self.eat_punct(Punct::Comma)? {
3076                    break;
3077                }
3078            }
3079            self.expect_punct(Punct::RBrace)?;
3080        } else if !specifiers.is_empty() {
3081            return Err(self.unexpected());
3082        } else if self.at_punct(Punct::LBrace) {
3083            unreachable!("handled above");
3084        } else {
3085            return Err(self.unexpected());
3086        }
3087        self.finish_import(start, specifiers)
3088    }
3089
3090    fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
3091        if !self.eat_contextual("from")? {
3092            return Err(self.unexpected());
3093        }
3094        let TokenKind::String(source) = self.current.kind.clone() else {
3095            return Err(self.error("string expected"));
3096        };
3097        let source = as_specifier(&source);
3098        self.bump()?;
3099        let attributes = self.parse_import_attributes()?;
3100        self.semicolon()?;
3101        let span = self.span_from(start);
3102        for specifier in &specifiers {
3103            let local = match specifier {
3104                ImportSpecifier::Default(id) => id,
3105                ImportSpecifier::Namespace(id) => id,
3106                ImportSpecifier::Named { local, .. } => local,
3107            };
3108            self.declare_lexical(&local.name)?;
3109            if let Some(scope) = self.scopes.last_mut()
3110                && !scope.import_names.iter().any(|n| n == &local.name)
3111            {
3112                scope.import_names.push(local.name.clone());
3113            }
3114        }
3115        Ok(Stmt::new(
3116            StmtKind::Import(Box::new(ImportDecl {
3117                specifiers,
3118                source,
3119                attributes,
3120                span,
3121            })),
3122            span,
3123        ))
3124    }
3125
3126    fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
3127        let mut attributes = Vec::new();
3128        let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
3129        if !has_with {
3130            return Ok(attributes);
3131        }
3132        let peek = self.peek()?;
3133        if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
3134            return Ok(attributes);
3135        }
3136        self.bump()?; // with / assert
3137        self.expect_punct(Punct::LBrace)?;
3138        while !self.at_punct(Punct::RBrace) {
3139            let attr_start = self.current.span.start;
3140            let key = match self.current.kind.clone() {
3141                TokenKind::Ident(name) => name,
3142                TokenKind::String(value) => as_specifier(&value),
3143                _ => return Err(self.error("expecting an import attribute name")),
3144            };
3145            self.bump()?;
3146            self.expect_punct(Punct::Colon)?;
3147            let TokenKind::String(value) = self.current.kind.clone() else {
3148                return Err(self.error("expecting an import attribute value string"));
3149            };
3150            let value = as_specifier(&value);
3151            self.bump()?;
3152            attributes.push(ImportAttribute {
3153                key,
3154                value,
3155                span: self.span_from(attr_start),
3156            });
3157            if !self.eat_punct(Punct::Comma)? {
3158                break;
3159            }
3160        }
3161        self.expect_punct(Punct::RBrace)?;
3162        Ok(attributes)
3163    }
3164
3165    fn parse_module_name(&mut self) -> Result<ModuleName> {
3166        match self.current.kind.clone() {
3167            TokenKind::String(value) => {
3168                self.bump()?;
3169                Ok(ModuleName::Str(as_specifier(&value)))
3170            }
3171            TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
3172            TokenKind::Keyword(kw) => {
3173                let span = self.current.span;
3174                self.bump()?;
3175                Ok(ModuleName::Ident(Ident {
3176                    name: kw.as_str().to_string(),
3177                    span,
3178                }))
3179            }
3180            // `export {a as}`: the alias may be an identifier or a string, and the
3181            // reference names both (`js_parse_error(s, "identifier or string expected")`).
3182            _ => Err(self.error("identifier or string expected")),
3183        }
3184    }
3185
3186    fn parse_export_decl(&mut self) -> Result<Stmt> {
3187        let start = self.current.span.start;
3188        self.bump()?; // export
3189        if self.at_punct(Punct::Star) {
3190            self.bump()?;
3191            let mut exported = None;
3192            if self.eat_contextual("as")? {
3193                exported = Some(self.parse_module_name()?);
3194            }
3195            if !self.eat_contextual("from")? {
3196                return Err(self.error("expecting 'from' after 'export *'"));
3197            }
3198            let TokenKind::String(source) = self.current.kind.clone() else {
3199                return Err(self.error("string expected"));
3200            };
3201            let source = as_specifier(&source);
3202            self.bump()?;
3203            let attributes = self.parse_import_attributes()?;
3204            self.semicolon()?;
3205            let span = self.span_from(start);
3206            return Ok(Stmt::new(
3207                StmtKind::Export(Box::new(ExportDecl {
3208                    kind: ExportKind::All {
3209                        source,
3210                        exported,
3211                        attributes,
3212                    },
3213                    span,
3214                })),
3215                span,
3216            ));
3217        }
3218        if self.eat_keyword(Keyword::Default)? {
3219            let value = if self.at_keyword(Keyword::Function) {
3220                let func = self.parse_function(FunctionForm::Expression, false, None)?;
3221                Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3222            } else if self.at_ident("async") {
3223                let peek = self.peek()?;
3224                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
3225                    self.bump()?;
3226                    let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
3227                    Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
3228                } else {
3229                    self.parse_assignment(true)?
3230                }
3231            } else if self.at_keyword(Keyword::Class) {
3232                let class = self.parse_class(true)?;
3233                Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
3234            } else {
3235                let expr = self.parse_assignment(true)?;
3236                self.semicolon()?;
3237                expr
3238            };
3239            let span = self.span_from(start);
3240            return Ok(Stmt::new(
3241                StmtKind::Export(Box::new(ExportDecl {
3242                    kind: ExportKind::Default(Box::new(value)),
3243                    span,
3244                })),
3245                span,
3246            ));
3247        }
3248        if self.at_keyword(Keyword::Var)
3249            || self.at_keyword(Keyword::Const)
3250            || self.at_keyword(Keyword::Function)
3251            || self.at_keyword(Keyword::Class)
3252            || (self.at_ident("let") && self.let_starts_declaration()?)
3253        {
3254            let decl = self.parse_statement_list_item()?;
3255            let span = self.span_from(start);
3256            return Ok(Stmt::new(
3257                StmtKind::Export(Box::new(ExportDecl {
3258                    kind: ExportKind::Declaration(Box::new(decl)),
3259                    span,
3260                })),
3261                span,
3262            ));
3263        }
3264        if self.at_ident("async") {
3265            let peek = self.peek()?;
3266            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
3267                let decl = self.parse_statement_list_item()?;
3268                let span = self.span_from(start);
3269                return Ok(Stmt::new(
3270                    StmtKind::Export(Box::new(ExportDecl {
3271                        kind: ExportKind::Declaration(Box::new(decl)),
3272                        span,
3273                    })),
3274                    span,
3275                ));
3276            }
3277        }
3278        if self.at_punct(Punct::LBrace) {
3279            self.bump()?;
3280            let mut specifiers = Vec::new();
3281            let mut candidates: Vec<(String, Span)> = Vec::new();
3282            let mut source = None;
3283            while !self.at_punct(Punct::RBrace) {
3284                let spec_start = self.current.span.start;
3285                let local = self.parse_module_name()?;
3286                let exported = if self.eat_contextual("as")? {
3287                    self.parse_module_name()?
3288                } else {
3289                    local.clone()
3290                };
3291                // Deferred: whether these name *local* bindings (and so have to be
3292                // checked against the module's declarations) depends on whether a
3293                // `from` follows, which is not known until the closing brace.
3294                if let ModuleName::Ident(id) = &local {
3295                    candidates.push((id.name.clone(), id.span));
3296                }
3297                specifiers.push(ExportSpecifier {
3298                    local,
3299                    exported,
3300                    span: self.span_from(spec_start),
3301                });
3302                if !self.eat_punct(Punct::Comma)? {
3303                    break;
3304                }
3305            }
3306            self.expect_punct(Punct::RBrace)?;
3307            let mut attributes = Vec::new();
3308            let has_from = self.eat_contextual("from")?;
3309            if !has_from {
3310                // `export { a }` re-exports a binding of this module and must name one;
3311                // `export { a } from "m"` names an export of `m` and is checked when the
3312                // module is linked, not here.
3313                self.pending_exports.extend(candidates);
3314            }
3315            if has_from {
3316                let TokenKind::String(value) = self.current.kind.clone() else {
3317                    return Err(self.error("string expected"));
3318                };
3319                let value = as_specifier(&value);
3320                self.bump()?;
3321                source = Some(value);
3322                attributes = self.parse_import_attributes()?;
3323            }
3324            self.semicolon()?;
3325            let span = self.span_from(start);
3326            return Ok(Stmt::new(
3327                StmtKind::Export(Box::new(ExportDecl {
3328                    kind: ExportKind::Named {
3329                        specifiers,
3330                        source,
3331                        attributes,
3332                    },
3333                    span,
3334                })),
3335                span,
3336            ));
3337        }
3338        Err(self.unexpected())
3339    }
3340
3341    // -- patterns from expressions ----------------------------------------
3342
3343    fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
3344        self.expr_to_pattern_inner(expr, kind, false)
3345    }
3346
3347    fn expr_to_pattern_inner(
3348        &mut self,
3349        expr: Expr,
3350        kind: TargetKind,
3351        nested: bool,
3352    ) -> Result<Pattern> {
3353        let span = expr.span;
3354        match expr.kind {
3355            ExprKind::Ident(ident) => {
3356                if kind == TargetKind::Binding {
3357                    self.check_binding_name(&ident.name, ident.span)?;
3358                } else {
3359                    self.check_identifier(&ident.name, ident.span)?;
3360                    if self.strict && (ident.name == "eval" || ident.name == "arguments") {
3361                        return Err(self.error_at(
3362                            format!("invalid assignment to '{}' in strict mode", ident.name),
3363                            ident.span,
3364                        ));
3365                    }
3366                }
3367                Ok(Pattern::new(PatternKind::Ident(ident), span))
3368            }
3369            ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
3370            ExprKind::Array { elements } => {
3371                let mut out = Vec::new();
3372                let mut rest = None;
3373                let count = elements.len();
3374                for (index, element) in elements.into_iter().enumerate() {
3375                    match element {
3376                        None => out.push(None),
3377                        Some(ArrayElement::Expr(expr)) => {
3378                            let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
3379                            out.push(Some(PatternElement::Pattern(pattern)));
3380                        }
3381                        Some(ArrayElement::Spread(expr)) => {
3382                            if index + 1 != count {
3383                                return Err(
3384                                    self.error_at("rest element must be the last one", expr.span)
3385                                );
3386                            }
3387                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3388                        }
3389                    }
3390                }
3391                Ok(Pattern::new(
3392                    PatternKind::Array {
3393                        elements: out,
3394                        rest,
3395                    },
3396                    span,
3397                ))
3398            }
3399            ExprKind::Object(properties) => {
3400                self.cover_inits
3401                    .retain(|cover| !span_contains(span, *cover));
3402                let mut out = Vec::new();
3403                let mut rest = None;
3404                let count = properties.len();
3405                for (index, property) in properties.into_iter().enumerate() {
3406                    match property {
3407                        ObjectProperty::Spread(expr) => {
3408                            if index + 1 != count {
3409                                return Err(
3410                                    self.error_at("rest element must be the last one", expr.span)
3411                                );
3412                            }
3413                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
3414                        }
3415                        ObjectProperty::Property {
3416                            key,
3417                            value,
3418                            kind: _,
3419                            shorthand,
3420                            span,
3421                        } => {
3422                            let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
3423                            out.push(Some(PatternElement::Property {
3424                                key,
3425                                value: pattern,
3426                                shorthand,
3427                                span,
3428                            }));
3429                        }
3430                    }
3431                }
3432                Ok(Pattern::new(
3433                    PatternKind::Object {
3434                        properties: out,
3435                        rest,
3436                    },
3437                    span,
3438                ))
3439            }
3440            ExprKind::Assign { op, target, value } if op.is_simple() => {
3441                // `{a = 1}` inside a pattern: the target must itself be a pattern.
3442                let target = match target.kind {
3443                    PatternKind::Ident(ident) => {
3444                        Pattern::new(PatternKind::Ident(ident), target.span)
3445                    }
3446                    other => {
3447                        let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
3448                        self.expr_to_pattern_inner(expr, kind, nested)?
3449                    }
3450                };
3451                Ok(Pattern::new(
3452                    PatternKind::Assign {
3453                        target: Box::new(target),
3454                        default: value,
3455                    },
3456                    span,
3457                ))
3458            }
3459            ExprKind::Member {
3460                object,
3461                property,
3462                optional,
3463            } => {
3464                if kind == TargetKind::Binding {
3465                    return Err(self.error_at("invalid binding pattern", span));
3466                }
3467                if optional {
3468                    return Err(self.error_at("invalid assignment target", span));
3469                }
3470                let op_pos = expr.op_pos;
3471                Ok(Pattern::new(
3472                    PatternKind::Member(Box::new(MemberPattern {
3473                        object,
3474                        property,
3475                        span,
3476                        op_pos,
3477                    })),
3478                    span,
3479                ))
3480            }
3481            ExprKind::OptionalChain(_) => {
3482                Err(self.error_at("invalid assignment left-hand side", span))
3483            }
3484            // QuickJS reports `a() = 1` at run time (it evaluates the callee
3485            // first, then rejects the reference) but rejects the same thing
3486            // inside a destructuring pattern at parse time. Every other
3487            // non-assignable expression is rejected here.
3488            other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
3489                Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
3490            ),
3491            _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
3492            // Inside an object or array literal being reinterpreted as a pattern the
3493            // reference says `invalid destructuring target`; a non-reference at the top
3494            // level of an assignment says `invalid assignment left-hand side`. `nested` is
3495            // exactly that distinction — `[1] = 2` is the first, `1 = 2` the second.
3496            _ if nested => Err(self.error_at("invalid destructuring target", span)),
3497            _ => Err(self.error_at("invalid assignment left-hand side", span)),
3498        }
3499    }
3500
3501    fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
3502        // Array and object literals wrap their spread elements, so the target is
3503        // one level in.
3504        let expr = match expr.kind {
3505            ExprKind::Spread(inner) => *inner,
3506            other => Expr::new(other, expr.span),
3507        };
3508        if kind == TargetKind::Binding {
3509            return Ok(RestElement::Pattern(
3510                self.expr_to_pattern_inner(expr, kind, true)?,
3511            ));
3512        }
3513        match &expr.kind {
3514            ExprKind::Member { optional, .. } => {
3515                if *optional {
3516                    return Err(self.error_at("invalid assignment target", expr.span));
3517                }
3518                match self.expr_to_pattern_inner(expr, kind, true)?.kind {
3519                    PatternKind::Member(member) => Ok(RestElement::Member(member)),
3520                    _ => unreachable!("member expressions convert to member patterns"),
3521                }
3522            }
3523            _ => Ok(RestElement::Pattern(
3524                self.expr_to_pattern_inner(expr, kind, true)?,
3525            )),
3526        }
3527    }
3528
3529    // -- expressions -------------------------------------------------------
3530
3531    /// `Expression` (comma separated).
3532    fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
3533        self.enter()?;
3534        let result = self.parse_expression_unguarded(allow_in);
3535        self.leave();
3536        result
3537    }
3538
3539    fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
3540        // The flag is threaded down as an argument, but a few decisions in `parse_primary`
3541        // have no argument to read it from — `#x in o` is one. Mirroring it into the field
3542        // keeps those decisions able to see it, which is what makes `for (#f in v;;)` fail on
3543        // the `#f` instead of somewhere further along.
3544        let saved_allow_in = self.allow_in;
3545        self.allow_in = allow_in;
3546        let result = self.parse_expression_in(allow_in);
3547        self.allow_in = saved_allow_in;
3548        result
3549    }
3550
3551    fn parse_expression_in(&mut self, allow_in: bool) -> Result<Expr> {
3552        let start = self.current.span.start;
3553        let first = self.parse_assignment(allow_in)?;
3554        if !self.at_punct(Punct::Comma) {
3555            return Ok(first);
3556        }
3557        let mut items = vec![first];
3558        while self.eat_punct(Punct::Comma)? {
3559            items.push(self.parse_assignment(allow_in)?);
3560        }
3561        Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
3562    }
3563
3564    fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
3565        let start = self.current.span.start;
3566
3567        // `yield` in a generator — but never in its own formal parameters
3568        // (§15.5.1: `FormalParameters Contains YieldExpression` is a `SyntaxError`).
3569        if self.ctx.in_generator && self.at_ident("yield") {
3570            if self.in_formal_parameters {
3571                return Err(self.error_at("yield in default expression", self.current.span));
3572            }
3573            return self.parse_yield(allow_in);
3574        }
3575
3576        let lhs = match self.try_parse_arrow(allow_in)? {
3577            Some(arrow) => return Ok(arrow),
3578            None => self.parse_conditional(allow_in)?,
3579        };
3580
3581        if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
3582            let op_pos = self.current.span.start;
3583            let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
3584            self.bump()?;
3585            let value = self.parse_assignment(allow_in)?;
3586            return Ok(Expr::at_operator(
3587                ExprKind::Assign {
3588                    op,
3589                    target: Box::new(target),
3590                    value: Box::new(value),
3591                },
3592                self.span_from(start),
3593                op_pos,
3594            ));
3595        }
3596        let _ = start;
3597        Ok(lhs)
3598    }
3599
3600    fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
3601        let start = self.current.span.start;
3602        self.bump()?; // yield
3603        let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
3604            self.bump()?;
3605            true
3606        } else {
3607            false
3608        };
3609        let argument = if delegate {
3610            Some(Box::new(self.parse_assignment(allow_in)?))
3611        } else if self.current.newline_before
3612            || self.at_punct(Punct::RParen)
3613            || self.at_punct(Punct::RBracket)
3614            || self.at_punct(Punct::RBrace)
3615            || self.at_punct(Punct::Comma)
3616            || self.at_punct(Punct::Semicolon)
3617            || self.at_punct(Punct::Colon)
3618            || self.current.is_eof()
3619        {
3620            None
3621        } else {
3622            Some(Box::new(self.parse_assignment(allow_in)?))
3623        };
3624        Ok(Expr::new(
3625            ExprKind::Yield { argument, delegate },
3626            self.span_from(start),
3627        ))
3628    }
3629
3630    fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
3631        let starts_paren = self.at_punct(Punct::LParen);
3632        let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
3633        if !starts_paren && !starts_ident {
3634            return Ok(None);
3635        }
3636        // `(` could be a parenthesised expression instead of a parameter list.
3637        // Scanning ahead for the matching `)` and looking for `=>` avoids the
3638        // speculative parse (and its stack cost) in the common case.
3639        if starts_paren && !self.arrow_follows_paren()? {
3640            return Ok(None);
3641        }
3642        let snapshot = self.snapshot();
3643        let head = match self.parse_arrow_head() {
3644            Ok(head) => head,
3645            Err(_) => {
3646                self.restore(snapshot);
3647                return Ok(None);
3648            }
3649        };
3650        let Some(head) = head else {
3651            self.restore(snapshot);
3652            return Ok(None);
3653        };
3654        // Committed: `=>` has been consumed, so errors from here on are real.
3655        // Arrow parameter lists may never repeat a name, in any mode. The message is the
3656        // same one `js_parse_function_args` uses, with no name appended — an earlier
3657        // version added ` ('a')`, which the reference does not print. The position is the
3658        // body's first token: `(a, a) => x` points at the `x`, and `(a, a) => {}` at the
3659        // `}`, because the reference has already consumed the `{` by then.
3660        let body_start = if self.at_punct(Punct::LBrace) {
3661            self.peek()?.span
3662        } else {
3663            self.current.span
3664        };
3665        self.check_duplicate_parameters(&head.params, true, body_start)?;
3666        let saved_ctx = self.ctx;
3667        let saved_loop = self.loop_depth;
3668        let saved_switch = self.switch_depth;
3669        let saved_labels = std::mem::take(&mut self.labels);
3670        let saved_top = self.top_level;
3671        self.ctx = FnCtx {
3672            in_function: true,
3673            in_generator: false,
3674            in_async: head.is_async,
3675            in_method: saved_ctx.in_method,
3676            in_derived_constructor: saved_ctx.in_derived_constructor,
3677            // An arrow is not a static block, so it gets its own `return` and `await` is
3678            // an ordinary name again — but it has no `arguments` of its own, so the ban
3679            // travels with it.
3680            in_static_block: false,
3681            arguments_allowed: saved_ctx.arguments_allowed,
3682        };
3683        self.loop_depth = 0;
3684        self.switch_depth = 0;
3685        self.top_level = false;
3686        let body_start = self.current.span.start;
3687        let (body, strict) = if self.at_punct(Punct::LBrace) {
3688            let (block, strict) = self.parse_arrow_block(&head.params)?;
3689            (block, (self.prev_end, strict))
3690        } else {
3691            let expr = self.parse_assignment(allow_in)?;
3692            let end = expr.span.end;
3693            // An expression body has no directive prologue, so it inherits.
3694            let strict = self.strict;
3695            (FunctionBody::Expr(Box::new(expr)), (end, strict))
3696        };
3697        self.ctx = saved_ctx;
3698        self.loop_depth = saved_loop;
3699        self.switch_depth = saved_switch;
3700        self.labels = saved_labels;
3701        self.top_level = saved_top;
3702        let _ = body_start;
3703        let (body, (end, strict)) = (body, strict);
3704        let span = Span::new(head.span.start, end);
3705        Ok(Some(Expr::new(
3706            ExprKind::Arrow(Box::new(Function {
3707                name: None,
3708                params: head.params,
3709                body,
3710                is_async: head.is_async,
3711                is_generator: false,
3712                strict,
3713                is_arrow: true,
3714                span,
3715                params_span: head.params_span,
3716            })),
3717            span,
3718        )))
3719    }
3720
3721    /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
3722    fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<(FunctionBody, bool)> {
3723        // Like a function body: the arrow's own directive governs the arrow, and the
3724        // enclosing scope's mode is restored afterwards.
3725        let saved_strict = self.strict;
3726        self.expect_punct(Punct::LBrace)?;
3727        self.push_scope(Scope::function(simple_parameter_names(params)));
3728        let result = (|| -> Result<Vec<Stmt>> {
3729            let mut body = Vec::new();
3730            let mut prologue = true;
3731            while !self.at_punct(Punct::RBrace) {
3732                if self.current.is_eof() {
3733                    return Err(self.unexpected());
3734                }
3735                let stmt = self.parse_statement_list_item()?;
3736                if prologue {
3737                    match self.directive_value(&stmt) {
3738                        Some(directive) if directive == "use strict" => self.enter_strict()?,
3739                        Some(_) => {}
3740                        None => prologue = false,
3741                    }
3742                }
3743                body.push(stmt);
3744            }
3745            Ok(body)
3746        })();
3747        self.pop_scope();
3748        let body_strict = self.strict;
3749        self.strict = saved_strict;
3750        self.lexer.set_strict(saved_strict);
3751        let body = result?;
3752        self.bump()?;
3753        Ok((FunctionBody::Block(body), body_strict))
3754    }
3755
3756    /// Whether the parenthesis at the current token is the parameter list of an
3757    /// arrow function, i.e. the matching `)` is followed by `=>`.
3758    ///
3759    /// This is a plain token walk with a bracket counter: no recursion, so it
3760    /// costs a clone of the lexer and nothing else.
3761    fn arrow_follows_paren(&self) -> Result<bool> {
3762        let mut lexer = self.lexer.clone();
3763        // The opening `(` was already consumed by the caller.
3764        let mut depth = 1usize;
3765        loop {
3766            let token = lexer.next_token()?;
3767            match token.kind {
3768                TokenKind::Eof => return Ok(false),
3769                // A `/` may open a regular expression literal, and this scan has to agree
3770                // with the parser about which it is. A pattern can contain `(`, `)` and `[`
3771                // without balancing them, and lexing one as division also made the
3772                // pattern's characters into tokens — `(/😀/)` was a `SyntaxError` about an
3773                // identifier, because `😀` is not one. Re-scan from the slash; if no pattern
3774                // terminates on this line there is none, and the scan carries on after the
3775                // `/` exactly as division did.
3776                TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3777                    if lexer.re_scan_regex(token.span.start).is_err() {
3778                        lexer.reset_to(token.span.end);
3779                    }
3780                }
3781                TokenKind::Punct(Punct::LParen)
3782                | TokenKind::Punct(Punct::LBracket)
3783                | TokenKind::Punct(Punct::LBrace) => depth += 1,
3784                TokenKind::Punct(Punct::RParen)
3785                | TokenKind::Punct(Punct::RBracket)
3786                | TokenKind::Punct(Punct::RBrace) => {
3787                    if depth == 0 {
3788                        // Unbalanced input: the caller reports it.
3789                        return Ok(false);
3790                    }
3791                    depth -= 1;
3792                    if depth == 0 {
3793                        // The current token is the opening `(`, so the matching
3794                        // `)` is the token that brought us back to zero.
3795                        let next = lexer.next_token()?;
3796                        return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
3797                            && !next.newline_before);
3798                    }
3799                }
3800                _ => {}
3801            }
3802        }
3803    }
3804
3805    /// Speculatively parse an arrow head, consuming `=>` on success.
3806    fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
3807        let start = self.current.span.start;
3808        let mut is_async = false;
3809        if self.at_ident("async") {
3810            let peek = self.peek()?;
3811            if peek.newline_before {
3812                return Ok(None);
3813            }
3814            let plausible =
3815                matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
3816            if !plausible {
3817                return Ok(None);
3818            }
3819            self.bump()?;
3820            is_async = true;
3821        }
3822        let params_start = self.current.span.start;
3823        let params = if self.at_punct(Punct::LParen) {
3824            self.parse_formal_parameters()?
3825        } else if matches!(self.current.kind, TokenKind::Ident(_)) {
3826            let ident = self.expect_ident()?;
3827            vec![Pattern::new(
3828                PatternKind::Ident(ident),
3829                self.span_from(params_start),
3830            )]
3831        } else {
3832            return Ok(None);
3833        };
3834        let params_span = self.span_from(params_start);
3835        if !self.at_punct(Punct::Arrow) || self.current.newline_before {
3836            return Ok(None);
3837        }
3838        self.bump()?; // =>
3839        Ok(Some(ArrowHead {
3840            params,
3841            is_async,
3842            span: self.span_from(start),
3843            params_span,
3844        }))
3845    }
3846
3847    fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
3848        let start = self.current.span.start;
3849        let test = self.parse_binary(allow_in, 0)?;
3850        if !self.at_punct(Punct::Question) {
3851            return Ok(test);
3852        }
3853        self.bump()?;
3854        let consequent = self.parse_assignment(true)?;
3855        self.expect_punct(Punct::Colon)?;
3856        let alternate = self.parse_assignment(allow_in)?;
3857        Ok(Expr::new(
3858            ExprKind::Conditional {
3859                test: Box::new(test),
3860                cons: Box::new(consequent),
3861                alt: Box::new(alternate),
3862            },
3863            self.span_from(start),
3864        ))
3865    }
3866
3867    fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
3868        let start = self.current.span.start;
3869        let mut lhs = self.parse_unary()?;
3870        while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
3871            if prec < min_prec {
3872                break;
3873            }
3874            let op_pos = self.current.span.start;
3875            self.bump()?;
3876            let next_min = if op.is_right_associative() {
3877                prec
3878            } else {
3879                prec + 1
3880            };
3881            let rhs = self.parse_binary(allow_in, next_min)?;
3882            lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
3883        }
3884        Ok(lhs)
3885    }
3886
3887    /// Unary and postfix operators. `in` is handled by the binary layer, so no
3888    /// `allow_in` flag is needed here.
3889    fn parse_unary(&mut self) -> Result<Expr> {
3890        let start = self.current.span.start;
3891        // Unary operators.
3892        let unary = match &self.current.kind {
3893            TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
3894            TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
3895            TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
3896            TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
3897            TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
3898            TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
3899            TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
3900            _ => None,
3901        };
3902        if let Some(op) = unary {
3903            let op_pos = self.current.span.start;
3904            self.bump()?;
3905            let argument = self.parse_unary()?;
3906            if op == UnaryOp::Delete && self.strict {
3907                if let ExprKind::Ident(ident) = &argument.unparen().kind {
3908                    return Err(self.error_at(
3909                        "cannot delete a direct reference in strict mode",
3910                        ident.span,
3911                    ));
3912                }
3913            }
3914            // `delete obj.#x` is an early error in *any* mode, and so is the "covered" form:
3915            // the spec rule applies to the derived expression through any number of
3916            // parentheses, through the last element of a sequence, and to the callee of a
3917            // call. Missing the covered forms let those programs run, and `$DONOTEVALUATE()`
3918            // is what the test suite then reported instead of a `SyntaxError`.
3919            if op == UnaryOp::Delete && deletes_a_private_member(&argument) {
3920                // Reported at the token *after* the operand, which is where the reference
3921                // reports it: `js_parse_delete` finishes parsing the expression and then calls
3922                // `js_parse_error`, whose position is `s->token`.
3923                return Err(self.error("cannot delete a private class field"));
3924            }
3925            let expr = Expr::at_operator(
3926                ExprKind::Unary {
3927                    op,
3928                    argument: Box::new(argument),
3929                },
3930                self.span_from(start),
3931                op_pos,
3932            );
3933            if self.at_punct(Punct::StarStar) {
3934                return Err(self.error(
3935                    // The reference's wording, from `js_parse_error` in the `**` check.
3936                    "unparenthesized unary expression can't appear on the left-hand side of '**'",
3937                ));
3938            }
3939            return Ok(expr);
3940        }
3941        // Prefix increment/decrement.
3942        if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
3943            let op_pos = self.current.span.start;
3944            let op = if self.at_punct(Punct::PlusPlus) {
3945                UpdateOp::Increment
3946            } else {
3947                UpdateOp::Decrement
3948            };
3949            self.bump()?;
3950            let argument = self.parse_unary()?;
3951            self.check_simple_target(&argument)?;
3952            return Ok(Expr::at_operator(
3953                ExprKind::Update {
3954                    op,
3955                    argument: Box::new(argument),
3956                    prefix: true,
3957                },
3958                self.span_from(start),
3959                op_pos,
3960            ));
3961        }
3962        // `await` wherever the enclosing function is `async`, operator or not.
3963        //
3964        // There is no "unless the next token rules it out" case: the reference reaches
3965        // `TOK_AWAIT` and consumes it unconditionally, so `await;` and `f(await)` report
3966        // the *operand* as unexpected rather than treating `await` as an identifier. That
3967        // is why this asks nothing about what follows.
3968        if self.at_ident("await") && self.ctx.in_async {
3969            // §15.8.1: `async` functions may not have an `AwaitExpression` in their own
3970            // formal parameters, so `new AsyncFunction("x = await 1", "")` is an error.
3971            if self.in_formal_parameters {
3972                return Err(self.error_at("await in default expression", self.current.span));
3973            }
3974            self.bump()?;
3975            let argument = self.parse_unary()?;
3976            return Ok(Expr::new(
3977                ExprKind::Await(Box::new(argument)),
3978                self.span_from(start),
3979            ));
3980        }
3981        let expr = self.parse_lhs_expression()?;
3982        // Postfix increment/decrement (no line break allowed before the operator).
3983        let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3984            && !self.current.newline_before
3985        {
3986            let op_pos = self.current.span.start;
3987            let op = if self.at_punct(Punct::PlusPlus) {
3988                UpdateOp::Increment
3989            } else {
3990                UpdateOp::Decrement
3991            };
3992            self.check_simple_target(&expr)?;
3993            self.bump()?;
3994            Expr::at_operator(
3995                ExprKind::Update {
3996                    op,
3997                    argument: Box::new(expr),
3998                    prefix: false,
3999                },
4000                self.span_from(start),
4001                op_pos,
4002            )
4003        } else {
4004            expr
4005        };
4006        Ok(result)
4007    }
4008
4009    /// The operand of `++`/`--`, which must be a plain reference.
4010    ///
4011    /// Its own message, not the assignment one: the reference rejects `++1` and `1++` with
4012    /// `js_parse_error(s, "invalid increment/decrement operand")`.
4013    fn check_simple_target(&self, expr: &Expr) -> Result<()> {
4014        match &expr.unparen().kind {
4015            ExprKind::Ident(_) => Ok(()),
4016            ExprKind::Member {
4017                optional: false, ..
4018            } => Ok(()),
4019            _ => Err(self.error_at("invalid increment/decrement operand", expr.span)),
4020        }
4021    }
4022
4023    fn parse_lhs_expression(&mut self) -> Result<Expr> {
4024        let start = self.current.span.start;
4025        let mut expr = if self.at_keyword(Keyword::New) {
4026            self.parse_new_expression()?
4027        } else {
4028            self.parse_primary()?
4029        };
4030        let mut saw_optional = false;
4031        loop {
4032            // The position of the punctuator that follows the base expression: a
4033            // failed `.`, `[` or `(` is blamed on that token, not on the base.
4034            let op_pos = self.current.span.start;
4035            match self.current.kind.clone() {
4036                TokenKind::Punct(Punct::Dot) => {
4037                    self.bump()?;
4038                    let property = self.parse_member_property()?;
4039                    expr = Expr::at_operator(
4040                        ExprKind::Member {
4041                            object: Box::new(expr),
4042                            property,
4043                            optional: false,
4044                        },
4045                        self.span_from(start),
4046                        op_pos,
4047                    );
4048                }
4049                TokenKind::Punct(Punct::QuestionDot) => {
4050                    saw_optional = true;
4051                    self.bump()?;
4052                    if self.at_punct(Punct::LParen) {
4053                        let arguments = self.parse_arguments()?;
4054                        expr = Expr::at_operator(
4055                            ExprKind::Call {
4056                                callee: Box::new(expr),
4057                                arguments,
4058                                optional: true,
4059                            },
4060                            self.span_from(start),
4061                            op_pos,
4062                        );
4063                    } else if self.at_punct(Punct::LBracket) {
4064                        self.bump()?;
4065                        let index = self.parse_expression(true)?;
4066                        self.expect_punct(Punct::RBracket)?;
4067                        expr = Expr::at_operator(
4068                            ExprKind::Member {
4069                                object: Box::new(expr),
4070                                property: MemberProp::Computed(Box::new(index)),
4071                                optional: true,
4072                            },
4073                            self.span_from(start),
4074                            op_pos,
4075                        );
4076                    } else {
4077                        let property = self.parse_member_property()?;
4078                        expr = Expr::at_operator(
4079                            ExprKind::Member {
4080                                object: Box::new(expr),
4081                                property,
4082                                optional: true,
4083                            },
4084                            self.span_from(start),
4085                            op_pos,
4086                        );
4087                    }
4088                }
4089                TokenKind::Punct(Punct::LBracket) => {
4090                    self.bump()?;
4091                    let index = self.parse_expression(true)?;
4092                    self.expect_punct(Punct::RBracket)?;
4093                    expr = Expr::at_operator(
4094                        ExprKind::Member {
4095                            object: Box::new(expr),
4096                            property: MemberProp::Computed(Box::new(index)),
4097                            optional: false,
4098                        },
4099                        self.span_from(start),
4100                        op_pos,
4101                    );
4102                }
4103                TokenKind::Punct(Punct::LParen) => {
4104                    let arguments = self.parse_arguments()?;
4105                    expr = Expr::at_operator(
4106                        ExprKind::Call {
4107                            callee: Box::new(expr),
4108                            arguments,
4109                            optional: false,
4110                        },
4111                        self.span_from(start),
4112                        op_pos,
4113                    );
4114                }
4115                TokenKind::Template(_) => {
4116                    if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
4117                        return Err(
4118                            self.error("tagged template cannot be used in an optional chain")
4119                        );
4120                    }
4121                    let quasi = self.parse_template()?;
4122                    expr = Expr::new(
4123                        ExprKind::TaggedTemplate {
4124                            tag: Box::new(expr),
4125                            quasi: Box::new(quasi),
4126                        },
4127                        self.span_from(start),
4128                    );
4129                }
4130                _ => break,
4131            }
4132        }
4133        if saw_optional {
4134            expr = Expr::new(
4135                ExprKind::OptionalChain(Box::new(expr)),
4136                self.span_from(start),
4137            );
4138        }
4139        Ok(expr)
4140    }
4141
4142    /// `#name`, with `#` the current token.
4143    ///
4144    /// The `#` and the name may not be separated: `class C { # x = 1 }` is
4145    /// `invalid first character of private name`, not a field called `x`. The reference checks
4146    /// it in the lexer (`parse_ident` with `is_private`, which requires an identifier-start
4147    /// character immediately after the `#`), so the error is reported at the `#`.
4148    fn parse_private_name(&mut self) -> Result<Ident> {
4149        let hash = self.current.span;
4150        self.bump()?;
4151        let ident = self.expect_ident()?;
4152        if ident.span.start.offset != hash.end.offset {
4153            return Err(self.error_at("invalid first character of private name", hash));
4154        }
4155        Ok(ident)
4156    }
4157
4158    fn parse_member_property(&mut self) -> Result<MemberProp> {
4159        if self.at_punct(Punct::Hash) {
4160            let ident = self.parse_private_name()?;
4161            if !self.private.iter().any(|env| env.contains(&ident.name)) {
4162                // The reference names the field and nothing else:
4163                // `js_parse_error(s, "undefined private field '#%s'")`.
4164                return Err(self.error_at(
4165                    format!("undefined private field '#{}'", ident.name),
4166                    ident.span,
4167                ));
4168            }
4169            return Ok(MemberProp::Private(ident));
4170        }
4171        match self.current.kind.clone() {
4172            TokenKind::Ident(name) => {
4173                let span = self.current.span;
4174                self.bump()?;
4175                Ok(MemberProp::Ident(Ident { name, span }))
4176            }
4177            TokenKind::Keyword(kw) => {
4178                let span = self.current.span;
4179                self.bump()?;
4180                Ok(MemberProp::Ident(Ident {
4181                    name: kw.as_str().to_string(),
4182                    span,
4183                }))
4184            }
4185            // After `.` or `?.` the reference says "expecting field name", not
4186            // "invalid property name" — it is `js_parse_error(s, "expecting field name")`
4187            // at the member-access site.
4188            _ => Err(self.error("expecting field name")),
4189        }
4190    }
4191
4192    fn parse_new_expression(&mut self) -> Result<Expr> {
4193        let start = self.current.span.start;
4194        self.bump()?; // new
4195        if self.at_punct(Punct::Dot) {
4196            self.bump()?;
4197            if !self.at_ident("target") {
4198                return Err(self.error("expecting target"));
4199            }
4200            if !self.ctx.in_function {
4201                return Err(self.error("new.target only allowed within functions"));
4202            }
4203            self.bump()?;
4204            return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
4205        }
4206        let mut callee = if self.at_keyword(Keyword::New) {
4207            self.parse_new_expression()?
4208        } else {
4209            self.parse_primary()?
4210        };
4211        // Member accesses bind tighter than `new`, calls do not.
4212        loop {
4213            let op_pos = self.current.span.start;
4214            match self.current.kind.clone() {
4215                TokenKind::Punct(Punct::Dot) => {
4216                    self.bump()?;
4217                    let property = self.parse_member_property()?;
4218                    callee = Expr::at_operator(
4219                        ExprKind::Member {
4220                            object: Box::new(callee),
4221                            property,
4222                            optional: false,
4223                        },
4224                        self.span_from(start),
4225                        op_pos,
4226                    );
4227                }
4228                TokenKind::Punct(Punct::LBracket) => {
4229                    self.bump()?;
4230                    let index = self.parse_expression(true)?;
4231                    self.expect_punct(Punct::RBracket)?;
4232                    callee = Expr::at_operator(
4233                        ExprKind::Member {
4234                            object: Box::new(callee),
4235                            property: MemberProp::Computed(Box::new(index)),
4236                            optional: false,
4237                        },
4238                        self.span_from(start),
4239                        op_pos,
4240                    );
4241                }
4242                TokenKind::Punct(Punct::QuestionDot) => {
4243                    return Err(self.error("new keyword cannot be used with an optional chain"));
4244                }
4245                _ => break,
4246            }
4247        }
4248        if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
4249            return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
4250        }
4251        // `ImportCall` is a *CallExpression*, and `new` only reaches a `MemberExpression`
4252        // (`MemberExpression : new MemberExpression Arguments`), so `new import(x)` is a
4253        // SyntaxError. `import.meta`, by contrast, *is* a `MemberExpression`, so
4254        // `new import.meta()` parses and fails at run time for not being a constructor.
4255        if matches!(callee.unparen().kind, ExprKind::ImportCall(_)) {
4256            return Err(self.error_at("invalid use of 'import()'", callee.span));
4257        }
4258        let arguments = if self.at_punct(Punct::LParen) {
4259            // `new C(...)`: a failure in the constructor call is blamed on the `(`.
4260            let op_pos = self.current.span.start;
4261            let arguments = Some(self.parse_arguments()?);
4262            return Ok(Expr::at_operator(
4263                ExprKind::New {
4264                    callee: Box::new(callee),
4265                    arguments,
4266                },
4267                self.span_from(start),
4268                op_pos,
4269            ));
4270        } else {
4271            None
4272        };
4273        // `new C` with no argument list: the reference emits its position at the token
4274        // *after* the constructor (`emit_source_pos(s, s->token.ptr)` for "new operator on
4275        // an object"), not at the `new`.
4276        Ok(Expr::at_operator(
4277            ExprKind::New {
4278                callee: Box::new(callee),
4279                arguments,
4280            },
4281            self.span_from(start),
4282            self.current.span.start,
4283        ))
4284    }
4285
4286    fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
4287        self.expect_punct(Punct::LParen)?;
4288        let mut arguments = Vec::new();
4289        while !self.at_punct(Punct::RParen) {
4290            if self.at_punct(Punct::Ellipsis) {
4291                let start = self.current.span.start;
4292                self.bump()?;
4293                let argument = self.parse_assignment(true)?;
4294                arguments.push(Expr::new(
4295                    ExprKind::Spread(Box::new(argument)),
4296                    self.span_from(start),
4297                ));
4298            } else {
4299                arguments.push(self.parse_assignment(true)?);
4300            }
4301            if !self.eat_punct(Punct::Comma)? {
4302                break;
4303            }
4304        }
4305        self.expect_punct(Punct::RParen)?;
4306        Ok(arguments)
4307    }
4308
4309    /// Primary expressions.
4310    ///
4311    /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
4312    /// so that this function — which sits on every nesting level — keeps a small
4313    /// stack frame. That directly raises how deeply a program may nest before
4314    /// the stack limit is hit (debug builds get ~4x more depth out of it).
4315    fn parse_primary(&mut self) -> Result<Expr> {
4316        let start = self.current.span.start;
4317        match self.current.kind.clone() {
4318            TokenKind::Number(NumberLiteral::Int(value)) => {
4319                self.bump()?;
4320                Ok(Expr::new(
4321                    ExprKind::Number(value as f64),
4322                    self.span_from(start),
4323                ))
4324            }
4325            TokenKind::Number(NumberLiteral::Float(value)) => {
4326                self.bump()?;
4327                Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
4328            }
4329            TokenKind::String(value) => {
4330                self.bump()?;
4331                Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
4332            }
4333            // A *contextual* keyword, so only its own spelling counts: `\u0061sync
4334            // function(){}` is an identifier followed by a declaration, which is a syntax
4335            // error rather than an async function expression.
4336            TokenKind::Ident(name) if name == "async" && !self.current.escaped => {
4337                let peek = self.peek()?;
4338                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
4339                    && !peek.newline_before
4340                {
4341                    self.bump()?; // async
4342                    let func = self.parse_function(FunctionForm::Expression, true, Some(start))?;
4343                    return Ok(Expr::new(
4344                        ExprKind::Function(Box::new(func)),
4345                        self.span_from(start),
4346                    ));
4347                }
4348                let span = self.current.span;
4349                self.bump()?;
4350                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4351            }
4352            TokenKind::Ident(name) => {
4353                let span = self.current.span;
4354                self.check_identifier(&name, span)?;
4355                self.check_arguments_reference(&name, span)?;
4356                self.bump()?;
4357                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
4358            }
4359            TokenKind::Keyword(Keyword::This) => {
4360                self.bump()?;
4361                Ok(Expr::new(ExprKind::This, self.span_from(start)))
4362            }
4363            TokenKind::Keyword(Keyword::Null) => {
4364                self.bump()?;
4365                Ok(Expr::new(ExprKind::Null, self.span_from(start)))
4366            }
4367            TokenKind::Keyword(Keyword::True) => {
4368                self.bump()?;
4369                Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
4370            }
4371            TokenKind::Keyword(Keyword::False) => {
4372                self.bump()?;
4373                Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
4374            }
4375            TokenKind::Punct(Punct::LParen) => {
4376                self.bump()?;
4377                let inner = self.parse_expression(true)?;
4378                self.expect_punct(Punct::RParen)?;
4379                Ok(Expr::new(
4380                    ExprKind::Paren(Box::new(inner)),
4381                    self.span_from(start),
4382                ))
4383            }
4384            TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
4385                self.parse_regex_literal(start)
4386            }
4387            _ => self.parse_primary_complex(start),
4388        }
4389    }
4390
4391    /// The primary expressions that need a lot of code: literals with structure,
4392    /// functions, classes, `import`, `super`, `#x in y`.
4393    #[inline(never)]
4394    fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
4395        match self.current.kind.clone() {
4396            TokenKind::BigInt(literal) => {
4397                self.bump()?;
4398                Ok(Expr::new(
4399                    ExprKind::BigInt {
4400                        digits: literal.digits,
4401                        radix: literal.radix,
4402                    },
4403                    self.span_from(start),
4404                ))
4405            }
4406            TokenKind::Template(_) => {
4407                let template = self.parse_template()?;
4408                Ok(Expr::new(
4409                    ExprKind::Template(Box::new(template)),
4410                    self.span_from(start),
4411                ))
4412            }
4413            TokenKind::Keyword(Keyword::Function) => {
4414                let func = self.parse_function(FunctionForm::Expression, false, None)?;
4415                Ok(Expr::new(
4416                    ExprKind::Function(Box::new(func)),
4417                    self.span_from(start),
4418                ))
4419            }
4420            TokenKind::Keyword(Keyword::Class) => {
4421                let class = self.parse_class(true)?;
4422                Ok(Expr::new(
4423                    ExprKind::Class(Box::new(class)),
4424                    self.span_from(start),
4425                ))
4426            }
4427            TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
4428            TokenKind::Keyword(Keyword::Super) => self.parse_super(),
4429            TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
4430            TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
4431            // `#x` is only an expression as `#x in obj`, and `in` is not available where the
4432            // grammar forbids it — a `for` head, for instance. The reference parses the head
4433            // with the `[~In]` production, so `for (#f in v;;)` fails on the `#f` itself with
4434            // "unexpected token in expression: '#f'" rather than somewhere later.
4435            TokenKind::Punct(Punct::Hash) if self.allow_in => self.parse_private_in(start),
4436            // Reached only when `in` is unavailable, so `#f` cannot start an expression here.
4437            // The message is the reference's, which quotes the whole private name rather than
4438            // the lone `#` that the token stream holds.
4439            TokenKind::Punct(Punct::Hash) => {
4440                let hash = self.current.span;
4441                let name = match self.peek()?.kind.clone() {
4442                    TokenKind::Ident(name) => format!("#{name}"),
4443                    _ => "#".to_string(),
4444                };
4445                Err(SyntaxError::new(
4446                    format!("unexpected token in expression: '{name}'"),
4447                    hash,
4448                ))
4449            }
4450            _ => Err(self.unexpected()),
4451        }
4452    }
4453
4454    /// `super` or `super(...)`.
4455    #[inline(never)]
4456    fn parse_super(&mut self) -> Result<Expr> {
4457        let start = self.current.span.start;
4458        self.bump()?;
4459        // Every error below is reported at the token *after* `super`, because the reference
4460        // consumes the keyword before it looks at what follows (`case TOK_SUPER:
4461        // next_token(s); …`) and `js_parse_error` always points at the current token. So
4462        // `super.x` reports the `.`, `super()` the `(`, and a bare `super` the token that
4463        // ends the expression.
4464        let after = self.current.span;
4465        if self.at_punct(Punct::LParen) {
4466            if !self.ctx.in_derived_constructor {
4467                return Err(self.error_at(
4468                    "super() is only valid in a derived class constructor",
4469                    after,
4470                ));
4471            }
4472            // A `super()` call is positioned on its `(` like any other call: the reference
4473            // reaches the same `emit_source_pos(op_token_ptr)` on the way to `apply`.
4474            let arguments = self.parse_arguments()?;
4475            return Ok(Expr::at_operator(
4476                ExprKind::SuperCall(arguments),
4477                self.span_from(start),
4478                after.start,
4479            ));
4480        }
4481        if !self.ctx.in_method {
4482            // Three messages, told apart by what follows `super`:
4483            //   `super` alone        -> invalid use of 'super'
4484            //   `super.x`, `super[x]` -> 'super' is only valid in a method
4485            //   `super()`            -> handled above
4486            // A bare `super` never reaches the member-access code, so the reference names
4487            // it on its own.
4488            let message = if self.at_punct(Punct::Dot) || self.at_punct(Punct::LBracket) {
4489                "'super' is only valid in a method"
4490            } else {
4491                "invalid use of 'super'"
4492            };
4493            return Err(self.error_at(message, after));
4494        }
4495        Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
4496    }
4497
4498    /// `#name in object`.
4499    #[inline(never)]
4500    fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
4501        self.bump()?;
4502        let ident = self.expect_ident()?;
4503        if !self.private.iter().any(|env| env.contains(&ident.name)) {
4504            return Err(self.error_at(
4505                format!(
4506                    "private field '#{}' must be declared in an enclosing class",
4507                    ident.name
4508                ),
4509                ident.span,
4510            ));
4511        }
4512        if !self.at_keyword(Keyword::In) {
4513            return Err(self.error("expecting 'in' after a private name"));
4514        }
4515        self.bump()?;
4516        // `RelationalExpression : PrivateIdentifier in ShiftExpression` — the right operand is
4517        // a *shift* expression, so a second private-in cannot nest inside it. The reference
4518        // says so by rejecting `#f in #f in this` at the inner `#f`.
4519        if self.at_punct(Punct::Hash) {
4520            let hash = self.current.span;
4521            let name = match self.peek()?.kind.clone() {
4522                TokenKind::Ident(name) => format!("#{name}"),
4523                _ => "#".to_string(),
4524            };
4525            return Err(SyntaxError::new(
4526                format!("unexpected token in expression: '{name}'"),
4527                hash,
4528            ));
4529        }
4530        let object = self.parse_unary()?;
4531        Ok(Expr::new(
4532            ExprKind::PrivateIn {
4533                name: ident,
4534                object: Box::new(object),
4535            },
4536            self.span_from(start),
4537        ))
4538    }
4539
4540    /// A regular expression literal: the lexer produced `/` (or `/=`), so the
4541    /// token has to be re-scanned from that position.
4542    #[inline(never)]
4543    fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
4544        let token = self.lexer.re_scan_regex(self.current.span.start)?;
4545        self.current = token;
4546        let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
4547            unreachable!("re_scan_regex returns a RegExp token")
4548        };
4549        self.bump()?;
4550        Ok(Expr::new(
4551            ExprKind::RegExp { pattern, flags },
4552            self.span_from(start),
4553        ))
4554    }
4555
4556    fn parse_import_expression(&mut self) -> Result<Expr> {
4557        let start = self.current.span.start;
4558        self.bump()?; // import
4559        if self.at_punct(Punct::Dot) {
4560            if !self.module {
4561                return Err(self.error_at(
4562                    "import.meta only valid in module code",
4563                    self.span_from(start),
4564                ));
4565            }
4566            self.bump()?;
4567            if !self.at_ident("meta") {
4568                return Err(self.error("expecting 'meta' after 'import.'"));
4569            }
4570            self.bump()?;
4571            return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
4572        }
4573        if self.at_punct(Punct::LParen) {
4574            self.bump()?;
4575            let specifier = self.parse_assignment(true)?;
4576            if self.at_punct(Punct::Comma) {
4577                return Err(self.error("import() takes exactly one argument"));
4578            }
4579            self.expect_punct(Punct::RParen)?;
4580            return Ok(Expr::new(
4581                ExprKind::ImportCall(Box::new(specifier)),
4582                self.span_from(start),
4583            ));
4584        }
4585        Err(self.unexpected())
4586    }
4587
4588    fn parse_array_literal(&mut self) -> Result<Expr> {
4589        let start = self.current.span.start;
4590        self.expect_punct(Punct::LBracket)?;
4591        let mut elements = Vec::new();
4592        while !self.at_punct(Punct::RBracket) {
4593            if self.at_punct(Punct::Comma) {
4594                self.bump()?;
4595                elements.push(None);
4596                continue;
4597            }
4598            if self.at_punct(Punct::Ellipsis) {
4599                let spread_start = self.current.span.start;
4600                self.bump()?;
4601                let argument = self.parse_assignment(true)?;
4602                elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
4603                    ExprKind::Spread(Box::new(argument)),
4604                    self.span_from(spread_start),
4605                )))));
4606            } else {
4607                let expr = self.parse_assignment(true)?;
4608                elements.push(Some(ArrayElement::Expr(Box::new(expr))));
4609            }
4610            if !self.eat_punct(Punct::Comma)? {
4611                break;
4612            }
4613        }
4614        self.expect_punct(Punct::RBracket)?;
4615        Ok(Expr::new(
4616            ExprKind::Array { elements },
4617            self.span_from(start),
4618        ))
4619    }
4620
4621    fn parse_object_literal(&mut self) -> Result<Expr> {
4622        let start = self.current.span.start;
4623        self.expect_punct(Punct::LBrace)?;
4624        let mut properties: Vec<ObjectProperty> = Vec::new();
4625        let mut proto_count = 0;
4626        while !self.at_punct(Punct::RBrace) {
4627            let property_start = self.current.span.start;
4628            if self.at_punct(Punct::Ellipsis) {
4629                self.bump()?;
4630                let argument = self.parse_assignment(true)?;
4631                properties.push(ObjectProperty::Spread(Box::new(argument)));
4632            } else {
4633                let mut is_async = false;
4634                let mut is_generator = false;
4635                let mut accessor: Option<MethodKind> = None;
4636                if self.at_ident("async") {
4637                    let peek = self.peek()?;
4638                    let is_modifier = !matches!(
4639                        peek.kind,
4640                        TokenKind::Punct(Punct::LParen)
4641                            | TokenKind::Punct(Punct::Colon)
4642                            | TokenKind::Punct(Punct::Comma)
4643                            | TokenKind::Punct(Punct::RBrace)
4644                            | TokenKind::Punct(Punct::Eq)
4645                    ) && !peek.newline_before;
4646                    if is_modifier {
4647                        self.bump()?;
4648                        is_async = true;
4649                    }
4650                }
4651                if self.at_punct(Punct::Star) {
4652                    self.bump()?;
4653                    is_generator = true;
4654                }
4655                if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
4656                    let is_get = self.at_ident("get");
4657                    let peek = self.peek()?;
4658                    if is_property_key_start(&peek.kind) {
4659                        self.bump()?;
4660                        accessor = Some(if is_get {
4661                            MethodKind::Get
4662                        } else {
4663                            MethodKind::Set
4664                        });
4665                    }
4666                }
4667                let key = self.parse_property_key()?;
4668                let is_computed = matches!(key, PropName::Computed(_));
4669                if self.at_punct(Punct::LParen) {
4670                    let saved = self.ctx;
4671                    self.ctx = FnCtx {
4672                        in_function: true,
4673                        in_generator: is_generator,
4674                        in_async: is_async,
4675                        in_method: true,
4676                        in_derived_constructor: false,
4677                        in_static_block: false,
4678                        arguments_allowed: true,
4679                    };
4680                    let saved_top = self.top_level;
4681                    self.top_level = false;
4682                    let func_result = (|| -> Result<Function> {
4683                        let params = self.parse_formal_parameters()?;
4684                        let (params, params_span, body, strict) =
4685                            self.parse_function_body(params, true)?;
4686                        Ok(Function {
4687                            name: None,
4688                            params,
4689                            body,
4690                            is_async,
4691                            is_generator,
4692                            strict,
4693                            is_arrow: false,
4694                            span: self.span_from(property_start),
4695                            params_span,
4696                        })
4697                    })();
4698                    self.ctx = saved;
4699                    self.top_level = saved_top;
4700                    let func = func_result?;
4701                    let kind = match accessor {
4702                        Some(kind) => {
4703                            if is_generator || is_async {
4704                                return Err(self.error_at(
4705                                    "accessors may not be generators or async",
4706                                    func.span,
4707                                ));
4708                            }
4709                            if kind == MethodKind::Get && !func.params.is_empty() {
4710                                return Err(self.error_at(
4711                                    "invalid number of arguments for getter or setter",
4712                                    func.span,
4713                                ));
4714                            }
4715                            if kind == MethodKind::Set && func.params.len() != 1 {
4716                                return Err(self.error_at(
4717                                    "invalid number of arguments for getter or setter",
4718                                    func.span,
4719                                ));
4720                            }
4721                            match kind {
4722                                MethodKind::Get => PropertyKind::Get,
4723                                MethodKind::Set => PropertyKind::Set,
4724                                MethodKind::Method | MethodKind::Constructor => {
4725                                    PropertyKind::Method
4726                                }
4727                            }
4728                        }
4729                        None => PropertyKind::Method,
4730                    };
4731                    let span = self.span_from(property_start);
4732                    properties.push(ObjectProperty::Property {
4733                        key,
4734                        value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
4735                        kind,
4736                        shorthand: false,
4737                        span,
4738                    });
4739                } else if self.eat_punct(Punct::Colon)? {
4740                    let value = self.parse_assignment(true)?;
4741                    if !is_computed
4742                        && let Some(PropKeyRef::Str(name)) = key.static_name()
4743                        && name == "__proto__"
4744                    {
4745                        proto_count += 1;
4746                        if proto_count > 1 {
4747                            return Err(self.error_at(
4748                                "duplicate __proto__ property name",
4749                                self.span_from(property_start),
4750                            ));
4751                        }
4752                    }
4753                    properties.push(ObjectProperty::Property {
4754                        key,
4755                        value: Box::new(value),
4756                        kind: PropertyKind::Value,
4757                        shorthand: false,
4758                        span: self.span_from(property_start),
4759                    });
4760                } else {
4761                    // Shorthand `{a}` / `{a = 1}` (the latter only inside a
4762                    // destructuring pattern).
4763                    let PropName::Literal(PropKey::Str(name)) = &key else {
4764                        return Err(self.error("expecting ':' after a property name"));
4765                    };
4766                    let ident_span = self.span_from(property_start);
4767                    let ident = Ident {
4768                        // A shorthand `{"\uD800" as a name}` is not a thing: a binding name
4769                        // is an identifier, so this path is only reached for text that is
4770                        // already valid; the lossy conversion cannot lose anything here.
4771                        name: name.to_string_lossy().into_owned(),
4772                        span: ident_span,
4773                    };
4774                    self.check_identifier(&ident.name, ident.span)?;
4775                    let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
4776                    if self.at_punct(Punct::Eq) {
4777                        // CoverInitializedName: only legal once the object turns
4778                        // out to be a destructuring pattern.
4779                        self.cover_inits.push(ident_span);
4780                        self.bump()?;
4781                        let default = self.parse_assignment(true)?;
4782                        let target = Pattern::new(PatternKind::Ident(ident), ident_span);
4783                        value = Expr::new(
4784                            ExprKind::Assign {
4785                                op: AssignOp::Assign,
4786                                target: Box::new(target),
4787                                value: Box::new(default),
4788                            },
4789                            ident_span,
4790                        );
4791                    }
4792                    properties.push(ObjectProperty::Property {
4793                        key,
4794                        value: Box::new(value),
4795                        kind: PropertyKind::Value,
4796                        shorthand: true,
4797                        span: ident_span,
4798                    });
4799                }
4800            }
4801            if !self.eat_punct(Punct::Comma)? {
4802                break;
4803            }
4804        }
4805        self.expect_punct(Punct::RBrace)?;
4806        Ok(Expr::new(
4807            ExprKind::Object(properties),
4808            self.span_from(start),
4809        ))
4810    }
4811
4812    fn parse_template(&mut self) -> Result<TemplateLiteral> {
4813        let mut quasis = Vec::new();
4814        let mut expressions = Vec::new();
4815        loop {
4816            let (cooked, raw, kind) = match self.current.kind.clone() {
4817                TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
4818                _ => return Err(self.error("expecting a template literal")),
4819            };
4820            let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
4821            quasis.push(TemplateChunk { cooked, raw, tail });
4822            if tail {
4823                self.bump()?;
4824                break;
4825            }
4826            self.bump()?; // move to the first token of the substitution
4827            let expr = self.parse_expression(true)?;
4828            expressions.push(expr);
4829            if !self.at_punct(Punct::RBrace) {
4830                return Err(self.error("expecting '}' in a template substitution"));
4831            }
4832            let brace = self.current.span.start;
4833            let token = self.lexer.re_scan_template_continue(brace)?;
4834            self.current = token;
4835        }
4836        Ok(TemplateLiteral {
4837            quasis,
4838            expressions,
4839        })
4840    }
4841}
4842
4843/// Which kind of function is being parsed (affects whether a name is required).
4844#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4845enum FunctionForm {
4846    Declaration,
4847    Expression,
4848}
4849
4850/// Names of the parameters that participate in declaration-conflict checks.
4851///
4852/// Engines only check *simple* (identifier) parameters against the body's
4853/// lexical declarations: `function f(a) { let a; }` is an early error, but
4854/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
4855/// deliberately follows the reference rather than ES2025 §10.2.1).
4856/// Whether this parameter is a bare identifier, as opposed to a pattern.
4857fn is_plain_identifier(param: &Pattern) -> bool {
4858    matches!(param.unparen_kind(), PatternKind::Ident(_))
4859}
4860
4861/// Every name `param` binds, in binding order, tagged with whether it sits inside a
4862/// destructuring pattern.
4863///
4864/// A rest parameter is a pattern only when its target is: `...a` binds like a plain name,
4865/// while `...[a]` does not.
4866fn parameter_bindings(param: &Pattern) -> Vec<(String, Span, bool)> {
4867    fn walk(pattern: &Pattern, in_pattern: bool, out: &mut Vec<(String, Span, bool)>) {
4868        match &pattern.kind {
4869            PatternKind::Ident(ident) => out.push((ident.name.clone(), ident.span, in_pattern)),
4870            PatternKind::Assign { target, default } => {
4871                walk(target, in_pattern, out);
4872                // A default's own expression can bind nothing, so only the target is walked.
4873                let _ = default;
4874            }
4875            PatternKind::Rest(target) => walk(target, !is_plain_identifier(target), out),
4876            PatternKind::Array { .. } | PatternKind::Object { .. } => {
4877                let mut names = Vec::new();
4878                pattern.bound_names(&mut names);
4879                for name in names {
4880                    out.push((name.name, name.span, true));
4881                }
4882            }
4883            _ => {}
4884        }
4885    }
4886    let mut out = Vec::new();
4887    let in_pattern = !is_plain_identifier(param);
4888    walk(param, in_pattern, &mut out);
4889    // A pattern's own walk above already flagged its names; a plain identifier or a
4890    // defaulted one goes through `walk` directly.
4891    if out.is_empty() {
4892        let mut names = Vec::new();
4893        param.bound_names(&mut names);
4894        out.extend(names.into_iter().map(|name| (name.name, name.span, false)));
4895    }
4896    out
4897}
4898
4899/// Whether any binding in `pattern` carries a default value.
4900///
4901/// This is the closest stand-in we have for the reference's lookahead: it scans the
4902/// parenthesised parameter text for an `=` (`SKIP_HAS_ASSIGNMENT`) *before* parsing it, and
4903/// that flag decides which of the two duplicate-name messages a later conflict gets.
4904fn pattern_has_default(pattern: &Pattern) -> bool {
4905    let element = |element: &Option<PatternElement>| {
4906        element.as_ref().is_some_and(|element| match element {
4907            PatternElement::Pattern(inner) => pattern_has_default(inner),
4908            PatternElement::Property { value, .. } => pattern_has_default(value),
4909        })
4910    };
4911    let rest = |rest: &Option<Box<RestElement>>| {
4912        rest.as_ref().is_some_and(|rest| match rest.as_ref() {
4913            RestElement::Pattern(inner) => pattern_has_default(inner),
4914            RestElement::Member(_) => false,
4915        })
4916    };
4917    match &pattern.kind {
4918        PatternKind::Assign { .. } => true,
4919        PatternKind::Array {
4920            elements,
4921            rest: tail,
4922        } => elements.iter().any(element) || rest(tail),
4923        PatternKind::Object {
4924            properties,
4925            rest: tail,
4926        } => properties.iter().any(element) || rest(tail),
4927        PatternKind::Rest(target) => pattern_has_default(target),
4928        _ => false,
4929    }
4930}
4931
4932fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
4933    params
4934        .iter()
4935        .filter_map(|param| match &param.kind {
4936            PatternKind::Ident(id) => Some(id.name.clone()),
4937            _ => None,
4938        })
4939        .collect()
4940}
4941
4942/// Collect the names a top-level module item declares, for the exported-name
4943/// check.
4944fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
4945    match &stmt.kind {
4946        StmtKind::VarDecl(decl) => {
4947            // A `using` declaration is a lexical binding of the module's own scope but not
4948            // a *module variable*, so it cannot be exported: the reference excludes it from
4949            // `add_global_var` and `export {a}` of one reports
4950            // `exported variable 'a' does not exist`. Leaving it in this list would make
4951            // that export silently succeed.
4952            if decl.kind.is_using() {
4953                return;
4954            }
4955            for declarator in &decl.declarators {
4956                let mut names = Vec::new();
4957                declarator.target.bound_names(&mut names);
4958                out.extend(names.into_iter().map(|n| n.name));
4959            }
4960        }
4961        StmtKind::FuncDecl(func) => {
4962            if let Some(name) = &func.name {
4963                out.push(name.name.clone());
4964            }
4965        }
4966        StmtKind::ClassDecl(class) => {
4967            if let Some(name) = &class.name {
4968                out.push(name.name.clone());
4969            }
4970        }
4971        StmtKind::Import(decl) => {
4972            for specifier in &decl.specifiers {
4973                match specifier {
4974                    ImportSpecifier::Default(id) => out.push(id.name.clone()),
4975                    ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
4976                    ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
4977                }
4978            }
4979        }
4980        StmtKind::Export(decl) => match &decl.kind {
4981            ExportKind::Declaration(inner) => collect_module_binding(inner, out),
4982            ExportKind::Default(expr) => match &expr.unparen().kind {
4983                ExprKind::Function(func) => {
4984                    if let Some(name) = &func.name {
4985                        out.push(name.name.clone());
4986                    }
4987                }
4988                ExprKind::Class(class) => {
4989                    if let Some(name) = &class.name {
4990                        out.push(name.name.clone());
4991                    }
4992                }
4993                _ => {}
4994            },
4995            _ => {}
4996        },
4997        _ => {}
4998    }
4999}
5000
5001/// Whether `inner` is fully inside `outer` (byte offset comparison only).
5002fn span_contains(outer: Span, inner: Span) -> bool {
5003    inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
5004}
5005
5006fn is_property_key_start(kind: &TokenKind) -> bool {
5007    matches!(
5008        kind,
5009        TokenKind::Ident(_)
5010            | TokenKind::Keyword(_)
5011            | TokenKind::String(_)
5012            | TokenKind::Number(_)
5013            | TokenKind::Punct(Punct::LBracket)
5014            | TokenKind::Punct(Punct::Hash)
5015    )
5016}
5017
5018/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
5019#[derive(Debug, Clone, Copy)]
5020enum BinOp {
5021    Binary(BinaryOp),
5022    Logical(LogicalOp),
5023}
5024
5025impl BinOp {
5026    fn is_right_associative(self) -> bool {
5027        matches!(self, BinOp::Binary(BinaryOp::Pow))
5028    }
5029}
5030
5031fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
5032    use BinaryOp as B;
5033    use LogicalOp as L;
5034    let result = match kind {
5035        TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
5036        TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
5037        TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
5038        TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
5039        TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
5040        TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
5041        TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
5042        TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
5043        TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
5044        TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
5045        TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
5046        TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
5047        TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
5048        TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
5049        TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
5050        TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
5051        TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
5052        TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
5053        TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
5054        TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
5055        TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
5056        TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
5057        TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
5058        TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
5059        TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
5060        _ => return None,
5061    };
5062    Some(result)
5063}
5064
5065fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
5066    match op {
5067        BinOp::Binary(op) => Ok(Expr::at_operator(
5068            ExprKind::Binary {
5069                op,
5070                left: Box::new(left),
5071                right: Box::new(right),
5072            },
5073            span,
5074            op_pos,
5075        )),
5076        BinOp::Logical(op) => {
5077            // `??` may not be mixed with `&&`/`||` without parentheses.
5078            // A parenthesised operand is visibly a different production, so the
5079            // check must look at the raw node, not through `Paren`.
5080            let mixes = |expr: &Expr, op: LogicalOp| {
5081                matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
5082                    if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
5083            };
5084            if mixes(&left, op) || mixes(&right, op) {
5085                return Err(SyntaxError::new(
5086                    // The reference has no quotes in this one; the parenthesised form is the only
5087                    // way to write it, which the message states rather than implies.
5088                    "cannot mix ?? with && or ||",
5089                    span,
5090                ));
5091            }
5092            Ok(Expr::at_operator(
5093                ExprKind::Logical {
5094                    op,
5095                    left: Box::new(left),
5096                    right: Box::new(right),
5097                },
5098                span,
5099                op_pos,
5100            ))
5101        }
5102    }
5103}
5104
5105/// Rebuild an expression from a pattern (used when a pattern has to go back
5106/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
5107fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
5108    match pattern.kind {
5109        PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
5110        PatternKind::Assign { target, default } => Expr::new(
5111            ExprKind::Assign {
5112                op: AssignOp::Assign,
5113                target,
5114                value: default,
5115            },
5116            span,
5117        ),
5118        // A member target only ever reaches here by way of the cover grammar: `[o.p = 1]`
5119        // is parsed as an assignment whose target is already a pattern, and re-reading it
5120        // as an expression has to give the member back rather than a placeholder.
5121        PatternKind::Member(member) => {
5122            let MemberPattern {
5123                object,
5124                property,
5125                span,
5126                op_pos,
5127            } = *member;
5128            Expr {
5129                kind: ExprKind::Member {
5130                    object,
5131                    property,
5132                    optional: false,
5133                },
5134                span,
5135                op_pos,
5136            }
5137        }
5138        PatternKind::Object { properties, rest } => {
5139            let mut out = Vec::new();
5140            for element in properties {
5141                match element {
5142                    Some(PatternElement::Property {
5143                        key,
5144                        value,
5145                        shorthand,
5146                        span: _,
5147                    }) => {
5148                        let span = value.span;
5149                        out.push(ObjectProperty::Property {
5150                            key,
5151                            value: Box::new(pattern_to_expr(value, span)),
5152                            kind: PropertyKind::Value,
5153                            shorthand,
5154                            span,
5155                        });
5156                    }
5157                    // An object pattern's elements are always properties; a bare pattern
5158                    // here would be a malformed AST, and dropping it is the safe reading.
5159                    None | Some(PatternElement::Pattern(_)) => {}
5160                }
5161            }
5162            if let Some(rest) = rest
5163                && let RestElement::Pattern(pattern) = *rest
5164            {
5165                let span = pattern.span;
5166                out.push(ObjectProperty::Spread(Box::new(pattern_to_expr(
5167                    pattern, span,
5168                ))));
5169            }
5170            Expr::new(ExprKind::Object(out), span)
5171        }
5172        PatternKind::Array { elements, rest } => {
5173            let mut out = Vec::new();
5174            for element in elements {
5175                match element {
5176                    Some(PatternElement::Pattern(pattern)) => {
5177                        let span = pattern.span;
5178                        out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
5179                            pattern, span,
5180                        )))));
5181                    }
5182                    Some(PatternElement::Property { .. }) | None => out.push(None),
5183                }
5184            }
5185            if let Some(rest) = rest {
5186                let RestElement::Pattern(pattern) = *rest else {
5187                    return Expr::new(ExprKind::Null, span);
5188                };
5189                let span = pattern.span;
5190                out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
5191                    pattern, span,
5192                )))));
5193            }
5194            Expr::new(ExprKind::Array { elements: out }, span)
5195        }
5196        _ => Expr::new(ExprKind::Null, span),
5197    }
5198}
5199
5200impl Pattern {
5201    /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
5202    /// this keeps call sites uniform with [`Expr::unparen`]).
5203    fn unparen_kind(&self) -> &PatternKind {
5204        &self.kind
5205    }
5206}
5207
5208/// Whether this `delete` operand ultimately names a private member.
5209///
5210/// Whether this `delete` operand ultimately names a private member.
5211///
5212/// §13.5.1.1: `delete` may not be applied to a `MemberExpression : MemberExpression.PrivateName`
5213/// or a `CallExpression : CallExpression.PrivateName`, and the rule re-applies to a
5214/// parenthesised phrase. So the walk goes through parentheses and through a call's callee, and
5215/// stops everywhere else — including a sequence, because `delete (0, o.#x)` parenthesises
5216/// `0, o.#x`, and that phrase in place of the operand is `delete 0, o.#x`, which is legal. The
5217/// reference agrees: it accepts that one and rejects `delete (g().#x)`.
5218fn deletes_a_private_member(expr: &Expr) -> bool {
5219    match &expr.unparen().kind {
5220        ExprKind::Member { property, .. } => matches!(property, MemberProp::Private(_)),
5221        ExprKind::Call { callee, .. } => deletes_a_private_member(callee),
5222        _ => false,
5223    }
5224}
5225
5226/// A string that has to be a `&str` — a module specifier or an import attribute.
5227///
5228/// These reach the loader and the filesystem, neither of which can do anything with an
5229/// unpaired surrogate, so the lossy conversion is the honest one: it is what a path
5230/// encoding would do anyway. Every *other* cooked string in the tree keeps the surrogate,
5231/// because the language can observe it there.
5232fn as_specifier(value: &Wtf8) -> String {
5233    value.to_string_lossy().into_owned()
5234}