kataan 0.0.1

A high-performance JavaScript engine written in pure Rust. Library, C FFI, and CLI.
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Heap cells — the reference types the managed heap holds (`ROADMAP.md` §3).
//!
//! A NaN-boxed handle can point at any *reference* value, not just a plain
//! object: a string, an array, a function, … all live on the heap. `Cell` is
//! that sum — what a [`heap::Heap`](crate::heap::Heap) slot actually stores in
//! the performance model. This turn covers the three core kinds:
//! - `Cell::Object` — a shape + slots object,
//! - `Cell::Str` — a string *value*, backed by a [`rope::Rope`](crate::rope::Rope)
//!   so concatenation stays O(1),
//! - `Cell::Array` — a dense vector of element values.
//!
//! A cell knows how to enumerate its outgoing handles, so the collector traces a
//! mixed object/array/string graph uniformly: objects report their property
//! slots, arrays their elements, strings nothing.
//!
//! Pure, safe `alloc`-only Rust.

use crate::env::Scope;
use crate::gc::Trace;
use crate::heap::Handle;
use crate::nanbox::NanBox;
use crate::object::Object;
use crate::rope::Rope;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::RefCell;

/// A `Promise`'s settlement status.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PromiseStatus {
    /// Not yet settled.
    Pending,
    /// Settled with a value.
    Fulfilled,
    /// Settled with a reason.
    Rejected,
}

/// A `then` reaction: the handlers to run on settlement and the dependent
/// promise to settle with their result.
pub struct Reaction {
    /// Called on fulfillment (`undefined` to pass through).
    pub on_fulfilled: NanBox,
    /// Called on rejection (`undefined` to pass through).
    pub on_rejected: NanBox,
    /// The promise produced by `then`, settled with the handler's result.
    pub result: Handle,
    /// A `finally` reaction: the callback runs for side effects but the result
    /// mirrors the original promise (its value/rejection passes through).
    pub finally: bool,
}

/// A `Promise`'s internal state, shared (`Rc`) between the promise and its
/// resolve/reject functions.
pub struct PromiseState {
    /// The settlement status.
    pub status: PromiseStatus,
    /// The fulfillment value or rejection reason.
    pub value: NanBox,
    /// Reactions registered while pending, drained on settlement.
    pub reactions: Vec<Reaction>,
}

/// A heap-allocated reference value.
pub enum Cell {
    /// An ordinary object (shape + value slots).
    Object(Object),
    /// A string value (rope-backed for O(1) concatenation).
    Str(Rope),
    /// A dense array of element values.
    Array(Vec<NanBox>),
    /// A closure: an index into the interpreter's function table plus the
    /// lexical scope it captured at definition.
    Function {
        /// Index into the owning interpreter's function table (the AST body).
        func_id: u32,
        /// The captured lexical environment.
        env: Scope,
    },
    /// A built-in (native) function, identified by an id the interpreter maps to
    /// a Rust implementation.
    Native(u16),
    /// A native function bound to a heap value (e.g. a promise's resolve/reject,
    /// which carry the promise they settle).
    BoundNative {
        /// The built-in id.
        id: u16,
        /// The bound receiver (e.g. the promise to settle).
        target: Handle,
    },
    /// A `Promise` (its shared settlement state).
    Promise(Rc<RefCell<PromiseState>>),
    /// A `Date`: milliseconds since the Unix epoch (UTC).
    Date(f64),
    /// A `RegExp`: its source pattern and flags (compiled on demand by the
    /// `regex` engine, so the variant itself carries no feature-gated type).
    RegExp {
        /// The pattern source.
        source: alloc::boxed::Box<str>,
        /// The flags (e.g. `"gi"`).
        flags: alloc::boxed::Box<str>,
        /// The mutable `lastIndex` (where the next `g`/`y` search resumes).
        last_index: usize,
    },
    /// A class constructor: an index into the interpreter's class table plus the
    /// scope it was defined in.
    Class {
        /// Index into the owning interpreter's class table (the AST body).
        class_id: u32,
        /// The captured lexical environment.
        env: Scope,
    },
    /// A `Map` (`is_set = false`) or `Set` (`is_set = true`): insertion-ordered
    /// key/value entries (for a `Set`, the value equals the key).
    Collection {
        /// Whether this is a `Set` (vs a `Map`).
        is_set: bool,
        /// Whether this is a `WeakMap`/`WeakSet` (keys must be objects/symbols).
        is_weak: bool,
        /// The entries, in insertion order, compared by `SameValueZero`-ish
        /// strict equality.
        entries: Vec<(NanBox, NanBox)>,
    },
    /// A `Symbol` primitive: an immutable description and a process-unique id.
    /// Symbols compare by identity (two `Symbol("x")` are distinct).
    Symbol {
        /// The optional description (`Symbol("desc").description`).
        description: alloc::boxed::Box<str>,
        /// A unique id, assigned at creation, giving the symbol its identity.
        id: u64,
    },
    /// A `BigInt` primitive — true arbitrary precision (a pure-Rust bignum).
    BigInt(crate::bignum::BigInt),
    /// A `Proxy`: wraps a `target` object, routing property operations through a
    /// `handler` object's traps (`get`/`set`/`has`/`deleteProperty`).
    Proxy {
        /// The proxied object.
        target: Handle,
        /// The trap handler.
        handler: Handle,
        /// Whether the proxy has been revoked (`Proxy.revocable`); a revoked
        /// proxy throws on every operation.
        revoked: bool,
    },
}

