node-js 0.1.1

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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! JavaScript typed arrays (`Uint8Array`/`Int8Array`/…/`Float64Array`),
//! `ArrayBuffer`, `WeakRef`, and `TextEncoder`/`TextDecoder`.
//!
//! A typed array is a plain object tagged `@@native = "TypedArray"` carrying its
//! kind (`@@kind`), its elements as a hidden `@@elems` array of numbers, and the
//! enumerable `length`/`byteLength`/`BYTES_PER_ELEMENT` data properties JS code
//! reads directly. Element indexing (`ta[i]` get/set) is special-cased in
//! `builtins::get_property`/`set_property` via `elem_get`/`elem_set` here, which
//! also apply each kind's coercion (integer wrap / clamp / float).
//!
//! `WeakRef` holds a *strong* reference (`deref()` always returns the target) —
//! node-js has no GC of JS objects, so this is observably correct for the
//! express dependency tree (object-inspect/qs/side-channel only ever `deref()`).

use crate::host::{with_host, JsObj};
use fusevm::Value;
use indexmap::IndexMap;

pub const STATIC_METHODS: &[&str] = &["from", "of"];

/// The nine element kinds plus `ArrayBuffer` (which carries only a byte length).
pub fn is_ctor(name: &str) -> bool {
    matches!(
        name,
        "Uint8Array"
            | "Int8Array"
            | "Uint8ClampedArray"
            | "Int16Array"
            | "Uint16Array"
            | "Int32Array"
            | "Uint32Array"
            | "Float32Array"
            | "Float64Array"
            | "ArrayBuffer"
    )
}

/// Bytes per element for a typed-array kind.
fn bytes_per_element(kind: &str) -> usize {
    match kind {
        "Int8Array" | "Uint8Array" | "Uint8ClampedArray" => 1,
        "Int16Array" | "Uint16Array" => 2,
        "Int32Array" | "Uint32Array" | "Float32Array" => 4,
        "Float64Array" => 8,
        _ => 1,
    }
}

/// Coerce a JS number into the value stored for `kind` (integer wrap, unsigned
/// clamp, or float), mirroring the `ToInt8`/`ToUint8Clamp`/… abstract ops.
fn coerce(kind: &str, n: f64) -> f64 {
    match kind {
        "Int8Array" => (n as i64 as i8) as f64,
        "Uint8Array" => (n as i64 as u8) as f64,
        "Uint8ClampedArray" => {
            if n.is_nan() {
                0.0
            } else {
                n.round().clamp(0.0, 255.0)
            }
        }
        "Int16Array" => (n as i64 as i16) as f64,
        "Uint16Array" => (n as i64 as u16) as f64,
        "Int32Array" => (n as i64 as i32) as f64,
        "Uint32Array" => (n as i64 as u32) as f64,
        "Float32Array" => n as f32 as f64,
        _ => n, // Float64Array
    }
}

/// Build a typed array of `kind` from already-coerced element values.
fn make(kind: &str, elems: Vec<f64>) -> Value {
    with_host(|h| {
        let bpe = bytes_per_element(kind);
        let len = elems.len();
        let arr = h.new_array(elems.into_iter().map(Value::Float).collect());
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("TypedArray"));
        m.insert("@@kind".into(), h.new_str(kind));
        m.insert("@@elems".into(), arr);
        m.insert("length".into(), Value::Float(len as f64));
        m.insert("byteLength".into(), Value::Float((len * bpe) as f64));
        m.insert("BYTES_PER_ELEMENT".into(), Value::Float(bpe as f64));
        h.new_object(m)
    })
}

/// `new Uint8Array(...)` etc. `ArrayBuffer` is a byte container with only a
/// `byteLength`.
pub fn construct(kind: &str, args: &[Value]) -> Result<Value, String> {
    if kind == "ArrayBuffer" {
        let n = super::arg_num(args, 0).max(0.0) as usize;
        return Ok(with_host(|h| {
            let mut m = IndexMap::new();
            m.insert("@@native".into(), h.new_str("ArrayBuffer"));
            m.insert("byteLength".into(), Value::Float(n as f64));
            h.new_object(m)
        }));
    }
    let elems = build_elems(kind, args)?;
    Ok(make(kind, elems))
}

