Skip to main content

js_parse/
parser.rs

1//! The parser: tokens to [`crate::ast`].
2//!
3//! A recursive-descent parser with precedence climbing for expressions. It
4//! follows the specification's grammar productions closely, which keeps the
5//! early errors next to the code that can detect them.
6//!
7//! Two productions need backtracking / reinterpretation, exactly as in an
8//! engine:
9//!
10//! * **arrow functions** use the cover grammar. `(` starts either a
11//!   parenthesized expression or a parameter list; the parser speculatively
12//!   parses a parameter list and commits only if `=>` follows, otherwise it
13//!   restores the lexer and parses an expression.
14//! * **`let`** at statement start is a declaration keyword when followed by a
15//!   binding, otherwise an identifier.
16//!
17//! Automatic semicolon insertion is implemented where the grammar allows it
18//! (`Stmt` terminators, `do…while`, `return`/`throw` restricted productions,
19//! postfix `++`/`--`, `async` before arrow parameters, `yield`/`await`).
20//!
21//! Early errors implemented here (not at run time):
22//!
23//! * `with`, legacy octal literals/escapes, `delete identifier`,
24//!   `eval`/`arguments` as binding or assignment target — strict mode only;
25//! * `super` outside a method, `super()` outside a derived constructor,
26//!   `new.target` outside a function;
27//! * `await`/`yield` used as identifiers where they are reserved;
28//! * duplicate `__proto__` in an object literal, duplicate private names;
29//! * `break`/`continue` target validity, `return` outside a function;
30//! * `??` mixed with `&&`/`||` without parentheses, `-x ** y`, assignment to a
31//!   non-assignable target, `new` on an optional chain;
32//! * duplicate parameter names (always for arrows/methods/non-simple lists).
33//!
34//! Not implemented yet (tracked for M1b.2): scope-analysis early errors such as
35//! `let x; let x;` in the same block, and parameter/`var` conflicts.
36
37use crate::ast::*;
38use crate::error::{Result, SyntaxError};
39use crate::lexer::Lexer;
40use crate::token::{Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, Token, TokenKind};
41
42/// Everything that has to be saved to backtrack.
43struct Snapshot<'a> {
44    lexer: Lexer<'a>,
45    current: Token,
46    prev_end: Position,
47    strict: bool,
48    allow_in: bool,
49    ctx: FnCtx,
50    loop_depth: u32,
51    switch_depth: u32,
52    labels: Vec<Label>,
53    private: Vec<PrivateEnv>,
54    top_level: bool,
55    cover_inits: Vec<Span>,
56    pending_exports: Vec<(String, Span)>,
57    current_legacy_octal: bool,
58    scopes: Vec<Scope>,
59}
60
61/// Context of the function currently being parsed.
62#[derive(Debug, Clone, Copy, Default)]
63struct FnCtx {
64    in_function: bool,
65    in_generator: bool,
66    in_async: bool,
67    /// Inside a method (or a nested arrow in one): `super.x` is legal.
68    in_method: bool,
69    /// Inside a derived class constructor: `super()` is legal.
70    in_derived_constructor: bool,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74enum LabelKind {
75    /// Labels a loop.
76    Iteration,
77    /// Labels any other statement.
78    Other,
79}
80
81#[derive(Debug, Clone)]
82struct Label {
83    name: String,
84    kind: LabelKind,
85}
86
87/// Private names declared by the class currently being parsed.
88#[derive(Debug, Clone, Default)]
89struct PrivateEnv {
90    names: Vec<PrivateName>,
91}
92
93#[derive(Debug, Clone)]
94struct PrivateName {
95    name: String,
96    has_get: bool,
97    has_set: bool,
98}
99
100impl PrivateEnv {
101    /// Register a private name. `get #x` + `set #x` is the only legal pair;
102    /// every other duplicate (including `get #x` twice) is an early error.
103    fn declare(&mut self, name: &str, accessor: Option<MethodKind>) -> bool {
104        if let Some(existing) = self.names.iter_mut().find(|n| n.name == name) {
105            return match accessor {
106                Some(MethodKind::Get) if !existing.has_get => {
107                    existing.has_get = true;
108                    true
109                }
110                Some(MethodKind::Set) if !existing.has_set => {
111                    existing.has_set = true;
112                    true
113                }
114                _ => false,
115            };
116        }
117        let mut entry = PrivateName {
118            name: name.to_string(),
119            has_get: false,
120            has_set: false,
121        };
122        match accessor {
123            Some(MethodKind::Get) => entry.has_get = true,
124            Some(MethodKind::Set) => entry.has_set = true,
125            _ => {}
126        }
127        self.names.push(entry);
128        true
129    }
130
131    fn contains(&self, name: &str) -> bool {
132        self.names.iter().any(|n| n.name == name)
133    }
134}
135
136/// One lexical scope, used for the declaration-conflict early errors.
137#[derive(Debug, Clone)]
138struct Scope {
139    /// Whether this is a function/module scope (where `var` lands).
140    is_var_scope: bool,
141    /// `var`-declared names.
142    var_names: Vec<String>,
143    /// `let`/`const`/`class`/`import` names declared directly in this scope.
144    lex_names: Vec<String>,
145    /// Function-declaration names declared directly in this scope.
146    ///
147    /// Tracked apart from `var_names` because engines treat them differently:
148    /// two function declarations may share a name, a function at the top level
149    /// does not clash with an earlier `let`, and a function inside a block is
150    /// scoped to that block instead of hoisting.
151    fn_names: Vec<String>,
152    /// Names of *simple* (identifier) parameters, if this is a function body.
153    params: Vec<String>,
154}
155
156impl Scope {
157    fn block() -> Scope {
158        Scope {
159            is_var_scope: false,
160            var_names: Vec::new(),
161            lex_names: Vec::new(),
162            fn_names: Vec::new(),
163            params: Vec::new(),
164        }
165    }
166
167    fn function(params: Vec<String>) -> Scope {
168        Scope {
169            is_var_scope: true,
170            var_names: Vec::new(),
171            lex_names: Vec::new(),
172            fn_names: Vec::new(),
173            params,
174        }
175    }
176}
177
178/// Which kind of target a pattern is being built for.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180enum TargetKind {
181    /// `let x = 1`, `function f(x)`, `catch (x)` — binds new names.
182    Binding,
183    /// `x = 1`, `[a, b] = c` — assigns to existing bindings.
184    Assignment,
185}
186
187/// The arrow head produced by a successful speculative parse.
188struct ArrowHead {
189    params: Vec<Pattern>,
190    is_async: bool,
191    span: Span,
192    params_span: Span,
193}
194
195/// Default nesting limit.
196///
197/// QuickJS stops at roughly 700 nested parentheses, because it compares the real
198/// stack pointer against `--stack-size` (1 MiB by default). This port cannot do
199/// that portably, so it counts recursion depth instead; the depth a given stack
200/// can hold depends on the frame size, which differs a lot between build
201/// profiles (measured on an 8 MiB stack: ~220 levels in debug, ~1500 in release).
202/// The limit is therefore profile-dependent and deliberately leaves headroom, so
203/// that over-deep input produces a `SyntaxError: stack overflow` — exactly what
204/// QuickJS reports — instead of aborting the process.
205///
206/// [`Parser::set_max_depth`] raises it for callers that know they have a bigger
207/// stack (or a release build).
208pub const DEFAULT_MAX_DEPTH: u32 = if cfg!(debug_assertions) { 120 } else { 600 };
209
210/// ECMAScript 2025 parser.
211pub struct Parser<'a> {
212    lexer: Lexer<'a>,
213    current: Token,
214    prev_end: Position,
215    strict: bool,
216    module: bool,
217    allow_in: bool,
218    ctx: FnCtx,
219    loop_depth: u32,
220    switch_depth: u32,
221    labels: Vec<Label>,
222    private: Vec<PrivateEnv>,
223    top_level: bool,
224    /// Whether the token currently held by the parser contains an Annex B octal
225    /// literal or escape (checked again when strictness is switched on).
226    current_legacy_octal: bool,
227    /// Current recursion depth, and the limit that turns it into a
228    /// `SyntaxError` instead of a stack overflow.
229    depth: u32,
230    max_depth: u32,
231
232    /// Spans of `{a = 1}` object-literal shorthands. They are only legal when
233    /// the object is converted to a destructuring pattern, so any entry left
234    /// over at the end of a statement is a syntax error.
235    cover_inits: Vec<Span>,
236    /// `export {name}` clauses whose local binding still has to be checked
237    /// against the module's declared names (forward references are legal).
238    pending_exports: Vec<(String, Span)>,
239    /// Open lexical scopes, innermost last.
240    scopes: Vec<Scope>,
241}
242
243/// Parse `src` as a `Script`.
244pub fn parse_script(src: &str) -> Result<Program> {
245    Parser::new(src, false)?.parse_program()
246}
247
248/// Parse `src` as a `Module`.
249pub fn parse_module(src: &str) -> Result<Program> {
250    Parser::new(src, true)?.parse_program()
251}
252
253/// Parse `src` as a `Script` whose code is strict from the first token.
254///
255/// This is what a *direct* `eval` needs: the eval'd code inherits strictness from the
256/// code that called it, so `eval("x = 1")` inside a strict function is a
257/// `ReferenceError` rather than an implicit global. Prepending a `"use strict"`
258/// directive instead would shift every column on the first line, and the positions are
259/// exactly what a stack trace has to report.
260pub fn parse_script_strict(src: &str) -> Result<Program> {
261    let mut parser = Parser::new(src, false)?;
262    parser.enter_strict()?;
263    parser.parse_program()
264}
265
266/// Parse `src` as a single `Expression` (used by tests and by `eval`-like entry
267/// points that need the expression grammar only).
268pub fn parse_expression(src: &str) -> Result<Expr> {
269    let mut parser = Parser::new(src, false)?;
270    let expr = parser.parse_expression(true)?;
271    if !parser.current.is_eof() {
272        return Err(parser.unexpected());
273    }
274    Ok(expr)
275}
276
277impl<'a> Parser<'a> {
278    /// Create a parser over `src`. A module is always strict.
279    pub fn new(src: &'a str, module: bool) -> Result<Parser<'a>> {
280        let mut lexer = Lexer::new(src);
281        lexer.set_strict(module);
282        let current = lexer.next_token()?;
283        let current_legacy_octal = lexer.had_legacy_octal();
284        if module && current_legacy_octal {
285            return Err(SyntaxError::new(
286                "octal literals and octal escape sequences are not allowed in strict mode",
287                current.span,
288            ));
289        }
290        Ok(Parser {
291            lexer,
292            current,
293            prev_end: Position::START,
294            strict: module,
295            module,
296            allow_in: true,
297            ctx: FnCtx::default(),
298            loop_depth: 0,
299            switch_depth: 0,
300            labels: Vec::new(),
301            private: Vec::new(),
302            top_level: true,
303            current_legacy_octal,
304            depth: 0,
305            max_depth: DEFAULT_MAX_DEPTH,
306
307            cover_inits: Vec::new(),
308            pending_exports: Vec::new(),
309            scopes: vec![Scope::function(Vec::new())],
310        })
311    }
312
313    /// Raise or lower the nesting limit.
314    pub fn set_max_depth(&mut self, depth: u32) {
315        self.max_depth = depth;
316    }
317
318    /// Enter one level of recursion.
319    fn enter(&mut self) -> Result<()> {
320        self.depth += 1;
321        if self.depth > self.max_depth {
322            return Err(SyntaxError::new("stack overflow", self.current.span));
323        }
324        Ok(())
325    }
326
327    fn leave(&mut self) {
328        self.depth -= 1;
329    }
330
331    /// Parse the whole source.
332    pub fn parse_program(&mut self) -> Result<Program> {
333        let start = self.current.span.start;
334        let mut body = Vec::new();
335        let mut prologue = true;
336        while !self.current.is_eof() {
337            let stmt = self.parse_statement_list_item()?;
338            if prologue {
339                match self.directive_value(&stmt) {
340                    Some(directive) if directive == "use strict" => self.enter_strict()?,
341                    Some(_) => {}
342                    None => prologue = false,
343                }
344            }
345            body.push(stmt);
346        }
347        if self.module {
348            self.check_module_exports(&body)?;
349        }
350        Ok(Program {
351            kind: if self.module {
352                ProgramKind::Module
353            } else {
354                ProgramKind::Script
355            },
356            body,
357            span: Span::new(start, self.prev_end),
358            strict: self.strict,
359        })
360    }
361
362    /// `export {a}` requires `a` to be declared somewhere in the module (forward
363    /// references are legal, so this can only run once the whole body is known).
364    fn check_module_exports(&mut self, body: &[Stmt]) -> Result<()> {
365        if self.pending_exports.is_empty() {
366            return Ok(());
367        }
368        let mut declared: Vec<String> = Vec::new();
369        for stmt in body {
370            collect_module_binding(stmt, &mut declared);
371        }
372        let pending = std::mem::take(&mut self.pending_exports);
373        for (name, span) in pending {
374            if !declared.contains(&name) {
375                return Err(
376                    self.error_at(format!("exported variable '{name}' does not exist"), span)
377                );
378            }
379        }
380        Ok(())
381    }
382
383    // -- declaration tracking (early errors) -------------------------------
384
385    fn push_scope(&mut self, scope: Scope) {
386        self.scopes.push(scope);
387    }
388
389    fn pop_scope(&mut self) {
390        self.scopes.pop();
391    }
392
393    /// Declare a `let`/`const`/`class`/`import` name in the current scope.
394    ///
395    /// Conflicts are per scope: a lexical declaration clashes with another
396    /// lexical declaration, a `var`/function declaration or a simple parameter
397    /// *of the same scope*. `var a; { let a; }` is legal, `{ let a; { var a; } }`
398    /// is not (the `var` hoists past the `let`, which `declare_var` checks).
399    fn declare_lexical(&mut self, name: &str, span: Span) -> Result<()> {
400        let Some(scope) = self.scopes.last() else {
401            return Ok(());
402        };
403        let clashes = scope.lex_names.iter().any(|n| n == name)
404            || scope.var_names.iter().any(|n| n == name)
405            || scope.fn_names.iter().any(|n| n == name)
406            || scope.params.iter().any(|n| n == name);
407        if clashes {
408            return Err(self.duplicate_declaration(name, span));
409        }
410        if let Some(scope) = self.scopes.last_mut() {
411            scope.lex_names.push(name.to_string());
412        }
413        Ok(())
414    }
415
416    /// Declare a `var` or function-declaration name: it hoists to the nearest
417    /// function scope, but may not collide with a lexical name on the way up.
418    fn declare_var(&mut self, name: &str, span: Span) -> Result<()> {
419        for scope in self.scopes.iter().rev() {
420            if scope.lex_names.iter().any(|n| n == name) {
421                return Err(self.duplicate_declaration(name, span));
422            }
423            if scope.is_var_scope {
424                break;
425            }
426        }
427        let Some(index) = self.scopes.iter().rposition(|s| s.is_var_scope) else {
428            return Ok(());
429        };
430        // Record it in every scope it passes through: `{ var a; let a; }` is an
431        // early error because the block's VarDeclaredNames contain `a`.
432        for scope in &mut self.scopes[index..] {
433            if !scope.var_names.iter().any(|n| n == name) {
434                scope.var_names.push(name.to_string());
435            }
436        }
437        Ok(())
438    }
439
440    /// Declare a function declaration name.
441    ///
442    /// See [`Scope::fn_names`] for why this is not the same as a `var`.
443    fn declare_function(&mut self, name: &str, span: Span) -> Result<()> {
444        let in_var_scope = self.scopes.last().is_none_or(|s| s.is_var_scope);
445        if !in_var_scope {
446            let clashes = self
447                .scopes
448                .last()
449                .is_some_and(|s| s.lex_names.iter().any(|n| n == name));
450            if clashes {
451                return Err(self.duplicate_declaration(name, span));
452            }
453        } else if let Some(scope) = self.scopes.last_mut() {
454            if !scope.var_names.iter().any(|n| n == name) {
455                scope.var_names.push(name.to_string());
456            }
457        }
458        if let Some(scope) = self.scopes.last_mut() {
459            if !scope.fn_names.iter().any(|n| n == name) {
460                scope.fn_names.push(name.to_string());
461            }
462        }
463        Ok(())
464    }
465
466    fn duplicate_declaration(&self, name: &str, span: Span) -> SyntaxError {
467        self.error_at(
468            format!("identifier '{name}' has already been declared"),
469            span,
470        )
471    }
472
473    /// Declare every name bound by a pattern.
474    fn declare_pattern(&mut self, pattern: &Pattern, is_var: bool) -> Result<()> {
475        let mut names = Vec::new();
476        pattern.bound_names(&mut names);
477        for name in names {
478            if is_var {
479                self.declare_var(&name.name, name.span)?;
480            } else {
481                self.declare_lexical(&name.name, name.span)?;
482            }
483        }
484        Ok(())
485    }
486
487    // -- token helpers -----------------------------------------------------
488
489    fn snapshot(&self) -> Snapshot<'a> {
490        Snapshot {
491            lexer: self.lexer.clone(),
492            current: self.current.clone(),
493            prev_end: self.prev_end,
494            strict: self.strict,
495            allow_in: self.allow_in,
496            ctx: self.ctx,
497            loop_depth: self.loop_depth,
498            switch_depth: self.switch_depth,
499            labels: self.labels.clone(),
500            private: self.private.clone(),
501            top_level: self.top_level,
502            cover_inits: self.cover_inits.clone(),
503            pending_exports: self.pending_exports.clone(),
504            current_legacy_octal: self.current_legacy_octal,
505            scopes: self.scopes.clone(),
506        }
507    }
508
509    fn restore(&mut self, snap: Snapshot<'a>) {
510        self.lexer = snap.lexer;
511        self.current = snap.current;
512        self.prev_end = snap.prev_end;
513        self.strict = snap.strict;
514        self.allow_in = snap.allow_in;
515        self.ctx = snap.ctx;
516        self.loop_depth = snap.loop_depth;
517        self.switch_depth = snap.switch_depth;
518        self.labels = snap.labels;
519        self.private = snap.private;
520        self.top_level = snap.top_level;
521        self.cover_inits = snap.cover_inits;
522        self.pending_exports = snap.pending_exports;
523        self.current_legacy_octal = snap.current_legacy_octal;
524        self.scopes = snap.scopes;
525    }
526
527    fn bump(&mut self) -> Result<()> {
528        self.prev_end = self.current.span.end;
529        self.current = self.lexer.next_token()?;
530        self.current_legacy_octal = self.lexer.had_legacy_octal();
531        if self.strict && self.current_legacy_octal {
532            return Err(SyntaxError::new(
533                "octal literals and octal escape sequences are not allowed in strict mode",
534                self.current.span,
535            ));
536        }
537        Ok(())
538    }
539
540    fn peek(&self) -> Result<Token> {
541        let mut lexer = self.lexer.clone();
542        lexer.next_token()
543    }
544
545    fn enter_strict(&mut self) -> Result<()> {
546        self.strict = true;
547        self.lexer.set_strict(true);
548        // The token after the `"use strict"` directive has already been scanned
549        // with the old (sloppy) rules.
550        if self.current_legacy_octal {
551            return Err(SyntaxError::new(
552                "octal literals and octal escape sequences are not allowed in strict mode",
553                self.current.span,
554            ));
555        }
556        Ok(())
557    }
558
559    fn at_punct(&self, p: Punct) -> bool {
560        matches!(&self.current.kind, TokenKind::Punct(q) if *q == p)
561    }
562
563    fn at_keyword(&self, k: Keyword) -> bool {
564        matches!(&self.current.kind, TokenKind::Keyword(q) if *q == k)
565    }
566
567    fn at_contextual(&self, name: &str) -> bool {
568        self.at_ident(name)
569    }
570
571    fn at_ident(&self, name: &str) -> bool {
572        matches!(&self.current.kind, TokenKind::Ident(n) if n == name)
573    }
574
575    fn eat_punct(&mut self, p: Punct) -> Result<bool> {
576        if self.at_punct(p) {
577            self.bump()?;
578            return Ok(true);
579        }
580        Ok(false)
581    }
582
583    fn expect_punct(&mut self, p: Punct) -> Result<()> {
584        if self.eat_punct(p)? {
585            Ok(())
586        } else {
587            Err(self.unexpected())
588        }
589    }
590
591    fn eat_keyword(&mut self, k: Keyword) -> Result<bool> {
592        if self.at_keyword(k) {
593            self.bump()?;
594            return Ok(true);
595        }
596        Ok(false)
597    }
598
599    fn eat_contextual(&mut self, name: &str) -> Result<bool> {
600        if self.at_ident(name) {
601            self.bump()?;
602            return Ok(true);
603        }
604        Ok(false)
605    }
606
607    fn unexpected(&self) -> SyntaxError {
608        SyntaxError::new(
609            format!("unexpected token: {}", self.current.kind.describe()),
610            self.current.span,
611        )
612    }
613
614    fn error(&self, message: impl Into<String>) -> SyntaxError {
615        SyntaxError::new(message, self.current.span)
616    }
617
618    fn error_at(&self, message: impl Into<String>, span: Span) -> SyntaxError {
619        SyntaxError::new(message, span)
620    }
621
622    fn span_from(&self, start: Position) -> Span {
623        Span::new(start, self.prev_end)
624    }
625
626    /// Read an identifier that *binds* a name, applying the binding rules
627    /// (`eval`/`arguments`/`let` are restricted in strict mode).
628    fn expect_binding_ident(&mut self) -> Result<Ident> {
629        let ident = self.expect_ident()?;
630        self.check_binding_name(&ident.name, ident.span)?;
631        Ok(ident)
632    }
633
634    /// Read an identifier, rejecting reserved words.
635    fn expect_ident(&mut self) -> Result<Ident> {
636        match self.current.kind.clone() {
637            TokenKind::Ident(name) => {
638                let span = self.current.span;
639                self.check_identifier(&name, span)?;
640                self.bump()?;
641                Ok(Ident { name, span })
642            }
643            _ => Err(self.error(format!(
644                "expecting a variable name, got {}",
645                self.current.kind.describe()
646            ))),
647        }
648    }
649
650    /// Reject words that may not appear as an `IdentifierReference` here.
651    fn check_identifier(&self, name: &str, span: Span) -> Result<()> {
652        if Keyword::lookup(name).is_some() {
653            return Err(self.error_at(format!("unexpected keyword '{name}'"), span));
654        }
655        if self.strict && Keyword::is_strict_reserved(name) {
656            return Err(self.error_at(
657                format!("invalid use of strict mode reserved word '{name}'"),
658                span,
659            ));
660        }
661        if self.ctx.in_generator && name == "yield" {
662            return Err(self.error_at(
663                "invalid use of 'yield' identifier in a generator function",
664                span,
665            ));
666        }
667        if self.ctx.in_async && name == "await" {
668            return Err(self.error_at("unexpected 'await' identifier in an async function", span));
669        }
670        Ok(())
671    }
672
673    /// A declarative name (`let`, `class`, `function`, parameter): stricter than
674    /// an identifier reference because `let` is reserved in strict mode.
675    fn check_binding_name(&self, name: &str, span: Span) -> Result<()> {
676        self.check_identifier(name, span)?;
677        if self.strict && (name == "eval" || name == "arguments") {
678            return Err(self.error_at(
679                format!("invalid use of '{name}' as a binding in strict mode"),
680                span,
681            ));
682        }
683        if self.strict && name == "let" {
684            return Err(self.error_at(
685                "invalid use of 'let' as a variable name in strict mode",
686                span,
687            ));
688        }
689        Ok(())
690    }
691
692    /// The value of an expression statement that is a string literal with no
693    /// escape sequences (a directive prologue candidate).
694    fn directive_value(&self, stmt: &Stmt) -> Option<String> {
695        let StmtKind::Expr(expr) = &stmt.kind else {
696            return None;
697        };
698        let ExprKind::String(value) = &expr.unparen().kind else {
699            return None;
700        };
701        let raw = self.slice(expr.span);
702        if !raw.starts_with('"') && !raw.starts_with('\'') {
703            return None;
704        }
705        if raw.trim_matches(|c| c == '"' || c == '\'').contains('\\') {
706            return None;
707        }
708        Some(value.clone())
709    }
710
711    fn slice(&self, span: Span) -> &'a str {
712        let src = self.lexer.source();
713        let start = span.start.offset as usize;
714        let end = (span.end.offset as usize).min(src.len());
715        src.get(start..end).unwrap_or("")
716    }
717
718    // -- automatic semicolon insertion ------------------------------------
719
720    fn can_insert_semicolon(&self) -> bool {
721        self.current.is_eof() || self.at_punct(Punct::RBrace) || self.current.newline_before
722    }
723
724    fn semicolon(&mut self) -> Result<()> {
725        if self.eat_punct(Punct::Semicolon)? {
726            return Ok(());
727        }
728        if self.can_insert_semicolon() {
729            return Ok(());
730        }
731        Err(self.unexpected())
732    }
733
734    // -- statements --------------------------------------------------------
735
736    fn parse_statement_list_item(&mut self) -> Result<Stmt> {
737        self.enter()?;
738        let result = self.parse_statement_list_item_guarded();
739        self.leave();
740        result
741    }
742
743    fn parse_statement_list_item_guarded(&mut self) -> Result<Stmt> {
744        let cover_mark = self.cover_inits.len();
745        let stmt = self.parse_statement_list_item_inner()?;
746        if self.cover_inits.len() > cover_mark {
747            let span = self.cover_inits[cover_mark];
748            self.cover_inits.truncate(cover_mark);
749            return Err(self.error_at("expecting '}'", span));
750        }
751        Ok(stmt)
752    }
753
754    fn parse_statement_list_item_inner(&mut self) -> Result<Stmt> {
755        if self.at_keyword(Keyword::Function) {
756            let start = self.current.span.start;
757            let func = self.parse_function(FunctionForm::Declaration, false)?;
758            if let Some(name) = &func.name {
759                self.declare_function(&name.name, name.span)?;
760            }
761            return Ok(Stmt::new(
762                StmtKind::FuncDecl(Box::new(func)),
763                self.span_from(start),
764            ));
765        }
766        if self.at_ident("async") {
767            let peek = self.peek()?;
768            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
769                let start = self.current.span.start;
770                self.bump()?; // async
771                let func = self.parse_function(FunctionForm::Declaration, true)?;
772                if let Some(name) = &func.name {
773                    self.declare_function(&name.name, name.span)?;
774                }
775                return Ok(Stmt::new(
776                    StmtKind::FuncDecl(Box::new(func)),
777                    self.span_from(start),
778                ));
779            }
780        }
781        if self.at_keyword(Keyword::Class) {
782            let start = self.current.span.start;
783            let class = self.parse_class(false)?;
784            if let Some(name) = &class.name {
785                self.declare_lexical(&name.name, name.span)?;
786            }
787            return Ok(Stmt::new(
788                StmtKind::ClassDecl(Box::new(class)),
789                self.span_from(start),
790            ));
791        }
792        if self.at_keyword(Keyword::Var) {
793            let start = self.current.span.start;
794            let decl = self.parse_var_decl(VarDeclKind::Var, false, true)?;
795            self.semicolon()?;
796            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
797        }
798        if self.at_keyword(Keyword::Const) {
799            let start = self.current.span.start;
800            let decl = self.parse_var_decl(VarDeclKind::Const, false, true)?;
801            self.semicolon()?;
802            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
803        }
804        if self.at_ident("let") && self.let_starts_declaration()? {
805            let start = self.current.span.start;
806            let decl = self.parse_var_decl(VarDeclKind::Let, false, true)?;
807            self.semicolon()?;
808            return Ok(Stmt::new(StmtKind::VarDecl(decl), self.span_from(start)));
809        }
810        if self.module && self.at_keyword(Keyword::Import) {
811            let peek = self.peek()?;
812            // `import(` and `import.meta` are expressions, not declarations.
813            if !matches!(
814                peek.kind,
815                TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::Dot)
816            ) {
817                return self.parse_import_decl();
818            }
819        }
820        if self.module && self.at_keyword(Keyword::Export) {
821            return self.parse_export_decl();
822        }
823        self.parse_statement()
824    }
825
826    /// `let` is a declaration keyword when followed by a binding or a pattern.
827    fn let_starts_declaration(&self) -> Result<bool> {
828        let peek = self.peek()?;
829        Ok(matches!(
830            peek.kind,
831            TokenKind::Ident(_)
832                | TokenKind::Punct(Punct::LBracket)
833                | TokenKind::Punct(Punct::LBrace)
834        ))
835    }
836
837    fn parse_statement(&mut self) -> Result<Stmt> {
838        let start = self.current.span.start;
839        if self.at_punct(Punct::Semicolon) {
840            self.bump()?;
841            return Ok(Stmt::new(StmtKind::Empty, self.span_from(start)));
842        }
843        if self.at_punct(Punct::LBrace) {
844            let body = self.parse_block()?;
845            return Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)));
846        }
847        if self.at_keyword(Keyword::If) {
848            return self.parse_if();
849        }
850        if self.at_keyword(Keyword::Do) {
851            return self.parse_do_while();
852        }
853        if self.at_keyword(Keyword::While) {
854            return self.parse_while();
855        }
856        if self.at_keyword(Keyword::For) {
857            return self.parse_for();
858        }
859        if self.at_keyword(Keyword::Switch) {
860            return self.parse_switch();
861        }
862        if self.at_keyword(Keyword::Try) {
863            return self.parse_try();
864        }
865        if self.at_keyword(Keyword::Return) {
866            return self.parse_return();
867        }
868        if self.at_keyword(Keyword::Throw) {
869            return self.parse_throw();
870        }
871        if self.at_keyword(Keyword::Break) {
872            return self.parse_break_continue(true);
873        }
874        if self.at_keyword(Keyword::Continue) {
875            return self.parse_break_continue(false);
876        }
877        if self.at_keyword(Keyword::With) {
878            return self.parse_with();
879        }
880        if self.at_keyword(Keyword::Debugger) {
881            self.bump()?;
882            self.semicolon()?;
883            return Ok(Stmt::new(StmtKind::Debugger, self.span_from(start)));
884        }
885        if self.at_keyword(Keyword::Function) {
886            // Annex B: function declarations in statement position are legal in
887            // sloppy mode (`if (x) function f() {}`).
888            if self.strict {
889                return Err(
890                    self.error("invalid 'function' declaration in a single statement context")
891                );
892            }
893            let func = self.parse_function(FunctionForm::Declaration, false)?;
894            if let Some(name) = &func.name {
895                self.declare_function(&name.name, name.span)?;
896            }
897            return Ok(Stmt::new(
898                StmtKind::FuncDecl(Box::new(func)),
899                self.span_from(start),
900            ));
901        }
902        if self.at_keyword(Keyword::Class) {
903            return Err(self.error("invalid 'class' declaration in a single statement context"));
904        }
905        if self.at_keyword(Keyword::Import) {
906            return Err(self.error("'import' can only appear at the top level of a module"));
907        }
908        if self.at_keyword(Keyword::Export) {
909            return Err(self.error("'export' can only appear at the top level of a module"));
910        }
911        // Labelled statement.
912        if matches!(self.current.kind, TokenKind::Ident(_)) {
913            let peek = self.peek()?;
914            if matches!(peek.kind, TokenKind::Punct(Punct::Colon)) {
915                return self.parse_labeled();
916            }
917        }
918        self.parse_expression_statement()
919    }
920
921    fn parse_block(&mut self) -> Result<Vec<Stmt>> {
922        self.expect_punct(Punct::LBrace)?;
923        self.push_scope(Scope::block());
924        let result = self.parse_block_body();
925        self.pop_scope();
926        let body = result?;
927        self.bump()?; // }
928        Ok(body)
929    }
930
931    /// `{ … }` of a `catch` clause: parsed in the scope holding its parameter.
932    fn parse_catch_body(&mut self) -> Result<Vec<Stmt>> {
933        self.expect_punct(Punct::LBrace)?;
934        let body = self.parse_block_body()?;
935        self.bump()?; // }
936        Ok(body)
937    }
938
939    fn parse_block_body(&mut self) -> Result<Vec<Stmt>> {
940        let mut body = Vec::new();
941        while !self.at_punct(Punct::RBrace) {
942            if self.current.is_eof() {
943                return Err(self.unexpected());
944            }
945            body.push(self.parse_statement_list_item()?);
946        }
947        Ok(body)
948    }
949
950    fn parse_expression_statement(&mut self) -> Result<Stmt> {
951        let start = self.current.span.start;
952        let expr = self.parse_expression(true)?;
953        self.semicolon()?;
954        Ok(Stmt::new(
955            StmtKind::Expr(Box::new(expr)),
956            self.span_from(start),
957        ))
958    }
959
960    fn parse_if(&mut self) -> Result<Stmt> {
961        let start = self.current.span.start;
962        self.bump()?; // if
963        self.expect_punct(Punct::LParen)?;
964        let test = self.parse_expression(true)?;
965        self.expect_punct(Punct::RParen)?;
966        let cons = self.parse_statement()?;
967        let alt = if self.eat_keyword(Keyword::Else)? {
968            Some(Box::new(self.parse_statement()?))
969        } else {
970            None
971        };
972        Ok(Stmt::new(
973            StmtKind::If {
974                test: Box::new(test),
975                cons: Box::new(cons),
976                alt,
977            },
978            self.span_from(start),
979        ))
980    }
981
982    fn parse_do_while(&mut self) -> Result<Stmt> {
983        let start = self.current.span.start;
984        self.bump()?; // do
985        self.loop_depth += 1;
986        let body = self.parse_statement();
987        self.loop_depth -= 1;
988        let body = body?;
989        if !self.eat_keyword(Keyword::While)? {
990            return Err(self.unexpected());
991        }
992        self.expect_punct(Punct::LParen)?;
993        let test = self.parse_expression(true)?;
994        self.expect_punct(Punct::RParen)?;
995        // `do … while (x)` allows a missing semicolon even without a newline.
996        let _ = self.eat_punct(Punct::Semicolon)?;
997        Ok(Stmt::new(
998            StmtKind::DoWhile {
999                body: Box::new(body),
1000                test: Box::new(test),
1001            },
1002            self.span_from(start),
1003        ))
1004    }
1005
1006    fn parse_while(&mut self) -> Result<Stmt> {
1007        let start = self.current.span.start;
1008        self.bump()?; // while
1009        self.expect_punct(Punct::LParen)?;
1010        let test = self.parse_expression(true)?;
1011        self.expect_punct(Punct::RParen)?;
1012        self.loop_depth += 1;
1013        let body = self.parse_statement();
1014        self.loop_depth -= 1;
1015        Ok(Stmt::new(
1016            StmtKind::While {
1017                test: Box::new(test),
1018                body: Box::new(body?),
1019            },
1020            self.span_from(start),
1021        ))
1022    }
1023
1024    fn parse_for(&mut self) -> Result<Stmt> {
1025        let start = self.current.span.start;
1026        self.bump()?; // for
1027        self.push_scope(Scope::block());
1028        let result = self.parse_for_inner(start);
1029        self.pop_scope();
1030        result
1031    }
1032
1033    fn parse_for_inner(&mut self, start: Position) -> Result<Stmt> {
1034        let mut is_await = false;
1035        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
1036            let peek = self.peek()?;
1037            if matches!(peek.kind, TokenKind::Punct(Punct::LParen)) && !peek.newline_before {
1038                is_await = true;
1039                self.bump()?;
1040            }
1041        }
1042        self.expect_punct(Punct::LParen)?;
1043
1044        // `for (;;)`
1045        if self.at_punct(Punct::Semicolon) {
1046            self.bump()?;
1047            return self.parse_for_classic(start, None);
1048        }
1049
1050        // Declaration head.
1051        let decl_kind = if self.at_keyword(Keyword::Var) {
1052            Some(VarDeclKind::Var)
1053        } else if self.at_keyword(Keyword::Const) {
1054            Some(VarDeclKind::Const)
1055        } else if self.at_ident("let") && self.let_starts_declaration()? {
1056            Some(VarDeclKind::Let)
1057        } else {
1058            None
1059        };
1060        if let Some(kind) = decl_kind {
1061            let decl_start = self.current.span.start;
1062            let decl = self.parse_var_decl(kind, true, false)?;
1063            if self.at_for_head_keyword() {
1064                let is_of = self.at_contextual("of");
1065                if !is_of && decl.declarators.len() != 1 {
1066                    return Err(self.error_at(
1067                        "only one binding allowed in a for-in loop",
1068                        self.span_from(decl_start),
1069                    ));
1070                }
1071                if is_of && decl.declarators.len() != 1 {
1072                    return Err(self.error_at(
1073                        "only one binding allowed in a for-of loop",
1074                        self.span_from(decl_start),
1075                    ));
1076                }
1077                if let Some(declarator) = decl.declarators.first() {
1078                    if declarator.init.is_some() {
1079                        // `for (var x = 1 in y)` is legacy in sloppy mode only.
1080                        if is_of || kind.is_lexical() || self.strict {
1081                            return Err(self.error_at(
1082                                "for-in/of loop variable declaration may not have an initializer",
1083                                declarator.span,
1084                            ));
1085                        }
1086                    }
1087                }
1088                if is_await && !is_of {
1089                    return Err(self.error("for await is only valid with 'of'"));
1090                }
1091                self.bump()?; // in / of
1092                let right = self.parse_expression(true)?;
1093                self.expect_punct(Punct::RParen)?;
1094                self.loop_depth += 1;
1095                let body = self.parse_statement();
1096                self.loop_depth -= 1;
1097                let head = ForHead::VarDecl(decl);
1098                let span = self.span_from(start);
1099                return Ok(Stmt::new(
1100                    if is_of {
1101                        StmtKind::ForOf {
1102                            is_await,
1103                            left: head,
1104                            right: Box::new(right),
1105                            body: Box::new(body?),
1106                        }
1107                    } else {
1108                        StmtKind::ForIn {
1109                            left: head,
1110                            right: Box::new(right),
1111                            body: Box::new(body?),
1112                        }
1113                    },
1114                    span,
1115                ));
1116            }
1117            self.expect_punct(Punct::Semicolon)?;
1118            return self.parse_for_classic(start, Some(ForInit::VarDecl(decl)));
1119        }
1120
1121        // Expression head.
1122        let expr_start = self.current.span.start;
1123        let expr = self.parse_expression(false)?;
1124        if self.at_for_head_keyword() {
1125            let is_of = self.at_contextual("of");
1126            if is_await && !is_of {
1127                return Err(self.error("for await is only valid with 'of'"));
1128            }
1129            let target = self.expr_to_pattern(expr, TargetKind::Assignment)?;
1130            self.bump()?; // in / of
1131            let right = self.parse_expression(true)?;
1132            self.expect_punct(Punct::RParen)?;
1133            self.loop_depth += 1;
1134            let body = self.parse_statement();
1135            self.loop_depth -= 1;
1136            let head = ForHead::Assign(Box::new(target));
1137            let span = self.span_from(start);
1138            return Ok(Stmt::new(
1139                if is_of {
1140                    StmtKind::ForOf {
1141                        is_await,
1142                        left: head,
1143                        right: Box::new(right),
1144                        body: Box::new(body?),
1145                    }
1146                } else {
1147                    StmtKind::ForIn {
1148                        left: head,
1149                        right: Box::new(right),
1150                        body: Box::new(body?),
1151                    }
1152                },
1153                span,
1154            ));
1155        }
1156        let _ = expr_start;
1157        self.expect_punct(Punct::Semicolon)?;
1158        self.parse_for_classic(start, Some(ForInit::Expr(Box::new(expr))))
1159    }
1160
1161    /// Whether the `for` head continues with `in` (a keyword) or `of` (a
1162    /// contextual keyword).
1163    fn at_for_head_keyword(&self) -> bool {
1164        self.at_keyword(Keyword::In) || self.at_contextual("of")
1165    }
1166
1167    fn parse_for_classic(&mut self, start: Position, init: Option<ForInit>) -> Result<Stmt> {
1168        let test = if self.at_punct(Punct::Semicolon) {
1169            None
1170        } else {
1171            Some(Box::new(self.parse_expression(true)?))
1172        };
1173        self.expect_punct(Punct::Semicolon)?;
1174        let update = if self.at_punct(Punct::RParen) {
1175            None
1176        } else {
1177            Some(Box::new(self.parse_expression(true)?))
1178        };
1179        self.expect_punct(Punct::RParen)?;
1180        self.loop_depth += 1;
1181        let body = self.parse_statement();
1182        self.loop_depth -= 1;
1183        Ok(Stmt::new(
1184            StmtKind::For {
1185                init,
1186                test,
1187                update,
1188                body: Box::new(body?),
1189            },
1190            self.span_from(start),
1191        ))
1192    }
1193
1194    fn parse_switch(&mut self) -> Result<Stmt> {
1195        let start = self.current.span.start;
1196        self.bump()?; // switch
1197        self.expect_punct(Punct::LParen)?;
1198        let discriminant = self.parse_expression(true)?;
1199        self.expect_punct(Punct::RParen)?;
1200        self.expect_punct(Punct::LBrace)?;
1201        self.switch_depth += 1;
1202        self.push_scope(Scope::block());
1203        let mut cases = Vec::new();
1204        let mut seen_default = false;
1205        while !self.at_punct(Punct::RBrace) {
1206            if self.current.is_eof() {
1207                self.switch_depth -= 1;
1208                return Err(self.unexpected());
1209            }
1210            let case_start = self.current.span.start;
1211            let test = if self.eat_keyword(Keyword::Case)? {
1212                Some(Box::new(self.parse_expression(true)?))
1213            } else if self.eat_keyword(Keyword::Default)? {
1214                if seen_default {
1215                    self.switch_depth -= 1;
1216                    return Err(self.error("duplicate 'default' clause in switch statement"));
1217                }
1218                seen_default = true;
1219                None
1220            } else {
1221                self.switch_depth -= 1;
1222                return Err(self.unexpected());
1223            };
1224            self.expect_punct(Punct::Colon)?;
1225            let mut body = Vec::new();
1226            while !self.at_punct(Punct::RBrace)
1227                && !self.at_keyword(Keyword::Case)
1228                && !self.at_keyword(Keyword::Default)
1229            {
1230                if self.current.is_eof() {
1231                    self.switch_depth -= 1;
1232                    return Err(self.unexpected());
1233                }
1234                body.push(self.parse_statement_list_item()?);
1235            }
1236            cases.push(SwitchCase {
1237                test,
1238                body,
1239                span: self.span_from(case_start),
1240            });
1241        }
1242        self.switch_depth -= 1;
1243        self.bump()?; // }
1244        Ok(Stmt::new(
1245            StmtKind::Switch {
1246                discriminant: Box::new(discriminant),
1247                cases,
1248            },
1249            self.span_from(start),
1250        ))
1251    }
1252
1253    fn parse_try(&mut self) -> Result<Stmt> {
1254        let start = self.current.span.start;
1255        self.bump()?; // try
1256        let block = self.parse_block()?;
1257        let mut handler = None;
1258        let mut finalizer = None;
1259        if self.at_keyword(Keyword::Catch) {
1260            let catch_start = self.current.span.start;
1261            self.bump()?;
1262            // The catch parameter and the body share one scope, so `catch (e) {
1263            // let e; }` is an early error. A *simple* parameter is exempt from
1264            // the `var` check (`catch (e) { var e; }` is legal), a destructured
1265            // one is not (`catch ({e}) { var e; }` is rejected) — this matches
1266            // the reference engine.
1267            let param = if self.eat_punct(Punct::LParen)? {
1268                let pattern = self.parse_binding_target()?;
1269                self.expect_punct(Punct::RParen)?;
1270                Some(pattern)
1271            } else {
1272                None
1273            };
1274            self.push_scope(Scope::block());
1275            let body = match &param {
1276                // A simple parameter shares the body's scope: `catch (e) { let e;
1277                // }` is an error, `catch (e) { var e; }` is not.
1278                Some(Pattern {
1279                    kind: PatternKind::Ident(id),
1280                    ..
1281                }) => {
1282                    if let Some(scope) = self.scopes.last_mut() {
1283                        scope.params.push(id.name.clone());
1284                    }
1285                    self.parse_catch_body()
1286                }
1287                // A destructuring parameter is declared lexically in the clause's
1288                // own scope, with the body nested inside it: `catch ({e}) { var
1289                // e; }` is an error (the `var` hoists past the binding) while
1290                // `catch ({e}) { let e; }` is not.
1291                Some(pattern) => {
1292                    self.declare_pattern(pattern, false)?;
1293                    self.parse_block()
1294                }
1295                None => self.parse_catch_body(),
1296            };
1297            self.pop_scope();
1298            let body = body?;
1299            handler = Some(CatchClause {
1300                param,
1301                body,
1302                span: self.span_from(catch_start),
1303            });
1304        }
1305        if self.eat_keyword(Keyword::Finally)? {
1306            finalizer = Some(self.parse_block()?);
1307        }
1308        if handler.is_none() && finalizer.is_none() {
1309            return Err(self.error("expecting catch or finally"));
1310        }
1311        Ok(Stmt::new(
1312            StmtKind::Try {
1313                block,
1314                handler,
1315                finalizer,
1316            },
1317            self.span_from(start),
1318        ))
1319    }
1320
1321    fn parse_return(&mut self) -> Result<Stmt> {
1322        let start = self.current.span.start;
1323        let span = self.current.span;
1324        if !self.ctx.in_function {
1325            return Err(self.error_at("invalid return statement outside of a function", span));
1326        }
1327        self.bump()?;
1328        let argument = if self.at_punct(Punct::Semicolon)
1329            || self.at_punct(Punct::RBrace)
1330            || self.current.is_eof()
1331            || self.current.newline_before
1332        {
1333            None
1334        } else {
1335            Some(Box::new(self.parse_expression(true)?))
1336        };
1337        self.semicolon()?;
1338        Ok(Stmt::new(StmtKind::Return(argument), self.span_from(start)))
1339    }
1340
1341    fn parse_throw(&mut self) -> Result<Stmt> {
1342        let start = self.current.span.start;
1343        self.bump()?; // throw
1344        if self.current.newline_before {
1345            return Err(self.error("line terminator not allowed after 'throw'"));
1346        }
1347        let argument = self.parse_expression(true)?;
1348        self.semicolon()?;
1349        Ok(Stmt::new(
1350            StmtKind::Throw(Box::new(argument)),
1351            self.span_from(start),
1352        ))
1353    }
1354
1355    fn parse_break_continue(&mut self, is_break: bool) -> Result<Stmt> {
1356        let start = self.current.span.start;
1357        let keyword_span = self.current.span;
1358        self.bump()?;
1359        let label = if matches!(self.current.kind, TokenKind::Ident(_))
1360            && !self.current.newline_before
1361        {
1362            let ident = self.expect_ident()?;
1363            let found = self.labels.iter().rev().find(|l| l.name == ident.name);
1364            match found {
1365                None => {
1366                    return Err(
1367                        self.error_at(format!("label '{}' not found", ident.name), ident.span)
1368                    );
1369                }
1370                Some(label) => {
1371                    if !is_break && label.kind != LabelKind::Iteration {
1372                        return Err(self.error_at(
1373                            format!("continue must be inside of a loop (label '{}')", ident.name),
1374                            ident.span,
1375                        ));
1376                    }
1377                }
1378            }
1379            Some(ident)
1380        } else {
1381            if !is_break && self.loop_depth == 0 {
1382                return Err(self.error_at("continue must be inside of a loop", keyword_span));
1383            }
1384            if is_break && self.loop_depth == 0 && self.switch_depth == 0 && self.labels.is_empty()
1385            {
1386                return Err(self.error_at("break must be inside of a loop or switch", keyword_span));
1387            }
1388            None
1389        };
1390        self.semicolon()?;
1391        Ok(Stmt::new(
1392            if is_break {
1393                StmtKind::Break(label)
1394            } else {
1395                StmtKind::Continue(label)
1396            },
1397            self.span_from(start),
1398        ))
1399    }
1400
1401    fn parse_with(&mut self) -> Result<Stmt> {
1402        let start = self.current.span.start;
1403        let span = self.current.span;
1404        if self.strict {
1405            return Err(self.error_at("invalid 'with' statement in strict mode", span));
1406        }
1407        self.bump()?; // with
1408        self.expect_punct(Punct::LParen)?;
1409        let object = self.parse_expression(true)?;
1410        self.expect_punct(Punct::RParen)?;
1411        let body = self.parse_statement()?;
1412        Ok(Stmt::new(
1413            StmtKind::With {
1414                object: Box::new(object),
1415                body: Box::new(body),
1416            },
1417            self.span_from(start),
1418        ))
1419    }
1420
1421    fn parse_labeled(&mut self) -> Result<Stmt> {
1422        let start = self.current.span.start;
1423        let label = self.expect_ident()?;
1424        self.expect_punct(Punct::Colon)?;
1425        if self.labels.iter().any(|l| l.name == label.name) {
1426            return Err(self.error_at(
1427                format!("label '{}' already declared", label.name),
1428                label.span,
1429            ));
1430        }
1431        let kind = if self.at_keyword(Keyword::For)
1432            || self.at_keyword(Keyword::While)
1433            || self.at_keyword(Keyword::Do)
1434        {
1435            LabelKind::Iteration
1436        } else {
1437            LabelKind::Other
1438        };
1439        self.labels.push(Label {
1440            name: label.name.clone(),
1441            kind,
1442        });
1443        let body = self.parse_statement();
1444        self.labels.pop();
1445        Ok(Stmt::new(
1446            StmtKind::Labeled {
1447                label,
1448                body: Box::new(body?),
1449            },
1450            self.span_from(start),
1451        ))
1452    }
1453
1454    // -- declarations ------------------------------------------------------
1455
1456    fn parse_var_decl(
1457        &mut self,
1458        kind: VarDeclKind,
1459        in_for_head: bool,
1460        require_init: bool,
1461    ) -> Result<VarDecl> {
1462        let start = self.current.span.start;
1463        self.bump()?; // var / let / const
1464        let mut declarators = Vec::new();
1465        loop {
1466            let declarator_start = self.current.span.start;
1467            let target = self.parse_binding_target()?;
1468            let init = if self.eat_punct(Punct::Eq)? {
1469                // `for (var x = a in b;;)` must not parse `a in b` as the
1470                // initialiser: the head uses AssignmentExpression[~In].
1471                Some(Box::new(self.parse_assignment(!in_for_head)?))
1472            } else {
1473                None
1474            };
1475            if init.is_none() && require_init {
1476                if kind == VarDeclKind::Const {
1477                    return Err(self.error("missing initializer in const declaration"));
1478                }
1479                if !matches!(target.unparen_kind(), PatternKind::Ident(_)) && !in_for_head {
1480                    return Err(self.error_at(
1481                        "missing initializer in destructuring declaration",
1482                        target.span,
1483                    ));
1484                }
1485            }
1486            if kind.is_lexical() {
1487                let mut names = Vec::new();
1488                target.bound_names(&mut names);
1489                if let Some(name) = names.iter().find(|n| n.name == "let") {
1490                    return Err(self.error_at("'let' is not a valid lexical identifier", name.span));
1491                }
1492            }
1493            self.declare_pattern(&target, !kind.is_lexical())?;
1494            declarators.push(Declarator {
1495                target,
1496                init,
1497                span: self.span_from(declarator_start),
1498            });
1499            if !self.eat_punct(Punct::Comma)? {
1500                break;
1501            }
1502        }
1503        Ok(VarDecl {
1504            kind,
1505            declarators,
1506            span: self.span_from(start),
1507        })
1508    }
1509
1510    /// A binding element: `target` or `target = default`. Used for parameters and
1511    /// for elements of array/object patterns.
1512    fn parse_binding_element(&mut self) -> Result<Pattern> {
1513        let pattern = self.parse_binding_target()?;
1514        if self.eat_punct(Punct::Eq)? {
1515            let start = pattern.span.start;
1516            let default = self.parse_assignment(self.allow_in)?;
1517            return Ok(Pattern::new(
1518                PatternKind::Assign {
1519                    target: Box::new(pattern),
1520                    default: Box::new(default),
1521                },
1522                self.span_from(start),
1523            ));
1524        }
1525        Ok(pattern)
1526    }
1527
1528    /// A binding target: `Ident`, `[ … ]` or `{ … }`, with no default value.
1529    /// Used for declarators, `catch` parameters, rest elements and `for` heads.
1530    fn parse_binding_target(&mut self) -> Result<Pattern> {
1531        self.enter()?;
1532        let result = self.parse_binding_target_unguarded();
1533        self.leave();
1534        result
1535    }
1536
1537    fn parse_binding_target_unguarded(&mut self) -> Result<Pattern> {
1538        let start = self.current.span.start;
1539        if self.at_punct(Punct::LBracket) {
1540            return self.parse_array_pattern(start);
1541        }
1542        if self.at_punct(Punct::LBrace) {
1543            return self.parse_object_pattern(start);
1544        }
1545        let ident = self.expect_binding_ident()?;
1546        Ok(Pattern::new(
1547            PatternKind::Ident(ident),
1548            self.span_from(start),
1549        ))
1550    }
1551
1552    fn parse_array_pattern(&mut self, start: Position) -> Result<Pattern> {
1553        self.expect_punct(Punct::LBracket)?;
1554        let mut elements = Vec::new();
1555        let mut rest = None;
1556        loop {
1557            if self.at_punct(Punct::RBracket) {
1558                break;
1559            }
1560            if self.at_punct(Punct::Comma) {
1561                self.bump()?;
1562                elements.push(None);
1563                continue;
1564            }
1565            if self.at_punct(Punct::Ellipsis) {
1566                self.bump()?;
1567                let target = self.parse_binding_target()?;
1568                if self.at_punct(Punct::Comma) {
1569                    return Err(self.error("rest element must be last"));
1570                }
1571                rest = Some(Box::new(RestElement::Pattern(target)));
1572                break;
1573            }
1574            let element_start = self.current.span.start;
1575            let element = self.parse_binding_element()?;
1576            let span = self.span_from(element_start);
1577            elements.push(Some(PatternElement::Pattern(element)));
1578            let _ = span;
1579            if !self.eat_punct(Punct::Comma)? {
1580                break;
1581            }
1582        }
1583        self.expect_punct(Punct::RBracket)?;
1584        Ok(Pattern::new(
1585            PatternKind::Array { elements, rest },
1586            self.span_from(start),
1587        ))
1588    }
1589
1590    fn parse_object_pattern(&mut self, start: Position) -> Result<Pattern> {
1591        self.expect_punct(Punct::LBrace)?;
1592        let mut properties = Vec::new();
1593        let mut rest = None;
1594        loop {
1595            if self.at_punct(Punct::RBrace) {
1596                break;
1597            }
1598            if self.at_punct(Punct::Ellipsis) {
1599                self.bump()?;
1600                let target = self.parse_binding_target()?;
1601                rest = Some(Box::new(RestElement::Pattern(target)));
1602                if self.at_punct(Punct::Comma) {
1603                    return Err(self.error("rest element must be last"));
1604                }
1605                break;
1606            }
1607            let property_start = self.current.span.start;
1608            let key = self.parse_property_key()?;
1609            if self.eat_punct(Punct::Colon)? {
1610                let value = self.parse_binding_element()?;
1611                properties.push(Some(PatternElement::Property {
1612                    key,
1613                    value,
1614                    shorthand: false,
1615                    span: self.span_from(property_start),
1616                }));
1617            } else {
1618                let PropName::Literal(PropKey::Str(name)) = &key else {
1619                    return Err(
1620                        self.error("expecting ':' after a computed or numeric property key")
1621                    );
1622                };
1623                let span = self.span_from(property_start);
1624                let ident = Ident {
1625                    name: name.clone(),
1626                    span,
1627                };
1628                self.check_binding_name(&ident.name, ident.span)?;
1629                let mut value = Pattern::new(PatternKind::Ident(ident), span);
1630                if self.eat_punct(Punct::Eq)? {
1631                    let default = self.parse_assignment(self.allow_in)?;
1632                    value = Pattern::new(
1633                        PatternKind::Assign {
1634                            target: Box::new(value),
1635                            default: Box::new(default),
1636                        },
1637                        span,
1638                    );
1639                }
1640                properties.push(Some(PatternElement::Property {
1641                    key,
1642                    value,
1643                    shorthand: true,
1644                    span,
1645                }));
1646            }
1647            if !self.eat_punct(Punct::Comma)? {
1648                break;
1649            }
1650        }
1651        self.expect_punct(Punct::RBrace)?;
1652        Ok(Pattern::new(
1653            PatternKind::Object { properties, rest },
1654            self.span_from(start),
1655        ))
1656    }
1657
1658    /// A property key: identifier, string, number, computed or `#private`.
1659    fn parse_property_key(&mut self) -> Result<PropName> {
1660        match self.current.kind.clone() {
1661            TokenKind::Ident(name) => {
1662                self.bump()?;
1663                Ok(PropName::Literal(PropKey::Str(name)))
1664            }
1665            TokenKind::Keyword(kw) => {
1666                // Reserved words are valid property names (`{ if: 1 }`).
1667                self.bump()?;
1668                Ok(PropName::Literal(PropKey::Str(kw.as_str().to_string())))
1669            }
1670            TokenKind::String(value) => {
1671                self.bump()?;
1672                Ok(PropName::Literal(PropKey::Str(value)))
1673            }
1674            TokenKind::Number(NumberLiteral::Int(v)) => {
1675                self.bump()?;
1676                Ok(PropName::Literal(PropKey::Num(v as f64)))
1677            }
1678            TokenKind::Number(NumberLiteral::Float(v)) => {
1679                self.bump()?;
1680                Ok(PropName::Literal(PropKey::Num(v)))
1681            }
1682            TokenKind::BigInt(big) => Err(self.error(format!(
1683                "BigInt property keys are not supported ('{}n')",
1684                big.digits
1685            ))),
1686            TokenKind::Punct(Punct::LBracket) => {
1687                self.bump()?;
1688                let expr = self.parse_assignment(true)?;
1689                self.expect_punct(Punct::RBracket)?;
1690                Ok(PropName::Computed(Box::new(expr)))
1691            }
1692            TokenKind::Punct(Punct::Hash) => {
1693                self.bump()?;
1694                let ident = self.expect_ident()?;
1695                Ok(PropName::Private(ident))
1696            }
1697            _ => Err(self.error("expecting a property name")),
1698        }
1699    }
1700
1701    // -- functions ---------------------------------------------------------
1702
1703    fn parse_function(&mut self, form: FunctionForm, is_async: bool) -> Result<Function> {
1704        let start = self.current.span.start;
1705        self.bump()?; // function
1706        let is_generator = self.eat_punct(Punct::Star)?;
1707        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
1708            let ident = if form == FunctionForm::Declaration {
1709                self.expect_binding_ident()?
1710            } else {
1711                self.expect_ident()?
1712            };
1713            if is_generator && ident.name == "yield" {
1714                return Err(self.error_at("invalid use of 'yield' as a function name", ident.span));
1715            }
1716            if is_async && ident.name == "await" {
1717                return Err(self.error_at("invalid use of 'await' as a function name", ident.span));
1718            }
1719            Some(ident)
1720        } else {
1721            if form == FunctionForm::Declaration {
1722                return Err(self.error("expecting a function name"));
1723            }
1724            None
1725        };
1726        let saved = self.ctx;
1727        self.ctx = FnCtx {
1728            in_function: true,
1729            in_generator: is_generator,
1730            in_async: is_async,
1731            in_method: false,
1732            in_derived_constructor: false,
1733        };
1734        let saved_top = self.top_level;
1735        self.top_level = false;
1736        // Strictness is per function: `function f(){ "use strict"; }` must leave the
1737        // code *after* it sloppy. Without this save the directive leaked outwards, the
1738        // enclosing script was compiled as strict, and a later `function g(){}` lost its
1739        // declaration status — `typeof g` then raised instead of answering, because an
1740        // implicit global is not a declaration.
1741        let saved_strict = self.strict;
1742        let params_result = self.parse_formal_parameters();
1743        let result = match params_result {
1744            Ok(params) => self.parse_function_body(params, is_generator, is_async),
1745            Err(err) => Err(err),
1746        };
1747        self.ctx = saved;
1748        self.top_level = saved_top;
1749        self.strict = saved_strict;
1750        self.lexer.set_strict(saved_strict);
1751        let (params, params_span, body) = result?;
1752        Ok(Function {
1753            name,
1754            params,
1755            body,
1756            is_async,
1757            is_generator,
1758            is_arrow: false,
1759            span: self.span_from(start),
1760            params_span,
1761        })
1762    }
1763
1764    fn parse_formal_parameters(&mut self) -> Result<Vec<Pattern>> {
1765        self.expect_punct(Punct::LParen)?;
1766        let mut params = Vec::new();
1767        loop {
1768            if self.at_punct(Punct::RParen) {
1769                break;
1770            }
1771            if self.at_punct(Punct::Ellipsis) {
1772                self.bump()?;
1773                let target = self.parse_binding_target()?;
1774                if matches!(target.unparen_kind(), PatternKind::Assign { .. }) {
1775                    return Err(self.error_at("rest parameter may not have a default", target.span));
1776                }
1777                params.push(Pattern::new(
1778                    PatternKind::Rest(Box::new(target.clone())),
1779                    target.span,
1780                ));
1781                if self.at_punct(Punct::Comma) {
1782                    return Err(self.error("rest parameter must be last"));
1783                }
1784                break;
1785            }
1786            let param = self.parse_binding_element()?;
1787            self.check_parameter(&param)?;
1788            params.push(param);
1789            if !self.eat_punct(Punct::Comma)? {
1790                break;
1791            }
1792        }
1793        self.expect_punct(Punct::RParen)?;
1794        Ok(params)
1795    }
1796
1797    fn check_parameter(&self, param: &Pattern) -> Result<()> {
1798        match &param.kind {
1799            PatternKind::Ident(ident) => self.check_binding_name(&ident.name, ident.span),
1800            PatternKind::Assign { target, .. } => self.check_parameter(target),
1801            _ => Ok(()),
1802        }
1803    }
1804
1805    fn parse_function_body(
1806        &mut self,
1807        params: Vec<Pattern>,
1808        is_generator: bool,
1809        is_async: bool,
1810    ) -> Result<(Vec<Pattern>, Span, FunctionBody)> {
1811        let params_span = self.prev_end;
1812        if !self.at_punct(Punct::LBrace) {
1813            return Err(self.unexpected());
1814        }
1815        let param_names = simple_parameter_names(&params);
1816        let simple_params = params
1817            .iter()
1818            .all(|p| matches!(p.unparen_kind(), PatternKind::Ident(_)));
1819        let mut body = Vec::new();
1820        let mut prologue = true;
1821        let mut strict_seen = false;
1822        self.bump()?; // {
1823        self.push_scope(Scope::function(param_names));
1824        while !self.at_punct(Punct::RBrace) {
1825            if self.current.is_eof() {
1826                return Err(self.unexpected());
1827            }
1828            let stmt = self.parse_statement_list_item()?;
1829            if prologue {
1830                match self.directive_value(&stmt) {
1831                    Some(directive) if directive == "use strict" => {
1832                        strict_seen = true;
1833                        self.enter_strict()?;
1834                    }
1835                    Some(_) => {}
1836                    None => prologue = false,
1837                }
1838            }
1839            body.push(stmt);
1840        }
1841        self.pop_scope();
1842        self.bump()?; // }
1843        if strict_seen && !simple_params {
1844            return Err(self.error_at(
1845                "'use strict' directive is not allowed with non-simple parameters",
1846                Span::new(params_span, params_span),
1847            ));
1848        }
1849        // Duplicate parameter names: always illegal for non-simple lists and in
1850        // strict mode; in sloppy simple lists they are allowed (last wins).
1851        if self.strict || !simple_params || is_generator || is_async {
1852            let mut seen: Vec<String> = Vec::new();
1853            for param in &params {
1854                let mut names = Vec::new();
1855                param.bound_names(&mut names);
1856                for name in names {
1857                    if seen.contains(&name.name) {
1858                        return Err(self.error_at(
1859                            format!("duplicate parameter name '{}'", name.name),
1860                            name.span,
1861                        ));
1862                    }
1863                    seen.push(name.name);
1864                }
1865            }
1866        }
1867        let params_span_value = Span::new(params_span, params_span);
1868        Ok((params, params_span_value, FunctionBody::Block(body)))
1869    }
1870
1871    // -- classes -----------------------------------------------------------
1872
1873    fn parse_class(&mut self, is_expression: bool) -> Result<Class> {
1874        let start = self.current.span.start;
1875        self.bump()?; // class
1876        let name = if matches!(self.current.kind, TokenKind::Ident(_)) {
1877            if is_expression {
1878                Some(self.expect_ident()?)
1879            } else {
1880                Some(self.expect_binding_ident()?)
1881            }
1882        } else {
1883            if !is_expression {
1884                return Err(self.error("expecting a class name"));
1885            }
1886            None
1887        };
1888        let super_class = if self.eat_keyword(Keyword::Extends)? {
1889            Some(Box::new(self.parse_lhs_expression()?))
1890        } else {
1891            None
1892        };
1893        let has_super = super_class.is_some();
1894        self.private.push(PrivateEnv::default());
1895        self.expect_punct(Punct::LBrace)?;
1896        let mut elements = Vec::new();
1897        let mut seen_constructor = false;
1898        let result = (|| -> Result<()> {
1899            while !self.at_punct(Punct::RBrace) {
1900                if self.current.is_eof() {
1901                    return Err(self.unexpected());
1902                }
1903                if self.eat_punct(Punct::Semicolon)? {
1904                    continue;
1905                }
1906                elements.push(self.parse_class_element(has_super, &mut seen_constructor)?);
1907            }
1908            Ok(())
1909        })();
1910        self.private.pop();
1911        result?;
1912        self.bump()?; // }
1913        Ok(Class {
1914            name,
1915            super_class,
1916            elements,
1917            span: self.span_from(start),
1918        })
1919    }
1920
1921    fn parse_class_element(
1922        &mut self,
1923        has_super: bool,
1924        seen_constructor: &mut bool,
1925    ) -> Result<ClassElement> {
1926        let start = self.current.span.start;
1927        let mut is_static = false;
1928        if self.at_ident("static") {
1929            let peek = self.peek()?;
1930            let is_modifier = !matches!(
1931                peek.kind,
1932                TokenKind::Punct(Punct::LParen)
1933                    | TokenKind::Punct(Punct::Eq)
1934                    | TokenKind::Punct(Punct::Semicolon)
1935                    | TokenKind::Punct(Punct::RBrace)
1936            );
1937            if is_modifier {
1938                if matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
1939                    self.bump()?; // static
1940                    let body = self.parse_block()?;
1941                    return Ok(ClassElement::StaticBlock {
1942                        body,
1943                        span: self.span_from(start),
1944                    });
1945                }
1946                self.bump()?; // static
1947                is_static = true;
1948                if self.at_punct(Punct::LBrace) {
1949                    let body = self.parse_block()?;
1950                    return Ok(ClassElement::StaticBlock {
1951                        body,
1952                        span: self.span_from(start),
1953                    });
1954                }
1955            }
1956        }
1957
1958        // Modifiers: async, get, set, *
1959        let mut is_async = false;
1960        let mut is_generator = false;
1961        let mut accessor: Option<MethodKind> = None;
1962        if self.at_ident("async") {
1963            let peek = self.peek()?;
1964            let is_modifier = !matches!(
1965                peek.kind,
1966                TokenKind::Punct(Punct::LParen)
1967                    | TokenKind::Punct(Punct::Eq)
1968                    | TokenKind::Punct(Punct::Semicolon)
1969                    | TokenKind::Punct(Punct::RBrace)
1970            ) && !peek.newline_before;
1971            if is_modifier {
1972                self.bump()?;
1973                is_async = true;
1974            }
1975        }
1976        if self.at_punct(Punct::Star) {
1977            self.bump()?;
1978            is_generator = true;
1979        }
1980        if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
1981            let is_get = self.at_ident("get");
1982            let peek = self.peek()?;
1983            if is_property_key_start(&peek.kind) {
1984                self.bump()?;
1985                accessor = Some(if is_get {
1986                    MethodKind::Get
1987                } else {
1988                    MethodKind::Set
1989                });
1990            }
1991        }
1992        let key = self.parse_property_key()?;
1993
1994        // Private names must be registered (duplicates are early errors).
1995        if let PropName::Private(ident) = &key {
1996            if let Some(env) = self.private.last_mut() {
1997                if !env.declare(&ident.name, accessor) {
1998                    return Err(self.error_at(
1999                        format!("duplicate private name '#{}'", ident.name),
2000                        ident.span,
2001                    ));
2002                }
2003            }
2004        }
2005
2006        if self.at_punct(Punct::LParen) {
2007            let kind = match accessor {
2008                Some(kind) => kind,
2009                None => {
2010                    let is_constructor = !is_static
2011                        && !is_generator
2012                        && !is_async
2013                        && matches!(&key, PropName::Literal(PropKey::Str(s)) if s == "constructor");
2014                    if is_constructor {
2015                        if *seen_constructor {
2016                            return Err(self.error_at(
2017                                "property constructor appears more than once",
2018                                self.span_from(start),
2019                            ));
2020                        }
2021                        *seen_constructor = true;
2022                        MethodKind::Constructor
2023                    } else {
2024                        MethodKind::Method
2025                    }
2026                }
2027            };
2028            if kind == MethodKind::Constructor && (is_generator || is_async) {
2029                return Err(self.error("a constructor may not be a generator or async"));
2030            }
2031            let saved = self.ctx;
2032            self.ctx = FnCtx {
2033                in_function: true,
2034                in_generator: is_generator,
2035                in_async: is_async,
2036                in_method: true,
2037                in_derived_constructor: kind == MethodKind::Constructor && has_super,
2038            };
2039            let saved_top = self.top_level;
2040            self.top_level = false;
2041            let result = (|| -> Result<Function> {
2042                let params = self.parse_formal_parameters()?;
2043                let (params, params_span, body) =
2044                    self.parse_function_body(params, is_generator, is_async)?;
2045                Ok(Function {
2046                    name: None,
2047                    params,
2048                    body,
2049                    is_async,
2050                    is_generator,
2051                    is_arrow: false,
2052                    span: self.span_from(start),
2053                    params_span,
2054                })
2055            })();
2056            self.ctx = saved;
2057            self.top_level = saved_top;
2058            let func = result?;
2059            if is_static {
2060                if let PropName::Literal(PropKey::Str(name)) = &key {
2061                    if name == "prototype" {
2062                        return Err(self.error_at("invalid method name 'prototype'", func.span));
2063                    }
2064                }
2065            }
2066            if kind == MethodKind::Get && !func.params.is_empty() {
2067                return Err(self.error_at("getter must have no arguments", func.span));
2068            }
2069            if kind == MethodKind::Set && func.params.len() != 1 {
2070                return Err(self.error_at("setter must have exactly one argument", func.span));
2071            }
2072            return Ok(ClassElement::Method {
2073                key,
2074                is_static,
2075                kind,
2076                func: Box::new(func),
2077                span: self.span_from(start),
2078            });
2079        }
2080
2081        // Field definition.
2082        if accessor.is_some() {
2083            return Err(self.error("expecting '(' after an accessor name"));
2084        }
2085        if let PropName::Literal(PropKey::Str(name)) = &key {
2086            if name == "constructor" && !is_static {
2087                return Err(self.error("classes may not have a field named 'constructor'"));
2088            }
2089            if name == "prototype" && is_static {
2090                return Err(self.error("classes may not have a static property named 'prototype'"));
2091            }
2092        }
2093        let value = if self.eat_punct(Punct::Eq)? {
2094            Some(Box::new(self.parse_assignment(true)?))
2095        } else {
2096            None
2097        };
2098        // Fields are terminated by `;`, `}` or a line break.
2099        self.semicolon()?;
2100        Ok(ClassElement::Field {
2101            key,
2102            is_static,
2103            value,
2104            span: self.span_from(start),
2105        })
2106    }
2107
2108    // -- modules -----------------------------------------------------------
2109
2110    fn parse_import_decl(&mut self) -> Result<Stmt> {
2111        let start = self.current.span.start;
2112        self.bump()?; // import
2113        let mut specifiers = Vec::new();
2114        if let TokenKind::String(source) = self.current.kind.clone() {
2115            self.bump()?;
2116            let attributes = self.parse_import_attributes()?;
2117            self.semicolon()?;
2118            return Ok(Stmt::new(
2119                StmtKind::Import(Box::new(ImportDecl {
2120                    specifiers,
2121                    source,
2122                    attributes,
2123                    span: self.span_from(start),
2124                })),
2125                self.span_from(start),
2126            ));
2127        }
2128        // Default import.
2129        if matches!(self.current.kind, TokenKind::Ident(_)) {
2130            let local = self.expect_ident()?;
2131            specifiers.push(ImportSpecifier::Default(local));
2132            if !self.eat_punct(Punct::Comma)? {
2133                return self.finish_import(start, specifiers);
2134            }
2135        }
2136        if self.at_punct(Punct::Star) {
2137            self.bump()?;
2138            if !self.eat_contextual("as")? {
2139                return Err(self.unexpected());
2140            }
2141            let local = self.expect_ident()?;
2142            specifiers.push(ImportSpecifier::Namespace(local));
2143            return self.finish_import(start, specifiers);
2144        }
2145        if self.at_punct(Punct::LBrace) {
2146            self.bump()?;
2147            while !self.at_punct(Punct::RBrace) {
2148                let imported = self.parse_module_name()?;
2149                let local = if self.eat_contextual("as")? {
2150                    self.expect_ident()?
2151                } else {
2152                    match &imported {
2153                        ModuleName::Ident(id) => id.clone(),
2154                        ModuleName::Str(_) => {
2155                            return Err(self.error_at(
2156                                "a string module name must be followed by 'as'",
2157                                self.current.span,
2158                            ));
2159                        }
2160                    }
2161                };
2162                specifiers.push(ImportSpecifier::Named { imported, local });
2163                if !self.eat_punct(Punct::Comma)? {
2164                    break;
2165                }
2166            }
2167            self.expect_punct(Punct::RBrace)?;
2168        } else if !specifiers.is_empty() {
2169            return Err(self.unexpected());
2170        } else if self.at_punct(Punct::LBrace) {
2171            unreachable!("handled above");
2172        } else {
2173            return Err(self.unexpected());
2174        }
2175        self.finish_import(start, specifiers)
2176    }
2177
2178    fn finish_import(&mut self, start: Position, specifiers: Vec<ImportSpecifier>) -> Result<Stmt> {
2179        if !self.eat_contextual("from")? {
2180            return Err(self.unexpected());
2181        }
2182        let TokenKind::String(source) = self.current.kind.clone() else {
2183            return Err(self.error("expecting a module name string"));
2184        };
2185        self.bump()?;
2186        let attributes = self.parse_import_attributes()?;
2187        self.semicolon()?;
2188        let span = self.span_from(start);
2189        for specifier in &specifiers {
2190            let local = match specifier {
2191                ImportSpecifier::Default(id) => id,
2192                ImportSpecifier::Namespace(id) => id,
2193                ImportSpecifier::Named { local, .. } => local,
2194            };
2195            self.declare_lexical(&local.name, local.span)?;
2196        }
2197        Ok(Stmt::new(
2198            StmtKind::Import(Box::new(ImportDecl {
2199                specifiers,
2200                source,
2201                attributes,
2202                span,
2203            })),
2204            span,
2205        ))
2206    }
2207
2208    fn parse_import_attributes(&mut self) -> Result<Vec<ImportAttribute>> {
2209        let mut attributes = Vec::new();
2210        let has_with = self.at_keyword(Keyword::With) || self.at_ident("assert");
2211        if !has_with {
2212            return Ok(attributes);
2213        }
2214        let peek = self.peek()?;
2215        if !matches!(peek.kind, TokenKind::Punct(Punct::LBrace)) {
2216            return Ok(attributes);
2217        }
2218        self.bump()?; // with / assert
2219        self.expect_punct(Punct::LBrace)?;
2220        while !self.at_punct(Punct::RBrace) {
2221            let attr_start = self.current.span.start;
2222            let key = match self.current.kind.clone() {
2223                TokenKind::Ident(name) => name,
2224                TokenKind::String(value) => value,
2225                _ => return Err(self.error("expecting an import attribute name")),
2226            };
2227            self.bump()?;
2228            self.expect_punct(Punct::Colon)?;
2229            let TokenKind::String(value) = self.current.kind.clone() else {
2230                return Err(self.error("expecting an import attribute value string"));
2231            };
2232            self.bump()?;
2233            attributes.push(ImportAttribute {
2234                key,
2235                value,
2236                span: self.span_from(attr_start),
2237            });
2238            if !self.eat_punct(Punct::Comma)? {
2239                break;
2240            }
2241        }
2242        self.expect_punct(Punct::RBrace)?;
2243        Ok(attributes)
2244    }
2245
2246    fn parse_module_name(&mut self) -> Result<ModuleName> {
2247        match self.current.kind.clone() {
2248            TokenKind::String(value) => {
2249                self.bump()?;
2250                Ok(ModuleName::Str(value))
2251            }
2252            TokenKind::Ident(_) => Ok(ModuleName::Ident(self.expect_ident()?)),
2253            TokenKind::Keyword(kw) => {
2254                let span = self.current.span;
2255                self.bump()?;
2256                Ok(ModuleName::Ident(Ident {
2257                    name: kw.as_str().to_string(),
2258                    span,
2259                }))
2260            }
2261            _ => Err(self.error("expecting an export name")),
2262        }
2263    }
2264
2265    fn parse_export_decl(&mut self) -> Result<Stmt> {
2266        let start = self.current.span.start;
2267        self.bump()?; // export
2268        if self.at_punct(Punct::Star) {
2269            self.bump()?;
2270            let mut exported = None;
2271            if self.eat_contextual("as")? {
2272                exported = Some(self.parse_module_name()?);
2273            }
2274            if !self.eat_contextual("from")? {
2275                return Err(self.error("expecting 'from' after 'export *'"));
2276            }
2277            let TokenKind::String(source) = self.current.kind.clone() else {
2278                return Err(self.error("expecting a module name string"));
2279            };
2280            self.bump()?;
2281            let attributes = self.parse_import_attributes()?;
2282            self.semicolon()?;
2283            let span = self.span_from(start);
2284            return Ok(Stmt::new(
2285                StmtKind::Export(Box::new(ExportDecl {
2286                    kind: ExportKind::All {
2287                        source,
2288                        exported,
2289                        attributes,
2290                    },
2291                    span,
2292                })),
2293                span,
2294            ));
2295        }
2296        if self.eat_keyword(Keyword::Default)? {
2297            let value = if self.at_keyword(Keyword::Function) {
2298                let func = self.parse_function(FunctionForm::Expression, false)?;
2299                Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2300            } else if self.at_ident("async") {
2301                let peek = self.peek()?;
2302                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) {
2303                    self.bump()?;
2304                    let func = self.parse_function(FunctionForm::Expression, true)?;
2305                    Expr::new(ExprKind::Function(Box::new(func)), self.span_from(start))
2306                } else {
2307                    self.parse_assignment(true)?
2308                }
2309            } else if self.at_keyword(Keyword::Class) {
2310                let class = self.parse_class(true)?;
2311                Expr::new(ExprKind::Class(Box::new(class)), self.span_from(start))
2312            } else {
2313                let expr = self.parse_assignment(true)?;
2314                self.semicolon()?;
2315                expr
2316            };
2317            let span = self.span_from(start);
2318            return Ok(Stmt::new(
2319                StmtKind::Export(Box::new(ExportDecl {
2320                    kind: ExportKind::Default(Box::new(value)),
2321                    span,
2322                })),
2323                span,
2324            ));
2325        }
2326        if self.at_keyword(Keyword::Var)
2327            || self.at_keyword(Keyword::Const)
2328            || self.at_keyword(Keyword::Function)
2329            || self.at_keyword(Keyword::Class)
2330            || (self.at_ident("let") && self.let_starts_declaration()?)
2331        {
2332            let decl = self.parse_statement_list_item()?;
2333            let span = self.span_from(start);
2334            return Ok(Stmt::new(
2335                StmtKind::Export(Box::new(ExportDecl {
2336                    kind: ExportKind::Declaration(Box::new(decl)),
2337                    span,
2338                })),
2339                span,
2340            ));
2341        }
2342        if self.at_ident("async") {
2343            let peek = self.peek()?;
2344            if matches!(peek.kind, TokenKind::Keyword(Keyword::Function)) && !peek.newline_before {
2345                let decl = self.parse_statement_list_item()?;
2346                let span = self.span_from(start);
2347                return Ok(Stmt::new(
2348                    StmtKind::Export(Box::new(ExportDecl {
2349                        kind: ExportKind::Declaration(Box::new(decl)),
2350                        span,
2351                    })),
2352                    span,
2353                ));
2354            }
2355        }
2356        if self.at_punct(Punct::LBrace) {
2357            self.bump()?;
2358            let mut specifiers = Vec::new();
2359            let mut source = None;
2360            while !self.at_punct(Punct::RBrace) {
2361                let spec_start = self.current.span.start;
2362                let local = self.parse_module_name()?;
2363                let exported = if self.eat_contextual("as")? {
2364                    self.parse_module_name()?
2365                } else {
2366                    local.clone()
2367                };
2368                if source.is_none() {
2369                    if let ModuleName::Ident(id) = &local {
2370                        self.pending_exports.push((id.name.clone(), id.span));
2371                    }
2372                }
2373                specifiers.push(ExportSpecifier {
2374                    local,
2375                    exported,
2376                    span: self.span_from(spec_start),
2377                });
2378                if !self.eat_punct(Punct::Comma)? {
2379                    break;
2380                }
2381            }
2382            self.expect_punct(Punct::RBrace)?;
2383            let mut attributes = Vec::new();
2384            if self.eat_contextual("from")? {
2385                let TokenKind::String(value) = self.current.kind.clone() else {
2386                    return Err(self.error("expecting a module name string"));
2387                };
2388                self.bump()?;
2389                source = Some(value);
2390                attributes = self.parse_import_attributes()?;
2391            }
2392            self.semicolon()?;
2393            let span = self.span_from(start);
2394            return Ok(Stmt::new(
2395                StmtKind::Export(Box::new(ExportDecl {
2396                    kind: ExportKind::Named {
2397                        specifiers,
2398                        source,
2399                        attributes,
2400                    },
2401                    span,
2402                })),
2403                span,
2404            ));
2405        }
2406        Err(self.unexpected())
2407    }
2408
2409    // -- patterns from expressions ----------------------------------------
2410
2411    fn expr_to_pattern(&mut self, expr: Expr, kind: TargetKind) -> Result<Pattern> {
2412        self.expr_to_pattern_inner(expr, kind, false)
2413    }
2414
2415    fn expr_to_pattern_inner(
2416        &mut self,
2417        expr: Expr,
2418        kind: TargetKind,
2419        nested: bool,
2420    ) -> Result<Pattern> {
2421        let span = expr.span;
2422        match expr.kind {
2423            ExprKind::Ident(ident) => {
2424                if kind == TargetKind::Binding {
2425                    self.check_binding_name(&ident.name, ident.span)?;
2426                } else {
2427                    self.check_identifier(&ident.name, ident.span)?;
2428                    if self.strict && (ident.name == "eval" || ident.name == "arguments") {
2429                        return Err(self.error_at(
2430                            format!("invalid assignment to '{}' in strict mode", ident.name),
2431                            ident.span,
2432                        ));
2433                    }
2434                }
2435                Ok(Pattern::new(PatternKind::Ident(ident), span))
2436            }
2437            ExprKind::Paren(inner) => self.expr_to_pattern_inner(*inner, kind, nested),
2438            ExprKind::Array { elements } => {
2439                let mut out = Vec::new();
2440                let mut rest = None;
2441                let count = elements.len();
2442                for (index, element) in elements.into_iter().enumerate() {
2443                    match element {
2444                        None => out.push(None),
2445                        Some(ArrayElement::Expr(expr)) => {
2446                            let pattern = self.expr_to_pattern_inner(*expr, kind, true)?;
2447                            out.push(Some(PatternElement::Pattern(pattern)));
2448                        }
2449                        Some(ArrayElement::Spread(expr)) => {
2450                            if index + 1 != count {
2451                                return Err(self.error_at("rest element must be last", expr.span));
2452                            }
2453                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2454                        }
2455                    }
2456                }
2457                Ok(Pattern::new(
2458                    PatternKind::Array {
2459                        elements: out,
2460                        rest,
2461                    },
2462                    span,
2463                ))
2464            }
2465            ExprKind::Object(properties) => {
2466                self.cover_inits
2467                    .retain(|cover| !span_contains(span, *cover));
2468                let mut out = Vec::new();
2469                let mut rest = None;
2470                let count = properties.len();
2471                for (index, property) in properties.into_iter().enumerate() {
2472                    match property {
2473                        ObjectProperty::Spread(expr) => {
2474                            if index + 1 != count {
2475                                return Err(self.error_at("rest element must be last", expr.span));
2476                            }
2477                            rest = Some(Box::new(self.expr_to_rest(*expr, kind)?));
2478                        }
2479                        ObjectProperty::Property {
2480                            key,
2481                            value,
2482                            kind: _,
2483                            shorthand,
2484                            span,
2485                        } => {
2486                            let pattern = self.expr_to_pattern_inner(*value, kind, true)?;
2487                            out.push(Some(PatternElement::Property {
2488                                key,
2489                                value: pattern,
2490                                shorthand,
2491                                span,
2492                            }));
2493                        }
2494                    }
2495                }
2496                Ok(Pattern::new(
2497                    PatternKind::Object {
2498                        properties: out,
2499                        rest,
2500                    },
2501                    span,
2502                ))
2503            }
2504            ExprKind::Assign { op, target, value } if op.is_simple() => {
2505                // `{a = 1}` inside a pattern: the target must itself be a pattern.
2506                let target = match target.kind {
2507                    PatternKind::Ident(ident) => {
2508                        Pattern::new(PatternKind::Ident(ident), target.span)
2509                    }
2510                    other => {
2511                        let expr = pattern_to_expr(Pattern::new(other, target.span), target.span);
2512                        self.expr_to_pattern_inner(expr, kind, nested)?
2513                    }
2514                };
2515                Ok(Pattern::new(
2516                    PatternKind::Assign {
2517                        target: Box::new(target),
2518                        default: value,
2519                    },
2520                    span,
2521                ))
2522            }
2523            ExprKind::Member {
2524                object,
2525                property,
2526                optional,
2527            } => {
2528                if kind == TargetKind::Binding {
2529                    return Err(self.error_at("invalid binding pattern", span));
2530                }
2531                if optional {
2532                    return Err(self.error_at("invalid assignment target", span));
2533                }
2534                let op_pos = expr.op_pos;
2535                Ok(Pattern::new(
2536                    PatternKind::Member(Box::new(MemberPattern {
2537                        object,
2538                        property,
2539                        span,
2540                        op_pos,
2541                    })),
2542                    span,
2543                ))
2544            }
2545            ExprKind::OptionalChain(_) => {
2546                Err(self.error_at("invalid assignment left-hand side", span))
2547            }
2548            // QuickJS reports `a() = 1` at run time (it evaluates the callee
2549            // first, then rejects the reference) but rejects the same thing
2550            // inside a destructuring pattern at parse time. Every other
2551            // non-assignable expression is rejected here.
2552            other @ ExprKind::Call { .. } if !nested && kind == TargetKind::Assignment => Ok(
2553                Pattern::new(PatternKind::Invalid(Box::new(Expr::new(other, span))), span),
2554            ),
2555            _ if kind == TargetKind::Binding => Err(self.error_at("invalid binding pattern", span)),
2556            _ => Err(self.error_at("invalid destructuring target", span)),
2557        }
2558    }
2559
2560    fn expr_to_rest(&mut self, expr: Expr, kind: TargetKind) -> Result<RestElement> {
2561        // Array and object literals wrap their spread elements, so the target is
2562        // one level in.
2563        let expr = match expr.kind {
2564            ExprKind::Spread(inner) => *inner,
2565            other => Expr::new(other, expr.span),
2566        };
2567        if kind == TargetKind::Binding {
2568            return Ok(RestElement::Pattern(
2569                self.expr_to_pattern_inner(expr, kind, true)?,
2570            ));
2571        }
2572        match &expr.kind {
2573            ExprKind::Member { optional, .. } => {
2574                if *optional {
2575                    return Err(self.error_at("invalid assignment target", expr.span));
2576                }
2577                match self.expr_to_pattern_inner(expr, kind, true)?.kind {
2578                    PatternKind::Member(member) => Ok(RestElement::Member(member)),
2579                    _ => unreachable!("member expressions convert to member patterns"),
2580                }
2581            }
2582            _ => Ok(RestElement::Pattern(
2583                self.expr_to_pattern_inner(expr, kind, true)?,
2584            )),
2585        }
2586    }
2587
2588    // -- expressions -------------------------------------------------------
2589
2590    /// `Expression` (comma separated).
2591    fn parse_expression(&mut self, allow_in: bool) -> Result<Expr> {
2592        self.enter()?;
2593        let result = self.parse_expression_unguarded(allow_in);
2594        self.leave();
2595        result
2596    }
2597
2598    fn parse_expression_unguarded(&mut self, allow_in: bool) -> Result<Expr> {
2599        let start = self.current.span.start;
2600        let first = self.parse_assignment(allow_in)?;
2601        if !self.at_punct(Punct::Comma) {
2602            return Ok(first);
2603        }
2604        let mut items = vec![first];
2605        while self.eat_punct(Punct::Comma)? {
2606            items.push(self.parse_assignment(allow_in)?);
2607        }
2608        Ok(Expr::new(ExprKind::Sequence(items), self.span_from(start)))
2609    }
2610
2611    fn parse_assignment(&mut self, allow_in: bool) -> Result<Expr> {
2612        let start = self.current.span.start;
2613
2614        // `yield` in a generator.
2615        if self.ctx.in_generator && self.at_ident("yield") {
2616            return self.parse_yield(allow_in);
2617        }
2618
2619        let lhs = match self.try_parse_arrow(allow_in)? {
2620            Some(arrow) => return Ok(arrow),
2621            None => self.parse_conditional(allow_in)?,
2622        };
2623
2624        if let Some(op) = self.current.kind.as_punct().and_then(AssignOp::from_punct) {
2625            let op_pos = self.current.span.start;
2626            let target = self.expr_to_pattern(lhs, TargetKind::Assignment)?;
2627            self.bump()?;
2628            let value = self.parse_assignment(allow_in)?;
2629            return Ok(Expr::at_operator(
2630                ExprKind::Assign {
2631                    op,
2632                    target: Box::new(target),
2633                    value: Box::new(value),
2634                },
2635                self.span_from(start),
2636                op_pos,
2637            ));
2638        }
2639        let _ = start;
2640        Ok(lhs)
2641    }
2642
2643    fn parse_yield(&mut self, allow_in: bool) -> Result<Expr> {
2644        let start = self.current.span.start;
2645        self.bump()?; // yield
2646        let delegate = if self.at_punct(Punct::Star) && !self.current.newline_before {
2647            self.bump()?;
2648            true
2649        } else {
2650            false
2651        };
2652        let argument = if delegate {
2653            Some(Box::new(self.parse_assignment(allow_in)?))
2654        } else if self.current.newline_before
2655            || self.at_punct(Punct::RParen)
2656            || self.at_punct(Punct::RBracket)
2657            || self.at_punct(Punct::RBrace)
2658            || self.at_punct(Punct::Comma)
2659            || self.at_punct(Punct::Semicolon)
2660            || self.at_punct(Punct::Colon)
2661            || self.current.is_eof()
2662        {
2663            None
2664        } else {
2665            Some(Box::new(self.parse_assignment(allow_in)?))
2666        };
2667        Ok(Expr::new(
2668            ExprKind::Yield { argument, delegate },
2669            self.span_from(start),
2670        ))
2671    }
2672
2673    fn try_parse_arrow(&mut self, allow_in: bool) -> Result<Option<Expr>> {
2674        let starts_paren = self.at_punct(Punct::LParen);
2675        let starts_ident = matches!(self.current.kind, TokenKind::Ident(_));
2676        if !starts_paren && !starts_ident {
2677            return Ok(None);
2678        }
2679        // `(` could be a parenthesised expression instead of a parameter list.
2680        // Scanning ahead for the matching `)` and looking for `=>` avoids the
2681        // speculative parse (and its stack cost) in the common case.
2682        if starts_paren && !self.arrow_follows_paren()? {
2683            return Ok(None);
2684        }
2685        let snapshot = self.snapshot();
2686        let head = match self.parse_arrow_head() {
2687            Ok(head) => head,
2688            Err(_) => {
2689                self.restore(snapshot);
2690                return Ok(None);
2691            }
2692        };
2693        let Some(head) = head else {
2694            self.restore(snapshot);
2695            return Ok(None);
2696        };
2697        // Committed: `=>` has been consumed, so errors from here on are real.
2698        // Arrow parameter lists may never repeat a name, in any mode.
2699        {
2700            let mut seen: Vec<String> = Vec::new();
2701            for param in &head.params {
2702                let mut names = Vec::new();
2703                param.bound_names(&mut names);
2704                for name in names {
2705                    if seen.contains(&name.name) {
2706                        return Err(self.error_at(
2707                            format!(
2708                                "duplicate argument names not allowed in this context ('{}')",
2709                                name.name
2710                            ),
2711                            name.span,
2712                        ));
2713                    }
2714                    seen.push(name.name);
2715                }
2716            }
2717        }
2718        let saved_ctx = self.ctx;
2719        let saved_loop = self.loop_depth;
2720        let saved_switch = self.switch_depth;
2721        let saved_labels = std::mem::take(&mut self.labels);
2722        let saved_top = self.top_level;
2723        self.ctx = FnCtx {
2724            in_function: true,
2725            in_generator: false,
2726            in_async: head.is_async,
2727            in_method: saved_ctx.in_method,
2728            in_derived_constructor: saved_ctx.in_derived_constructor,
2729        };
2730        self.loop_depth = 0;
2731        self.switch_depth = 0;
2732        self.top_level = false;
2733        let body_start = self.current.span.start;
2734        let body = if self.at_punct(Punct::LBrace) {
2735            let block = self.parse_arrow_block(&head.params)?;
2736            (block, self.prev_end)
2737        } else {
2738            let expr = self.parse_assignment(allow_in)?;
2739            let end = expr.span.end;
2740            (FunctionBody::Expr(Box::new(expr)), end)
2741        };
2742        self.ctx = saved_ctx;
2743        self.loop_depth = saved_loop;
2744        self.switch_depth = saved_switch;
2745        self.labels = saved_labels;
2746        self.top_level = saved_top;
2747        let _ = body_start;
2748        let (body, end) = body;
2749        let span = Span::new(head.span.start, end);
2750        Ok(Some(Expr::new(
2751            ExprKind::Arrow(Box::new(Function {
2752                name: None,
2753                params: head.params,
2754                body,
2755                is_async: head.is_async,
2756                is_generator: false,
2757                is_arrow: true,
2758                span,
2759                params_span: head.params_span,
2760            })),
2761            span,
2762        )))
2763    }
2764
2765    /// Parse the `{ … }` body of an arrow, honouring a `"use strict"` prologue.
2766    fn parse_arrow_block(&mut self, params: &[Pattern]) -> Result<FunctionBody> {
2767        self.expect_punct(Punct::LBrace)?;
2768        self.push_scope(Scope::function(simple_parameter_names(params)));
2769        let result = (|| -> Result<Vec<Stmt>> {
2770            let mut body = Vec::new();
2771            let mut prologue = true;
2772            while !self.at_punct(Punct::RBrace) {
2773                if self.current.is_eof() {
2774                    return Err(self.unexpected());
2775                }
2776                let stmt = self.parse_statement_list_item()?;
2777                if prologue {
2778                    match self.directive_value(&stmt) {
2779                        Some(directive) if directive == "use strict" => self.enter_strict()?,
2780                        Some(_) => {}
2781                        None => prologue = false,
2782                    }
2783                }
2784                body.push(stmt);
2785            }
2786            Ok(body)
2787        })();
2788        self.pop_scope();
2789        let body = result?;
2790        self.bump()?;
2791        Ok(FunctionBody::Block(body))
2792    }
2793
2794    /// Whether the parenthesis at the current token is the parameter list of an
2795    /// arrow function, i.e. the matching `)` is followed by `=>`.
2796    ///
2797    /// This is a plain token walk with a bracket counter: no recursion, so it
2798    /// costs a clone of the lexer and nothing else.
2799    fn arrow_follows_paren(&self) -> Result<bool> {
2800        let mut lexer = self.lexer.clone();
2801        // The opening `(` was already consumed by the caller.
2802        let mut depth = 1usize;
2803        loop {
2804            let token = lexer.next_token()?;
2805            match token.kind {
2806                TokenKind::Eof => return Ok(false),
2807                TokenKind::Punct(Punct::LParen)
2808                | TokenKind::Punct(Punct::LBracket)
2809                | TokenKind::Punct(Punct::LBrace) => depth += 1,
2810                TokenKind::Punct(Punct::RParen)
2811                | TokenKind::Punct(Punct::RBracket)
2812                | TokenKind::Punct(Punct::RBrace) => {
2813                    if depth == 0 {
2814                        // Unbalanced input: the caller reports it.
2815                        return Ok(false);
2816                    }
2817                    depth -= 1;
2818                    if depth == 0 {
2819                        // The current token is the opening `(`, so the matching
2820                        // `)` is the token that brought us back to zero.
2821                        let next = lexer.next_token()?;
2822                        return Ok(matches!(next.kind, TokenKind::Punct(Punct::Arrow))
2823                            && !next.newline_before);
2824                    }
2825                }
2826                _ => {}
2827            }
2828        }
2829    }
2830
2831    /// Speculatively parse an arrow head, consuming `=>` on success.
2832    fn parse_arrow_head(&mut self) -> Result<Option<ArrowHead>> {
2833        let start = self.current.span.start;
2834        let mut is_async = false;
2835        if self.at_ident("async") {
2836            let peek = self.peek()?;
2837            if peek.newline_before {
2838                return Ok(None);
2839            }
2840            let plausible =
2841                matches!(peek.kind, TokenKind::Punct(Punct::LParen)) || peek.kind.is_identifier();
2842            if !plausible {
2843                return Ok(None);
2844            }
2845            self.bump()?;
2846            is_async = true;
2847        }
2848        let params_start = self.current.span.start;
2849        let params = if self.at_punct(Punct::LParen) {
2850            self.parse_formal_parameters()?
2851        } else if matches!(self.current.kind, TokenKind::Ident(_)) {
2852            let ident = self.expect_ident()?;
2853            vec![Pattern::new(
2854                PatternKind::Ident(ident),
2855                self.span_from(params_start),
2856            )]
2857        } else {
2858            return Ok(None);
2859        };
2860        let params_span = self.span_from(params_start);
2861        if !self.at_punct(Punct::Arrow) || self.current.newline_before {
2862            return Ok(None);
2863        }
2864        self.bump()?; // =>
2865        Ok(Some(ArrowHead {
2866            params,
2867            is_async,
2868            span: self.span_from(start),
2869            params_span,
2870        }))
2871    }
2872
2873    fn parse_conditional(&mut self, allow_in: bool) -> Result<Expr> {
2874        let start = self.current.span.start;
2875        let test = self.parse_binary(allow_in, 0)?;
2876        if !self.at_punct(Punct::Question) {
2877            return Ok(test);
2878        }
2879        self.bump()?;
2880        let consequent = self.parse_assignment(true)?;
2881        self.expect_punct(Punct::Colon)?;
2882        let alternate = self.parse_assignment(allow_in)?;
2883        Ok(Expr::new(
2884            ExprKind::Conditional {
2885                test: Box::new(test),
2886                cons: Box::new(consequent),
2887                alt: Box::new(alternate),
2888            },
2889            self.span_from(start),
2890        ))
2891    }
2892
2893    fn parse_binary(&mut self, allow_in: bool, min_prec: u8) -> Result<Expr> {
2894        let start = self.current.span.start;
2895        let mut lhs = self.parse_unary()?;
2896        while let Some((prec, op)) = binary_operator(&self.current.kind, allow_in) {
2897            if prec < min_prec {
2898                break;
2899            }
2900            let op_pos = self.current.span.start;
2901            self.bump()?;
2902            let next_min = if op.is_right_associative() {
2903                prec
2904            } else {
2905                prec + 1
2906            };
2907            let rhs = self.parse_binary(allow_in, next_min)?;
2908            lhs = build_binary(op, lhs, rhs, self.span_from(start), op_pos)?;
2909        }
2910        Ok(lhs)
2911    }
2912
2913    /// Unary and postfix operators. `in` is handled by the binary layer, so no
2914    /// `allow_in` flag is needed here.
2915    fn parse_unary(&mut self) -> Result<Expr> {
2916        let start = self.current.span.start;
2917        // Unary operators.
2918        let unary = match &self.current.kind {
2919            TokenKind::Keyword(Keyword::Delete) => Some(UnaryOp::Delete),
2920            TokenKind::Keyword(Keyword::Void) => Some(UnaryOp::Void),
2921            TokenKind::Keyword(Keyword::Typeof) => Some(UnaryOp::Typeof),
2922            TokenKind::Punct(Punct::Plus) => Some(UnaryOp::Plus),
2923            TokenKind::Punct(Punct::Minus) => Some(UnaryOp::Minus),
2924            TokenKind::Punct(Punct::Bang) => Some(UnaryOp::Not),
2925            TokenKind::Punct(Punct::Tilde) => Some(UnaryOp::BitNot),
2926            _ => None,
2927        };
2928        if let Some(op) = unary {
2929            let op_pos = self.current.span.start;
2930            self.bump()?;
2931            let argument = self.parse_unary()?;
2932            if op == UnaryOp::Delete && self.strict {
2933                if let ExprKind::Ident(ident) = &argument.unparen().kind {
2934                    return Err(
2935                        self.error_at("cannot delete a variable in strict mode", ident.span)
2936                    );
2937                }
2938            }
2939            let expr = Expr::at_operator(
2940                ExprKind::Unary {
2941                    op,
2942                    argument: Box::new(argument),
2943                },
2944                self.span_from(start),
2945                op_pos,
2946            );
2947            if self.at_punct(Punct::StarStar) {
2948                return Err(self.error(
2949                    "unexpected token '**': a unary expression may not be the base of '**'",
2950                ));
2951            }
2952            return Ok(expr);
2953        }
2954        // Prefix increment/decrement.
2955        if self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus) {
2956            let op_pos = self.current.span.start;
2957            let op = if self.at_punct(Punct::PlusPlus) {
2958                UpdateOp::Increment
2959            } else {
2960                UpdateOp::Decrement
2961            };
2962            self.bump()?;
2963            let argument = self.parse_unary()?;
2964            self.check_simple_target(&argument)?;
2965            return Ok(Expr::at_operator(
2966                ExprKind::Update {
2967                    op,
2968                    argument: Box::new(argument),
2969                    prefix: true,
2970                },
2971                self.span_from(start),
2972                op_pos,
2973            ));
2974        }
2975        // `await` in async contexts (and at a module's top level).
2976        if self.at_ident("await") && (self.ctx.in_async || (self.module && self.top_level)) {
2977            let peek = self.peek()?;
2978            let starts_expression = !matches!(
2979                peek.kind,
2980                TokenKind::Punct(Punct::RParen)
2981                    | TokenKind::Punct(Punct::RBracket)
2982                    | TokenKind::Punct(Punct::RBrace)
2983                    | TokenKind::Punct(Punct::Comma)
2984                    | TokenKind::Punct(Punct::Semicolon)
2985                    | TokenKind::Punct(Punct::Colon)
2986                    | TokenKind::Punct(Punct::Eq)
2987                    | TokenKind::Punct(Punct::Arrow)
2988                    | TokenKind::Punct(Punct::Dot)
2989                    | TokenKind::Punct(Punct::QuestionDot)
2990                    | TokenKind::Punct(Punct::LBracket)
2991            ) && !peek.newline_before;
2992            if starts_expression {
2993                self.bump()?;
2994                let argument = self.parse_unary()?;
2995                return Ok(Expr::new(
2996                    ExprKind::Await(Box::new(argument)),
2997                    self.span_from(start),
2998                ));
2999            }
3000        }
3001        let expr = self.parse_lhs_expression()?;
3002        // Postfix increment/decrement (no line break allowed before the operator).
3003        let result = if (self.at_punct(Punct::PlusPlus) || self.at_punct(Punct::MinusMinus))
3004            && !self.current.newline_before
3005        {
3006            let op_pos = self.current.span.start;
3007            let op = if self.at_punct(Punct::PlusPlus) {
3008                UpdateOp::Increment
3009            } else {
3010                UpdateOp::Decrement
3011            };
3012            self.check_simple_target(&expr)?;
3013            self.bump()?;
3014            Expr::at_operator(
3015                ExprKind::Update {
3016                    op,
3017                    argument: Box::new(expr),
3018                    prefix: false,
3019                },
3020                self.span_from(start),
3021                op_pos,
3022            )
3023        } else {
3024            expr
3025        };
3026        Ok(result)
3027    }
3028
3029    fn check_simple_target(&self, expr: &Expr) -> Result<()> {
3030        match &expr.unparen().kind {
3031            ExprKind::Ident(_) => Ok(()),
3032            ExprKind::Member {
3033                optional: false, ..
3034            } => Ok(()),
3035            _ => Err(self.error_at("invalid assignment left-hand side", expr.span)),
3036        }
3037    }
3038
3039    fn parse_lhs_expression(&mut self) -> Result<Expr> {
3040        let start = self.current.span.start;
3041        let mut expr = if self.at_keyword(Keyword::New) {
3042            self.parse_new_expression()?
3043        } else {
3044            self.parse_primary()?
3045        };
3046        let mut saw_optional = false;
3047        loop {
3048            // The position of the punctuator that follows the base expression: a
3049            // failed `.`, `[` or `(` is blamed on that token, not on the base.
3050            let op_pos = self.current.span.start;
3051            match self.current.kind.clone() {
3052                TokenKind::Punct(Punct::Dot) => {
3053                    self.bump()?;
3054                    let property = self.parse_member_property()?;
3055                    expr = Expr::at_operator(
3056                        ExprKind::Member {
3057                            object: Box::new(expr),
3058                            property,
3059                            optional: false,
3060                        },
3061                        self.span_from(start),
3062                        op_pos,
3063                    );
3064                }
3065                TokenKind::Punct(Punct::QuestionDot) => {
3066                    saw_optional = true;
3067                    self.bump()?;
3068                    if self.at_punct(Punct::LParen) {
3069                        let arguments = self.parse_arguments()?;
3070                        expr = Expr::at_operator(
3071                            ExprKind::Call {
3072                                callee: Box::new(expr),
3073                                arguments,
3074                                optional: true,
3075                            },
3076                            self.span_from(start),
3077                            op_pos,
3078                        );
3079                    } else if self.at_punct(Punct::LBracket) {
3080                        self.bump()?;
3081                        let index = self.parse_expression(true)?;
3082                        self.expect_punct(Punct::RBracket)?;
3083                        expr = Expr::at_operator(
3084                            ExprKind::Member {
3085                                object: Box::new(expr),
3086                                property: MemberProp::Computed(Box::new(index)),
3087                                optional: true,
3088                            },
3089                            self.span_from(start),
3090                            op_pos,
3091                        );
3092                    } else {
3093                        let property = self.parse_member_property()?;
3094                        expr = Expr::at_operator(
3095                            ExprKind::Member {
3096                                object: Box::new(expr),
3097                                property,
3098                                optional: true,
3099                            },
3100                            self.span_from(start),
3101                            op_pos,
3102                        );
3103                    }
3104                }
3105                TokenKind::Punct(Punct::LBracket) => {
3106                    self.bump()?;
3107                    let index = self.parse_expression(true)?;
3108                    self.expect_punct(Punct::RBracket)?;
3109                    expr = Expr::at_operator(
3110                        ExprKind::Member {
3111                            object: Box::new(expr),
3112                            property: MemberProp::Computed(Box::new(index)),
3113                            optional: false,
3114                        },
3115                        self.span_from(start),
3116                        op_pos,
3117                    );
3118                }
3119                TokenKind::Punct(Punct::LParen) => {
3120                    let arguments = self.parse_arguments()?;
3121                    expr = Expr::at_operator(
3122                        ExprKind::Call {
3123                            callee: Box::new(expr),
3124                            arguments,
3125                            optional: false,
3126                        },
3127                        self.span_from(start),
3128                        op_pos,
3129                    );
3130                }
3131                TokenKind::Template(_) => {
3132                    if saw_optional || matches!(expr.unparen().kind, ExprKind::OptionalChain(_)) {
3133                        return Err(
3134                            self.error("tagged template cannot be used in an optional chain")
3135                        );
3136                    }
3137                    let quasi = self.parse_template()?;
3138                    expr = Expr::new(
3139                        ExprKind::TaggedTemplate {
3140                            tag: Box::new(expr),
3141                            quasi: Box::new(quasi),
3142                        },
3143                        self.span_from(start),
3144                    );
3145                }
3146                _ => break,
3147            }
3148        }
3149        if saw_optional {
3150            expr = Expr::new(
3151                ExprKind::OptionalChain(Box::new(expr)),
3152                self.span_from(start),
3153            );
3154        }
3155        Ok(expr)
3156    }
3157
3158    fn parse_member_property(&mut self) -> Result<MemberProp> {
3159        if self.at_punct(Punct::Hash) {
3160            self.bump()?;
3161            let ident = self.expect_ident()?;
3162            if !self.private.iter().any(|env| env.contains(&ident.name)) {
3163                return Err(self.error_at(
3164                    format!(
3165                        "private field '#{}' must be declared in an enclosing class",
3166                        ident.name
3167                    ),
3168                    ident.span,
3169                ));
3170            }
3171            return Ok(MemberProp::Private(ident));
3172        }
3173        match self.current.kind.clone() {
3174            TokenKind::Ident(name) => {
3175                let span = self.current.span;
3176                self.bump()?;
3177                Ok(MemberProp::Ident(Ident { name, span }))
3178            }
3179            TokenKind::Keyword(kw) => {
3180                let span = self.current.span;
3181                self.bump()?;
3182                Ok(MemberProp::Ident(Ident {
3183                    name: kw.as_str().to_string(),
3184                    span,
3185                }))
3186            }
3187            _ => Err(self.error("expecting a property name")),
3188        }
3189    }
3190
3191    fn parse_new_expression(&mut self) -> Result<Expr> {
3192        let start = self.current.span.start;
3193        self.bump()?; // new
3194        if self.at_punct(Punct::Dot) {
3195            self.bump()?;
3196            if !self.at_ident("target") {
3197                return Err(self.error("expecting 'target' after 'new.'"));
3198            }
3199            if !self.ctx.in_function {
3200                return Err(self.error("invalid use of 'new.target' outside of a function"));
3201            }
3202            self.bump()?;
3203            return Ok(Expr::new(ExprKind::NewTarget, self.span_from(start)));
3204        }
3205        let mut callee = if self.at_keyword(Keyword::New) {
3206            self.parse_new_expression()?
3207        } else {
3208            self.parse_primary()?
3209        };
3210        // Member accesses bind tighter than `new`, calls do not.
3211        loop {
3212            let op_pos = self.current.span.start;
3213            match self.current.kind.clone() {
3214                TokenKind::Punct(Punct::Dot) => {
3215                    self.bump()?;
3216                    let property = self.parse_member_property()?;
3217                    callee = Expr::at_operator(
3218                        ExprKind::Member {
3219                            object: Box::new(callee),
3220                            property,
3221                            optional: false,
3222                        },
3223                        self.span_from(start),
3224                        op_pos,
3225                    );
3226                }
3227                TokenKind::Punct(Punct::LBracket) => {
3228                    self.bump()?;
3229                    let index = self.parse_expression(true)?;
3230                    self.expect_punct(Punct::RBracket)?;
3231                    callee = Expr::at_operator(
3232                        ExprKind::Member {
3233                            object: Box::new(callee),
3234                            property: MemberProp::Computed(Box::new(index)),
3235                            optional: false,
3236                        },
3237                        self.span_from(start),
3238                        op_pos,
3239                    );
3240                }
3241                TokenKind::Punct(Punct::QuestionDot) => {
3242                    return Err(self.error("new keyword cannot be used with an optional chain"));
3243                }
3244                _ => break,
3245            }
3246        }
3247        if matches!(callee.unparen().kind, ExprKind::OptionalChain(_)) {
3248            return Err(self.error_at("cannot use 'new' with an optional chain", callee.span));
3249        }
3250        let arguments = if self.at_punct(Punct::LParen) {
3251            // `new C(...)`: a failure in the constructor call is blamed on the `(`.
3252            let op_pos = self.current.span.start;
3253            let arguments = Some(self.parse_arguments()?);
3254            return Ok(Expr::at_operator(
3255                ExprKind::New {
3256                    callee: Box::new(callee),
3257                    arguments,
3258                },
3259                self.span_from(start),
3260                op_pos,
3261            ));
3262        } else {
3263            None
3264        };
3265        Ok(Expr::new(
3266            ExprKind::New {
3267                callee: Box::new(callee),
3268                arguments,
3269            },
3270            self.span_from(start),
3271        ))
3272    }
3273
3274    fn parse_arguments(&mut self) -> Result<Vec<Expr>> {
3275        self.expect_punct(Punct::LParen)?;
3276        let mut arguments = Vec::new();
3277        while !self.at_punct(Punct::RParen) {
3278            if self.at_punct(Punct::Ellipsis) {
3279                let start = self.current.span.start;
3280                self.bump()?;
3281                let argument = self.parse_assignment(true)?;
3282                arguments.push(Expr::new(
3283                    ExprKind::Spread(Box::new(argument)),
3284                    self.span_from(start),
3285                ));
3286            } else {
3287                arguments.push(self.parse_assignment(true)?);
3288            }
3289            if !self.eat_punct(Punct::Comma)? {
3290                break;
3291            }
3292        }
3293        self.expect_punct(Punct::RParen)?;
3294        Ok(arguments)
3295    }
3296
3297    /// Primary expressions.
3298    ///
3299    /// The rarely used forms are dispatched to [`Parser::parse_primary_complex`]
3300    /// so that this function — which sits on every nesting level — keeps a small
3301    /// stack frame. That directly raises how deeply a program may nest before
3302    /// the stack limit is hit (debug builds get ~4x more depth out of it).
3303    fn parse_primary(&mut self) -> Result<Expr> {
3304        let start = self.current.span.start;
3305        match self.current.kind.clone() {
3306            TokenKind::Number(NumberLiteral::Int(value)) => {
3307                self.bump()?;
3308                Ok(Expr::new(
3309                    ExprKind::Number(value as f64),
3310                    self.span_from(start),
3311                ))
3312            }
3313            TokenKind::Number(NumberLiteral::Float(value)) => {
3314                self.bump()?;
3315                Ok(Expr::new(ExprKind::Number(value), self.span_from(start)))
3316            }
3317            TokenKind::String(value) => {
3318                self.bump()?;
3319                Ok(Expr::new(ExprKind::String(value), self.span_from(start)))
3320            }
3321            TokenKind::Ident(name) if name == "async" => {
3322                let peek = self.peek()?;
3323                if matches!(peek.kind, TokenKind::Keyword(Keyword::Function))
3324                    && !peek.newline_before
3325                {
3326                    self.bump()?; // async
3327                    let func = self.parse_function(FunctionForm::Expression, true)?;
3328                    return Ok(Expr::new(
3329                        ExprKind::Function(Box::new(func)),
3330                        self.span_from(start),
3331                    ));
3332                }
3333                let span = self.current.span;
3334                self.bump()?;
3335                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3336            }
3337            TokenKind::Ident(name) => {
3338                let span = self.current.span;
3339                self.check_identifier(&name, span)?;
3340                self.bump()?;
3341                Ok(Expr::new(ExprKind::Ident(Ident { name, span }), span))
3342            }
3343            TokenKind::Keyword(Keyword::This) => {
3344                self.bump()?;
3345                Ok(Expr::new(ExprKind::This, self.span_from(start)))
3346            }
3347            TokenKind::Keyword(Keyword::Null) => {
3348                self.bump()?;
3349                Ok(Expr::new(ExprKind::Null, self.span_from(start)))
3350            }
3351            TokenKind::Keyword(Keyword::True) => {
3352                self.bump()?;
3353                Ok(Expr::new(ExprKind::Bool(true), self.span_from(start)))
3354            }
3355            TokenKind::Keyword(Keyword::False) => {
3356                self.bump()?;
3357                Ok(Expr::new(ExprKind::Bool(false), self.span_from(start)))
3358            }
3359            TokenKind::Punct(Punct::LParen) => {
3360                self.bump()?;
3361                let inner = self.parse_expression(true)?;
3362                self.expect_punct(Punct::RParen)?;
3363                Ok(Expr::new(
3364                    ExprKind::Paren(Box::new(inner)),
3365                    self.span_from(start),
3366                ))
3367            }
3368            TokenKind::Punct(Punct::Slash) | TokenKind::Punct(Punct::SlashEq) => {
3369                self.parse_regex_literal(start)
3370            }
3371            _ => self.parse_primary_complex(start),
3372        }
3373    }
3374
3375    /// The primary expressions that need a lot of code: literals with structure,
3376    /// functions, classes, `import`, `super`, `#x in y`.
3377    #[inline(never)]
3378    fn parse_primary_complex(&mut self, start: Position) -> Result<Expr> {
3379        match self.current.kind.clone() {
3380            TokenKind::BigInt(literal) => {
3381                self.bump()?;
3382                Ok(Expr::new(
3383                    ExprKind::BigInt {
3384                        digits: literal.digits,
3385                        radix: literal.radix,
3386                    },
3387                    self.span_from(start),
3388                ))
3389            }
3390            TokenKind::Template(_) => {
3391                let template = self.parse_template()?;
3392                Ok(Expr::new(
3393                    ExprKind::Template(Box::new(template)),
3394                    self.span_from(start),
3395                ))
3396            }
3397            TokenKind::Keyword(Keyword::Function) => {
3398                let func = self.parse_function(FunctionForm::Expression, false)?;
3399                Ok(Expr::new(
3400                    ExprKind::Function(Box::new(func)),
3401                    self.span_from(start),
3402                ))
3403            }
3404            TokenKind::Keyword(Keyword::Class) => {
3405                let class = self.parse_class(true)?;
3406                Ok(Expr::new(
3407                    ExprKind::Class(Box::new(class)),
3408                    self.span_from(start),
3409                ))
3410            }
3411            TokenKind::Keyword(Keyword::Import) => self.parse_import_expression(),
3412            TokenKind::Keyword(Keyword::Super) => self.parse_super(),
3413            TokenKind::Punct(Punct::LBracket) => self.parse_array_literal(),
3414            TokenKind::Punct(Punct::LBrace) => self.parse_object_literal(),
3415            TokenKind::Punct(Punct::Hash) => self.parse_private_in(start),
3416            _ => Err(self.unexpected()),
3417        }
3418    }
3419
3420    /// `super` or `super(...)`.
3421    #[inline(never)]
3422    fn parse_super(&mut self) -> Result<Expr> {
3423        let start = self.current.span.start;
3424        self.bump()?;
3425        if self.at_punct(Punct::LParen) {
3426            if !self.ctx.in_derived_constructor {
3427                return Err(self.error_at(
3428                    "invalid use of 'super' in a non-derived constructor",
3429                    self.span_from(start),
3430                ));
3431            }
3432            let arguments = self.parse_arguments()?;
3433            return Ok(Expr::new(
3434                ExprKind::SuperCall(arguments),
3435                self.span_from(start),
3436            ));
3437        }
3438        if !self.ctx.in_method {
3439            return Err(self.error_at(
3440                "invalid use of 'super' outside of a method",
3441                self.span_from(start),
3442            ));
3443        }
3444        Ok(Expr::new(ExprKind::SuperProp, self.span_from(start)))
3445    }
3446
3447    /// `#name in object`.
3448    #[inline(never)]
3449    fn parse_private_in(&mut self, start: Position) -> Result<Expr> {
3450        self.bump()?;
3451        let ident = self.expect_ident()?;
3452        if !self.private.iter().any(|env| env.contains(&ident.name)) {
3453            return Err(self.error_at(
3454                format!(
3455                    "private field '#{}' must be declared in an enclosing class",
3456                    ident.name
3457                ),
3458                ident.span,
3459            ));
3460        }
3461        if !self.at_keyword(Keyword::In) {
3462            return Err(self.error("expecting 'in' after a private name"));
3463        }
3464        self.bump()?;
3465        let object = self.parse_unary()?;
3466        Ok(Expr::new(
3467            ExprKind::PrivateIn {
3468                name: ident,
3469                object: Box::new(object),
3470            },
3471            self.span_from(start),
3472        ))
3473    }
3474
3475    /// A regular expression literal: the lexer produced `/` (or `/=`), so the
3476    /// token has to be re-scanned from that position.
3477    #[inline(never)]
3478    fn parse_regex_literal(&mut self, start: Position) -> Result<Expr> {
3479        let token = self.lexer.re_scan_regex(self.current.span.start)?;
3480        self.current = token;
3481        let TokenKind::RegExp { pattern, flags } = self.current.kind.clone() else {
3482            unreachable!("re_scan_regex returns a RegExp token")
3483        };
3484        self.bump()?;
3485        Ok(Expr::new(
3486            ExprKind::RegExp { pattern, flags },
3487            self.span_from(start),
3488        ))
3489    }
3490
3491    fn parse_import_expression(&mut self) -> Result<Expr> {
3492        let start = self.current.span.start;
3493        self.bump()?; // import
3494        if self.at_punct(Punct::Dot) {
3495            if !self.module {
3496                return Err(self.error_at(
3497                    "invalid use of 'import.meta' outside of a module",
3498                    self.span_from(start),
3499                ));
3500            }
3501            self.bump()?;
3502            if !self.at_ident("meta") {
3503                return Err(self.error("expecting 'meta' after 'import.'"));
3504            }
3505            self.bump()?;
3506            return Ok(Expr::new(ExprKind::ImportMeta, self.span_from(start)));
3507        }
3508        if self.at_punct(Punct::LParen) {
3509            self.bump()?;
3510            let specifier = self.parse_assignment(true)?;
3511            if self.at_punct(Punct::Comma) {
3512                return Err(self.error("import() takes exactly one argument"));
3513            }
3514            self.expect_punct(Punct::RParen)?;
3515            return Ok(Expr::new(
3516                ExprKind::ImportCall(Box::new(specifier)),
3517                self.span_from(start),
3518            ));
3519        }
3520        Err(self.unexpected())
3521    }
3522
3523    fn parse_array_literal(&mut self) -> Result<Expr> {
3524        let start = self.current.span.start;
3525        self.expect_punct(Punct::LBracket)?;
3526        let mut elements = Vec::new();
3527        while !self.at_punct(Punct::RBracket) {
3528            if self.at_punct(Punct::Comma) {
3529                self.bump()?;
3530                elements.push(None);
3531                continue;
3532            }
3533            if self.at_punct(Punct::Ellipsis) {
3534                let spread_start = self.current.span.start;
3535                self.bump()?;
3536                let argument = self.parse_assignment(true)?;
3537                elements.push(Some(ArrayElement::Spread(Box::new(Expr::new(
3538                    ExprKind::Spread(Box::new(argument)),
3539                    self.span_from(spread_start),
3540                )))));
3541            } else {
3542                let expr = self.parse_assignment(true)?;
3543                elements.push(Some(ArrayElement::Expr(Box::new(expr))));
3544            }
3545            if !self.eat_punct(Punct::Comma)? {
3546                break;
3547            }
3548        }
3549        self.expect_punct(Punct::RBracket)?;
3550        Ok(Expr::new(
3551            ExprKind::Array { elements },
3552            self.span_from(start),
3553        ))
3554    }
3555
3556    fn parse_object_literal(&mut self) -> Result<Expr> {
3557        let start = self.current.span.start;
3558        self.expect_punct(Punct::LBrace)?;
3559        let mut properties: Vec<ObjectProperty> = Vec::new();
3560        let mut proto_count = 0;
3561        while !self.at_punct(Punct::RBrace) {
3562            let property_start = self.current.span.start;
3563            if self.at_punct(Punct::Ellipsis) {
3564                self.bump()?;
3565                let argument = self.parse_assignment(true)?;
3566                properties.push(ObjectProperty::Spread(Box::new(argument)));
3567            } else {
3568                let mut is_async = false;
3569                let mut is_generator = false;
3570                let mut accessor: Option<MethodKind> = None;
3571                if self.at_ident("async") {
3572                    let peek = self.peek()?;
3573                    let is_modifier = !matches!(
3574                        peek.kind,
3575                        TokenKind::Punct(Punct::LParen)
3576                            | TokenKind::Punct(Punct::Colon)
3577                            | TokenKind::Punct(Punct::Comma)
3578                            | TokenKind::Punct(Punct::RBrace)
3579                            | TokenKind::Punct(Punct::Eq)
3580                    ) && !peek.newline_before;
3581                    if is_modifier {
3582                        self.bump()?;
3583                        is_async = true;
3584                    }
3585                }
3586                if self.at_punct(Punct::Star) {
3587                    self.bump()?;
3588                    is_generator = true;
3589                }
3590                if accessor.is_none() && (self.at_ident("get") || self.at_ident("set")) {
3591                    let is_get = self.at_ident("get");
3592                    let peek = self.peek()?;
3593                    if is_property_key_start(&peek.kind) {
3594                        self.bump()?;
3595                        accessor = Some(if is_get {
3596                            MethodKind::Get
3597                        } else {
3598                            MethodKind::Set
3599                        });
3600                    }
3601                }
3602                let key = self.parse_property_key()?;
3603                let is_computed = matches!(key, PropName::Computed(_));
3604                if self.at_punct(Punct::LParen) {
3605                    let saved = self.ctx;
3606                    self.ctx = FnCtx {
3607                        in_function: true,
3608                        in_generator: is_generator,
3609                        in_async: is_async,
3610                        in_method: true,
3611                        in_derived_constructor: false,
3612                    };
3613                    let saved_top = self.top_level;
3614                    self.top_level = false;
3615                    let func_result = (|| -> Result<Function> {
3616                        let params = self.parse_formal_parameters()?;
3617                        let (params, params_span, body) =
3618                            self.parse_function_body(params, is_generator, is_async)?;
3619                        Ok(Function {
3620                            name: None,
3621                            params,
3622                            body,
3623                            is_async,
3624                            is_generator,
3625                            is_arrow: false,
3626                            span: self.span_from(property_start),
3627                            params_span,
3628                        })
3629                    })();
3630                    self.ctx = saved;
3631                    self.top_level = saved_top;
3632                    let func = func_result?;
3633                    let kind = match accessor {
3634                        Some(kind) => {
3635                            if is_generator || is_async {
3636                                return Err(self.error_at(
3637                                    "accessors may not be generators or async",
3638                                    func.span,
3639                                ));
3640                            }
3641                            if kind == MethodKind::Get && !func.params.is_empty() {
3642                                return Err(
3643                                    self.error_at("getter must have no arguments", func.span)
3644                                );
3645                            }
3646                            if kind == MethodKind::Set && func.params.len() != 1 {
3647                                return Err(self
3648                                    .error_at("setter must have exactly one argument", func.span));
3649                            }
3650                            match kind {
3651                                MethodKind::Get => PropertyKind::Get,
3652                                MethodKind::Set => PropertyKind::Set,
3653                                MethodKind::Method | MethodKind::Constructor => {
3654                                    PropertyKind::Method
3655                                }
3656                            }
3657                        }
3658                        None => PropertyKind::Method,
3659                    };
3660                    let span = self.span_from(property_start);
3661                    properties.push(ObjectProperty::Property {
3662                        key,
3663                        value: Box::new(Expr::new(ExprKind::Function(Box::new(func)), span)),
3664                        kind,
3665                        shorthand: false,
3666                        span,
3667                    });
3668                } else if self.eat_punct(Punct::Colon)? {
3669                    let value = self.parse_assignment(true)?;
3670                    if !is_computed {
3671                        if let Some(PropKeyRef::Str("__proto__")) = key.static_name() {
3672                            proto_count += 1;
3673                            if proto_count > 1 {
3674                                return Err(self.error_at(
3675                                    "duplicate __proto__ fields are not allowed in object literals",
3676                                    self.span_from(property_start),
3677                                ));
3678                            }
3679                        }
3680                    }
3681                    properties.push(ObjectProperty::Property {
3682                        key,
3683                        value: Box::new(value),
3684                        kind: PropertyKind::Value,
3685                        shorthand: false,
3686                        span: self.span_from(property_start),
3687                    });
3688                } else {
3689                    // Shorthand `{a}` / `{a = 1}` (the latter only inside a
3690                    // destructuring pattern).
3691                    let PropName::Literal(PropKey::Str(name)) = &key else {
3692                        return Err(self.error("expecting ':' after a property name"));
3693                    };
3694                    let ident_span = self.span_from(property_start);
3695                    let ident = Ident {
3696                        name: name.clone(),
3697                        span: ident_span,
3698                    };
3699                    self.check_identifier(&ident.name, ident.span)?;
3700                    let mut value = Expr::new(ExprKind::Ident(ident.clone()), ident_span);
3701                    if self.at_punct(Punct::Eq) {
3702                        // CoverInitializedName: only legal once the object turns
3703                        // out to be a destructuring pattern.
3704                        self.cover_inits.push(ident_span);
3705                        self.bump()?;
3706                        let default = self.parse_assignment(true)?;
3707                        let target = Pattern::new(PatternKind::Ident(ident), ident_span);
3708                        value = Expr::new(
3709                            ExprKind::Assign {
3710                                op: AssignOp::Assign,
3711                                target: Box::new(target),
3712                                value: Box::new(default),
3713                            },
3714                            ident_span,
3715                        );
3716                    }
3717                    properties.push(ObjectProperty::Property {
3718                        key,
3719                        value: Box::new(value),
3720                        kind: PropertyKind::Value,
3721                        shorthand: true,
3722                        span: ident_span,
3723                    });
3724                }
3725            }
3726            if !self.eat_punct(Punct::Comma)? {
3727                break;
3728            }
3729        }
3730        self.expect_punct(Punct::RBrace)?;
3731        Ok(Expr::new(
3732            ExprKind::Object(properties),
3733            self.span_from(start),
3734        ))
3735    }
3736
3737    fn parse_template(&mut self) -> Result<TemplateLiteral> {
3738        let mut quasis = Vec::new();
3739        let mut expressions = Vec::new();
3740        loop {
3741            let (cooked, raw, kind) = match self.current.kind.clone() {
3742                TokenKind::Template(chunk) => (chunk.cooked, chunk.raw, chunk.kind),
3743                _ => return Err(self.error("expecting a template literal")),
3744            };
3745            let tail = matches!(kind, TemplateKind::NoSubstitution | TemplateKind::Tail);
3746            quasis.push(TemplateChunk { cooked, raw, tail });
3747            if tail {
3748                self.bump()?;
3749                break;
3750            }
3751            self.bump()?; // move to the first token of the substitution
3752            let expr = self.parse_expression(true)?;
3753            expressions.push(expr);
3754            if !self.at_punct(Punct::RBrace) {
3755                return Err(self.error("expecting '}' in a template substitution"));
3756            }
3757            let brace = self.current.span.start;
3758            let token = self.lexer.re_scan_template_continue(brace)?;
3759            self.current = token;
3760        }
3761        Ok(TemplateLiteral {
3762            quasis,
3763            expressions,
3764        })
3765    }
3766}
3767
3768/// Which kind of function is being parsed (affects whether a name is required).
3769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3770enum FunctionForm {
3771    Declaration,
3772    Expression,
3773}
3774
3775/// Names of the parameters that participate in declaration-conflict checks.
3776///
3777/// Engines only check *simple* (identifier) parameters against the body's
3778/// lexical declarations: `function f(a) { let a; }` is an early error, but
3779/// `function f({a}) { let a; }` is not (QuickJS behaves the same way, so this
3780/// deliberately follows the reference rather than ES2025 §10.2.1).
3781fn simple_parameter_names(params: &[Pattern]) -> Vec<String> {
3782    params
3783        .iter()
3784        .filter_map(|param| match &param.kind {
3785            PatternKind::Ident(id) => Some(id.name.clone()),
3786            _ => None,
3787        })
3788        .collect()
3789}
3790
3791/// Collect the names a top-level module item declares, for the exported-name
3792/// check.
3793fn collect_module_binding(stmt: &Stmt, out: &mut Vec<String>) {
3794    match &stmt.kind {
3795        StmtKind::VarDecl(decl) => {
3796            for declarator in &decl.declarators {
3797                let mut names = Vec::new();
3798                declarator.target.bound_names(&mut names);
3799                out.extend(names.into_iter().map(|n| n.name));
3800            }
3801        }
3802        StmtKind::FuncDecl(func) => {
3803            if let Some(name) = &func.name {
3804                out.push(name.name.clone());
3805            }
3806        }
3807        StmtKind::ClassDecl(class) => {
3808            if let Some(name) = &class.name {
3809                out.push(name.name.clone());
3810            }
3811        }
3812        StmtKind::Import(decl) => {
3813            for specifier in &decl.specifiers {
3814                match specifier {
3815                    ImportSpecifier::Default(id) => out.push(id.name.clone()),
3816                    ImportSpecifier::Namespace(id) => out.push(id.name.clone()),
3817                    ImportSpecifier::Named { local, .. } => out.push(local.name.clone()),
3818                }
3819            }
3820        }
3821        StmtKind::Export(decl) => match &decl.kind {
3822            ExportKind::Declaration(inner) => collect_module_binding(inner, out),
3823            ExportKind::Default(expr) => match &expr.unparen().kind {
3824                ExprKind::Function(func) => {
3825                    if let Some(name) = &func.name {
3826                        out.push(name.name.clone());
3827                    }
3828                }
3829                ExprKind::Class(class) => {
3830                    if let Some(name) = &class.name {
3831                        out.push(name.name.clone());
3832                    }
3833                }
3834                _ => {}
3835            },
3836            _ => {}
3837        },
3838        _ => {}
3839    }
3840}
3841
3842/// Whether `inner` is fully inside `outer` (byte offset comparison only).
3843fn span_contains(outer: Span, inner: Span) -> bool {
3844    inner.start.offset >= outer.start.offset && inner.end.offset <= outer.end.offset
3845}
3846
3847fn is_property_key_start(kind: &TokenKind) -> bool {
3848    matches!(
3849        kind,
3850        TokenKind::Ident(_)
3851            | TokenKind::Keyword(_)
3852            | TokenKind::String(_)
3853            | TokenKind::Number(_)
3854            | TokenKind::Punct(Punct::LBracket)
3855            | TokenKind::Punct(Punct::Hash)
3856    )
3857}
3858
3859/// A binary operator with its precedence, as consumed by [`Parser::parse_binary`].
3860#[derive(Debug, Clone, Copy)]
3861enum BinOp {
3862    Binary(BinaryOp),
3863    Logical(LogicalOp),
3864}
3865
3866impl BinOp {
3867    fn is_right_associative(self) -> bool {
3868        matches!(self, BinOp::Binary(BinaryOp::Pow))
3869    }
3870}
3871
3872fn binary_operator(kind: &TokenKind, allow_in: bool) -> Option<(u8, BinOp)> {
3873    use BinaryOp as B;
3874    use LogicalOp as L;
3875    let result = match kind {
3876        TokenKind::Punct(Punct::QuestionQuestion) => (1, BinOp::Logical(L::Coalesce)),
3877        TokenKind::Punct(Punct::PipePipe) => (2, BinOp::Logical(L::Or)),
3878        TokenKind::Punct(Punct::AmpAmp) => (3, BinOp::Logical(L::And)),
3879        TokenKind::Punct(Punct::Pipe) => (4, BinOp::Binary(B::BitOr)),
3880        TokenKind::Punct(Punct::Caret) => (5, BinOp::Binary(B::BitXor)),
3881        TokenKind::Punct(Punct::Amp) => (6, BinOp::Binary(B::BitAnd)),
3882        TokenKind::Punct(Punct::EqEq) => (7, BinOp::Binary(B::Eq)),
3883        TokenKind::Punct(Punct::NotEq) => (7, BinOp::Binary(B::NotEq)),
3884        TokenKind::Punct(Punct::EqEqEq) => (7, BinOp::Binary(B::StrictEq)),
3885        TokenKind::Punct(Punct::NotEqEq) => (7, BinOp::Binary(B::StrictNotEq)),
3886        TokenKind::Punct(Punct::Lt) => (8, BinOp::Binary(B::Lt)),
3887        TokenKind::Punct(Punct::LtEq) => (8, BinOp::Binary(B::LtEq)),
3888        TokenKind::Punct(Punct::Gt) => (8, BinOp::Binary(B::Gt)),
3889        TokenKind::Punct(Punct::GtEq) => (8, BinOp::Binary(B::GtEq)),
3890        TokenKind::Keyword(Keyword::Instanceof) => (8, BinOp::Binary(B::Instanceof)),
3891        TokenKind::Keyword(Keyword::In) if allow_in => (8, BinOp::Binary(B::In)),
3892        TokenKind::Punct(Punct::Shl) => (9, BinOp::Binary(B::Shl)),
3893        TokenKind::Punct(Punct::Shr) => (9, BinOp::Binary(B::Shr)),
3894        TokenKind::Punct(Punct::UShr) => (9, BinOp::Binary(B::UShr)),
3895        TokenKind::Punct(Punct::Plus) => (10, BinOp::Binary(B::Add)),
3896        TokenKind::Punct(Punct::Minus) => (10, BinOp::Binary(B::Sub)),
3897        TokenKind::Punct(Punct::Star) => (11, BinOp::Binary(B::Mul)),
3898        TokenKind::Punct(Punct::Slash) => (11, BinOp::Binary(B::Div)),
3899        TokenKind::Punct(Punct::Percent) => (11, BinOp::Binary(B::Mod)),
3900        TokenKind::Punct(Punct::StarStar) => (12, BinOp::Binary(B::Pow)),
3901        _ => return None,
3902    };
3903    Some(result)
3904}
3905
3906fn build_binary(op: BinOp, left: Expr, right: Expr, span: Span, op_pos: Position) -> Result<Expr> {
3907    match op {
3908        BinOp::Binary(op) => Ok(Expr::at_operator(
3909            ExprKind::Binary {
3910                op,
3911                left: Box::new(left),
3912                right: Box::new(right),
3913            },
3914            span,
3915            op_pos,
3916        )),
3917        BinOp::Logical(op) => {
3918            // `??` may not be mixed with `&&`/`||` without parentheses.
3919            // A parenthesised operand is visibly a different production, so the
3920            // check must look at the raw node, not through `Paren`.
3921            let mixes = |expr: &Expr, op: LogicalOp| {
3922                matches!(&expr.kind, ExprKind::Logical { op: inner, .. }
3923                    if (op == LogicalOp::Coalesce) != (*inner == LogicalOp::Coalesce))
3924            };
3925            if mixes(&left, op) || mixes(&right, op) {
3926                return Err(SyntaxError::new(
3927                    "cannot mix '??' with '&&' or '||' without parentheses",
3928                    span,
3929                ));
3930            }
3931            Ok(Expr::at_operator(
3932                ExprKind::Logical {
3933                    op,
3934                    left: Box::new(left),
3935                    right: Box::new(right),
3936                },
3937                span,
3938                op_pos,
3939            ))
3940        }
3941    }
3942}
3943
3944/// Rebuild an expression from a pattern (used when a pattern has to go back
3945/// through [`Parser::expr_to_pattern`], e.g. `{a: [b = 1]}`).
3946fn pattern_to_expr(pattern: Pattern, span: Span) -> Expr {
3947    match pattern.kind {
3948        PatternKind::Ident(ident) => Expr::new(ExprKind::Ident(ident), span),
3949        PatternKind::Assign { target, default } => Expr::new(
3950            ExprKind::Assign {
3951                op: AssignOp::Assign,
3952                target,
3953                value: default,
3954            },
3955            span,
3956        ),
3957        PatternKind::Array { elements, rest } => {
3958            let mut out = Vec::new();
3959            for element in elements {
3960                match element {
3961                    Some(PatternElement::Pattern(pattern)) => {
3962                        let span = pattern.span;
3963                        out.push(Some(ArrayElement::Expr(Box::new(pattern_to_expr(
3964                            pattern, span,
3965                        )))));
3966                    }
3967                    Some(PatternElement::Property { .. }) | None => out.push(None),
3968                }
3969            }
3970            if let Some(rest) = rest {
3971                let RestElement::Pattern(pattern) = *rest else {
3972                    return Expr::new(ExprKind::Null, span);
3973                };
3974                let span = pattern.span;
3975                out.push(Some(ArrayElement::Spread(Box::new(pattern_to_expr(
3976                    pattern, span,
3977                )))));
3978            }
3979            Expr::new(ExprKind::Array { elements: out }, span)
3980        }
3981        _ => Expr::new(ExprKind::Null, span),
3982    }
3983}
3984
3985impl Pattern {
3986    /// Pattern kind, ignoring `Paren` wrappers (patterns never have any, but
3987    /// this keeps call sites uniform with [`Expr::unparen`]).
3988    fn unparen_kind(&self) -> &PatternKind {
3989        &self.kind
3990    }
3991}