quickjs-pure 0.14.2

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Modules: linking, cycles, namespaces, and data modules.
//!
//! The tests use an in-memory loader rather than the filesystem, which is the point of
//! `ModuleLoader` being a trait — the semantics under test are the graph's, not the
//! disk's. The two properties worth stating up front, because they are what most module
//! implementations get wrong:
//!
//! * **Live bindings.** `export let x` and a later `x = 1` is visible to the importer.
//!   Copying the value at link time passes every simple test and fails this one.
//! * **Cycles.** Two modules that import each other must link, hoist, and evaluate in
//!   the right order, so that a function in one is callable from the other's body.

use std::collections::BTreeMap;

use quickjs::module::{LoadedModule, ModuleLoader};

/// A loader over a fixed set of sources, keyed by the name a specifier resolves to.
struct MemoryLoader {
    sources: BTreeMap<String, Vec<u8>>,
}

impl MemoryLoader {
    /// Resolving `./x.js` against `/m/main.js` gives `/m/x.js`, exactly as a file loader
    /// would, without touching a disk. `.` and `..` are folded because a real loader
    /// canonicalises, and a specifier that only differs by a dot must be one module.
    fn resolve(specifier: &str, referrer: &str) -> String {
        if referrer.is_empty() {
            return specifier.to_string();
        }
        let dir = match referrer.rfind('/') {
            Some(index) => &referrer[..index],
            None => "",
        };
        let joined = format!("{dir}/{specifier}");
        let mut parts: Vec<&str> = Vec::new();
        for part in joined.split('/') {
            match part {
                "" | "." => {}
                ".." => {
                    parts.pop();
                }
                other => parts.push(other),
            }
        }
        format!("/{}", parts.join("/"))
    }
}

impl ModuleLoader for MemoryLoader {
    fn load(
        &self,
        specifier: &str,
        _attributes: &[(String, String)],
        referrer: &str,
    ) -> Result<LoadedModule, String> {
        let name = Self::resolve(specifier, referrer);
        let source = self
            .sources
            .get(&name)
            .cloned()
            .ok_or_else(|| format!("could not load module filename '{specifier}'"))?;
        Ok(LoadedModule {
            url: format!("file://{name}"),
            name,
            source,
        })
    }
}

/// Run `/m/main.js` in a world where `files` are the only sources that exist.
fn run(files: &[(&str, &str)]) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let sources = files
        .iter()
        .map(|(name, source)| (format!("/m/{name}"), source.as_bytes().to_vec()))
        .collect();
    ctx.set_module_loader(Box::new(MemoryLoader { sources }));
    match ctx.eval_module("/m/main.js") {
        Ok(_) => ctx.output().to_string(),
        Err(error) => panic!(
            "{files:?} failed: {error}\noutput so far:\n{}",
            ctx.output()
        ),
    }
}

/// Like [`run`], but the failure is what is being tested.
fn fails(files: &[(&str, &str)]) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let sources = files
        .iter()
        .map(|(name, source)| (format!("/m/{name}"), source.as_bytes().to_vec()))
        .collect();
    ctx.set_module_loader(Box::new(MemoryLoader { sources }));
    match ctx.eval_module("/m/main.js") {
        Ok(_) => panic!("{files:?} should have failed"),
        Err(error) => error.to_string(),
    }
}

#[test]
fn an_imported_binding_is_the_exporters_cell_not_a_copy() {
    // `bump()` runs in `lib.js` and assigns `counter` there; the importer must see it.
    // Copying at link time would leave `ns.counter` at 0 forever.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import def, * as ns from "./lib.js";
print("default:" + def);
print("keys:" + Object.keys(ns).join(","));
print("before:" + ns.counter);
ns.bump();
print("after:" + ns.counter);
"#
            ),
            (
                "lib.js",
                r#"
export let counter = 0;
export function bump() { counter++ }
export default "D";
"#
            ),
        ]),
        "default:D\nkeys:bump,counter,default\nbefore:0\nafter:1\n"
    );
}

