Web × AI Architecture Lab · Local Compute

Live .wat-to-.wasm Compiler & Equivalence Gate

Companion experiment for WAT the heck? — compiles compact WebAssembly Text (.wat) S-expressions to binary .wasm at runtime in the browser and on a Cloudflare Worker, enforces a fail-closed Wasm(x) === JS(x) equivalence gate, races cold compilation against warm loops, and isolates DOM updates behind explicit host imports.

GitHub Source

Why compile raw .wat at runtime?

Instead of shipping a precompiled static binary, this page runs a zero-dependency S-expression compiler in JavaScript that parses any (module ...) text on demand in both your browser and the Cloudflare Worker (POST /api/compile-wat), then checks every test vector against a JS reference oracle before allowing execution or benchmarking.

Three measurements exposed below: (1) Estimated token count of .wat vs. equivalent JS. (2) Fail-closed detection of semantic mismatches without manual stack-code review. (3) Cold compile + instantiate latency vs. warm Wasm and JS JIT loops, including DOM host-import crossings.

Hypothesis

Compiling compact .wat directly to .wasm at runtime, gated by an automated Wasm(x) === JS(x) oracle, lets unreviewed stack instructions fail closed on semantic bugs without external compiler toolchains.

Confirm / Falsify Signals

Confirm: live compilation emits valid .wasm, mismatches block execution and DOM rendering, and pure CPU loops outrun JS. Falsify: cold compile latency, token verbosity, or DOM host-import crossings outweigh pure compute gains.

What to Try

1. Click Inject Bug to trigger the fail-closed equivalence gate. 2. Synthesize a new spec via Synthesize & Compile .wat. 3. Open DOM Host-Import Boundary to inspect dom.paint_bar crossings.

Does cold WAT compilation + execution still outrun JS JIT for pure arithmetic loops?

Compiles a trial-division prime counter `count_primes(limit)` directly from .wat text, verifies outputs against JS on 6 inputs, and measures Cold vs. Warm execution latency.

Raw .wat Size — Est. tokens: —
JS Reference Size — Est. tokens: —
Compiled .wasm Binary 176 B Compiled in 0 ms
Equivalence Test Gate Pending Checks Wasm(x) === JS(x)

Live WebAssembly Text (.wat)

Editable S-expression source compiled locally & on Cloudflare Workers
Ready.

Equivalent JavaScript Oracle

Reference implementation used for semantic verification & speed racing
export "count_primes"
function isPrime(n) {
  if (n < 2) return false;
  if (n === 2) return true;
  if ((n & 1) === 0) return false;
  for (let d = 3; d * d <= n; d += 2) {
    if (n % d === 0) return false;
  }
  return true;
}

export function count_primes(limit) {
  let count = 0;
  for (let i = 2; i <= limit; i++) {
    if (isPrime(i)) count++;
  }
  return count;
}

Equivalence Gate Results

Fail-closed behavior check: blocks execution if any test vector diverges
0 / 0 passed
Test Input JS Oracle Output Compiled .wasm Output Status

Cold vs. Warm Race & Host DOM Bridge

Compares first-call compile+instantiate cost against warm loop throughput
01 · Compiled .wasm Section Map & Binary Hex Dump 176 bytes

          
02 · Edge Worker Compiler Verification (POST /api/compile-wat) Click Compile & Verify to compare browser vs. edge output

Every compile action sends the current .wat source to the Cloudflare Worker at POST /api/compile-wat to verify identical section offsets and binary byte length outside the browser, alongside live-compiled application/wasm endpoints at /wasm/preset/<id>.wasm.

Pending verification...
03 · Supported S-Expression Grammar & Opcodes Zero-dependency compiler subset

Module & Structure

  • (module ...) with optional $id
  • (type ...), (import "mod" "name" (func|memory ...))
  • (func $id? (export "...")? (param ...)* (result ...)? (local ...)* ...)
  • (memory (export "memory")? min max?) and (data ...)

