# SPDX-License-Identifier: MIT """Rung 0, third part: the executed words' disassembly against Mesen2's trace text. Mesen2's Cx4 disassembler uses its own syntax (BRA/BEQ/BCS for the jumps, SMUL, STOP, ``RAM:n`` byte lanes, ``(A << 8)``...). Each distinct (word, text) pair in the recordings is rewritten into this core's syntax (byuu's mnemonics) and must equal ``disasm.text(word)``. The recordings are ``tests/mesen_traces/*/cx4.trace.gz`` (``scripts/record_mesen_windows.py``); the test skips without them. """ from __future__ import annotations import re from pathlib import Path import pytest from hg51b_python.disasm import text from hg51b_python.replay import read_trace TRACES = Path(__file__).parent / "mesen_traces" JUMPS = {"BRA": "JMP", "BEQ": "JMP EQ,", "BCS": "JMP GE,", "BMI": "JMP MI,", "BVS": "JMP VS,"} CALLS = {"JSR": "JSR", "JEQ": "JSR EQ,", "JCS": "JSR GE,", "JMI": "JSR MI,", "JVS": "JSR VS,"} NAMES = {"MULTH": "MH", "MULTL": "ML", "RDROM": "BUS", "RDRAM": "BUSRAM"} def mesen_to_ours(mesen: str) -> str: """Rewrite one Mesen2 disassembly into this core's syntax.""" s = re.sub(r"\s*,\s*", ",", mesen.strip()) s = re.sub(r"\(A << (\d+)\)", r"A<<\1", s) head, _, rest = s.partition(" ") if head in JUMPS or head in CALLS: new = (JUMPS | CALLS)[head] return f"{new}{'' if new.endswith(',') else ' '}{rest}" if head == "STOP": return "HALT" if head.startswith("SKIP"): return f"SKIP {head[4]}={1 if head[5] == 'S' else 0}" if head == "SMUL": operand = rest.split(",", 1)[1] return f"MUL {NAMES.get(operand, operand)}" if head == "RDROM": return "RDROM A" if rest == "(a)" else f"RDROM #${int(rest[3:-1], 16):03X}" if head == "RDRAM": lane, source = re.match(r"RAM:(\d),(.*)", rest).groups() return f"RDRAM {lane},{source}" if head == "WRRAM": target, lane = re.match(r"(.*),RAM:(\d)", rest).groups() return f"WRRAM {lane},{target}" if head == "???": return "NOP" operands = [NAMES.get(part, part) for part in rest.split(",")] if rest else [] return f"{head} {','.join(operands)}".strip() def pairs() -> dict[int, str]: found: dict[int, str] = {} for path in sorted(TRACES.glob("*/cx4.trace.gz")): for line in read_trace(path): found.setdefault(line.word, line.text) return found def test_executed_words_match_mesen2_disassembly() -> None: found = pairs() if not found: pytest.skip("no recordings: python -I scripts/record_mesen_windows.py") wrong = { f"{word:04X}": (mine, mesen) for word, mesen in found.items() if (mine := text(word)) != mesen_to_ours(mesen) } assert not wrong, wrong assert len(found) > 200