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