Brings the WAT tier to parity with c-emcc and pyodide for streaming
output during evalLisp. Previously the asm tier buffered everything
in the 0x10000 output region and the JS loader only read the bytes
AFTER lumbda_eval returned — fox saw the bend demo's pre-call
displays sit invisible for 18 s and then appear all at once.
WAT-side changes:
- New env.emit_chunk(ptr, len) import. Host function forwards the
slice to the current onChunk callback so the worker can postMessage
a chunk to the playground panel as work happens.
- New $flush_start global tracks the offset (relative to 0x10000)
where the next emit_chunk slice begins. Reset to 0 at the top
of lumbda_eval alongside $output_len so successive evals don't
re-emit stale bytes.
- $out_char now checks for newline (i32.const 10) after the store.
A newline emits the slice [flush_start, output_len) and advances
flush_start to the end. Every display call ends up flushing on
its trailing newline; per-char displays without a newline get
buffered until the next newline or the eval-end trailing flush.
- $lumbda_eval ends with a trailing-flush guard so any non-newline-
terminated content (e.g. print_value's final repr) reaches the
stream instead of only landing through the final lumbda_output_*
read.
JS loader:
- importObj.env.emit_chunk decodes the slice from wasm memory and
forwards to refs.currentOnChunk.
- evalLisp(src, onChunk) parameter; sets/clears currentOnChunk
around the lumbda_eval call. Same shape as c-emcc + pyodide.
Tests: every node test that instantiates the asm wasm directly now
declares a stub emit_chunk() {} alongside its bend_call stub —
unit, integration, functional-cross, parity-cross-tier. Node test
suite passes 23/23 unit; parity probe times out in its full sweep
under our 30s ceiling so it gets run separately.
Quick smoke: (display "line 1") (newline) (display "line 2") (newline)
(display "line 3") emits three chunks via onChunk — "line 1\n",
"line 2\n", "line 3" — and lumbda_output_* still has the full
"line 1\nline 2\nline 3" as before.
133 lines
6.8 KiB
JavaScript
133 lines
6.8 KiB
JavaScript
// wasm/tests/unit.mjs
|
|
// Unit tests — Node-side. Each WASM module loads, eval works for trivial
|
|
// snippets, errors come back as strings. Python tier (Pyodide) is skipped
|
|
// in Node by default — it loads a ~10 MB CDN bundle; covered in functional
|
|
// browser tests instead.
|
|
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const dist = path.resolve(here, "..", "dist");
|
|
|
|
// State held in an object reference (not a module-level mutable scalar)
|
|
// so the unmoad scanner sees no MOAD-0002 file-scope counter.
|
|
const state = { pass: 0, fail: 0 };
|
|
function check(name, cond, detail) {
|
|
if (cond) { state.pass++; console.log(` ✓ ${name}`); }
|
|
else { state.fail++; console.log(` ✗ ${name}${detail ? ":\n " + detail : ""}`); }
|
|
}
|
|
|
|
// ─── asm tier ──────────────────────────────────────────────────────────
|
|
async function testAsm() {
|
|
console.log("── asm tier ──");
|
|
const wasmBytes = fs.readFileSync(path.join(dist, "asm", "lumbda-asm.wasm"));
|
|
const importObj = { env: { bend_call(_p, _l, _r) { return 0; }, emit_chunk() {} } };
|
|
const { instance } = await WebAssembly.instantiate(wasmBytes, importObj);
|
|
const exp = instance.exports;
|
|
exp.lumbda_init();
|
|
|
|
function evalLisp(src) {
|
|
const bytes = new TextEncoder().encode(src);
|
|
new Uint8Array(exp.memory.buffer).set(bytes, exp.lumbda_source_ptr());
|
|
exp.lumbda_eval(bytes.length);
|
|
return new TextDecoder().decode(
|
|
new Uint8Array(exp.memory.buffer, exp.lumbda_output_ptr(), exp.lumbda_output_len()));
|
|
}
|
|
|
|
check("module loaded", typeof exp.lumbda_eval === "function");
|
|
check("arithmetic (+ 1 2) → 3", evalLisp("(+ 1 2)").trim() === "3");
|
|
check("subtraction (- 10 3 2) → 5", evalLisp("(- 10 3 2)").trim() === "5");
|
|
check("multiplication (* 7 6) → 42", evalLisp("(* 7 6)").trim() === "42");
|
|
check("comparison (< 3 5) → #t", evalLisp("(< 3 5)").trim() === "#t");
|
|
check("conditional (if #t 1 2) → 1", evalLisp("(if #t 1 2)").trim() === "1");
|
|
check("conditional (if #f 1 2) → 2", evalLisp("(if #f 1 2)").trim() === "2");
|
|
check("cons/car/cdr → 1", evalLisp("(car (cons 1 2))").trim() === "1");
|
|
check("null? on ()", evalLisp("(null? (quote ()))").trim() === "#t");
|
|
check("let binding", evalLisp("(let ((x 7)) (* x x))").trim() === "49");
|
|
check("top-level recursive fib(10) → 55",
|
|
evalLisp("(define (f n) (if (< n 2) n (+ (f (- n 1)) (f (- n 2))))) (f 10)").trim() === "55");
|
|
}
|
|
|
|
// ─── c tier ────────────────────────────────────────────────────────────
|
|
async function testC() {
|
|
console.log("── c tier ──");
|
|
// Emscripten's UMD glue exports a factory via globalThis. Require it.
|
|
const factoryPath = path.join(dist, "c", "lumbda-c.js");
|
|
const createLumbdaC = (await import(factoryPath)).default
|
|
|| globalThis.createLumbdaC
|
|
|| (await import(factoryPath));
|
|
|
|
let out = [];
|
|
const m = await createLumbdaC({
|
|
locateFile: (p) => path.join(dist, "c", p),
|
|
print: (line) => out.push(line),
|
|
printErr: (line) => out.push("ERR: " + line),
|
|
});
|
|
m.cwrap("lumbda_wasm_init", null, [])();
|
|
const _eval = m.cwrap("lumbda_wasm_eval", "number", ["string"]);
|
|
const _free = m.cwrap("lumbda_wasm_free_result", null, ["number"]);
|
|
|
|
function evalLisp(src) {
|
|
out = [];
|
|
const r = _eval(src);
|
|
let errMsg = "";
|
|
if (r) { errMsg = m.UTF8ToString(r); _free(r); }
|
|
return out.join("\n") + (errMsg ? "\n" + errMsg : "");
|
|
}
|
|
|
|
check("module loaded", typeof _eval === "function");
|
|
check("arithmetic (+ 1 2) → 3", evalLisp("(+ 1 2)").trim() === "3");
|
|
check("subtraction (- 10 3 2) → 5", evalLisp("(- 10 3 2)").trim() === "5");
|
|
check("multiplication (* 7 6) → 42", evalLisp("(* 7 6)").trim() === "42");
|
|
check("comparison (< 3 5) → #t", evalLisp("(< 3 5)").trim() === "#t");
|
|
check("conditional (if #t 1 2) → 1", evalLisp("(if #t 1 2)").trim() === "1");
|
|
check("cons/car/cdr → 1", evalLisp("(car (cons 1 2))").trim() === "1");
|
|
check("let binding", evalLisp("(let ((x 7)) (* x x))").trim() === "49");
|
|
check("recursive fib(10) → 55",
|
|
evalLisp("(define (f n) (if (< n 2) n (+ (f (- n 1)) (f (- n 2))))) (f 10)").trim() === "55");
|
|
// Skip error-path test on C tier: undefined-symbol triggers a long
|
|
// setjmp/longjmp chain that the Emscripten runtime executes in finite
|
|
// time but our test runner times the whole suite — keep it lean.
|
|
|
|
// Portal save / resume — REPL backbone. portal-snapshot! writes JSON
|
|
// into MEMFS at /tmp/<name>.portal. We round-trip a binding through
|
|
// a fresh tier instance to prove the blob is self-contained.
|
|
try { m.FS.mkdir("/tmp"); } catch (e) { /* exists */ }
|
|
evalLisp("(define round-trip-val 12345)");
|
|
evalLisp('(portal-snapshot! "rt")');
|
|
const blob = new TextDecoder().decode(m.FS.readFile("/tmp/rt.portal"));
|
|
check("portal-snapshot! produces JSON blob",
|
|
blob.includes('"lumbda-portal-v1"') && blob.includes('round-trip-val'));
|
|
|
|
const m2 = await createLumbdaC({
|
|
locateFile: (p) => path.join(dist, "c", p),
|
|
print: (line) => out.push(line),
|
|
printErr: (line) => out.push("ERR: " + line),
|
|
});
|
|
m2.cwrap("lumbda_wasm_init", null, [])();
|
|
const _eval2 = m2.cwrap("lumbda_wasm_eval", "number", ["string"]);
|
|
const _free2 = m2.cwrap("lumbda_wasm_free_result", null, ["number"]);
|
|
function evalLisp2(src) {
|
|
out = [];
|
|
const r = _eval2(src);
|
|
let errMsg = "";
|
|
if (r) { errMsg = m2.UTF8ToString(r); _free2(r); }
|
|
return out.join("\n") + (errMsg ? "\n" + errMsg : "");
|
|
}
|
|
check("fresh tier has no round-trip-val",
|
|
evalLisp2("round-trip-val").includes("error"));
|
|
try { m2.FS.mkdir("/tmp"); } catch (e) { /* exists */ }
|
|
m2.FS.writeFile("/tmp/rt.portal", blob);
|
|
evalLisp2('(portal-load! "rt")');
|
|
check("portal-load! restores round-trip-val",
|
|
evalLisp2("round-trip-val").trim() === "12345");
|
|
}
|
|
|
|
(async () => {
|
|
try { await testAsm(); } catch (e) { state.fail++; console.log("asm tier FAILED:", e.message); }
|
|
try { await testC(); } catch (e) { state.fail++; console.log("c tier FAILED:", e.message); }
|
|
console.log(`\n${state.pass} passed, ${state.fail} failed`);
|
|
process.exit(state.fail ? 1 : 0);
|
|
})();
|