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