"""Derive src/z80_python/_access_timing.py from the SingleStepTests corpus. SingleStepTests gives every case's bus state once per T-state (``cycles``: ``[address, data, pins]``, sampled between T-states; ``pins`` shows ``r``/``w`` and ``m``/``i``). This script reads all 1,604 files and, for each instruction, records where each of its memory and I/O accesses falls: the index of the first sample whose pins show that access. It then checks that every case of an instruction agrees. An instruction has one *shape* (a fixed list of accesses and a fixed length) or, for the conditional and repeating ones, two. The two always agree on every access they both make: they differ only in whether the later accesses happen and in how many internal T-states follow. So one list per instruction, the longest, answers "when does the k-th access fall" before the instruction has decided which way it goes. The script refuses to write a table if any instruction breaks that. python scripts/fetch_test_vectors.py # once python scripts/derive_access_timing.py # rewrite the table python scripts/derive_access_timing.py --check ``--check`` exits 1 if the committed table differs from a fresh derivation; tests/test_access_timing.py runs it when the corpus is present. """ from __future__ import annotations import argparse import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "tests" / "z80_test_vectors" / "v1" TABLE = ROOT / "src" / "z80_python" / "_access_timing.py" #: SingleStepTests pin strings, as the access kinds of z80_python.timing. KINDS = {"r-m-": "read", "-wm-": "write", "r--i": "in", "-w-i": "out"} def key_of(stem: str) -> tuple[int, ...]: """``"dd cb __ 06"`` -> ``(0xDD, 0xCB, 0x06)``: the opcode bytes, displacement left out.""" return tuple(int(token, 16) for token in stem.split() if token != "__") def accesses_of(cycles: list) -> tuple[tuple[str, int], ...]: found: list[tuple[str, int]] = [] previous = "----" for t, (_address, _data, pins) in enumerate(cycles): if pins != previous and pins in KINDS: found.append((KINDS[pins], t)) elif pins != "----" and pins not in KINDS: raise ValueError(f"unknown pins {pins!r}") previous = pins return tuple(found) def derive(corpus: Path = CORPUS) -> dict[tuple[int, ...], tuple[tuple, tuple]]: """Return ``{opcode bytes: (longest access list, ((t_states, accesses made), ...))}``. The shapes are those the corpus shows, plus each block repeat's last pass (see below); the accesses are the corpus's alone. """ table = {} files = sorted(corpus.glob("*.json")) if len(files) != 1604: raise SystemExit(f"expected 1,604 corpus files in {corpus}, found {len(files)}") for path in files: shapes = set() for case in json.loads(path.read_text()): shapes.add((accesses_of(case["cycles"]), len(case["cycles"]))) longest = max((accesses for accesses, _ in shapes), key=len) for accesses, _ in shapes: if longest[: len(accesses)] != accesses: raise SystemExit(f"{path.name}: shapes disagree on a shared access: {shapes}") table[key_of(path.stem)] = ( longest, tuple(sorted((t_states, len(accesses)) for accesses, t_states in shapes)), ) # A block instruction's last pass (BC or B run out, or CPIR/CPDR matching) # is its one-shot form: LDIR ends as LDI. The corpus draws BC at random, so # LDIR/LDDR's last pass (BC = 1) never occurs in it; take that shape from # the one-shot form, whose accesses must be the repeat's exactly. for repeat in range(0xB0, 0xBC): if (repeat & 0x07) > 3: continue once = table[(0xED, repeat - 0x10)] accesses, shapes = table[(0xED, repeat)] if once[0] != accesses: raise SystemExit(f"ED {repeat:02X}: accesses differ from ED {repeat - 0x10:02X}") table[(0xED, repeat)] = (accesses, tuple(sorted(set(shapes) | set(once[1])))) return table def render(table: dict) -> str: lines = [ '"""GENERATED by scripts/derive_access_timing.py from SingleStepTests. Do not edit.', "", "Where each memory and I/O access of each instruction falls; see z80_python.timing.", "Key: the opcode bytes (prefixes and opcode, not operands or displacement).", "Value: (accesses, shapes). accesses: (kind, t) for every access the", "instruction can make, in order, t being the index of the first per-T-state bus", "sample that shows it. shapes: (t_states, how many of those accesses are made)", "for each way the instruction can execute.", '"""', "", "# fmt: off", "TABLE = {", ] for key, (accesses, shapes) in table.items(): opcode = ", ".join(f"0x{byte:02X}" for byte in key) listed = ", ".join(f'("{kind}", {t})' for kind, t in accesses) lines.append(f" ({opcode},): (({listed},), {shapes!r}),") lines += ["}", "# fmt: on", ""] return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--check", action="store_true") args = parser.parse_args(argv) source = render(derive()) if args.check: if TABLE.read_text() != source: print(f"{TABLE} differs from a fresh derivation", file=sys.stderr) return 1 print(f"{TABLE} matches the corpus") return 0 TABLE.write_text(source) print(f"wrote {TABLE}") return 0 if __name__ == "__main__": raise SystemExit(main())