#[test]
fn a_cycle_hoists_before_any_body_runs() {
    // `b.js` calls `a`'s function from its own top level. That only works because every
    // module in the cycle has had its hoisted bindings created during linking — before a
    // single body has run. Getting the order wrong here is the classic failure.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import { a } from "./a.js";
print("main:" + a(1));
"#
            ),
            (
                "a.js",
                r#"
import { b } from "./b.js";
export function a(x) { return x + 1 }
print("a sees b: " + typeof b);
"#
            ),
            (
                "b.js",
                r#"
import { a } from "./a.js";
export function b(x) { return 2 * a(x) }
print("b sees a: " + typeof a);
print("b calls a: " + a(1));
"#
            ),
        ]),
        // `b` evaluates first (it is the innermost dependency), and `a`'s function is
        // already there because linking hoisted both modules.
        "b sees a: function\nb calls a: 2\na sees b: function\nmain:2\n"
    );
}

#[test]
fn a_namespace_is_sorted_frozen_and_tagged() {
    // §10.4.6: sorted keys, not extensible, `[object Module]`. The getters make the
    // bindings live; the sort is what makes `Object.keys` deterministic.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import * as ns from "./lib.js";
print(Object.keys(ns).join(","));
print(Object.prototype.toString.call(ns));
print(Object.isExtensible(ns));
try { ns.extra = 1 } catch (e) { print("assign threw") }
print("extra" in ns);
"#
            ),
            (
                "lib.js",
                r#"
export const zebra = 1;
export const alpha = 2;
export function middle() {}
"#
            ),
        ]),
        "alpha,middle,zebra\n[object Module]\nfalse\nassign threw\nfalse\n"
    );
}

#[test]
fn re_exports_forward_names_and_their_own_default() {
    // `export *` forwards everything except `default`, while `export * as ns` and
    // `export { x } from` name things explicitly.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import * as barrel from "./barrel.js";
print("barrel keys:" + Object.keys(barrel).join(","));
print("a:" + barrel.a);
print("aliased:" + barrel.renamed);
print("ns:" + Object.keys(barrel.ns).join(","));
"#
            ),
            (
                "barrel.js",
                r#"
export * from "./base.js";
export { b as renamed } from "./base.js";
export * as ns from "./base.js";
"#
            ),
            (
                "base.js",
                r#"
export const a = "A";
export const b = "B";
export default "default-not-forwarded";
"#
            ),
        ]),
        // `b` appears twice over: once forwarded by `export *` under its own name and
        // once as `renamed`. `default` is absent, because `export *` never forwards it.
        "barrel keys:a,b,ns,renamed\na:A\naliased:B\nns:a,b,default\n"
    );
}

#[test]
fn json_and_text_modules_are_two_modules_from_one_file() {
    // The same path as JSON and as text: two records, two values. Keying the cache by
    // path alone would make the second import silently receive the first one's value.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import data from "./data.json";
import text from "./data.json" with { type: "text" };
print(JSON.stringify(data));
print(typeof text);
print(JSON.stringify(text));
"#
            ),
            ("data.json", "{\"n\": [1, 2]}"),
        ]),
        "{\"n\":[1,2]}\nstring\n\"{\\\"n\\\": [1, 2]}\"\n"
    );
}

#[test]
fn a_dynamic_import_settles_after_the_current_script() {
    // §13.3.10.1 makes `import()` settle through a job, so the synchronous tail runs
    // first — the same ordering rule a promise follows.
    assert_eq!(
        run(&[
            (
                "main.js",
                r#"
import("./lib.js").then(m => print("dynamic:" + m.value));
print("sync");
"#
            ),
            ("lib.js", "export const value = 42;\n"),
        ]),
        "sync\ndynamic:42\n"
    );
}

#[test]
fn a_missing_export_is_reported_at_link_time() {
    // `export { nope } from "m"` where `m` has no `nope`: the graph cannot be linked, and
    // saying so beats an `undefined` that surfaces at use.
    let text = fails(&[
        (
            "main.js",
            "import { nope } from \"./lib.js\";\nprint(nope);\n",
        ),
        ("lib.js", "export const yes = 1;\n"),
    ]);
    // The reference's wording, because an error message is behaviour.
    assert!(
        text.contains("Could not find export 'nope' in module"),
        "unexpected error: {text}"
    );
}

#[test]
fn a_module_has_no_arguments_and_no_global_leak() {
    // Module scope is not global scope: `var` here must not reach the global object, and
    // `arguments` must not exist at all.
    assert_eq!(
        run(&[(
            "main.js",
            r#"
var leaked = 1;
function f(){ return leaked }
print(f());
print(typeof arguments);
print(typeof globalThis.leaked);
"#
        ),]),
        "1\nundefined\nundefined\n"
    );
}

