"""Side-effect-free structured disassembly for the 65C02, per part. The decode table is built from the opcode map the core executes (``_dispatch.opcodes_for``), so the disassembler cannot disagree with the core about which opcode is which instruction or how long it is, and the same byte decodes differently on different rows: ``$07`` is ``RMB0 $12`` on an R65C02 and a one-byte ``NOP`` on a G65SC02. Every function takes the row (a CPU class); the default is the W65C02S. Syntax is WDC's (DS Table 5-2) as assemblers write it: ``LDA #$12``, ``LDA $12``, ``LDA $1234,X``, ``LDA ($12,X)``, ``LDA ($12),Y``, ``LDA ($12)``, ``JMP ($1234)``, ``JMP ($1234,X)``, ``ASL A``, ``BBR0 $12,$4567`` (zero-page byte, branch target), and branches with their 16-bit target. ``BRK`` is shown with its signature byte (``BRK #$12``): it is a two-byte instruction (DS Table 4-1 note 5). The undefined opcodes are ``NOP`` with the operand bytes they skip (``NOP #$12``, ``NOP $12``, ``NOP $12,X``, ``NOP $1234``). """ from __future__ import annotations from collections.abc import Callable, Sequence from dataclasses import dataclass from functools import cache from w65c02_python._dispatch import FORM_BYTES, opcodes_for from w65c02_python.cpu import W65C02S ByteReader = Callable[[int], int] # The dispatch's operand form -> (mode, text template); "{}" is the operand in hex. _FORMS = { "imp": ("implied", None), "acc": ("accumulator", "A"), "imm": ("immediate", "#${}"), "zp": ("zero_page", "${}"), "zpx": ("zero_page_x", "${},X"), "zpy": ("zero_page_y", "${},Y"), "zpind": ("zero_page_indirect", "(${})"), "idx": ("zero_page_indexed_indirect", "(${},X)"), "idy": ("zero_page_indirect_indexed", "(${}),Y"), "abs": ("absolute", "${}"), "abx": ("absolute_x", "${},X"), "aby": ("absolute_y", "${},Y"), "ind": ("absolute_indirect", "(${})"), "abxind": ("absolute_indexed_indirect", "(${},X)"), "rel": ("relative", None), "zprel": ("zero_page_relative", None), } #: Addressing modes, as ``Instruction.mode`` reports them. MODES = tuple(mode for mode, _template in _FORMS.values()) @dataclass(frozen=True, slots=True) class Instruction: """One decoded instruction and the exact bytes it occupies.""" address: int data: bytes mnemonic: str operands: tuple[str, ...] = () mode: str = "implied" #: The address the operand names -- zero-page byte, absolute address, #: pointer or branch target -- before any indexing; None for implied, #: accumulator and immediate forms. target: int | None = None #: False for an opcode the row does not define (it runs as a NOP). documented: bool = True 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 self.data: raise ValueError("data must contain at least one byte") if type(self.mnemonic) is not str or not self.mnemonic: raise ValueError("mnemonic must not be empty") if type(self.operands) is not tuple or not all(type(o) is str for o in self.operands): raise ValueError("operands must be a tuple of strings") if self.mode not in MODES: raise ValueError(f"mode must be one of {MODES}") @property def size(self) -> int: """Number of encoded bytes.""" return len(self.data) @property def next_address(self) -> int: """The address after the instruction: PC wraps at 16 bits.""" return (self.address + self.size) & 0xFFFF @property def text(self) -> str: """Canonical human-readable assembly text.""" return self.mnemonic if not self.operands else f"{self.mnemonic} {','.join(self.operands)}" @cache def decode_table(row: type = W65C02S) -> tuple[tuple[str, str, int, str | None, bool], ...]: """(mnemonic, mode, operand bytes, template, documented) for each of the row's 256 opcodes.""" table = [] for opcode, (handler, _mode, mnemonic, form, _cycles) in sorted(opcodes_for(row).items()): mode, template = _FORMS[form] documented = not handler.startswith("nop_") # `$EA` is handler "nop" table.append((mnemonic, mode, FORM_BYTES[form] - 1, template, documented)) return tuple(table) def operand_size(opcode: int, row: type = W65C02S) -> int: """Operand bytes after ``opcode`` on ``row``.""" return decode_table(row)[opcode][2] def _signed(value: int) -> int: return value - 0x100 if value & 0x80 else value def _decode(data: bytes, address: int, row: type) -> Instruction: mnemonic, mode, _size, template, documented = decode_table(row)[data[0]] operand = int.from_bytes(data[1:], "little") operands: tuple[str, ...] = () target = None if mode == "relative": target = (address + len(data) + _signed(data[1])) & 0xFFFF operands = (f"${target:04X}",) elif mode == "zero_page_relative": target = (address + len(data) + _signed(data[2])) & 0xFFFF operands = (f"${data[1]:02X}", f"${target:04X}") elif mode == "accumulator": operands = ("A",) elif template is not None: # Split at the commas, as 6502-python does: "($12,X)" -> "($12", "X)". operands = tuple(template.format(f"{operand:0{2 * len(data[1:])}X}").split(",")) if mode != "immediate": target = operand return Instruction(address, bytes(data), mnemonic, operands, mode, target, documented) def disassemble(reader: ByteReader, address: int, row: type = W65C02S) -> Instruction: """Decode the instruction at ``address`` as ``row`` executes it, using only ``reader``. ``reader`` must be side-effect-free (a peek, not the host's bus read). The bytes after the opcode wrap at 16 bits, as the program counter does. """ if type(address) is not int or not 0 <= address <= 0xFFFF: raise ValueError("address must be an integer in range 0x0000..0xFFFF") opcode = _byte(reader, address) size = operand_size(opcode, row) data = bytes((opcode, *(_byte(reader, (address + n) & 0xFFFF) for n in range(1, size + 1)))) return _decode(data, address, row) def disassemble_bytes( data: Sequence[int] | bytes, address: int = 0, row: type = W65C02S ) -> Instruction: """Decode exactly one instruction from ``data``, whose first byte sits at ``address``.""" copy = bytes(data) if not copy: raise ValueError("data must not be empty") size = operand_size(copy[0], row) if len(copy) != 1 + size: raise ValueError(f"opcode ${copy[0]:02X} takes {size} operand bytes, not {len(copy) - 1}") return _decode(copy, address, row) def disassemble_range( reader: ByteReader, address: int, count: int, row: type = W65C02S ) -> list[Instruction]: """Decode ``count`` consecutive instructions.""" listing = [] for _ in range(count): instruction = disassemble(reader, address, row) listing.append(instruction) address = instruction.next_address return listing def _byte(reader: ByteReader, address: int) -> int: value = reader(address) if type(value) is not int or not 0 <= value <= 0xFF: raise ValueError(f"byte reader returned a non-byte value at 0x{address:04X}") return value __all__ = [ "MODES", "ByteReader", "Instruction", "decode_table", "disassemble", "disassemble_bytes", "disassemble_range", "operand_size", ]