Skip to main content

nodejs/
parser.rs

1//! JavaScript parser: token stream → AST.
2//!
3//! Recursive descent with precedence climbing for binary operators. Automatic
4//! Semicolon Insertion is applied at statement boundaries using the
5//! `newline_before` flag the lexer records on every token. Arrow functions are
6//! detected at assignment level by looking ahead for `=>` after a parameter
7//! list. Template-literal `${...}` fields are re-parsed here from the raw source
8//! the lexer captured.
9
10use crate::ast::*;
11use crate::lexer::{lex, Legacy, Tok, Token};
12
13const KEYWORDS: &[&str] = &[
14    "var",
15    "let",
16    "const",
17    "function",
18    "return",
19    "if",
20    "else",
21    "while",
22    "do",
23    "for",
24    "in",
25    "switch",
26    "case",
27    "default",
28    "break",
29    "continue",
30    "true",
31    "false",
32    "null",
33    "this",
34    "new",
35    "typeof",
36    "void",
37    "delete",
38    "instanceof",
39    "throw",
40    "try",
41    "catch",
42    "finally",
43];
44
45fn is_keyword(s: &str) -> bool {
46    KEYWORDS.contains(&s)
47}
48
49/// The private names one class body declares and the ones its code refers to.
50#[derive(Default)]
51struct PrivateScope {
52    declared: Vec<String>,
53    used: Vec<String>,
54}
55
56/// The names a binding pattern introduces.
57fn pattern_idents(e: &Expr, out: &mut Vec<String>) {
58    match e {
59        Expr::Ident(n) => out.push(n.clone()),
60        Expr::Array(items) => items.iter().for_each(|i| pattern_idents(i, out)),
61        Expr::Spread(inner) => pattern_idents(inner, out),
62        Expr::Assign { target, .. } => pattern_idents(target, out),
63        Expr::Object(props) => {
64            for pr in props {
65                match pr {
66                    Prop::KeyValue { value, .. } => pattern_idents(value, out),
67                    Prop::Spread(inner) => pattern_idents(inner, out),
68                    _ => {}
69                }
70            }
71        }
72        _ => {}
73    }
74}
75
76/// 15.4.1: a getter takes no parameters and a setter exactly one, which is not
77/// a rest parameter.
78fn check_accessor_arity(kind: MemberKind, params: &[Param]) -> Result<(), String> {
79    match kind {
80        MemberKind::Get if !params.is_empty() => {
81            Err("SyntaxError: Getter must not have any formal parameters.".to_string())
82        }
83        MemberKind::Set if params.len() != 1 => {
84            Err("SyntaxError: Setter must have exactly one formal parameter.".to_string())
85        }
86        MemberKind::Set if params[0].rest => {
87            Err("SyntaxError: Setter function argument must not be a rest parameter".to_string())
88        }
89        _ => Ok(()),
90    }
91}
92
93fn private_not_declared(name: &str) -> String {
94    format!("SyntaxError: Private field '{name}' must be declared in an enclosing class")
95}
96
97struct Parser {
98    toks: Vec<Token>,
99    pos: usize,
100    /// True while parsing a generator body — enables `yield` as an operator.
101    in_generator: bool,
102    /// True while parsing an async body — enables `await` as an operator.
103    in_async: bool,
104    /// True while parsing a `for` init in LHS position — suppresses `in` as a
105    /// relational operator so `for (x in obj)` (no declaration keyword) parses
106    /// the `in` as the loop separator, not a binary expression. Cleared inside
107    /// any parenthesised/bracketed sub-expression, where `in` is legal again.
108    no_in: bool,
109    /// One frame per enclosing class body, each holding the private names that
110    /// body DECLARES and the ones its code USES. A private name is only in
111    /// scope inside a class that declares it, so an undeclared use is an EARLY
112    /// error (`SyntaxError`) rather than a runtime `TypeError` if the read ever
113    /// happens — a typo in a dead branch used to ship silently.
114    class_scopes: Vec<PrivateScope>,
115    /// Whether token offsets point into the script text, so a function's
116    /// [`Span`] can be recorded. Off for a re-parsed template field.
117    spans: bool,
118    /// The labels of the statements enclosing the current one, innermost last,
119    /// reset at each function boundary: a label may not be declared twice in
120    /// one nest (14.13.1).
121    labels: Vec<String>,
122    /// Whether the code being parsed is strict (a `'use strict'` directive
123    /// prologue, or a class body). Decides the early errors that only strict
124    /// code has: legacy octal forms, `let`/`yield`/… as names, a function
125    /// declaration as an `if`/loop body.
126    strict: bool,
127    /// Whether `super` may appear here: a method, an accessor, a class field
128    /// initialiser or a static block, and an arrow inside one. An `eval`'s
129    /// source starts out true, since it may be running inside a method.
130    super_ok: bool,
131    /// Whether a `return` is legal here: inside a function body, or at the top
132    /// of a file (which Node wraps in one). An `eval`'s top level is not.
133    in_function: bool,
134    /// The `{ a = 1 }` shorthand initialisers seen in an expression: the `=`
135    /// token and the source span of `a = 1`. They are legal only if the object turns out to be a pattern
136    /// (an assignment target, a `for` head); anything left when the statement
137    /// ends is the `Invalid shorthand property initializer` early error.
138    cover_init: Vec<(usize, Pos, Pos)>,
139    /// Set while parsing a binding pattern, where `{ a = 1 }` is simply a
140    /// default and never a cover grammar. Cleared again inside a default
141    /// value or a computed key, which are expressions.
142    in_binding: bool,
143    /// The names a binding pattern being parsed binds, with where each is
144    /// written; drained by [`Parser::parse_binding_target_at`].
145    bound_at: Vec<(String, Pos)>,
146    /// Whether the source is parsed with the Module goal (16.2): strict,
147    /// top-level `await`, `import`/`export` declarations and `import.meta`.
148    module: bool,
149}
150
151/// Parse a complete JS program into a statement list. Inline `rust { ... }` FFI
152/// blocks are desugared to `__rust_compile(...)` calls before lexing.
153pub fn parse(src: &str) -> Result<Vec<Stmt>, String> {
154    parse_source(src, false, false, false)
155}
156
157/// Parse the source text of an `eval` / `vm` script. Identical to [`parse`]
158/// except that `super` is accepted at the top level when `allow_super` says the
159/// code runs inside a method (a direct `eval` there may use it).
160pub fn parse_eval(src: &str, allow_super: bool, caller_strict: bool) -> Result<Vec<Stmt>, String> {
161    parse_source(src, allow_super, true, caller_strict)
162}
163
164fn parse_source(
165    src: &str,
166    allow_super: bool,
167    in_eval: bool,
168    caller_strict: bool,
169) -> Result<Vec<Stmt>, String> {
170    note_error_span(0, 0);
171    let desugared = crate::rust_ffi::desugar(src);
172    // A `rust { … }` block is rewritten before lexing, so offsets would point
173    // into text the caller never sees; record spans only when nothing moved.
174    let spans = desugared == src;
175    let toks = lex_noting(&desugared, spans)?;
176    let mut p = Parser {
177        toks,
178        pos: 0,
179        in_generator: false,
180        in_async: false,
181        no_in: false,
182        class_scopes: Vec::new(),
183        labels: Vec::new(),
184        strict: false,
185        super_ok: allow_super,
186        in_function: !in_eval,
187        cover_init: Vec::new(),
188        in_binding: false,
189        bound_at: Vec::new(),
190        spans,
191        module: false,
192    };
193    p.strict = caller_strict || p.leading_use_strict(0);
194    let mut out = Vec::new();
195    while !p.at_eof() {
196        out.push(p.note_error_pos(Parser::parse_stmt)?);
197    }
198    Ok(out)
199}
200
201thread_local! {
202    /// Where the last parse that failed stopped — see [`take_error_pos`].
203    static ERROR_POS: std::cell::Cell<Pos> = const { std::cell::Cell::new(0) };
204    /// The end of the span it underlines — see [`take_error_end`].
205    static ERROR_END: std::cell::Cell<Pos> = const { std::cell::Cell::new(0) };
206}
207
208/// The [`Pos`] of the token the last failed [`parse`] / [`parse_module`]
209/// stopped at (`0`: none, or none since the last call), which is where V8 puts
210/// a SyntaxError's caret.
211pub fn take_error_pos() -> Pos {
212    ERROR_POS.with(|p| p.replace(0))
213}
214
215/// One past the last character V8 underlines for that SyntaxError — the end
216/// of the offending token (`0`: underline the one character at the position).
217/// Taken by `host::note_syntax_error` alongside [`take_error_pos`].
218pub fn take_error_end() -> Pos {
219    ERROR_END.with(|p| p.replace(0))
220}
221
222/// Record a SyntaxError found after parsing — an early error such as a
223/// redeclaration — at the source span `[pos, end)`, for [`take_error_pos`].
224pub fn note_error_span(pos: Pos, end: Pos) {
225    ERROR_POS.with(|p| p.set(pos));
226    ERROR_END.with(|p| p.set(end));
227}
228
229/// [`lex`], recording the span of the token an error stopped in when `spans`
230/// says positions refer to the caller's text.
231fn lex_noting(src: &str, spans: bool) -> Result<Vec<Token>, String> {
232    lex(src).inspect_err(|_| {
233        let (start, end) = crate::lexer::take_error_span();
234        if spans {
235            note_error_span(start + 1, end + 1);
236        }
237    })
238}
239
240/// Parse `src` with the Module goal (ECMA-262 16.2.1): the code is strict,
241/// `await` is an operator at the top level, `return` there is an error, and the
242/// top level may hold `import`/`export` declarations. A hashbang line is a
243/// comment only at the very start of the text.
244pub fn parse_module(src: &str) -> Result<Vec<Stmt>, String> {
245    note_error_span(0, 0);
246    let toks = lex_noting(src, true)?;
247    let mut p = Parser {
248        toks,
249        pos: 0,
250        in_generator: false,
251        in_async: true,
252        no_in: false,
253        class_scopes: Vec::new(),
254        labels: Vec::new(),
255        strict: true,
256        super_ok: false,
257        in_function: false,
258        cover_init: Vec::new(),
259        in_binding: false,
260        bound_at: Vec::new(),
261        spans: true,
262        module: true,
263    };
264    let mut out = Vec::new();
265    while !p.at_eof() {
266        let line = p.line();
267        let item = if p.is_kw("export") {
268            p.parse_export()?
269        } else if p.is_kw("import")
270            && !matches!(
271                p.toks.get(p.pos + 1).map(|t| &t.tok),
272                Some(Tok::Punct(s)) if s == "(" || s == "."
273            )
274        {
275            p.parse_import()?
276        } else {
277            out.push(p.note_error_pos(Parser::parse_stmt)?);
278            continue;
279        };
280        out.push(Stmt::new(item, line));
281    }
282    Ok(out)
283}
284
285impl Parser {
286    // ── token helpers ────────────────────────────────────────────────────
287    fn cur(&self) -> &Token {
288        &self.toks[self.pos]
289    }
290    /// Parse one `${…}` field of a template token, keeping its spans in this
291    /// script's coordinates. The field is part of the enclosing code, so it
292    /// parses in the same context: `await` and `yield` stay operators inside
293    /// an async or generator body, and a private name it uses is checked
294    /// against the enclosing class body like any other use. A field used to be
295    /// parsed as if at the top level, so `` `${await x}` `` was a
296    /// `ReferenceError` and `` `${this.#c}` `` a `SyntaxError`.
297    fn parse_field(&mut self, src: &str, at: u32) -> Result<Expr, String> {
298        // `${}`: the field is empty, so the first thing wrong is its `}`.
299        if src.trim().is_empty() {
300            return Err("SyntaxError: Unexpected token '}'".to_string());
301        }
302        let mut p = field_parser(src, self.spans.then_some(at))?;
303        p.in_generator = self.in_generator;
304        p.in_async = self.in_async;
305        p.strict = self.strict;
306        p.super_ok = self.super_ok;
307        p.in_function = self.in_function;
308        p.module = self.module;
309        if !self.class_scopes.is_empty() {
310            p.class_scopes.push(PrivateScope::default());
311        }
312        let e = p.parse_expr()?;
313        if let (Some(scope), Some(inner)) = (self.class_scopes.last_mut(), p.class_scopes.pop()) {
314            scope.used.extend(inner.used);
315        }
316        Ok(e)
317    }
318
319    /// The [`Pos`] of the current token: one past its byte offset, or `0`
320    /// when this parser's offsets do not index the caller's text.
321    fn pos_here(&self) -> Pos {
322        if self.spans {
323            self.toks[self.pos].start + 1
324        } else {
325            0
326        }
327    }
328
329    /// Run one parse step; when it fails, record the token it stopped at for
330    /// [`take_error_pos`].
331    fn note_error_pos<T>(
332        &mut self,
333        step: impl FnOnce(&mut Self) -> Result<T, String>,
334    ) -> Result<T, String> {
335        let r = step(self);
336        // An error that placed itself (`note_error_span`) keeps its place.
337        if r.is_err() && ERROR_POS.with(|p| p.get()) == 0 {
338            let end = if self.spans {
339                self.toks[self.pos].end + 1
340            } else {
341                0
342            };
343            note_error_span(self.pos_here(), end);
344        }
345        r
346    }
347
348    /// The [`Pos`] V8 gives a call whose `(` is the current token: the token
349    /// before it when that is a name (`f(`, `o.m(` — "for call of an identifier
350    /// we want to report position of the identifier", `ParseLeftHandSideContinuation`),
351    /// else the parenthesis itself (`o[k](`, `f()(`, `f?.(`).
352    fn call_pos(&self) -> Pos {
353        match self.pos.checked_sub(1).map(|i| &self.toks[i]) {
354            Some(t) if self.spans && matches!(t.tok, Tok::Ident(_)) => t.start + 1,
355            _ => self.pos_here(),
356        }
357    }
358
359    /// Byte offset where token `i` begins.
360    fn start_at(&self, i: usize) -> u32 {
361        self.toks[i].start
362    }
363    /// The source range from `start` to the end of the last consumed token.
364    fn span_from(&self, start: u32) -> Span {
365        if !self.spans || self.pos == 0 {
366            return (0, 0);
367        }
368        (start, self.toks[self.pos - 1].end)
369    }
370    fn tok(&self) -> &Tok {
371        &self.toks[self.pos].tok
372    }
373    fn line(&self) -> u32 {
374        self.toks[self.pos].line
375    }
376    fn at_eof(&self) -> bool {
377        matches!(self.tok(), Tok::Eof)
378    }
379    fn newline_before(&self) -> bool {
380        self.cur().newline_before
381    }
382    fn advance(&mut self) -> Tok {
383        let t = self.toks[self.pos].tok.clone();
384        if self.pos + 1 < self.toks.len() {
385            self.pos += 1;
386        }
387        t
388    }
389
390    /// True if the current token is the punctuation `s`.
391    fn is_punct(&self, s: &str) -> bool {
392        matches!(self.tok(), Tok::Punct(p) if p == s)
393    }
394    /// True if the current token is the identifier/keyword `s`.
395    fn is_kw(&self, s: &str) -> bool {
396        matches!(self.tok(), Tok::Ident(i) if i == s)
397    }
398    /// Consume the punctuation `s` if present.
399    fn eat_punct(&mut self, s: &str) -> bool {
400        if self.is_punct(s) {
401            self.advance();
402            true
403        } else {
404            false
405        }
406    }
407    fn eat_kw(&mut self, s: &str) -> bool {
408        if self.is_kw(s) {
409            self.advance();
410            true
411        } else {
412            false
413        }
414    }
415    /// V8's message for a token the grammar has no place for. Which wording
416    /// depends on the token's class — a reserved word and a punctuator are
417    /// `Unexpected token 'x'`, an identifier names itself, and a literal says
418    /// only what kind it is — so every "this token cannot go here" error site
419    /// shares one function rather than describing the token its own way.
420    fn unexpected(&self) -> String {
421        /// The ReservedWords (13.1.1) V8 reports as a bare token.
422        const RESERVED: &[&str] = &[
423            "break",
424            "case",
425            "catch",
426            "class",
427            "const",
428            "continue",
429            "debugger",
430            "default",
431            "delete",
432            "do",
433            "else",
434            "export",
435            "extends",
436            "false",
437            "finally",
438            "for",
439            "function",
440            "if",
441            "import",
442            "in",
443            "instanceof",
444            "new",
445            "null",
446            "return",
447            "super",
448            "switch",
449            "this",
450            "throw",
451            "true",
452            "try",
453            "typeof",
454            "var",
455            "void",
456            "while",
457            "with",
458        ];
459        // V8 explains a stray `await` operand by the missing `async`, not by
460        // the operand: `await 1` outside an async function reaches the `1`.
461        if self.pos > 0
462            && !self.in_async
463            && matches!(&self.toks[self.pos - 1].tok, Tok::Ident(s) if s == "await")
464            && !matches!(self.tok(), Tok::Punct(p) if p == ")" || p == ";" || p == ",")
465        {
466            return "SyntaxError: await is only valid in async functions and the top level bodies of modules".to_string();
467        }
468        let what = match self.tok() {
469            Tok::Eof => "Unexpected end of input".to_string(),
470            Tok::Num(_) | Tok::BigInt(_) => "Unexpected number".to_string(),
471            Tok::Str(_) => "Unexpected string".to_string(),
472            Tok::Template { .. } => "Unexpected template string".to_string(),
473            Tok::Regex(..) => "Unexpected regular expression".to_string(),
474            Tok::Ident(s) if s == "enum" => "Unexpected reserved word".to_string(),
475            Tok::Ident(s) if RESERVED.contains(&s.as_str()) => {
476                format!("Unexpected token '{s}'")
477            }
478            Tok::Ident(s) => format!("Unexpected identifier '{s}'"),
479            Tok::Punct(p) => format!("Unexpected token '{p}'"),
480        };
481        format!("SyntaxError: {what}")
482    }
483
484    /// The parameter-list early errors that depend on how the function is
485    /// written (15.2.1, 15.1.1): a repeated name is allowed only in sloppy code
486    /// with a plain list of simple names, and a `'use strict'` body needs a
487    /// simple list. `unique` is set for arrows, methods and accessors, which
488    /// never allow a repeat; `body_strict` for a body that begins with the
489    /// directive (strictness inherited from outside is `self.strict`).
490    fn check_params(
491        &self,
492        params: &[Param],
493        body_strict: bool,
494        unique: bool,
495    ) -> Result<(), String> {
496        let simple = params
497            .iter()
498            .all(|p| !p.rest && p.default.is_none() && matches!(p.pattern, Expr::Ident(_)));
499        if body_strict && !simple {
500            return Err(
501                "SyntaxError: Illegal 'use strict' directive in function with \
502                        non-simple parameter list"
503                    .to_string(),
504            );
505        }
506        let strict = self.strict || body_strict;
507        let mut names: Vec<String> = Vec::new();
508        for p in params {
509            pattern_idents(&p.pattern, &mut names);
510        }
511        if strict && names.iter().any(|n| n == "eval" || n == "arguments") {
512            return Err("SyntaxError: Unexpected eval or arguments in strict mode".to_string());
513        }
514        let repeats = names
515            .iter()
516            .enumerate()
517            .any(|(i, n)| names[..i].contains(n));
518        if repeats && (strict || unique || !simple) {
519            return Err(
520                "SyntaxError: Duplicate parameter name not allowed in this context".to_string(),
521            );
522        }
523        Ok(())
524    }
525
526    /// Whether the directive prologue starting at token `from` contains
527    /// `'use strict'` (14.1.1): the leading run of string-literal expression
528    /// statements, each ended by `;`, a newline or the end of the block.
529    fn leading_use_strict(&self, from: usize) -> bool {
530        let mut i = from;
531        while let Some(Token {
532            tok: Tok::Str(s), ..
533        }) = self.toks.get(i)
534        {
535            let ends = match self.toks.get(i + 1) {
536                Some(t) => {
537                    matches!(&t.tok, Tok::Punct(p) if p == ";" || p == "}")
538                        || t.newline_before
539                        || matches!(t.tok, Tok::Eof)
540                }
541                None => true,
542            };
543            if !ends {
544                return false;
545            }
546            if s == "use strict" {
547                return true;
548            }
549            i += 1;
550            if matches!(self.toks.get(i), Some(Token { tok: Tok::Punct(p), .. }) if p == ";") {
551                i += 1;
552            }
553        }
554        false
555    }
556
557    /// Run `f` with `super` allowed or not.
558    fn with_super<T>(&mut self, ok: bool, f: impl FnOnce(&mut Self) -> T) -> T {
559        let saved = std::mem::replace(&mut self.super_ok, ok);
560        let out = f(self);
561        self.super_ok = saved;
562        out
563    }
564
565    /// The strict-mode-only restriction the current token trips, if the code
566    /// is strict.
567    fn check_legacy(&self) -> Result<(), String> {
568        if !self.strict {
569            return Ok(());
570        }
571        let msg = match self.cur().legacy {
572            Legacy::None => return Ok(()),
573            Legacy::OctalLiteral => "Octal literals are not allowed in strict mode.",
574            Legacy::LeadingZeroDecimal => {
575                "Decimals with leading zeros are not allowed in strict mode."
576            }
577            Legacy::OctalEscape => "Octal escape sequences are not allowed in strict mode.",
578            Legacy::NonOctalEscape => "\\8 and \\9 are not allowed in strict mode.",
579        };
580        Err(format!("SyntaxError: {msg}"))
581    }
582
583    fn expect_punct(&mut self, s: &str) -> Result<(), String> {
584        if self.eat_punct(s) {
585            Ok(())
586        } else {
587            Err(self.unexpected())
588        }
589    }
590
591    /// Consume an identifier name (any non-punct ident, including keywords used
592    /// as property names when `allow_kw`).
593    fn ident_name(&mut self) -> Result<String, String> {
594        match self.tok().clone() {
595            Tok::Ident(s) => {
596                self.advance();
597                Ok(s)
598            }
599            _ => Err(self.unexpected()),
600        }
601    }
602
603    /// Apply ASI: consume an explicit `;`, or accept a newline / `}` / EOF.
604    fn semicolon(&mut self) -> Result<(), String> {
605        if self.eat_punct(";") {
606            return Ok(());
607        }
608        if self.newline_before() || self.is_punct("}") || self.at_eof() {
609            return Ok(());
610        }
611        Err(self.unexpected())
612    }
613
614    // ── statements ───────────────────────────────────────────────────────
615    fn parse_stmt(&mut self) -> Result<Stmt, String> {
616        let stmt = self.parse_stmt_inner()?;
617        // Whatever `{ a = 1 }` is still unclaimed by a pattern is an error
618        // (13.2.5.1), reported where V8 reports it: under `a = 1`.
619        if let Some(&(_, pos, end)) = self.cover_init.first() {
620            note_error_span(pos, end);
621            return Err("SyntaxError: Invalid shorthand property initializer".to_string());
622        }
623        Ok(stmt)
624    }
625
626    fn parse_stmt_inner(&mut self) -> Result<Stmt, String> {
627        let line = self.line();
628        let pos = self.pos_here();
629        let kind = match self.tok().clone() {
630            Tok::Punct(p) if p == "{" => {
631                self.advance();
632                StmtKind::Block(self.parse_block_body()?)
633            }
634            Tok::Punct(p) if p == ";" => {
635                self.advance();
636                StmtKind::Empty
637            }
638            // A script has no `export`, and `import` is only the call form
639            // `import(…)` and the meta property `import.meta`.
640            Tok::Ident(kw) if kw == "export" => return Err(self.unexpected()),
641            Tok::Ident(kw)
642                if kw == "import"
643                    && !matches!(
644                        self.toks.get(self.pos + 1).map(|t| &t.tok),
645                        Some(Tok::Punct(p)) if p == "(" || p == "."
646                    ) =>
647            {
648                return Err("SyntaxError: Cannot use import statement outside a module".to_string());
649            }
650            Tok::Ident(kw) if kw == "var" || kw == "let" || kw == "const" => {
651                let k = self.parse_decl_kind();
652                let decls = self.parse_declarators()?;
653                self.check_declarators(&k, &decls)?;
654                self.semicolon()?;
655                StmtKind::Decl { kind: k, decls }
656            }
657            Tok::Ident(kw) if kw == "function" => self.parse_func_decl(false)?,
658            // `async function …` (declaration). `async` stays a plain identifier
659            // anywhere else (contextual keyword).
660            Tok::Ident(kw)
661                if kw == "async" && self.peek_kw(1, "function") && !self.peek_newline(1) =>
662            {
663                self.advance(); // async
664                self.parse_func_decl(true)?
665            }
666            Tok::Ident(kw) if kw == "class" => {
667                // A class DECLARATION needs a binding name (15.7.1).
668                if matches!(
669                    self.toks.get(self.pos + 1).map(|t| &t.tok),
670                    Some(Tok::Punct(p)) if p == "{"
671                ) || self.peek_kw(1, "extends")
672                {
673                    self.advance();
674                    return Err(self.unexpected());
675                }
676                let node = self.parse_class(true)?;
677                StmtKind::ClassDecl(node)
678            }
679            Tok::Ident(kw) if kw == "if" => self.parse_if()?,
680            Tok::Ident(kw) if kw == "while" => self.parse_while()?,
681            Tok::Ident(kw) if kw == "with" => self.parse_with()?,
682            Tok::Ident(kw) if kw == "do" => self.parse_do_while()?,
683            Tok::Ident(kw) if kw == "for" => self.parse_for()?,
684            Tok::Ident(kw) if kw == "switch" => self.parse_switch()?,
685            Tok::Ident(kw) if kw == "return" => {
686                if !self.in_function {
687                    return Err("SyntaxError: Illegal return statement".to_string());
688                }
689                self.advance();
690                let arg = if self.is_punct(";")
691                    || self.is_punct("}")
692                    || self.newline_before()
693                    || self.at_eof()
694                {
695                    None
696                } else {
697                    Some(self.parse_expr()?)
698                };
699                self.semicolon()?;
700                StmtKind::Return(arg)
701            }
702            Tok::Ident(kw) if kw == "break" => {
703                self.advance();
704                let label = self.opt_label();
705                self.semicolon()?;
706                StmtKind::Break(label)
707            }
708            Tok::Ident(kw) if kw == "continue" => {
709                self.advance();
710                let label = self.opt_label();
711                self.semicolon()?;
712                StmtKind::Continue(label)
713            }
714            Tok::Ident(kw) if kw == "throw" => {
715                self.advance();
716                // 14.14: no LineTerminator between `throw` and its operand.
717                if self.newline_before() {
718                    return Err("SyntaxError: Illegal newline after throw".to_string());
719                }
720                let e = self.parse_expr()?;
721                self.semicolon()?;
722                StmtKind::Throw(e)
723            }
724            Tok::Ident(kw) if kw == "try" => self.parse_try()?,
725            // `label: stmt` — a bare identifier immediately followed by `:` at
726            // statement position is a label (never an expression; the reserved
727            // control keywords are all matched above, and switch `case`/`default`
728            // labels are parsed inside `parse_switch`).
729            Tok::Ident(name) if matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":") =>
730            {
731                if self.labels.contains(&name) {
732                    return Err(format!(
733                        "SyntaxError: Label '{name}' has already been declared"
734                    ));
735                }
736                self.advance(); // the label identifier
737                self.advance(); // the ':'
738                self.labels.push(name.clone());
739                // 14.13.1 / B.3.2: a labelled FunctionDeclaration is sloppy-only.
740                let body = if self.strict
741                    && (self.is_kw("function")
742                        || self.is_kw("async") && self.peek_kw(1, "function"))
743                {
744                    Err("SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.".to_string())
745                } else {
746                    self.parse_stmt()
747                };
748                self.labels.pop();
749                StmtKind::Labeled {
750                    label: name,
751                    body: Box::new(body?),
752                }
753            }
754            _ => {
755                let e = self.parse_expr()?;
756                self.semicolon()?;
757                StmtKind::Expr(e)
758            }
759        };
760        Ok(Stmt::at(kind, line, pos))
761    }
762
763    /// Whether the token `n` ahead is the punctuator `p`.
764    fn peek_punct_at(&self, n: usize, p: &str) -> bool {
765        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Punct(s)) if s == p)
766    }
767    /// Whether the token `n` ahead is the identifier `kw`.
768    fn peek_kw(&self, n: usize, kw: &str) -> bool {
769        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Ident(s)) if s == kw)
770    }
771    /// Whether the token `n` ahead has a newline before it.
772    fn peek_newline(&self, n: usize) -> bool {
773        self.toks
774            .get(self.pos + n)
775            .map(|t| t.newline_before)
776            .unwrap_or(false)
777    }
778
779    // ── module declarations (16.2.2, 16.2.3) ─────────────────────────────
780    /// A ModuleExportName: an IdentifierName, or a string literal (`"a b"`).
781    fn module_export_name(&mut self) -> Result<String, String> {
782        match self.tok().clone() {
783            Tok::Str(s) => {
784                self.advance();
785                Ok(s)
786            }
787            Tok::Ident(_) => self.ident_name(),
788            _ => Err(self.unexpected()),
789        }
790    }
791
792    /// A binding identifier an import introduces: never a reserved word.
793    fn import_binding(&mut self) -> Result<String, String> {
794        if matches!(self.tok(), Tok::Ident(s) if is_keyword(s) || s == "import" || s == "export") {
795            return Err(self.unexpected());
796        }
797        let name = self.ident_name()?;
798        self.check_binding_name(&name)?;
799        if name == "eval" || name == "arguments" {
800            return Err("SyntaxError: Unexpected eval or arguments in strict mode".to_string());
801        }
802        Ok(name)
803    }
804
805    /// The module specifier string after `from` (or after a bare `import`).
806    fn module_specifier(&mut self) -> Result<String, String> {
807        match self.tok().clone() {
808            Tok::Str(s) => {
809                self.advance();
810                Ok(s)
811            }
812            _ => Err(self.unexpected()),
813        }
814    }
815
816    /// An optional `with { key: "value", … }` import-attributes clause (the
817    /// older `assert` spelling is accepted the same way).
818    fn import_attributes(&mut self) -> Result<Vec<(String, String)>, String> {
819        let mut out = Vec::new();
820        if !(self.is_kw("with") || self.is_kw("assert") && !self.newline_before()) {
821            return Ok(out);
822        }
823        self.advance();
824        self.expect_punct("{")?;
825        while !self.is_punct("}") {
826            let key = self.module_export_name()?;
827            self.expect_punct(":")?;
828            let value = self.module_specifier()?;
829            if out.iter().any(|(k, _)| *k == key) {
830                return Err(format!(
831                    "SyntaxError: Import attribute has duplicate key '{key}'"
832                ));
833            }
834            out.push((key, value));
835            if !self.eat_punct(",") {
836                break;
837            }
838        }
839        self.expect_punct("}")?;
840        Ok(out)
841    }
842
843    /// `import …;` at the top level of a module (the `import` keyword is current).
844    fn parse_import(&mut self) -> Result<StmtKind, String> {
845        self.advance(); // import
846        let mut specs = Vec::new();
847        let mut clause: Span = (0, 0);
848        // `import "m";` — no bindings, the module is evaluated for effect.
849        if !matches!(self.tok(), Tok::Str(_)) {
850            if !self.is_punct("{") && !self.is_punct("*") {
851                specs.push(ImportSpec::Default(self.import_binding()?));
852                if !self.eat_punct(",") {
853                    return self.finish_import(specs, clause);
854                }
855            }
856            if self.eat_punct("*") {
857                if !self.eat_kw("as") {
858                    return Err(self.unexpected());
859                }
860                specs.push(ImportSpec::Namespace(self.import_binding()?));
861            } else if self.is_punct("{") {
862                let start = self.start_at(self.pos);
863                self.advance();
864                while !self.is_punct("}") {
865                    let string_name = matches!(self.tok(), Tok::Str(_));
866                    let imported = self.module_export_name()?;
867                    let local = if self.eat_kw("as") {
868                        self.import_binding()?
869                    } else if string_name || is_keyword(&imported) {
870                        // `import { "a b" }` / `import { default }` have no
871                        // binding name of their own.
872                        return Err("SyntaxError: Unexpected reserved word".to_string());
873                    } else {
874                        self.check_binding_name(&imported)?;
875                        imported.clone()
876                    };
877                    specs.push(ImportSpec::Named { imported, local });
878                    if !self.eat_punct(",") {
879                        break;
880                    }
881                }
882                self.expect_punct("}")?;
883                clause = self.span_from(start);
884            } else {
885                return Err(self.unexpected());
886            }
887        }
888        self.finish_import(specs, clause)
889    }
890
891    /// `from "m" [with {…}];` closing an import declaration with `specs`.
892    fn finish_import(&mut self, specs: Vec<ImportSpec>, clause: Span) -> Result<StmtKind, String> {
893        if !specs.is_empty() && !self.eat_kw("from") {
894            return Err(self.unexpected());
895        }
896        let specifier = self.module_specifier()?;
897        let attributes = self.import_attributes()?;
898        self.semicolon()?;
899        Ok(StmtKind::Import(ImportDecl {
900            specifier,
901            specs,
902            attributes,
903            clause,
904        }))
905    }
906
907    /// `export …` at the top level of a module (the `export` keyword is current).
908    fn parse_export(&mut self) -> Result<StmtKind, String> {
909        self.advance(); // export
910        let line = self.line();
911        if self.eat_punct("*") {
912            let alias = if self.eat_kw("as") {
913                Some(self.module_export_name()?)
914            } else {
915                None
916            };
917            if !self.eat_kw("from") {
918                return Err(self.unexpected());
919            }
920            let from = self.module_specifier()?;
921            let attributes = self.import_attributes()?;
922            self.semicolon()?;
923            return Ok(StmtKind::Export(ExportDecl::Star {
924                alias,
925                from,
926                attributes,
927            }));
928        }
929        if self.eat_punct("{") {
930            let mut specs = Vec::new();
931            let mut string_locals = false;
932            while !self.is_punct("}") {
933                string_locals |= matches!(self.tok(), Tok::Str(_));
934                let local = self.module_export_name()?;
935                let exported = if self.eat_kw("as") {
936                    self.module_export_name()?
937                } else {
938                    local.clone()
939                };
940                specs.push(ExportSpec { local, exported });
941                if !self.eat_punct(",") {
942                    break;
943                }
944            }
945            self.expect_punct("}")?;
946            let from = if self.eat_kw("from") {
947                Some(self.module_specifier()?)
948            } else {
949                None
950            };
951            // Without `from`, each local must be a binding of this module, which
952            // a string literal or a reserved word can never be.
953            if from.is_none() {
954                if string_locals {
955                    return Err("SyntaxError: Unexpected string".to_string());
956                }
957                if let Some(s) = specs.iter().find(|s| is_keyword(&s.local)) {
958                    return Err(format!("SyntaxError: Unexpected token '{}'", s.local));
959                }
960            }
961            let attributes = if from.is_some() {
962                self.import_attributes()?
963            } else {
964                Vec::new()
965            };
966            self.semicolon()?;
967            return Ok(StmtKind::Export(ExportDecl::Named {
968                specs,
969                from,
970                attributes,
971            }));
972        }
973        if self.eat_kw("default") {
974            let is_fn = self.is_kw("function")
975                || self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
976            if is_fn {
977                let is_async = self.eat_kw("async");
978                let Expr::Function {
979                    params,
980                    body: FnBody::Block(body),
981                    name,
982                    is_generator,
983                    is_async,
984                    span,
985                    ..
986                } = self.parse_function_expr(is_async)?
987                else {
988                    return Err(self.unexpected());
989                };
990                let decl = StmtKind::FuncDecl {
991                    name: name.unwrap_or_else(|| "default".to_string()),
992                    params,
993                    body,
994                    is_generator,
995                    is_async,
996                    span,
997                };
998                return Ok(StmtKind::Export(ExportDecl::DefaultDecl(Box::new(
999                    Stmt::new(decl, line),
1000                ))));
1001            }
1002            if self.is_kw("class") {
1003                let mut node = self.parse_class(true)?;
1004                node.name.get_or_insert_with(|| "default".to_string());
1005                return Ok(StmtKind::Export(ExportDecl::DefaultDecl(Box::new(
1006                    Stmt::new(StmtKind::ClassDecl(node), line),
1007                ))));
1008            }
1009            let e = self.allow_in(|p| p.parse_assign())?;
1010            self.semicolon()?;
1011            return Ok(StmtKind::Export(ExportDecl::DefaultExpr(e)));
1012        }
1013        // `export` + a declaration: var/let/const, function, async function, class.
1014        let is_decl = self.is_kw("var")
1015            || self.is_kw("let")
1016            || self.is_kw("const")
1017            || self.is_kw("function")
1018            || self.is_kw("class")
1019            || self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
1020        if !is_decl {
1021            return Err(self.unexpected());
1022        }
1023        let decl = self.parse_stmt()?;
1024        Ok(StmtKind::Export(ExportDecl::Decl(Box::new(decl))))
1025    }
1026
1027    /// Parse a `function` declaration (the `function`/`async function` keyword is
1028    /// current). `is_async` is true when a preceding `async` was consumed.
1029    fn parse_func_decl(&mut self, is_async: bool) -> Result<StmtKind, String> {
1030        // `async` was consumed by the caller and is part of the source text.
1031        let start = self.start_at(if is_async { self.pos - 1 } else { self.pos });
1032        self.advance(); // function
1033        let is_generator = self.eat_punct("*");
1034        if self.is_punct("(") {
1035            return Err("SyntaxError: Function statements require a function name".to_string());
1036        }
1037        let name = self.ident_name()?;
1038        let params = self.parse_params()?;
1039        self.check_params(&params, self.leading_use_strict(self.pos + 1), false)?;
1040        self.expect_punct("{")?;
1041        let body = self.with_super(false, |p| p.parse_fn_body_block(is_generator, is_async))?;
1042        Ok(StmtKind::FuncDecl {
1043            name,
1044            params,
1045            body,
1046            is_generator,
1047            is_async,
1048            span: self.span_from(start),
1049        })
1050    }
1051
1052    /// Parse a brace-delimited function body under the given generator/async
1053    /// context (so `yield`/`await` inside are operators, not identifiers).
1054    fn parse_fn_body_block(
1055        &mut self,
1056        is_generator: bool,
1057        is_async: bool,
1058    ) -> Result<Vec<Stmt>, String> {
1059        self.parse_body_block(is_generator, is_async, true)
1060    }
1061
1062    /// [`Self::parse_fn_body_block`] with `return` admitted or not: a class
1063    /// static block is a body in every other respect but may not `return`.
1064    fn parse_body_block(
1065        &mut self,
1066        is_generator: bool,
1067        is_async: bool,
1068        returns: bool,
1069    ) -> Result<Vec<Stmt>, String> {
1070        let (pg, pa) = (self.in_generator, self.in_async);
1071        self.in_generator = is_generator;
1072        self.in_async = is_async;
1073        let outer_labels = std::mem::take(&mut self.labels);
1074        let outer_strict = self.strict;
1075        let outer_in_function = std::mem::replace(&mut self.in_function, returns);
1076        self.strict = outer_strict || self.leading_use_strict(self.pos);
1077        let body = self.parse_block_body();
1078        self.in_function = outer_in_function;
1079        self.strict = outer_strict;
1080        self.labels = outer_labels;
1081        self.in_generator = pg;
1082        self.in_async = pa;
1083        body
1084    }
1085
1086    /// Parse a function *expression* (`function`/`async function`, keyword
1087    /// current). Supports `function*` generators.
1088    fn parse_function_expr(&mut self, is_async: bool) -> Result<Expr, String> {
1089        let start = self.start_at(if is_async { self.pos - 1 } else { self.pos });
1090        self.advance(); // function
1091        let is_generator = self.eat_punct("*");
1092        let name = if let Tok::Ident(n) = self.tok() {
1093            if !is_keyword(n) {
1094                let n = n.clone();
1095                self.advance();
1096                Some(n)
1097            } else {
1098                None
1099            }
1100        } else {
1101            None
1102        };
1103        let params = self.parse_params()?;
1104        self.check_params(&params, self.leading_use_strict(self.pos + 1), false)?;
1105        self.expect_punct("{")?;
1106        let body = self.with_super(false, |p| p.parse_fn_body_block(is_generator, is_async))?;
1107        Ok(Expr::Function {
1108            params,
1109            body: FnBody::Block(body),
1110            is_arrow: false,
1111            name,
1112            is_generator,
1113            is_async,
1114            is_method: false,
1115            span: self.span_from(start),
1116        })
1117    }
1118
1119    /// Parse a `class` (the `class` keyword is current). `_decl` distinguishes a
1120    /// declaration (name required in strict mode, but we accept optional) from an
1121    /// expression.
1122    /// 15.7.1: a private name must be declared by an enclosing class body.
1123    /// Outside one, `this.#x` is a SyntaxError at parse time — it used to parse
1124    /// and then throw a `TypeError` only if the read ever ran, so a typo in a
1125    /// dead branch shipped silently.
1126    fn check_private_in_scope(&mut self, property: &str) -> Result<(), String> {
1127        if !property.starts_with('#') {
1128            return Ok(());
1129        }
1130        match self.class_scopes.last_mut() {
1131            // Recorded, not resolved: the declaration may still be ahead of the
1132            // use in the same body, so the check runs when the body closes.
1133            Some(scope) => scope.used.push(property.to_string()),
1134            None => return Err(private_not_declared(property)),
1135        }
1136        Ok(())
1137    }
1138
1139    fn parse_class(&mut self, _decl: bool) -> Result<ClassNode, String> {
1140        self.class_scopes.push(PrivateScope::default());
1141        let out = self.parse_class_inner();
1142        let scope = self.class_scopes.pop().unwrap_or_default();
1143        let out = out?;
1144        for name in &scope.used {
1145            if scope.declared.contains(name) {
1146                continue;
1147            }
1148            // A nested class may reference a name an OUTER class declares, so an
1149            // unresolved use is handed outwards rather than rejected here.
1150            match self.class_scopes.last_mut() {
1151                Some(outer) => outer.used.push(name.clone()),
1152                None => return Err(private_not_declared(name)),
1153            }
1154        }
1155        Ok(out)
1156    }
1157
1158    fn parse_class_inner(&mut self) -> Result<ClassNode, String> {
1159        let start = self.start_at(self.pos);
1160        self.advance(); // class
1161        let name = if let Tok::Ident(n) = self.tok() {
1162            if !is_keyword(n) && n != "extends" {
1163                let n = n.clone();
1164                self.advance();
1165                Some(n)
1166            } else {
1167                None
1168            }
1169        } else {
1170            None
1171        };
1172        let parent = if self.eat_kw("extends") {
1173            // The superclass is a left-hand-side expression (`extends Base`,
1174            // `extends foo.Bar`).
1175            Some(Box::new(self.parse_call_member()?))
1176        } else {
1177            None
1178        };
1179        self.expect_punct("{")?;
1180        // 11.2.2: every part of a class is strict code.
1181        let outer_strict = std::mem::replace(&mut self.strict, true);
1182        let mut members = Vec::new();
1183        while !self.is_punct("}") && !self.at_eof() {
1184            if self.eat_punct(";") {
1185                continue; // stray semicolons between members
1186            }
1187            let member = self.with_super(true, |p| p.parse_class_member());
1188            let member = match member {
1189                Ok(m) => m,
1190                Err(e) => {
1191                    self.strict = outer_strict;
1192                    return Err(e);
1193                }
1194            };
1195            if member.kind == MemberKind::Constructor
1196                && members
1197                    .iter()
1198                    .any(|m: &ClassMember| m.kind == MemberKind::Constructor)
1199            {
1200                return Err("SyntaxError: A class may only have one constructor".to_string());
1201            }
1202            if let Expr::Str(k) = &member.key {
1203                if k.starts_with('#') {
1204                    // A name is declared once — except a getter and a setter of
1205                    // the same staticness, which together are one accessor.
1206                    let pair = |a: &MemberKind, b: &MemberKind| {
1207                        matches!(
1208                            (a, b),
1209                            (MemberKind::Get, MemberKind::Set) | (MemberKind::Set, MemberKind::Get)
1210                        )
1211                    };
1212                    let clash = members.iter().any(|m: &ClassMember| {
1213                        matches!(&m.key, Expr::Str(n) if n == k)
1214                            && !(pair(&m.kind, &member.kind) && m.is_static == member.is_static)
1215                    });
1216                    if clash {
1217                        return Err(format!(
1218                            "SyntaxError: Identifier '{k}' has already been declared"
1219                        ));
1220                    }
1221                    if let Some(scope) = self.class_scopes.last_mut() {
1222                        scope.declared.push(k.clone());
1223                    }
1224                }
1225            }
1226            members.push(member);
1227        }
1228        self.strict = outer_strict;
1229        self.expect_punct("}")?;
1230        Ok(ClassNode {
1231            name,
1232            parent,
1233            members,
1234            span: self.span_from(start),
1235        })
1236    }
1237
1238    /// Parse one class member: `[static] [get|set|async|*] name(params){…}` or a
1239    /// `[static] name [= init];` field.
1240    fn parse_class_member(&mut self) -> Result<ClassMember, String> {
1241        let is_static = self.is_kw("static") && !self.peek_is_member_punct(1) && {
1242            self.advance();
1243            true
1244        };
1245        let start = self.start_at(self.pos);
1246        // `static { … }` — a class static initialization block (ES2022). A brace
1247        // where a member key would be is unambiguous: no member name can start
1248        // with `{`, so this is checked before the key parse (which otherwise
1249        // rejects it as `bad member key Punct("{")`).
1250        if is_static && self.is_punct("{") {
1251            self.advance();
1252            // Its own function context: `yield`/`await` are plain identifiers
1253            // inside a static block, whatever encloses the class.
1254            let body = self.parse_body_block(false, false, false)?;
1255            return Ok(ClassMember {
1256                key: Expr::Str(String::new()),
1257                computed: false,
1258                kind: MemberKind::StaticBlock,
1259                is_static: true,
1260                is_generator: false,
1261                is_async: false,
1262                params: Vec::new(),
1263                body,
1264                field_init: None,
1265                span: self.span_from(start),
1266            });
1267        }
1268        // Accessor / async / generator prefixes (each contextual: only a prefix
1269        // when followed by another member name, not itself the member name).
1270        let mut kind = MemberKind::Method;
1271        let mut is_async = false;
1272        let mut is_generator = false;
1273        if self.is_kw("get") && !self.peek_is_member_punct(1) {
1274            self.advance();
1275            kind = MemberKind::Get;
1276        } else if self.is_kw("set") && !self.peek_is_member_punct(1) {
1277            self.advance();
1278            kind = MemberKind::Set;
1279        } else {
1280            if self.is_kw("async") && !self.peek_is_member_punct(1) && !self.peek_newline(1) {
1281                self.advance();
1282                is_async = true;
1283            }
1284            if self.eat_punct("*") {
1285                is_generator = true;
1286            }
1287        }
1288        // The member key (computed `[expr]`, string, number, or identifier).
1289        let (key, computed) = self.parse_property_key()?;
1290        // A field (no parentheses) vs a method.
1291        if kind == MemberKind::Method && !self.is_punct("(") {
1292            let field_init = if self.eat_punct("=") {
1293                Some(self.parse_assign()?)
1294            } else {
1295                None
1296            };
1297            self.semicolon()?;
1298            return Ok(ClassMember {
1299                key,
1300                computed,
1301                kind: MemberKind::Field,
1302                is_static,
1303                is_generator: false,
1304                is_async: false,
1305                params: Vec::new(),
1306                body: Vec::new(),
1307                field_init,
1308                span: (0, 0),
1309            });
1310        }
1311        // A method / accessor / constructor.
1312        let is_ctor = !is_static
1313            && !computed
1314            && matches!(&key, Expr::Str(s) if s == "constructor")
1315            && kind == MemberKind::Method;
1316        let params = self.parse_params()?;
1317        check_accessor_arity(kind, &params)?;
1318        self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
1319        self.expect_punct("{")?;
1320        let body = self.parse_fn_body_block(is_generator, is_async)?;
1321        Ok(ClassMember {
1322            key,
1323            computed,
1324            kind: if is_ctor {
1325                MemberKind::Constructor
1326            } else {
1327                kind
1328            },
1329            is_static,
1330            is_generator,
1331            is_async,
1332            params,
1333            body,
1334            field_init: None,
1335            span: self.span_from(start),
1336        })
1337    }
1338
1339    /// Whether the token `n` ahead is `(`, `=`, `;`, `}`, or a newline-boundary —
1340    /// i.e. the current word is itself the member name, not a modifier prefix.
1341    fn peek_is_member_punct(&self, n: usize) -> bool {
1342        matches!(
1343            self.toks.get(self.pos + n).map(|t| &t.tok),
1344            Some(Tok::Punct(p)) if p == "(" || p == "=" || p == ";" || p == "}"
1345        )
1346    }
1347
1348    /// Parse a property key for a class member / object method: `[expr]` (computed),
1349    /// a string, a number, or an identifier (returned as an `Expr::Str`).
1350    fn parse_property_key(&mut self) -> Result<(Expr, bool), String> {
1351        if self.is_punct("[") {
1352            self.advance();
1353            let k = self.outside_binding(Self::parse_assign)?;
1354            self.expect_punct("]")?;
1355            Ok((k, true))
1356        } else {
1357            match self.tok().clone() {
1358                Tok::Str(s) => {
1359                    self.advance();
1360                    Ok((Expr::Str(s), false))
1361                }
1362                Tok::Num(n) => {
1363                    self.advance();
1364                    Ok((Expr::Str(crate::host::fmt_number(n)), false))
1365                }
1366                Tok::Ident(s) => {
1367                    self.advance();
1368                    Ok((Expr::Str(s), false))
1369                }
1370                _ => Err(self.unexpected()),
1371            }
1372        }
1373    }
1374
1375    /// An optional non-newline label after break/continue.
1376    fn opt_label(&mut self) -> Option<String> {
1377        if self.newline_before() {
1378            return None;
1379        }
1380        if let Tok::Ident(s) = self.tok() {
1381            if !is_keyword(s) {
1382                let s = s.clone();
1383                self.advance();
1384                return Some(s);
1385            }
1386        }
1387        None
1388    }
1389
1390    /// Parse statements up to (and consuming) the closing `}`.
1391    fn parse_block_body(&mut self) -> Result<Vec<Stmt>, String> {
1392        let mut out = Vec::new();
1393        while !self.is_punct("}") && !self.at_eof() {
1394            out.push(self.parse_stmt()?);
1395        }
1396        self.expect_punct("}")?;
1397        Ok(out)
1398    }
1399
1400    /// Early errors of a `var`/`let`/`const` statement's declarator list: a
1401    /// `const` or a destructuring pattern needs an initialiser, `let` may not
1402    /// be a lexically bound name, and `enum` is never a binding.
1403    fn check_declarators(&self, kind: &DeclKind, decls: &[Declarator]) -> Result<(), String> {
1404        for d in decls {
1405            if d.init.is_none() {
1406                if !matches!(d.target, Expr::Ident(_)) {
1407                    return Err(
1408                        "SyntaxError: Missing initializer in destructuring declaration".to_string(),
1409                    );
1410                }
1411                if matches!(kind, DeclKind::Const) {
1412                    return Err("SyntaxError: Missing initializer in const declaration".to_string());
1413                }
1414            }
1415            if !matches!(kind, DeclKind::Var) {
1416                if let Expr::Ident(n) = &d.target {
1417                    if n == "let" {
1418                        return Err(
1419                            "SyntaxError: let is disallowed as a lexically bound name".to_string()
1420                        );
1421                    }
1422                }
1423            }
1424        }
1425        Ok(())
1426    }
1427
1428    /// A statement in a single-statement position — the body of a loop or the
1429    /// arm of an `if`. Declarations are not statements there (14.6, 14.7);
1430    /// V8 words the refusal by what the declaration was and by strictness.
1431    /// Sloppy code keeps B.3.3's one allowance: a plain function declaration
1432    /// as an `if` arm.
1433    fn parse_sub_stmt(&mut self, is_if_arm: bool) -> Result<Stmt, String> {
1434        let is_async_fn =
1435            self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
1436        if self.is_kw("function") || is_async_fn {
1437            let generator = self.peek_punct_after_function();
1438            if is_async_fn {
1439                return Err("SyntaxError: Async functions can only be declared at the top level or inside a block.".to_string());
1440            }
1441            if generator {
1442                return Err("SyntaxError: Generators can only be declared at the top level or inside a block.".to_string());
1443            }
1444            if self.strict {
1445                return Err("SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.".to_string());
1446            }
1447            if !is_if_arm {
1448                return Err("SyntaxError: In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.".to_string());
1449            }
1450        }
1451        if self.is_kw("class") {
1452            return Err(self.unexpected());
1453        }
1454        if self.is_kw("const") {
1455            return Err(self.unexpected());
1456        }
1457        if self.is_kw("let")
1458            && matches!(
1459                self.toks.get(self.pos + 1).map(|t| &t.tok),
1460                Some(Tok::Punct(p)) if p == "[" || p == "{"
1461            )
1462        {
1463            return Err(
1464                "SyntaxError: Lexical declaration cannot appear in a single-statement context"
1465                    .to_string(),
1466            );
1467        }
1468        self.parse_stmt()
1469    }
1470
1471    /// Whether the `function` keyword at the cursor is `function*`.
1472    fn peek_punct_after_function(&self) -> bool {
1473        let at = if self.is_kw("async") { 2 } else { 1 };
1474        matches!(self.toks.get(self.pos + at).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "*")
1475    }
1476
1477    fn parse_decl_kind(&mut self) -> DeclKind {
1478        let k = match self.tok() {
1479            Tok::Ident(s) if s == "let" => DeclKind::Let,
1480            Tok::Ident(s) if s == "const" => DeclKind::Const,
1481            _ => DeclKind::Var,
1482        };
1483        self.advance();
1484        k
1485    }
1486
1487    fn parse_declarators(&mut self) -> Result<Vec<Declarator>, String> {
1488        let mut decls = Vec::new();
1489        loop {
1490            let (target, bound) = self.parse_binding_target_at()?;
1491            let init = if self.eat_punct("=") {
1492                Some(self.parse_assign()?)
1493            } else {
1494                None
1495            };
1496            decls.push(Declarator {
1497                target,
1498                init,
1499                bound,
1500            });
1501            if !self.eat_punct(",") {
1502                break;
1503            }
1504        }
1505        Ok(decls)
1506    }
1507
1508    /// A binding target: identifier or array/object destructuring pattern.
1509    fn parse_binding_target(&mut self) -> Result<Expr, String> {
1510        self.parse_binding_target_at().map(|(target, _)| target)
1511    }
1512
1513    /// [`Parser::parse_binding_target`], with where each name it binds is
1514    /// written (empty without source spans).
1515    fn parse_binding_target_at(&mut self) -> Result<(Expr, Vec<(String, Pos)>), String> {
1516        let mark = self.bound_at.len();
1517        let pos = self.pos_here();
1518        let target = self.parse_binding_pattern();
1519        let mut bound = self.bound_at.split_off(mark);
1520        let target = target?;
1521        if let Expr::Ident(n) = &target {
1522            bound = vec![(n.clone(), pos)];
1523        }
1524        if !self.spans {
1525            bound.clear();
1526        }
1527        Ok((target, bound))
1528    }
1529
1530    /// Run `f` on an expression nested in a binding pattern — a default value
1531    /// or a computed key — where names are references, not bindings.
1532    fn outside_binding<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1533        let outer = std::mem::replace(&mut self.in_binding, false);
1534        let r = f(self);
1535        self.in_binding = outer;
1536        r
1537    }
1538
1539    fn parse_binding_pattern(&mut self) -> Result<Expr, String> {
1540        if self.is_punct("[") || self.is_punct("{") {
1541            let outer = std::mem::replace(&mut self.in_binding, true);
1542            let pattern = if self.is_punct("[") {
1543                self.parse_array_literal()
1544            } else {
1545                self.parse_object_literal()
1546            };
1547            self.in_binding = outer;
1548            pattern
1549        } else {
1550            let name = self.ident_name()?;
1551            self.check_binding_name(&name)?;
1552            Ok(Expr::Ident(name))
1553        }
1554    }
1555
1556    /// Words that may not be bound: `enum` always, and the future-reserved
1557    /// words (plus `let`, `static`, `yield`) in strict code (13.1.1).
1558    fn check_binding_name(&self, name: &str) -> Result<(), String> {
1559        const STRICT_RESERVED: &[&str] = &[
1560            "implements",
1561            "interface",
1562            "let",
1563            "package",
1564            "private",
1565            "protected",
1566            "public",
1567            "static",
1568            "yield",
1569        ];
1570        // `await` is reserved throughout module code (13.1.1).
1571        if name == "enum" || self.module && name == "await" {
1572            return Err("SyntaxError: Unexpected reserved word".to_string());
1573        }
1574        if self.strict && STRICT_RESERVED.contains(&name) {
1575            return Err("SyntaxError: Unexpected strict mode reserved word".to_string());
1576        }
1577        Ok(())
1578    }
1579
1580    fn parse_if(&mut self) -> Result<StmtKind, String> {
1581        self.advance(); // if
1582        self.expect_punct("(")?;
1583        let test = self.parse_expr()?;
1584        self.expect_punct(")")?;
1585        let cons = Box::new(self.parse_sub_stmt(true)?);
1586        let alt = if self.eat_kw("else") {
1587            Some(Box::new(self.parse_sub_stmt(true)?))
1588        } else {
1589            None
1590        };
1591        Ok(StmtKind::If { test, cons, alt })
1592    }
1593
1594    fn parse_while(&mut self) -> Result<StmtKind, String> {
1595        self.advance();
1596        self.expect_punct("(")?;
1597        let test = self.parse_expr()?;
1598        self.expect_punct(")")?;
1599        let body = Box::new(self.parse_sub_stmt(false)?);
1600        Ok(StmtKind::While { test, body })
1601    }
1602
1603    fn parse_with(&mut self) -> Result<StmtKind, String> {
1604        if self.strict {
1605            return Err(
1606                "SyntaxError: Strict mode code may not include a with statement".to_string(),
1607            );
1608        }
1609        self.advance();
1610        self.expect_punct("(")?;
1611        let object = self.parse_expr()?;
1612        self.expect_punct(")")?;
1613        let body = Box::new(self.parse_sub_stmt(false)?);
1614        Ok(StmtKind::With { object, body })
1615    }
1616
1617    fn parse_do_while(&mut self) -> Result<StmtKind, String> {
1618        self.advance();
1619        let body = Box::new(self.parse_sub_stmt(false)?);
1620        if !self.eat_kw("while") {
1621            return Err(self.unexpected());
1622        }
1623        self.expect_punct("(")?;
1624        let test = self.parse_expr()?;
1625        self.expect_punct(")")?;
1626        // 12.10.1 rule 3: a `;` is inserted after `do … while ( … )` even with no
1627        // line break, so `do ; while (0) 1` is two statements.
1628        self.eat_punct(";");
1629        Ok(StmtKind::DoWhile { body, test })
1630    }
1631
1632    fn parse_for(&mut self) -> Result<StmtKind, String> {
1633        self.advance();
1634        // `for await (… of …)` — the async-iteration form (valid in an async body).
1635        let is_await = self.eat_kw("await");
1636        self.expect_punct("(")?;
1637        // Optional declaration or expression init.
1638        let decl_kind = match self.tok() {
1639            Tok::Ident(s) if s == "var" || s == "let" || s == "const" => {
1640                Some(self.parse_decl_kind())
1641            }
1642            _ => None,
1643        };
1644        // Empty init: `for (;;)`.
1645        if decl_kind.is_none() && self.is_punct(";") {
1646            return self.parse_c_for(None);
1647        }
1648        // Parse the first binding/expression, then decide of/in vs C-style.
1649        let mut first_bound = Vec::new();
1650        let first_target = if decl_kind.is_some() {
1651            let (target, bound) = self.parse_binding_target_at()?;
1652            first_bound = bound;
1653            target
1654        } else {
1655            self.parse_expr_no_in()?
1656        };
1657        if self.is_kw("of") || self.is_kw("in") {
1658            // `for ({ a = 1 } of xs)`: the head is a pattern.
1659            self.cover_init.clear();
1660        }
1661        if self.eat_kw("of") {
1662            let iter = self.parse_assign()?;
1663            self.expect_punct(")")?;
1664            let body = Box::new(self.parse_sub_stmt(false)?);
1665            return Ok(StmtKind::ForOf {
1666                decl_kind,
1667                target: first_target,
1668                iter,
1669                body,
1670                is_await,
1671            });
1672        }
1673        if self.eat_kw("in") {
1674            let object = self.parse_assign()?;
1675            self.expect_punct(")")?;
1676            let body = Box::new(self.parse_sub_stmt(false)?);
1677            return Ok(StmtKind::ForIn {
1678                decl_kind,
1679                target: first_target,
1680                object,
1681                body,
1682            });
1683        }
1684        // C-style: reconstruct the init statement.
1685        let init_stmt = if let Some(k) = decl_kind {
1686            let init = if self.eat_punct("=") {
1687                Some(self.parse_assign()?)
1688            } else {
1689                None
1690            };
1691            let mut decls = vec![Declarator {
1692                target: first_target,
1693                init,
1694                bound: first_bound,
1695            }];
1696            while self.eat_punct(",") {
1697                let (target, bound) = self.parse_binding_target_at()?;
1698                let init = if self.eat_punct("=") {
1699                    Some(self.parse_assign()?)
1700                } else {
1701                    None
1702                };
1703                decls.push(Declarator {
1704                    target,
1705                    init,
1706                    bound,
1707                });
1708            }
1709            // `for (let a, b of …)` / `for (let a = 1 of …)` are for-of headers
1710            // that carry more than a bare binding.
1711            if self.is_kw("of") {
1712                return Err(if decls.len() > 1 {
1713                    "SyntaxError: Invalid left-hand side in for-of loop: Must have a single binding."
1714                } else {
1715                    "SyntaxError: for-of loop variable declaration may not have an initializer."
1716                }
1717                .to_string());
1718            }
1719            StmtKind::Decl { kind: k, decls }
1720        } else {
1721            // A non-declaration C-style init may be a comma sequence
1722            // (`for (i = 0, n = a.length; …)`) — extend past the first assignment.
1723            let init = if self.is_punct(",") {
1724                let mut items = vec![first_target];
1725                while self.eat_punct(",") {
1726                    items.push(self.parse_expr_no_in()?);
1727                }
1728                Expr::Sequence(items)
1729            } else {
1730                first_target
1731            };
1732            StmtKind::Expr(init)
1733        };
1734        self.parse_c_for(Some(Stmt::from(init_stmt)))
1735    }
1736
1737    fn parse_c_for(&mut self, init: Option<Stmt>) -> Result<StmtKind, String> {
1738        self.expect_punct(";")?;
1739        let test = if self.is_punct(";") {
1740            None
1741        } else {
1742            Some(self.parse_expr()?)
1743        };
1744        self.expect_punct(";")?;
1745        let update = if self.is_punct(")") {
1746            None
1747        } else {
1748            Some(self.parse_expr()?)
1749        };
1750        self.expect_punct(")")?;
1751        let body = Box::new(self.parse_sub_stmt(false)?);
1752        Ok(StmtKind::For {
1753            init: init.map(Box::new),
1754            test,
1755            update,
1756            body,
1757        })
1758    }
1759
1760    fn parse_switch(&mut self) -> Result<StmtKind, String> {
1761        self.advance();
1762        self.expect_punct("(")?;
1763        let disc = self.parse_expr()?;
1764        self.expect_punct(")")?;
1765        self.expect_punct("{")?;
1766        let mut cases = Vec::new();
1767        while !self.is_punct("}") && !self.at_eof() {
1768            let test = if self.eat_kw("case") {
1769                let e = self.parse_expr()?;
1770                Some(e)
1771            } else if self.eat_kw("default") {
1772                None
1773            } else {
1774                return Err(self.unexpected());
1775            };
1776            self.expect_punct(":")?;
1777            let mut body = Vec::new();
1778            while !self.is_punct("}")
1779                && !self.is_kw("case")
1780                && !self.is_kw("default")
1781                && !self.at_eof()
1782            {
1783                body.push(self.parse_stmt()?);
1784            }
1785            cases.push(SwitchCase { test, body });
1786        }
1787        self.expect_punct("}")?;
1788        Ok(StmtKind::Switch { disc, cases })
1789    }
1790
1791    fn parse_try(&mut self) -> Result<StmtKind, String> {
1792        self.advance();
1793        self.expect_punct("{")?;
1794        let block = self.parse_block_body()?;
1795        let handler = if self.eat_kw("catch") {
1796            let param = if self.eat_punct("(") {
1797                let p = self.parse_binding_target()?;
1798                self.expect_punct(")")?;
1799                Some(p)
1800            } else {
1801                None
1802            };
1803            self.expect_punct("{")?;
1804            let body = self.parse_block_body()?;
1805            Some((param, body))
1806        } else {
1807            None
1808        };
1809        let finalizer = if self.eat_kw("finally") {
1810            self.expect_punct("{")?;
1811            Some(self.parse_block_body()?)
1812        } else {
1813            None
1814        };
1815        Ok(StmtKind::Try {
1816            block,
1817            handler,
1818            finalizer,
1819        })
1820    }
1821
1822    // ── expressions ──────────────────────────────────────────────────────
1823    /// Full expression, including the comma sequence operator.
1824    fn parse_expr(&mut self) -> Result<Expr, String> {
1825        let first = self.parse_assign()?;
1826        if self.is_punct(",") {
1827            let mut items = vec![first];
1828            while self.eat_punct(",") {
1829                items.push(self.parse_assign()?);
1830            }
1831            Ok(Expr::Sequence(items))
1832        } else {
1833            Ok(first)
1834        }
1835    }
1836
1837    /// Like `parse_expr` but stops before `in` (used in `for` init position).
1838    fn parse_expr_no_in(&mut self) -> Result<Expr, String> {
1839        // For simplicity the no-in variant only parses an assignment/LHS chain,
1840        // which is sufficient for `for (x in ...)` / `for (x of ...)` heads.
1841        let saved = self.no_in;
1842        self.no_in = true;
1843        let r = self.parse_assign();
1844        self.no_in = saved;
1845        r
1846    }
1847
1848    /// Whether `e` is an optional chain — i.e. its member/call SPINE carries a
1849    /// `?.` link. Mirrors the compiler's spine walk; used only to decide
1850    /// whether a set of parentheses is a chain boundary worth recording.
1851    fn has_optional_link(e: &Expr) -> bool {
1852        match e {
1853            Expr::Member {
1854                object, optional, ..
1855            } => *optional || Self::has_optional_link(object),
1856            Expr::Index {
1857                object, optional, ..
1858            } => *optional || Self::has_optional_link(object),
1859            Expr::Call { func, optional, .. } => *optional || Self::has_optional_link(func),
1860            _ => false,
1861        }
1862    }
1863
1864    /// Run `f` with `in` re-enabled (inside a parenthesised/bracketed sub-
1865    /// expression of a `for` LHS, where the no-in restriction does not apply).
1866    fn allow_in<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
1867        let saved = self.no_in;
1868        self.no_in = false;
1869        let r = f(self);
1870        self.no_in = saved;
1871        r
1872    }
1873
1874    /// `yield [no LineTerminator here] [*] [expr]` (15.5): a YieldExpression is
1875    /// an AssignmentExpression, so nothing binds to it from the right — `yield
1876    /// * 2` is a bare `yield` and then a stray `*`.
1877    fn parse_yield(&mut self) -> Result<Expr, String> {
1878        self.advance(); // yield
1879        let delegate = !self.newline_before() && self.eat_punct("*");
1880        // `yield` with no argument (before `)`, `]`, `}`, `,`, `;`, `:`,
1881        // newline, or EOF).
1882        let arg = if delegate
1883            || !(self.is_punct(")")
1884                || self.is_punct("]")
1885                || self.is_punct("}")
1886                || self.is_punct(",")
1887                || self.is_punct(";")
1888                || self.is_punct(":")
1889                || self.newline_before()
1890                || self.at_eof())
1891        {
1892            Some(Box::new(self.parse_assign()?))
1893        } else {
1894            None
1895        };
1896        Ok(Expr::Yield { arg, delegate })
1897    }
1898
1899    fn parse_assign(&mut self) -> Result<Expr, String> {
1900        if self.in_generator && self.is_kw("yield") {
1901            return self.parse_yield();
1902        }
1903        // Arrow function detection.
1904        if let Some(arrow) = self.try_parse_arrow()? {
1905            return Ok(arrow);
1906        }
1907        let start = self.pos;
1908        let left = self.parse_conditional()?;
1909        // Assignment operators (right-associative).
1910        let op = match self.tok() {
1911            Tok::Punct(p) => p.clone(),
1912            _ => return Ok(left),
1913        };
1914        // `{ a = 1 } = v`: the shorthand initialisers just parsed belong to a
1915        // pattern, so they are defaults and not an error.
1916        if op == "=" {
1917            // A parenthesised literal is a value, never a pattern (13.15.1):
1918            // `({ a }) = 1` and `([a]) = 1` are early errors, where `(a) = 1` is
1919            // fine.
1920            if matches!(left, Expr::Object(_) | Expr::Array(_))
1921                && matches!(&self.toks[start].tok, Tok::Punct(p) if p == "(")
1922                && self.matching_paren(start) == Some(self.pos - 1)
1923            {
1924                return Err("SyntaxError: Invalid left-hand side in assignment".to_string());
1925            }
1926            self.cover_init.retain(|&(at, ..)| at < start);
1927        }
1928        let compound = match op.as_str() {
1929            "=" => None,
1930            "+=" => Some(BinOp::Add),
1931            "-=" => Some(BinOp::Sub),
1932            "*=" => Some(BinOp::Mul),
1933            "/=" => Some(BinOp::Div),
1934            "%=" => Some(BinOp::Mod),
1935            "**=" => Some(BinOp::Pow),
1936            "&=" => Some(BinOp::BitAnd),
1937            "|=" => Some(BinOp::BitOr),
1938            "^=" => Some(BinOp::BitXor),
1939            "<<=" => Some(BinOp::Shl),
1940            ">>=" => Some(BinOp::Shr),
1941            ">>>=" => Some(BinOp::UShr),
1942            "&&=" | "||=" | "??=" => {
1943                // Logical assignment. The operator is CARRIED, not desugared:
1944                // building `Logical(op, left.clone(), value)` here duplicated
1945                // the target, so `o[k()] ||= 1` evaluated `k` twice — once for
1946                // the read and once for the write — where node evaluates it
1947                // once and may not write at all.
1948                self.advance();
1949                let value = self.parse_assign()?;
1950                let lop = match op.as_str() {
1951                    "&&=" => LogicalOp::And,
1952                    "||=" => LogicalOp::Or,
1953                    _ => LogicalOp::Nullish,
1954                };
1955                return Ok(Expr::Assign {
1956                    target: Box::new(left),
1957                    op: Some(AssignOp::Logical(lop)),
1958                    value: Box::new(value),
1959                });
1960            }
1961            _ => return Ok(left),
1962        };
1963        self.advance();
1964        let value = self.outside_binding(Self::parse_assign)?;
1965        Ok(Expr::Assign {
1966            target: Box::new(left),
1967            op: compound.map(AssignOp::Binary),
1968            value: Box::new(value),
1969        })
1970    }
1971
1972    fn parse_conditional(&mut self) -> Result<Expr, String> {
1973        let test = self.parse_binary(0)?;
1974        if self.eat_punct("?") {
1975            let cons = self.parse_assign()?;
1976            self.expect_punct(":")?;
1977            let alt = self.parse_assign()?;
1978            Ok(Expr::Conditional {
1979                test: Box::new(test),
1980                cons: Box::new(cons),
1981                alt: Box::new(alt),
1982            })
1983        } else {
1984            Ok(test)
1985        }
1986    }
1987
1988    /// Precedence-climbing binary parser. Handles `&& || ??` as logical nodes.
1989    fn parse_binary(&mut self, min_prec: u8) -> Result<Expr, String> {
1990        let mut left = self.parse_unary()?;
1991        // The logical operator that built `left` in THIS loop. A parenthesised
1992        // operand arrives from `parse_unary` and is None, which is what makes
1993        // `(a || b) ?? c` legal while `a || b ?? c` is not (13.12).
1994        let mut left_logical: Option<LogicalOp> = None;
1995        while let Some((prec, right_assoc, logical, bin)) = self.bin_info() {
1996            if prec < min_prec {
1997                break;
1998            }
1999            if let Some(lop) = logical {
2000                let nullish = |o: LogicalOp| matches!(o, LogicalOp::Nullish);
2001                if left_logical.is_some_and(|l| nullish(l) != nullish(lop)) {
2002                    return Err(self.unexpected());
2003                }
2004            }
2005            self.advance();
2006            // `??` takes BitwiseOR-level operands (prec 4), never `||`/`&&`.
2007            let next_min = match logical {
2008                Some(LogicalOp::Nullish) => 4,
2009                _ if right_assoc => prec,
2010                _ => prec + 1,
2011            };
2012            let right = self.parse_binary(next_min)?;
2013            left_logical = logical;
2014            left = if let Some(lop) = logical {
2015                Expr::Logical(lop, Box::new(left), Box::new(right))
2016            } else {
2017                Expr::Binary(bin.unwrap(), Box::new(left), Box::new(right))
2018            };
2019        }
2020        Ok(left)
2021    }
2022
2023    /// `(precedence, right_assoc, logical_op, bin_op)` for the current token.
2024    fn bin_info(&self) -> Option<(u8, bool, Option<LogicalOp>, Option<BinOp>)> {
2025        let p = match self.tok() {
2026            Tok::Punct(p) => p.as_str(),
2027            // In a `for` LHS (no-in) context, `in` is the loop separator, not a
2028            // relational operator.
2029            Tok::Ident(s) if s == "in" => {
2030                if self.no_in {
2031                    return None;
2032                }
2033                "in"
2034            }
2035            Tok::Ident(s) if s == "instanceof" => "instanceof",
2036            _ => return None,
2037        };
2038        let (prec, ra, log, bin) = match p {
2039            "??" => (1, false, Some(LogicalOp::Nullish), None),
2040            "||" => (2, false, Some(LogicalOp::Or), None),
2041            "&&" => (3, false, Some(LogicalOp::And), None),
2042            "|" => (4, false, None, Some(BinOp::BitOr)),
2043            "^" => (5, false, None, Some(BinOp::BitXor)),
2044            "&" => (6, false, None, Some(BinOp::BitAnd)),
2045            "==" => (7, false, None, Some(BinOp::EqEq)),
2046            "!=" => (7, false, None, Some(BinOp::NeEq)),
2047            "===" => (7, false, None, Some(BinOp::EqEqEq)),
2048            "!==" => (7, false, None, Some(BinOp::NeEqEq)),
2049            "<" => (8, false, None, Some(BinOp::Lt)),
2050            "<=" => (8, false, None, Some(BinOp::Le)),
2051            ">" => (8, false, None, Some(BinOp::Gt)),
2052            ">=" => (8, false, None, Some(BinOp::Ge)),
2053            "in" => (8, false, None, Some(BinOp::In)),
2054            "instanceof" => (8, false, None, Some(BinOp::InstanceOf)),
2055            "<<" => (9, false, None, Some(BinOp::Shl)),
2056            ">>" => (9, false, None, Some(BinOp::Shr)),
2057            ">>>" => (9, false, None, Some(BinOp::UShr)),
2058            "+" => (10, false, None, Some(BinOp::Add)),
2059            "-" => (10, false, None, Some(BinOp::Sub)),
2060            "*" => (11, false, None, Some(BinOp::Mul)),
2061            "/" => (11, false, None, Some(BinOp::Div)),
2062            "%" => (11, false, None, Some(BinOp::Mod)),
2063            "**" => (12, true, None, Some(BinOp::Pow)),
2064            _ => return None,
2065        };
2066        Some((prec, ra, log, bin))
2067    }
2068
2069    /// Reject a `**` directly after a just-parsed UnaryExpression. JS only
2070    /// allows an UpdateExpression there (`x++ ** y` and `++x ** y` are fine),
2071    /// so an unparenthesized `-x ** y` / `typeof x ** y` / `await x ** y` is a
2072    /// SyntaxError rather than a silently-reassociated `-(x ** y)`.
2073    fn reject_unary_before_pow(&mut self) -> Result<(), String> {
2074        if self.is_punct("**") {
2075            return Err("SyntaxError: Unary operator used immediately before \
2076                 exponentiation expression. Parenthesis must be used to \
2077                 disambiguate operator precedence"
2078                .to_string());
2079        }
2080        Ok(())
2081    }
2082
2083    fn parse_unary(&mut self) -> Result<Expr, String> {
2084        let op = match self.tok() {
2085            Tok::Punct(p) if p == "!" => Some(UnOp::Not),
2086            Tok::Punct(p) if p == "~" => Some(UnOp::BitNot),
2087            Tok::Punct(p) if p == "+" => Some(UnOp::Pos),
2088            Tok::Punct(p) if p == "-" => Some(UnOp::Neg),
2089            Tok::Ident(s) if s == "typeof" => Some(UnOp::TypeOf),
2090            Tok::Ident(s) if s == "void" => Some(UnOp::Void),
2091            Tok::Ident(s) if s == "delete" => Some(UnOp::Delete),
2092            _ => None,
2093        };
2094        if let Some(op) = op {
2095            self.advance();
2096            let e = self.parse_unary()?;
2097            // `ExponentiationExpression : UpdateExpression ** …` — a
2098            // UnaryExpression on the left of `**` is a SyntaxError, so
2099            // `-x ** y` must be written `(-x) ** y` or `-(x ** y)`.
2100            self.reject_unary_before_pow()?;
2101            return Ok(Expr::Unary(op, Box::new(e)));
2102        }
2103        // Prefix ++/--.
2104        if self.is_punct("++") || self.is_punct("--") {
2105            let op = if self.is_punct("++") {
2106                UpdateOp::Inc
2107            } else {
2108                UpdateOp::Dec
2109            };
2110            self.advance();
2111            let e = self.parse_unary()?;
2112            return Ok(Expr::Update {
2113                op,
2114                prefix: true,
2115                target: Box::new(e),
2116            });
2117        }
2118        self.parse_postfix()
2119    }
2120
2121    fn parse_postfix(&mut self) -> Result<Expr, String> {
2122        let mut e = self.parse_call_member()?;
2123        // Postfix ++/-- (no line break before).
2124        if (self.is_punct("++") || self.is_punct("--")) && !self.newline_before() {
2125            let op = if self.is_punct("++") {
2126                UpdateOp::Inc
2127            } else {
2128                UpdateOp::Dec
2129            };
2130            self.advance();
2131            e = Expr::Update {
2132                op,
2133                prefix: false,
2134                target: Box::new(e),
2135            };
2136        }
2137        Ok(e)
2138    }
2139
2140    fn parse_call_member(&mut self) -> Result<Expr, String> {
2141        let new_pos = self.pos_here();
2142        let mut e = if self.eat_kw("new") {
2143            // `new.target` meta-property.
2144            if self.is_punct(".") {
2145                self.advance();
2146                let prop = self.ident_name()?;
2147                if prop != "target" {
2148                    return Err(self.unexpected());
2149                }
2150                Expr::NewTarget
2151            } else {
2152                let callee = self.parse_call_member_no_call()?;
2153                // An optional chain cannot be the callee of `new` (13.3.5.1):
2154                // `new a?.b()` and `new C?.()` are early errors. Parenthesising
2155                // the chain ends it, so `new (a?.b)()` is legal — which is why
2156                // the check is on the callee's own spine, and the parenthesised
2157                // form records a chain boundary that clears `optional`.
2158                if Self::has_optional_link(&callee) || self.is_punct("?.") {
2159                    return Err(
2160                        "SyntaxError: Invalid optional chain from new expression".to_string()
2161                    );
2162                }
2163                let args = if self.is_punct("(") {
2164                    self.parse_args()?
2165                } else {
2166                    Vec::new()
2167                };
2168                Expr::New {
2169                    callee: Box::new(callee),
2170                    args,
2171                    pos: new_pos,
2172                }
2173            }
2174        } else {
2175            self.parse_primary()?
2176        };
2177        loop {
2178            if self.eat_punct(".") {
2179                let pos = self.pos_here();
2180                let property = self.ident_name()?;
2181                self.check_private_in_scope(&property)?;
2182                e = Expr::Member {
2183                    object: Box::new(e),
2184                    property,
2185                    optional: false,
2186                    pos,
2187                };
2188            } else if self.eat_punct("?.") {
2189                if matches!(self.tok(), Tok::Template { .. }) {
2190                    return Err(
2191                        "SyntaxError: Invalid tagged template on optional chain".to_string()
2192                    );
2193                }
2194                if self.is_punct("(") {
2195                    let pos = self.call_pos();
2196                    let args = self.parse_args()?;
2197                    e = Expr::Call {
2198                        func: Box::new(e),
2199                        args,
2200                        optional: true,
2201                        pos,
2202                    };
2203                } else if self.is_punct("[") {
2204                    let pos = self.pos_here();
2205                    self.advance();
2206                    let index = self.allow_in(|p| p.parse_expr())?;
2207                    self.expect_punct("]")?;
2208                    e = Expr::Index {
2209                        object: Box::new(e),
2210                        index: Box::new(index),
2211                        optional: true,
2212                        pos,
2213                    };
2214                } else {
2215                    let pos = self.pos_here();
2216                    let property = self.ident_name()?;
2217                    e = Expr::Member {
2218                        object: Box::new(e),
2219                        property,
2220                        optional: true,
2221                        pos,
2222                    };
2223                }
2224            } else if self.is_punct("[") {
2225                let pos = self.pos_here();
2226                self.advance();
2227                let index = self.allow_in(|p| p.parse_expr())?;
2228                self.expect_punct("]")?;
2229                e = Expr::Index {
2230                    object: Box::new(e),
2231                    index: Box::new(index),
2232                    optional: false,
2233                    pos,
2234                };
2235            } else if self.is_punct("(") {
2236                let pos = self.call_pos();
2237                let args = self.parse_args()?;
2238                e = Expr::Call {
2239                    func: Box::new(e),
2240                    args,
2241                    optional: false,
2242                    pos,
2243                };
2244            } else if matches!(self.tok(), Tok::Template { .. }) {
2245                // A template literal immediately after a callee is a *tagged*
2246                // template: `` tag`...` `` → `tag(strings, ...values)`.
2247                // A tagged template cannot sit on an optional chain (13.3.11.1):
2248                // `a?.b`t`` is an early error, because the tag would have to be
2249                // called even when the chain short-circuited.
2250                if Self::has_optional_link(&e) {
2251                    return Err(
2252                        "SyntaxError: Invalid tagged template on optional chain".to_string()
2253                    );
2254                }
2255                e = self.parse_tagged_template(e)?;
2256            } else {
2257                break;
2258            }
2259        }
2260        Ok(e)
2261    }
2262
2263    /// Parse `` tag`a${x}b` `` into a `TaggedTemplate` node (the tag expression is
2264    /// already parsed as `tag`, and the current token is the template).
2265    fn parse_tagged_template(&mut self, tag: Expr) -> Result<Expr, String> {
2266        let (quasis, raws, exprs_src, expr_at) = match self.tok().clone() {
2267            Tok::Template {
2268                quasis,
2269                raws,
2270                exprs,
2271                expr_at,
2272            } => (quasis, raws, exprs, expr_at),
2273            _ => unreachable!(),
2274        };
2275        self.advance();
2276        let mut exprs = Vec::new();
2277        for (src, at) in exprs_src.iter().zip(expr_at) {
2278            exprs.push(self.parse_field(src, at)?);
2279        }
2280        Ok(Expr::TaggedTemplate {
2281            tag: Box::new(tag),
2282            quasis,
2283            raws,
2284            exprs,
2285        })
2286    }
2287
2288    /// Member chain without a trailing call — the `new X.Y` callee grammar.
2289    fn parse_call_member_no_call(&mut self) -> Result<Expr, String> {
2290        let mut e = self.parse_primary()?;
2291        loop {
2292            if self.eat_punct(".") {
2293                let pos = self.pos_here();
2294                let property = self.ident_name()?;
2295                self.check_private_in_scope(&property)?;
2296                e = Expr::Member {
2297                    object: Box::new(e),
2298                    property,
2299                    optional: false,
2300                    pos,
2301                };
2302            } else if self.is_punct("[") {
2303                let pos = self.pos_here();
2304                self.advance();
2305                let index = self.allow_in(|p| p.parse_expr())?;
2306                self.expect_punct("]")?;
2307                e = Expr::Index {
2308                    object: Box::new(e),
2309                    index: Box::new(index),
2310                    optional: false,
2311                    pos,
2312                };
2313            } else {
2314                break;
2315            }
2316        }
2317        Ok(e)
2318    }
2319
2320    fn parse_args(&mut self) -> Result<Vec<Expr>, String> {
2321        self.expect_punct("(")?;
2322        // Inside a call-argument list `in` is always a relational operator, even
2323        // in a `for` LHS.
2324        let args = self.allow_in(|p| {
2325            let mut args = Vec::new();
2326            while !p.is_punct(")") {
2327                if p.eat_punct("...") {
2328                    let e = p.parse_assign()?;
2329                    args.push(Expr::Spread(Box::new(e)));
2330                } else {
2331                    args.push(p.parse_assign()?);
2332                }
2333                if !p.eat_punct(",") {
2334                    break;
2335                }
2336            }
2337            Ok(args)
2338        })?;
2339        // V8 reserves its own wording for a call whose argument list does not
2340        // close, whatever token stopped it (`f(1 2)`, `f(`).
2341        if !self.eat_punct(")") {
2342            return Err("SyntaxError: missing ) after argument list".to_string());
2343        }
2344        Ok(args)
2345    }
2346
2347    fn parse_primary(&mut self) -> Result<Expr, String> {
2348        match self.tok().clone() {
2349            Tok::Num(n) => {
2350                self.check_legacy()?;
2351                self.advance();
2352                Ok(Expr::Number(n))
2353            }
2354            Tok::BigInt(s) => {
2355                self.advance();
2356                Ok(Expr::BigInt(s))
2357            }
2358            Tok::Regex(pat, flags) => {
2359                // A regex LITERAL's flags and pattern are early errors (13.2.7.3),
2360                // reported before anything in the program runs.
2361                crate::regexp::check_literal(&pat, &flags)?;
2362                self.advance();
2363                Ok(Expr::Regex(pat, flags))
2364            }
2365            Tok::Str(s) => {
2366                self.check_legacy()?;
2367                self.advance();
2368                Ok(Expr::Str(s))
2369            }
2370            Tok::Template {
2371                quasis,
2372                raws: _,
2373                exprs,
2374                expr_at,
2375            } => {
2376                self.advance();
2377                let mut parsed = Vec::new();
2378                for (src, at) in exprs.iter().zip(expr_at) {
2379                    parsed.push(self.parse_field(src, at)?);
2380                }
2381                Ok(Expr::Template {
2382                    quasis,
2383                    exprs: parsed,
2384                })
2385            }
2386            Tok::Punct(p) if p == "(" => {
2387                self.advance();
2388                let e = self.parse_expr()?;
2389                self.expect_punct(")")?;
2390                // Parentheses are otherwise erased, but around an OPTIONAL CHAIN
2391                // they are load-bearing: they END the chain, so a `?.` inside
2392                // them cannot short-circuit an access written outside them.
2393                // `o?.a.b` is `undefined` when `o` is nullish; `(o?.a).b` reads
2394                // `.b` off that `undefined` and THROWS (ECMA-262 13.3.1 —
2395                // `ParenthesizedExpression` is not an `OptionalExpression`).
2396                // With the parentheses dropped the two parsed to the same tree
2397                // and both answered `undefined`.
2398                //
2399                // The boundary is spelled as a one-element sequence rather than
2400                // a new node type: `(e)` and `e,` evaluate identically, every
2401                // existing pass already walks `Sequence` correctly, and the
2402                // chain-spine walk does not descend through it — which is the
2403                // whole point. Only chains are wrapped, so no other expression's
2404                // tree shape changes.
2405                if Self::has_optional_link(&e) {
2406                    return Ok(Expr::Sequence(vec![e]));
2407                }
2408                Ok(e)
2409            }
2410            Tok::Punct(p) if p == "[" => self.parse_array_literal(),
2411            Tok::Punct(p) if p == "{" => self.parse_object_literal(),
2412            Tok::Ident(s) => {
2413                match s.as_str() {
2414                    "true" => {
2415                        self.advance();
2416                        Ok(Expr::True)
2417                    }
2418                    "false" => {
2419                        self.advance();
2420                        Ok(Expr::False)
2421                    }
2422                    "null" => {
2423                        self.advance();
2424                        Ok(Expr::Null)
2425                    }
2426                    "this" => {
2427                        self.advance();
2428                        Ok(Expr::This)
2429                    }
2430                    "super" => {
2431                        if !self.super_ok {
2432                            return Err("SyntaxError: 'super' keyword unexpected here".to_string());
2433                        }
2434                        self.advance();
2435                        Ok(Expr::Super)
2436                    }
2437                    "class" => Ok(Expr::Class(Box::new(self.parse_class(false)?))),
2438                    "function" => self.parse_function_expr(false),
2439                    "async" if self.peek_kw(1, "function") && !self.peek_newline(1) => {
2440                        self.advance(); // async
2441                        self.parse_function_expr(true)
2442                    }
2443                    // `yield` in a generator is an AssignmentExpression and is
2444                    // parsed by `parse_assign`; reaching it here means it sat
2445                    // where only a higher-precedence operand may (`a + yield`).
2446                    "yield" if self.in_generator => Err(self.unexpected()),
2447                    // `import(…)` (ImportCall) is left as a call of the name
2448                    // `import`, which the module lowering and the compiler
2449                    // recognise; `import.meta` is a meta property that only the
2450                    // Module goal has (16.2.1.1).
2451                    "import" if self.peek_punct_at(1, ".") => {
2452                        self.advance(); // import
2453                        self.advance(); // .
2454                        if !self.is_kw("meta") {
2455                            return Err(self.unexpected());
2456                        }
2457                        if !self.module {
2458                            return Err("SyntaxError: Cannot use 'import.meta' outside a module"
2459                                .to_string());
2460                        }
2461                        self.advance(); // meta
2462                        Ok(Expr::Member {
2463                            object: Box::new(Expr::Ident("import".into())),
2464                            property: "meta".into(),
2465                            optional: false,
2466                            pos: 0,
2467                        })
2468                    }
2469                    "import" if !self.peek_punct_at(1, "(") => Err(self.unexpected()),
2470                    "await" if self.in_async => {
2471                        let pos = self.pos_here();
2472                        self.advance();
2473                        let e = self.parse_unary()?;
2474                        // An AwaitExpression is a UnaryExpression, so it too
2475                        // cannot sit directly left of `**`.
2476                        self.reject_unary_before_pow()?;
2477                        Ok(Expr::Await(Box::new(e), pos))
2478                    }
2479                    _ if is_keyword(&s) => Err(self.unexpected()),
2480                    // The future-reserved words are not identifiers in strict code.
2481                    "implements" | "interface" | "package" | "private" | "protected" | "public"
2482                    | "static" | "yield"
2483                        if self.strict =>
2484                    {
2485                        Err("SyntaxError: Unexpected strict mode reserved word".to_string())
2486                    }
2487                    _ => {
2488                        if self.in_binding {
2489                            self.bound_at.push((s.clone(), self.pos_here()));
2490                        }
2491                        self.advance();
2492                        Ok(Expr::Ident(s))
2493                    }
2494                }
2495            }
2496            _ => Err(self.unexpected()),
2497        }
2498    }
2499
2500    fn parse_array_literal(&mut self) -> Result<Expr, String> {
2501        self.expect_punct("[")?;
2502        let mut items = Vec::new();
2503        while !self.is_punct("]") {
2504            if self.is_punct(",") {
2505                // Elision: the element is a HOLE, not a stored `undefined`.
2506                items.push(Expr::Hole);
2507                self.advance();
2508                continue;
2509            }
2510            if self.eat_punct("...") {
2511                let e = self.parse_assign()?;
2512                items.push(Expr::Spread(Box::new(e)));
2513            } else {
2514                items.push(self.parse_assign()?);
2515            }
2516            if !self.eat_punct(",") {
2517                break;
2518            }
2519        }
2520        self.expect_punct("]")?;
2521        Ok(Expr::Array(items))
2522    }
2523
2524    fn parse_object_literal(&mut self) -> Result<Expr, String> {
2525        self.expect_punct("{")?;
2526        let mut props = Vec::new();
2527        let mut proto_seen = false;
2528        while !self.is_punct("}") {
2529            if self.eat_punct("...") {
2530                let e = self.parse_assign()?;
2531                props.push(Prop::Spread(e));
2532                if !self.eat_punct(",") {
2533                    break;
2534                }
2535                continue;
2536            }
2537            // `get key() {}` / `set key(v) {}` accessor (contextual: `get`/`set`
2538            // is a modifier only when followed by another key, not `:`/`(`/`,`).
2539            if (self.is_kw("get") || self.is_kw("set"))
2540                && !self.peek_is_member_punct(1)
2541                && !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
2542            {
2543                let is_getter = self.is_kw("get");
2544                let start = self.start_at(self.pos);
2545                self.advance();
2546                let (key, computed) = self.parse_property_key()?;
2547                let params = self.parse_params()?;
2548                check_accessor_arity(
2549                    if is_getter {
2550                        MemberKind::Get
2551                    } else {
2552                        MemberKind::Set
2553                    },
2554                    &params,
2555                )?;
2556                self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
2557                self.expect_punct("{")?;
2558                let body = self.with_super(true, |p| p.parse_fn_body_block(false, false))?;
2559                let func = Expr::Function {
2560                    params,
2561                    body: FnBody::Block(body),
2562                    is_arrow: false,
2563                    name: None,
2564                    is_generator: false,
2565                    is_async: false,
2566                    is_method: true,
2567                    span: self.span_from(start),
2568                };
2569                props.push(Prop::Accessor {
2570                    key,
2571                    computed,
2572                    is_getter,
2573                    func,
2574                });
2575                if !self.eat_punct(",") {
2576                    break;
2577                }
2578                continue;
2579            }
2580            // Concise-method modifiers: `async` and/or `*` before the key.
2581            let mut m_async = false;
2582            let mut m_gen = false;
2583            let start = self.start_at(self.pos);
2584            if self.is_kw("async")
2585                && !self.peek_is_member_punct(1)
2586                && !self.peek_newline(1)
2587                && !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
2588            {
2589                self.advance();
2590                m_async = true;
2591            }
2592            if self.is_punct("*") {
2593                self.advance();
2594                m_gen = true;
2595            }
2596            let key_pos = self.pos_here();
2597            let (key, computed) = self.parse_property_key()?;
2598            // Method shorthand `key(params) { }` (incl. `*gen(){}`, `async m(){}`).
2599            if self.is_punct("(") {
2600                let params = self.parse_params()?;
2601                self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
2602                self.expect_punct("{")?;
2603                let body = self.with_super(true, |p| p.parse_fn_body_block(m_gen, m_async))?;
2604                let f = Expr::Function {
2605                    params,
2606                    body: FnBody::Block(body),
2607                    is_arrow: false,
2608                    name: None,
2609                    is_generator: m_gen,
2610                    is_async: m_async,
2611                    is_method: true,
2612                    span: self.span_from(start),
2613                };
2614                props.push(Prop::KeyValue {
2615                    key,
2616                    value: f,
2617                    computed,
2618                });
2619            } else if self.eat_punct(":") {
2620                // 13.2.5.1: a second `__proto__: v` in one literal is an early error
2621                // (the shorthand and method forms do not set the prototype).
2622                if !computed && matches!(&key, Expr::Str(k) if k == "__proto__") {
2623                    if proto_seen {
2624                        return Err(
2625                            "SyntaxError: Duplicate __proto__ fields are not allowed in object literals"
2626                                .to_string(),
2627                        );
2628                    }
2629                    proto_seen = true;
2630                }
2631                let value = self.parse_assign()?;
2632                props.push(Prop::KeyValue {
2633                    key,
2634                    value,
2635                    computed,
2636                });
2637            } else {
2638                // Shorthand `{ x }` -> key "x", value ident x. Or with default
2639                // in a destructuring pattern: `{ x = 1 }`.
2640                let name = match &key {
2641                    Expr::Str(s) => s.clone(),
2642                    _ => return Err(format!("SyntaxError: bad shorthand (line {})", self.line())),
2643                };
2644                if self.in_binding {
2645                    self.bound_at.push((name.clone(), key_pos));
2646                }
2647                let value = if self.is_punct("=") {
2648                    let eq = self.pos;
2649                    self.advance();
2650                    // Pattern default; represent as Assign so destructuring reads it.
2651                    let d = self.outside_binding(Self::parse_assign)?;
2652                    if !self.in_binding {
2653                        let end = if self.spans {
2654                            self.toks[self.pos - 1].end + 1
2655                        } else {
2656                            0
2657                        };
2658                        self.cover_init.push((eq, key_pos, end));
2659                    }
2660                    Expr::Assign {
2661                        target: Box::new(Expr::Ident(name.clone())),
2662                        op: None,
2663                        value: Box::new(d),
2664                    }
2665                } else {
2666                    Expr::Ident(name)
2667                };
2668                props.push(Prop::KeyValue {
2669                    key,
2670                    value,
2671                    computed,
2672                });
2673            }
2674            if !self.eat_punct(",") {
2675                break;
2676            }
2677        }
2678        self.expect_punct("}")?;
2679        Ok(Expr::Object(props))
2680    }
2681
2682    // ── functions / arrows ───────────────────────────────────────────────
2683    fn parse_params(&mut self) -> Result<Vec<Param>, String> {
2684        self.expect_punct("(")?;
2685        let mut params = Vec::new();
2686        while !self.is_punct(")") {
2687            let rest = self.eat_punct("...");
2688            let pattern = self.parse_binding_target()?;
2689            let default = if !rest && self.eat_punct("=") {
2690                Some(self.parse_assign()?)
2691            } else {
2692                None
2693            };
2694            params.push(Param {
2695                pattern,
2696                default,
2697                rest,
2698            });
2699            if !self.eat_punct(",") {
2700                break;
2701            }
2702        }
2703        self.expect_punct(")")?;
2704        Ok(params)
2705    }
2706
2707    /// Try to parse an arrow function starting at the current position. Returns
2708    /// `None` (without consuming) if the head is not an arrow.
2709    fn try_parse_arrow(&mut self) -> Result<Option<Expr>, String> {
2710        let start = self.start_at(self.pos);
2711        // `async` prefix on an arrow (`async x => …` / `async (…) => …`), only
2712        // when `async` is not itself the parameter and no newline intervenes.
2713        let mut is_async = false;
2714        let mut base = self.pos;
2715        if self.is_kw("async") && !self.peek_newline(1) {
2716            let next = self.toks.get(self.pos + 1).map(|t| &t.tok);
2717            let looks_async_arrow = matches!(next, Some(Tok::Punct(p)) if p == "(")
2718                || matches!(next, Some(Tok::Ident(n)) if !is_keyword(n) && self.peek_is_arrow_after(2));
2719            if looks_async_arrow {
2720                is_async = true;
2721                base += 1;
2722            }
2723        }
2724        // `ident => ...`
2725        if let Some(Tok::Ident(name)) = self.toks.get(base).map(|t| &t.tok) {
2726            if !is_keyword(name)
2727                && matches!(self.toks.get(base + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
2728            {
2729                let name = name.clone();
2730                if is_async {
2731                    self.advance(); // async
2732                }
2733                self.advance(); // ident
2734                self.advance(); // =>
2735                let body = self.parse_arrow_body(is_async)?;
2736                return Ok(Some(Expr::Function {
2737                    params: vec![Param {
2738                        pattern: Expr::Ident(name),
2739                        default: None,
2740                        rest: false,
2741                    }],
2742                    body,
2743                    is_arrow: true,
2744                    name: None,
2745                    is_generator: false,
2746                    is_async,
2747                    is_method: false,
2748                    span: self.span_from(start),
2749                }));
2750            }
2751        }
2752        // `( ... ) => ...`
2753        if matches!(self.toks.get(base).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "(") {
2754            if let Some(close) = self.matching_paren(base) {
2755                let after = close + 1;
2756                if matches!(self.toks.get(after).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
2757                {
2758                    if is_async {
2759                        self.advance(); // async
2760                    }
2761                    let params = self.parse_params()?;
2762                    self.check_params(&params, false, true)?;
2763                    self.expect_punct("=>")?;
2764                    let body = self.parse_arrow_body(is_async)?;
2765                    return Ok(Some(Expr::Function {
2766                        params,
2767                        body,
2768                        is_arrow: true,
2769                        name: None,
2770                        is_generator: false,
2771                        is_async,
2772                        is_method: false,
2773                        span: self.span_from(start),
2774                    }));
2775                }
2776            }
2777        }
2778        Ok(None)
2779    }
2780
2781    fn parse_arrow_body(&mut self, is_async: bool) -> Result<FnBody, String> {
2782        let (pg, pa) = (self.in_generator, self.in_async);
2783        self.in_generator = false;
2784        self.in_async = is_async;
2785        let outer_labels = std::mem::take(&mut self.labels);
2786        let outer_strict = self.strict;
2787        let outer_in_function = std::mem::replace(&mut self.in_function, true);
2788        let r = if self.is_punct("{") {
2789            self.advance();
2790            self.strict = outer_strict || self.leading_use_strict(self.pos);
2791            self.parse_block_body().map(FnBody::Block)
2792        } else {
2793            self.parse_assign().map(|e| FnBody::Expr(Box::new(e)))
2794        };
2795        self.in_function = outer_in_function;
2796        self.strict = outer_strict;
2797        self.labels = outer_labels;
2798        self.in_generator = pg;
2799        self.in_async = pa;
2800        r
2801    }
2802
2803    /// Whether the token `n` positions ahead is `=>`.
2804    fn peek_is_arrow_after(&self, n: usize) -> bool {
2805        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
2806    }
2807
2808    /// Index of the `)` matching the `(` at `open`, skipping nested brackets.
2809    fn matching_paren(&self, open: usize) -> Option<usize> {
2810        let mut depth = 0i32;
2811        let mut i = open;
2812        while i < self.toks.len() {
2813            match &self.toks[i].tok {
2814                Tok::Punct(p) if p == "(" || p == "[" || p == "{" => depth += 1,
2815                Tok::Punct(p) if p == ")" || p == "]" || p == "}" => {
2816                    depth -= 1;
2817                    if depth == 0 {
2818                        return Some(i);
2819                    }
2820                }
2821                Tok::Eof => return None,
2822                _ => {}
2823            }
2824            i += 1;
2825        }
2826        None
2827    }
2828}
2829
2830/// A parser over a template-literal `${...}` field's raw source. `base` is the
2831/// field's byte offset in the enclosing script, so the spans recorded inside it
2832/// index that script; `None` records none.
2833fn field_parser(src: &str, base: Option<u32>) -> Result<Parser, String> {
2834    let mut toks = lex(src)?;
2835    for t in &mut toks {
2836        t.start += base.unwrap_or(0);
2837        t.end += base.unwrap_or(0);
2838        if let Tok::Template { expr_at, .. } = &mut t.tok {
2839            for at in expr_at {
2840                *at += base.unwrap_or(0);
2841            }
2842        }
2843    }
2844    Ok(Parser {
2845        toks,
2846        pos: 0,
2847        in_generator: false,
2848        in_async: false,
2849        no_in: false,
2850        class_scopes: Vec::new(),
2851        labels: Vec::new(),
2852        strict: false,
2853        super_ok: false,
2854        in_function: true,
2855        cover_init: Vec::new(),
2856        in_binding: false,
2857        bound_at: Vec::new(),
2858        spans: base.is_some(),
2859        module: false,
2860    })
2861}