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