#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Generate src/decode.rs and src/dispatch.rs from the reference's decode table. sh2-python's ``src/sh2_python/_decode.py`` is itself generated (its ``scripts/gen_decode.py``, from PM table A.50 and table 7.2). This script reads its ``FORMS`` at the pinned reference and writes the same rows as Rust, in the same order, and the dispatch match that stands for the reference's ``_table[op](self, op)`` (one arm per handler, in FORMS order; undefined code goes to ``illegal``). python3 scripts/gen_decode.py SH2_PYTHON # rewrite the two files python3 scripts/gen_decode.py SH2_PYTHON --check # exit 1 if either is stale Rung 0 runs ``--check``, so the Rust table cannot drift from the reference's. """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] HEADER = """// SPDX-License-Identifier: MIT //! The SH-2 decode table: every form of PM appendix A, its handler and pipeline class. //! //! Generated by ``scripts/gen_decode.py`` from sh2-python's ``_decode.py`` (itself //! generated from PM table A.50, pp. 276-283, and PM table 7.2, pp. 177-183); do not edit //! by hand. Rung 0 regenerates it and checks every one of the 65,536 encodings decodes to //! the reference's form. //! //! Each row: mnemonic and operands as PM prints them, the code pattern (``n``/``m`` //! register fields, ``d`` displacement, ``i`` immediate), its mask and match, the //! handler, the pipeline class (src/pipeline.rs), the execution states as table A.50 //! prints them, and the PM section that defines the instruction. Encodings no row //! matches are undefined: the general illegal instruction exception, or the slot //! illegal exception in a delay slot (HM 4.5.4, table 4.9). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Form { pub mnemonic: &'static str, pub operands: &'static str, pub code: &'static str, pub mask: u32, pub matches: u32, pub handler: &'static str, pub pipeline: &'static str, pub states: &'static str, pub section: &'static str, } #[allow(clippy::too_many_arguments)] const fn form( mnemonic: &'static str, operands: &'static str, code: &'static str, mask: u32, matches: u32, handler: &'static str, pipeline: &'static str, states: &'static str, section: &'static str, ) -> Form { Form { mnemonic, operands, code, mask, matches, handler, pipeline, states, section } } #[rustfmt::skip] pub static FORMS: [Form; {count}] = [ """ FOOTER = """]; /// The form of each of the 65,536 encodings, as an index into [`FORMS`], or ``None`` /// when undefined. Panics if an encoding matches two forms (the reference raises). pub fn decode_index() -> Vec> { let mut index: Vec> = vec![None; 0x10000]; for (number, form) in FORMS.iter().enumerate() { for opcode in 0..0x10000u32 { if opcode & form.mask == form.matches { if index[opcode as usize].is_some() { panic!("{opcode:04X} matches two forms"); } index[opcode as usize] = Some(number as u16); } } } index } """ DISPATCH_HEADER = """// SPDX-License-Identifier: MIT //! The dispatch: the reference's ``self._table[op](self, op)`` (cpu.py's ``_LazyTable``), //! one arm per handler in [`crate::decode::FORMS`] order. Generated by //! ``scripts/gen_decode.py``; do not edit by hand. use crate::bus::Bus; use crate::cpu::Sh7604; /// The handler number of undefined code (the reference's ``_illegal``). pub const ILLEGAL: u16 = {count}; impl Sh7604 { #[rustfmt::skip] pub(crate) fn dispatch(&mut self, handler: u16, op: u32) { match handler { """ DISPATCH_FOOTER = """ _ => self.illegal(op), } } } """ def render(forms) -> tuple[str, str]: rows = [] arms = [] for number, f in enumerate(forms): rows.append( f' form("{f.mnemonic}", "{f.operands}", "{f.code}", 0x{f.mask:04X}, 0x{f.match:04X}, ' f'"{f.handler}", "{f.pipeline}", "{f.states}", "{f.section}"),' ) arms.append(f" {number} => self.{f.handler[1:]}(op),") decode = HEADER.replace("{count}", str(len(forms))) + "\n".join(rows) + "\n" + FOOTER dispatch = DISPATCH_HEADER.replace("{count}", str(len(forms))) + "\n".join(arms) + "\n" + DISPATCH_FOOTER return decode, dispatch def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("reference", type=Path, help="the sh2-python checkout at the pin") parser.add_argument("--check", action="store_true") args = parser.parse_args() sys.path.insert(0, str(args.reference / "src")) from sh2_python._decode import FORMS handlers = [f.handler for f in FORMS] if len(set(handlers)) != len(handlers): raise SystemExit("two forms share a handler: the dispatch needs one arm per handler") decode, dispatch = render(FORMS) targets = ((ROOT / "src" / "decode.rs", decode), (ROOT / "src" / "dispatch.rs", dispatch)) if args.check: stale = [str(path.name) for path, text in targets if path.read_text() != text] if stale: print(f"stale: {', '.join(stale)} (run scripts/gen_decode.py)") return 1 print(f"decode table: {len(FORMS)} forms, the reference's, in its order") return 0 for path, text in targets: path.write_text(text) print(f"wrote {len(FORMS)} forms") return 0 if __name__ == "__main__": sys.exit(main())