1
0
Fork 0
mirror of https://github.com/imjasonh/nescript synced 2026-07-08 08:55:38 +00:00

ir/codegen: signed comparison lowering for i8/i16

Closes the §A follow-up gap: ordering compares (`<`, `<=`, `>`, `>=`)
on signed integer types now use the canonical 6502 `CMP / SBC / BVC /
EOR #$80` overflow-correction idiom so the N flag reflects the true
sign of the difference, instead of the previous BCC/BCS-based path
that always treated `$FFxx` as greater than `$00yy`.

The same change also fixes narrow-to-wide widening: assigning a
runtime `i8` expression to an `i16` variable now sign-extends the
high byte via a new `IrOp::SignExtend` op instead of zero-extending
it, so `var w: i16 = some_i8_neg` round-trips negative values.

The lowerer tracks signedness on each IR temp (analogous to the
existing `wide_hi` map) and threads it onto the new `Signedness`
field of `CmpLt`/`CmpGt`/`CmpLtEq`/`CmpGtEq` and their 16-bit
variants. The optimizer's constant-folder uses the same flag to
fold compares correctly under either signedness. Casts to `u8`/`u16`
strip the signed flag so an explicit `as` opt-out stays unsigned.

`examples/signed_compare.ne` exercises both bit widths through the
emulator harness — the four pip sprites at the top of the screen
show three lit (signed-correct) and one dark (would only light if
the compare regressed to unsigned semantics).
This commit is contained in:
Claude 2026-04-19 00:17:34 +00:00
parent 3719b6c0dd
commit 9719dc4111
No known key found for this signature in database
11 changed files with 878 additions and 81 deletions

View file

