# SPDX-License-Identifier: MIT """Run SingleStepTests ``spc700`` cases against the core (validation.md rung 1). Each case gives initial and final registers, sparse RAM and one ``[address, data, kind]`` per SPC700 cycle, the opcode fetch first, kind ``read``, ``write`` or ``wait``. The corpus is emulator-derived (higan's timings through JSMoo), so it is a detector: registers, PSW, RAM, and every cycle's kind and address are compared, data only where the corpus gives it (C9). Internal cycles have no address (C1). SLEEP and STOP compare registers only: the corpus's seven cycles are its generator's artefact (C5). Where this schedule disagrees with anomie's cycle doc the corpus is followed, and the core's handler says so: C4 (`[d]+Y` read forms), C6 (the cycle order of PUSH, POP, CALL, PCALL, TCALL, BRK, RET, RET1), C7 (CBNE d+X, DBNZ Y). Counts agree everywhere; anomie's own notes call those orders guesses. """ from __future__ import annotations import json from pathlib import Path from spc700_python import SPC700, CPUState CORPUS = Path(__file__).resolve().parents[1] / "reference" / "src" / "spc700" / "v1" REGISTERS = ("a", "x", "y", "sp", "pc", "psw") REGISTERS_ONLY = ("ef", "ff") def corpus_files() -> list[Path]: """Every corpus file, in opcode order.""" return sorted(CORPUS.glob("*.json")) class Bench: """A 64 KiB RAM host that records every bus callback of a step.""" def __init__(self) -> None: self.memory = bytearray(0x10000) self.log: list[tuple[str, int | None, int | None]] = [] self.cpu = SPC700(self.read, self.write, self.idle) def read(self, address: int) -> int: value = self.memory[address] self.log.append(("read", address, value)) return value def write(self, address: int, value: int) -> None: self.memory[address] = value self.log.append(("write", address, value)) def idle(self) -> None: self.log.append(("wait", None, None)) def run_case(bench: Bench, case: dict, *, registers_only: bool = False) -> list[str]: """Run one case; return the list of disagreements (empty when it passes).""" initial, final = case["initial"], case["final"] memory = bench.memory for address, value in initial["ram"]: memory[address] = value bench.log.clear() cpu = bench.cpu cpu.restore_state(CPUState(**{name: initial[name] for name in REGISTERS})) problems: list[str] = [] cycles = cpu.step() if cycles != len(bench.log): problems.append(f"step() returned {cycles} but made {len(bench.log)} callbacks") if not registers_only: expected = case["cycles"] for index, (want, got) in enumerate(zip(expected, bench.log, strict=False)): address, data, kind = want if kind != got[0] or address != got[1] or (data is not None and data != got[2]): problems.append(f"cycle {index + 1}: expected {want}, got {got}") if len(expected) != len(bench.log): problems.append(f"{len(bench.log)} cycles, expected {len(expected)}") state = cpu.capture_state() problems.extend( f"{name}: {getattr(state, name):#x} != {final[name]:#x}" for name in REGISTERS if getattr(state, name) != final[name] ) wanted = dict(final["ram"]) for address, value in wanted.items(): if memory[address] != value: problems.append(f"[{address:#06x}] = {memory[address]:#x}, expected {value:#x}") for kind, address, _ in bench.log: if kind == "write" and address not in wanted: problems.append(f"unexpected write to {address:#06x}") for address in {a for a, _ in initial["ram"]} | set(wanted): memory[address] = 0 for _, address, _ in bench.log: if address is not None: memory[address] = 0 return problems def run_file(path: Path, limit: int | None = None) -> list[str]: """Run a corpus file (or its first ``limit`` cases); return ``name: problem`` lines.""" bench = Bench() registers_only = path.stem in REGISTERS_ONLY failures: list[str] = [] for case in json.loads(path.read_text(encoding="utf-8"))[:limit]: failures.extend( f"{case['name']}: {p}" for p in run_case(bench, case, registers_only=registers_only) ) return failures