node-js 0.1.13

JavaScript as a fusevm frontend: a lexer/parser and compiler to fusevm::Chunk on a JsHost object heap, with no bespoke VM or JIT
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! JavaScript abstract syntax tree.
//!
//! Every node here has a direct lowering in `compiler.rs`. JS is
//! statement-oriented with brace-delimited blocks, so the tree separates `Stmt`
//! (blocks of these form a program/function body) from `Expr`. Numbers are all
//! IEEE-754 `f64`, matching JavaScript's single number type.

/// A source range as UTF-8 byte offsets `(start, end)` into the text the
/// parser read. `(0, 0)` means none was recorded (a `${…}` template field is
/// re-parsed from a copy, so its offsets would not point into the script).
/// `Function.prototype.toString` returns this slice (20.2.3.5).
pub type Span = (u32, u32);

/// A binary operator (`a <op> b`). `&&`/`||`/`??` are `LogicalOp` because they
/// short-circuit and yield an operand value, not a coerced boolean.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow, // **
    // Comparison
    Lt,
    Le,
    Gt,
    Ge,
    EqEqEq, // ===
    NeEqEq, // !==
    EqEq,   // ==  (loose, coercing)
    NeEq,   // !=
    // Bitwise / shift
    BitAnd,
    BitOr,
    BitXor,
    Shl,  // <<
    Shr,  // >>
    UShr, // >>>
    // `in` / `instanceof`
    In,
    InstanceOf,
}

/// A short-circuiting logical operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogicalOp {
    And,     // &&
    Or,      // ||
    Nullish, // ??
}

/// The operator carried by a COMPOUND assignment (`a += b`, `a ??= b`).
///
/// It rides on the [`Expr::Assign`] node rather than being desugared away at
/// parse time. The parser used to rewrite `a op= b` into `a = a op b`, which
/// duplicates the target expression — so every side effect in the target ran
/// TWICE. `o[k()] += 1` called `k` once in node and twice here, and the same
/// held for the logical forms even when they short-circuited and never wrote.
/// Duplication cannot be undone later by inspecting the tree, because
/// `o[k()] = o[k()] + 1` is a DIFFERENT program that legitimately calls `k`
/// twice and is structurally identical after the rewrite.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
    /// `+= -= *= /= %= **= &= |= ^= <<= >>= >>>=` — always reads, computes, writes.
    Binary(BinOp),
    /// `&&= ||= ??=` — reads, and writes only if the read did not short-circuit.
    Logical(LogicalOp),
}

/// A unary prefix operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,    // -x
    Pos,    // +x
    Not,    // !x
    BitNot, // ~x
    TypeOf, // typeof x
    Void,   // void x
    Delete, // delete x
}

/// The kind of a variable declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeclKind {
    Var,
    Let,
    Const,
}

/// The update (increment/decrement) operator, prefix or postfix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateOp {
    Inc, // ++
    Dec, // --
}

/// A property of an object literal.
#[derive(Debug, Clone, PartialEq)]
pub enum Prop {
    /// `key: value` — `computed` marks `[expr]: value`.
    KeyValue {
        key: Expr,
        value: Expr,
        computed: bool,
    },
    /// `...spread`.
    Spread(Expr),
    /// `get key() {}` / `set key(v) {}` — an accessor property.
    Accessor {
        key: Expr,
        computed: bool,
        /// `true` for a getter, `false` for a setter.
        is_getter: bool,
        /// The accessor function (an `Expr::Function`).
        func: Expr,
    },
}

