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)`
831    ImportCall(Box<Expr>),
832    /// `super()` — only valid in a derived constructor.
833    SuperCall(Vec<Expr>),
834    /// `super.x` / `super[x]` base (never standalone).
835    SuperProp,
836    /// `op expr`
837    Unary {
838        /// Operator.
839        op: UnaryOp,
840        /// Operand.
841        argument: Box<Expr>,
842    },
843    /// `++x`, `x--`
844    Update {
845        /// Operator.
846        op: UpdateOp,
847        /// Operand.
848        argument: Box<Expr>,
849        /// Whether the operator came before the operand.
850        prefix: bool,
851    },
852    /// `a + b`, `a instanceof b`, `a in b`, …
853    Binary {
854        /// Operator.
855        op: BinaryOp,
856        /// Left operand.
857        left: Box<Expr>,
858        /// Right operand.
859        right: Box<Expr>,
860    },
861    /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
862    /// short-circuit code generation).
863    Logical {
864        /// Operator.
865        op: LogicalOp,
866        /// Left operand.
867        left: Box<Expr>,
868        /// Right operand.
869        right: Box<Expr>,
870    },
871    /// `a ? b : c`
872    Conditional {
873        /// Condition.
874        test: Box<Expr>,
875        /// Consequent.
876        cons: Box<Expr>,
877        /// Alternate.
878        alt: Box<Expr>,
879    },
880    /// `target op= value`
881    Assign {
882        /// Assignment operator.
883        op: AssignOp,
884        /// Assignment target (converted from the cover grammar).
885        target: Box<Pattern>,
886        /// Right-hand side.
887        value: Box<Expr>,
888    },
889    /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
890    /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
891    Paren(Box<Expr>),
892    /// `(a, b, c)`
893    Sequence(Vec<Expr>),
894    /// `yield expr` / `yield* expr`
895    Yield {
896        /// Operand; `None` for `yield;`.
897        argument: Option<Box<Expr>>,
898        /// Whether `yield*` was used.
899        delegate: bool,
900    },
901    /// `await expr`
902    Await(Box<Expr>),
903    /// `...expr` — only valid in call arguments, arrays and object literals.
904    Spread(Box<Expr>),
905    /// A member/call chain that contains at least one `?.`. Compiling the
906    /// wrapper short-circuits the whole spine when a link's base is nullish.
907    OptionalChain(Box<Expr>),
908    /// `#x in obj`
909    PrivateIn {
910        /// Private name.
911        name: Ident,
912        /// Tested object.
913        object: Box<Expr>,
914    },
915}
916
917/// One element of an array literal.
918#[derive(Debug, Clone, PartialEq)]
919pub enum ArrayElement {
920    /// An ordinary element.
921    Expr(Box<Expr>),
922    /// `...iterable`
923    Spread(Box<Expr>),
924}
925
926/// What an object-literal property does with its value.
927///
928/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
929/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
930/// compile to different instructions (`define_field` vs `define_method`), even though
931/// both hold a value on the stack.
932#[derive(Debug, Clone, Copy, PartialEq, Eq)]
933pub enum PropertyKind {
934    /// `key: value` or the `{key}` shorthand — stores a data property.
935    Value,
936    /// `m() {}` — defines a method.
937    Method,
938    /// `get m() {}` — the value is the getter.
939    Get,
940    /// `set m(v) {}` — the value is the setter.
941    Set,
942}
943
944/// One property of an object literal.
945#[derive(Debug, Clone, PartialEq)]
946pub enum ObjectProperty {
947    /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
948    Property {
949        /// Property key.
950        key: PropName,
951        /// Value expression; for `get`/`set` it is the function.
952        value: Box<Expr>,
953        /// Whether this stores a value or defines an accessor/method.
954        kind: PropertyKind,
955        /// Whether the source used shorthand (`{a}` / `{a = 1}`).
956        shorthand: bool,
957        /// Source range.
958        span: Span,
959    },
960    /// `...spread`
961    Spread(Box<Expr>),
962}
963
964/// A template literal: `quasis.len() == expressions.len() + 1`.
965#[derive(Debug, Clone, PartialEq)]
966pub struct TemplateLiteral {
967    /// Literal chunks, in source order.
968    pub quasis: Vec<TemplateChunk>,
969    /// Substitution expressions, in source order.
970    pub expressions: Vec<Expr>,
971}
972
973/// One chunk of a [`TemplateLiteral`].
974#[derive(Debug, Clone, PartialEq, Eq)]
975pub struct TemplateChunk {
976    /// Escape-expanded text; `None` when the chunk has an invalid escape
977    /// sequence (legal in tagged templates only, where it becomes `undefined`).
978    ///
979    /// A [`Wtf8`] because a template may hold an unpaired surrogate, just as a string
980    /// literal may.
981    pub cooked: Option<Wtf8>,
982    /// Source text, verbatim.
983    pub raw: String,
984    /// Whether this chunk ends with the closing backtick.
985    pub tail: bool,
986}
987
988/// Property selector of a member expression.
989#[derive(Debug, Clone, PartialEq)]
990pub enum MemberProp {
991    /// `.name`
992    Ident(Ident),
993    /// `[expr]`
994    Computed(Box<Expr>),
995    /// `.#name`
996    Private(Ident),
997}
998
999/// Unary operators.
1000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1001pub enum UnaryOp {
1002    /// `-`
1003    Minus,
1004    /// `+`
1005    Plus,
1006    /// `!`
1007    Not,
1008    /// `~`
1009    BitNot,
1010    /// `typeof`
1011    Typeof,
1012    /// `void`
1013    Void,
1014    /// `delete`
1015    Delete,
1016}
1017
1018impl UnaryOp {
1019    /// The operator text.
1020    pub fn as_str(self) -> &'static str {
1021        match self {
1022            UnaryOp::Minus => "-",
1023            UnaryOp::Plus => "+",
1024            UnaryOp::Not => "!",
1025            UnaryOp::BitNot => "~",
1026            UnaryOp::Typeof => "typeof",
1027            UnaryOp::Void => "void",
1028            UnaryOp::Delete => "delete",
1029        }
1030    }
1031}
1032
1033/// `++`/`--`.
1034#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1035pub enum UpdateOp {
1036    /// `++`
1037    Increment,
1038    /// `--`
1039    Decrement,
1040}
1041
1042impl UpdateOp {
1043    /// The operator text.
1044    pub fn as_str(self) -> &'static str {
1045        match self {
1046            UpdateOp::Increment => "++",
1047            UpdateOp::Decrement => "--",
1048        }
1049    }
1050}
1051
1052/// Non-short-circuiting binary operators.
1053#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1054pub enum BinaryOp {
1055    /// `==`
1056    Eq,
1057    /// `!=`
1058    NotEq,
1059    /// `===`
1060    StrictEq,
1061    /// `!==`
1062    StrictNotEq,
1063    /// `<`
1064    Lt,
1065    /// `<=`
1066    LtEq,
1067    /// `>`
1068    Gt,
1069    /// `>=`
1070    GtEq,
1071    /// `<<`
1072    Shl,
1073    /// `>>`
1074    Shr,
1075    /// `>>>`
1076    UShr,
1077    /// `+`
1078    Add,
1079    /// `-`
1080    Sub,
1081    /// `*`
1082    Mul,
1083    /// `/`
1084    Div,
1085    /// `%`
1086    Mod,
1087    /// `**`
1088    Pow,
1089    /// `|`
1090    BitOr,
1091    /// `^`
1092    BitXor,
1093    /// `&`
1094    BitAnd,
1095    /// `in`
1096    In,
1097    /// `instanceof`
1098    Instanceof,
1099}
1100
1101impl BinaryOp {
1102    /// The operator text.
1103    pub fn as_str(self) -> &'static str {
1104        match self {
1105            BinaryOp::Eq => "==",
1106            BinaryOp::NotEq => "!=",
1107            BinaryOp::StrictEq => "===",
1108            BinaryOp::StrictNotEq => "!==",
1109            BinaryOp::Lt => "<",
1110            BinaryOp::LtEq => "<=",
1111            BinaryOp::Gt => ">",
1112            BinaryOp::GtEq => ">=",
1113            BinaryOp::Shl => "<<",
1114            BinaryOp::Shr => ">>",
1115            BinaryOp::UShr => ">>>",
1116            BinaryOp::Add => "+",
1117            BinaryOp::Sub => "-",
1118            BinaryOp::Mul => "*",
1119            BinaryOp::Div => "/",
1120            BinaryOp::Mod => "%",
1121            BinaryOp::Pow => "**",
1122            BinaryOp::BitOr => "|",
1123            BinaryOp::BitXor => "^",
1124            BinaryOp::BitAnd => "&",
1125            BinaryOp::In => "in",
1126            BinaryOp::Instanceof => "instanceof",
1127        }
1128    }
1129
1130    /// Whether the operator is relational (`in`/`instanceof` included), which
1131    /// matters for the `no-in` restriction in `for` heads.
1132    pub fn is_relational(self) -> bool {
1133        matches!(
1134            self,
1135            BinaryOp::Lt
1136                | BinaryOp::LtEq
1137                | BinaryOp::Gt
1138                | BinaryOp::GtEq
1139                | BinaryOp::In
1140                | BinaryOp::Instanceof
1141        )
1142    }
1143}
1144
1145/// Short-circuiting operators.
1146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1147pub enum LogicalOp {
1148    /// `&&`
1149    And,
1150    /// `||`
1151    Or,
1152    /// `??`
1153    Coalesce,
1154}
1155
1156impl LogicalOp {
1157    /// The operator text.
1158    pub fn as_str(self) -> &'static str {
1159        match self {
1160            LogicalOp::And => "&&",
1161            LogicalOp::Or => "||",
1162            LogicalOp::Coalesce => "??",
1163        }
1164    }
1165}
1166
1167/// Assignment operators.
1168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1169pub enum AssignOp {
1170    /// `=`
1171    Assign,
1172    /// `+=`
1173    Add,
1174    /// `-=`
1175    Sub,
1176    /// `*=`
1177    Mul,
1178    /// `/=`
1179    Div,
1180    /// `%=`
1181    Mod,
1182    /// `**=`
1183    Pow,
1184    /// `<<=`
1185    Shl,
1186    /// `>>=`
1187    Shr,
1188    /// `>>>=`
1189    UShr,
1190    /// `|=`
1191    BitOr,
1192    /// `^=`
1193    BitXor,
1194    /// `&=`
1195    BitAnd,
1196    /// `&&=`
1197    And,
1198    /// `||=`
1199    Or,
1200    /// `??=`
1201    Coalesce,
1202}
1203
1204impl AssignOp {
1205    /// The operator text.
1206    pub fn as_str(self) -> &'static str {
1207        match self {
1208            AssignOp::Assign => "=",
1209            AssignOp::Add => "+=",
1210            AssignOp::Sub => "-=",
1211            AssignOp::Mul => "*=",
1212            AssignOp::Div => "/=",
1213            AssignOp::Mod => "%=",
1214            AssignOp::Pow => "**=",
1215            AssignOp::Shl => "<<=",
1216            AssignOp::Shr => ">>=",
1217            AssignOp::UShr => ">>>=",
1218            AssignOp::BitOr => "|=",
1219            AssignOp::BitXor => "^=",
1220            AssignOp::BitAnd => "&=",
1221            AssignOp::And => "&&=",
1222            AssignOp::Or => "||=",
1223            AssignOp::Coalesce => "??=",
1224        }
1225    }
1226
1227    /// Whether this is a simple `=`.
1228    pub fn is_simple(self) -> bool {
1229        matches!(self, AssignOp::Assign)
1230    }
1231
1232    /// The binary operator a compound assignment implies.
1233    pub fn binary_op(self) -> Option<BinaryOp> {
1234        Some(match self {
1235            AssignOp::Assign => return None,
1236            AssignOp::Add => BinaryOp::Add,
1237            AssignOp::Sub => BinaryOp::Sub,
1238            AssignOp::Mul => BinaryOp::Mul,
1239            AssignOp::Div => BinaryOp::Div,
1240            AssignOp::Mod => BinaryOp::Mod,
1241            AssignOp::Pow => BinaryOp::Pow,
1242            AssignOp::Shl => BinaryOp::Shl,
1243            AssignOp::Shr => BinaryOp::Shr,
1244            AssignOp::UShr => BinaryOp::UShr,
1245            AssignOp::BitOr => BinaryOp::BitOr,
1246            AssignOp::BitXor => BinaryOp::BitXor,
1247            AssignOp::BitAnd => BinaryOp::BitAnd,
1248            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1249        })
1250    }
1251
1252    /// The logical operator a short-circuiting assignment implies.
1253    pub fn logical_op(self) -> Option<LogicalOp> {
1254        match self {
1255            AssignOp::And => Some(LogicalOp::And),
1256            AssignOp::Or => Some(LogicalOp::Or),
1257            AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1258            _ => None,
1259        }
1260    }
1261
1262    /// Map a punctuator to an assignment operator.
1263    pub fn from_punct(p: Punct) -> Option<AssignOp> {
1264        Some(match p {
1265            Punct::Eq => AssignOp::Assign,
1266            Punct::PlusEq => AssignOp::Add,
1267            Punct::MinusEq => AssignOp::Sub,
1268            Punct::StarEq => AssignOp::Mul,
1269            Punct::SlashEq => AssignOp::Div,
1270            Punct::PercentEq => AssignOp::Mod,
1271            Punct::StarStarEq => AssignOp::Pow,
1272            Punct::ShlEq => AssignOp::Shl,
1273            Punct::ShrEq => AssignOp::Shr,
1274            Punct::UShrEq => AssignOp::UShr,
1275            Punct::PipeEq => AssignOp::BitOr,
1276            Punct::CaretEq => AssignOp::BitXor,
1277            Punct::AmpEq => AssignOp::BitAnd,
1278            Punct::AmpAmpEq => AssignOp::And,
1279            Punct::PipePipeEq => AssignOp::Or,
1280            Punct::QuestionQuestionEq => AssignOp::Coalesce,
1281            _ => return None,
1282        })
1283    }
1284}
1285
1286// ---------------------------------------------------------------------------
1287// Modules
1288// ---------------------------------------------------------------------------
1289
1290/// The name on either side of a module binding, which may be a string.
1291#[derive(Debug, Clone, PartialEq, Eq)]
1292pub enum ModuleName {
1293    /// `foo`
1294    Ident(Ident),
1295    /// `"foo bar"`
1296    ///
1297    /// A `String`, unlike every other cooked string in this tree: a module specifier names
1298    /// a file, so it has to reach the loader as `&str`, and a path cannot contain a lone
1299    /// surrogate. The parser converts with `to_string_lossy` when it builds one, which is
1300    /// also what a filesystem would do with it.
1301    Str(String),
1302}
1303
1304impl ModuleName {
1305    /// The textual name.
1306    pub fn as_str(&self) -> &str {
1307        match self {
1308            ModuleName::Ident(id) => &id.name,
1309            ModuleName::Str(s) => s,
1310        }
1311    }
1312}
1313
1314/// `import …`
1315#[derive(Debug, Clone, PartialEq)]
1316pub struct ImportDecl {
1317    /// What is imported.
1318    pub specifiers: Vec<ImportSpecifier>,
1319    /// Module specifier string.
1320    pub source: String,
1321    /// `with { type: "json" }` attributes.
1322    pub attributes: Vec<ImportAttribute>,
1323    /// Source range.
1324    pub span: Span,
1325}
1326
1327/// One entry of an import clause.
1328#[derive(Debug, Clone, PartialEq)]
1329pub enum ImportSpecifier {
1330    /// `import d from "m"`
1331    Default(Ident),
1332    /// `import * as ns from "m"`
1333    Namespace(Ident),
1334    /// `import { a, b as c } from "m"`
1335    Named {
1336        /// Name in the exporting module.
1337        imported: ModuleName,
1338        /// Local binding.
1339        local: Ident,
1340    },
1341}
1342
1343/// `with { key: "value" }`
1344#[derive(Debug, Clone, PartialEq)]
1345pub struct ImportAttribute {
1346    /// Attribute key.
1347    pub key: String,
1348    /// Attribute value.
1349    pub value: String,
1350    /// Source range.
1351    pub span: Span,
1352}
1353
1354/// `export …`
1355#[derive(Debug, Clone, PartialEq)]
1356pub struct ExportDecl {
1357    /// What is exported.
1358    pub kind: ExportKind,
1359    /// Source range.
1360    pub span: Span,
1361}
1362
1363/// The variants of an export declaration.
1364#[derive(Debug, Clone, PartialEq)]
1365pub enum ExportKind {
1366    /// `export var/let/const/function/class …`
1367    Declaration(Box<Stmt>),
1368    /// `export default expr` / `export default function …` / `export default class …`
1369    Default(Box<Expr>),
1370    /// `export { a, b as c }` / `export { a } from "m"`
1371    Named {
1372        /// Exported bindings.
1373        specifiers: Vec<ExportSpecifier>,
1374        /// Re-export source.
1375        source: Option<String>,
1376        /// Import attributes for the `from` clause.
1377        attributes: Vec<ImportAttribute>,
1378    },
1379    /// `export * from "m"` / `export * as ns from "m"`
1380    All {
1381        /// Re-export source.
1382        source: String,
1383        /// `as ns`, when present.
1384        exported: Option<ModuleName>,
1385        /// Import attributes for the `from` clause.
1386        attributes: Vec<ImportAttribute>,
1387    },
1388}
1389
1390/// One entry of an `export { … }` clause.
1391#[derive(Debug, Clone, PartialEq)]
1392pub struct ExportSpecifier {
1393    /// Local name (or the name in the source module).
1394    pub local: ModuleName,
1395    /// Exported name.
1396    pub exported: ModuleName,
1397    /// Source range.
1398    pub span: Span,
1399}