#!/usr/bin/env python3 """Re-derive the MCS-48 opcode table from MAME and diff it against the docs. docs/start-here.md carries two tables transcribed from MAME 0.285: a 16x16 opcode map and a per-instruction table with byte and cycle counts. A transcribed table rots silently. This script re-derives both from the pinned sources that scripts/fetch_sources.py leaves in vendor/mame/ and reports every disagreement, so the documents cannot drift from their source without a failing check. What it derives, and from where: mnemonic mcs48dsm.cpp the disassembler's switch, taking the MCS-48 arm of every `m_upi41` / `m_i802x` conditional cycles mcs48.cpp the `burn_cycles(n)` call in each OPHANDLER body bytes mcs48.cpp 2 if the handler reaches `argument_fetch()`, directly or through execute_jcc/execute_call defined mcs48.cpp the 256-entry s_mcs48_opcodes dispatch table; anything mapped to `illegal` is undefined python scripts/check_instruction_table.py # check the docs python scripts/check_instruction_table.py --dump # print the table Exit status is 0 when the documents agree with MAME. """ from __future__ import annotations import argparse import json import pathlib import re import sys ROOT = pathlib.Path(__file__).resolve().parent.parent VENDOR = ROOT / "vendor" / "mame" DOC = ROOT / "docs" / "start-here.md" # -------------------------------------------------------------------------- # Derive the table from MAME # -------------------------------------------------------------------------- def handler_bodies(src: str) -> dict[str, str]: """Map each OPHANDLER name to its brace-balanced body.""" bodies: dict[str, str] = {} for match in re.finditer(r"OPHANDLER\(\s*(\w+)\s*\)\s*\{", src): name = match.group(1) start = src.index("{", match.end(1)) depth, index = 0, start while True: if src[index] == "{": depth += 1 elif src[index] == "}": depth -= 1 if depth == 0: break index += 1 bodies[name] = src[start:index + 1] return bodies def dispatch_table(src: str, symbol: str) -> list[str]: match = re.search(re.escape(symbol) + r"\[256\]\s*=\s*\{(.*?)\n\};", src, re.S) if match is None: raise SystemExit(f"could not find {symbol} in mcs48.cpp") body = re.sub(r"//[^\n]*", "", match.group(1)) names = re.findall(r"OP\((\w+)\)", body) if len(names) != 256: raise SystemExit(f"{symbol} has {len(names)} entries, expected 256") return names def cycles_and_bytes(bodies: dict[str, str], name: str) -> tuple[int, int]: body = bodies[name] match = re.search(r"burn_cycles\((\d+)\)", body) if match is None: raise SystemExit(f"no burn_cycles() in OPHANDLER({name})") cycles = int(match.group(1)) # A two-byte instruction is one that consumes an operand byte. Handlers # either call argument_fetch() themselves or go through execute_jcc (which # fetches the branch target) or execute_call (which fetches the low byte). two = ("argument_fetch" in body or "execute_jcc" in body or "execute_call" in body) return cycles, 2 if two else 1 def disassembler_mnemonics(src: str) -> dict[int, str]: """Take the plain-MCS-48 arm of every case in mcs48dsm.cpp.""" body = src[src.index("switch (opcodes.r8(cpc++))"):] parts = re.split(r"\n\t\tcase 0x([0-9a-f]{2}):", body) out: dict[int, str] = {} for index in range(1, len(parts), 2): opcode = int(parts[index], 16) block = parts[index + 1] literals = re.findall(r'stream_format\(stream, "([^"]+)"', block) if not literals: continue if "m_upi41" in block or "m_i802x" in block: # three shapes appear; in each, pick the branch that is neither # the 8021/8022 nor the UPI-41 one for pattern in (r"if \(m_i802x\)[^;]+;\s*else if \(!m_upi41\)\s*" r'util::stream_format\(stream, "([^"]+)"', r"if \(!m_i802x\)\s*\{?\s*" r'util::stream_format\(stream, "([^"]+)"', r"if \(!m_upi41\)\s*\{?\s*" r'util::stream_format\(stream, "([^"]+)"'): found = re.search(pattern, block) if found: out[opcode] = found.group(1) break else: out[opcode] = literals[0] else: out[opcode] = literals[0] return out def normalise(text: str) -> str: """Reduce a disassembly template or a doc cell to a comparable form.""" text = re.sub(r"\$[0-7]?%0[23]X", "ADDR", text) text = text.replace("#$%02X", "#D").replace("%02X", "D") text = text.upper().replace("#DATA", "#D").replace("#D", "#D") text = re.sub(r"\bADDR\b", "", text) text = re.sub(r"\bP[0-7]\b(?=\s*$)", lambda m: m.group(0), text) return re.sub(r"[\s,]+", " ", text).strip() def derive() -> dict[int, dict]: cpp = (VENDOR / "mcs48.cpp").read_text(encoding="utf-8", errors="replace") dsm = (VENDOR / "mcs48dsm.cpp").read_text(encoding="utf-8", errors="replace") bodies = handler_bodies(cpp) mcs48 = dispatch_table(cpp, "mcs48_cpu_device::s_mcs48_opcodes") upi41 = dispatch_table(cpp, "mcs48_cpu_device::s_upi41_opcodes") mnemonics = disassembler_mnemonics(dsm) table = {} for opcode in range(256): handler = mcs48[opcode] defined = handler != "illegal" cycles, size = cycles_and_bytes(bodies, handler) table[opcode] = { "handler": handler, "upi_handler": upi41[opcode], "defined": defined, "cycles": cycles, "bytes": size, "mnemonic": mnemonics.get(opcode, ""), } return table # -------------------------------------------------------------------------- # Parse the documents # -------------------------------------------------------------------------- OPCODE_SPECS = [ (re.compile(r"^([0-9A-F]{2})\+r$"), lambda m: [int(m[1], 16) + i for i in range(8)]), (re.compile(r"^([0-9A-F]{2})\+32N$"), lambda m: [int(m[1], 16) + 32 * i for i in range(8)]), (re.compile(r"^([0-9A-F]{2})\+32b$"), lambda m: [int(m[1], 16) + 32 * i for i in range(8)]), (re.compile(r"^([0-9A-F]{2})-([0-9A-F]{2})$"), lambda m: list(range(int(m[1], 16), int(m[2], 16) + 1))), ] def parse_opcode_spec(spec: str) -> list[int]: spec = spec.strip() for pattern, expand in OPCODE_SPECS: match = pattern.match(spec) if match: return expand(match) if "," in spec: return [int(part.strip(), 16) for part in spec.split(",")] return [int(spec, 16)] def doc_rows(text: str) -> list[tuple[str, str, int, int]]: """Rows of the per-instruction table: (opcodes, instruction, bytes, cycles).""" section = text.split("### Per-instruction table", 1)[1] section = section.split("\nTotals:", 1)[0] rows = [] for line in section.splitlines(): if not line.startswith("|"): continue cells = [cell.strip() for cell in line.strip("|").split("|")] if len(cells) < 5 or cells[0] in ("Opcodes", "---"): continue if set(cells[0]) <= set("- "): continue rows.append((cells[0], cells[1], int(cells[2]), int(cells[3]))) return rows def doc_map(text: str) -> dict[int, str]: """The 16x16 opcode map.""" section = text.split("### Opcode map", 1)[1].split("### Per-instruction", 1)[0] out = {} for line in section.splitlines(): match = re.match(r"\|\s*\*\*([0-9A-F])x\*\*\s*\|(.*)\|\s*$", line) if not match: continue high = int(match.group(1), 16) cells = [cell.strip() for cell in match.group(2).split("|")] if len(cells) != 16: raise SystemExit(f"row {high:X}x has {len(cells)} cells, expected 16") for low, cell in enumerate(cells): out[high * 16 + low] = cell return out # -------------------------------------------------------------------------- def check() -> int: table = derive() text = DOC.read_text(encoding="utf-8") problems: list[str] = [] # 1. the opcode map: defined-ness and mnemonic mapping = doc_map(text) if len(mapping) != 256: problems.append(f"opcode map has {len(mapping)} cells, expected 256") for opcode, cell in sorted(mapping.items()): entry = table[opcode] if cell == "—": if entry["defined"]: problems.append( f"map {opcode:02X}: documented undefined, MAME has " f"{entry['mnemonic'] or entry['handler']}") continue if not entry["defined"]: problems.append(f"map {opcode:02X}: documented {cell!r}, MAME has illegal") continue want, got = normalise(entry["mnemonic"]), normalise(cell) # the map abbreviates: "#data" as "#d", and drops jump targets got = got.replace("#D", "#D") if want != got and not want.startswith(got.split()[0]): problems.append(f"map {opcode:02X}: doc {cell!r} vs MAME {entry['mnemonic']!r}") # 2. the per-instruction table: coverage, bytes, cycles covered: dict[int, str] = {} for spec, instruction, size, cycles in doc_rows(text): for opcode in parse_opcode_spec(spec): entry = table[opcode] if opcode in covered: problems.append(f"{opcode:02X} listed twice: {covered[opcode]!r} and {instruction!r}") covered[opcode] = instruction if not entry["defined"]: problems.append(f"{opcode:02X} ({instruction}): MAME says illegal") continue if entry["bytes"] != size: problems.append( f"{opcode:02X} ({instruction}): doc {size} bytes, MAME {entry['bytes']}") if entry["cycles"] != cycles: problems.append( f"{opcode:02X} ({instruction}): doc {cycles} cycles, MAME {entry['cycles']}") defined = {op for op, entry in table.items() if entry["defined"]} missing = sorted(defined - set(covered)) extra = sorted(set(covered) - defined) if missing: problems.append("not in the per-instruction table: " + " ".join(f"{op:02X}" for op in missing)) if extra: problems.append("in the table but undefined in MAME: " + " ".join(f"{op:02X}" for op in extra)) # 3. the totals sentence counts = { "defined": len(defined), "undefined": 256 - len(defined), "one_cycle": sum(1 for e in table.values() if e["cycles"] == 1), "two_cycle": sum(1 for e in table.values() if e["cycles"] == 2), "one_byte": sum(1 for e in table.values() if e["bytes"] == 1), "two_byte": sum(1 for e in table.values() if e["bytes"] == 2), } expected = (f"Totals: {counts['defined']} defined opcodes, " f"{counts['undefined']} undefined; {counts['one_cycle']} one-cycle and " f"{counts['two_cycle']} two-cycle\nopcodes; {counts['one_byte']} one-byte " f"and {counts['two_byte']} two-byte.") if expected not in text: problems.append("the Totals sentence does not match MAME; it should read:\n " + expected.replace("\n", " ")) # 4. the UPI-41 difference table upi_diff = {op: (e["handler"], e["upi_handler"]) for op, e in table.items() if e["handler"] != e["upi_handler"]} section = text.split("## The UPI-41/42 difference", 1)[1] listed = {int(m, 16) for m in re.findall(r"^\| ([0-9A-F]{2}) \|", section, re.M)} if listed != set(upi_diff): problems.append( "UPI table lists " + " ".join(f"{o:02X}" for o in sorted(listed)) + " but MAME differs at " + " ".join(f"{o:02X}" for o in sorted(upi_diff))) for problem in problems: print(problem) print(f"\n{len(problems)} disagreement(s) between docs/start-here.md and " f"MAME 0.285.") return 1 if problems else 0 def dump() -> int: table = derive() print(json.dumps({f"{op:02X}": entry for op, entry in derive().items()}, indent=1)) return 0 def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dump", action="store_true", help="print the derived table as JSON") args = parser.parse_args() if not (VENDOR / "mcs48.cpp").exists(): print("vendor/mame is empty; run scripts/fetch_sources.py first", file=sys.stderr) return 2 return dump() if args.dump else check() if __name__ == "__main__": raise SystemExit(main())