# SPDX-License-Identifier: MIT """Readability contract for the instruction core, enforced the way correctness is (rung 0). The core is a reference, so every opcode handler must be findable by the mnemonic an SPC700 programmer would grep for, must live in the module that owns that instruction group, and must say where its rule comes from. Derived from the source with :mod:`ast` (nothing is executed): 1. Every ``_op_*`` method has a docstring whose headline (first paragraph) lists the mnemonics it implements, separated by ``/``, optionally followed by ``-- explanation``, and ends with the source of its rule in parentheses (docs/timing.md group or a docs item such as ``U4``). 2. Every handler lives in the module that owns its mnemonic group. 3. Every opcode of the generated table is claimed by the handler that decodes it, and no handler name is defined twice across the mixins (the MRO would silently shadow one). 4. The decode table names only handlers that exist, and every ``_op_*`` is reachable from it. """ from __future__ import annotations import ast import re from pathlib import Path import pytest from spc700_python._dispatch import HANDLER_NAMES from spc700_python._opcodes import OPCODES SRC = Path(__file__).resolve().parents[1] / "src" / "spc700_python" OWNERS: dict[str, frozenset[str]] = { module: frozenset(mnemonics.split()) for module, mnemonics in { "_moves.py": "MOV PUSH POP", "_alu.py": "OR AND EOR CMP ADC SBC ASL ROL LSR ROR INC DEC XCN DAA DAS", "_word.py": "MOVW ADDW SUBW CMPW INCW DECW MUL DIV", "_bit.py": "SET1 CLR1 TSET1 TCLR1 AND1 OR1 EOR1 NOT1 MOV1", "_control.py": ( "BPL BMI BVC BVS BCC BCS BNE BEQ BRA BBS BBC CBNE DBNZ JMP CALL PCALL TCALL BRK RET " "RET1 NOP CLRP SETP CLRC SETC NOTC CLRV EI DI SLEEP STOP" ), }.items() } _SEGMENT = re.compile(r"^(?P[A-Z][A-Z0-9]*)(?:\s.*)?$") _CITATION = re.compile(r"\((?:timing\.md|U\d+|C\d+).*\)\.?$") def handlers() -> dict[str, tuple[str, str]]: """name -> (module file, docstring) for every ``_op_*`` method.""" found: dict[str, tuple[str, str]] = {} for path in sorted(SRC.glob("_*.py")): for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): if isinstance(node, ast.FunctionDef) and node.name.startswith("_op_"): assert node.name not in found, f"{node.name} defined twice ({path.name})" found[node.name] = (path.name, ast.get_docstring(node) or "") return found HANDLERS = handlers() def headline(doc: str) -> str: return doc.split("\n\n")[0].replace("\n", " ").strip() def mnemonics(doc: str) -> list[str]: """The mnemonic words a docstring headline claims.""" words = [] for segment in headline(doc).split(" -- ")[0].split("/"): match = _SEGMENT.match(segment.strip()) assert match, f"headline segment {segment!r} does not start with a mnemonic" words.append(match["word"]) return words @pytest.mark.parametrize("name", sorted(HANDLERS)) def test_docstring_headline(name): module, doc = HANDLERS[name] assert doc, f"{name} has no docstring" assert _CITATION.search(headline(doc)), f"{name}: headline must end with its source" for word in mnemonics(doc): assert word in OWNERS[module], f"{name} claims {word}, which {module} does not own" def test_every_opcode_is_claimed_by_its_handler(): for code, entry in enumerate(OPCODES): name = HANDLER_NAMES[code] assert entry.mnemonic in mnemonics(HANDLERS[name][1]), f"${code:02X} -> {name}" def test_decode_table_names_real_handlers_and_leaves_none_dead(): assert set(HANDLER_NAMES) <= set(HANDLERS) dead = set(HANDLERS) - set(HANDLER_NAMES) assert not dead, f"handlers no opcode reaches: {sorted(dead)}"