#[test]
fn import_meta_names_the_module_and_marks_the_entry() {
    assert_eq!(
        run(&[
            ("main.js", "print(import.meta.url); import \"./lib.js\";\n"),
            (
                "lib.js",
                "print(import.meta.url); print(import.meta.main);\n"
            ),
        ]),
        "file:///m/lib.js\nfalse\nfile:///m/main.js\n"
    );
}

#[test]
fn top_level_await_makes_evaluation_asynchronous() {
    // A module body with top-level `await` is compiled as an async function, so the host
    // runs it as a coroutine and waits. Without that the `await` suspends in a body
    // nothing knows how to resume — which surfaced as "a generator body ran as an
    // ordinary call", an internal error rather than a wrong answer.
    assert_eq!(
        run(&[(
            "main.js",
            r#"
const v = await Promise.resolve(7);
print("awaited:" + v);
export const out = v;
"#
        ),]),
        "awaited:7\n"
    );
}

#[test]
fn a_dependency_with_top_level_await_is_waited_for() {
    // The parent has no `await` of its own, but its dependency does: the graph's
    // evaluation is still asynchronous, so the parent's body must not run until the
    // dependency has settled.
    assert_eq!(
        run(&[
            (
                "main.js",
                "import { ready } from \"./dep.js\";\nprint(\"main sees: \" + ready);\n"
            ),
            (
                "dep.js",
                "const p = Promise.resolve(\"ready\");\nawait p;\n\
                 print(\"dep done\");\nexport const ready = \"ready\";\n"
            ),
        ]),
        "dep done\nmain sees: ready\n"
    );
}

#[test]
fn a_rejection_at_the_top_level_stops_the_module() {
    let text = fails(&[(
        "main.js",
        "await Promise.reject(new Error(\"top-level\"));\nprint(\"never\");\n",
    )]);
    assert!(text.contains("top-level"), "unexpected error: {text}");
}

#[test]
fn a_caught_top_level_rejection_continues() {
    assert_eq!(
        run(&[(
            "main.js",
            r#"
try { await Promise.reject(new Error("caught-here")) } catch (e) {
  print("caught:" + e.message);
}
print("after");
"#
        )]),
        "caught:caught-here\nafter\n"
    );
}

/// A `using` binding at the top level of a module *is* disposed, at module end.
///
/// This was a compiler panic — "a using binding was declared during hoisting" — because
/// module-level declarations become module cells rather than local slots, and the disposal
/// epilogue addresses its resources by slot. The reference excludes `using` from the
/// module-cell path on purpose (`var_def_type != JS_VAR_DEF_USING`, with the comment
/// "'using' variables are currently not exported in modules"), which makes it an ordinary
/// local of the module body function. That is what these tests pin: disposal works, in
/// reverse order, and also when the body throws.
#[test]
fn a_module_top_level_using_is_disposed_at_the_end() {
    assert_eq!(
        run(&[(
            "main.js",
            "using a = { [Symbol.dispose]() { print('dispose a') } };\n\
             using b = { [Symbol.dispose]() { print('dispose b') } };\n\
             print('body');\n"
        )]),
        "body\ndispose b\ndispose a\n"
    );
}

#[test]
fn a_module_top_level_using_is_disposed_when_the_body_throws() {
    let text = fails(&[(
        "main.js",
        "using a = { [Symbol.dispose]() { print('dispose a') } };\n\
         throw new Error('x');\n",
    )]);
    assert!(text.contains("Error: x"), "unexpected error: {text}");
}

/// A `using` binding is a local of the module body, so it cannot be exported.
///
/// The reference reports a *link* error for this, without a position — our parser makes the
/// same check itself, so it has to say so explicitly (`SyntaxError::positionless`).
#[test]
fn a_using_binding_cannot_be_exported() {
    assert_eq!(
        fails(&[(
            "main.js",
            "using a = { [Symbol.dispose]() {} };\nexport { a };\n"
        )]),
        // The trailing newline is the printer's: an error with an empty `stack` string
        // still gets the newline that precedes it.
        "SyntaxError: exported variable 'a' does not exist\n"
    );
}

