quickjs-pure 0.9.0

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! Running from bytecode alone: the AOT path, without the AOT tool.
//!
//! A blob is what `qjsc` embeds. The property that matters is not "it deserialises" but
//! **it runs the same as the source did** — every table the compiler had to hand the
//! runtime has to survive the trip, and there are four that are easy to lose silently:
//!
//! * the file name — dropped, every stack frame reports `<input>`;
//! * the source text — dropped, `Function.prototype.toString` answers `[native code]`;
//! * the eval-site table — dropped, a direct `eval` resolves a shadowed name to the wrong
//!   slot;
//! * the module tables — dropped, a module blob runs with no imports wired up.
//!
//! Each case below is run twice, once from source and once from the blob, and the two
//! outputs must be identical. That is a stronger statement than checking a few values: it
//! covers stack text and error text too.

use std::collections::BTreeMap;

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

/// Compile `source` and hand back the blob an AOT compiler would embed.
fn compile_to_bytes(source: &str, name: &str, keep_source: bool) -> Vec<u8> {
    let program = js_parse::parse_script(source).expect("parse");
    let mut code = js_compile::compile_script(&program).expect("compile");
    code.set_filename(name);
    // The host supplies the text, exactly as `qjs` does for a file it read; whether the
    // blob keeps it is the writer's `Options::keep_source`.
    code.source = Some(source.to_string());
    js_compile::serialize::serialize_with(&code, js_compile::serialize::Options { keep_source })
}

/// Run `source` as a script, returning everything the host would print.
fn from_source(source: &str) -> String {
    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    context.set_script_name("<test>");
    let _ = context.eval(source);
    context.output().to_string()
}

/// Run the same program from bytecode.
fn from_bytecode(bytes: &[u8]) -> (String, Option<String>) {
    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    let error = context
        .eval_bytecode(bytes)
        .err()
        .map(|error| error.to_string());
    (context.output().to_string(), error)
}

fn same_from_both(source: &str, keep_source: bool) -> (String, String) {
    let bytes = compile_to_bytes(source, "<test>", keep_source);
    let (blob_output, blob_error) = from_bytecode(&bytes);
    let source_output = from_source(source);
    assert_eq!(
        blob_error, None,
        "the blob must run without an error; source produced {source_output:?}"
    );
    assert_eq!(blob_output, source_output);
    (blob_output, source_output)
}

/// The plain case: a script that prints.
#[test]
fn a_script_runs_the_same_from_bytecode() {
    let (blob, _) = same_from_both(
        r#"
        const xs = [1, 2, 3];
        print(xs.map((x) => x * 2).join("-"));
        function add(a, b = 10) { return a + b }
        print(add(1), add(1, 2));
        "#,
        false,
    );
    assert_eq!(blob, "2-4-6\n11 3\n");
}

/// A throw reports the *compiled* file name and position, not `<input>`.
#[test]
fn stack_frames_keep_their_file_name() {
    let source = r#"
        function boom() { throw new Error("bad") }
        try { boom() } catch (e) { print(e.stack) }
        "#;
    let (blob, from_source_output) = same_from_both(source, false);
    // Both frames, both named: the blob has to carry the file name *and* the position
    // table, since a frame is a lookup by bytecode offset.
    assert!(
        blob.contains("at boom (<test>:2:") && blob.contains("at <eval> (<test>:3:"),
        "the frames must name the compiled file: {blob:?}"
    );
    assert_eq!(blob, from_source_output);
}

/// The source text survives only when the writer kept it, which is `qjsc --keep-source`.
#[test]
fn the_source_text_is_optional() {
    let source = "function named(){ return 1 }\nprint(named.toString());\n";

    // Stripped: the default, and what `-s`/`--strip-source` mean. What is left is the
    // same shape the reference prints for a function it has no source for.
    let stripped = compile_to_bytes(source, "<test>", false);
    let (blob, _) = from_bytecode(&stripped);
    assert_eq!(blob, "function named() {\n    [native code]\n}\n");
    assert!(!blob.contains("return 1"));

    // Kept: the text is in the blob. It is not what `toString` reads *yet* — that reports
    // `[native code]` for user functions whether or not the source is around, a separate
    // gap listed in README — so what is asserted here is the format, not the output.
    let kept = compile_to_bytes(source, "<test>", true);
    assert!(
        kept.len() > stripped.len(),
        "keeping the source must make the blob bigger"
    );
    assert!(
        String::from_utf8_lossy(&kept).contains("function named(){ return 1 }"),
        "the kept blob must carry the source text"
    );
    assert!(!String::from_utf8_lossy(&stripped).contains("return 1"));
    // …and the round trip still yields a runnable program.
    let (blob, _) = from_bytecode(&kept);
    assert_eq!(blob, "function named() {\n    [native code]\n}\n");
}

/// A direct `eval` resolves names through the compiler's eval-site table, which is not
/// derivable from the bytecode: two sibling blocks can bind the same name.
#[test]
fn a_direct_eval_still_finds_the_right_binding() {
    let source = r#"
        for (let i = 0; i < 1; i++) { print(eval("i")) }
        for (let i = 10; i < 11; i++) { print(eval("i")) }
        "#;
    let (blob, from_source_output) = same_from_both(source, false);
    assert_eq!(blob, from_source_output);
    assert_eq!(blob, "0\n10\n");
}

