"""Read the ``error.log`` that ``scripts/mame_trace.py`` makes (docs/mame-oracle.md). Two line kinds matter, interleaved in execution order: - an instruction line, logged before the instruction runs: ``PC AF BC DE HL IX IY SP AF' I R totalcycles beamy beamx`` (hex, then decimal); - an I/O line: ``IW port value totalcycles`` or ``IR port value totalcycles``, where ``totalcycles`` is the *instruction's* start cycle (MAME stamps it that way). Every other line (MAME's own log messages) is skipped. """ from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path @dataclass(frozen=True, slots=True) class Instruction: pc: int af: int bc: int de: int hl: int ix: int iy: int sp: int af2: int i: int r: int cycles: int beam_y: int beam_x: int @dataclass(frozen=True, slots=True) class PortAccess: write: bool port: int value: int cycles: int def read_log(path: Path) -> Iterator[Instruction | PortAccess]: """Yield the log's instructions and port accesses in order.""" with path.open("rb") as log: for raw in log: fields = raw.split() if len(fields) == 4 and fields[0] in (b"IW", b"IR"): try: yield PortAccess( fields[0] == b"IW", int(fields[1], 16), int(fields[2], 16), int(fields[3]) ) except ValueError: continue elif len(fields) == 14: try: hexes = [int(field, 16) for field in fields[:11]] decimals = [int(field) for field in fields[11:]] except ValueError: continue yield Instruction(*hexes, *decimals)