impl Cell {
    /// The object, if this cell is one.
    #[must_use]
    pub fn as_object(&self) -> Option<&Object> {
        match self {
            Cell::Object(o) => Some(o),
            _ => None,
        }
    }

    /// The object mutably, if this cell is one.
    pub fn as_object_mut(&mut self) -> Option<&mut Object> {
        match self {
            Cell::Object(o) => Some(o),
            _ => None,
        }
    }

    /// The string, if this cell is one.
    #[must_use]
    pub fn as_str(&self) -> Option<&Rope> {
        match self {
            Cell::Str(s) => Some(s),
            _ => None,
        }
    }

    /// The array elements, if this cell is one.
    #[must_use]
    pub fn as_array(&self) -> Option<&[NanBox]> {
        match self {
            Cell::Array(a) => Some(a),
            _ => None,
        }
    }

    /// The array elements mutably, if this cell is one.
    pub fn as_array_mut(&mut self) -> Option<&mut Vec<NanBox>> {
        match self {
            Cell::Array(a) => Some(a),
            _ => None,
        }
    }

    /// The function's `(func_id, captured env)`, if this cell is a function.
    #[must_use]
    pub fn as_function(&self) -> Option<(u32, &Scope)> {
        match self {
            Cell::Function { func_id, env } => Some((*func_id, env)),
            _ => None,
        }
    }

    /// The built-in id, if this cell is a native function.
    #[must_use]
    pub fn as_native(&self) -> Option<u16> {
        match self {
            Cell::Native(id) => Some(*id),
            _ => None,
        }
    }

    /// The `(id, target)` if this cell is a bound native function.
    #[must_use]
    pub fn as_bound_native(&self) -> Option<(u16, Handle)> {
        match self {
            Cell::BoundNative { id, target } => Some((*id, *target)),
            _ => None,
        }
    }

    /// The shared promise state, if this cell is a promise.
    #[must_use]
    pub fn as_promise(&self) -> Option<&Rc<RefCell<PromiseState>>> {
        match self {
            Cell::Promise(p) => Some(p),
            _ => None,
        }
    }

    /// The timestamp (ms since epoch), if this cell is a `Date`.
    #[must_use]
    pub fn as_date(&self) -> Option<f64> {
        match self {
            Cell::Date(ms) => Some(*ms),
            _ => None,
        }
    }

    /// The `(source, flags)` if this cell is a `RegExp`.
    #[must_use]
    pub fn as_regexp(&self) -> Option<(&str, &str)> {
        match self {
            Cell::RegExp { source, flags, .. } => Some((source, flags)),
            _ => None,
        }
    }

