# SPDX-License-Identifier: MIT """Run SingleStepTests 65x02 cases (the three CMOS sets) through the core, bus cycles included. The corpus is **emulator-generated** (docs/validation.md): a volume detector, never a judge. Each case gives the registers and sparse RAM before and after one instruction and every cycle as ``[address, value, "read" | "write"]``. A case passes when the core's registers, RAM, cycle count (``step()``'s return and the number of callbacks) and every cycle's address, value and direction equal the corpus's. How the corpus is read: - **B** (bit 4 of P) has no flip-flop; the core never stores it. The corpus keeps a B bit in its ``p`` (set in about half the initial states, cleared by ``PLP`` and ``RTI``). It is dropped going in and not compared coming out. Bit 5 is compared. Where a higher tier contradicts the corpus the core follows the higher tier, and the cases are **counted by name**, each class an entry of docs/undocumented-behavior.md. A case is counted only if it fails the full comparison and passes its classes' reduced comparison, which is everything the contradiction does not touch. Two kinds of class: *The instruction itself differs.* - ``C1``: ``$5C`` is 8 cycles (CAP on both parts, DS, GDS, VDS, NDS), 4 in the corpus. Reduced: registers, RAM and the first three cycles. - ``C2``: ``x7`` and ``xF`` on the part without bit instructions are one-byte, one-cycle NOPs (CAP on the G65SC12; GDS, VDS, NDS); the ``synertek65c02`` set has two- and three-byte NOPs. Reduced: A X Y S P and RAM unchanged, the opcode fetch. - ``C3``: ``$CB`` and ``$DB`` without ``WAI``/``STP`` are one-byte, one-cycle NOPs (GDS, VDS, NDS, CL); the Rockwell and Synertek sets have 1 byte 2 cycles and 2 bytes 4 cycles. Reduced: as C2. *Only the address of a dummy read differs* (the captures of two real parts decide the address, rung 4; the corpus has another). Reduced: registers, RAM, the cycle count, every cycle's direction, and the address and value of every cycle but the named dummy cycle(s): - ``C10``: ``$DC`` and ``$FC``, cycle 4: the absolute address (CL note i, LK, CAP); the corpus re-reads the last operand byte. - ``C13``: the cycle decimal mode adds to ``ADC`` and ``SBC`` (the last): the next opcode's address (CAP); the corpus re-reads the operand, and for the immediate forms a fixed address that differs between its sets. - ``C14``: indexed stores and ``INC``/``DEC abs,X`` without a page crossing, cycle 4: the operand's own address (CAP); the corpus re-reads PC+2. - ``C15``: ``(zp),Y``, the extra cycle (cycle 5): the pointer's high byte in page zero again (CAP); the corpus re-reads PC+1. - ``C16``: a branch taken across a page, cycle 4: the next opcode's address again (CAP); the corpus reads the old page with the target's low byte. - ``C17``: ``JMP (abs)``, cycles 4 to 6: the operand's high byte again, then the pointer (CAP); the corpus reads the pointer, the NMOS part's wrong high address, then the right one. ``JMP (abs,X)``, cycle 4: the operand's high byte again (CAP); the corpus re-reads the low byte. - ``C18``: ``zp,X``, ``zp,Y`` and ``(zp,X)``, cycle 3: the operand byte again (CAP); the corpus reads the unindexed zero-page address. """ from __future__ import annotations import json from collections.abc import Iterator from pathlib import Path from w65c02_python import G65SC02, R65C02, W65C02S from w65c02_python._dispatch import OPCODES ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "65x02" FETCH_HINT = "SingleStepTests 65x02 not fetched: python -I scripts/fetch_references.py" #: corpus set -> the row it is run on (docs/validation.md, rung 1). SETS = {"wdc65c02": W65C02S, "rockwell65c02": R65C02, "synertek65c02": G65SC02} REGISTERS = ("pc", "s", "a", "x", "y", "p") B = 0x10 D = 0x08 ADC_SBC = frozenset(opcode for opcode, row in OPCODES.items() if row[2] in ("ADC", "SBC")) BIT_OPCODES = frozenset(opcode for opcode in range(256) if opcode & 0x0F in (0x07, 0x0F)) def _dummy_classes() -> dict[tuple[int, int], str]: """(opcode, cycle index from 0) -> the class that says the corpus's dummy address is wrong.""" classes: dict[tuple[int, int], str] = {} for opcode, (_handler, mode, _mnemonic, form, _cycles) in OPCODES.items(): if form in ("zpx", "zpy", "idx"): classes[opcode, 2] = "C18" if form == "idy": classes[opcode, 4] = "C15" if mode is not None and mode.endswith("_fixed") and form in ("abx", "aby"): classes[opcode, 3] = "C14" if form == "rel": classes[opcode, 3] = "C16" for index in (3, 4, 5): classes[0x6C, index] = "C17" classes[0x7C, 3] = "C17" classes[0xDC, 3] = classes[0xFC, 3] = "C10" return classes DUMMY_CLASSES = _dummy_classes() def corpus_present() -> bool: return all((CORPUS / name / "v1" / "a9.json").is_file() for name in SETS) def load_cases(set_name: str, opcode: int, limit: int | None = None) -> Iterator[dict]: """The cases of one file: a JSON array with one case per line (an empty file has none).""" path = CORPUS / set_name / "v1" / f"{opcode:02x}.json" with path.open(encoding="utf-8") as handle: for line in handle: # The array's brackets and separators; a case starts with "{" and ends with "}". line = line.strip().lstrip("[").rstrip(",]") if not line.startswith("{"): continue yield json.loads(line) if limit is not None: limit -= 1 if not limit: return def run_case(case: dict, set_name: str, row: type | None = None) -> tuple[list[str], list[str]]: """Run one case on the set's row (or ``row``). Returns (problems, classes): no problems and no classes is a pass; no problems and classes is a case counted under those names; problems are a failure. """ initial = case["initial"] final = case["final"] memory = dict(initial["ram"]) seen: list[tuple[int, int, str]] = [] def read_byte(address: int) -> int: value = memory.get(address, 0) seen.append((address, value, "read")) return value def write_byte(address: int, value: int) -> None: memory[address] = value seen.append((address, value, "write")) cpu = (row or SETS[set_name])(read_byte, write_byte) for name in REGISTERS: setattr(cpu, name, initial[name]) cpu.p = initial["p"] & ~B returned = cpu.step() opcode = int(case["name"].split()[0], 16) expected = [tuple(cycle) for cycle in case["cycles"]] registers = [ f"{name}: got ${getattr(cpu, name):X}, want ${final[name]:X}" for name in REGISTERS if name != "p" and getattr(cpu, name) != final[name] ] if (cpu.p ^ final["p"]) & ~B: registers.append(f"p: got ${cpu.p:02X}, want ${final['p']:02X} (B not compared)") ram = [ f"ram ${address:04X}: got ${memory.get(address, 0):02X}, want ${value:02X}" for address, value in final["ram"] if memory.get(address, 0) != value ] count = [] if returned != len(seen): count.append(f"step() returned {returned} for {len(seen)} callbacks") if len(seen) != len(expected): count.append(f"cycles: got {len(seen)}, want {len(expected)}") differing = [index for index, pair in enumerate(zip(seen, expected)) if pair[0] != pair[1]] bus = [f"cycle {index + 1}: got {seen[index]}, want {expected[index]}" for index in differing] problems = registers + ram + count + bus if not problems: return [], [] # The classes where the instruction itself differs. if opcode == 0x5C: if not registers and not ram and seen[:3] == expected[:3] and returned == len(seen) == 8: return [], ["C1"] return problems, [] name = None if set_name == "synertek65c02" and opcode in BIT_OPCODES: name = "C2" elif set_name != "wdc65c02" and opcode in (0xCB, 0xDB): name = "C3" if name: unchanged = all(getattr(cpu, r) == initial[r] for r in ("s", "a", "x", "y")) unchanged = unchanged and not (cpu.p ^ initial["p"]) & ~B and not ram if unchanged and seen == expected[:1] and cpu.pc == (initial["pc"] + 1) & 0xFFFF: return [], [name] return problems, [] # The classes where only a dummy read's address differs. if registers or ram or count: return problems, [] classes = set() for index in differing: name = DUMMY_CLASSES.get((opcode, index)) if name is None and opcode in ADC_SBC and initial["p"] & D and index == len(seen) - 1: name = "C13" if name is None or seen[index][2] != "read" or expected[index][2] != "read": return problems, [] classes.add(name) return [], sorted(classes)