#!/usr/bin/env python3 """WDC's Table 5-7 (W65C816S datasheet, 2024-03-13) as code, compared with SingleStepTests. Table 5-7 lists, for every addressing mode, each cycle's VPB, MLB, VDA, VPA, RWB and address-bus expression, with notes (1)-(17) adding or removing cycles. tests/datasheet.py transcribes it, one branch per table row; used here *literally*: it applies no knowledge from any other source (no emulation-mode page wrapping, no 65C02 fixes), so every disagreement with the corpus is a place where the datasheet is silent, wrong, or simplified. It is a measuring tool for docs/timing.md and docs/validation.md, not a CPU: it evaluates only what the address bus and cycle count need (operand bytes, index registers, D, S, a branch condition), never an instruction's result. python -I scripts/datasheet_timing.py # every file, 1,000 cases each python -I scripts/datasheet_timing.py --cases 10000 # every case python -I scripts/datasheet_timing.py --opcodes 7c fc 22 --show 2 It reads reference/src/65816/v1/*.json (scripts/fetch_references.py) and prints, per opcode and mode (e/n): cases whose cycle count agrees, cases whose per-cycle signals (VDA VPA VPB RWB MLB) agree, and cases whose addresses agree on VDA/VPA cycles and on internal (IO) cycles separately. ``--json PATH`` writes the per-file numbers. """ from __future__ import annotations import argparse import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "65816" / "v1" sys.path.insert(0, str(ROOT / "tests")) # The transcription lives in tests/datasheet.py, rung 0's fixture; this # script uses it literally (quirks off) to measure the corpus. from datasheet import OPCODES, Machine, schedule def corpus_cycles(case: dict) -> list[tuple[int, tuple[bool, ...]]]: """The corpus's cycles; WAI and STP end with a [null, null, '--------'] row that marks the stopped clock rather than a bus cycle, and is dropped.""" rows = [] for address, _value, flags in case["cycles"]: if address is None: continue rows.append( (address, (flags[0] == "d", flags[1] == "p", flags[2] == "v", flags[3] == "w", flags[7] == "l")) ) # fmt: skip return rows def compare_file(path: Path, cases: int, show: int) -> dict: op = int(path.name[:2], 16) tally = {"cases": 0, "count": 0, "signals": 0, "bus_address": 0, "io_address": 0} shown = 0 with path.open(encoding="utf-8") as handle: tests = json.load(handle)[:cases] for case in tests: initial = case["initial"] ram = {address: value for address, value in initial["ram"]} machine = Machine(initial, ram) expected = list(schedule(op, machine)) actual = corpus_cycles(case) tally["cases"] += 1 if len(expected) != len(actual): if shown < show: shown += 1 print(f" {case['name']}: datasheet {len(expected)} cycles, corpus {len(actual)}") continue tally["count"] += 1 pairs = list(zip(expected, actual, strict=True)) if all(cycle.signals() == flags for cycle, (_, flags) in pairs): tally["signals"] += 1 elif shown < show: shown += 1 print(f" {case['name']}: signals differ") for cycle, (address, flags) in pairs: print(f" datasheet {cycle.address:06x} {cycle.signals()}", end="") print(f" corpus {address:06x} {flags}") bus = [(c.address, a) for c, (a, f) in pairs if f[0] or f[1] or f[2]] idle = [(c.address, a) for c, (a, f) in pairs if not (f[0] or f[1] or f[2])] tally["bus_address"] += all(x == y for x, y in bus) tally["io_address"] += all(x == y for x, y in idle) return tally def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--cases", type=int, default=1000, help="cases per file (max 10,000)") parser.add_argument("--opcodes", nargs="*", help="hex opcodes to check (default: all)") parser.add_argument("--show", type=int, default=0, help="disagreements to print per file") parser.add_argument("--json", type=Path, help="write per-file tallies here") args = parser.parse_args() if not CORPUS.is_dir(): raise SystemExit(f"{CORPUS} missing: run scripts/fetch_references.py") wanted = {int(o, 16) for o in args.opcodes} if args.opcodes else set(range(256)) results = {} totals = {"cases": 0, "count": 0, "signals": 0, "bus_address": 0, "io_address": 0} for path in sorted(CORPUS.glob("*.json")): op = int(path.name[:2], 16) if op not in wanted: continue tally = compare_file(path, args.cases, args.show) results[path.stem] = tally for key in totals: totals[key] += tally[key] mnemonic, mode = OPCODES[op] agreed = {tally[key] for key in ("count", "signals", "bus_address", "io_address")} flag = "" if agreed == {tally["cases"]} else " *" print(f"{path.stem:5} {mnemonic} {mode:8} count {tally['count']:5}/{tally['cases']}" f" signals {tally['signals']:5} bus-addr {tally['bus_address']:5}" f" io-addr {tally['io_address']:5}{flag}") # fmt: skip print(f"total: {totals}") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())