#!/usr/bin/env python3 """Generate src/sm83_python/_opcodes.py: mnemonic, length and category of all 512 opcodes. Sources, both pinned in scripts/pinned_repos.json and fetched by scripts/fetch_references.py: * GBCTR ``opcodes.toml`` supplies the mnemonic text and the timing category of every opcode (research documentation; the category keys ``tests/gbctr_timing.json``). * ``gbdev/gb-opcodes`` ``Opcodes.json`` supplies the byte length of every opcode. The two are cross-checked while generating, and the script stops on any disagreement: the first word of every mnemonic, the byte length implied by the operand names (``nn`` is 3 bytes, ``n`` and ``e`` are 2, a CB opcode is 2), and the set of undefined opcodes. Handlers are hand-written; this table only names them (the disassembler, the bus-schedule test and the readability test all read it). python scripts/gen_opcode_table.py # rewrites src/sm83_python/_opcodes.py python scripts/gen_opcode_table.py --check # exits 1 if the file is out of date """ from __future__ import annotations import argparse import json import re import sys import tomllib from pathlib import Path ROOT = Path(__file__).resolve().parents[1] GBCTR = ROOT / "reference" / "src" / "gb-ctr" / "opcodes.toml" GB_OPCODES = ROOT / "reference" / "src" / "gb-opcodes" / "Opcodes.json" OUT = ROOT / "src" / "sm83_python" / "_opcodes.py" #: Opcodes the SM83 has no instruction for (Pan Docs, CPU_Instruction_Set.md). HOLES = (0xD3, 0xDB, 0xDD, 0xE3, 0xE4, 0xEB, 0xEC, 0xED, 0xF4, 0xFC, 0xFD) def implied_length(mnemonic: str, prefixed: bool) -> int: """Byte length a GBCTR mnemonic implies: nn is 2 operand bytes, n or e is 1.""" if prefixed: return 2 if mnemonic == "STOP": return 2 operands = re.split(r"[ ,+]", mnemonic.partition(" ")[2]) if "nn" in operands or "(nn)" in operands: return 3 if "n" in operands or "(n)" in operands or "e" in operands: return 2 return 1 def build() -> str: gbctr = tomllib.loads(GBCTR.read_text()) lengths = json.loads(GB_OPCODES.read_text()) problems: list[str] = [] tables = {} for name, key, source, prefixed in ( ("OPCODES", "opcodes", "unprefixed", False), ("CB_OPCODES", "cb_opcodes", "cbprefixed", True), ): rows = [] entries = gbctr[key] if len(entries) != 256: problems.append(f"{key}: {len(entries)} entries, expected 256") for code, entry in enumerate(entries): reference = lengths[source][f"0x{code:02X}"] mnemonic = entry["mnemonic"] undefined = entry["category"] == "undefined" if undefined != (not prefixed and code in HOLES): problems.append(f"{key} 0x{code:02X}: undefined mismatch ({mnemonic})") if undefined: mnemonic = f"DB ${code:02X}" elif mnemonic.split()[0] != reference["mnemonic"].split("_")[0] and ( reference["mnemonic"] != "PREFIX" or code != 0xCB ): problems.append(f"{key} 0x{code:02X}: {mnemonic!r} vs {reference['mnemonic']!r}") length = reference["bytes"] if not undefined and code != 0xCB and implied_length(mnemonic, prefixed) != length: problems.append(f"{key} 0x{code:02X}: {mnemonic!r} implies a different length") rows.append((mnemonic, length, entry["category"])) tables[name] = rows if problems: sys.exit("\n".join(problems)) lines = [ '"""The 512 SM83 opcodes: mnemonic, byte length and GBCTR timing category.', "", "Generated by scripts/gen_opcode_table.py from GBCTR's opcodes.toml (mnemonics and", "categories) and gbdev/gb-opcodes' Opcodes.json (lengths), cross-checked. Do not edit;", "regenerate. The handlers are hand-written in the ``_*.py`` instruction modules.", '"""', "", "from typing import NamedTuple", "", "", "class Opcode(NamedTuple):", ' """One opcode: GBCTR\'s mnemonic text, length in bytes, and timing category."""', "", " mnemonic: str", " length: int", " category: str", "", "", ] for name, doc in ( ("OPCODES", "Unprefixed opcodes, indexed by opcode byte; holes are ``DB $XX``."), ("CB_OPCODES", "Opcodes after the $CB prefix, indexed by the second byte."), ): lines.append(f"#: {doc}") lines.append(f"{name}: tuple[Opcode, ...] = (") lines.extend( f" Opcode({json.dumps(m)}, {n}, {json.dumps(c)})," for m, n, c in tables[name] ) lines += [")", "", ""] lines.append('__all__ = ["CB_OPCODES", "OPCODES", "Opcode"]') return "\n".join(lines) + "\n" def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--check", action="store_true", help="exit 1 if the file is stale") text = build() if parser.parse_args().check: sys.exit(0 if OUT.read_text() == text else 1) OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(text) print(f"wrote {OUT.relative_to(ROOT)}") if __name__ == "__main__": main()