Skip to main content

js_parse/
parser.rs

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