@ -50,7 +50,8 @@ Open any `.nes` file in an NES emulator ([Mesen](https://www.mesen.ca/), [FCEUX]
| `auto_sprite_flicker.ne` | `game { sprite_flicker: true }` | The `game` attribute equivalent of calling `cycle_sprites` at the top of every `on frame` handler. Same 12-sprite layout as `sprite_flicker_demo.ne`, minus the explicit call — the IR lowerer injects the op automatically when the flag is set, so it's byte-identical to a hand-rolled version without the per-site boilerplate. |
| `fade_demo.ne` | `fade_out(n)`, `fade_in(n)` | Blocking fade helpers that walk brightness 4 → 0 and 0 → 4 with `n` frames per step. The runtime splices `__fade_out` / `__fade_in` plus a callable `__wait_frame_rt` helper when the builtin is used; fade use also forces `__set_palette_brightness` to be linked in since the fade body JSRs into it. |
| `sprite_0_split_demo.ne` | `sprite_0_split(x, y)` | Mid-frame scroll change driven by the PPU's sprite-0 hit flag (`$2002` bit 6), so the effect works on any mapper — NROM, UxROM, MMC1 — not just MMC3 via `on_scanline(N)`. Two-phase busy-wait (wait for clear, then wait for set) guarantees the hit we're responding to came from the current frame. Requires a sprite in OAM slot 0 that overlaps opaque background pixels; this demo uses a full smiley background so every frame's sprite-0 hit fires deterministically. |
| `i16_demo.ne` | `i16` signed 16-bit type | Negative literals fold to wide two's complement (`-10``$FFF6`), so `var vy: i16 = -10` stores the right bytes instead of the zero-extended `$00F6`. Comparisons currently use the unsigned 16-bit compare path (matching existing `i8` behaviour) — fine for positive ranges, wrong for negative compares. The companion `i16_negative_literal_sign_extends_to_wide_store` integration test guards the literal-fold path. |
| `i16_demo.ne` | `i16` signed 16-bit type | Negative literals fold to wide two's complement (`-10``$FFF6`), so `var vy: i16 = -10` stores the right bytes instead of the zero-extended `$00F6`. The companion `i16_negative_literal_sign_extends_to_wide_store` integration test guards the literal-fold path. |
| `signed_compare.ne` | signed `<` / `<=` / `>` / `>=` on `i8` and `i16` | Bounces a marker between X = 32 and X = 224 driven by signed `i16` compares against negative deltas, plus four pip sprites at the top of the screen that gate on directly-negative compares (`i8_neg < 0`, `i16_minus_one < i16_one`, etc.). The signed lowering uses the canonical `CMP / SBC / BVC / EOR #$80` overflow-correction idiom in `gen_cmp_signed_set_n` so the N flag reflects the true sign of the difference. The fourth pip is intentionally dark — it would only light if the lowering fell back to unsigned semantics. The companion integration tests `signed_i16_lt_emits_overflow_corrected_branch` and `signed_i8_lt_emits_overflow_corrected_branch` enforce the asm shape. |
| `sram_demo.ne` | `save { var ... }` | Battery-backed save block. The analyzer allocates `high_score` and `coins` at `$6000+` (cartridge SRAM window) instead of main RAM, and the linker flips iNES header byte-6 bit-1 so emulators (FCEUX, Mesen, Nestopia) load and persist the region from a `.sav` file alongside the ROM. SRAM is uninitialized at first power-on; production games should reserve a magic-byte sentinel and validate it before trusting the rest of the data — the compiler doesn't auto-initialize and emits W0111 if you try. |
| `vram_buffer_demo.ne` | `nt_set`, `nt_attr`, `nt_fill_h` | Minimal VRAM update buffer exercise — three single-tile writes, a 16-tile horizontal fill, and an attribute write firing every frame. Useful as a test case; see `hud_demo.ne` for a realistic usage pattern. |
| `hud_demo.ne` | VRAM buffer driving a classic status bar | A bouncing ball playfield with a HUD across the top: a 5-cell lives indicator that ticks down once per second via `nt_fill_h`, a score counter at the right edge that bumps on every wall hit via `nt_set`, and a one-shot `nt_attr` call at startup that flips the top-left metatile group to a red "UI chrome" palette. Shadow-comparing `score` / `lives` to their `last_*` copies keeps the buffer empty on the ~58-of-60 frames when nothing changed — per-frame cost scales with what actually moved. This is the pattern every nesdoug scoreboard / dialog box / destroyed-metatile animation is built on. |

View file

@ -0,0 +1,75 @@
// Signed-comparison demo — exercises the signed lowering of
// `<` / `>` / `<=` / `>=` on `i8` and `i16` against negative
// values. The pre-fix behaviour (unsigned BCC/BCS branches on
// signed types) gave the wrong answer for any compare that
// crossed zero — `var v: i16 = -1; if v < 0` was always false
// because $FFFF compared greater than $0000 unsigned.
//
// What this program shows on screen at frame 180 (the harness
// snapshot frame):
//
// - Sprite 0 (Marker, X = signed_x_pos) bounces between
// X = 32 and X = 224. The bounce flips when the i16
// position passes the bounds, which only works if the
// signed compare lowers correctly. By frame 180 the
// marker has executed enough bounces to land at a
// position that an unsigned-compare regression would
// not be able to reach.
//
// - Pip 1 (X=64) lights iff `i8_neg < 0` evaluates true.
// A regression to the unsigned path would treat $FF
// as >= $00 and the pip would go dark.
//
// - Pip 2 (X=96) lights iff `(i16_minus_one) < (i16_one)`.
// Same story but on the wide path — the BVC / EOR #$80
// idiom in `gen_cmp16_signed` is what lets it fire.
//
// - Pip 3 (X=128) lights iff `i8_neg <= i8_neg2` where
// i8_neg = -10, i8_neg2 = -1, so the comparison is
// -10 <= -1 (true). Wrong-path lowering would compare
// $F6 <= $FF unsigned, which is also true by accident
// — *but* if we flip to `i8_neg2 <= i8_neg` (-1 <= -10,
// false signed, true unsigned) Pip 4 should be DARK.
// Both pips together let the harness distinguish signed
// from unsigned semantics.
//
// - Pip 4 (X=160) is intentionally driven by the
// opposite-direction compare so a regression to
// unsigned semantics would light it. With the signed
// path it stays dark.
//
// Build: cargo run --release -- build examples/signed_compare.ne
game "Signed Compare" {
mapper: NROM
}
var i8_neg: i8 = -1
var i8_neg2: i8 = -10
var i16_minus_one: i16 = -1
var i16_one: i16 = 1
var signed_x_pos: i16 = 32
var dx: i16 = 1
on frame {
// Bounce the marker between 32 and 224 using i16 signed
// comparisons. The arithmetic lives in i16 land so the
// signed-compare path is the only one that can produce
// the right turnaround.
signed_x_pos += dx
if signed_x_pos >= 224 { dx = -1 }
if signed_x_pos <= 32 { dx = 1 }
// Marker — its X coordinate is the i16 position truncated
// to u8 for the draw call.
var mx: u8 = signed_x_pos as u8
draw Marker at: (mx, 120)
// Pips at the top of the screen, each gated on a signed
// comparison.
if i8_neg < 0 { draw Pip at: (64, 16) }
if i16_minus_one < i16_one { draw Pip at: (96, 16) }
if i8_neg2 <= i8_neg { draw Pip at: (128, 16) }
if i8_neg <= i8_neg2 { draw Pip at: (160, 16) }
}
start Main

BIN
examples/signed_compare.nes Normal file

Binary file not shown.