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
390impl Class {
391    /// Whether the class body itself defines `name`, which an anonymous class then keeps.
392    ///
393    /// `class { static name(){} }` has an own `name` property, so assigning one from the
394    /// binding would either fail or be shadowed — `NamedEvaluation` checks for it and
395    /// leaves the class alone.
396    pub fn has_own_name(&self) -> bool {
397        self.elements.iter().any(|element| match element {
398            ClassElement::Method { key, is_static, .. }
399            | ClassElement::Field { key, is_static, .. } => {
400                *is_static
401                    && matches!(key.static_name(), Some(PropKeyRef::Str(name)) if name == "name")
402            }
403            ClassElement::StaticBlock { .. } => false,
404        })
405    }
406}
407
408/// The binding a computed field key is stored in.
409///
410/// `js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, n)` produces
411/// `computed_field0`/`computed_field_static0`; the dump prints them as `<computed_field>0` and
412/// `<computed_field_static>0`, which is the reference's own bracket convention for a hidden
413/// name.
414pub fn computed_field_binding(index: usize, is_static: bool) -> String {
415    if is_static {
416        format!("<computed_field_static>{index}")
417    } else {
418        format!("<computed_field>{index}")
419    }
420}
421
422/// One member of a class body.
423#[derive(Debug, Clone, PartialEq)]
424pub enum ClassElement {
425    /// A method (`constructor`, ordinary, `get`, `set`, generator or async).
426    Method {
427        /// Property key.
428        key: PropName,
429        /// `static`
430        is_static: bool,
431        /// Which kind of method this is.
432        kind: MethodKind,
433        /// The method itself.
434        func: Box<Function>,
435        /// Source range.
436        span: Span,
437    },
438    /// A field (`x = 1`, `#x`, `static x`).
439    Field {
440        /// Property key.
441        key: PropName,
442        /// `static`
443        is_static: bool,
444        /// Initialiser expression.
445        value: Option<Box<Expr>>,
446        /// Source range.
447        span: Span,
448    },
449    /// `static { … }`
450    StaticBlock {
451        /// Block body.
452        body: Vec<Stmt>,
453        /// Position of the opening `{`, which is where the reference puts the function it
454        /// compiles the body into — the seed for the block's line table.
455        body_start: Position,
456        /// Source range.
457        span: Span,
458    },
459}
460
461/// Which kind of method a class member or object literal property defines.
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
463pub enum MethodKind {
464    /// `constructor`
465    Constructor,
466    /// An ordinary method.
467    Method,
468    /// `get name()`
469    Get,
470    /// `set name(v)`
471    Set,
472}
473
474/// A property key.
475#[derive(Debug, Clone, PartialEq)]
476pub enum PropName {
477    /// A bare identifier, string or numeric key. The variant records which
478    /// spelling was used, because `{ 1e2: x }` needs the numeric value while
479    /// `{ "1e2": x }` needs the string.
480    Literal(PropKey),
481    /// `[expr]`
482    Computed(Box<Expr>),
483    /// `#name` (classes only).
484    Private(Ident),
485}
486
487impl PropName {
488    /// Static name of the key, when it is not computed.
489    pub fn static_name(&self) -> Option<PropKeyRef<'_>> {
490        match self {
491            PropName::Literal(k) => Some(k.as_ref()),
492            PropName::Private(id) => Some(PropKeyRef::Private(&id.name)),
493            PropName::Computed(_) => None,
494        }
495    }
496}
497
498/// A literal property key.
499#[derive(Debug, Clone, PartialEq)]
500pub enum PropKey {
501    /// `foo` or `"foo"` — identical once the value is interned.
502    Str(String),
503    /// `1`, `1.5`, `0x10` — the numeric value matters for array indexing.
504    Num(f64),
505}
506
507impl PropKey {
508    /// Borrow as [`PropKeyRef`].
509    pub fn as_ref(&self) -> PropKeyRef<'_> {
510        match self {
511            PropKey::Str(s) => PropKeyRef::Str(s),
512            PropKey::Num(n) => PropKeyRef::Num(*n),
513        }
514    }
515}
516
517/// Borrowed view of a [`PropKey`], used by the compiler.
518#[derive(Debug, Clone, Copy, PartialEq)]
519pub enum PropKeyRef<'a> {
520    /// A string key.
521    Str(&'a str),
522    /// A numeric key.
523    Num(f64),
524    /// A private name.
525    Private(&'a str),
526}
527
528// ---------------------------------------------------------------------------
529// Patterns
530// ---------------------------------------------------------------------------
531
532/// A binding pattern or assignment target.
533#[derive(Debug, Clone, PartialEq)]
534pub struct Pattern {
535    /// Pattern payload.
536    pub kind: PatternKind,
537    /// Source range.
538    pub span: Span,
539}
540
541impl Pattern {
542    /// Build a pattern node.
543    pub fn new(kind: PatternKind, span: Span) -> Pattern {
544        Pattern { kind, span }
545    }
546
547    /// Collect every name bound by this pattern, in source order.
548    pub fn bound_names(&self, out: &mut Vec<Ident>) {
549        match &self.kind {
550            PatternKind::Ident(id) => out.push(id.clone()),
551            PatternKind::Array { elements, rest, .. }
552            | PatternKind::Object {
553                properties: elements,
554                rest,
555                ..
556            } => {
557                for element in elements.iter().flatten() {
558                    match element {
559                        PatternElement::Pattern(p) => p.bound_names(out),
560                        PatternElement::Property { value, .. } => value.bound_names(out),
561                    }
562                }
563                if let Some(rest) = rest {
564                    match &**rest {
565                        RestElement::Pattern(p) => p.bound_names(out),
566                        RestElement::Member(m) => m.bound_names(out),
567                    }
568                }
569            }
570            PatternKind::Assign { target, .. } => target.bound_names(out),
571            PatternKind::Rest(target) => target.bound_names(out),
572            PatternKind::Invalid(_) => {}
573            PatternKind::Member(m) => m.bound_names(out),
574        }
575    }
576}
577
578/// Pattern payloads.
579#[derive(Debug, Clone, PartialEq)]
580pub enum PatternKind {
581    /// A binding identifier.
582    Ident(Ident),
583    /// `[a, , b, ...rest]`
584    Array {
585        /// Element patterns; `None` for an elision (`,,`).
586        elements: Vec<Option<PatternElement>>,
587        /// Trailing rest element.
588        rest: Option<Box<RestElement>>,
589    },
590    /// `{ a, b: c, [k]: d, ...rest }`
591    Object {
592        /// Properties, in source order.
593        properties: Vec<Option<PatternElement>>,
594        /// Trailing rest element.
595        rest: Option<Box<RestElement>>,
596    },
597    /// `target = default`
598    Assign {
599        /// Pattern being defaulted.
600        target: Box<Pattern>,
601        /// Default value expression.
602        default: Box<Expr>,
603    },
604    /// `obj.prop` / `obj[k]` — only valid as an assignment target, never as a
605    /// binding pattern.
606    Member(Box<MemberPattern>),
607    /// `...target` — a rest element of a parameter list or pattern.
608    Rest(Box<Pattern>),
609    /// An assignment target that is not assignable (`a() = 1`). QuickJS rejects
610    /// this at run time rather than at parse time, so the compiler has to raise
611    /// the error while evaluating the expression.
612    Invalid(Box<Expr>),
613}
614
615/// An element of an array or object pattern.
616#[derive(Debug, Clone, PartialEq)]
617pub enum PatternElement {
618    /// A nested pattern (array element, or an object property's value).
619    Pattern(Pattern),
620    /// An object property with an explicit key.
621    Property {
622        /// Property key.
623        key: PropName,
624        /// Bound pattern.
625        value: Pattern,
626        /// Whether the source used shorthand (`{a}` versus `{a: a}`).
627        shorthand: bool,
628        /// Source range.
629        span: Span,
630    },
631}
632
633/// `...` in a pattern.
634#[derive(Debug, Clone, PartialEq)]
635pub enum RestElement {
636    /// `...rest` where `rest` is a binding/assignment pattern.
637    Pattern(Pattern),
638    /// `...[a, b]` style member target inside an assignment pattern.
639    Member(Box<MemberPattern>),
640}
641
642/// A member expression used as an assignment target.
643#[derive(Debug, Clone, PartialEq)]
644pub struct MemberPattern {
645    /// Object being accessed.
646    pub object: Box<Expr>,
647    /// Property selector.
648    pub property: MemberProp,
649    /// Source range.
650    pub span: Span,
651    /// Where the selector punctuator (`.` or `[`) sits, carried over from the
652    /// expression this pattern came from.
653    ///
654    /// A store is blamed on that token, not on the `=` and not on the base object, so
655    /// the compiler needs the position after the expression has been turned into a
656    /// pattern.
657    pub op_pos: Option<Position>,
658}
659
660impl MemberPattern {
661    /// Member targets never bind names; provided so patterns can be walked
662    /// uniformly.
663    pub fn bound_names(&self, _out: &mut Vec<Ident>) {}
664}
665
666// ---------------------------------------------------------------------------
667// Expressions
668// ---------------------------------------------------------------------------
669
670/// An expression.
671#[derive(Debug, Clone, PartialEq)]
672pub struct Expr {
673    /// Expression payload.
674    pub kind: ExprKind,
675    /// Source range.
676    pub span: Span,
677    /// Where the operator or punctuator that produced this node sits.
678    ///
679    /// Stack traces report the position of the token that failed, not the start of
680    /// the enclosing expression: `1 + null[0]` blames the `[`, and `o.foo = 1` blames
681    /// the `.`. `span.start` cannot stand in for it — the base expression starts
682    /// earlier — so the parser records the token here for the node kinds that emit an
683    /// instruction at an operator, and the compiler puts it in the position table.
684    pub op_pos: Option<Position>,
685}
686
687impl Expr {
688    /// Build an expression node.
689    pub fn new(kind: ExprKind, span: Span) -> Expr {
690        Expr {
691            kind,
692            span,
693            op_pos: None,
694        }
695    }
696
697    /// Build an expression node whose failing instruction sits at `pos`.
698    pub fn at_operator(kind: ExprKind, span: Span, pos: Position) -> Expr {
699        Expr {
700            kind,
701            span,
702            op_pos: Some(pos),
703        }
704    }
705
706    /// Strip any `( … )` wrappers, which carry no runtime meaning.
707    pub fn unparen(&self) -> &Expr {
708        let mut expr = self;
709        while let ExprKind::Paren(inner) = &expr.kind {
710            expr = inner;
711        }
712        expr
713    }
714
715    /// Whether this expression is an anonymous function definition, which takes
716    /// its name from the binding it is assigned to (`var f = function(){}`).
717    ///
718    /// Parentheses are looked through: `[f = (function(){})] = []` still names the
719    /// function `f`. A sequence expression does **not** — `(0, function(){})` is an
720    /// anonymous function used as a value, and `NamedEvaluation` only reaches a form
721    /// that *is* a function definition.
722    pub fn is_anonymous_function_definition(&self) -> bool {
723        match &self.unparen().kind {
724            ExprKind::Function(f) => f.name.is_none() && !f.is_arrow,
725            // An arrow is anonymous by construction — it has no name of its own to
726            // write — and still takes one from the binding: `var f = () => {}` leaves
727            // `f.name === "f"`, which is what a stack frame prints.
728            ExprKind::Arrow(_) => true,
729            // A class that already has an own `name` — `class { static name(){} }` — keeps
730            // it: `NamedEvaluation` only sets the name when the class has none.
731            ExprKind::Class(c) => c.name.is_none() && !c.has_own_name(),
732            _ => false,
733        }
734    }
735}
736
737/// Expression payloads.
738#[derive(Debug, Clone, PartialEq)]
739pub enum ExprKind {
740    /// An identifier reference (not resolved to a binding yet).
741    Ident(Ident),
742    /// `null`
743    Null,
744    /// `true` / `false`
745    Bool(bool),
746    /// `1.5`
747    Number(f64),
748    /// `1n`
749    BigInt {
750        /// Digits without prefix or separators.
751        digits: String,
752        /// 2, 8, 10 or 16.
753        radix: u32,
754    },
755    /// `"text"`
756    String(String),
757    /// `/pattern/flags`
758    RegExp {
759        /// Pattern source.
760        pattern: String,
761        /// Flag letters.
762        flags: String,
763    },
764    /// `this`
765    This,
766    /// `[a, b, ...c]`
767    Array {
768        /// Elements; `None` for an elision.
769        elements: Vec<Option<ArrayElement>>,
770    },
771    /// `{ a, b: c, ...d }`
772    Object(Vec<ObjectProperty>),
773    /// `function name() {}`
774    Function(Box<Function>),
775    /// `(params) => body`
776    Arrow(Box<Function>),
777    /// `class { }`
778    Class(Box<Class>),
779    /// `` `a${b}c` ``
780    Template(Box<TemplateLiteral>),
781    /// `` tag`a${b}c` ``
782    TaggedTemplate {
783        /// Tag function.
784        tag: Box<Expr>,
785        /// Template parts.
786        quasi: Box<TemplateLiteral>,
787    },
788    /// `a.b`, `a[b]`, `a?.b`, `super.x`
789    Member {
790        /// Base object.
791        object: Box<Expr>,
792        /// Selector.
793        property: MemberProp,
794        /// Whether `?.` was used.
795        optional: bool,
796    },
797    /// `f(args)`
798    Call {
799        /// Callee.
800        callee: Box<Expr>,
801        /// Arguments.
802        arguments: Vec<Expr>,
803        /// Whether `?.()` was used.
804        optional: bool,
805    },
806    /// `new C(args)` / `new C`
807    New {
808        /// Constructor.
809        callee: Box<Expr>,
810        /// Arguments; `None` for `new C` without a list.
811        arguments: Option<Vec<Expr>>,
812    },
813    /// `new.target`
814    NewTarget,
815    /// `import.meta`
816    ImportMeta,
817    /// `import(specifier)`
818    ImportCall(Box<Expr>),
819    /// `super()` — only valid in a derived constructor.
820    SuperCall(Vec<Expr>),
821    /// `super.x` / `super[x]` base (never standalone).
822    SuperProp,
823    /// `op expr`
824    Unary {
825        /// Operator.
826        op: UnaryOp,
827        /// Operand.
828        argument: Box<Expr>,
829    },
830    /// `++x`, `x--`
831    Update {
832        /// Operator.
833        op: UpdateOp,
834        /// Operand.
835        argument: Box<Expr>,
836        /// Whether the operator came before the operand.
837        prefix: bool,
838    },
839    /// `a + b`, `a instanceof b`, `a in b`, …
840    Binary {
841        /// Operator.
842        op: BinaryOp,
843        /// Left operand.
844        left: Box<Expr>,
845        /// Right operand.
846        right: Box<Expr>,
847    },
848    /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
849    /// short-circuit code generation).
850    Logical {
851        /// Operator.
852        op: LogicalOp,
853        /// Left operand.
854        left: Box<Expr>,
855        /// Right operand.
856        right: Box<Expr>,
857    },
858    /// `a ? b : c`
859    Conditional {
860        /// Condition.
861        test: Box<Expr>,
862        /// Consequent.
863        cons: Box<Expr>,
864        /// Alternate.
865        alt: Box<Expr>,
866    },
867    /// `target op= value`
868    Assign {
869        /// Assignment operator.
870        op: AssignOp,
871        /// Assignment target (converted from the cover grammar).
872        target: Box<Pattern>,
873        /// Right-hand side.
874        value: Box<Expr>,
875    },
876    /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
877    /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
878    Paren(Box<Expr>),
879    /// `(a, b, c)`
880    Sequence(Vec<Expr>),
881    /// `yield expr` / `yield* expr`
882    Yield {
883        /// Operand; `None` for `yield;`.
884        argument: Option<Box<Expr>>,
885        /// Whether `yield*` was used.
886        delegate: bool,
887    },
888    /// `await expr`
889    Await(Box<Expr>),
890    /// `...expr` — only valid in call arguments, arrays and object literals.
891    Spread(Box<Expr>),
892    /// A member/call chain that contains at least one `?.`. Compiling the
893    /// wrapper short-circuits the whole spine when a link's base is nullish.
894    OptionalChain(Box<Expr>),
895    /// `#x in obj`
896    PrivateIn {
897        /// Private name.
898        name: Ident,
899        /// Tested object.
900        object: Box<Expr>,
901    },
902}
903
904/// One element of an array literal.
905#[derive(Debug, Clone, PartialEq)]
906pub enum ArrayElement {
907    /// An ordinary element.
908    Expr(Box<Expr>),
909    /// `...iterable`
910    Spread(Box<Expr>),
911}
912
913/// What an object-literal property does with its value.
914///
915/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
916/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
917/// compile to different instructions (`define_field` vs `define_method`), even though
918/// both hold a value on the stack.
919#[derive(Debug, Clone, Copy, PartialEq, Eq)]
920pub enum PropertyKind {
921    /// `key: value` or the `{key}` shorthand — stores a data property.
922    Value,
923    /// `m() {}` — defines a method.
924    Method,
925    /// `get m() {}` — the value is the getter.
926    Get,
927    /// `set m(v) {}` — the value is the setter.
928    Set,
929}
930
931/// One property of an object literal.
932#[derive(Debug, Clone, PartialEq)]
933pub enum ObjectProperty {
934    /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
935    Property {
936        /// Property key.
937        key: PropName,
938        /// Value expression; for `get`/`set` it is the function.
939        value: Box<Expr>,
940        /// Whether this stores a value or defines an accessor/method.
941        kind: PropertyKind,
942        /// Whether the source used shorthand (`{a}` / `{a = 1}`).
943        shorthand: bool,
944        /// Source range.
945        span: Span,
946    },
947    /// `...spread`
948    Spread(Box<Expr>),
949}
950
951/// A template literal: `quasis.len() == expressions.len() + 1`.
952#[derive(Debug, Clone, PartialEq)]
953pub struct TemplateLiteral {
954    /// Literal chunks, in source order.
955    pub quasis: Vec<TemplateChunk>,
956    /// Substitution expressions, in source order.
957    pub expressions: Vec<Expr>,
958}
959
960/// One chunk of a [`TemplateLiteral`].
961#[derive(Debug, Clone, PartialEq, Eq)]
962pub struct TemplateChunk {
963    /// Escape-expanded text; `None` when the chunk has an invalid escape
964    /// sequence (legal in tagged templates only, where it becomes `undefined`).
965    pub cooked: Option<String>,
966    /// Source text, verbatim.
967    pub raw: String,
968    /// Whether this chunk ends with the closing backtick.
969    pub tail: bool,
970}
971
972/// Property selector of a member expression.
973#[derive(Debug, Clone, PartialEq)]
974pub enum MemberProp {
975    /// `.name`
976    Ident(Ident),
977    /// `[expr]`
978    Computed(Box<Expr>),
979    /// `.#name`
980    Private(Ident),
981}
982
983/// Unary operators.
984#[derive(Debug, Clone, Copy, PartialEq, Eq)]
985pub enum UnaryOp {
986    /// `-`
987    Minus,
988    /// `+`
989    Plus,
990    /// `!`
991    Not,
992    /// `~`
993    BitNot,
994    /// `typeof`
995    Typeof,
996    /// `void`
997    Void,
998    /// `delete`
999    Delete,
1000}
1001
1002impl UnaryOp {
1003    /// The operator text.
1004    pub fn as_str(self) -> &'static str {
1005        match self {
1006            UnaryOp::Minus => "-",
1007            UnaryOp::Plus => "+",
1008            UnaryOp::Not => "!",
1009            UnaryOp::BitNot => "~",
1010            UnaryOp::Typeof => "typeof",
1011            UnaryOp::Void => "void",
1012            UnaryOp::Delete => "delete",
1013        }
1014    }
1015}
1016
1017/// `++`/`--`.
1018#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1019pub enum UpdateOp {
1020    /// `++`
1021    Increment,
1022    /// `--`
1023    Decrement,
1024}
1025
1026impl UpdateOp {
1027    /// The operator text.
1028    pub fn as_str(self) -> &'static str {
1029        match self {
1030            UpdateOp::Increment => "++",
1031            UpdateOp::Decrement => "--",
1032        }
1033    }
1034}
1035
1036/// Non-short-circuiting binary operators.
1037#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1038pub enum BinaryOp {
1039    /// `==`
1040    Eq,
1041    /// `!=`
1042    NotEq,
1043    /// `===`
1044    StrictEq,
1045    /// `!==`
1046    StrictNotEq,
1047    /// `<`
1048    Lt,
1049    /// `<=`
1050    LtEq,
1051    /// `>`
1052    Gt,
1053    /// `>=`
1054    GtEq,
1055    /// `<<`
1056    Shl,
1057    /// `>>`
1058    Shr,
1059    /// `>>>`
1060    UShr,
1061    /// `+`
1062    Add,
1063    /// `-`
1064    Sub,
1065    /// `*`
1066    Mul,
1067    /// `/`
1068    Div,
1069    /// `%`
1070    Mod,
1071    /// `**`
1072    Pow,
1073    /// `|`
1074    BitOr,
1075    /// `^`
1076    BitXor,
1077    /// `&`
1078    BitAnd,
1079    /// `in`
1080    In,
1081    /// `instanceof`
1082    Instanceof,
1083}
1084
1085impl BinaryOp {
1086    /// The operator text.
1087    pub fn as_str(self) -> &'static str {
1088        match self {
1089            BinaryOp::Eq => "==",
1090            BinaryOp::NotEq => "!=",
1091            BinaryOp::StrictEq => "===",
1092            BinaryOp::StrictNotEq => "!==",
1093            BinaryOp::Lt => "<",
1094            BinaryOp::LtEq => "<=",
1095            BinaryOp::Gt => ">",
1096            BinaryOp::GtEq => ">=",
1097            BinaryOp::Shl => "<<",
1098            BinaryOp::Shr => ">>",
1099            BinaryOp::UShr => ">>>",
1100            BinaryOp::Add => "+",
1101            BinaryOp::Sub => "-",
1102            BinaryOp::Mul => "*",
1103            BinaryOp::Div => "/",
1104            BinaryOp::Mod => "%",
1105            BinaryOp::Pow => "**",
1106            BinaryOp::BitOr => "|",
1107            BinaryOp::BitXor => "^",
1108            BinaryOp::BitAnd => "&",
1109            BinaryOp::In => "in",
1110            BinaryOp::Instanceof => "instanceof",
1111        }
1112    }
1113
1114    /// Whether the operator is relational (`in`/`instanceof` included), which
1115    /// matters for the `no-in` restriction in `for` heads.
1116    pub fn is_relational(self) -> bool {
1117        matches!(
1118            self,
1119            BinaryOp::Lt
1120                | BinaryOp::LtEq
1121                | BinaryOp::Gt
1122                | BinaryOp::GtEq
1123                | BinaryOp::In
1124                | BinaryOp::Instanceof
1125        )
1126    }
1127}
1128
1129/// Short-circuiting operators.
1130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1131pub enum LogicalOp {
1132    /// `&&`
1133    And,
1134    /// `||`
1135    Or,
1136    /// `??`
1137    Coalesce,
1138}
1139
1140impl LogicalOp {
1141    /// The operator text.
1142    pub fn as_str(self) -> &'static str {
1143        match self {
1144            LogicalOp::And => "&&",
1145            LogicalOp::Or => "||",
1146            LogicalOp::Coalesce => "??",
1147        }
1148    }
1149}
1150
1151/// Assignment operators.
1152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1153pub enum AssignOp {
1154    /// `=`
1155    Assign,
1156    /// `+=`
1157    Add,
1158    /// `-=`
1159    Sub,
1160    /// `*=`
1161    Mul,
1162    /// `/=`
1163    Div,
1164    /// `%=`
1165    Mod,
1166    /// `**=`
1167    Pow,
1168    /// `<<=`
1169    Shl,
1170    /// `>>=`
1171    Shr,
1172    /// `>>>=`
1173    UShr,
1174    /// `|=`
1175    BitOr,
1176    /// `^=`
1177    BitXor,
1178    /// `&=`
1179    BitAnd,
1180    /// `&&=`
1181    And,
1182    /// `||=`
1183    Or,
1184    /// `??=`
1185    Coalesce,
1186}
1187
1188impl AssignOp {
1189    /// The operator text.
1190    pub fn as_str(self) -> &'static str {
1191        match self {
1192            AssignOp::Assign => "=",
1193            AssignOp::Add => "+=",
1194            AssignOp::Sub => "-=",
1195            AssignOp::Mul => "*=",
1196            AssignOp::Div => "/=",
1197            AssignOp::Mod => "%=",
1198            AssignOp::Pow => "**=",
1199            AssignOp::Shl => "<<=",
1200            AssignOp::Shr => ">>=",
1201            AssignOp::UShr => ">>>=",
1202            AssignOp::BitOr => "|=",
1203            AssignOp::BitXor => "^=",
1204            AssignOp::BitAnd => "&=",
1205            AssignOp::And => "&&=",
1206            AssignOp::Or => "||=",
1207            AssignOp::Coalesce => "??=",
1208        }
1209    }
1210
1211    /// Whether this is a simple `=`.
1212    pub fn is_simple(self) -> bool {
1213        matches!(self, AssignOp::Assign)
1214    }
1215
1216    /// The binary operator a compound assignment implies.
1217    pub fn binary_op(self) -> Option<BinaryOp> {
1218        Some(match self {
1219            AssignOp::Assign => return None,
1220            AssignOp::Add => BinaryOp::Add,
1221            AssignOp::Sub => BinaryOp::Sub,
1222            AssignOp::Mul => BinaryOp::Mul,
1223            AssignOp::Div => BinaryOp::Div,
1224            AssignOp::Mod => BinaryOp::Mod,
1225            AssignOp::Pow => BinaryOp::Pow,
1226            AssignOp::Shl => BinaryOp::Shl,
1227            AssignOp::Shr => BinaryOp::Shr,
1228            AssignOp::UShr => BinaryOp::UShr,
1229            AssignOp::BitOr => BinaryOp::BitOr,
1230            AssignOp::BitXor => BinaryOp::BitXor,
1231            AssignOp::BitAnd => BinaryOp::BitAnd,
1232            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1233        })
1234    }
1235
1236    /// The logical operator a short-circuiting assignment implies.
1237    pub fn logical_op(self) -> Option<LogicalOp> {
1238        match self {
1239            AssignOp::And => Some(LogicalOp::And),
1240            AssignOp::Or => Some(LogicalOp::Or),
1241            AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1242            _ => None,
1243        }
1244    }
1245
1246    /// Map a punctuator to an assignment operator.
1247    pub fn from_punct(p: Punct) -> Option<AssignOp> {
1248        Some(match p {
1249            Punct::Eq => AssignOp::Assign,
1250            Punct::PlusEq => AssignOp::Add,
1251            Punct::MinusEq => AssignOp::Sub,
1252            Punct::StarEq => AssignOp::Mul,
1253            Punct::SlashEq => AssignOp::Div,
1254            Punct::PercentEq => AssignOp::Mod,
1255            Punct::StarStarEq => AssignOp::Pow,
1256            Punct::ShlEq => AssignOp::Shl,
1257            Punct::ShrEq => AssignOp::Shr,
1258            Punct::UShrEq => AssignOp::UShr,
1259            Punct::PipeEq => AssignOp::BitOr,
1260            Punct::CaretEq => AssignOp::BitXor,
1261            Punct::AmpEq => AssignOp::BitAnd,
1262            Punct::AmpAmpEq => AssignOp::And,
1263            Punct::PipePipeEq => AssignOp::Or,
1264            Punct::QuestionQuestionEq => AssignOp::Coalesce,
1265            _ => return None,
1266        })
1267    }
1268}
1269
1270// ---------------------------------------------------------------------------
1271// Modules
1272// ---------------------------------------------------------------------------
1273
1274/// The name on either side of a module binding, which may be a string.
1275#[derive(Debug, Clone, PartialEq, Eq)]
1276pub enum ModuleName {
1277    /// `foo`
1278    Ident(Ident),
1279    /// `"foo bar"`
1280    Str(String),
1281}
1282
1283impl ModuleName {
1284    /// The textual name.
1285    pub fn as_str(&self) -> &str {
1286        match self {
1287            ModuleName::Ident(id) => &id.name,
1288            ModuleName::Str(s) => s,
1289        }
1290    }
1291}
1292
1293/// `import …`
1294#[derive(Debug, Clone, PartialEq)]
1295pub struct ImportDecl {
1296    /// What is imported.
1297    pub specifiers: Vec<ImportSpecifier>,
1298    /// Module specifier string.
1299    pub source: String,
1300    /// `with { type: "json" }` attributes.
1301    pub attributes: Vec<ImportAttribute>,
1302    /// Source range.
1303    pub span: Span,
1304}
1305
1306/// One entry of an import clause.
1307#[derive(Debug, Clone, PartialEq)]
1308pub enum ImportSpecifier {
1309    /// `import d from "m"`
1310    Default(Ident),
1311    /// `import * as ns from "m"`
1312    Namespace(Ident),
1313    /// `import { a, b as c } from "m"`
1314    Named {
1315        /// Name in the exporting module.
1316        imported: ModuleName,
1317        /// Local binding.
1318        local: Ident,
1319    },
1320}
1321
1322/// `with { key: "value" }`
1323#[derive(Debug, Clone, PartialEq)]
1324pub struct ImportAttribute {
1325    /// Attribute key.
1326    pub key: String,
1327    /// Attribute value.
1328    pub value: String,
1329    /// Source range.
1330    pub span: Span,
1331}
1332
1333/// `export …`
1334#[derive(Debug, Clone, PartialEq)]
1335pub struct ExportDecl {
1336    /// What is exported.
1337    pub kind: ExportKind,
1338    /// Source range.
1339    pub span: Span,
1340}
1341
1342/// The variants of an export declaration.
1343#[derive(Debug, Clone, PartialEq)]
1344pub enum ExportKind {
1345    /// `export var/let/const/function/class …`
1346    Declaration(Box<Stmt>),
1347    /// `export default expr` / `export default function …` / `export default class …`
1348    Default(Box<Expr>),
1349    /// `export { a, b as c }` / `export { a } from "m"`
1350    Named {
1351        /// Exported bindings.
1352        specifiers: Vec<ExportSpecifier>,
1353        /// Re-export source.
1354        source: Option<String>,
1355        /// Import attributes for the `from` clause.
1356        attributes: Vec<ImportAttribute>,
1357    },
1358    /// `export * from "m"` / `export * as ns from "m"`
1359    All {
1360        /// Re-export source.
1361        source: String,
1362        /// `as ns`, when present.
1363        exported: Option<ModuleName>,
1364        /// Import attributes for the `from` clause.
1365        attributes: Vec<ImportAttribute>,
1366    },
1367}
1368
1369/// One entry of an `export { … }` clause.
1370#[derive(Debug, Clone, PartialEq)]
1371pub struct ExportSpecifier {
1372    /// Local name (or the name in the source module).
1373    pub local: ModuleName,
1374    /// Exported name.
1375    pub exported: ModuleName,
1376    /// Source range.
1377    pub span: Span,
1378}