Control Flow & Instructions

  • Folded S-expressions (op (arg1) (arg2)) and flat linear opcodes
  • block, loop, if / then / else, br, br_if, call, return
  • i32 & f64 arithmetic, bitwise, comparison, conversions, load/store with offset=/align=
How This Is Set Up

Compilation, Fail-Closed Gate & Host-Import Boundary

Generated JavaScript executes with ambient access to window, document, and fetch. Compiling WebAssembly Text (.wat) to .wasm at runtime restricts the module to linear memory and explicitly declared host imports, while an automated Wasm(x) === JS(x) equivalence check fails closed on semantic divergence.

Ambient JavaScript DOM mutation
// Generated JS runs with ambient DOM and network authority
export function renderWidgetBars(count, seed) {
  const out = document.getElementById("chart"); // Ambient global DOM access
  for (let i = 0; i < count; i++) {
    const h = 16 + ((i * 29 + seed * 17) % 84);
    const bar = document.createElement("div");
    bar.textContent = String(h);
    out.appendChild(bar); // Direct DOM mutation without declared capability
  }
}
Capability-imported .wat module
;; public/lib/wat-presets.js — .wat bounded by explicit host import
(module
  (import "dom" "paint_bar" (func $paint_bar (param i32 i32 i32)))
  (func (export "render_bars") (param $count i32) (param $seed i32) (result i32)
    ;; Pure stack arithmetic over i32 locals; zero ambient DOM or fetch access
    (call $paint_bar (local.get $i) (local.get $h) (i32.rem_u (local.get $i) (i32.const 3)))
    (local.get $sum)
  )
)
Complete Page Setup: HTML Controls, Fail-Closed Gate & Worker Parity Route

Matches the live markup in renderHtml() (src/worker.ts), generateWatFromSpec() (public/lib/wat-presets.js), and the fail-closed verification loop in public/app.js.

<!-- 1. Page HTML Setup (src/worker.ts) -->
<form class="synth-bar" id="synth-form">
  <select id="spec-algorithm" name="algorithm">
    <option value="sum-squares">sum-squares</option>
    <option value="xor-checksum">xor-checksum</option>
    <option value="threshold-count">threshold-count</option>
    <option value="collatz-steps">collatz-steps</option>
  </select>
  <input id="spec-factor" name="factor" type="number" min="1" max="97" value="7" />
  <input id="spec-modulo" name="modulo" type="number" min="3" max="499" value="97" />
</form>
<textarea id="wat-editor" class="code-editor"></textarea>
<tbody id="equiv-tbody"></tbody>
<div id="dom-bridge-bars" class="dom-bars"></div>
<script type="module" src="/app.js"></script>

// 2. Runtime Compilation + Fail-Closed Equivalence Gate (public/app.js)
const compiled = compileWat(els.watEditor.value);
const { instance } = await WebAssembly.instantiate(compiled.wasm, {
  dom: {
    paint_bar(index, heightPx, band) {
      domEvents.push({ index, heightPx, band });
    }
  }
});

let passed = 0;
for (const input of state.activeItem.testInputs) {
  const jsOut = runJsReference(state.activeItem.id, input, { ...state.spec, seed: 7 });
  const wasmOut = invokeTarget(state.activeItem, instance.exports, input, state.spec, domEvents);
  if (wasmOut === jsOut) passed += 1;
}

if (passed !== state.activeItem.testInputs.length) {
  // Fail closed: block DOM host-import commit and benchmark execution
  renderFailClosedGate(passed, state.activeItem.testInputs.length);
  return;
}

// 3. Edge Worker Parity Route (src/worker.ts -> POST /api/compile-wat)
const res = await fetch("/api/compile-wat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ wat: els.watEditor.value })
});
What is removed

External C/Rust compiler toolchains for small generated routines and ambient window/document/fetch access inside pure compute logic.

What becomes explicit

Declared (import "dom" "paint_bar") host capabilities, fail-closed Wasm(x) === JS(x) equivalence checks, and deterministic binary sections.

Remaining trade-offs

Raw .wat often uses more tokens than equivalent JS, cold compile latency must amortize across warm iterations, and DOM/string marshaling still crosses linear memory or JS host imports.