# SPDX-License-Identifier: MIT """Rung 0: the generated table equals anomie's, and the handlers keep to it. Research documentation (anomie SPC700 Doc rev 1162). The JSON is rebuilt from the fetched document by scripts/anomie_opcodes.py; the table check is skipped without it, the behaviour checks are not. """ import json import random from pathlib import Path import pytest from spc700_python import SPC700, CPUState from spc700_python._dispatch import HANDLER_NAMES, RULES from spc700_python._opcodes import OPCODES JSON = Path(__file__).with_name("anomie_opcodes.json") @pytest.mark.skipif(not JSON.exists(), reason="run scripts/anomie_opcodes.py first") def test_generated_table_equals_anomie(): for entry in json.loads(JSON.read_text(encoding="utf-8")): row = OPCODES[entry["opcode"]] assert row.mnemonic == entry["mnemonic"] assert row.operands == entry["operands"] assert row.length == entry["bytes"] assert list(row.cycles) == entry["cycles"] assert row.flags == entry["flags"] def test_all_256_opcodes_decode(): assert len(HANDLER_NAMES) == 256 assert all(len(pattern) == 8 for pattern, _ in RULES) class Bench: """One random memory for one opcode; each run picks a new PC and registers in it.""" def __init__(self, opcode: int) -> None: self.opcode = opcode self.rng = random.Random(opcode) self.memory = bytearray(self.rng.randbytes(0x10000)) self.log: list[str] = [] self.cpu = SPC700(self.read, self.write, lambda: self.log.append("i")) def read(self, address: int) -> int: self.log.append("r") return self.memory[address] def write(self, address: int, value: int) -> None: self.log.append("w") self.memory[address] = value def run(self) -> tuple[int, int]: """One random instruction: (cycles, PSW before).""" rng = self.rng self.log.clear() pc = rng.randrange(0x10000) self.memory[pc] = self.opcode psw = rng.randrange(256) self.cpu.restore_state( CPUState( a=rng.randrange(256), x=rng.randrange(256), y=rng.randrange(256), sp=rng.randrange(256), pc=pc, psw=psw, ) ) return self.cpu.step(), psw @pytest.mark.parametrize("opcode", range(256), ids=lambda o: f"{o:02X}") def test_cycles_equal_anomie_and_callbacks(opcode): """Every cycle count seen is anomie's, and ``step()`` returned the callback count. Both paths of the conditionals are forced in test_bus_schedule.py.""" bench = Bench(opcode) entry = OPCODES[opcode] for _ in range(200): cycles, _ = bench.run() assert cycles == len(bench.log) assert cycles in (entry.cycles or (1,)) # SLEEP, STOP: the fetch, then stopped (C5) @pytest.mark.parametrize("opcode", range(256), ids=lambda o: f"{o:02X}") def test_only_the_flags_anomie_lists_change(opcode): entry = OPCODES[opcode] free = sum(0x80 >> i for i, c in enumerate(entry.flags) if c != ".") forced_set = sum(0x80 >> i for i, c in enumerate(entry.flags) if c == "1") forced_clear = sum(0x80 >> i for i, c in enumerate(entry.flags) if c == "0") bench = Bench(opcode) for _ in range(200): _, before = bench.run() assert (bench.cpu.psw ^ before) & ~free & 0xFF == 0 assert bench.cpu.psw & forced_set == forced_set assert bench.cpu.psw & forced_clear == 0 @pytest.mark.parametrize("opcode", range(256), ids=lambda o: f"{o:02X}") def test_length_equals_anomie(opcode): """Instructions that do not jump end at PC + length; a zero offset makes both paths do so.""" entry = OPCODES[opcode] if entry.mnemonic in {"JMP", "CALL", "PCALL", "TCALL", "BRK", "RET", "RET1"}: return memory = bytearray(0x10000) memory[0x4000] = opcode cpu = SPC700(memory.__getitem__, memory.__setitem__) cpu.restore_state(CPUState(pc=0x4000)) cpu.step() assert cpu.pc == 0x4000 + entry.length