Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
<!doctype html>
|
|
|
|
|
<html>
|
|
|
|
|
<head>
|
|
|
|
|
<meta charset="utf-8" />
|
|
|
|
|
<title>NEScript jsnes harness</title>
|
|
|
|
|
<style>
|
|
|
|
|
body { margin: 0; background: #222; color: #eee; font-family: monospace; }
|
|
|
|
|
canvas { image-rendering: pixelated; background: #000; display: block; }
|
|
|
|
|
#info { padding: 8px; }
|
|
|
|
|
</style>
|
|
|
|
|
</head>
|
|
|
|
|
<body>
|
|
|
|
|
<canvas id="screen" width="256" height="240"></canvas>
|
|
|
|
|
<div id="info">waiting…</div>
|
|
|
|
|
<script src="./node_modules/jsnes/dist/jsnes.js"></script>
|
|
|
|
|
<script>
|
|
|
|
|
(function () {
|
|
|
|
|
const { NES } = window.jsnes;
|
|
|
|
|
const canvas = document.getElementById("screen");
|
|
|
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
|
const image = ctx.createImageData(256, 240);
|
|
|
|
|
// Pre-fill alpha channel so we don't have to do it every frame.
|
|
|
|
|
const buf = new ArrayBuffer(image.data.length);
|
|
|
|
|
const buf8 = new Uint8ClampedArray(buf);
|
|
|
|
|
const buf32 = new Uint32Array(buf);
|
|
|
|
|
for (let i = 0; i < buf32.length; i++) buf32[i] = 0xff000000;
|
|
|
|
|
|
2026-04-12 22:33:48 +00:00
|
|
|
// Audio recording buffers. `onAudioSample(l, r)` pushes one
|
|
|
|
|
// sample per channel; we collect both into growable int16 arrays
|
|
|
|
|
// so the runner can hash them for fast diffing or dump them as a
|
|
|
|
|
// WAV file when a diff fails. Samples are quantized to int16 at
|
|
|
|
|
// capture time — minor fp drift in jsnes shouldn't change the
|
|
|
|
|
// hash, and WAV output expects int16 anyway. The capacity grows
|
|
|
|
|
// exponentially to amortize reallocation; 3 seconds at 44.1 kHz
|
|
|
|
|
// is ~132k samples per channel which comfortably fits in the
|
|
|
|
|
// initial 64k allocation after one doubling.
|
|
|
|
|
const SAMPLE_RATE = 44100;
|
|
|
|
|
let audioLeft = new Int16Array(65536);
|
|
|
|
|
let audioRight = new Int16Array(65536);
|
|
|
|
|
let audioLen = 0;
|
|
|
|
|
|
|
|
|
|
function pushAudio(l, r) {
|
|
|
|
|
if (audioLen >= audioLeft.length) {
|
|
|
|
|
const next = new Int16Array(audioLeft.length * 2);
|
|
|
|
|
next.set(audioLeft);
|
|
|
|
|
audioLeft = next;
|
|
|
|
|
const next2 = new Int16Array(audioRight.length * 2);
|
|
|
|
|
next2.set(audioRight);
|
|
|
|
|
audioRight = next2;
|
|
|
|
|
}
|
|
|
|
|
// Clamp to [-1, 1] then scale to int16 range. jsnes nominally
|
|
|
|
|
// produces samples in [-1, 1] but we clamp defensively in case
|
|
|
|
|
// of numerical edge cases at high volumes.
|
|
|
|
|
let ll = l;
|
|
|
|
|
if (ll < -1) ll = -1;
|
|
|
|
|
else if (ll > 1) ll = 1;
|
|
|
|
|
let rr = r;
|
|
|
|
|
if (rr < -1) rr = -1;
|
|
|
|
|
else if (rr > 1) rr = 1;
|
|
|
|
|
audioLeft[audioLen] = (ll * 32767) | 0;
|
|
|
|
|
audioRight[audioLen] = (rr * 32767) | 0;
|
|
|
|
|
audioLen++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resetAudio() {
|
|
|
|
|
audioLen = 0;
|
|
|
|
|
}
|
|
|
|
|
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
const nes = new NES({
|
|
|
|
|
onFrame(frameBuffer) {
|
|
|
|
|
for (let i = 0; i < 256 * 240; i++) {
|
|
|
|
|
// jsnes pixel is 0x00BBGGRR in little-endian = 0xFFBBGGRR when alpha set
|
|
|
|
|
buf32[i] = 0xff000000 | frameBuffer[i];
|
|
|
|
|
}
|
|
|
|
|
image.data.set(buf8);
|
|
|
|
|
ctx.putImageData(image, 0, 0);
|
|
|
|
|
},
|
2026-04-12 22:33:48 +00:00
|
|
|
onAudioSample(l, r) {
|
|
|
|
|
pushAudio(l, r);
|
|
|
|
|
},
|
|
|
|
|
sampleRate: SAMPLE_RATE,
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Expose an API for puppeteer to drive.
|
|
|
|
|
window.nesHarness = {
|
|
|
|
|
loadRomBase64(b64) {
|
|
|
|
|
// atob produces a binary string, which is exactly what jsnes wants.
|
|
|
|
|
const bin = atob(b64);
|
2026-04-12 22:33:48 +00:00
|
|
|
// Wipe any stale audio samples left over from a previous
|
|
|
|
|
// ROM in the same page lifecycle (the runner reuses the
|
|
|
|
|
// puppeteer Page across ROMs in some configurations).
|
|
|
|
|
resetAudio();
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
nes.loadROM(bin);
|
|
|
|
|
},
|
|
|
|
|
frame() {
|
|
|
|
|
nes.frame();
|
|
|
|
|
},
|
|
|
|
|
runFrames(n) {
|
|
|
|
|
for (let i = 0; i < n; i++) nes.frame();
|
|
|
|
|
},
|
|
|
|
|
buttonDown(player, button) {
|
|
|
|
|
nes.buttonDown(player, button);
|
|
|
|
|
},
|
|
|
|
|
buttonUp(player, button) {
|
|
|
|
|
nes.buttonUp(player, button);
|
|
|
|
|
},
|
2026-04-12 22:33:48 +00:00
|
|
|
// Return an FNV-1a hash (32-bit, hex) over the full captured
|
|
|
|
|
// stereo int16 audio buffer. This is the golden-compare key
|
|
|
|
|
// — tiny enough to commit per-ROM alongside the PNG hash, and
|
|
|
|
|
// stable across runs because samples are pre-quantized to
|
|
|
|
|
// int16 at capture. A silent ROM hashes to a single well-
|
|
|
|
|
// known value; any audio-producing ROM gets a distinct hash
|
|
|
|
|
// that will immediately flag driver regressions.
|
|
|
|
|
audioHash() {
|
|
|
|
|
let h = 2166136261 >>> 0; // FNV-1a offset basis
|
|
|
|
|
for (let i = 0; i < audioLen; i++) {
|
|
|
|
|
const l = audioLeft[i] & 0xffff;
|
|
|
|
|
const r = audioRight[i] & 0xffff;
|
|
|
|
|
h ^= l & 0xff;
|
|
|
|
|
h = Math.imul(h, 16777619);
|
|
|
|
|
h ^= (l >> 8) & 0xff;
|
|
|
|
|
h = Math.imul(h, 16777619);
|
|
|
|
|
h ^= r & 0xff;
|
|
|
|
|
h = Math.imul(h, 16777619);
|
|
|
|
|
h ^= (r >> 8) & 0xff;
|
|
|
|
|
h = Math.imul(h, 16777619);
|
|
|
|
|
}
|
|
|
|
|
return { hash: (h >>> 0).toString(16), samples: audioLen };
|
|
|
|
|
},
|
|
|
|
|
// Return a base64-encoded WAV file (16-bit stereo PCM at
|
|
|
|
|
// SAMPLE_RATE Hz) containing everything the harness has
|
|
|
|
|
// captured since the last ROM load. The runner only pulls
|
|
|
|
|
// this when it needs to write an `actual/<name>.wav` for a
|
|
|
|
|
// failed diff — we keep the full samples in memory so no
|
|
|
|
|
// re-emulation is needed.
|
|
|
|
|
audioWavBase64() {
|
|
|
|
|
const n = audioLen;
|
|
|
|
|
const dataBytes = n * 4; // 2 channels * 2 bytes per sample
|
|
|
|
|
const headerBytes = 44;
|
|
|
|
|
const total = headerBytes + dataBytes;
|
|
|
|
|
const wav = new Uint8Array(total);
|
|
|
|
|
const dv = new DataView(wav.buffer);
|
|
|
|
|
// RIFF header
|
|
|
|
|
wav[0] = 0x52; // 'R'
|
|
|
|
|
wav[1] = 0x49; // 'I'
|
|
|
|
|
wav[2] = 0x46; // 'F'
|
|
|
|
|
wav[3] = 0x46; // 'F'
|
|
|
|
|
dv.setUint32(4, total - 8, true);
|
|
|
|
|
wav[8] = 0x57; // 'W'
|
|
|
|
|
wav[9] = 0x41; // 'A'
|
|
|
|
|
wav[10] = 0x56; // 'V'
|
|
|
|
|
wav[11] = 0x45; // 'E'
|
|
|
|
|
// fmt chunk
|
|
|
|
|
wav[12] = 0x66; // 'f'
|
|
|
|
|
wav[13] = 0x6d; // 'm'
|
|
|
|
|
wav[14] = 0x74; // 't'
|
|
|
|
|
wav[15] = 0x20; // ' '
|
|
|
|
|
dv.setUint32(16, 16, true); // fmt chunk size
|
|
|
|
|
dv.setUint16(20, 1, true); // PCM
|
|
|
|
|
dv.setUint16(22, 2, true); // stereo
|
|
|
|
|
dv.setUint32(24, SAMPLE_RATE, true); // sample rate
|
|
|
|
|
dv.setUint32(28, SAMPLE_RATE * 4, true); // byte rate
|
|
|
|
|
dv.setUint16(32, 4, true); // block align
|
|
|
|
|
dv.setUint16(34, 16, true); // bits per sample
|
|
|
|
|
// data chunk
|
|
|
|
|
wav[36] = 0x64; // 'd'
|
|
|
|
|
wav[37] = 0x61; // 'a'
|
|
|
|
|
wav[38] = 0x74; // 't'
|
|
|
|
|
wav[39] = 0x61; // 'a'
|
|
|
|
|
dv.setUint32(40, dataBytes, true);
|
|
|
|
|
let off = 44;
|
|
|
|
|
for (let i = 0; i < n; i++) {
|
|
|
|
|
dv.setInt16(off, audioLeft[i], true);
|
|
|
|
|
dv.setInt16(off + 2, audioRight[i], true);
|
|
|
|
|
off += 4;
|
|
|
|
|
}
|
|
|
|
|
// Base64-encode in chunks to avoid stringify limits.
|
|
|
|
|
const chunks = [];
|
|
|
|
|
for (let i = 0; i < wav.length; i += 4096) {
|
|
|
|
|
chunks.push(String.fromCharCode.apply(null, wav.subarray(i, i + 4096)));
|
|
|
|
|
}
|
|
|
|
|
return btoa(chunks.join(""));
|
|
|
|
|
},
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
// Return a hash and non-zero-pixel count for the current canvas contents.
|
|
|
|
|
frameStats() {
|
|
|
|
|
const data = ctx.getImageData(0, 0, 256, 240).data;
|
|
|
|
|
let nonBlack = 0;
|
|
|
|
|
let hash = 2166136261 >>> 0; // FNV-1a
|
|
|
|
|
for (let i = 0; i < data.length; i += 4) {
|
|
|
|
|
const r = data[i], g = data[i + 1], b = data[i + 2];
|
|
|
|
|
if (r !== 0 || g !== 0 || b !== 0) nonBlack++;
|
|
|
|
|
hash ^= r; hash = Math.imul(hash, 16777619);
|
|
|
|
|
hash ^= g; hash = Math.imul(hash, 16777619);
|
|
|
|
|
hash ^= b; hash = Math.imul(hash, 16777619);
|
|
|
|
|
}
|
|
|
|
|
return { nonBlack, hash: (hash >>> 0).toString(16), totalPixels: 256 * 240 };
|
|
|
|
|
},
|
tests/emulator: byte-exact golden-image diffs
The smoke test used to check a per-example `nonBlack` floor — "at
least one sprite rendered," plus a per-example minimum for the
multi-sprite examples. That catches gross regressions (a compiler
bug that makes everything go black) but silently lets through
anything that changes a handful of pixels without dropping below
the sprite floor. The whole point of this harness is to catch
compiler miscompiles before they land; a softer check means bugs
can still sneak in.
This swap makes every run diff the raw canvas framebuffer against
a committed PNG golden. One mismatched byte at pixel (120, 119)
is enough to fail CI — there's nowhere for a regression to hide.
Workflow:
# normal — fails on any pixel change
node tests/emulator/run_examples.mjs
# when the diff is intentional, rewrite the goldens
UPDATE_GOLDENS=1 node tests/emulator/run_examples.mjs
# or: node tests/emulator/run_examples.mjs --update-goldens
git diff tests/emulator/goldens/ # review the change
git add tests/emulator/goldens/
git commit # explain WHY in the message
When a run fails without `UPDATE_GOLDENS`, the runner writes:
tests/emulator/actual/<name>.png the run's raw output
tests/emulator/actual/<name>.diff.png red-highlighted pixel diff
so reviewers can eyeball what changed without rerunning locally.
`actual/` is gitignored and re-created on every run. The CI job
now uploads `actual/`, `goldens/`, and `report.json` together as
a single `emulator-diff` artifact on failure — side by side means
the "what changed" story is obvious without cloning.
Implementation:
- `tests/emulator/screenshots/` is renamed to `tests/emulator/goldens/`.
All 18 existing PNGs are preserved as the initial goldens (git
detected them as pure renames).
- `harness.html` gets a new `window.nesHarness.rawPixelsBase64()`
that returns the 245760-byte (256 × 240 × 4 bytes) RGBA canvas
buffer as base64. The runner compares raw pixels, not PNG
bytes, so encoder quirks (zlib level, filter heuristics) can't
cause false positives across Chrome versions or platforms.
- The runner uses `pngjs` (pure-JS, no native deps) to decode
goldens and to write diff PNGs. `PNG.sync.write` is
byte-deterministic for identical pixels, so `git diff` on a
committed golden only ever shows up when the actual rendered
pixels changed — not because two machines produced slightly
different compression.
- The committed goldens were re-encoded with pngjs in this commit
so the baseline is consistent from day one. File sizes are a
touch larger than Chrome's output (~1KB vs ~800B on average),
but that's negligible and it eliminates one entire class of
flaky-looking diffs in the future.
Determinism verification: I ran each of the 18 ROMs twice
through fresh `NES` instances in fresh puppeteer pages, hashed
the 245760-byte framebuffers at frame 180 with SHA-256, and
confirmed `run1 == run2` for every single one. Exact-pixel diffs
are safe for this ROM set.
Negative path verification: I corrupted one golden (flipped one
pixel to pure red via pngjs) and reran the runner. It printed
DIFF hello_sprite 1/61440 pixels differ; first at (120,120)
expected [255,0,0] got [0,0,0]
actual: tests/emulator/actual/hello_sprite.png
diff: tests/emulator/actual/hello_sprite.diff.png
and exited 1 as expected. The diff PNG shows a dim-grayscale
silhouette of the expected frame with a bright-red dot on the
one mismatched pixel — enough visual context to locate the
regression at a glance.
All 18 examples match their goldens in strict mode. `cargo fmt
--check`, `cargo clippy --release --all-targets -- -D warnings`,
and `cargo test --release` (313 unit + 37 integration) are all
still green.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 21:30:18 +00:00
|
|
|
// Raw canvas pixels as a base64-encoded RGBA buffer
|
|
|
|
|
// (256 * 240 * 4 bytes). Used by the golden-diff runner to
|
|
|
|
|
// compare pixel-for-pixel against a decoded PNG golden file.
|
|
|
|
|
// Base64 is cheap and avoids any puppeteer JSON-serialization
|
|
|
|
|
// pitfalls with typed arrays.
|
|
|
|
|
rawPixelsBase64() {
|
|
|
|
|
const data = ctx.getImageData(0, 0, 256, 240).data;
|
|
|
|
|
const chunks = [];
|
|
|
|
|
// Chunk to stay under String.fromCharCode's argument limit.
|
|
|
|
|
for (let i = 0; i < data.length; i += 4096) {
|
|
|
|
|
chunks.push(String.fromCharCode.apply(null, data.subarray(i, i + 4096)));
|
|
|
|
|
}
|
|
|
|
|
return btoa(chunks.join(""));
|
|
|
|
|
},
|
Add jsnes emulator harness and fix four codegen bugs it surfaced
Running the compiled example ROMs through a headless puppeteer +
local jsnes harness exposed four latent bugs that the
header-structure-only integration tests couldn't catch:
- src/asm/mod.rs: the first pass treated ANY instruction with
`AddressingMode::Label` as a label definition, silently dropping
every `JMP`/`JSR` to a label. Now only `NOP + Label` is a label
def; other opcodes emit the opcode byte plus a 2-byte absolute
fixup resolved in pass two. Without this, every example crashed
with "invalid opcode at $1xxx" once the CPU fell through into
the math runtime and hit an unbalanced `RTS`.
- src/ir/lowering.rs (lower_handler): handler-local `VarDecl`s
(e.g. `var i: u8 = 0` inside a `while`) were pushed onto
`current_locals` but the handler built its own throwaway
`locals` list, so those var ids never got RAM addresses and
every `LoadVar`/`StoreVar` for them silently emitted nothing.
Seed `current_locals` with the state's declared locals and
reuse it so `lower_statement`'s appends flow through to the
`IrFunction`. Fixes the black screen in `arrays_and_functions`.
- src/ir/lowering.rs (global init): struct-literal initializers
on globals (`var player: Player = Player { x: 120, ... }`) fell
through to `eval_const`, which returned `None` for a
non-literal, so no init code was emitted. Now the per-field
synthetic globals each get their own `init_value`. Fixes the
black screen in `structs_enums_for`.
- src/codegen/mod.rs: the legacy AST codegen was emitting
`JSR __fn_poke` / treating `peek` as `LDA #0` for the hardware
intrinsics. It only "worked" before because the broken
assembler swallowed the bogus JSR. Handle `poke`/`peek` as
direct STA/LDA to a compile-time-constant absolute address,
matching the IR codegen's intrinsic path.
The harness lives in `tests/emulator/`: a tiny HTML page that
wraps the `jsnes` npm package, driven by a puppeteer script that
loads each ROM, runs ~180 frames, snapshots the canvas, and
records a smoke-test verdict (booted without a CPU crash, non-zero
pixels rendered, frames differ over time). `npm install && node
run_examples.mjs` from `tests/emulator/` runs the full sweep.
9/9 example ROMs now load, render, and animate where expected.
All 324 unit + 35 integration tests still pass.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 18:46:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Controller button enum constants (from jsnes Controller).
|
|
|
|
|
window.nesButtons = {
|
|
|
|
|
A: 0, B: 1, SELECT: 2, START: 3,
|
|
|
|
|
UP: 4, DOWN: 5, LEFT: 6, RIGHT: 7,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
document.getElementById("info").textContent = "ready";
|
|
|
|
|
})();
|
|
|
|
|
</script>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|