/// The module body function object has no `name`, so a trace reaching it says
/// `<anonymous>`.
///
/// A *script* body says `<eval>`, which is its name. The reference builds the module's
/// function object with `js_closure2` and never runs `js_function_set_properties`
/// (`js_create_module_bytecode_function`), so the name property is simply absent.
#[test]
fn a_module_body_frame_is_anonymous() {
    let text = fails(&[(
        "main.js",
        "function inner() { throw new Error('x') }\ninner();\n",
    )]);
    assert!(
        text.contains("at <anonymous> (/m/main.js:2:6)"),
        "expected an anonymous module frame, got: {text}"
    );
}

// ---------------------------------------------------------------------------
// Native modules
// ---------------------------------------------------------------------------

/// A loader that answers one name with a *record* rather than bytes, which is the shape a C
/// module takes: by the time the loader runs, the exports are already values.
struct NativeLoader {
    /// Text sources, keyed by the name [`MemoryLoader`] would produce.
    sources: BTreeMap<String, Vec<u8>>,
    /// Root of the native module's name, e.g. `native.so`.
    native: String,
    /// The exports, taken once: a module is loaded once.
    exports: std::cell::RefCell<Option<Vec<(String, quickjs::Value)>>>,
}

impl ModuleLoader for NativeLoader {
    fn load(
        &self,
        specifier: &str,
        _attributes: &[(String, String)],
        referrer: &str,
    ) -> Result<LoadedModule, String> {
        // The same textual rule [`MemoryLoader`] uses, so a specifier resolves the same way
        // whether or not a native module is in play.
        let name = MemoryLoader::resolve(specifier, referrer);
        let source = self
            .sources
            .get(&name)
            .cloned()
            .ok_or_else(|| format!("could not load module filename '{specifier}'"))?;
        Ok(LoadedModule {
            url: format!("file://{name}"),
            name,
            source,
        })
    }

    fn load_native(
        &self,
        interp: &mut quickjs::Interp<'_>,
        name: &str,
    ) -> Option<Result<quickjs::Gc<quickjs::module::ModuleRecord>, String>> {
        if !name.ends_with(&self.native) {
            return None;
        }
        let exports = self.exports.borrow_mut().take()?;
        Some(Ok(interp.register_native_module(name, exports)))
    }
}

/// Run `/m/main.js` with a native module available under `/m/native.so`.
fn run_with_native(exports: Vec<(String, quickjs::Value)>) -> String {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let mut sources: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    sources.insert(
        "/m/main.js".to_string(),
        br#"
            import * as native from "./native.so";
            print(Object.keys(native).join(","));
            print(native.alpha, native.zeta);
            print(Object.prototype.toString.call(native));
            print(native[Symbol.toStringTag]);
            try { native.alpha = 9; print("wrote", native.alpha); }
            catch (e) { print("threw", e.name); }
        "#
        .to_vec(),
    );
    ctx.set_module_loader(Box::new(NativeLoader {
        sources,
        native: "native.so".to_string(),
        exports: std::cell::RefCell::new(Some(exports)),
    }));
    match ctx.eval_module("/m/main.js") {
        Ok(_) => ctx.output().to_string(),
        Err(error) => panic!("failed: {error}\noutput so far:\n{}", ctx.output()),
    }
}

#[test]
fn a_native_module_is_a_module() {
    // A C module is not a special case in the module system: its exports sort, its
    // namespace is `[object Module]`, and it is not writable. Anything else would be a
    // second implementation of namespaces, and the difference would show up in a script.
    let output = run_with_native(vec![
        ("zeta".to_string(), quickjs::Value::Int(2)),
        ("alpha".to_string(), quickjs::Value::Int(1)),
    ]);
    assert_eq!(
        output.trim_end(),
        "alpha,zeta\n1 2\n[object Module]\nModule\nthrew TypeError"
    );
}

#[test]
fn a_missing_native_module_is_a_load_error() {
    let rt = quickjs::Runtime::new();
    let mut ctx = quickjs::Context::new(&rt);
    let mut sources: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    sources.insert(
        "/m/main.js".to_string(),
        br#"import * as m from "./native.so";"#.to_vec(),
    );
    ctx.set_module_loader(Box::new(NativeLoader {
        sources,
        // Nothing answers `native.so`, so the loader falls through to reading bytes and
        // fails there — which is the message the reference prints for a missing `.so`.
        native: "other.so".to_string(),
        exports: std::cell::RefCell::new(None),
    }));
    let error = ctx.eval_module("/m/main.js").unwrap_err().to_string();
    assert!(
        error.contains("could not load module filename"),
        "unexpected error: {error}"
    );
}