/// Element vector for a typed-array construction from its first argument:
/// a number → that many zeroed slots; an array/iterable/typed-array → its coerced
/// values; otherwise → empty.
fn build_elems(kind: &str, args: &[Value]) -> Result<Vec<f64>, String> {
    match args.first() {
        None | Some(Value::Undef) => Ok(Vec::new()),
        Some(Value::Int(_)) | Some(Value::Float(_)) => {
            let n = super::arg_num(args, 0).max(0.0) as usize;
            Ok(vec![0.0; n])
        }
        Some(v) => {
            // Another typed array / Buffer → copy its elements.
            if let Some(src) = elems_of(v) {
                return Ok(src.iter().map(|x| coerce(kind, *x)).collect());
            }
            // A plain array or arraylike → coerce each entry.
            let items = crate::host::iter_all(v).unwrap_or_default();
            Ok(items
                .iter()
                .map(|x| coerce(kind, with_host(|h| h.to_number(x))))
                .collect())
        }
    }
}

/// `Uint8Array.from(iterable[, mapFn])` / `Uint8Array.of(...items)`.
pub fn static_call(kind: &str, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
    Some(match method {
        "of" => Ok(make(
            kind,
            args.iter()
                .map(|x| coerce(kind, with_host(|h| h.to_number(x))))
                .collect(),
        )),
        "from" => from(kind, args),
        _ => return None,
    })
}

fn from(kind: &str, args: &[Value]) -> Result<Value, String> {
    let src = args.first().cloned().unwrap_or(Value::Undef);
    let map_fn = args
        .get(1)
        .cloned()
        .filter(|f| with_host(|h| crate::host::is_callable(h, f)));
    let items = if let Some(e) = elems_of(&src) {
        e.into_iter().map(Value::Float).collect()
    } else {
        crate::host::iter_all(&src).unwrap_or_default()
    };
    let mut out = Vec::with_capacity(items.len());
    for (i, it) in items.into_iter().enumerate() {
        let mapped = match &map_fn {
            Some(f) => crate::host::invoke(f, vec![it, Value::Float(i as f64)], None)?,
            None => it,
        };
        out.push(coerce(kind, with_host(|h| h.to_number(&mapped))));
    }
    Ok(make(kind, out))
}

/// The element values of a typed array / Buffer (`None` for anything else).
fn elems_of(v: &Value) -> Option<Vec<f64>> {
    let tag = super::native_tag(v)?;
    let field = match tag.as_str() {
        "TypedArray" => "@@elems",
        "Buffer" => "@@bytes",
        _ => return None,
    };
    with_host(|h| match h.get(v) {
        Some(JsObj::Object(p)) => match p.get(field).and_then(|a| h.get(a)) {
            Some(JsObj::Array(items)) => Some(items.iter().map(|x| h.to_number(x)).collect()),
            _ => None,
        },
        _ => None,
    })
}

/// The `@@kind` of a typed-array receiver (defaults to `Uint8Array`).
fn kind_of(recv: &Value) -> String {
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => p
            .get("@@kind")
            .map(|v| h.str_of(v))
            .unwrap_or_else(|| "Uint8Array".into()),
        _ => "Uint8Array".into(),
    })
}

// ── element indexing (called from builtins::get_property/set_property) ────────

/// `ta[i]` read: the element at char/index `i`, or `None` if `i` is out of range
/// or not an integer index.
pub fn elem_get(recv: &Value, key: &str) -> Option<Value> {
    let i: usize = key.parse().ok()?;
    with_host(|h| match h.get(recv) {
        Some(JsObj::Object(p)) => match p.get("@@elems").and_then(|a| h.get(a)) {
            Some(JsObj::Array(items)) => items.get(i).cloned(),
            _ => None,
        },
        _ => None,
    })
}

/// `ta[i] = v` write (coerced to the kind). Returns true if `i` is a valid index.
pub fn elem_set(recv: &Value, key: &str, val: &Value) -> bool {
    let Ok(i) = key.parse::<usize>() else {
        return false;
    };
    let kind = kind_of(recv);
    let n = coerce(&kind, with_host(|h| h.to_number(val)));
    with_host(|h| {
        if let Some(JsObj::Object(p)) = h.get(recv) {
            if let Some(arr) = p.get("@@elems").cloned() {
                if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
                    if i < items.len() {
                        items[i] = Value::Float(n);
                        return true;
                    }
                }
            }
        }
        false
    })
}

