1
0
Fork 0
mirror of https://github.com/imjasonh/nescript synced 2026-07-12 10:39:31 +00:00

lang: NES 2.0 headers and u16 struct fields

Implements two items from docs/future-work.md's language-feature gaps:

NES 2.0 header support: `RomBuilder` gains a `header_format` field
and a matching `enable_nes2()` method. When enabled, byte 7 bits 2-3
are set to `10` and bytes 8-15 are populated per the NES 2.0 spec
(submapper, PRG/CHR MSBs, PRG/CHR RAM, timing). The header stays
16 bytes. Programs opt in via `game Foo { header: nes2 }`; the
default remains iNES 1.0 so every committed example ROM is byte
identical. `validate_ines` now detects and reports which format it
parsed.

u16 struct fields: the analyzer's `register_struct` accepts `u16`
fields with a two-byte size and the struct-variable allocator tracks
per-field sizes so the synthesized `pos.x`/`pos.y` globals get the
right address span. IR lowering's `LValue::Field` and
`Expr::FieldAccess` follow the same wide path as u16 globals, and
struct-literal initialization writes both bytes for u16 fields.
Array and nested-struct fields stay rejected with a clearer
message. Existing u8/i8/bool struct programs are unaffected.

https://claude.ai/code/session_01MaNVcDmK9gsspRkdxowQAM
This commit is contained in:
Claude 2026-04-14 02:05:51 +00:00
parent 65a63f9a68
commit 33351f8b32
No known key found for this signature in database
13 changed files with 588 additions and 26 deletions

View file

