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