/// Typed-array instance methods.
pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
    let kind = kind_of(recv);
    let elems = elems_of(recv).unwrap_or_default();
    match method {
        "toString" | "join" => {
            let sep = if method == "join" && !args.is_empty() {
                super::arg_str(args, 0)
            } else {
                ",".into()
            };
            let parts: Vec<String> =
                with_host(|h| elems.iter().map(|n| h.str_of(&Value::Float(*n))).collect());
            Ok(with_host(|h| h.new_str(parts.join(&sep))))
        }
        "slice" | "subarray" => {
            let len = elems.len();
            let norm = |n: f64| -> usize {
                if n < 0.0 {
                    (len as f64 + n).max(0.0) as usize
                } else {
                    (n as usize).min(len)
                }
            };
            let s = if args.is_empty() {
                0
            } else {
                norm(super::arg_num(args, 0))
            };
            let e = if args.len() < 2 {
                len
            } else {
                norm(super::arg_num(args, 1))
            };
            Ok(make(&kind, elems[s.min(e)..e.max(s)].to_vec()))
        }
        "indexOf" => {
            let needle = super::arg_num(args, 0);
            Ok(Value::Float(
                elems
                    .iter()
                    .position(|x| *x == needle)
                    .map(|p| p as f64)
                    .unwrap_or(-1.0),
            ))
        }
        "includes" => {
            let needle = super::arg_num(args, 0);
            Ok(Value::Bool(elems.contains(&needle)))
        }
        "fill" => {
            let v = coerce(&kind, super::arg_num(args, 0));
            Ok(make(&kind, vec![v; elems.len()]))
        }
        "set" => {
            // `ta.set(src[, offset])` — write `src`'s values in place.
            let src = elems_of(&args.first().cloned().unwrap_or(Value::Undef))
                .or_else(|| {
                    Some(
                        crate::host::iter_all(&args.first().cloned().unwrap_or(Value::Undef))
                            .ok()?
                            .iter()
                            .map(|x| with_host(|h| h.to_number(x)))
                            .collect(),
                    )
                })
                .unwrap_or_default();
            let off = super::arg_num(args, 1).max(0.0) as usize;
            with_host(|h| {
                if let Some(JsObj::Object(p)) = h.get(recv) {
                    if let Some(arr) = p.get("@@elems").cloned() {
                        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
                            for (k, v) in src.iter().enumerate() {
                                if off + k < items.len() {
                                    items[off + k] = Value::Float(coerce(&kind, *v));
                                }
                            }
                        }
                    }
                }
            });
            Ok(Value::Undef)
        }
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}

// ── WeakRef (strong-ref approximation) ────────────────────────────────────────

pub fn construct_weakref(args: &[Value]) -> Result<Value, String> {
    let target = args.first().cloned().unwrap_or(Value::Undef);
    Ok(with_host(|h| {
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("WeakRef"));
        m.insert("@@target".into(), target);
        h.new_object(m)
    }))
}

pub fn weakref_call(recv: &Value, method: &str) -> Result<Value, String> {
    match method {
        "deref" => Ok(with_host(|h| match h.get(recv) {
            Some(JsObj::Object(p)) => p.get("@@target").cloned().unwrap_or(Value::Undef),
            _ => Value::Undef,
        })),
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}

// ── FinalizationRegistry (no-GC approximation) ────────────────────────────────
//
// This VM holds every value strongly (see `WeakRef` above), so a registered
// target is never reclaimed and the cleanup callback never fires. The ECMAScript
// spec permits an implementation to never call cleanup callbacks, so this is a
// conformant approximation: the constructor and `register`/`unregister` enforce
// their type checks and `unregister`'s bookkeeping exactly, only the (optional)
// callback invocation is absent. Registered unregister-tokens are tracked in a
// hidden `@@fr_tokens` array so `unregister` returns the correct boolean.

/// Whether `v` is an Object (a valid `register` target / unregister token) — a
/// heap value that is not one of the primitive-wrapper heap variants.
fn is_object_value(v: &Value) -> bool {
    matches!(v, Value::Obj(_))
        && with_host(|h| {
            !matches!(
                h.get(v),
                Some(JsObj::Str(_))
                    | Some(JsObj::Symbol { .. })
                    | Some(JsObj::BigInt(_))
                    | Some(JsObj::Null)
            )
        })
}

pub fn construct_finalization_registry(args: &[Value]) -> Result<Value, String> {
    let cb = args.first().cloned().unwrap_or(Value::Undef);
    if !with_host(|h| crate::host::is_callable(h, &cb)) {
        return Err(crate::host::type_error(
            "FinalizationRegistry: cleanup must be callable",
        ));
    }
    Ok(with_host(|h| {
        let tokens = h.new_array(Vec::new());
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("FinalizationRegistry"));
        m.insert("@@fr_cb".into(), cb);
        m.insert("@@fr_tokens".into(), tokens);
        h.new_object(m)
    }))
}

