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