@ -1,7 +1,7 @@
#[cfg(test)]
mod tests;
use crate::parser::ast::{Mapper, Mirroring};
use crate::parser::ast::{HeaderFormat, Mapper, Mirroring};
/// iNES header magic bytes
const INES_MAGIC: [u8; 4] = [0x4E, 0x45, 0x53, 0x1A]; // "NES\x1A"
@ -20,6 +20,12 @@ const CHR_BANK_SIZE: usize = 8192;
/// call [`RomBuilder::set_prg_banks`] the builder writes each bank
/// back-to-back in the order you provided. The iNES header's PRG
/// bank count always reflects the actual number of 16 KB slots.
///
/// By default the builder emits an iNES 1.0 header. Call
/// [`RomBuilder::enable_nes2`] to opt into the NES 2.0 header format,
/// which is backwards-compatible (byte 7 bits 2-3 are set to `10`)
/// and populates bytes 8-15 per the NES 2.0 spec. The header remains
/// 16 bytes either way.
pub struct RomBuilder {
/// One Vec per 16 KB PRG bank, in physical order. An empty
/// outer Vec means no PRG has been set yet; a single inner Vec
@ -28,6 +34,7 @@ pub struct RomBuilder {
chr_data: Vec<u8>,
mapper: u8,
mirroring: Mirroring,
header_format: HeaderFormat,
}
impl RomBuilder {
@ -37,6 +44,7 @@ impl RomBuilder {
chr_data: Vec::new(),
mapper: 0, // NROM
mirroring,
header_format: HeaderFormat::Ines1,
}
}
@ -45,6 +53,14 @@ impl RomBuilder {
self.mapper = mapper;
}
/// Opt into the NES 2.0 header format. Bytes 7 bits 2-3 are
/// set to `10` to mark the header as NES 2.0, and bytes 8-15
/// are populated with the extended metadata. The header is
/// still exactly 16 bytes.
pub fn enable_nes2(&mut self) {
self.header_format = HeaderFormat::Nes2;
}
/// Set the PRG ROM data as a single bank. Will be padded to fill
/// 16 KB or 32 KB. Equivalent to calling `set_prg_banks` with a
/// one- or two-element Vec depending on whether the data crosses
@ -108,10 +124,11 @@ impl RomBuilder {
let mut rom = Vec::with_capacity(16 + prg_size + chr_size);
// iNES header (16 bytes)
// iNES header (16 bytes — NES 2.0 is the same size, it just
// reinterprets bytes 7-15).
rom.extend_from_slice(&INES_MAGIC);
rom.push(prg_banks as u8); // PRG ROM banks (16 KB units)
rom.push(chr_banks as u8); // CHR ROM banks (8 KB units)
rom.push(prg_banks as u8); // PRG ROM banks (16 KB units) — low 8 bits
rom.push(chr_banks as u8); // CHR ROM banks (8 KB units) — low 8 bits
// Flags 6: mirroring, mapper low nibble
let mut flags6 = match self.mirroring {
@ -121,12 +138,47 @@ impl RomBuilder {
flags6 |= (self.mapper & 0x0F) << 4;
rom.push(flags6);
// Flags 7: mapper high nibble
let flags7 = self.mapper & 0xF0;
// Flags 7: mapper high nibble plus header-format marker.
// NES 2.0 sets bits 2-3 to `10`; iNES 1.0 leaves them at `00`.
let mut flags7 = self.mapper & 0xF0;
if self.header_format == HeaderFormat::Nes2 {
flags7 |= 0b0000_1000;
}
rom.push(flags7);
// Bytes 8-15: padding zeros
rom.extend_from_slice(&[0u8; 8]);
// Bytes 8-15. For iNES 1.0 these are zero-padded. For NES 2.0
// they carry the extended metadata described in the spec:
//
// byte 8 — mapper high nibble (bits 8-11) + submapper (0)
// byte 9 — PRG ROM size MSB (0) | CHR ROM size MSB (0)
// byte 10 — PRG RAM / EEPROM size (0)
// byte 11 — CHR RAM size (0 — we use CHR ROM)
// byte 12 — CPU/PPU timing (0 = NTSC)
// byte 13 — mapper-specific (0)
// byte 14 — miscellaneous ROMs (0)
// byte 15 — default expansion device (0)
//
// Since we never exceed 4 MB of PRG or 2 MB of CHR, don't use
// submappers, and don't have CHR RAM or miscellaneous ROMs,
// most of these stay zero. Only the mapper high nibble in
// byte 8 can be non-zero for mappers numbered >= 256.
match self.header_format {
HeaderFormat::Ines1 => rom.extend_from_slice(&[0u8; 8]),
HeaderFormat::Nes2 => {
// byte 8 low nibble would hold mapper bits 8-11;
// since `self.mapper` is a u8 it's always zero here.
// High nibble would hold the submapper, which we
// never use.
rom.push(0); // byte 8
rom.push(0); // byte 9: PRG/CHR size MSBs
rom.push(0); // byte 10: PRG RAM / EEPROM
rom.push(0); // byte 11: CHR RAM
rom.push(0); // byte 12: NTSC timing
rom.push(0); // byte 13: mapper-specific
rom.push(0); // byte 14: miscellaneous ROMs
rom.push(0); // byte 15: default expansion device
}
}
// PRG ROM data: each bank padded to 16 KB, concatenated.
for mut bank in prg_banks_vec {
@ -145,7 +197,11 @@ impl RomBuilder {
}
}
/// Validate that a byte slice looks like a valid iNES ROM.
/// Validate that a byte slice looks like a valid iNES ROM. Accepts
/// both iNES 1.0 and NES 2.0 headers — the former treats bytes 8-15
/// as zero-padded, the latter as extended metadata. The returned
/// [`RomInfo`] reports which format was detected in `header_format`
/// so callers can distinguish the two.
pub fn validate_ines(data: &[u8]) -> Result<RomInfo, &'static str> {
if data.len() < 16 {
return Err("file too small for iNES header");
@ -168,13 +224,38 @@ pub fn validate_ines(data: &[u8]) -> Result<RomInfo, &'static str> {
Mirroring::Vertical
};
let mapper = (data[6] >> 4) | (data[7] & 0xF0);
// Header format is encoded in byte 7 bits 2-3. `10` (binary)
// means NES 2.0; anything else is iNES 1.0.
let header_format = if data[7] & 0x0C == 0x08 {
HeaderFormat::Nes2
} else {
HeaderFormat::Ines1
};
// iNES 1.0: mapper number is the low nibble of byte 6 plus the
// high nibble of byte 7. NES 2.0 extends this with bits 8-11 in
// byte 8's low nibble — we decode that too, even though we
// never emit mappers >= 256 ourselves.
let mut mapper = (data[6] >> 4) | (data[7] & 0xF0);
if header_format == HeaderFormat::Nes2 {
// Mapper field is 12 bits in NES 2.0; the high nibble in
// byte 8 would push the mapper number past a u8. We still
// only return the low 8 bits here since NEScript never
// emits mappers beyond NROM/MMC1/UxROM/MMC3.
let mapper_high = data[8] & 0x0F;
if mapper_high != 0 {
// Can't fit in a u8 — callers that care about high
// mapper bits should read the header directly.
mapper = mapper.wrapping_add(mapper_high << 4);
}
}
Ok(RomInfo {
prg_banks,
chr_banks,
mapper,
mirroring,
header_format,
})
}
@ -184,6 +265,7 @@ pub struct RomInfo {
pub chr_banks: usize,
pub mapper: u8,
pub mirroring: Mirroring,
pub header_format: HeaderFormat,
}
/// Map a `Mapper` enum variant to its iNES mapper number.