examples: 4 new programs covering MMC3 + other e2e gaps
Four new examples bring total coverage to 18/18 ROMs through
the jsnes smoke test:
- mmc3_per_state_split.ne — two states, each with their own
`on scanline(N)` handler at a different line (80 vs 160).
Pressing START transitions between them. Verifies the
per-state MMC3 IRQ dispatch: the `__ir_mmc3_reload` helper
CMPs `current_state` on every NMI and writes the right
latch value to `$C000`/`$C001`, and `__irq_user` runs the
current state's handler when the counter fires. This is
the first example that exercises the per-state reload logic
at runtime, not just at compile-time.
- two_player.ne — exercises `p2.button.*` reads alongside
the default (P1) `button.*`. Two independently-moveable
sprites sharing a single frame handler and the runtime OAM
cursor. The runtime's NMI controller poll already reads
both `$4016` and `$4017`, but until this example no
runtime test actually looked at `$08` (the P2 input byte).
- function_chain.ne — five-deep user-function call chain
(`frame -> compute -> scale -> clamp -> fold -> taper`)
with parameter passing through ZP `$04-$07` and return
values through A. Early returns inside nested `if`s,
handler-local result var, mixed shift + additive transforms.
Catches any regression in: JSR stack discipline, param slot
layout, RTS stack unwinding, return-value flow, or the
analyzer's call-graph / max-depth computation.
- comparisons.ne — one `if` per comparison operator
(`==`, `!=`, `<`, `<=`, `>`, `>=`) gated on a u8 ramping
through 0..255. Each `if` drives a pip sprite at a fixed
column. Exercises every `CmpKind::*` case in the IR
codegen's `gen_cmp`, catching regressions in branch-opcode
selection (BEQ/BNE/BCC/BCS) and inverted-branch peephole
folding.
Smoke test deltas (all 18/18 pass, with per-example floors):
comparisons 208 (floor 150)
function_chain 104 (floor 100)
mmc3_per_state_split 104 (floor 80)
two_player 104 (floor 100)
`tests/emulator/run_examples.mjs` gets new `EXAMPLE_FLOORS`
entries for each, with notes describing the expected content
so a regression prints a helpful reason.
cargo test (313 unit + 37 integration), cargo fmt --check,
cargo clippy --release -- -D warnings all clean.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 20:48:31 +00:00
|
|
|
// Function Chain — exercises a deep call graph with parameter
|
|
|
|
|
// passing and return values across multiple user functions.
|
|
|
|
|
//
|
|
|
|
|
// The analyzer caps call depth at 8 (hard NES stack limit for
|
|
|
|
|
// a cooperative compiler). This example chains five functions:
|
|
|
|
|
//
|
|
|
|
|
// frame -> compute -> scale -> clamp -> fold -> taper
|
|
|
|
|
//
|
analyzer+codegen: lift the 4-param ceiling via a direct-write calling convention
Follow-up to the silent-drop audit. The old ABI passed every
parameter through four fixed zero-page transport slots `$04-$07`,
imposing a hard 4-param cap (E0506) that didn't compose with
structs/arrays/u16s and fell back to "pack args into a global"
workarounds whenever a function needed five things. The transport
scheme also cost every non-leaf call a 4-LDA/STA spill prologue
(~28 cycles, 16 bytes) to copy args out of ZP before the next
nested `JSR` could clobber them.
Replace it with a hybrid convention keyed on leaf-ness:
- **Leaf callees** (no nested `JSR` in body, ≤4 params):
unchanged. Caller stages args into `$04-$07`; body reads those
slots directly for its entire lifetime. No prologue copy.
Fastest path, 3-cycle ZP stores + 3-cycle ZP loads, preserves
the SHA-256 leaf-primitive optimisation that motivated the
original fast path.
- **Non-leaf callees** (body contains a nested `JSR`, OR ≥5
params): direct-write. Caller stages each argument straight
into the callee's analyzer-allocated parameter RAM slot,
bypassing the transport slots entirely. No prologue copy on
the callee side. Saves ~24 cycles and ~16 bytes per call vs
the old transport-then-spill path, and — crucially — scales
past 4 params because the per-param slots live wherever the
analyzer put them rather than in a fixed ZP window.
The analyzer's ceiling moves from 4 to 8. Functions with 5–8
params are silently promoted to the non-leaf convention (even if
their body has no nested `JSR`), which pays the direct-write cost
rather than the prologue-copy cost — still cheaper than the old
ABI. Declarations with 9+ params still emit E0506.
### Implementation
- `function_is_leaf` now also requires `param_count <= 4`.
- `IrCodeGen::new` populates `non_leaf_param_addrs: HashMap<String,
Vec<u16>>` — for every non-leaf function, the ordered list of
addresses its parameters occupy. Callers use this to route each
arg directly to the right slot.
- `IrOp::Call` branches on presence in the map: non-leaf → direct-
write, leaf (or absent — 0-arg case) → ZP transport.
- `gen_function` no longer emits a prologue. Leaves didn't have
one; non-leaves had a 4-LDA/STA copy that is now unnecessary
because args arrive pre-written to the slot.
- The previous `leaf_functions: HashSet<String>` field is
removed; leaf-ness is now inferred from absence-in-
`non_leaf_param_addrs` at the call site.
### Tests and regressions
- `eight_param_non_leaf_function_stages_every_arg_at_its_allocated_slot`
compiles an 8-param function, scans PRG for a distinct
`LDA #\$NN / STA <addr>` per arg (immediates `0x11..0x88`), and
asserts that STAs to the `$04-$07` range are strictly fewer
than 8 — proof the old transport path is gone for this call.
- `non_leaf_call_direct_writes_args_to_callee_param_slots`
replaces the old `gen_function_prologue_spills_params_to_local_ram`
test with a dual assertion: (a) no `LDA \$04` prologue at the
callee entry, and (b) the caller-side STA lands at the
analyzer-allocated param slot, not at `\$04-\$07`.
- `analyze_rejects_function_with_more_than_4_params` renamed and
rewritten for the new 8-param cap.
- `feature_canary.ne` gains a 6-param `sum6` call (1+2+3+4+5+6 =
21) as check 8. The canary stays green (all eight checks
pass), so the committed golden is unchanged.
### Blast radius
- Six example ROMs change bytes (arrays_and_functions, function_chain,
mmc1_banked, pong, sha256, war) because their non-leaf call sites
pick up the shorter staging sequence.
- Pong and war audio hashes refresh (pure layout-timing shift; no
behavioural change in the 180-frame no-input window). docs/pong.gif
and docs/war.gif stay byte-identical.
- `examples/function_chain.ne`'s header comment updated to
document the leaf vs non-leaf split it exercises.
- `docs/language-guide.md` parameter-count section and E0506 entry
updated to reflect the new rule.
All 720 Rust tests pass; all 35 emulator goldens pass.
https://claude.ai/code/session_01AoQ678uVeqpyayvWHpfDhC
2026-04-18 02:34:56 +00:00
|
|
|
// Each function takes its argument through the calling
|
|
|
|
|
// convention and returns a value in A. The chained result is
|
|
|
|
|
// what drives the player sprite's X position on screen each
|
|
|
|
|
// frame.
|
|
|
|
|
//
|
|
|
|
|
// Parameters land at a non-uniform address set:
|
|
|
|
|
// - The deepest callee (`taper`) is a leaf — it has no nested
|
|
|
|
|
// `JSR` and can receive its arg in the `$04` transport slot
|
|
|
|
|
// directly. Its body reads `$04` in place of a spill copy.
|
|
|
|
|
// - Every other function (`compute`, `scale`, `clamp`, `fold`)
|
|
|
|
|
// is non-leaf and uses the direct-write convention: each
|
|
|
|
|
// caller stages the arg straight into the callee's
|
|
|
|
|
// analyzer-allocated param slot before the `JSR`. No
|
|
|
|
|
// transport, no prologue copy.
|
examples: 4 new programs covering MMC3 + other e2e gaps
Four new examples bring total coverage to 18/18 ROMs through
the jsnes smoke test:
- mmc3_per_state_split.ne — two states, each with their own
`on scanline(N)` handler at a different line (80 vs 160).
Pressing START transitions between them. Verifies the
per-state MMC3 IRQ dispatch: the `__ir_mmc3_reload` helper
CMPs `current_state` on every NMI and writes the right
latch value to `$C000`/`$C001`, and `__irq_user` runs the
current state's handler when the counter fires. This is
the first example that exercises the per-state reload logic
at runtime, not just at compile-time.
- two_player.ne — exercises `p2.button.*` reads alongside
the default (P1) `button.*`. Two independently-moveable
sprites sharing a single frame handler and the runtime OAM
cursor. The runtime's NMI controller poll already reads
both `$4016` and `$4017`, but until this example no
runtime test actually looked at `$08` (the P2 input byte).
- function_chain.ne — five-deep user-function call chain
(`frame -> compute -> scale -> clamp -> fold -> taper`)
with parameter passing through ZP `$04-$07` and return
values through A. Early returns inside nested `if`s,
handler-local result var, mixed shift + additive transforms.
Catches any regression in: JSR stack discipline, param slot
layout, RTS stack unwinding, return-value flow, or the
analyzer's call-graph / max-depth computation.
- comparisons.ne — one `if` per comparison operator
(`==`, `!=`, `<`, `<=`, `>`, `>=`) gated on a u8 ramping
through 0..255. Each `if` drives a pip sprite at a fixed
column. Exercises every `CmpKind::*` case in the IR
codegen's `gen_cmp`, catching regressions in branch-opcode
selection (BEQ/BNE/BCC/BCS) and inverted-branch peephole
folding.
Smoke test deltas (all 18/18 pass, with per-example floors):
comparisons 208 (floor 150)
function_chain 104 (floor 100)
mmc3_per_state_split 104 (floor 80)
two_player 104 (floor 100)
`tests/emulator/run_examples.mjs` gets new `EXAMPLE_FLOORS`
entries for each, with notes describing the expected content
so a regression prints a helpful reason.
cargo test (313 unit + 37 integration), cargo fmt --check,
cargo clippy --release -- -D warnings all clean.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 20:48:31 +00:00
|
|
|
//
|
|
|
|
|
// What this exercises end-to-end:
|
|
|
|
|
// - Five levels of nested `JSR` without stack corruption
|
analyzer+codegen: lift the 4-param ceiling via a direct-write calling convention
Follow-up to the silent-drop audit. The old ABI passed every
parameter through four fixed zero-page transport slots `$04-$07`,
imposing a hard 4-param cap (E0506) that didn't compose with
structs/arrays/u16s and fell back to "pack args into a global"
workarounds whenever a function needed five things. The transport
scheme also cost every non-leaf call a 4-LDA/STA spill prologue
(~28 cycles, 16 bytes) to copy args out of ZP before the next
nested `JSR` could clobber them.
Replace it with a hybrid convention keyed on leaf-ness:
- **Leaf callees** (no nested `JSR` in body, ≤4 params):
unchanged. Caller stages args into `$04-$07`; body reads those
slots directly for its entire lifetime. No prologue copy.
Fastest path, 3-cycle ZP stores + 3-cycle ZP loads, preserves
the SHA-256 leaf-primitive optimisation that motivated the
original fast path.
- **Non-leaf callees** (body contains a nested `JSR`, OR ≥5
params): direct-write. Caller stages each argument straight
into the callee's analyzer-allocated parameter RAM slot,
bypassing the transport slots entirely. No prologue copy on
the callee side. Saves ~24 cycles and ~16 bytes per call vs
the old transport-then-spill path, and — crucially — scales
past 4 params because the per-param slots live wherever the
analyzer put them rather than in a fixed ZP window.
The analyzer's ceiling moves from 4 to 8. Functions with 5–8
params are silently promoted to the non-leaf convention (even if
their body has no nested `JSR`), which pays the direct-write cost
rather than the prologue-copy cost — still cheaper than the old
ABI. Declarations with 9+ params still emit E0506.
### Implementation
- `function_is_leaf` now also requires `param_count <= 4`.
- `IrCodeGen::new` populates `non_leaf_param_addrs: HashMap<String,
Vec<u16>>` — for every non-leaf function, the ordered list of
addresses its parameters occupy. Callers use this to route each
arg directly to the right slot.
- `IrOp::Call` branches on presence in the map: non-leaf → direct-
write, leaf (or absent — 0-arg case) → ZP transport.
- `gen_function` no longer emits a prologue. Leaves didn't have
one; non-leaves had a 4-LDA/STA copy that is now unnecessary
because args arrive pre-written to the slot.
- The previous `leaf_functions: HashSet<String>` field is
removed; leaf-ness is now inferred from absence-in-
`non_leaf_param_addrs` at the call site.
### Tests and regressions
- `eight_param_non_leaf_function_stages_every_arg_at_its_allocated_slot`
compiles an 8-param function, scans PRG for a distinct
`LDA #\$NN / STA <addr>` per arg (immediates `0x11..0x88`), and
asserts that STAs to the `$04-$07` range are strictly fewer
than 8 — proof the old transport path is gone for this call.
- `non_leaf_call_direct_writes_args_to_callee_param_slots`
replaces the old `gen_function_prologue_spills_params_to_local_ram`
test with a dual assertion: (a) no `LDA \$04` prologue at the
callee entry, and (b) the caller-side STA lands at the
analyzer-allocated param slot, not at `\$04-\$07`.
- `analyze_rejects_function_with_more_than_4_params` renamed and
rewritten for the new 8-param cap.
- `feature_canary.ne` gains a 6-param `sum6` call (1+2+3+4+5+6 =
21) as check 8. The canary stays green (all eight checks
pass), so the committed golden is unchanged.
### Blast radius
- Six example ROMs change bytes (arrays_and_functions, function_chain,
mmc1_banked, pong, sha256, war) because their non-leaf call sites
pick up the shorter staging sequence.
- Pong and war audio hashes refresh (pure layout-timing shift; no
behavioural change in the 180-frame no-input window). docs/pong.gif
and docs/war.gif stay byte-identical.
- `examples/function_chain.ne`'s header comment updated to
document the leaf vs non-leaf split it exercises.
- `docs/language-guide.md` parameter-count section and E0506 entry
updated to reflect the new rule.
All 720 Rust tests pass; all 35 emulator goldens pass.
https://claude.ai/code/session_01AoQ678uVeqpyayvWHpfDhC
2026-04-18 02:34:56 +00:00
|
|
|
// - The hybrid leaf / non-leaf calling convention
|
examples: 4 new programs covering MMC3 + other e2e gaps
Four new examples bring total coverage to 18/18 ROMs through
the jsnes smoke test:
- mmc3_per_state_split.ne — two states, each with their own
`on scanline(N)` handler at a different line (80 vs 160).
Pressing START transitions between them. Verifies the
per-state MMC3 IRQ dispatch: the `__ir_mmc3_reload` helper
CMPs `current_state` on every NMI and writes the right
latch value to `$C000`/`$C001`, and `__irq_user` runs the
current state's handler when the counter fires. This is
the first example that exercises the per-state reload logic
at runtime, not just at compile-time.
- two_player.ne — exercises `p2.button.*` reads alongside
the default (P1) `button.*`. Two independently-moveable
sprites sharing a single frame handler and the runtime OAM
cursor. The runtime's NMI controller poll already reads
both `$4016` and `$4017`, but until this example no
runtime test actually looked at `$08` (the P2 input byte).
- function_chain.ne — five-deep user-function call chain
(`frame -> compute -> scale -> clamp -> fold -> taper`)
with parameter passing through ZP `$04-$07` and return
values through A. Early returns inside nested `if`s,
handler-local result var, mixed shift + additive transforms.
Catches any regression in: JSR stack discipline, param slot
layout, RTS stack unwinding, return-value flow, or the
analyzer's call-graph / max-depth computation.
- comparisons.ne — one `if` per comparison operator
(`==`, `!=`, `<`, `<=`, `>`, `>=`) gated on a u8 ramping
through 0..255. Each `if` drives a pip sprite at a fixed
column. Exercises every `CmpKind::*` case in the IR
codegen's `gen_cmp`, catching regressions in branch-opcode
selection (BEQ/BNE/BCC/BCS) and inverted-branch peephole
folding.
Smoke test deltas (all 18/18 pass, with per-example floors):
comparisons 208 (floor 150)
function_chain 104 (floor 100)
mmc3_per_state_split 104 (floor 80)
two_player 104 (floor 100)
`tests/emulator/run_examples.mjs` gets new `EXAMPLE_FLOORS`
entries for each, with notes describing the expected content
so a regression prints a helpful reason.
cargo test (313 unit + 37 integration), cargo fmt --check,
cargo clippy --release -- -D warnings all clean.
https://claude.ai/code/session_014Z5y3Q9krLcAxYpZQJhZ5V
2026-04-12 20:48:31 +00:00
|
|
|
// - Return value propagation through A
|
|
|
|
|
// - `fun ... -> u8 { return ... }` — the full typed-function
|
|
|
|
|
// shape, including an early `return` inside an `if`
|
|
|
|
|
// - Interaction of function calls with handler-local vars
|
|
|
|
|
// (the `out` result ends up in a local that drives draw)
|
|
|
|
|
//
|
|
|
|
|
// Build: cargo run -- build examples/function_chain.ne
|
|
|
|
|
|
|
|
|
|
game "Fn Chain" {
|
|
|
|
|
mapper: NROM
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const SCREEN_MIN: u8 = 16
|
|
|
|
|
const SCREEN_MAX: u8 = 232
|
|
|
|
|
|
|
|
|
|
var tick: u8 = 0
|
|
|
|
|
|
|
|
|
|
// Level 5: final transform — fold the input by reflecting any
|
|
|
|
|
// overshoot back toward the middle. Pure function, returns u8.
|
|
|
|
|
fun taper(v: u8) -> u8 {
|
|
|
|
|
if v > 200 {
|
|
|
|
|
return 200
|
|
|
|
|
}
|
|
|
|
|
return v
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Level 4: fold — bias the input toward the screen center.
|
|
|
|
|
fun fold(v: u8) -> u8 {
|
|
|
|
|
var biased: u8 = v
|
|
|
|
|
if biased < SCREEN_MIN {
|
|
|
|
|
biased = SCREEN_MIN
|
|
|
|
|
}
|
|
|
|
|
return taper(biased)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Level 3: clamp to the visible screen band.
|
|
|
|
|
fun clamp(v: u8) -> u8 {
|
|
|
|
|
if v > SCREEN_MAX {
|
|
|
|
|
return fold(SCREEN_MAX)
|
|
|
|
|
}
|
|
|
|
|
return fold(v)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Level 2: scale the tick into a pixel position. Uses a shift
|
|
|
|
|
// instead of multiply so we don't pull in the soft multiply.
|
|
|
|
|
fun scale(t: u8) -> u8 {
|
|
|
|
|
return clamp(t << 1)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Level 1: top of the call chain. Takes the raw frame counter,
|
|
|
|
|
// adds a small offset, and hands it to `scale`. The returned
|
|
|
|
|
// value is the player's X position.
|
|
|
|
|
fun compute(counter: u8) -> u8 {
|
|
|
|
|
var shifted: u8 = counter
|
|
|
|
|
shifted += 16
|
|
|
|
|
return scale(shifted)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
on frame {
|
|
|
|
|
tick += 1
|
|
|
|
|
|
|
|
|
|
// Single call site that triggers the whole chain. If any
|
|
|
|
|
// link in the chain corrupts the param passing or stack,
|
|
|
|
|
// the player sprite starts jittering or disappears.
|
|
|
|
|
var x: u8 = compute(tick)
|
|
|
|
|
|
|
|
|
|
// Player Y is fixed; X comes from the chain. Visually the
|
|
|
|
|
// sprite sweeps across the screen as the chain holds.
|
|
|
|
|
draw Player at: (x, 112)
|
|
|
|
|
|
|
|
|
|
// Also draw a static reference marker so the smoke test
|
|
|
|
|
// always has at least one visible sprite even if the chain
|
|
|
|
|
// somehow returns 0.
|
|
|
|
|
draw Marker at: (8, 8)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
start Main
|