# SPDX-License-Identifier: MIT """Rung 0: the opcode tables of every row against the data sheets and the measured counts. Judges (docs/validation.md): the manufacturers' tables as transcribed in tests/datasheet.py (tier 2), the cycle counts measured on real chips in docs/timing.md (CAP, tier 1), and, as a detector, the SingleStepTests grid (tier 5), from which every difference must be one of C1, C2 and C3. """ import json import re from collections import Counter from pathlib import Path import datasheet import pytest from w65c02_python import G65SC02, R65C02, W65C02S, Lynx2Cell from w65c02_python._dispatch import BIT_OPCODES, FORM_BYTES, OPCODES, WAI_STP_OPCODES, opcodes_for ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "65x02" #: The WDC data sheet's mode notation -> the dispatch table's form. DS_FORMS = { "a": "abs", "(a,x)": "abxind", "a,x": "abx", "a,y": "aby", "(a)": "ind", "A": "acc", "#": "imm", "i": "imp", "r": "rel", "s": "imp", "zp": "zp", "(zp,x)": "idx", "zp,x": "zpx", "zp,y": "zpy", "(zp)": "zpind", "(zp),y": "idy", } # fmt: skip #: GDS Table IV's columns -> the forms an opcode in that column can have. GDS_FORMS = { "imm": ("imm",), "abs": ("abs",), "zp": ("zp",), "imp": ("imp", "acc"), "(ind,x)": ("idx", "abxind"), "(ind),y": ("idy",), "zpg,x": ("zpx",), "abs,x": ("abx",), "abs,y": ("aby",), "rel": ("rel",), "ind": ("ind", "zpind"), "zpg,y": ("zpy",), } # fmt: skip def documented(row: type) -> set[int]: """The opcodes ``row`` gives an instruction (not an undefined-opcode NOP).""" return { opcode for opcode, (handler, *_rest) in opcodes_for(row).items() if not handler.startswith("nop_") } def test_the_w65c02s_row_is_the_data_sheets_opcode_matrix() -> None: """DS Table 5-2: mnemonic and addressing mode of all 212 opcodes; the rest are NOPs.""" matrix = datasheet.ds_matrix() table = opcodes_for(W65C02S) for opcode, cell in matrix.items(): handler, _mode, mnemonic, form, _cycles = table[opcode] if cell is None: assert handler.startswith("nop_") and mnemonic == "NOP", f"${opcode:02X}" continue want_mnemonic, want_mode = cell assert mnemonic == want_mnemonic, f"${opcode:02X}" if want_mnemonic[:3] in ("BBR", "BBS"): assert form == "zprel", f"${opcode:02X}" # the matrix prints "r"; three bytes (CL 4) elif want_mnemonic == "BRK": assert FORM_BYTES[form] == datasheet.DS_BRK_BYTES # Table 4-1 note 5 elif want_mnemonic == "JMP" and want_mode == "(a,x)": assert form == "abxind" else: assert form == DS_FORMS[want_mode], f"${opcode:02X}" assert len(documented(W65C02S)) == 212 # DS section 1.1 def test_the_rows_differ_only_in_the_cells_their_data_sheets_name() -> None: """RDS: no WAI or STP (210). GDS, VDS, NDS: no bit instructions either (178). C12: the Lynx II's cell is the 178 plus the bit instructions.""" full = documented(W65C02S) assert documented(R65C02) == full - set(WAI_STP_OPCODES) assert documented(G65SC02) == full - set(WAI_STP_OPCODES) - set(BIT_OPCODES) assert documented(Lynx2Cell) == documented(R65C02) assert len(documented(G65SC02)) == 178 # GDS, VDS, NDS "178 operational codes" for row in (R65C02, G65SC02, Lynx2Cell): table = opcodes_for(row) for opcode in documented(row): assert table[opcode] == OPCODES[opcode] @pytest.mark.parametrize( ("row", "nops"), [ (W65C02S, datasheet.DS_NOPS), # RDS has no WAI or STP: `$CB` and `$DB` join the one-byte, one-cycle NOPs (U3). (R65C02, {**datasheet.DS_NOPS, 0xCB: (1, 1), 0xDB: (1, 1)}), (G65SC02, datasheet.GDS_NOPS), (Lynx2Cell, {**datasheet.DS_NOPS, 0xCB: (1, 1), 0xDB: (1, 1)}), ], ids=lambda value: getattr(value, "__name__", ""), ) def test_undefined_opcodes_have_the_bytes_and_cycles_of_the_data_sheets(row, nops) -> None: """DS Table 7-1 and GDS Table V: every undefined opcode is a NOP of a stated size and time.""" table = opcodes_for(row) undefined = set(range(256)) - documented(row) assert undefined == {opcode for opcode in nops if opcode in undefined} for opcode in undefined: _handler, _mode, mnemonic, form, cycles = table[opcode] assert mnemonic == "NOP" assert (FORM_BYTES[form], cycles) == nops[opcode], f"${opcode:02X}" def test_bytes_and_cycles_are_gds_table_iv() -> None: """GDS Table IV: mnemonic, bytes and cycles of each of the 178 opcodes, with three stated exceptions.""" printed = datasheet.gds_table_iv() table = opcodes_for(G65SC02) assert set(printed) == documented(G65SC02) for opcode, (mnemonic, column, cycles, size) in printed.items(): _handler, _mode, ours, form, base = table[opcode] assert ours == mnemonic, f"${opcode:02X}" assert form in GDS_FORMS[column] or mnemonic == "BRK", f"${opcode:02X}" if mnemonic == "BRK": # Table IV prints one byte; BRK skips a second (DS Table 4-1 note 5; LT `cpu` test 4). assert (FORM_BYTES[form], base) == (2, cycles) continue assert FORM_BYTES[form] == size, f"${opcode:02X}" if mnemonic == "BRA": assert ( base == cycles + 1 ) # Table IV note 2: add 1 when the branch occurs; it always does elif mnemonic in ("INC", "DEC") and column == "abs,x": # C11: Table IV prints 6, as for the shifts; real parts take 7 in every # execution (CAP: `DE FE` 7; CL section 7). assert (cycles, base) == (6, 7) else: assert base == cycles, f"${opcode:02X}" def test_bit_instructions_wai_and_stp_are_clark_and_laughtons() -> None: """CL sections 4 and 5: bytes and cycles of the instructions Table IV does not have.""" for opcode in (*BIT_OPCODES, *WAI_STP_OPCODES): _handler, _mode, mnemonic, form, cycles = OPCODES[opcode] assert (FORM_BYTES[form], cycles) == datasheet.CL_EXTRA[mnemonic[:3]], mnemonic # -- the counts measured on real chips (docs/timing.md) ------------------------------------ #: Never ran without decimal mode or a page crossing on that part (docs/timing.md): the #: smallest count seen is base + 1. NEVER_AT_BASE = {(G65SC02, 0xF1), (R65C02, 0xF1), (R65C02, 0x71)} def measured() -> dict[int, tuple[set[int], set[int]]]: """docs/timing.md's table of cycle counts per opcode: opcode -> (G65SC12's, R65C02's).""" text = (ROOT / "docs" / "timing.md").read_text(encoding="utf-8") block = text.split("## Measured: cycles per opcode on real chips (CAP)")[1] block = block.split("```")[1] counts = {} for opcode, seen in re.findall(r"\b([0-9A-F]{2}) ([0-9/|*]+)", block): gte, _, rockwell = seen.replace("*", "").partition("|") gte_counts = {int(count) for count in gte.split("/")} counts[int(opcode, 16)] = ( gte_counts, {int(count) for count in rockwell.split("/")} if rockwell else gte_counts, ) return counts def test_base_cycles_are_the_counts_measured_on_real_chips() -> None: """CAP: for every opcode the captures executed, the smallest count seen on the G65SC12 is the G65SC02 row's base count and on the R65C02 the R65C02 row's, and the largest is at most two more (a branch across a page; decimal mode and a page crossed).""" counts = measured() assert set(counts) == set(range(256)) - {0x00, 0xCB, 0xDB} # never executed for row, part in ((G65SC02, 0), (R65C02, 1)): table = opcodes_for(row) for opcode, seen in counts.items(): base = table[opcode][4] fewest = min(seen[part]) assert fewest == base + ((row, opcode) in NEVER_AT_BASE), ( f"{row.__name__} ${opcode:02X}" ) assert max(seen[part]) <= base + 2, f"{row.__name__} ${opcode:02X}" def test_the_two_captured_parts_differ_only_in_the_bit_instructions() -> None: """CAP: `x7` and `xF` take one cycle on the G65SC12 and five or six on the R65C02 (C2); every other opcode's counts differ at most by a page crossing one machine's runs never made.""" for opcode, (gte, rockwell) in measured().items(): if opcode in BIT_OPCODES: assert gte == {1} assert rockwell <= {5, 6} and 5 in rockwell else: assert gte <= rockwell or rockwell <= gte, f"${opcode:02X}" # -- the corpus's grid, a detector ---------------------------------------------------------- SETS = {"wdc65c02": W65C02S, "rockwell65c02": R65C02, "synertek65c02": G65SC02} FLOW = ("rel", "zprel") # forms whose length the final PC does not show JUMPS = ("BRK", "JSR", "RTI", "RTS", "JMP") def corpus_grid(set_name: str, opcode: int, cases: int = 60) -> tuple[int | None, int] | None: """(bytes, fewest cycles) of the first cases of one corpus file; None for an empty file.""" path = CORPUS / set_name / "v1" / f"{opcode:02x}.json" lengths: Counter = Counter() fewest = None with path.open(encoding="utf-8") as handle: for line in handle: line = line.strip().rstrip(",") if not line.startswith("{"): continue case = json.loads(line) lengths[(case["final"]["pc"] - case["initial"]["pc"]) & 0xFFFF] += 1 cycles = len(case["cycles"]) fewest = cycles if fewest is None else min(fewest, cycles) cases -= 1 if not cases: break if fewest is None: return None return lengths.most_common(1)[0][0], fewest def test_every_difference_from_the_corpus_grid_is_c1_c2_or_c3() -> None: """SST (emulator tier): bytes and base cycles per opcode per set agree with the rows except `$5C` (C1), `x7`/`xF` in the Synertek set (C2) and `$CB`/`$DB` in the Rockwell and Synertek sets (C3). The WDC set has no cases for `$CB` and `$DB`.""" if not (CORPUS / "wdc65c02" / "v1" / "a9.json").is_file(): pytest.skip("SingleStepTests 65x02 not fetched: python -I scripts/fetch_references.py") expected = {(name, 0x5C) for name in SETS} expected |= {("synertek65c02", opcode) for opcode in BIT_OPCODES} expected |= {(name, opcode) for name in ("rockwell65c02", "synertek65c02") for opcode in (0xCB, 0xDB)} # fmt: skip different = set() for name, row in SETS.items(): table = opcodes_for(row) for opcode in range(256): grid = corpus_grid(name, opcode) if grid is None: assert name == "wdc65c02" and opcode in (0xCB, 0xDB) continue size, fewest = grid _handler, _mode, mnemonic, form, cycles = table[opcode] flow = form in FLOW or mnemonic in JUMPS if fewest != cycles or (not flow and size != FORM_BYTES[form]): different.add((name, opcode)) assert different == expected