# SPDX-License-Identifier: MIT """Readability contract for the instruction core, enforced the way correctness is. The core is a reference, so every handler must be findable by the mnemonic an ARM programmer would grep for, must live in the module that owns that instruction family, and must say where its rule comes from. Derived from the source with :mod:`ast` (nothing is executed): 1. Every handler the decode tables name 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 (DS or TRM section, timing.md, a docs item such as ``U4`` or ``C5``). 2. Every handler lives in the module that owns its mnemonic family, and is defined once. 3. The tables name only handlers that exist, and every ``_arm_*``/``_thumb_*`` method that is not a handler is a helper with a different prefix shape (no dead handlers). """ from __future__ import annotations import ast import re from pathlib import Path import pytest from arm7tdmi_python._tables import ARM_HANDLERS, THUMB_HANDLERS SRC = Path(__file__).resolve().parents[1] / "src" / "arm7tdmi_python" OWNERS: dict[str, frozenset[str]] = { module: frozenset(mnemonics.split()) for module, mnemonics in { "_alu.py": "AND EOR SUB RSB ADD ADC SBC RSC TST TEQ CMP CMN ORR MOV BIC MVN LSL LSR ASR " "ROR NEG", "_psr.py": "MRS MSR", "_multiply.py": "MUL MLA UMULL UMLAL SMULL SMLAL", "_transfer.py": "LDR STR LDRB STRB LDRH STRH LDRSB LDRSH LDSB LDSH LDRD STRD", "_block.py": "LDM STM PUSH POP LDMIA STMIA", "_swap.py": "SWP SWPB", "_branch.py": "B BL BX", "_exception.py": "SWI UNDEFINED CDP LDC STC MRC MCR", }.items() } HANDLER_NAMES = frozenset(ARM_HANDLERS) | frozenset(THUMB_HANDLERS) _SEGMENT = re.compile(r"^(?P[A-Z]+)(?:[<\s].*)?$") _CITATION = re.compile(r"\((?=[^)]*(?:DS \d|TRM|timing\.md|table \d|U\d+|C\d+))[^)]*\)\.?$") def methods() -> dict[str, tuple[str, str]]: """name -> (module file, docstring) for every ``_arm_*``/``_thumb_*`` method.""" found: dict[str, tuple[str, str]] = {} for path in sorted(SRC.glob("_*.py")): for node in ast.walk(ast.parse(path.read_text())): if isinstance(node, ast.FunctionDef) and node.name.startswith(("_arm_", "_thumb_")): 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 METHODS = methods() def headline(doc: str) -> str: return doc.split("\n\n")[0].replace("\n", " ").strip() def mnemonics(doc: str) -> list[str]: 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 def test_tables_name_existing_handlers(): missing = sorted(HANDLER_NAMES - METHODS.keys()) assert not missing, f"tables name undefined handlers: {missing}" @pytest.mark.parametrize("name", sorted(HANDLER_NAMES)) def test_handler_headline(name): module, doc = METHODS[name] assert doc, f"{name} has no docstring" assert " -- " in headline(doc), f"{name}: headline needs 'MNEMONIC -- explanation'" 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}: {word} does not belong in {module}" def test_helpers_are_not_handlers(): """A method shaped like a handler but in no table is dead or misnamed.""" helpers = { "_arm_load", "_arm_store", "_thumb_next", "_thumb_shift_imm", "_thumb_logic", "_thumb_shift_reg", "_thumb_load", "_thumb_store", "_thumb_refill_from", } # fmt: skip dead = sorted(METHODS.keys() - HANDLER_NAMES - helpers) assert not dead, f"handler-shaped methods no table names: {dead}"