"""Rung 0: every instruction's bus cycles are the datasheet's (DS Table 5-7). For every opcode in emulation mode and in native mode with each M/X pair, random states run one instruction through the core and through tests/datasheet.py's transcription of Table 5-7 with the decided readings layered on (U1-U3, C1, C2, C3, C5; docs/undocumented-behavior.md). Each cycle's (address, VDA, VPA, VPB, RWB, MLB) must agree, and so must the count. The states are biased towards the conditional cycles' paths: D.l zero half the time (note 2), operands and index registers near a page's end and direct-page sums at $xxFF a quarter of the time (note 4, U1, U3), branch flags at random (notes 5, 6), the stack at the ends of page one (U2), and short block moves. States in which the instruction writes over its own bytes are drawn again (see ``overwrites_itself``). Manufacturer tier: no other oracle is read. Mutation-checked: removing U1, U2 or U3 from the fixture, or note 4's store cycle, fails the quick run. """ import random import pytest from datasheet import OPCODES, Cycle, Machine, schedule from w65c816 import W65C816 QUICK_STATES = 24 SLOW_STATES = 2000 MODES = {"e": (1, 0x30), "n00": (0, 0x00), "n01": (0, 0x10), "n10": (0, 0x20), "n11": (0, 0x30)} EDGE_BYTES = (0x00, 0x01, 0x7F, 0x80, 0xFE, 0xFF) def pick_byte(rng: random.Random) -> int: return rng.choice(EDGE_BYTES) if rng.random() < 0.4 else rng.randrange(256) def pick_word(rng: random.Random) -> int: return pick_byte(rng) << 8 | pick_byte(rng) def random_state(rng: random.Random, opcode: int, mode: str) -> tuple[dict, dict[int, int]]: e, mx = MODES[mode] p = rng.randrange(256) & ~0x30 | mx state = { "pc": pick_word(rng), "pbr": pick_byte(rng), "dbr": pick_byte(rng), "d": pick_byte(rng) << 8 | (0 if rng.random() < 0.5 else pick_byte(rng)), "s": pick_word(rng), "a": pick_word(rng), "x": pick_word(rng), "y": pick_word(rng), "p": p, "e": e, } # fmt: skip if e: state["s"] = 0x0100 | pick_byte(rng) if p & 0x10: state["x"] &= 0xFF state["y"] &= 0xFF if OPCODES[opcode][1] == "xyc": state["a"] = rng.randrange(4) # at most four bytes moved pc = state["pbr"] << 16 | state["pc"] memory = {pc: opcode} operands = [pick_byte(rng) for _ in range(3)] if rng.random() < 0.25: # a direct-page sum at $xxFF (U1, U3) index = state["x"] if rng.random() < 0.5 else 0 operands[0] = (0xFF - state["d"] - index) & 0xFF for k, value in enumerate(operands, 1): memory[state["pbr"] << 16 | (state["pc"] + k) & 0xFFFF] = value return state, memory def run_core(state: dict, memory: dict[int, int], seed: int) -> tuple[list[Cycle], dict]: """Run one instruction (a whole block move); return its cycles and the first value seen at every address it touched.""" fill = random.Random(seed) first: dict[int, int] = {} seen: list[Cycle] = [] def value_at(address: int) -> int: if address not in memory: memory[address] = fill.randrange(256) first.setdefault(address, memory[address]) return memory[address] def read_byte(address: int) -> int: seen.append(Cycle(address, cpu.vda, cpu.vpa, False, cpu.vpb, cpu.mlb)) return value_at(address) def write_byte(address: int, value: int) -> None: value_at(address) seen.append(Cycle(address, cpu.vda, cpu.vpa, True, cpu.vpb, cpu.mlb)) memory[address] = value def idle(address: int) -> None: seen.append(Cycle(address, cpu.vda, cpu.vpa, False, cpu.vpb, cpu.mlb)) cpu = W65C816(read_byte, write_byte, idle) for name, value in state.items(): setattr(cpu, name, value) start = cpu.pc cpu.step() while cpu.pc == start and memory[state["pbr"] << 16 | start] in (0x44, 0x54): cpu.step() # MVP/MVN: one byte per step until C wraps return seen, first def overwrites_itself(state: dict, cycles: list[Cycle]) -> bool: """Whether the instruction wrote over its own opcode or operands (a push over JSR (a,x)'s operand, a block move onto MVN): the transcription reads those bytes from the initial memory, so such states are drawn again.""" own = {state["pbr"] << 16 | (state["pc"] + k) & 0xFFFF for k in range(4)} return any(cycle.write and cycle.address in own for cycle in cycles) def check(opcode: int, mode: str, states: int) -> None: rng = random.Random(opcode << 8 | list(MODES).index(mode)) number = 0 while number < states: state, memory = random_state(rng, opcode, mode) got, first = run_core(state, memory, rng.randrange(1 << 30)) if overwrites_itself(state, got): continue number += 1 want = list(schedule(opcode, Machine(state, first, quirks=True))) where = f"{opcode:02X} {OPCODES[opcode]} {mode} state {number}: {state}" assert len(got) == len(want), f"{where}: {len(got)} cycles, datasheet {len(want)}" for index, (core, sheet) in enumerate(zip(got, want, strict=True)): assert (core.address, core.signals()) == (sheet.address, sheet.signals()), ( f"{where}: cycle {index}: core {core}, datasheet {sheet}" ) @pytest.mark.parametrize("mode", MODES) @pytest.mark.parametrize("opcode", range(256), ids=lambda opcode: f"{opcode:02x}") def test_schedule_is_the_datasheets(opcode: int, mode: str) -> None: check(opcode, mode, QUICK_STATES) @pytest.mark.slow @pytest.mark.parametrize("mode", MODES) @pytest.mark.parametrize("opcode", range(256), ids=lambda opcode: f"{opcode:02x}") def test_schedule_is_the_datasheets_many(opcode: int, mode: str) -> None: check(opcode, mode, SLOW_STATES)