pub fn finalization_registry_call(
    recv: &Value,
    method: &str,
    args: &[Value],
) -> Result<Value, String> {
    match method {
        "register" => {
            let target = args.first().cloned().unwrap_or(Value::Undef);
            let held = args.get(1).cloned().unwrap_or(Value::Undef);
            let token = args.get(2).cloned().unwrap_or(Value::Undef);
            if !is_object_value(&target) {
                return Err(crate::host::type_error(
                    "FinalizationRegistry.prototype.register: target must be an object",
                ));
            }
            if with_host(|h| h.strict_eq(&target, &held)) {
                return Err(crate::host::type_error(
                    "FinalizationRegistry.prototype.register: target and holdings must not be same",
                ));
            }
            // A supplied unregister token must be an object; record it so a later
            // `unregister` can find (and drop) this registration.
            if !matches!(token, Value::Undef) {
                if !is_object_value(&token) {
                    return Err(crate::host::type_error(
                        "FinalizationRegistry.prototype.register: unregister token must be an object",
                    ));
                }
                with_host(|h| {
                    let toks = registry_tokens(h, recv);
                    if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
                        items.push(token);
                    }
                });
            }
            Ok(Value::Undef)
        }
        "unregister" => {
            let token = args.first().cloned().unwrap_or(Value::Undef);
            if !is_object_value(&token) {
                return Err(crate::host::type_error(
                    "FinalizationRegistry.prototype.unregister: unregister token must be an object",
                ));
            }
            Ok(Value::Bool(with_host(|h| {
                let toks = registry_tokens(h, recv);
                let kept: Vec<Value> = match h.get(&toks) {
                    Some(JsObj::Array(items)) => items
                        .iter()
                        .filter(|t| !h.strict_eq(t, &token))
                        .cloned()
                        .collect(),
                    _ => Vec::new(),
                };
                let removed = match h.get(&toks) {
                    Some(JsObj::Array(items)) => items.len() != kept.len(),
                    _ => false,
                };
                if let Some(JsObj::Array(items)) = h.get_mut(&toks) {
                    *items = kept;
                }
                removed
            })))
        }
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}

/// The hidden `@@fr_tokens` array backing a `FinalizationRegistry`.
fn registry_tokens(h: &crate::host::JsHost, recv: &Value) -> Value {
    match h.get(recv) {
        Some(JsObj::Object(p)) => p.get("@@fr_tokens").cloned().unwrap_or(Value::Undef),
        _ => Value::Undef,
    }
}

// ── TextEncoder / TextDecoder ─────────────────────────────────────────────────

pub fn construct_text_encoder() -> Result<Value, String> {
    Ok(with_host(|h| {
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("TextEncoder"));
        m.insert("encoding".into(), h.new_str("utf-8"));
        h.new_object(m)
    }))
}

pub fn text_encoder_call(_recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
    match method {
        // `encode(str)` → a Uint8Array of the UTF-8 bytes.
        "encode" => {
            let s = super::arg_str(args, 0);
            Ok(make(
                "Uint8Array",
                s.as_bytes().iter().map(|b| *b as f64).collect(),
            ))
        }
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}

pub fn construct_text_decoder(args: &[Value]) -> Result<Value, String> {
    let label = if args.is_empty() {
        "utf-8".to_string()
    } else {
        super::arg_str(args, 0)
    };
    Ok(with_host(|h| {
        let mut m = IndexMap::new();
        m.insert("@@native".into(), h.new_str("TextDecoder"));
        m.insert("encoding".into(), h.new_str(label.to_ascii_lowercase()));
        h.new_object(m)
    }))
}

pub fn text_decoder_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
    match method {
        // `decode(bytes)` → a string from the buffer's UTF-8 (or latin1) bytes.
        "decode" => {
            let bytes: Vec<u8> = elems_of(&args.first().cloned().unwrap_or(Value::Undef))
                .unwrap_or_default()
                .iter()
                .map(|n| *n as u8)
                .collect();
            let enc = with_host(|h| match h.get(recv) {
                Some(JsObj::Object(p)) => p
                    .get("encoding")
                    .map(|v| h.str_of(v))
                    .unwrap_or_else(|| "utf-8".into()),
                _ => "utf-8".into(),
            });
            let s = match enc.as_str() {
                "latin1" | "iso-8859-1" | "ascii" => bytes.iter().map(|b| *b as char).collect(),
                _ => String::from_utf8_lossy(&bytes).into_owned(),
            };
            Ok(with_host(|h| h.new_str(s)))
        }
        _ => Err(crate::host::type_error(&format!(
            "{method} is not a function"
        ))),
    }
}