# SPDX-License-Identifier: MIT """Side-effect-free SPC700 disassembly, driven by the generated opcode table. Text is anomie's syntax with the operands filled in: direct page ``$12``, immediate ``#$12``, absolute ``!$1234``, indexed ``$12+X``, ``!$1234+Y``, ``[$12+X]``, ``[$12]+Y``, ``[!$1234+X]``, bits ``$12.3`` and ``$1234.5`` (with ``/`` for the complemented forms), and a relative operand as its target address. Operand bytes follow the opcode source first (``dd, ds`` is stored ``ds dd``, ``d, #i`` is stored ``i d``), except BBS, BBC, CBNE and DBNZ d, which store ``d`` then ``r``. """ from __future__ import annotations import re from collections.abc import Callable from dataclasses import dataclass from spc700_python._opcodes import OPCODES ByteReader = Callable[[int], int] _TOKEN = re.compile(r"!a|/?m\.b|dd|ds|#i|\bd\b|\br\b|\bu\b") @dataclass(frozen=True, slots=True) class Instruction: """One decoded instruction: where it is, its bytes, and its text.""" address: int data: bytes mnemonic: str operands: tuple[str, ...] = () def __post_init__(self) -> None: if type(self.address) is not int or not 0 <= self.address <= 0xFFFF: raise ValueError("address must be an integer in range 0x0000..0xFFFF") if type(self.data) is not bytes or not 1 <= len(self.data) <= 3: raise ValueError("data must be 1 to 3 bytes") @property def length(self) -> int: return len(self.data) @property def text(self) -> str: """The instruction as one line, e.g. ``MOV A, !$1234+X``.""" return f"{self.mnemonic} {', '.join(self.operands)}" if self.operands else self.mnemonic def _signed(byte: int) -> int: return byte - 0x100 if byte & 0x80 else byte def disassemble(read: ByteReader, address: int) -> Instruction: """Decode the instruction at ``address``, reading bytes through ``read`` (no bus cycles: pass the host's memory, not its bus).""" opcode = read(address) & 0xFF entry = OPCODES[opcode] data = bytes(read((address + i) & 0xFFFF) & 0xFF for i in range(entry.length)) return disassemble_bytes(data, address) def disassemble_bytes(data: bytes, address: int = 0) -> Instruction: """Decode the one instruction ``data`` starts with.""" entry = OPCODES[data[0]] if len(data) < entry.length: raise ValueError(f"{entry.mnemonic} needs {entry.length} bytes") data = bytes(data[: entry.length]) fill = _Filler(data, address) operands = tuple(_TOKEN.sub(fill, operand) for operand in entry.operands.split(", ") if operand) return Instruction(address, data, entry.mnemonic, operands) class _Filler: """Replaces operand tokens with values, taking the bytes in encoded order.""" def __init__(self, data: bytes, address: int) -> None: self.data = data self.address = address tokens = _TOKEN.findall(OPCODES[data[0]].operands) # Two-byte-operand forms are stored source first: the second token owns the first byte. self.swapped = tokens in (["dd", "ds"], ["d", "#i"]) self.index = 2 if self.swapped else 1 def __call__(self, match: re.Match[str]) -> str: token = match[0] data = self.data if token == "!a": return f"!${data[2] << 8 | data[1]:04X}" if token.endswith("m.b"): word = data[2] << 8 | data[1] prefix = "/" if token.startswith("/") else "" return f"{prefix}${word & 0x1FFF:04X}.{word >> 13}" byte = data[self.index] self.index += -1 if self.swapped else 1 if token == "#i": return f"#${byte:02X}" if token == "r": return f"${(self.address + len(data) + _signed(byte)) & 0xFFFF:04X}" return f"${byte:02X}" __all__ = ["ByteReader", "Instruction", "disassemble", "disassemble_bytes"]