#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Generate src/spc700_python/_opcodes.py from tests/anomie_opcodes.json. The table (mnemonic, operands, bytes, cycles, flags) is anomie's, as extracted by scripts/anomie_opcodes.py; the handlers are hand-written. Rung 0 checks the generated module against the JSON again. Run with ``python -I``: the input derives from fetched text. python -I scripts/anomie_opcodes.py python -I scripts/gen_opcode_table.py """ from __future__ import annotations import json from pathlib import Path ROOT = Path(__file__).resolve().parents[1] SOURCE = ROOT / "tests" / "anomie_opcodes.json" TARGET = ROOT / "src" / "spc700_python" / "_opcodes.py" HEADER = '''# SPDX-License-Identifier: MIT """The 256 SPC700 opcodes: mnemonic, operands, length, cycles and flags. Generated by scripts/gen_opcode_table.py from anomie's SPC700 Doc rev 1162 (through tests/anomie_opcodes.json). Do not edit; regenerate. The handlers are hand-written in the ``_*.py`` instruction modules. ``cycles`` is ``(n,)``, ``(not taken, taken)`` for a conditional, or ``()`` for SLEEP and STOP, which never finish. ``flags`` is anomie's ``NVPBHIZC`` column: a letter for a flag the instruction computes, ``0`` or ``1`` for one it forces, ``.`` for one it leaves alone. """ from typing import NamedTuple class Opcode(NamedTuple): """One opcode: anomie's mnemonic and operand text, bytes, cycles and flags column.""" mnemonic: str operands: str length: int cycles: tuple[int, ...] flags: str #: Every opcode, indexed by opcode byte. OPCODES: tuple[Opcode, ...] = ( ''' def main() -> None: entries = json.loads(SOURCE.read_text(encoding="utf-8")) rows = [] for entry in entries: cycles = entry["cycles"] text = "()" if not cycles else f"({cycles[0]},)" if len(cycles) == 1 else str(tuple(cycles)) rows.append( f' Opcode("{entry["mnemonic"]}", "{entry["operands"]}", {entry["bytes"]}, ' f'{text}, "{entry["flags"]}"),\n' ) footer = ')\n\n__all__ = ["OPCODES", "Opcode"]\n' TARGET.write_text(HEADER + "".join(rows) + footer, encoding="utf-8") print(f"{TARGET}: {len(rows)} opcodes") if __name__ == "__main__": main()