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