    /// The `(class_id, captured env)`, if this cell is a class.
    #[must_use]
    pub fn as_class(&self) -> Option<(u32, &Scope)> {
        match self {
            Cell::Class { class_id, env } => Some((*class_id, env)),
            _ => None,
        }
    }

    /// The `(is_set, entries)` of a collection, mutably.
    pub fn as_collection_mut(&mut self) -> Option<(bool, &mut Vec<(NanBox, NanBox)>)> {
        match self {
            Cell::Collection {
                is_set, entries, ..
            } => Some((*is_set, entries)),
            _ => None,
        }
    }

    /// The `(is_set, entries)` of a collection.
    #[must_use]
    pub fn as_collection(&self) -> Option<(bool, &[(NanBox, NanBox)])> {
        match self {
            Cell::Collection {
                is_set, entries, ..
            } => Some((*is_set, entries)),
            _ => None,
        }
    }

    /// The `typeof` string for this reference value (`"string"` for strings,
    /// `"function"` for functions, `"object"` for objects and arrays — JS has no
    /// array primitive type).
    #[must_use]
    pub fn type_of(&self) -> &'static str {
        match self {
            Cell::Str(_) => "string",
            Cell::Function { .. }
            | Cell::Native(_)
            | Cell::BoundNative { .. }
            | Cell::Class { .. } => "function",
            Cell::Symbol { .. } => "symbol",
            Cell::BigInt(_) => "bigint",
            Cell::Object(_)
            | Cell::Array(_)
            | Cell::Collection { .. }
            | Cell::Promise(_)
            | Cell::Date(_)
            | Cell::RegExp { .. }
            | Cell::Proxy { .. } => "object",
        }
    }

    /// The `(description, id)` of this symbol, if it is one.
    #[must_use]
    pub fn as_symbol(&self) -> Option<(&str, u64)> {
        match self {
            Cell::Symbol { description, id } => Some((description, *id)),
            _ => None,
        }
    }

    /// The value if this cell is a `BigInt`.
    #[must_use]
    pub fn as_bigint(&self) -> Option<&crate::bignum::BigInt> {
        match self {
            Cell::BigInt(n) => Some(n),
            _ => None,
        }
    }

    /// The `(target, handler)` if this cell is a `Proxy`.
    #[must_use]
    pub fn as_proxy(&self) -> Option<(Handle, Handle)> {
        match self {
            Cell::Proxy {
                target, handler, ..
            } => Some((*target, *handler)),
            _ => None,
        }
    }

    /// Whether this proxy has been revoked, if it is a proxy.
    #[must_use]
    pub fn proxy_revoked(&self) -> Option<bool> {
        match self {
            Cell::Proxy { revoked, .. } => Some(*revoked),
            _ => None,
        }
    }

    /// Marks this proxy revoked (no-op if not a proxy).
    pub fn revoke_proxy(&mut self) {
        if let Cell::Proxy { revoked, .. } = self {
            *revoked = true;
        }
    }
}

impl Trace for Cell {
    fn trace(&self, visit: &mut dyn FnMut(Handle)) {
        match self {
            Cell::Object(o) => o.trace_handles(visit),
            Cell::Array(elems) => {
                for e in elems {
                    if let Some(raw) = e.as_handle() {
                        visit(Handle::from_raw(raw));
                    }
                }
            }
            // A closure (or class) keeps its captured environment alive.
            Cell::Function { env, .. } | Cell::Class { env, .. } => env.for_each_handle(visit),
            // A collection's keys and values are reachable.
            Cell::Collection { entries, .. } => {
                for (k, v) in entries {
                    if let Some(raw) = k.as_handle() {
                        visit(Handle::from_raw(raw));
                    }
                    if let Some(raw) = v.as_handle() {
                        visit(Handle::from_raw(raw));
                    }
                }
            }
            // A promise keeps its value and reaction handlers reachable.
            Cell::Promise(p) => {
                let s = p.borrow();
                if let Some(raw) = s.value.as_handle() {
                    visit(Handle::from_raw(raw));
                }
                for r in &s.reactions {
                    for h in [r.on_fulfilled, r.on_rejected] {
                        if let Some(raw) = h.as_handle() {
                            visit(Handle::from_raw(raw));
                        }
                    }
                    visit(r.result);
                }
            }
            // A bound native keeps its target reachable.
            Cell::BoundNative { target, .. } => visit(*target),
            // A proxy keeps its target and handler reachable.
            Cell::Proxy {
                target, handler, ..
            } => {
                visit(*target);
                visit(*handler);
            }
            // Strings, native functions, dates, and regexes reference no handles.
            Cell::Str(_)
            | Cell::Native(_)
            | Cell::Date(_)
            | Cell::RegExp { .. }
            | Cell::Symbol { .. }
            | Cell::BigInt(_) => {}
        }
    }
}

