#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Write src/machine.rs from the reference's src/sega32x_python/machine.py. The quirk records are data with long citations; this carries every field of every record into Rust word for word, in declaration order, with the class's section comments, so the two can be read side by side and a change upstream regenerates the Rust exactly. The value of each record is typed in Rust (README, "What Rust forced": a dict becomes a struct with the same keys, a tuple a slice, bytes an array). PYTHONPATH=$SEGA32X_PYTHON/src python3 scripts/gen_machine.py $SEGA32X_PYTHON > src/machine.rs Run with any Python 3.11 (it imports only the reference's machine.py, which needs nothing else). Stdlib only. """ from __future__ import annotations import ast import sys from pathlib import Path from sega32x_python.machine import _SH2_VARIANT, MACHINES, Quirk, Quirks #: Rust types of the dict-valued records: (struct name, [(key, rust type)]). STRUCTS = { "sh2_waits": "Sh2Waits", "sh2_framebuffer_fifo": "FramebufferFifo", "m68k_waits": "M68kWaits", "sh2_bus_arbitration": "BusArbitration", "hblank_timing": "HblankTiming", "composite_alignment": "CompositeAlignment", } def rstr(text: str) -> str: """A Rust raw string literal holding ``text`` exactly.""" hashes = "#" while f'"{hashes}' in text: hashes += "#" return f'r{hashes}"{text}"{hashes}' def rust_type(name: str, value: object) -> str: if name in STRUCTS: return STRUCTS[name] if name == "cartridge_boards": return "&'static [(&'static str, &'static str)]" if isinstance(value, bool): return "bool" if isinstance(value, int): return "i64" if isinstance(value, float): return "f64" if isinstance(value, bytes): return f"[u8; {len(value)}]" if isinstance(value, str): return "&'static str" if isinstance(value, tuple): return "&'static [u32]" raise TypeError(f"{name}: {type(value)}") def rust_value(name: str, value: object) -> str: if name in STRUCTS: fields = ", ".join(f"{key.lower()}: {v}" for key, v in value.items()) # type: ignore[union-attr] return f"{STRUCTS[name]} {{ {fields} }}" if name == "cartridge_boards": items = ", ".join(f'("{k}", "{v}")' for k, v in value.items()) # type: ignore[union-attr] return f"&[{items}]" if isinstance(value, bool): return "true" if value else "false" if isinstance(value, float): return repr(value) if isinstance(value, int): return str(value) if isinstance(value, bytes): return "*b" + '"' + value.decode("ascii") + '"' if isinstance(value, str): return rstr(value) if isinstance(value, tuple): return "&[" + ", ".join(str(v) for v in value) + "]" raise TypeError(name) def quirk_literal(name: str, q: Quirk, indent: str) -> str: lines = [f"{indent}Quirk {{", f"{indent} value: {rust_value(name, q.value)},"] for field in ("source", "tier"): lines.append(f"{indent} {field}: {rstr(getattr(q, field)) if field == 'source' else tier(q.tier)},") lines.append(f"{indent} milestone: {q.milestone},") for field in ("documents", "hardware", "unresolved"): lines.append(f"{indent} {field}: {rstr(getattr(q, field))},") lines.append(f"{indent}}}") return "\n".join(lines) def tier(value: str) -> str: return { "hardware-corrected": "HARDWARE_CORRECTED", "specification": "SPECIFICATION", "research": "RESEARCH", "emulator-derived": "EMULATOR", "assumption": "ASSUMPTION", }[value] def doc(text: str, indent: str = "") -> str: return "\n".join(f"{indent}///{(' ' + line) if line else ''}" for line in text.strip().splitlines()) def main() -> int: source_path = Path(sys.argv[1]) / "src/sega32x_python/machine.py" source = source_path.read_text() tree = ast.parse(source) lines = source.splitlines() module_doc = ast.get_docstring(tree) or "" quirks_class = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "Quirks") quirk_class = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "Quirk") machine_class = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "Machine") q = Quirks() out: list[str] = [] w = out.append w("// SPDX-License-Identifier: MIT") w("// Generated by scripts/gen_machine.py from sega32x-python's src/sega32x_python/machine.py:") w("// edit the reference and regenerate, never this file.") w("\n".join(f"//!{(' ' + line) if line else ''}" for line in module_doc.splitlines())) w("//!") w("//! What Rust forced: each record's value is typed (a dict is a struct with the same") w("//! keys, a tuple a slice, bytes an array); `Quirks::default()` is the dataclass's") w("//! defaults; `table` names each record's value only by its field name and source.") w("") w("/// Oracle tiers (docs/validation.md), strongest first.") w('pub const HARDWARE_CORRECTED: &str = "hardware-corrected";') w('pub const SPECIFICATION: &str = "specification";') w('pub const RESEARCH: &str = "research";') w('pub const EMULATOR: &str = "emulator-derived";') w("/// The board's own choice where no source decides: the open items of") w("/// docs/undocumented-behavior.md.") w('pub const ASSUMPTION: &str = "assumption";') w("") w(doc(ast.get_docstring(quirk_class) or "")) w("#[derive(Clone, Copy, Debug, PartialEq)]") w("pub struct Quirk {") w(" pub value: T,") w(" pub source: &'static str,") w(" pub tier: &'static str,") w(" pub milestone: u32,") w(" pub documents: &'static str,") w(" pub hardware: &'static str,") w(" pub unresolved: &'static str,") w("}") w("") # The dict-valued records' structs. for name, struct in STRUCTS.items(): value = getattr(q, name).value w(f"/// The value of `Quirks::{name}` (a dict in the reference, with these keys).") w("#[derive(Clone, Copy, Debug, PartialEq, Eq)]") w(f"pub struct {struct} {{") for key in value: w(f" pub {key.lower()}: i64,") w("}") w("") w(doc(ast.get_docstring(quirks_class) or "")) w("#[derive(Clone, Copy, Debug, PartialEq)]") w("pub struct Quirks {") fields = [n for n in quirks_class.body if isinstance(n, ast.AnnAssign)] previous_end = quirks_class.body[0].end_lineno if isinstance(quirks_class.body[0], ast.Expr) else quirks_class.lineno for node in fields: name = node.target.id # type: ignore[attr-defined] for line in lines[previous_end : node.lineno - 1]: if line.strip().startswith("#"): w(" //" + line.strip()[1:]) previous_end = node.end_lineno or node.lineno w(f" pub {name}: Quirk<{rust_type(name, getattr(q, name).value)}>,") w("}") w("") w("impl Default for Quirks {") w(" fn default() -> Self {") w(" Quirks {") previous_end = quirks_class.body[0].end_lineno if isinstance(quirks_class.body[0], ast.Expr) else quirks_class.lineno for node in fields: name = node.target.id # type: ignore[attr-defined] for line in lines[previous_end : node.lineno - 1]: if line.strip().startswith("#"): w(" //" + line.strip()[1:]) previous_end = node.end_lineno or node.lineno w(f" {name}: " + quirk_literal(name, getattr(q, name), " ").lstrip() + ",") w(" }") w(" }") w("}") w("") w("impl Quirks {") w(" /// Every quirk by field name, in declaration order, with its source and tier.") w(" pub fn table(&self) -> Vec<(&'static str, &'static str, &'static str)> {") w(" vec![") for node in fields: name = node.target.id # type: ignore[attr-defined] w(f' ("{name}", self.{name}.source, self.{name}.tier),') w(" ]") w(" }") w("}") w("") w(doc(ast.get_docstring(machine_class) or "")) w("#[derive(Clone, Copy, Debug, PartialEq)]") w("pub struct Machine {") w(" pub name: &'static str,") w(" pub description: &'static str,") w(" pub revision: &'static str,") w(" pub sh2_variant: Quirk<&'static str>,") w(" pub boot_roms: &'static str,") w(" pub quirks: Quirks,") w("}") w("") w("pub const SH2_VARIANT: Quirk<&'static str> = " + quirk_literal("sh2_variant", _SH2_VARIANT, "").lstrip() + ";") w("") w("/// The models (the reference's `MACHINES`).") w("pub fn machines() -> Vec {") w(" vec![") for key, m in MACHINES.items(): assert key == m.name and m.boot_roms == "user" and m.quirks == Quirks() w(" Machine {") w(f' name: "{m.name}",') w(f" description: {rstr(m.description)},") w(f" revision: {rstr(m.revision)},") w(" sh2_variant: SH2_VARIANT,") w(' boot_roms: "user",') w(" quirks: Quirks::default(),") w(" },") w(" ]") w("}") w("") w("/// The model named `name` (`MACHINES[name]`).") w("pub fn machine(name: &str) -> Option {") w(" machines().into_iter().find(|m| m.name == name)") w("}") print("\n".join(out)) return 0 if __name__ == "__main__": sys.exit(main())