/// A JavaScript expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    Null,
    Undefined,
    True,
    False,
    Number(f64),
    /// A `BigInt` literal as its canonical decimal digit string (`"123"` for
    /// `123n`). Lowered to a heap `JsObj::BigInt`.
    BigInt(String),
    /// A regex literal: `(pattern, flags)`. Lowered to a `JsObj::RegExp`.
    Regex(String, String),
    Str(String),
    /// A template literal: alternating literal quasis and interpolated exprs.
    /// `quasis.len() == exprs.len() + 1`.
    Template {
        quasis: Vec<String>,
        exprs: Vec<Expr>,
    },
    /// A tagged template `` tag`a${x}b` ``: calls `tag(strings, ...values)` where
    /// `strings` is the cooked-quasi array carrying a `.raw` array of `raws`.
    TaggedTemplate {
        tag: Box<Expr>,
        quasis: Vec<String>,
        raws: Vec<String>,
        exprs: Vec<Expr>,
    },

    /// A bare identifier (`x`); the compiler resolves scope at runtime.
    Ident(String),
    /// `this`.
    This,
    /// `super` (only valid as `super(...)` call callee or `super.x` object).
    Super,
    /// `new.target`.
    NewTarget,
    /// `yield expr` / `yield* expr` / `yield` (generator).
    Yield {
        arg: Option<Box<Expr>>,
        delegate: bool,
    },
    /// `await expr` (async function).
    Await(Box<Expr>),
    /// A `class` expression.
    Class(Box<ClassNode>),

    Array(Vec<Expr>),
    /// An elided array-literal element (`[1,,3]`) — a HOLE, which reads back as
    /// `undefined` but is not an own property. Distinct from `Expr::Undefined`
    /// so `compile_array` can record it and `destructure_array` can skip it.
    Hole,
    Object(Vec<Prop>),
    /// `...expr` — a spread element (array/call).
    Spread(Box<Expr>),

    Logical(LogicalOp, Box<Expr>, Box<Expr>),
    Unary(UnOp, Box<Expr>),
    Binary(BinOp, Box<Expr>, Box<Expr>),

    /// `test ? cons : alt`.
    Conditional {
        test: Box<Expr>,
        cons: Box<Expr>,
        alt: Box<Expr>,
    },

    /// `target = value`, or a compound `target op= value` when `op` is `Some`.
    ///
    /// A compound assignment evaluates the target reference ONCE: for
    /// `o[k()] += 1` the object and the key are computed a single time, the
    /// old value is read through them, and the result is written back through
    /// the same reference (ECMA-262 13.15.2).
    Assign {
        target: Box<Expr>,
        op: Option<AssignOp>,
        value: Box<Expr>,
    },
    /// `++x` / `x++` / `--x` / `x--`.
    Update {
        op: UpdateOp,
        prefix: bool,
        target: Box<Expr>,
    },

    /// A call `func(args)`. `optional` marks `?.(`.
    Call {
        func: Box<Expr>,
        args: Vec<Expr>,
        optional: bool,
    },
    /// `new Ctor(args)`.
    New {
        callee: Box<Expr>,
        args: Vec<Expr>,
    },
    /// `value.name` — `optional` marks `?.name`.
    Member {
        object: Box<Expr>,
        property: String,
        optional: bool,
    },
    /// `value[expr]` — `optional` marks `?.[expr]`.
    Index {
        object: Box<Expr>,
        index: Box<Expr>,
        optional: bool,
    },

    /// A function expression / arrow function.
    Function {
        params: Vec<Param>,
        body: FnBody,
        is_arrow: bool,
        name: Option<String>,
        is_generator: bool,
        is_async: bool,
        /// True for a MethodDefinition (`{ m(){} }`, `{ get x(){} }`) rather
        /// than an ordinary function expression. A non-generator method owns no
        /// `prototype` property (10.2.5 runs only for ordinary functions).
        is_method: bool,
        /// The definition's source text: from `async`/`function`/`get`/`*`/the
        /// key or the arrow's parameters, to its last token.
        span: Span,
    },

    /// `,`-sequence expression: evaluate all, yield the last.
    Sequence(Vec<Expr>),
}

/// A `class` declaration/expression body.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassNode {
    pub name: Option<String>,
    /// The `extends` expression, if any.
    pub parent: Option<Box<Expr>>,
    pub members: Vec<ClassMember>,
    /// `class` through the closing brace.
    pub span: Span,
}

/// One member of a class body: a method, accessor, or field, on the instance or
/// static side.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassMember {
    /// The property key (an `Expr::Str` for a plain name, or any expr when
    /// `computed`).
    pub key: Expr,
    pub computed: bool,
    pub kind: MemberKind,
    pub is_static: bool,
    pub is_generator: bool,
    pub is_async: bool,
    /// Params + body for a method/accessor/constructor.
    pub params: Vec<Param>,
    pub body: Vec<Stmt>,
    /// Initializer expression for a field (`x = expr;`).
    pub field_init: Option<Expr>,
    /// A method's source, from its first modifier after `static` (or its
    /// key) to the closing brace.
    pub span: Span,
}