/// A module blob runs with its requests resolved through the host loader, so a
/// precompiled entry module can import ordinary source files.
#[test]
fn a_module_blob_imports_source_files() {
    struct MemoryLoader {
        sources: BTreeMap<String, Vec<u8>>,
    }
    impl ModuleLoader for MemoryLoader {
        fn load(
            &self,
            specifier: &str,
            _attributes: &[(String, String)],
            _referrer: &str,
        ) -> Result<LoadedModule, String> {
            let source = self
                .sources
                .get(specifier)
                .ok_or_else(|| format!("could not load module '{specifier}'"))?
                .clone();
            Ok(LoadedModule {
                name: specifier.to_string(),
                url: specifier.to_string(),
                source,
            })
        }
    }

    let module_source = r#"
        import { value, bump } from "/dep.js";
        print("entry sees", value);
        bump();
        print("after bump", value);
        export { value };
    "#;
    let program = js_parse::parse_module(module_source).expect("parse module");
    let mut code = js_compile::compile_module(&program).expect("compile module");
    code.set_filename("/main.js");
    assert!(
        code.module
            .as_ref()
            .is_some_and(|meta| !meta.requests.is_empty()),
        "the compile unit must carry its requests"
    );
    let bytes = js_compile::serialize::serialize(&code);

    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    context.set_module_loader(Box::new(MemoryLoader {
        sources: BTreeMap::from([(
            "/dep.js".to_string(),
            b"export let value = 1; export function bump() { value++ }".to_vec(),
        )]),
    }));
    context.eval_bytecode(&bytes).expect("run the module blob");
    assert_eq!(context.output(), "entry sees 1\nafter bump 2\n");
}

/// A module that ships as a blob and is registered by name: an import of it never reaches
/// the loader.
///
/// The context here has **no loader at all**, which is what a product is. If the name in
/// the registry were not exactly what the entry's request resolves to, this would fail with
/// "could not load module filename" — the failure mode that makes name agreement the whole
/// game.
#[test]
fn a_registered_module_is_found_without_a_loader() {
    let dep_source = "export const x = 42;\nexport function bump() { return x + 1 }\n";
    let dep_program = js_parse::parse_module(dep_source).expect("parse");
    let mut dep_code = js_compile::compile_module(&dep_program).expect("compile");
    dep_code.set_filename("dep.js");
    let dep_bytes = js_compile::serialize::serialize(&dep_code);

    let main_source = r#"
        import { x, bump } from "./dep.js";
        print("x", x, "bump", bump());
        "#;
    let main_program = js_parse::parse_module(main_source).expect("parse");
    let mut main_code = js_compile::compile_module(&main_program).expect("compile");
    main_code.set_filename("main.js");
    let main_bytes = js_compile::serialize::serialize(&main_code);

    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    context.register_module(&dep_bytes).expect("register dep");
    // No `set_module_loader`: every module here is in memory.
    context.eval_bytecode(&main_bytes).expect("run main");
    assert_eq!(context.output(), "x 42 bump 43\n");
}

/// A data module registered by name: a value, not code.
#[test]
fn a_registered_data_module_is_found_without_a_loader() {
    let main_source = r#"
        import data from "./data.json" with { type: "json" };
        print("a", data.a, "b", data.b.join("+"));
        "#;
    let program = js_parse::parse_module(main_source).expect("parse");
    let mut code = js_compile::compile_module(&program).expect("compile");
    code.set_filename("main.js");
    let bytes = js_compile::serialize::serialize(&code);

    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    context
        .register_data_module(
            "data.json",
            br#"{"a": 1, "b": [2, 3]}"#.to_vec(),
            &[("type".to_string(), "json".to_string())],
        )
        .expect("register data");
    context.eval_bytecode(&bytes).expect("run main");
    assert_eq!(context.output(), "a 1 b 2+3\n");
}

/// A missing module with no loader installed reports the missing *file*, which is what the
/// reference says, rather than an internal error about the host's setup.
#[test]
fn a_missing_module_names_the_file() {
    let source = "import { x } from \"./gone.js\";\nprint(x);\n";
    let program = js_parse::parse_module(source).expect("parse");
    let mut code = js_compile::compile_module(&program).expect("compile");
    code.set_filename("main.js");
    let bytes = js_compile::serialize::serialize(&code);

    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);
    let error = context.eval_bytecode(&bytes).unwrap_err();
    let text = error.to_string();
    assert!(
        text.contains("could not load module filename 'gone.js'"),
        "{text}"
    );
}

/// A blob from another format version, or one that has been edited, is rejected loudly.
#[test]
fn a_bad_blob_is_rejected() {
    let runtime = Runtime::new();
    let mut context = Context::new(&runtime);

    let error = context.eval_bytecode(b"not bytecode at all").unwrap_err();
    assert!(
        format!("{error}").contains("invalid bytecode"),
        "a wrong magic number must say so: {error}"
    );

    // Truncating a valid blob must not run a prefix of the program.
    let bytes = compile_to_bytes("print(1)", "<test>", false);
    let truncated = &bytes[..bytes.len() - 8];
    assert!(context.eval_bytecode(truncated).is_err());
    assert_eq!(context.output(), "");
}