#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Score the NBA referee against every SingleStepTests ARM7TDMI file. For each file it runs ``$EMU_TOOLS_GPL/tools/nanoboyadvance/build/arm7tdmi-sst/nba_sst`` and prints the cases where NBA's final state agrees, where its bus sequence agrees (kind, size, address, write data, N/S and code bits, in order; internal cycles are not in the corpus and are left out of the comparison), and the histogram of internal cycles NBA made per instruction, which the corpus cannot show. ``--classify`` sorts every disagreement into the classes docs/validation.md names (C2, C3, C4 in docs/undocumented-behavior.md) and prints the counts; a disagreement that fits none is printed in full. python scripts/referee_sst.py # table to stdout python scripts/referee_sst.py --json out.json # also keep the numbers python scripts/referee_sst.py --classify # why the rest disagree python scripts/referee_sst.py --dump arm_swp 5 # first 5 disagreements of one file """ from __future__ import annotations import argparse import json import os import re import subprocess import sys from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] CORPUS = ROOT / "reference" / "src" / "SingleStepTests-ARM7TDMI" / "v1" #: NBA's ARM7TDMI referee, built by emu-tools-gpl's nanoboyadvance tool (since 2026-11-25; #: reference/build/nba_sst before), at its documented path under EMU_TOOLS_GPL. REFEREE = Path(os.environ.get("EMU_TOOLS_GPL", "$EMU_TOOLS_GPL")) / ( "tools/nanoboyadvance/build/arm7tdmi-sst/nba_sst" ) def run(path: Path, dump: int = 0) -> dict: command = [str(REFEREE), str(path)] if dump: command += ["--dump", str(dump)] result = subprocess.run(command, capture_output=True, text=True, check=True) if dump: sys.stderr.write(result.stderr) return json.loads(result.stdout) def same_but_low_bits(nba: list[str], sst: list[str]) -> bool: """Whether two printed bus sequences differ only in fetch-address bits 1:0.""" if len(nba) != len(sst): return False for a, b in zip(nba, sst, strict=True): (kind_a, addr_a), (kind_b, addr_b) = a.split("@"), b.split("@") if kind_a != kind_b or int(addr_a, 16) & ~3 != int(addr_b, 16) & ~3: return False return True def classify(path: Path) -> Counter: """Count one file's disagreements by class; print any that fit no class.""" command = [str(REFEREE), str(path), "--dump", "1000000"] lines = subprocess.run(command, capture_output=True, text=True, check=True).stderr lines = lines.splitlines() counts: Counter = Counter() for head, nba_line, sst_line in zip(lines[0::3], lines[1::3], lines[2::3], strict=False): fields = set(re.findall(r" (\w+) nba=", head)) nba = [t for t in nba_line.split()[1:] if t != "I"] sst = sst_line.split()[1:] extra_refill = len(sst) == len(nba) + 2 and sst[: len(nba)] == nba if fields <= {"pipe0", "pipe1"} and same_but_low_bits(nba, sst): kind = "C3 refill fetch address bits 1:0" elif extra_refill and any(t.startswith("W") for t in nba): kind = "C2 store write-back to R15 refills" elif extra_refill: kind = "C2 load write-back to R15 refills" elif any( a.startswith("RN8") and b.startswith("RN16") for a, b in zip(nba, sst, strict=False) ): kind = "C4 LDRSH odd address: width 8 vs 16" else: kind = "unclassified" print(f"{path.name}: {head}\n{nba_line}\n{sst_line}") counts[kind] += 1 return counts def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--json", type=Path, help="write the numbers here too") parser.add_argument("--dump", nargs=2, metavar=("FILE", "N"), help="show disagreements") parser.add_argument("--classify", action="store_true", help="count disagreements by class") args = parser.parse_args() if not REFEREE.exists(): print(f"no referee at {REFEREE}: set EMU_TOOLS_GPL, then run scripts/build_referees.py", file=sys.stderr) # fmt: skip return 3 if args.dump: run(CORPUS / f"{args.dump[0]}.json.bin", int(args.dump[1])) return 0 if args.classify: total_counts: Counter = Counter() for path in sorted(CORPUS.glob("*.json.bin")): counts = classify(path) if counts: print(f"{path.name.removesuffix('.json.bin'):32} {dict(counts)}") total_counts += counts for kind, count in sorted(total_counts.items()): print(f"{count:7,} {kind}") print(f"{sum(total_counts.values()):7,} in all") return 0 results = {} total = agree = 0 for path in sorted(CORPUS.glob("*.json.bin")): name = path.name.removesuffix(".json.bin") r = results[name] = run(path) total += r["cases"] agree += r["both"] bad = sorted(r["fields"].items(), key=lambda item: -item[1])[:3] print( f"{name:32} {r['both']:6}/{r['cases']} state={r['state']:6} bus={r['bus']:6} " f"I={r['idle_cycles']} worst={dict(bad)}" ) print(f"all: {agree:,}/{total:,} cases agree on state and bus ({100 * agree / total:.2f}%)") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())