"""Load and run the SingleStepTests 65x02 corpus: its "6502" NMOS set and its "nes6502" set, the same chip with decimal mode disconnected (RP2A03). Each case gives a register image, RAM contents, the state after one instruction, and the address, value and direction of every bus cycle the instruction makes. ``run_case`` checks all of it: registers, every RAM byte the case names, the cycle count, and the bus sequence access by access. The corpus is emulator-derived: generated by its author's emulator, not captured from a chip (docs/validation.md, "Oracles and tiers"). It records P with whatever B bit the generator chose; B is not a flip-flop and this core keeps it clear, so B is the one bit P is not compared on. """ import json from dataclasses import dataclass from pathlib import Path from sixfiveohtwo import MOS6502, RP2A03 VECTORS = Path(__file__).resolve().parent / "6502_test_vectors" #: Each set of the corpus and the CPU class it checks. SETS: dict[str, type[MOS6502]] = {"6502": MOS6502, "nes6502": RP2A03} FETCH_HINT = "run `python scripts/fetch_test_vectors.py` to fetch the pinned corpus" def corpus_present(corpus: str = "6502") -> bool: return (VECTORS / corpus / "v1" / "a9.json").is_file() def load_cases(opcode: int, limit: int | None = None, corpus: str = "6502") -> list[dict]: """The corpus's cases for ``opcode``: all 10,000, or only the first ``limit``. A limited load decodes the file's JSON array incrementally and stops, so a sample costs its own size rather than the whole 1.6 MB file. """ path = VECTORS / corpus / "v1" / f"{opcode:02x}.json" if limit is None: with path.open(encoding="utf-8") as stream: return json.load(stream) decoder = json.JSONDecoder() cases: list[dict] = [] with path.open(encoding="utf-8") as stream: text = stream.read(1 << 16).lstrip() if not text.startswith("["): raise ValueError(f"{path.name} is not a JSON array") position = 1 while len(cases) < limit: while position < len(text) and text[position] in " \t\r\n,": position += 1 if position < len(text) and text[position] == "]": break try: case, position = decoder.raw_decode(text, position) except json.JSONDecodeError: more = stream.read(1 << 16) if not more: raise text += more continue cases.append(case) return cases @dataclass class Mismatch: name: str field: str got: object expected: object def __str__(self) -> str: return f"{self.name}: {self.field} is {self.got!r}, expected {self.expected!r}" def run_case(case: dict, cpu_class: type[MOS6502] = MOS6502) -> list[Mismatch]: """Run one case on ``cpu_class``; return every field that disagrees (empty when it passes).""" initial, final, name = case["initial"], case["final"], case["name"] memory: dict[int, int] = dict(initial["ram"]) bus: list[list] = [] def read_byte(address: int) -> int: value = memory.get(address, 0) bus.append([address, value, "read"]) return value def write_byte(address: int, value: int) -> None: bus.append([address, value, "write"]) memory[address] = value cpu = cpu_class(read_byte, write_byte) cpu.a, cpu.x, cpu.y, cpu.s, cpu.pc = (initial[k] for k in ("a", "x", "y", "s", "pc")) cpu.p = (initial["p"] | 0x20) & ~0x10 cycles = cpu.step() mismatches = [ Mismatch(name, register, getattr(cpu, register), final[register]) for register in ("a", "x", "y", "s", "pc") if getattr(cpu, register) != final[register] ] if (cpu.p ^ final["p"]) & ~0x10 & 0xFF: mismatches.append(Mismatch(name, "p (B excluded)", hex(cpu.p), hex(final["p"]))) for address, value in final["ram"]: if memory.get(address, 0) != value: mismatches.append(Mismatch(name, f"ram[{address:#06x}]", memory.get(address), value)) if cycles != len(case["cycles"]): mismatches.append(Mismatch(name, "cycles", cycles, len(case["cycles"]))) if bus != case["cycles"]: mismatches.append(Mismatch(name, "bus", bus, case["cycles"])) return mismatches