# SPDX-License-Identifier: MIT """Readability contract for the instruction core, enforced the way correctness is. Following the family's tests/test_readability.py (6502-python, 65816-python, huc6280-python): every opcode handler must be findable by the mnemonic a 65C02 programmer would grep for, live in the module that owns its instruction family, and say where its rule comes from. Checked from the source with :mod:`ast`, without importing it: 1. Every ``_op_*`` method's docstring headline is ``MNEMONIC[ form] -- text (SOURCES).``, where SOURCES names at least one source by its key in docs/start-here.md (``DS``, ``RDS``, ``GDS``, ``VDS``, ``NDS``, ``CAP``, ``CL``, ``LK``, ``GF``, ``BC``, ``GW``, ``LT``). 2. The handler lives in the module that owns that mnemonic and is named after it, and every mnemonic of the opcode table has a handler. 3. Every opcode's handler exists and takes the mode argument exactly when the table says it has one, and the mode method exists. 4. Every U and C number cited in the source is an entry of docs/undocumented-behavior.md. """ import ast import inspect import re from pathlib import Path import pytest from w65c02_python import CMOS65C02 from w65c02_python._dispatch import OPCODES ROOT = Path(__file__).resolve().parents[1] SRC = ROOT / "src" / "w65c02_python" OWNERS: dict[str, frozenset[str]] = { module: frozenset(mnemonics.split()) for module, mnemonics in { "_alu.py": "ADC SBC AND ORA EOR CMP CPX CPY BIT", "_loads.py": "LDA LDX LDY STA STX STY STZ TAX TAY TXA TYA TSX TXS INX INY DEX DEY", "_shifts.py": "ASL LSR ROL ROR INC DEC", "_bits.py": "TSB TRB RMB SMB BBR BBS", "_nops.py": "NOP", "_control.py": "BPL BMI BVC BVS BCC BCS BNE BEQ BRA JMP JSR RTS RTI PHA PHX PHY PHP " "PLA PLX PLY PLP CLC SEC CLD SED CLV CLI SEI BRK WAI STP", }.items() } HEADLINE = re.compile( r"^(?P[A-Z]{3})(?P
[^-]*?) -- (?P.+)\((?P[^()]+)\)\.$" ) SOURCE_KEYS = re.compile(r"\b(DS|RDS|GDS|VDS|NDS|CAP|CL|LK|GF|BC|GW|LT)\b") def family(mnemonic: str) -> str: """The mnemonic without a bit number (BBR0 -> BBR).""" return mnemonic[:3] def handlers() -> list[tuple[str, ast.FunctionDef]]: found = [] for path in sorted(SRC.glob("_*.py")): tree = ast.parse(path.read_text(encoding="utf-8")) for cls in (node for node in tree.body if isinstance(node, ast.ClassDef)): found += [ (path.name, node) for node in cls.body if isinstance(node, ast.FunctionDef) and node.name.startswith("_op_") ] assert found return found HANDLERS = handlers() def headline(node: ast.FunctionDef) -> str: docstring = ast.get_docstring(node) or "" return " ".join(docstring.split("\n\n")[0].split()) @pytest.mark.parametrize(("module", "node"), HANDLERS, ids=[node.name for _, node in HANDLERS]) def test_handler_headline_names_its_mnemonic_and_cites_a_source( module: str, node: ast.FunctionDef ) -> None: line = headline(node) match = HEADLINE.match(line) assert match, f"{node.name}: headline must read 'MNEMONIC -- text (SOURCES).', got {line!r}" assert SOURCE_KEYS.search(match["sources"]), f"{node.name}: no source key in {line!r}" @pytest.mark.parametrize(("module", "node"), HANDLERS, ids=[node.name for _, node in HANDLERS]) def test_handler_lives_in_its_module_and_is_named_after_its_mnemonic( module: str, node: ast.FunctionDef ) -> None: mnemonic = HEADLINE.match(headline(node))["mnemonic"] assert mnemonic in OWNERS[module], f"{node.name}: {mnemonic} belongs elsewhere" assert node.name.removeprefix("_op_").split("_")[0] == mnemonic.lower() def test_every_mnemonic_has_a_handler_and_no_handler_is_defined_twice() -> None: names = [node.name for _, node in HANDLERS] assert len(names) == len(set(names)), "a duplicate would be shadowed by the MRO" claimed = {HEADLINE.match(headline(node))["mnemonic"] for _, node in HANDLERS} defined = {family(OPCODES[opcode][2]) for opcode in range(256)} assert claimed == defined, claimed ^ defined assert set().union(*OWNERS.values()) == defined @pytest.mark.parametrize("opcode", range(256), ids=lambda opcode: f"{opcode:02x}") def test_every_opcode_has_a_handler_that_takes_its_mode(opcode: int) -> None: handler, mode, mnemonic, _form, _cycles = OPCODES[opcode] assert handler.split("_")[0] == family(mnemonic).lower() function = getattr(CMOS65C02, f"_op_{handler}") parameters = list(inspect.signature(function).parameters) assert parameters == (["self"] if mode is None else ["self", "mode"]), (handler, mode) if mode is not None: assert callable(getattr(CMOS65C02, f"_{mode}")) def test_every_cited_unknown_and_contradiction_exists() -> None: entries = set( re.findall( r"^\*\*([UC]\d+)\.", (ROOT / "docs" / "undocumented-behavior.md").read_text(encoding="utf-8"), re.MULTILINE, ) ) assert entries for path in sorted(SRC.glob("*.py")): cited = set(re.findall(r"\b([UC]\d{1,2})\b", path.read_text(encoding="utf-8"))) assert cited <= entries, f"{path.name} cites {sorted(cited - entries)}"