Skip to main content

js_parse/
parser.rs

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