lumbda/wasm/tests/integration.mjs
russell@unturf.com 346b873247
wasm: three-tier Lumbda to WebAssembly + browser playground
Adds a parallel build of all three Lumbda implementations to WASM, a
single-page playground at www/playground/, and a verified test suite.

Tiers
  - Python: Pyodide (CPython-in-WASM) hosting lumbda.py
  - C:      Emscripten build of c/ (tree-walker + bytecode VM; jit.c
            stubbed, gc.c uses its existing no-Boehm fallback)
  - Asm:    hand-written asm/lumbda.wat — parallel impl to asm/lumbda.s.
            Reader, eval (lambda/define/if/cond/let/and/or/quote/set!),
            recursion across mutated top-level env, bump allocator with
            memory.grow, 24 primitives. ~1200 lines of raw WAT.

SPA (wasm/app/, deployed to www/playground/)
  - CodeMirror 6 editor (Scheme highlighting) on left, output on right
  - Radios: 4 demos (Mandelbrot, Fib+Ack, Sieve, self-interp meta-eval)
            x 4 tiers (Python | C | Asm | All three)
  - All-three mode renders the three tier outputs side by side with
    per-tier elapsed timing

Tests (38 verified assertions)
  - 20 unit (Node): per-tier module loads, eval smoke
  - 8 integration (Node): each demo on c+asm WASM byte-matches the
                          canonical native Python run
  - 10 functional (Playwright headless Chromium): page mounts, every
                          demo runs on every tier, all-three renders

Makefile
  - Root targets: wasm-build, wasm-test, wasm-test-fn, wasm-serve,
                  wasm-deploy, wasm-clean
  - wasm/Makefile orchestrates the three tier builds; deploy copies
    dist/ into www/playground/

Asm tier notes
  - WAT linear symbol intern + linear env lookup is MOAD-0001 at scale;
    documented in the asm/lumbda.wat header and in the SPA footer. The
    demos hit ~30 globals so the linear walks are cheap enough.
  - Bump allocator never frees (matches asm/lumbda.s heap discipline);
    memory.grow expands by 1 MB chunks. Browser tab tears down at unload.

Toolchain (developer prerequisites)
  - Emscripten 6.0.0 via emsdk at ~/git/emsdk
  - wabt 1.0.36 at ~/git/wabt
  - Playwright for functional tests (symlinked from ~/git/agnt)
2026-06-14 11:40:34 -04:00

102 lines
4 KiB
JavaScript

// wasm/tests/integration.mjs
// Cross-tier integration — each demo runs on c-WASM and asm-WASM (Node
// hosts), output is compared to the canonical native Python lumbda run.
// Python tier (Pyodide) loads from a CDN inside a browser; covered in the
// functional/Playwright test suite.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const dist = path.resolve(here, "..", "dist");
const repoRoot = path.resolve(here, "..", "..");
const demosDir = path.join(here, "..", "app", "demos");
const DEMOS = ["mandelbrot", "fib-ack", "sieve", "self-interp"];
const state = { pass: 0, fail: 0, failures: [] };
function check(name, cond, detail) {
if (cond) { state.pass++; console.log(`${name}`); }
else { state.fail++; console.log(`${name}`); if (detail) { console.log(detail); } state.failures.push({ name, detail }); }
}
function nativePython(demoPath) {
return execFileSync("python3", [path.join(repoRoot, "lumbda.py"), "--fast", demoPath], {
encoding: "utf8", timeout: 120000,
});
}
async function runAsm(src) {
const wasmBytes = fs.readFileSync(path.join(dist, "asm", "lumbda-asm.wasm"));
const { instance } = await WebAssembly.instantiate(wasmBytes);
const exp = instance.exports;
exp.lumbda_init();
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()));
}
async function runC(src) {
const { createRequire } = await import("node:module");
const require = createRequire(import.meta.url);
const createLumbdaC = require(path.join(dist, "c", "lumbda-c.js"));
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 r = m.cwrap("lumbda_wasm_eval", "number", ["string"])(src);
let errMsg = "";
if (r) errMsg = m.UTF8ToString(r);
return out.join("\n") + (errMsg ? "\n" + errMsg : "") + (out.length ? "\n" : "");
}
function diffSnippet(a, b) {
const aL = a.split("\n");
const bL = b.split("\n");
const n = Math.max(aL.length, bL.length);
const lines = [];
for (let i = 0; i < n; i++) {
if (aL[i] !== bL[i]) {
lines.push(` line ${i + 1}:`);
lines.push(` canonical: ${JSON.stringify(aL[i])}`);
lines.push(` got: ${JSON.stringify(bL[i])}`);
if (lines.length > 10) { lines.push(" ... (truncated)"); break; }
}
}
return lines.join("\n");
}
(async () => {
for (const demo of DEMOS) {
console.log(`── ${demo} ──`);
const demoPath = path.join(demosDir, demo + ".lsp");
const src = fs.readFileSync(demoPath, "utf8");
let canonical;
try { canonical = nativePython(demoPath); }
catch (e) { console.log(" ✗ canonical (native python lumbda) FAILED:", e.message.slice(0, 200)); state.fail++; continue; }
try {
const asmOut = await runAsm(src);
check(`${demo}: asm tier matches canonical`,
asmOut === canonical,
diffSnippet(canonical, asmOut));
} catch (e) { check(`${demo}: asm tier`, false, " threw: " + e.message); }
try {
const cOut = await runC(src);
check(`${demo}: c tier matches canonical`,
cOut === canonical,
diffSnippet(canonical, cOut));
} catch (e) { check(`${demo}: c tier`, false, " threw: " + e.message); }
}
console.log(`\n${state.pass} passed, ${state.fail} failed`);
process.exit(state.fail ? 1 : 0);
})();