#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write src/dispatch.rs from the reference's opcode map (w65c02_python._dispatch.OPCODES). $REFERENCE_PYTHON scripts/gen_dispatch.py The enums and the 256-row table are generated; the rest of the module (its header, ``opcodes_for``, ``build_table`` and the dispatch) is the text of ``scripts/dispatch_header.rs.in`` and ``scripts/dispatch_footer.rs.in``. Run it with the reference's interpreter (it imports ``w65c02_python``). """ from __future__ import annotations from pathlib import Path from w65c02_python._dispatch import OPCODES ROOT = Path(__file__).resolve().parents[1] def camel(name: str) -> str: return "".join(part.capitalize() for part in name.split("_")) def main() -> int: handlers = sorted({row[0] for row in OPCODES.values()} | {"nop_one_cycle"}) modes = sorted({row[1] for row in OPCODES.values() if row[1]}) forms: list[str] = [] for row in OPCODES.values(): if row[3] not in forms: forms.append(row[3]) table = [] for opcode in range(256): handler, mode, mnemonic, form, cycles = OPCODES[opcode] m = "Implied" if mode is None else camel(mode) table.append( f" /* {opcode:02X} */ (Op::{camel(handler)}, Mode::{m}, " f'"{mnemonic}", Form::{camel(form)}, {cycles}),' ) header = (ROOT / "scripts" / "dispatch_header.rs.in").read_text() footer = (ROOT / "scripts" / "dispatch_footer.rs.in").read_text() text = ( header.replace("@HANDLERS@", "\n".join(f" {camel(h)}," for h in handlers)) .replace("@MODES@", "\n".join(f" {camel(m)}," for m in modes)) .replace("@FORMS@", "\n".join(f" {camel(f)}," for f in sorted(forms))) .replace("@TABLE@", "\n".join(table)) ) (ROOT / "src" / "dispatch.rs").write_text(text + footer) print(f"wrote src/dispatch.rs: {len(handlers)} handlers, {len(modes)} modes, 256 opcodes") return 0 if __name__ == "__main__": raise SystemExit(main())