Skip to main content

nodejs/
ast.rs

1//! JavaScript abstract syntax tree.
2//!
3//! Every node here has a direct lowering in `compiler.rs`. JS is
4//! statement-oriented with brace-delimited blocks, so the tree separates `Stmt`
5//! (blocks of these form a program/function body) from `Expr`. Numbers are all
6//! IEEE-754 `f64`, matching JavaScript's single number type.
7
8/// A source range as UTF-8 byte offsets `(start, end)` into the text the
9/// parser read. `(0, 0)` means none was recorded (a `${…}` template field is
10/// re-parsed from a copy, so its offsets would not point into the script).
11/// `Function.prototype.toString` returns this slice (20.2.3.5).
12pub type Span = (u32, u32);
13
14/// A source position: one past the UTF-8 byte offset of a token in the text the
15/// node was parsed from, so `0` means "none" (a synthetic node, or text the
16/// parser could not map back — see `Parser::spans`). The compiler stores it in
17/// the `lines` entry of the op the node lowers to, and the loader rebases it into
18/// the host's source address space, which is what an error's source arrow and a
19/// stack frame's `file:line:column` are read from.
20pub type Pos = u32;
21
22/// A binary operator (`a <op> b`). `&&`/`||`/`??` are `LogicalOp` because they
23/// short-circuit and yield an operand value, not a coerced boolean.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum BinOp {
26    Add,
27    Sub,
28    Mul,
29    Div,
30    Mod,
31    Pow, // **
32    // Comparison
33    Lt,
34    Le,
35    Gt,
36    Ge,
37    EqEqEq, // ===
38    NeEqEq, // !==
39    EqEq,   // ==  (loose, coercing)
40    NeEq,   // !=
41    // Bitwise / shift
42    BitAnd,
43    BitOr,
44    BitXor,
45    Shl,  // <<
46    Shr,  // >>
47    UShr, // >>>
48    // `in` / `instanceof`
49    In,
50    InstanceOf,
51}
52
53/// A short-circuiting logical operator.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum LogicalOp {
56    And,     // &&
57    Or,      // ||
58    Nullish, // ??
59}
60
61/// The operator carried by a COMPOUND assignment (`a += b`, `a ??= b`).
62///
63/// It rides on the [`Expr::Assign`] node rather than being desugared away at
64/// parse time. The parser used to rewrite `a op= b` into `a = a op b`, which
65/// duplicates the target expression — so every side effect in the target ran
66/// TWICE. `o[k()] += 1` called `k` once in node and twice here, and the same
67/// held for the logical forms even when they short-circuited and never wrote.
68/// Duplication cannot be undone later by inspecting the tree, because
69/// `o[k()] = o[k()] + 1` is a DIFFERENT program that legitimately calls `k`
70/// twice and is structurally identical after the rewrite.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum AssignOp {
73    /// `+= -= *= /= %= **= &= |= ^= <<= >>= >>>=` — always reads, computes, writes.
74    Binary(BinOp),
75    /// `&&= ||= ??=` — reads, and writes only if the read did not short-circuit.
76    Logical(LogicalOp),
77}
78
79/// A unary prefix operator.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum UnOp {
82    Neg,    // -x
83    Pos,    // +x
84    Not,    // !x
85    BitNot, // ~x
86    TypeOf, // typeof x
87    Void,   // void x
88    Delete, // delete x
89}
90
91/// The kind of a variable declaration.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum DeclKind {
94    Var,
95    Let,
96    Const,
97}
98
99/// The update (increment/decrement) operator, prefix or postfix.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum UpdateOp {
102    Inc, // ++
103    Dec, // --
104}
105
106/// A property of an object literal.
107#[derive(Debug, Clone, PartialEq)]
108pub enum Prop {
109    /// `key: value` — `computed` marks `[expr]: value`.
110    KeyValue {
111        key: Expr,
112        value: Expr,
113        computed: bool,
114    },
115    /// `...spread`.
116    Spread(Expr),
117    /// `get key() {}` / `set key(v) {}` — an accessor property.
118    Accessor {
119        key: Expr,
120        computed: bool,
121        /// `true` for a getter, `false` for a setter.
122        is_getter: bool,
123        /// The accessor function (an `Expr::Function`).
124        func: Expr,
125    },
126}
127
128/// A JavaScript expression.
129#[derive(Debug, Clone, PartialEq)]
130pub enum Expr {
131    Null,
132    Undefined,
133    True,
134    False,
135    Number(f64),
136    /// A `BigInt` literal as its canonical decimal digit string (`"123"` for
137    /// `123n`). Lowered to a heap `JsObj::BigInt`.
138    BigInt(String),
139    /// A regex literal: `(pattern, flags)`. Lowered to a `JsObj::RegExp`.
140    Regex(String, String),
141    Str(String),
142    /// A template literal: alternating literal quasis and interpolated exprs.
143    /// `quasis.len() == exprs.len() + 1`.
144    Template {
145        quasis: Vec<String>,
146        exprs: Vec<Expr>,
147    },
148    /// A tagged template `` tag`a${x}b` ``: calls `tag(strings, ...values)` where
149    /// `strings` is the cooked-quasi array carrying a `.raw` array of `raws`.
150    TaggedTemplate {
151        tag: Box<Expr>,
152        quasis: Vec<String>,
153        raws: Vec<String>,
154        exprs: Vec<Expr>,
155    },
156
157    /// A bare identifier (`x`); the compiler resolves scope at runtime.
158    Ident(String),
159    /// `this`.
160    This,
161    /// `super` (only valid as `super(...)` call callee or `super.x` object).
162    Super,
163    /// `new.target`.
164    NewTarget,
165    /// `yield expr` / `yield* expr` / `yield` (generator).
166    Yield {
167        arg: Option<Box<Expr>>,
168        delegate: bool,
169    },
170    /// `await expr` (async function), at the `await` keyword: where a
171    /// suspension that never resumes is reported.
172    Await(Box<Expr>, Pos),
173    /// A `class` expression.
174    Class(Box<ClassNode>),
175
176    Array(Vec<Expr>),
177    /// An elided array-literal element (`[1,,3]`) — a HOLE, which reads back as
178    /// `undefined` but is not an own property. Distinct from `Expr::Undefined`
179    /// so `compile_array` can record it and `destructure_array` can skip it.
180    Hole,
181    Object(Vec<Prop>),
182    /// `...expr` — a spread element (array/call).
183    Spread(Box<Expr>),
184
185    Logical(LogicalOp, Box<Expr>, Box<Expr>),
186    Unary(UnOp, Box<Expr>),
187    Binary(BinOp, Box<Expr>, Box<Expr>),
188
189    /// `test ? cons : alt`.
190    Conditional {
191        test: Box<Expr>,
192        cons: Box<Expr>,
193        alt: Box<Expr>,
194    },
195
196    /// `target = value`, or a compound `target op= value` when `op` is `Some`.
197    ///
198    /// A compound assignment evaluates the target reference ONCE: for
199    /// `o[k()] += 1` the object and the key are computed a single time, the
200    /// old value is read through them, and the result is written back through
201    /// the same reference (ECMA-262 13.15.2).
202    Assign {
203        target: Box<Expr>,
204        op: Option<AssignOp>,
205        value: Box<Expr>,
206    },
207    /// `++x` / `x++` / `--x` / `x--`.
208    Update {
209        op: UpdateOp,
210        prefix: bool,
211        target: Box<Expr>,
212    },
213
214    /// A call `func(args)`. `optional` marks `?.(`.
215    Call {
216        func: Box<Expr>,
217        args: Vec<Expr>,
218        optional: bool,
219        /// Where V8 places the call for an error or a stack frame — see [`Pos`].
220        pos: Pos,
221    },
222    /// `new Ctor(args)`.
223    New {
224        callee: Box<Expr>,
225        args: Vec<Expr>,
226        /// The `new` keyword — see [`Pos`].
227        pos: Pos,
228    },
229    /// `value.name` — `optional` marks `?.name`.
230    Member {
231        object: Box<Expr>,
232        property: String,
233        optional: bool,
234        /// The property name — see [`Pos`].
235        pos: Pos,
236    },
237    /// `value[expr]` — `optional` marks `?.[expr]`.
238    Index {
239        object: Box<Expr>,
240        index: Box<Expr>,
241        optional: bool,
242        /// The `[` — see [`Pos`].
243        pos: Pos,
244    },
245
246    /// A function expression / arrow function.
247    Function {
248        params: Vec<Param>,
249        body: FnBody,
250        is_arrow: bool,
251        name: Option<String>,
252        is_generator: bool,
253        is_async: bool,
254        /// True for a MethodDefinition (`{ m(){} }`, `{ get x(){} }`) rather
255        /// than an ordinary function expression. A non-generator method owns no
256        /// `prototype` property (10.2.5 runs only for ordinary functions).
257        is_method: bool,
258        /// The definition's source text: from `async`/`function`/`get`/`*`/the
259        /// key or the arrow's parameters, to its last token.
260        span: Span,
261    },
262
263    /// `,`-sequence expression: evaluate all, yield the last.
264    Sequence(Vec<Expr>),
265}
266
267/// A `class` declaration/expression body.
268#[derive(Debug, Clone, PartialEq)]
269pub struct ClassNode {
270    pub name: Option<String>,
271    /// The `extends` expression, if any.
272    pub parent: Option<Box<Expr>>,
273    pub members: Vec<ClassMember>,
274    /// `class` through the closing brace.
275    pub span: Span,
276}
277
278/// One member of a class body: a method, accessor, or field, on the instance or
279/// static side.
280#[derive(Debug, Clone, PartialEq)]
281pub struct ClassMember {
282    /// The property key (an `Expr::Str` for a plain name, or any expr when
283    /// `computed`).
284    pub key: Expr,
285    pub computed: bool,
286    pub kind: MemberKind,
287    pub is_static: bool,
288    pub is_generator: bool,
289    pub is_async: bool,
290    /// Params + body for a method/accessor/constructor.
291    pub params: Vec<Param>,
292    pub body: Vec<Stmt>,
293    /// Initializer expression for a field (`x = expr;`).
294    pub field_init: Option<Expr>,
295    /// A method's source, from its first modifier after `static` (or its
296    /// key) to the closing brace.
297    pub span: Span,
298}
299
300/// The kind of a class member.
301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
302pub enum MemberKind {
303    Constructor,
304    Method,
305    Get,
306    Set,
307    Field,
308    /// A `static { … }` initialization block (ES2022). It has no key and no
309    /// parameters: only `body` is meaningful, and it runs once at class-definition
310    /// time with `this` bound to the constructor.
311    StaticBlock,
312}
313
314/// A function/arrow body: either a brace-delimited statement list or (arrow) a
315/// single expression whose value is returned.
316#[derive(Debug, Clone, PartialEq)]
317pub enum FnBody {
318    Block(Vec<Stmt>),
319    Expr(Box<Expr>),
320}
321
322/// A formal parameter.
323#[derive(Debug, Clone, PartialEq)]
324pub struct Param {
325    /// The binding target — an `Ident`, or an array/object pattern (also an
326    /// `Expr::Array`/`Expr::Object` used as a destructuring target).
327    pub pattern: Expr,
328    /// `= default`.
329    pub default: Option<Expr>,
330    /// `...rest`.
331    pub rest: bool,
332}
333
334/// One `case`/`default` clause of a `switch`.
335#[derive(Debug, Clone, PartialEq)]
336pub struct SwitchCase {
337    /// `None` for the `default:` clause.
338    pub test: Option<Expr>,
339    pub body: Vec<Stmt>,
340}
341
342/// A single declarator inside a `var`/`let`/`const`.
343#[derive(Debug, Clone, PartialEq)]
344pub struct Declarator {
345    pub target: Expr,
346    pub init: Option<Expr>,
347    /// Where each name the target binds is written, in source order — what
348    /// an early error such as a redeclaration is reported at. Empty when the
349    /// declaration was synthesised or parsed without source spans.
350    pub bound: Vec<(String, Pos)>,
351}
352
353/// A JavaScript statement.
354#[derive(Debug, Clone, PartialEq)]
355pub enum StmtKind {
356    /// An expression evaluated for effect (value discarded).
357    Expr(Expr),
358    /// `var`/`let`/`const` declaration list.
359    Decl {
360        kind: DeclKind,
361        decls: Vec<Declarator>,
362    },
363    /// `{ ... }` block.
364    Block(Vec<Stmt>),
365    /// `function name(params) { body }`.
366    FuncDecl {
367        name: String,
368        params: Vec<Param>,
369        body: Vec<Stmt>,
370        is_generator: bool,
371        is_async: bool,
372        span: Span,
373    },
374    /// `class Name … { … }`.
375    ClassDecl(ClassNode),
376
377    If {
378        test: Expr,
379        cons: Box<Stmt>,
380        alt: Option<Box<Stmt>>,
381    },
382    While {
383        test: Expr,
384        body: Box<Stmt>,
385    },
386    /// `with (object) body` (sloppy mode only): `body` resolves identifiers
387    /// against `object` first.
388    With {
389        object: Expr,
390        body: Box<Stmt>,
391    },
392    DoWhile {
393        body: Box<Stmt>,
394        test: Expr,
395    },
396    /// C-style `for (init; test; update) body`.
397    For {
398        init: Option<Box<Stmt>>,
399        test: Option<Expr>,
400        update: Option<Expr>,
401        body: Box<Stmt>,
402    },
403    /// `for (decl of iterable) body`. `is_await` marks `for await (…)`.
404    ForOf {
405        decl_kind: Option<DeclKind>,
406        target: Expr,
407        iter: Expr,
408        body: Box<Stmt>,
409        is_await: bool,
410    },
411    /// `for (decl in object) body`.
412    ForIn {
413        decl_kind: Option<DeclKind>,
414        target: Expr,
415        object: Expr,
416        body: Box<Stmt>,
417    },
418    Switch {
419        disc: Expr,
420        cases: Vec<SwitchCase>,
421    },
422
423    /// `label: stmt` — a labeled statement (typically a loop), targetable by
424    /// `break label` / `continue label`.
425    Labeled {
426        label: String,
427        body: Box<Stmt>,
428    },
429
430    Return(Option<Expr>),
431    Break(Option<String>),
432    Continue(Option<String>),
433    Throw(Expr),
434    Try {
435        block: Vec<Stmt>,
436        handler: Option<(Option<Expr>, Vec<Stmt>)>, // (param pattern, body)
437        finalizer: Option<Vec<Stmt>>,
438    },
439
440    /// An `import` declaration (module code only, top level).
441    Import(ImportDecl),
442    /// An `export` declaration (module code only, top level).
443    Export(ExportDecl),
444
445    Empty,
446}
447
448/// One binding an `import` declaration introduces (16.2.2).
449#[derive(Debug, Clone, PartialEq)]
450pub enum ImportSpec {
451    /// `import local from …` — the imported name is `default`.
452    Default(String),
453    /// `import * as local from …`.
454    Namespace(String),
455    /// `import { imported as local } from …` (`imported` may be a string literal
456    /// name such as `"a b"`).
457    Named { imported: String, local: String },
458}
459
460/// `import … from "specifier" with { … }` — the bindings may be empty
461/// (`import "m"` evaluates the module for its effects only).
462#[derive(Debug, Clone, PartialEq)]
463pub struct ImportDecl {
464    pub specifier: String,
465    pub specs: Vec<ImportSpec>,
466    /// The `with { type: "json" }` import attributes, in source order.
467    pub attributes: Vec<(String, String)>,
468    /// The source range of the `{ … }` named-imports clause, `(0, 0)` when
469    /// there is none — node quotes it back in the error for a named import a
470    /// CommonJS module does not provide.
471    pub clause: Span,
472}
473
474/// `local as exported` inside `export { … }`. Without a `from` clause `local`
475/// names a binding of this module; with one it is a name the requested module
476/// exports.
477#[derive(Debug, Clone, PartialEq)]
478pub struct ExportSpec {
479    pub local: String,
480    pub exported: String,
481}
482
483/// The forms of an `export` declaration (16.2.3).
484#[derive(Debug, Clone, PartialEq)]
485pub enum ExportDecl {
486    /// `export var|let|const …`, `export function …`, `export class …`.
487    Decl(Box<Stmt>),
488    /// `export default function …` / `export default class …`: a `FuncDecl` or
489    /// `ClassDecl` whose name is `default` when the source gave none.
490    DefaultDecl(Box<Stmt>),
491    /// `export default <AssignmentExpression>;`.
492    DefaultExpr(Expr),
493    /// `export { a, b as c }`, or `export { a } from "m"` when `from` is set.
494    Named {
495        specs: Vec<ExportSpec>,
496        from: Option<String>,
497        attributes: Vec<(String, String)>,
498    },
499    /// `export * from "m"`, or `export * as alias from "m"`.
500    Star {
501        alias: Option<String>,
502        from: String,
503        attributes: Vec<(String, String)>,
504    },
505}
506
507/// A statement plus its 1-based source line and the [`Pos`] of its first token.
508#[derive(Debug, Clone, PartialEq)]
509pub struct Stmt {
510    pub kind: StmtKind,
511    pub line: u32,
512    pub pos: Pos,
513}
514
515impl Stmt {
516    pub fn new(kind: StmtKind, line: u32) -> Stmt {
517        Stmt { kind, line, pos: 0 }
518    }
519    pub fn at(kind: StmtKind, line: u32, pos: Pos) -> Stmt {
520        Stmt { kind, line, pos }
521    }
522}
523
524impl From<StmtKind> for Stmt {
525    /// Wrap a `StmtKind` as a synthetic statement (line 0).
526    fn from(kind: StmtKind) -> Stmt {
527        Stmt {
528            kind,
529            line: 0,
530            pos: 0,
531        }
532    }
533}