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