lumbda/wasm/python/lumbda-py.js
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

80 lines
2.7 KiB
JavaScript

// wasm/python/lumbda-py.js
// Python tier loader — Pyodide (CPython-in-WASM) hosting lumbda.py.
//
// Exports createPythonTier() -> Promise<{ evalLisp(src) -> Promise<string> }>.
// Output is whatever the program printed (via display/print/write) plus the
// final value's printed form if non-void.
const PYODIDE_VERSION = "0.27.2";
const PYODIDE_INDEX_URL = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`;
async function _bootstrap(baseURL) {
// Load Pyodide loader script (sets globalThis.loadPyodide).
if (typeof loadPyodide === "undefined") {
await new Promise((resolve, reject) => {
const s = document.createElement("script");
s.src = PYODIDE_INDEX_URL + "pyodide.js";
s.onload = resolve;
s.onerror = () => reject(new Error("pyodide.js load failed"));
document.head.appendChild(s);
});
}
const pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX_URL });
// Pull lumbda.py + stdlib.lsp into Pyodide's virtual FS.
const lumbdaSrc = await (await fetch(baseURL + "lumbda.py")).text();
const stdlibSrc = await (await fetch(baseURL + "stdlib.lsp")).text();
pyodide.FS.writeFile("/home/pyodide/lumbda.py", lumbdaSrc);
pyodide.FS.writeFile("/home/pyodide/stdlib.lsp", stdlibSrc);
// Initialize the lumbda environment once. We swap sys.stdout to a StringIO
// buffer per eval to capture program output.
await pyodide.runPythonAsync(`
import sys, io
sys.path.insert(0, "/home/pyodide")
import lumbda
_env = lumbda.make_global_env()
for _e in lumbda.read_all(lumbda.PRELUDE):
lumbda.leval(_e, _env)
def _lumbda_eval(src):
buf = io.StringIO()
old = sys.stdout
sys.stdout = buf
last = None
try:
for e in lumbda.read_all(src):
last = lumbda.leval(e, _env)
except Exception as ex:
sys.stdout = old
return f"{buf.getvalue()}error: {ex}"
sys.stdout = old
out = buf.getvalue()
if last is not None and not isinstance(last, lumbda._Void):
rep = lumbda.show(last)
if out and not out.endswith("\\n"):
out += "\\n"
out += rep
return out
`);
return {
async evalLisp(src) {
// Pass src in via globals to avoid escaping issues.
pyodide.globals.set("_src_in", src);
const result = await pyodide.runPythonAsync("_lumbda_eval(_src_in)");
return result;
},
};
}
// Closure-encapsulated singleton (see lumbda-c.loader.js for rationale).
export const createPythonTier = (() => {
let tier = null;
return async (baseURL) => {
baseURL = baseURL || "./python/";
if (!tier) tier = await _bootstrap(baseURL);
return tier;
};
})();