use std::collections::BTreeMap;
use quickjs::module::{LoadedModule, ModuleLoader};
use quickjs::{Context, Runtime};
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);
code.source = Some(source.to_string());
js_compile::serialize::serialize_with(&code, js_compile::serialize::Options { keep_source })
}
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()
}
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)
}
#[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");
}
#[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);
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);
}
#[test]
fn the_source_text_is_optional() {
let source = "function named(){ return 1 }\nprint(named.toString());\n";
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"));
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"));
let (blob, _) = from_bytecode(&kept);
assert_eq!(blob, "function named() {\n [native code]\n}\n");
}
#[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");
}
#[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");
}
#[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");
context.eval_bytecode(&main_bytes).expect("run main");
assert_eq!(context.output(), "x 42 bump 43\n");
}
#[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");
}
#[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}"
);
}
#[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}"
);
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(), "");
}