#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Measure SingleStepTests spc700 against anomie's tables and the documented quirks. Reads ``reference/src/spc700/v1/*.json`` (emulator-derived, JSMoo) and ``tests/anomie_opcodes.json`` (scripts/anomie_opcodes.py) and prints the numbers docs/validation.md records: 1. cycle counts per opcode, every case, against anomie's ``Cyc`` column (both paths of conditional instructions); 2. the bus-kind sequence per opcode: ``R`` read with data, ``D`` read whose data the corpus leaves null (a dummy read), ``W`` write, ``I`` a ``wait`` cycle with no address; how many distinct sequences each opcode has; 3. the read-before-write claims in anomie's doc ("Most of the MOV instructions targeting memory actually include a read cycle on the destination"; MOV dd,ds, MOV (X)+,A and MOVW d,YA's high byte do not), checked on every case; 4. DIV and DAA/DAS final values against anomie's algorithms, every case; 5. how often the initial PSW has P set (direct page $01xx exercised). Run with ``python -I`` (it reads fetched files). ``--sequences`` prints every opcode's kind sequence(s), which docs/timing.md tabulates. python -I scripts/sst_survey.py python -I scripts/sst_survey.py --sequences """ from __future__ import annotations import argparse import json import sys from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SST = ROOT / "reference" / "src" / "spc700" / "v1" ANOMIE = ROOT / "tests" / "anomie_opcodes.json" KIND = {"read": "R", "write": "W", "wait": "I"} def kinds(cycles: list) -> str: out = [] for address, data, kind in cycles: letter = KIND[kind] if letter == "R" and data is None: letter = "D" if letter == "I" and address is not None: letter = "i" # a wait that names an address: none expected out.append(letter) return "".join(out) def anomie_div(ya: int, x: int) -> tuple[int, int, bool]: """anomie-spc700.txt "DIV has some interesting corner cases": the 9-step loop.""" yva = ya xs = x << 9 for _ in range(9): yva = ((yva << 1) | (yva >> 16)) & 0x1FFFF # ROL within 17 bits if yva >= xs: yva ^= 1 if yva & 1: yva = (yva - xs) & 0x1FFFF return yva & 0xFF, (yva >> 9) & 0xFF, bool(yva & 0x100) def anomie_daa(a: int, c: bool, h: bool, subtract: bool) -> tuple[int, bool]: """anomie-spc700.txt "DAA and DAS depend on C and H".""" if not subtract: if a > 0x99 or c: a = (a + 0x60) & 0xFF c = True if (a & 0x0F) > 9 or h: a = (a + 0x06) & 0xFF else: if a > 0x99 or not c: a = (a - 0x60) & 0xFF c = False if (a & 0x0F) > 9 or not h: a = (a - 0x06) & 0xFF return a, c def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--sequences", action="store_true") args = parser.parse_args() anomie = {e["opcode"]: e for e in json.loads(ANOMIE.read_text(encoding="utf-8"))} files = sorted(SST.glob("*.json")) total_cases = 0 count_agree = count_files = 0 count_disagree: list[str] = [] sequences: dict[int, Counter] = defaultdict(Counter) p_set = 0 rmw_checks: dict[str, Counter] = defaultdict(Counter) div = Counter() daa = Counter() for path in files: opcode = int(path.stem, 16) cases = json.loads(path.read_text(encoding="utf-8")) count_files += 1 lengths = Counter() for case in cases: total_cases += 1 cycles = case["cycles"] lengths[len(cycles)] += 1 sequences[opcode][kinds(cycles)] += 1 initial, final = case["initial"], case["final"] p_set += bool(initial["psw"] & 0x20) writes = [(a, i) for i, (a, d, k) in enumerate(cycles) if k == "write"] reads = [(a, i) for i, (a, d, k) in enumerate(cycles) if k == "read"] if writes: first_write_address, first_write_index = writes[0] read_first = any( a == first_write_address and i < first_write_index for a, i in reads ) rmw_checks[f"{opcode:02X}"][read_first] += 1 if opcode == 0x9E: ya = initial["y"] << 8 | initial["a"] a, y, v = anomie_div(ya, initial["x"]) div[(final["a"], final["y"], bool(final["psw"] & 0x40)) == (a, y, v)] += 1 if opcode in (0xDF, 0xBE): a, c = anomie_daa( initial["a"], bool(initial["psw"] & 1), bool(initial["psw"] & 8), opcode == 0xBE ) daa[(final["a"], bool(final["psw"] & 1)) == (a, c)] += 1 expected = sorted(anomie[opcode]["cycles"]) seen = sorted(lengths) if not expected: count_disagree.append( f"{opcode:02X} anomie ? corpus {seen} ({anomie[opcode]['mnemonic']})" ) elif seen == expected or (len(expected) == 2 and set(seen) <= set(expected)): count_agree += 1 else: count_disagree.append( f"{opcode:02X} {anomie[opcode]['mnemonic']} {anomie[opcode]['operands']}: " f"anomie {expected} corpus {dict(lengths)}" ) print(f"{count_files} files, {total_cases:,} cases") print(f"cycle count agrees with anomie on {count_agree}/{count_files} opcodes, every case") for line in count_disagree: print(" differs:", line) multi = {op: seq for op, seq in sequences.items() if len(seq) > 1} print(f"opcodes with one kind sequence on all cases: {count_files - len(multi)}") for op, seq in sorted(multi.items()): print(f" {op:02X} {anomie[op]['mnemonic']} {anomie[op]['operands']}: {dict(seq)}") all_letters = Counter() for seq in sequences.values(): for s, n in seq.items(): for ch in s: all_letters[ch] += n print("cycle kinds over all cases:", dict(all_letters)) print(f"initial PSW with P set: {p_set:,} of {total_cases:,}") print("DIV vs anomie's 9-step algorithm (A, Y, V):", dict(div)) print("DAA/DAS vs anomie's rule (A, C):", dict(daa)) claims = { "8F MOV d,#i (read first)": "8F", "C4 MOV d,A (read first)": "C4", "C5 MOV !a,A (read first)": "C5", "C6 MOV (X),A (read first)": "C6", "D4 MOV d+X,A (read first)": "D4", "D5 MOV !a+X,A (read first)": "D5", "C7 MOV [d+X],A (read first)": "C7", "D7 MOV [d]+Y,A (read first)": "D7", "FA MOV dd,ds (no read; True only when ds == dd)": "FA", "AF MOV (X)+,A (no read)": "AF", "DA MOVW d,YA (low read only)": "DA", } for label, op in claims.items(): print(f" {label}: read-before-first-write {dict(rmw_checks[op])}") if args.sequences: for op in range(256): for s, n in sequences[op].most_common(): print( f"{op:02X} {anomie[op]['mnemonic']:5} {anomie[op]['operands']:12} {len(s):2} {s} x{n}" ) return 0 if __name__ == "__main__": sys.exit(main())