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