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