Skip to main content

js_parse/
ast.rs

1//! The ECMAScript 2025 abstract syntax tree.
2//!
3//! The tree is a straightforward Box/Vec tree: the compiler (M2) walks it once
4//! per function body and immediately lowers it to bytecode, so an arena or
5//! visitor infrastructure would not pay for itself yet.
6//!
7//! Naming follows the specification: `Script`/`Module` bodies, `StatementListItem`
8//! (a statement or a declaration), `BindingIdentifier`, `AssignmentTarget`,
9//! `PropertyDefinition`, `ClassStaticBlock`, … Where the spec covers two
10//! productions with one node (a function declaration and a function expression,
11//! a script and a module), the node carries a discriminant instead of being
12//! duplicated.
13
14use crate::token::{Position, Punct, Span};
15use std::fmt;
16
17/// A whole program: a script or a module.
18#[derive(Debug, Clone, PartialEq)]
19pub struct Program {
20    /// Script or module.
21    pub kind: ProgramKind,
22    /// Top-level statements (`ScriptBody` / `ModuleItemList`).
23    pub body: Vec<Stmt>,
24    /// Whole-source range.
25    pub span: Span,
26    /// Whether the program is strict (modules always are).
27    pub strict: bool,
28}
29
30/// Which grammar production a [`Program`] is.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ProgramKind {
33    /// `Script`
34    Script,
35    /// `Module`
36    Module,
37}
38
39/// An identifier (binding, reference, label or private name).
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Ident {
42    /// Name as written, escapes already decoded.
43    pub name: String,
44    /// Source range.
45    pub span: Span,
46}
47
48impl Ident {
49    /// Shorthand for tests.
50    pub fn new(name: impl Into<String>) -> Ident {
51        Ident {
52            name: name.into(),
53            span: Span::default(),
54        }
55    }
56}
57
58impl fmt::Display for Ident {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str(&self.name)
61    }
62}
63
64// ---------------------------------------------------------------------------
65// Statements
66// ---------------------------------------------------------------------------
67
68/// A statement or declaration.
69#[derive(Debug, Clone, PartialEq)]
70pub struct Stmt {
71    /// Statement payload.
72    pub kind: StmtKind,
73    /// Source range.
74    pub span: Span,
75}
76
77impl Stmt {
78    /// Build a statement node.
79    pub fn new(kind: StmtKind, span: Span) -> Stmt {
80        Stmt { kind, span }
81    }
82
83    /// Whether this is an empty statement (`;`) or a block containing only
84    /// empty declarations, which ASI treats specially.
85    pub fn is_empty(&self) -> bool {
86        matches!(self.kind, StmtKind::Empty)
87    }
88}
89
90/// Statement and declaration nodes (`StatementListItem`).
91#[derive(Debug, Clone, PartialEq)]
92pub enum StmtKind {
93    /// `;`
94    Empty,
95    /// `{ ... }`
96    Block(Vec<Stmt>),
97    /// `expr;`
98    Expr(Box<Expr>),
99    /// `if (test) cons else alt`
100    If {
101        /// Condition.
102        test: Box<Expr>,
103        /// Then branch.
104        cons: Box<Stmt>,
105        /// Else branch.
106        alt: Option<Box<Stmt>>,
107    },
108    /// `do body while (test);`
109    DoWhile {
110        /// Loop body.
111        body: Box<Stmt>,
112        /// Loop condition.
113        test: Box<Expr>,
114    },
115    /// `while (test) body`
116    While {
117        /// Loop condition.
118        test: Box<Expr>,
119        /// Loop body.
120        body: Box<Stmt>,
121    },
122    /// `for (init; test; update) body`
123    For {
124        /// `null` for `for (;;)`, otherwise a var/let/const declaration or an
125        /// expression.
126        init: Option<ForInit>,
127        /// Loop condition.
128        test: Option<Box<Expr>>,
129        /// Per-iteration update expression.
130        update: Option<Box<Expr>>,
131        /// Loop body.
132        body: Box<Stmt>,
133    },
134    /// `for (decl|lhs in expr) body`
135    ForIn {
136        /// Left-hand side.
137        left: ForHead,
138        /// Enumerated object.
139        right: Box<Expr>,
140        /// Loop body.
141        body: Box<Stmt>,
142    },
143    /// `for (decl|lhs of expr) body`, plus `for await (…)`
144    ForOf {
145        /// Whether `await` was present.
146        is_await: bool,
147        /// Left-hand side.
148        left: ForHead,
149        /// Iterated value.
150        right: Box<Expr>,
151        /// Loop body.
152        body: Box<Stmt>,
153    },
154    /// `continue;` / `continue label;`
155    Continue(Option<Ident>),
156    /// `break;` / `break label;`
157    Break(Option<Ident>),
158    /// `return;` / `return expr;`
159    Return(Option<Box<Expr>>),
160    /// `with (obj) body`
161    With {
162        /// Object to put on the scope chain.
163        object: Box<Expr>,
164        /// Statement executed inside the `with`.
165        body: Box<Stmt>,
166    },
167    /// `label: stmt`
168    Labeled {
169        /// Label name.
170        label: Ident,
171        /// Labelled statement.
172        body: Box<Stmt>,
173    },
174    /// `switch (disc) { cases }`
175    Switch {
176        /// Discriminant.
177        discriminant: Box<Expr>,
178        /// Cases in source order.
179        cases: Vec<SwitchCase>,
180    },
181    /// `throw expr;`
182    Throw(Box<Expr>),
183    /// `try { } catch (e) { } finally { }`
184    Try {
185        /// Guarded block.
186        block: Vec<Stmt>,
187        /// Catch clause, if present.
188        handler: Option<CatchClause>,
189        /// Finalizer block, if present.
190        finalizer: Option<Vec<Stmt>>,
191    },
192    /// `debugger;`
193    Debugger,
194    /// `var`/`let`/`const` declaration.
195    VarDecl(VarDecl),
196    /// `function` declaration.
197    FuncDecl(Box<Function>),
198    /// `class` declaration.
199    ClassDecl(Box<Class>),
200    /// `import` declaration (modules only).
201    Import(Box<ImportDecl>),
202    /// `export` declaration (modules only).
203    Export(Box<ExportDecl>),
204}
205
206/// One `case`/`default` clause.
207#[derive(Debug, Clone, PartialEq)]
208pub struct SwitchCase {
209    /// Case selector; `None` for `default`.
210    pub test: Option<Box<Expr>>,
211    /// Statements of the clause.
212    pub body: Vec<Stmt>,
213    /// Source range of the whole clause.
214    pub span: Span,
215}
216
217/// The `catch` half of a `try` statement.
218#[derive(Debug, Clone, PartialEq)]
219pub struct CatchClause {
220    /// Bound error, if any (`catch { }` has none).
221    pub param: Option<Pattern>,
222    /// Handler body.
223    pub body: Vec<Stmt>,
224    /// Source range.
225    pub span: Span,
226}
227
228/// The `init` slot of a classic `for` statement.
229#[derive(Debug, Clone, PartialEq)]
230pub enum ForInit {
231    /// `for (var i = 0; …)`
232    VarDecl(VarDecl),
233    /// `for (i = 0; …)`
234    Expr(Box<Expr>),
235}
236
237/// The left-hand side of a `for-in`/`for-of` head.
238#[derive(Debug, Clone, PartialEq)]
239pub enum ForHead {
240    /// `for (let x of …)`, including single-declarator declarations.
241    VarDecl(VarDecl),
242    /// `for (x of …)`, `for ([a, b] of …)`, `for (obj.x of …)`.
243    Assign(Box<Pattern>),
244}
245
246/// `var`/`let`/`const`.
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248pub enum VarDeclKind {
249    /// `var`
250    Var,
251    /// `let`
252    Let,
253    /// `const`
254    Const,
255    /// `using`
256    ///
257    /// A lexical binding whose value is disposed at the end of the enclosing block. The
258    /// await form is a separate variant so that the await-ness travels with the
259    /// declaration the way the other keywords do.
260    Using,
261    /// `await using`
262    AwaitUsing,
263}
264
265impl VarDeclKind {
266    /// The keyword.
267    pub fn as_str(self) -> &'static str {
268        match self {
269            VarDeclKind::Var => "var",
270            VarDeclKind::Let => "let",
271            VarDeclKind::Const => "const",
272            // A message that uses this only names the binding kind, and `await using` is
273            // still a `using`.
274            VarDeclKind::Using | VarDeclKind::AwaitUsing => "using",
275        }
276    }
277
278    /// Whether the declaration is block-scoped.
279    pub fn is_lexical(self) -> bool {
280        !matches!(self, VarDeclKind::Var)
281    }
282
283    /// Whether this declaration disposes its binding at the end of the block.
284    pub fn is_using(self) -> bool {
285        matches!(self, VarDeclKind::Using | VarDeclKind::AwaitUsing)
286    }
287
288    /// Whether the disposal is awaited.
289    pub fn is_await_using(self) -> bool {
290        matches!(self, VarDeclKind::AwaitUsing)
291    }
292}
293
294/// A declaration statement, with all of its declarators.
295#[derive(Debug, Clone, PartialEq)]
296pub struct VarDecl {
297    /// `var`, `let` or `const`.
298    pub kind: VarDeclKind,
299    /// Declarators in source order.
300    pub declarators: Vec<Declarator>,
301    /// Source range.
302    pub span: Span,
303}
304
305/// One `pattern = init` declarator.
306#[derive(Debug, Clone, PartialEq)]
307pub struct Declarator {
308    /// Bound names.
309    pub target: Pattern,
310    /// Initialiser.
311    pub init: Option<Box<Expr>>,
312    /// Source range.
313    pub span: Span,
314}
315
316// ---------------------------------------------------------------------------
317// Functions and classes
318// ---------------------------------------------------------------------------
319
320/// A function in any of its forms (declaration, expression, arrow, method).
321#[derive(Debug, Clone, PartialEq)]
322pub struct Function {
323    /// Name: required for declarations, optional for expressions and arrows.
324    pub name: Option<Ident>,
325    /// Parameters, in source order; a rest parameter is [`Pattern::Rest`].
326    pub params: Vec<Pattern>,
327    /// Body.
328    pub body: FunctionBody,
329    /// `async`
330    pub is_async: bool,
331    /// `function*` / `*method` / `async function*`
332    pub is_generator: bool,
333    /// Whether the body is strict: either an enclosing strict context or the
334    /// function's own `"use strict"` directive.
335    ///
336    /// Recorded per function because strictness is not a property of the source but of
337    /// the enclosing context: a `"use strict"` inside one function body leaves the code
338    /// after it sloppy, so the compiler cannot infer a body's mode from the program's.
339    pub strict: bool,
340    /// `=>`
341    pub is_arrow: bool,
342    /// Source range.
343    pub span: Span,
344    /// Range of the parameter list, for error messages and `length`.
345    pub params_span: Span,
346}
347
348/// The body of a [`Function`].
349#[derive(Debug, Clone, PartialEq)]
350pub enum FunctionBody {
351    /// `{ … }`
352    Block(Vec<Stmt>),
353    /// An arrow's expression body (no braces).
354    Expr(Box<Expr>),
355}
356
357impl FunctionBody {
358    /// Statements of a block body, if this is one.
359    pub fn statements(&self) -> Option<&[Stmt]> {
360        match self {
361            FunctionBody::Block(body) => Some(body),
362            FunctionBody::Expr(_) => None,
363        }
364    }
365}
366
367/// A class body.
368#[derive(Debug, Clone, PartialEq)]
369pub struct Class {
370    /// Class name: required for declarations, optional for expressions.
371    pub name: Option<Ident>,
372    /// `extends` clause.
373    pub super_class: Option<Box<Expr>>,
374    /// Members, in source order.
375    pub elements: Vec<ClassElement>,
376    /// Source range.
377    pub span: Span,
378    /// The closing `}` of the body.
379    ///
380    /// A class that writes no constructor still gets one, and the reference creates that
381    /// synthetic function *at* the closing brace: `js_parse_class_default_ctor` runs with
382    /// the `}` as its current token and hands `s->token.ptr` to `js_new_function_def`. The
383    /// position is the function's own `source_pos`, which is the first entry of its
384    /// line table — so `class B extends BigInt {}` constructed as `new B(1)` reports its
385    /// frame at the `}`, not at `class`. `span.end` cannot stand in: it is one *past* the
386    /// brace, and the brace may be the last character of a line.
387    pub body_end: Position,
388}
389
390/// One member of a class body.
391#[derive(Debug, Clone, PartialEq)]
392pub enum ClassElement {
393    /// A method (`constructor`, ordinary, `get`, `set`, generator or async).
394    Method {
395        /// Property key.
396        key: PropName,
397        /// `static`
398        is_static: bool,
399        /// Which kind of method this is.
400        kind: MethodKind,
401        /// The method itself.
402        func: Box<Function>,
403        /// Source range.
404        span: Span,
405    },
406    /// A field (`x = 1`, `#x`, `static x`).
407    Field {
408        /// Property key.
409        key: PropName,
410        /// `static`
411        is_static: bool,
412        /// Initialiser expression.
413        value: Option<Box<Expr>>,
414        /// Source range.
415        span: Span,
416    },
417    /// `static { … }`
418    StaticBlock {
419        /// Block body.
420        body: Vec<Stmt>,
421        /// Position of the opening `{`, which is where the reference puts the function it
422        /// compiles the body into — the seed for the block's line table.
423        body_start: Position,
424        /// Source range.
425        span: Span,
426    },
427}
428
429/// Which kind of method a class member or object literal property defines.
430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431pub enum MethodKind {
432    /// `constructor`
433    Constructor,
434    /// An ordinary method.
435    Method,
436    /// `get name()`
437    Get,
438    /// `set name(v)`
439    Set,
440}
441
442/// A property key.
443#[derive(Debug, Clone, PartialEq)]
444pub enum PropName {
445    /// A bare identifier, string or numeric key. The variant records which
446    /// spelling was used, because `{ 1e2: x }` needs the numeric value while
447    /// `{ "1e2": x }` needs the string.
448    Literal(PropKey),
449    /// `[expr]`
450    Computed(Box<Expr>),
451    /// `#name` (classes only).
452    Private(Ident),
453}
454
455impl PropName {
456    /// Static name of the key, when it is not computed.
457    pub fn static_name(&self) -> Option<PropKeyRef<'_>> {
458        match self {
459            PropName::Literal(k) => Some(k.as_ref()),
460            PropName::Private(id) => Some(PropKeyRef::Private(&id.name)),
461            PropName::Computed(_) => None,
462        }
463    }
464}
465
466/// A literal property key.
467#[derive(Debug, Clone, PartialEq)]
468pub enum PropKey {
469    /// `foo` or `"foo"` — identical once the value is interned.
470    Str(String),
471    /// `1`, `1.5`, `0x10` — the numeric value matters for array indexing.
472    Num(f64),
473}
474
475impl PropKey {
476    /// Borrow as [`PropKeyRef`].
477    pub fn as_ref(&self) -> PropKeyRef<'_> {
478        match self {
479            PropKey::Str(s) => PropKeyRef::Str(s),
480            PropKey::Num(n) => PropKeyRef::Num(*n),
481        }
482    }
483}
484
485/// Borrowed view of a [`PropKey`], used by the compiler.
486#[derive(Debug, Clone, Copy, PartialEq)]
487pub enum PropKeyRef<'a> {
488    /// A string key.
489    Str(&'a str),
490    /// A numeric key.
491    Num(f64),
492    /// A private name.
493    Private(&'a str),
494}
495
496// ---------------------------------------------------------------------------
497// Patterns
498// ---------------------------------------------------------------------------
499
500/// A binding pattern or assignment target.
501#[derive(Debug, Clone, PartialEq)]
502pub struct Pattern {
503    /// Pattern payload.
504    pub kind: PatternKind,
505    /// Source range.
506    pub span: Span,
507}
508
509impl Pattern {
510    /// Build a pattern node.
511    pub fn new(kind: PatternKind, span: Span) -> Pattern {
512        Pattern { kind, span }
513    }
514
515    /// Collect every name bound by this pattern, in source order.
516    pub fn bound_names(&self, out: &mut Vec<Ident>) {
517        match &self.kind {
518            PatternKind::Ident(id) => out.push(id.clone()),
519            PatternKind::Array { elements, rest, .. }
520            | PatternKind::Object {
521                properties: elements,
522                rest,
523                ..
524            } => {
525                for element in elements.iter().flatten() {
526                    match element {
527                        PatternElement::Pattern(p) => p.bound_names(out),
528                        PatternElement::Property { value, .. } => value.bound_names(out),
529                    }
530                }
531                if let Some(rest) = rest {
532                    match &**rest {
533                        RestElement::Pattern(p) => p.bound_names(out),
534                        RestElement::Member(m) => m.bound_names(out),
535                    }
536                }
537            }
538            PatternKind::Assign { target, .. } => target.bound_names(out),
539            PatternKind::Rest(target) => target.bound_names(out),
540            PatternKind::Invalid(_) => {}
541            PatternKind::Member(m) => m.bound_names(out),
542        }
543    }
544}
545
546/// Pattern payloads.
547#[derive(Debug, Clone, PartialEq)]
548pub enum PatternKind {
549    /// A binding identifier.
550    Ident(Ident),
551    /// `[a, , b, ...rest]`
552    Array {
553        /// Element patterns; `None` for an elision (`,,`).
554        elements: Vec<Option<PatternElement>>,
555        /// Trailing rest element.
556        rest: Option<Box<RestElement>>,
557    },
558    /// `{ a, b: c, [k]: d, ...rest }`
559    Object {
560        /// Properties, in source order.
561        properties: Vec<Option<PatternElement>>,
562        /// Trailing rest element.
563        rest: Option<Box<RestElement>>,
564    },
565    /// `target = default`
566    Assign {
567        /// Pattern being defaulted.
568        target: Box<Pattern>,
569        /// Default value expression.
570        default: Box<Expr>,
571    },
572    /// `obj.prop` / `obj[k]` — only valid as an assignment target, never as a
573    /// binding pattern.
574    Member(Box<MemberPattern>),
575    /// `...target` — a rest element of a parameter list or pattern.
576    Rest(Box<Pattern>),
577    /// An assignment target that is not assignable (`a() = 1`). QuickJS rejects
578    /// this at run time rather than at parse time, so the compiler has to raise
579    /// the error while evaluating the expression.
580    Invalid(Box<Expr>),
581}
582
583/// An element of an array or object pattern.
584#[derive(Debug, Clone, PartialEq)]
585pub enum PatternElement {
586    /// A nested pattern (array element, or an object property's value).
587    Pattern(Pattern),
588    /// An object property with an explicit key.
589    Property {
590        /// Property key.
591        key: PropName,
592        /// Bound pattern.
593        value: Pattern,
594        /// Whether the source used shorthand (`{a}` versus `{a: a}`).
595        shorthand: bool,
596        /// Source range.
597        span: Span,
598    },
599}
600
601/// `...` in a pattern.
602#[derive(Debug, Clone, PartialEq)]
603pub enum RestElement {
604    /// `...rest` where `rest` is a binding/assignment pattern.
605    Pattern(Pattern),
606    /// `...[a, b]` style member target inside an assignment pattern.
607    Member(Box<MemberPattern>),
608}
609
610/// A member expression used as an assignment target.
611#[derive(Debug, Clone, PartialEq)]
612pub struct MemberPattern {
613    /// Object being accessed.
614    pub object: Box<Expr>,
615    /// Property selector.
616    pub property: MemberProp,
617    /// Source range.
618    pub span: Span,
619    /// Where the selector punctuator (`.` or `[`) sits, carried over from the
620    /// expression this pattern came from.
621    ///
622    /// A store is blamed on that token, not on the `=` and not on the base object, so
623    /// the compiler needs the position after the expression has been turned into a
624    /// pattern.
625    pub op_pos: Option<Position>,
626}
627
628impl MemberPattern {
629    /// Member targets never bind names; provided so patterns can be walked
630    /// uniformly.
631    pub fn bound_names(&self, _out: &mut Vec<Ident>) {}
632}
633
634// ---------------------------------------------------------------------------
635// Expressions
636// ---------------------------------------------------------------------------
637
638/// An expression.
639#[derive(Debug, Clone, PartialEq)]
640pub struct Expr {
641    /// Expression payload.
642    pub kind: ExprKind,
643    /// Source range.
644    pub span: Span,
645    /// Where the operator or punctuator that produced this node sits.
646    ///
647    /// Stack traces report the position of the token that failed, not the start of
648    /// the enclosing expression: `1 + null[0]` blames the `[`, and `o.foo = 1` blames
649    /// the `.`. `span.start` cannot stand in for it — the base expression starts
650    /// earlier — so the parser records the token here for the node kinds that emit an
651    /// instruction at an operator, and the compiler puts it in the position table.
652    pub op_pos: Option<Position>,
653}
654
655impl Expr {
656    /// Build an expression node.
657    pub fn new(kind: ExprKind, span: Span) -> Expr {
658        Expr {
659            kind,
660            span,
661            op_pos: None,
662        }
663    }
664
665    /// Build an expression node whose failing instruction sits at `pos`.
666    pub fn at_operator(kind: ExprKind, span: Span, pos: Position) -> Expr {
667        Expr {
668            kind,
669            span,
670            op_pos: Some(pos),
671        }
672    }
673
674    /// Strip any `( … )` wrappers, which carry no runtime meaning.
675    pub fn unparen(&self) -> &Expr {
676        let mut expr = self;
677        while let ExprKind::Paren(inner) = &expr.kind {
678            expr = inner;
679        }
680        expr
681    }
682
683    /// Whether this expression is an anonymous function definition, which takes
684    /// its name from the binding it is assigned to (`var f = function(){}`).
685    pub fn is_anonymous_function_definition(&self) -> bool {
686        match &self.kind {
687            ExprKind::Function(f) => f.name.is_none() && !f.is_arrow,
688            // An arrow is anonymous by construction — it has no name of its own to
689            // write — and still takes one from the binding: `var f = () => {}` leaves
690            // `f.name === "f"`, which is what a stack frame prints.
691            ExprKind::Arrow(_) => true,
692            ExprKind::Class(c) => c.name.is_none(),
693            _ => false,
694        }
695    }
696}
697
698/// Expression payloads.
699#[derive(Debug, Clone, PartialEq)]
700pub enum ExprKind {
701    /// An identifier reference (not resolved to a binding yet).
702    Ident(Ident),
703    /// `null`
704    Null,
705    /// `true` / `false`
706    Bool(bool),
707    /// `1.5`
708    Number(f64),
709    /// `1n`
710    BigInt {
711        /// Digits without prefix or separators.
712        digits: String,
713        /// 2, 8, 10 or 16.
714        radix: u32,
715    },
716    /// `"text"`
717    String(String),
718    /// `/pattern/flags`
719    RegExp {
720        /// Pattern source.
721        pattern: String,
722        /// Flag letters.
723        flags: String,
724    },
725    /// `this`
726    This,
727    /// `[a, b, ...c]`
728    Array {
729        /// Elements; `None` for an elision.
730        elements: Vec<Option<ArrayElement>>,
731    },
732    /// `{ a, b: c, ...d }`
733    Object(Vec<ObjectProperty>),
734    /// `function name() {}`
735    Function(Box<Function>),
736    /// `(params) => body`
737    Arrow(Box<Function>),
738    /// `class { }`
739    Class(Box<Class>),
740    /// `` `a${b}c` ``
741    Template(Box<TemplateLiteral>),
742    /// `` tag`a${b}c` ``
743    TaggedTemplate {
744        /// Tag function.
745        tag: Box<Expr>,
746        /// Template parts.
747        quasi: Box<TemplateLiteral>,
748    },
749    /// `a.b`, `a[b]`, `a?.b`, `super.x`
750    Member {
751        /// Base object.
752        object: Box<Expr>,
753        /// Selector.
754        property: MemberProp,
755        /// Whether `?.` was used.
756        optional: bool,
757    },
758    /// `f(args)`
759    Call {
760        /// Callee.
761        callee: Box<Expr>,
762        /// Arguments.
763        arguments: Vec<Expr>,
764        /// Whether `?.()` was used.
765        optional: bool,
766    },
767    /// `new C(args)` / `new C`
768    New {
769        /// Constructor.
770        callee: Box<Expr>,
771        /// Arguments; `None` for `new C` without a list.
772        arguments: Option<Vec<Expr>>,
773    },
774    /// `new.target`
775    NewTarget,
776    /// `import.meta`
777    ImportMeta,
778    /// `import(specifier)`
779    ImportCall(Box<Expr>),
780    /// `super()` — only valid in a derived constructor.
781    SuperCall(Vec<Expr>),
782    /// `super.x` / `super[x]` base (never standalone).
783    SuperProp,
784    /// `op expr`
785    Unary {
786        /// Operator.
787        op: UnaryOp,
788        /// Operand.
789        argument: Box<Expr>,
790    },
791    /// `++x`, `x--`
792    Update {
793        /// Operator.
794        op: UpdateOp,
795        /// Operand.
796        argument: Box<Expr>,
797        /// Whether the operator came before the operand.
798        prefix: bool,
799    },
800    /// `a + b`, `a instanceof b`, `a in b`, …
801    Binary {
802        /// Operator.
803        op: BinaryOp,
804        /// Left operand.
805        left: Box<Expr>,
806        /// Right operand.
807        right: Box<Expr>,
808    },
809    /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
810    /// short-circuit code generation).
811    Logical {
812        /// Operator.
813        op: LogicalOp,
814        /// Left operand.
815        left: Box<Expr>,
816        /// Right operand.
817        right: Box<Expr>,
818    },
819    /// `a ? b : c`
820    Conditional {
821        /// Condition.
822        test: Box<Expr>,
823        /// Consequent.
824        cons: Box<Expr>,
825        /// Alternate.
826        alt: Box<Expr>,
827    },
828    /// `target op= value`
829    Assign {
830        /// Assignment operator.
831        op: AssignOp,
832        /// Assignment target (converted from the cover grammar).
833        target: Box<Pattern>,
834        /// Right-hand side.
835        value: Box<Expr>,
836    },
837    /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
838    /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
839    Paren(Box<Expr>),
840    /// `(a, b, c)`
841    Sequence(Vec<Expr>),
842    /// `yield expr` / `yield* expr`
843    Yield {
844        /// Operand; `None` for `yield;`.
845        argument: Option<Box<Expr>>,
846        /// Whether `yield*` was used.
847        delegate: bool,
848    },
849    /// `await expr`
850    Await(Box<Expr>),
851    /// `...expr` — only valid in call arguments, arrays and object literals.
852    Spread(Box<Expr>),
853    /// A member/call chain that contains at least one `?.`. Compiling the
854    /// wrapper short-circuits the whole spine when a link's base is nullish.
855    OptionalChain(Box<Expr>),
856    /// `#x in obj`
857    PrivateIn {
858        /// Private name.
859        name: Ident,
860        /// Tested object.
861        object: Box<Expr>,
862    },
863}
864
865/// One element of an array literal.
866#[derive(Debug, Clone, PartialEq)]
867pub enum ArrayElement {
868    /// An ordinary element.
869    Expr(Box<Expr>),
870    /// `...iterable`
871    Spread(Box<Expr>),
872}
873
874/// What an object-literal property does with its value.
875///
876/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
877/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
878/// compile to different instructions (`define_field` vs `define_method`), even though
879/// both hold a value on the stack.
880#[derive(Debug, Clone, Copy, PartialEq, Eq)]
881pub enum PropertyKind {
882    /// `key: value` or the `{key}` shorthand — stores a data property.
883    Value,
884    /// `m() {}` — defines a method.
885    Method,
886    /// `get m() {}` — the value is the getter.
887    Get,
888    /// `set m(v) {}` — the value is the setter.
889    Set,
890}
891
892/// One property of an object literal.
893#[derive(Debug, Clone, PartialEq)]
894pub enum ObjectProperty {
895    /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
896    Property {
897        /// Property key.
898        key: PropName,
899        /// Value expression; for `get`/`set` it is the function.
900        value: Box<Expr>,
901        /// Whether this stores a value or defines an accessor/method.
902        kind: PropertyKind,
903        /// Whether the source used shorthand (`{a}` / `{a = 1}`).
904        shorthand: bool,
905        /// Source range.
906        span: Span,
907    },
908    /// `...spread`
909    Spread(Box<Expr>),
910}
911
912/// A template literal: `quasis.len() == expressions.len() + 1`.
913#[derive(Debug, Clone, PartialEq)]
914pub struct TemplateLiteral {
915    /// Literal chunks, in source order.
916    pub quasis: Vec<TemplateChunk>,
917    /// Substitution expressions, in source order.
918    pub expressions: Vec<Expr>,
919}
920
921/// One chunk of a [`TemplateLiteral`].
922#[derive(Debug, Clone, PartialEq, Eq)]
923pub struct TemplateChunk {
924    /// Escape-expanded text; `None` when the chunk has an invalid escape
925    /// sequence (legal in tagged templates only, where it becomes `undefined`).
926    pub cooked: Option<String>,
927    /// Source text, verbatim.
928    pub raw: String,
929    /// Whether this chunk ends with the closing backtick.
930    pub tail: bool,
931}
932
933/// Property selector of a member expression.
934#[derive(Debug, Clone, PartialEq)]
935pub enum MemberProp {
936    /// `.name`
937    Ident(Ident),
938    /// `[expr]`
939    Computed(Box<Expr>),
940    /// `.#name`
941    Private(Ident),
942}
943
944/// Unary operators.
945#[derive(Debug, Clone, Copy, PartialEq, Eq)]
946pub enum UnaryOp {
947    /// `-`
948    Minus,
949    /// `+`
950    Plus,
951    /// `!`
952    Not,
953    /// `~`
954    BitNot,
955    /// `typeof`
956    Typeof,
957    /// `void`
958    Void,
959    /// `delete`
960    Delete,
961}
962
963impl UnaryOp {
964    /// The operator text.
965    pub fn as_str(self) -> &'static str {
966        match self {
967            UnaryOp::Minus => "-",
968            UnaryOp::Plus => "+",
969            UnaryOp::Not => "!",
970            UnaryOp::BitNot => "~",
971            UnaryOp::Typeof => "typeof",
972            UnaryOp::Void => "void",
973            UnaryOp::Delete => "delete",
974        }
975    }
976}
977
978/// `++`/`--`.
979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub enum UpdateOp {
981    /// `++`
982    Increment,
983    /// `--`
984    Decrement,
985}
986
987impl UpdateOp {
988    /// The operator text.
989    pub fn as_str(self) -> &'static str {
990        match self {
991            UpdateOp::Increment => "++",
992            UpdateOp::Decrement => "--",
993        }
994    }
995}
996
997/// Non-short-circuiting binary operators.
998#[derive(Debug, Clone, Copy, PartialEq, Eq)]
999pub enum BinaryOp {
1000    /// `==`
1001    Eq,
1002    /// `!=`
1003    NotEq,
1004    /// `===`
1005    StrictEq,
1006    /// `!==`
1007    StrictNotEq,
1008    /// `<`
1009    Lt,
1010    /// `<=`
1011    LtEq,
1012    /// `>`
1013    Gt,
1014    /// `>=`
1015    GtEq,
1016    /// `<<`
1017    Shl,
1018    /// `>>`
1019    Shr,
1020    /// `>>>`
1021    UShr,
1022    /// `+`
1023    Add,
1024    /// `-`
1025    Sub,
1026    /// `*`
1027    Mul,
1028    /// `/`
1029    Div,
1030    /// `%`
1031    Mod,
1032    /// `**`
1033    Pow,
1034    /// `|`
1035    BitOr,
1036    /// `^`
1037    BitXor,
1038    /// `&`
1039    BitAnd,
1040    /// `in`
1041    In,
1042    /// `instanceof`
1043    Instanceof,
1044}
1045
1046impl BinaryOp {
1047    /// The operator text.
1048    pub fn as_str(self) -> &'static str {
1049        match self {
1050            BinaryOp::Eq => "==",
1051            BinaryOp::NotEq => "!=",
1052            BinaryOp::StrictEq => "===",
1053            BinaryOp::StrictNotEq => "!==",
1054            BinaryOp::Lt => "<",
1055            BinaryOp::LtEq => "<=",
1056            BinaryOp::Gt => ">",
1057            BinaryOp::GtEq => ">=",
1058            BinaryOp::Shl => "<<",
1059            BinaryOp::Shr => ">>",
1060            BinaryOp::UShr => ">>>",
1061            BinaryOp::Add => "+",
1062            BinaryOp::Sub => "-",
1063            BinaryOp::Mul => "*",
1064            BinaryOp::Div => "/",
1065            BinaryOp::Mod => "%",
1066            BinaryOp::Pow => "**",
1067            BinaryOp::BitOr => "|",
1068            BinaryOp::BitXor => "^",
1069            BinaryOp::BitAnd => "&",
1070            BinaryOp::In => "in",
1071            BinaryOp::Instanceof => "instanceof",
1072        }
1073    }
1074
1075    /// Whether the operator is relational (`in`/`instanceof` included), which
1076    /// matters for the `no-in` restriction in `for` heads.
1077    pub fn is_relational(self) -> bool {
1078        matches!(
1079            self,
1080            BinaryOp::Lt
1081                | BinaryOp::LtEq
1082                | BinaryOp::Gt
1083                | BinaryOp::GtEq
1084                | BinaryOp::In
1085                | BinaryOp::Instanceof
1086        )
1087    }
1088}
1089
1090/// Short-circuiting operators.
1091#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1092pub enum LogicalOp {
1093    /// `&&`
1094    And,
1095    /// `||`
1096    Or,
1097    /// `??`
1098    Coalesce,
1099}
1100
1101impl LogicalOp {
1102    /// The operator text.
1103    pub fn as_str(self) -> &'static str {
1104        match self {
1105            LogicalOp::And => "&&",
1106            LogicalOp::Or => "||",
1107            LogicalOp::Coalesce => "??",
1108        }
1109    }
1110}
1111
1112/// Assignment operators.
1113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1114pub enum AssignOp {
1115    /// `=`
1116    Assign,
1117    /// `+=`
1118    Add,
1119    /// `-=`
1120    Sub,
1121    /// `*=`
1122    Mul,
1123    /// `/=`
1124    Div,
1125    /// `%=`
1126    Mod,
1127    /// `**=`
1128    Pow,
1129    /// `<<=`
1130    Shl,
1131    /// `>>=`
1132    Shr,
1133    /// `>>>=`
1134    UShr,
1135    /// `|=`
1136    BitOr,
1137    /// `^=`
1138    BitXor,
1139    /// `&=`
1140    BitAnd,
1141    /// `&&=`
1142    And,
1143    /// `||=`
1144    Or,
1145    /// `??=`
1146    Coalesce,
1147}
1148
1149impl AssignOp {
1150    /// The operator text.
1151    pub fn as_str(self) -> &'static str {
1152        match self {
1153            AssignOp::Assign => "=",
1154            AssignOp::Add => "+=",
1155            AssignOp::Sub => "-=",
1156            AssignOp::Mul => "*=",
1157            AssignOp::Div => "/=",
1158            AssignOp::Mod => "%=",
1159            AssignOp::Pow => "**=",
1160            AssignOp::Shl => "<<=",
1161            AssignOp::Shr => ">>=",
1162            AssignOp::UShr => ">>>=",
1163            AssignOp::BitOr => "|=",
1164            AssignOp::BitXor => "^=",
1165            AssignOp::BitAnd => "&=",
1166            AssignOp::And => "&&=",
1167            AssignOp::Or => "||=",
1168            AssignOp::Coalesce => "??=",
1169        }
1170    }
1171
1172    /// Whether this is a simple `=`.
1173    pub fn is_simple(self) -> bool {
1174        matches!(self, AssignOp::Assign)
1175    }
1176
1177    /// The binary operator a compound assignment implies.
1178    pub fn binary_op(self) -> Option<BinaryOp> {
1179        Some(match self {
1180            AssignOp::Assign => return None,
1181            AssignOp::Add => BinaryOp::Add,
1182            AssignOp::Sub => BinaryOp::Sub,
1183            AssignOp::Mul => BinaryOp::Mul,
1184            AssignOp::Div => BinaryOp::Div,
1185            AssignOp::Mod => BinaryOp::Mod,
1186            AssignOp::Pow => BinaryOp::Pow,
1187            AssignOp::Shl => BinaryOp::Shl,
1188            AssignOp::Shr => BinaryOp::Shr,
1189            AssignOp::UShr => BinaryOp::UShr,
1190            AssignOp::BitOr => BinaryOp::BitOr,
1191            AssignOp::BitXor => BinaryOp::BitXor,
1192            AssignOp::BitAnd => BinaryOp::BitAnd,
1193            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1194        })
1195    }
1196
1197    /// The logical operator a short-circuiting assignment implies.
1198    pub fn logical_op(self) -> Option<LogicalOp> {
1199        match self {
1200            AssignOp::And => Some(LogicalOp::And),
1201            AssignOp::Or => Some(LogicalOp::Or),
1202            AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1203            _ => None,
1204        }
1205    }
1206
1207    /// Map a punctuator to an assignment operator.
1208    pub fn from_punct(p: Punct) -> Option<AssignOp> {
1209        Some(match p {
1210            Punct::Eq => AssignOp::Assign,
1211            Punct::PlusEq => AssignOp::Add,
1212            Punct::MinusEq => AssignOp::Sub,
1213            Punct::StarEq => AssignOp::Mul,
1214            Punct::SlashEq => AssignOp::Div,
1215            Punct::PercentEq => AssignOp::Mod,
1216            Punct::StarStarEq => AssignOp::Pow,
1217            Punct::ShlEq => AssignOp::Shl,
1218            Punct::ShrEq => AssignOp::Shr,
1219            Punct::UShrEq => AssignOp::UShr,
1220            Punct::PipeEq => AssignOp::BitOr,
1221            Punct::CaretEq => AssignOp::BitXor,
1222            Punct::AmpEq => AssignOp::BitAnd,
1223            Punct::AmpAmpEq => AssignOp::And,
1224            Punct::PipePipeEq => AssignOp::Or,
1225            Punct::QuestionQuestionEq => AssignOp::Coalesce,
1226            _ => return None,
1227        })
1228    }
1229}
1230
1231// ---------------------------------------------------------------------------
1232// Modules
1233// ---------------------------------------------------------------------------
1234
1235/// The name on either side of a module binding, which may be a string.
1236#[derive(Debug, Clone, PartialEq, Eq)]
1237pub enum ModuleName {
1238    /// `foo`
1239    Ident(Ident),
1240    /// `"foo bar"`
1241    Str(String),
1242}
1243
1244impl ModuleName {
1245    /// The textual name.
1246    pub fn as_str(&self) -> &str {
1247        match self {
1248            ModuleName::Ident(id) => &id.name,
1249            ModuleName::Str(s) => s,
1250        }
1251    }
1252}
1253
1254/// `import …`
1255#[derive(Debug, Clone, PartialEq)]
1256pub struct ImportDecl {
1257    /// What is imported.
1258    pub specifiers: Vec<ImportSpecifier>,
1259    /// Module specifier string.
1260    pub source: String,
1261    /// `with { type: "json" }` attributes.
1262    pub attributes: Vec<ImportAttribute>,
1263    /// Source range.
1264    pub span: Span,
1265}
1266
1267/// One entry of an import clause.
1268#[derive(Debug, Clone, PartialEq)]
1269pub enum ImportSpecifier {
1270    /// `import d from "m"`
1271    Default(Ident),
1272    /// `import * as ns from "m"`
1273    Namespace(Ident),
1274    /// `import { a, b as c } from "m"`
1275    Named {
1276        /// Name in the exporting module.
1277        imported: ModuleName,
1278        /// Local binding.
1279        local: Ident,
1280    },
1281}
1282
1283/// `with { key: "value" }`
1284#[derive(Debug, Clone, PartialEq)]
1285pub struct ImportAttribute {
1286    /// Attribute key.
1287    pub key: String,
1288    /// Attribute value.
1289    pub value: String,
1290    /// Source range.
1291    pub span: Span,
1292}
1293
1294/// `export …`
1295#[derive(Debug, Clone, PartialEq)]
1296pub struct ExportDecl {
1297    /// What is exported.
1298    pub kind: ExportKind,
1299    /// Source range.
1300    pub span: Span,
1301}
1302
1303/// The variants of an export declaration.
1304#[derive(Debug, Clone, PartialEq)]
1305pub enum ExportKind {
1306    /// `export var/let/const/function/class …`
1307    Declaration(Box<Stmt>),
1308    /// `export default expr` / `export default function …` / `export default class …`
1309    Default(Box<Expr>),
1310    /// `export { a, b as c }` / `export { a } from "m"`
1311    Named {
1312        /// Exported bindings.
1313        specifiers: Vec<ExportSpecifier>,
1314        /// Re-export source.
1315        source: Option<String>,
1316        /// Import attributes for the `from` clause.
1317        attributes: Vec<ImportAttribute>,
1318    },
1319    /// `export * from "m"` / `export * as ns from "m"`
1320    All {
1321        /// Re-export source.
1322        source: String,
1323        /// `as ns`, when present.
1324        exported: Option<ModuleName>,
1325        /// Import attributes for the `from` clause.
1326        attributes: Vec<ImportAttribute>,
1327    },
1328}
1329
1330/// One entry of an `export { … }` clause.
1331#[derive(Debug, Clone, PartialEq)]
1332pub struct ExportSpecifier {
1333    /// Local name (or the name in the source module).
1334    pub local: ModuleName,
1335    /// Exported name.
1336    pub exported: ModuleName,
1337    /// Source range.
1338    pub span: Span,
1339}