impl crate::gc::Relocate for Cell {
    fn relocate(&mut self, forward: &dyn Fn(Handle) -> Handle) {
        // Rewrites a handle-bearing value through `forward` (no-op otherwise).
        let fwd = |v: &mut NanBox| {
            if let Some(raw) = v.as_handle() {
                *v = NanBox::handle(forward(Handle::from_raw(raw)).to_raw());
            }
        };
        match self {
            Cell::Object(o) => o.relocate_handles(forward),
            Cell::Array(elems) => elems.iter_mut().for_each(fwd),
            Cell::Function { env, .. } | Cell::Class { env, .. } => env.relocate_handles(forward),
            Cell::Collection { entries, .. } => {
                for (k, v) in entries {
                    fwd(k);
                    fwd(v);
                }
            }
            Cell::Promise(p) => {
                let mut s = p.borrow_mut();
                fwd(&mut s.value);
                for r in &mut s.reactions {
                    fwd(&mut r.on_fulfilled);
                    fwd(&mut r.on_rejected);
                    r.result = forward(r.result);
                }
            }
            Cell::BoundNative { target, .. } => *target = forward(*target),
            Cell::Proxy {
                target, handler, ..
            } => {
                *target = forward(*target);
                *handler = forward(*handler);
            }
            Cell::Str(_)
            | Cell::Native(_)
            | Cell::Date(_)
            | Cell::RegExp { .. }
            | Cell::Symbol { .. }
            | Cell::BigInt(_) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::heap::Heap;
    use crate::shape::Shape;
    use alloc::rc::Rc;

    #[test]
    fn accessors_select_the_right_kind() {
        let obj = Cell::Object(Object::new(Shape::root()));
        assert!(obj.as_object().is_some());
        assert!(obj.as_str().is_none());
        assert!(obj.as_array().is_none());
        assert_eq!(obj.type_of(), "object");

        let s = Cell::Str(Rope::from("hi"));
        assert_eq!(s.as_str().map(Rope::materialize).as_deref(), Some("hi"));
        assert_eq!(s.type_of(), "string");

        let a = Cell::Array(alloc::vec![NanBox::number(1.0), NanBox::number(2.0)]);
        assert_eq!(a.as_array().map(<[_]>::len), Some(2));
        assert_eq!(a.type_of(), "object");
    }

    #[test]
    fn gc_traces_arrays_and_objects_uniformly() {
        // root array -> object -> (handle to) a leaf; plus an unreachable string.
        let mut heap: Heap<Cell> = Heap::new();
        let root_shape = Shape::root();

        let leaf = heap.alloc(Cell::Object(Object::new(Rc::clone(&root_shape))));
        let mut mid = Object::new(Rc::clone(&root_shape));
        mid.set("leaf", NanBox::handle(leaf.to_raw()));
        let mid_h = heap.alloc(Cell::Object(mid));
        let arr = heap.alloc(Cell::Array(alloc::vec![NanBox::handle(mid_h.to_raw())]));
        let _garbage = heap.alloc(Cell::Str(Rope::from("unreferenced")));
        assert_eq!(heap.len(), 4);

        let stats = crate::gc::collect(&mut heap, &[arr]);
        assert_eq!(stats.marked, 3); // arr -> mid -> leaf
        assert_eq!(stats.swept, 1); // the string
        assert!(heap.is_live(arr) && heap.is_live(mid_h) && heap.is_live(leaf));
    }
}