/// The kind of a class member.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberKind {
    Constructor,
    Method,
    Get,
    Set,
    Field,
    /// A `static { … }` initialization block (ES2022). It has no key and no
    /// parameters: only `body` is meaningful, and it runs once at class-definition
    /// time with `this` bound to the constructor.
    StaticBlock,
}

/// A function/arrow body: either a brace-delimited statement list or (arrow) a
/// single expression whose value is returned.
#[derive(Debug, Clone, PartialEq)]
pub enum FnBody {
    Block(Vec<Stmt>),
    Expr(Box<Expr>),
}

/// A formal parameter.
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    /// The binding target — an `Ident`, or an array/object pattern (also an
    /// `Expr::Array`/`Expr::Object` used as a destructuring target).
    pub pattern: Expr,
    /// `= default`.
    pub default: Option<Expr>,
    /// `...rest`.
    pub rest: bool,
}

/// One `case`/`default` clause of a `switch`.
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchCase {
    /// `None` for the `default:` clause.
    pub test: Option<Expr>,
    pub body: Vec<Stmt>,
}

/// A single declarator inside a `var`/`let`/`const`.
#[derive(Debug, Clone, PartialEq)]
pub struct Declarator {
    pub target: Expr,
    pub init: Option<Expr>,
}

/// A JavaScript statement.
#[derive(Debug, Clone, PartialEq)]
pub enum StmtKind {
    /// An expression evaluated for effect (value discarded).
    Expr(Expr),
    /// `var`/`let`/`const` declaration list.
    Decl {
        kind: DeclKind,
        decls: Vec<Declarator>,
    },
    /// `{ ... }` block.
    Block(Vec<Stmt>),
    /// `function name(params) { body }`.
    FuncDecl {
        name: String,
        params: Vec<Param>,
        body: Vec<Stmt>,
        is_generator: bool,
        is_async: bool,
        span: Span,
    },
    /// `class Name … { … }`.
    ClassDecl(ClassNode),

    If {
        test: Expr,
        cons: Box<Stmt>,
        alt: Option<Box<Stmt>>,
    },
    While {
        test: Expr,
        body: Box<Stmt>,
    },
    DoWhile {
        body: Box<Stmt>,
        test: Expr,
    },
    /// C-style `for (init; test; update) body`.
    For {
        init: Option<Box<Stmt>>,
        test: Option<Expr>,
        update: Option<Expr>,
        body: Box<Stmt>,
    },
    /// `for (decl of iterable) body`. `is_await` marks `for await (…)`.
    ForOf {
        decl_kind: Option<DeclKind>,
        target: Expr,
        iter: Expr,
        body: Box<Stmt>,
        is_await: bool,
    },
    /// `for (decl in object) body`.
    ForIn {
        decl_kind: Option<DeclKind>,
        target: Expr,
        object: Expr,
        body: Box<Stmt>,
    },
    Switch {
        disc: Expr,
        cases: Vec<SwitchCase>,
    },

    /// `label: stmt` — a labeled statement (typically a loop), targetable by
    /// `break label` / `continue label`.
    Labeled {
        label: String,
        body: Box<Stmt>,
    },

    Return(Option<Expr>),
    Break(Option<String>),
    Continue(Option<String>),
    Throw(Expr),
    Try {
        block: Vec<Stmt>,
        handler: Option<(Option<Expr>, Vec<Stmt>)>, // (param pattern, body)
        finalizer: Option<Vec<Stmt>>,
    },

    Empty,
}

/// A statement plus its 1-based source line.
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
    pub kind: StmtKind,
    pub line: u32,
}

impl Stmt {
    pub fn new(kind: StmtKind, line: u32) -> Stmt {
        Stmt { kind, line }
    }
}

impl From<StmtKind> for Stmt {
    /// Wrap a `StmtKind` as a synthetic statement (line 0).
    fn from(kind: StmtKind) -> Stmt {
        Stmt { kind, line: 0 }
    }
}