lumbda/wasm/tests/unit.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

99 lines
5.2 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 { instance } = await WebAssembly.instantiate(wasmBytes);
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.
}
(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);
})();