"""Generate src/z80_python_fast/_ops.py: one specialized function per opcode. The reference decodes register and condition fields at run time, through helper calls (``_read_reg(src)``, ``_write_pair(index, value)``, ``_read_operand_word()``, ``_alu_a(group, value)``). Here every opcode of every page gets its own function with those fields resolved when the file is generated: ``LD B,C`` is ``c.b = c.c``. The semantics are transcribed family by family from the reference handlers (named in each function's comment); validation/lockstep.py and the SingleStepTests prove the transcription. python tools/gen_ops.py # rewrite src/z80_python_fast/_ops.py python tools/gen_ops.py --check # exit 1 if the committed file is stale Every function takes the CPU and returns the instruction's T-states, prefix fetches included, exactly as the reference handler returns them. DD CB and FD CB functions also take the displacement byte. """ from __future__ import annotations import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "src" / "z80_python_fast" / "_ops.py" sys.path.insert(0, str(ROOT / "src")) from z80_python_fast.disasm import disassemble_bytes # noqa: E402 REG = ("b", "c", "d", "e", "h", "l", None, "a") PAIR_READ = ("((c.b << 8) | c.c)", "((c.d << 8) | c.e)", "((c.h << 8) | c.l)", "c.sp") HL = PAIR_READ[2] # cc in bits 5-3: NZ Z NC C PO PE P M. CONDITIONS = ( "not c._f & 0x40", "c._f & 0x40", "not c._f & 0x01", "c._f & 0x01", "not c._f & 0x04", "c._f & 0x04", "not c._f & 0x80", "c._f & 0x80", ) def write_pair(index: int, value: str) -> list[str]: """Statements storing the 16-bit expression ``value`` (already masked) into pair ``index``.""" if index == 3: return [f"c.sp = {value}"] hi, lo = (("b", "c"), ("d", "e"), ("h", "l"))[index] return [f"v = {value}", f"c.{hi} = v >> 8", f"c.{lo} = v & 0xFF"] def fetch_byte(name: str = "n") -> list[str]: """An operand byte at PC (an ordinary read: R does not move).""" return ["pc = c.pc", f"{name} = c.read_byte(pc)", "c.pc = (pc + 1) & 0xFFFF"] def fetch_word(name: str = "nn") -> list[str]: return [ "pc = c.pc", "rb = c.read_byte", "lo = rb(pc)", "hi = rb((pc + 1) & 0xFFFF)", "c.pc = (pc + 2) & 0xFFFF", f"{name} = lo | (hi << 8)", ] def signed(name: str) -> str: return f"({name} - 0x100 if {name} & 0x80 else {name})" def push(value: str) -> list[str]: """The reference's _push_word: high byte to SP-1, then low byte to SP-2.""" return [ f"w = {value}", "sp = (c.sp - 1) & 0xFFFF", "wb = c.write_byte", "wb(sp, w >> 8)", "sp = (sp - 1) & 0xFFFF", "c.sp = sp", "wb(sp, w & 0xFF)", ] def pop(name: str) -> list[str]: return [ "sp = c.sp", "rb = c.read_byte", "lo = rb(sp)", "hi = rb((sp + 1) & 0xFFFF)", "c.sp = (sp + 2) & 0xFFFF", f"{name} = lo | (hi << 8)", ] # --- 8-bit ALU ------------------------------------------------------------- def alu(group: int, v: str) -> list[str]: """A op= v for ADD ADC SUB SBC AND XOR OR CP; sets c._f and c.q (reference _alu_a).""" if group in (0, 1): carry = " + (c._f & 0x01)" if group == 1 else "" return [ "a = c.a", f"z = a + v{carry}", "r = z & 0xFF", "f = SZXY[r] | ((a ^ v ^ r) & 0x10) | (((a ^ v ^ 0x80) & (a ^ r) & 0x80) >> 5) | (z >> 8)", "c.a = r", ] if group in (2, 3): carry = " - (c._f & 0x01)" if group == 3 else "" return [ "a = c.a", f"z = a - v{carry}", "r = z & 0xFF", "f = (SZXY[r] | ((a ^ v ^ r) & 0x10) | (((a ^ v) & (a ^ r) & 0x80) >> 5)" " | 0x02 | ((z >> 8) & 0x01))", "c.a = r", ] if group == 4: return ["r = c.a & v", "f = SZXYP[r] | 0x10", "c.a = r"] if group == 5: return ["r = c.a ^ v", "f = SZXYP[r]", "c.a = r"] if group == 6: return ["r = c.a | v", "f = SZXYP[r]", "c.a = r"] return [ "a = c.a", "z = a - v", "r = z & 0xFF", "f = ((SZXY[r] & 0xC0) | (v & 0x28) | ((a ^ v ^ r) & 0x10)" " | (((a ^ v) & (a ^ r) & 0x80) >> 5) | 0x02 | ((z >> 8) & 0x01))", ] def with_alu(group: int, value: str) -> list[str]: return [f"v = {value}", *alu(group, "v"), "c._f = f", "c.q = f"] def inc8(x: str) -> list[str]: """r = x + 1 with the reference _inc flags into f (C kept).""" return [ f"r = ({x} + 1) & 0xFF", "f = ((c._f & 0x01) | SZXY[r] | (0x10 if (r & 0x0F) == 0 else 0)" " | (0x04 if r == 0x80 else 0))", ] def dec8(x: str) -> list[str]: return [ f"r = ({x} - 1) & 0xFF", "f = ((c._f & 0x01) | SZXY[r] | 0x02 | (0x10 if (r & 0x0F) == 0x0F else 0)" " | (0x04 if r == 0x7F else 0))", ] # --- CB rotates and shifts: (result, carry-out) in terms of x -------------- ROTATE = ( ("((x << 1) | (x >> 7)) & 0xFF", "x >> 7"), # RLC ("((x >> 1) | (x << 7)) & 0xFF", "x & 1"), # RRC ("((x << 1) | (c._f & 0x01)) & 0xFF", "x >> 7"), # RL ("(x >> 1) | ((c._f & 0x01) << 7)", "x & 1"), # RR ("(x << 1) & 0xFF", "x >> 7"), # SLA ("(x & 0x80) | (x >> 1)", "x & 1"), # SRA ("((x << 1) | 1) & 0xFF", "x >> 7"), # SLL ("x >> 1", "x & 1"), # SRL ) def rotate(group: int) -> list[str]: result, carry = ROTATE[group] return [f"r = {result}", f"f = SZXYP[r] | ({carry})"] def bit_flags(bit: int, value: str, xy_source: str) -> str: """The reference _bit_flags as one expression.""" # Z and PV when the bit is clear; S only for a set bit 7; H set; C kept. sign = f" | ({value} & 0x80)" if bit == 7 else "" return ( f"(c._f & 0x01) | 0x10 | ({xy_source} & 0x28){sign}" f" | (0 if {value} & {1 << bit:#04x} else 0x44)" ) # --- page builders ------------------------------------------------------------- class Page: def __init__(self, prefix: str, label_bytes: bytes) -> None: self.prefix = prefix self.label_bytes = label_bytes self.functions: dict[int, tuple[str, list[str], str]] = {} def add(self, opcode: int, reference: str, body: list[str], args: str = "c") -> None: if opcode in self.functions: raise ValueError(f"{self.prefix} {opcode:02X} generated twice") self.functions[opcode] = (reference, body, args) def name(self, opcode: int) -> str: return f"{self.prefix}_{opcode:02x}" def label(data: bytes) -> str: """Mnemonic text for a function comment, with the placeholder operands named.""" text = disassemble_bytes(data, 0).text text = text.replace("0x3412", "nn").replace("0x12", "n").replace("+0x05", "+d") return re.sub(r"JR (\w+,)?0x0014", r"JR \1e", re.sub(r"DJNZ 0x0014", "DJNZ e", text)) def main_page(page: Page, *, index: str | None = None) -> None: """The main page, or with ``index`` ('ix'/'iy') its DD/FD page. On the DD/FD page, opcodes the prefix does not modify run their main-page body plus the prefix's 4 T-states; the prefix M1 wrote no flags, so Q is 0 where SCF/CCF read it (the reference sets ``self.q = 0`` before dispatch). """ extra = 4 if index else 0 def plain(opcode: int, reference: str, body: list[str], t: int | str) -> None: total = t + extra if isinstance(t, int) else t page.add(opcode, reference, [*body, f"return {total}"]) # Opcodes the index page replaces; the caller fills them in. replaced: set[int] = set() if index: replaced = set(INDEX_REPLACED) def claim(opcode: int) -> bool: return opcode not in replaced if claim(0x00): plain(0x00, "_op_nop", ["c.q = 0"], 4) for p in range(4): op = 0x01 | p << 4 if claim(op): plain(op, "_op_ld_rr_nn", [*fetch_word(), *write_pair(p, "nn"), "c.q = 0"], 10) op = 0x03 | p << 4 if claim(op): plain( op, "_op_inc_rr", [*write_pair(p, f"({PAIR_READ[p]} + 1) & 0xFFFF"), "c.q = 0"], 6 ) op = 0x0B | p << 4 if claim(op): plain( op, "_op_dec_rr", [*write_pair(p, f"({PAIR_READ[p]} - 1) & 0xFFFF"), "c.q = 0"], 6 ) op = 0x09 | p << 4 if claim(op): plain( op, "_op_add_hl_rr", [ f"hl = {HL}", f"v = {PAIR_READ[p]}", "c.wz = (hl + 1) & 0xFFFF", "z = hl + v", "r = z & 0xFFFF", "f = ((c._f & 0xC4) | ((r >> 8) & 0x28) | (((hl ^ v ^ r) >> 8) & 0x10)" " | (z >> 16))", "c._f = f", "c.h = r >> 8", "c.l = r & 0xFF", "c.q = f", ], 11, ) for op, pair in ((0x02, 0), (0x12, 1)): plain( op, "_op_ld_irr_a", [ f"w = {PAIR_READ[pair]}", "a = c.a", "c.write_byte(w, a)", "c.wz = ((a << 8) | ((w + 1) & 0xFF)) & 0xFFFF", "c.q = 0", ], 7, ) for op, pair in ((0x0A, 0), (0x1A, 1)): plain( op, "_op_ld_a_irr", [ f"w = {PAIR_READ[pair]}", "c.a = c.read_byte(w)", "c.wz = (w + 1) & 0xFFFF", "c.q = 0", ], 7, ) for dest in range(8): reg = REG[dest] if reg is None: continue op = 0x04 | dest << 3 if claim(op): plain(op, "_op_inc_r", [*inc8(f"c.{reg}"), f"c.{reg} = r", "c._f = f", "c.q = f"], 4) op = 0x05 | dest << 3 if claim(op): plain(op, "_op_dec_r", [*dec8(f"c.{reg}"), f"c.{reg} = r", "c._f = f", "c.q = f"], 4) op = 0x06 | dest << 3 if claim(op): plain(op, "_op_ld_r_n", [*fetch_byte(), f"c.{reg} = n", "c.q = 0"], 7) if claim(0x34): plain( 0x34, "_op_inc_hl", [f"w = {HL}", *inc8("c.read_byte(w)"), "c._f = f", "c.write_byte(w, r)", "c.q = f"], 11, ) if claim(0x35): plain( 0x35, "_op_dec_hl", [f"w = {HL}", *dec8("c.read_byte(w)"), "c._f = f", "c.write_byte(w, r)", "c.q = f"], 11, ) if claim(0x36): plain(0x36, "_op_ld_r_n", [*fetch_byte(), f"c.write_byte({HL}, n)", "c.q = 0"], 10) plain( 0x07, "_op_rlca", [ "a = c.a", "a = ((a << 1) | (a >> 7)) & 0xFF", "c.a = a", "f = (c._f & 0xC4) | (a & 0x29)", "c._f = f", "c.q = f", ], 4, ) plain( 0x0F, "_op_rrca", [ "a = c.a", "carry = a & 1", "a = ((a >> 1) | (a << 7)) & 0xFF", "c.a = a", "f = (c._f & 0xC4) | (a & 0x28) | carry", "c._f = f", "c.q = f", ], 4, ) plain( 0x17, "_op_rla", [ "a = c.a", "f = c._f", "carry = a >> 7", "a = ((a << 1) | (f & 0x01)) & 0xFF", "c.a = a", "f = (f & 0xC4) | (a & 0x28) | carry", "c._f = f", "c.q = f", ], 4, ) plain( 0x1F, "_op_rra", [ "a = c.a", "f = c._f", "carry = a & 1", "a = (a >> 1) | ((f & 0x01) << 7)", "c.a = a", "f = (f & 0xC4) | (a & 0x28) | carry", "c._f = f", "c.q = f", ], 4, ) plain( 0x08, "_op_ex_af_af", [ "af = (c.a << 8) | c._f", "alt = c.af_", "c.a = alt >> 8", "c._f = alt & 0xFF", "c.af_ = af", "c.q = 0", ], 4, ) plain( 0x10, "_op_djnz", [ *fetch_byte("d"), "b = (c.b - 1) & 0xFF", "c.b = b", "c.q = 0", "if b:", f" w = (c.pc + {signed('d')}) & 0xFFFF", " c.wz = w", " c.pc = w", f" return {13 + extra}", ], 8, ) for op in (0x18, 0x20, 0x28, 0x30, 0x38): taken = "True" if op == 0x18 else CONDITIONS[(op >> 3) & 0x03] body = [*fetch_byte("d"), "c.q = 0"] if op == 0x18: body += [f"w = (c.pc + {signed('d')}) & 0xFFFF", "c.wz = w", "c.pc = w"] plain(op, "_op_jr", body, 12) else: body += [ f"if {taken}:", f" w = (c.pc + {signed('d')}) & 0xFFFF", " c.wz = w", " c.pc = w", f" return {12 + extra}", ] plain(op, "_op_jr", body, 7) if claim(0x22): plain( 0x22, "_op_ld_nn_hl", [ *fetch_word(), "wb = c.write_byte", "wb(nn, c.l)", "w = (nn + 1) & 0xFFFF", "c.wz = w", "wb(w, c.h)", "c.q = 0", ], 16, ) if claim(0x2A): plain( 0x2A, "_op_ld_hl_nn_from_mem", [ *fetch_word(), "c.l = rb(nn)", "w = (nn + 1) & 0xFFFF", "c.wz = w", "c.h = rb(w)", "c.q = 0", ], 16, ) plain( 0x27, "_op_daa", [ "original = a = c.a", "f = c._f", "carry = f & 0x01", "if carry or a > 0x99:", " a = (a + (-0x60 if f & 0x02 else 0x60)) & 0xFF", " carry = 0x01", "if f & 0x10 or (a & 0x0F) > 0x09:", " a = (a + (-0x06 if f & 0x02 else 0x06)) & 0xFF", "c.a = a", "f = SZXYP[a] | ((a ^ original) & 0x10) | (f & 0x02) | carry", "c._f = f", "c.q = f", ], 4, ) plain( 0x2F, "_op_cpl", [ "a = c.a ^ 0xFF", "c.a = a", "f = (c._f & 0xC5) | 0x12 | (a & 0x28)", "c._f = f", "c.q = f", ], 4, ) for op in (0x37, 0x3F): body = ["f = c._f", "a = c.a"] # Q holds F only if the previous M1 wrote flags; a DD/FD prefix M1 wrote none. body.append("xy = (f | a) & 0x28" if index else "xy = (a if c.q else f | a) & 0x28") if op == 0x37: body.append("ch = 0x01") else: body.append("ch = 0x10 if f & 0x01 else 0x01") body += ["f = (f & 0xC4) | xy | ch", "c._f = f", "c.q = f"] plain(op, "_op_scf_ccf", body, 4) plain( 0x32, "_op_ld_inn_a", [ *fetch_word(), "a = c.a", "c.write_byte(nn, a)", "c.wz = ((a << 8) | ((nn + 1) & 0xFF)) & 0xFFFF", "c.q = 0", ], 13, ) plain( 0x3A, "_op_ld_a_inn", [*fetch_word(), "c.a = rb(nn)", "c.wz = (nn + 1) & 0xFFFF", "c.q = 0"], 13, ) for op in range(0x40, 0x80): if op == 0x76 or not claim(op): continue dest, src = (op >> 3) & 7, op & 7 if src == 6: plain(op, "_op_ld_r_r", [f"c.{REG[dest]} = c.read_byte({HL})", "c.q = 0"], 7) elif dest == 6: plain(op, "_op_ld_r_r", [f"c.write_byte({HL}, c.{REG[src]})", "c.q = 0"], 7) else: body = [] if dest == src else [f"c.{REG[dest]} = c.{REG[src]}"] plain(op, "_op_ld_r_r", [*body, "c.q = 0"], 4) plain(0x76, "_op_halt", ["c._halted = True", "c._attention = True", "c.q = 0"], 4) for op in range(0x80, 0xC0): if not claim(op): continue group, src = (op >> 3) & 7, op & 7 if src == 6: plain(op, "_op_alu_r", with_alu(group, f"c.read_byte({HL})"), 7) else: plain(op, "_op_alu_r", with_alu(group, f"c.{REG[src]}"), 4) for cc in range(8): op = 0xC0 | cc << 3 plain( op, "_op_ret_cc", [ "c.q = 0", f"if {CONDITIONS[cc]}:", *(f" {line}" for line in pop("w")), " c.wz = w", " c.pc = w", f" return {11 + extra}", ], 5, ) op = 0xC2 | cc << 3 plain( op, "_op_jp", [*fetch_word(), "c.wz = nn", "c.q = 0", f"if {CONDITIONS[cc]}:", " c.pc = nn"], 10, ) op = 0xC4 | cc << 3 plain( op, "_op_call", [ *fetch_word(), "c.wz = nn", "c.q = 0", f"if {CONDITIONS[cc]}:", *(f" {line}" for line in push("c.pc")), " c.pc = nn", f" return {17 + extra}", ], 10, ) op = 0xC6 | cc << 3 plain(op, "_op_alu_n", [*fetch_byte(), *with_alu(cc, "n")], 7) op = 0xC7 | cc << 3 plain( op, "_op_rst", [*push("c.pc"), f"c.wz = {cc << 3:#04x}", f"c.pc = {cc << 3:#04x}", "c.q = 0"], 11, ) plain(0xC3, "_op_jp", [*fetch_word(), "c.wz = nn", "c.pc = nn", "c.q = 0"], 10) plain( 0xCD, "_op_call", [*fetch_word(), "c.wz = nn", *push("c.pc"), "c.pc = nn", "c.q = 0"], 17, ) plain(0xC9, "_op_ret", [*pop("w"), "c.wz = w", "c.pc = w", "c.q = 0"], 10) for p in range(3): op = 0xC1 | p << 4 if claim(op): plain(op, "_op_pop_rr", [*pop("w"), *write_pair(p, "w"), "c.q = 0"], 10) op = 0xC5 | p << 4 if claim(op): plain(op, "_op_push_rr", [*push(PAIR_READ[p]), "c.q = 0"], 11) plain(0xF1, "_op_pop_af", [*pop("w"), "c.a = w >> 8", "c._f = w & 0xFF", "c.q = 0"], 10) plain(0xF5, "_op_push_af", [*push("(c.a << 8) | c._f"), "c.q = 0"], 11) plain( 0xD3, "_op_out_n_a", [ *fetch_byte(), "a = c.a", "w = (a << 8) | n", "c.write_port(w, a)", "c.wz = (w & 0xFF00) | ((w + 1) & 0xFF)", "c.q = 0", ], 11, ) plain( 0xDB, "_op_in_a_n", [ *fetch_byte(), "w = (c.a << 8) | n", "c.a = c.read_port(w)", "c.wz = (w + 1) & 0xFFFF", "c.q = 0", ], 11, ) plain( 0xD9, "_op_exx", [ "bc = (c.b << 8) | c.c", "de = (c.d << 8) | c.e", "hl = (c.h << 8) | c.l", "w = c.bc_", "c.b = w >> 8", "c.c = w & 0xFF", "w = c.de_", "c.d = w >> 8", "c.e = w & 0xFF", "w = c.hl_", "c.h = w >> 8", "c.l = w & 0xFF", "c.bc_ = bc", "c.de_ = de", "c.hl_ = hl", "c.q = 0", ], 4, ) if claim(0xE3): plain( 0xE3, "_op_ex_sp_hl", [ "sp = c.sp", "rb = c.read_byte", "sp1 = (sp + 1) & 0xFFFF", "w = rb(sp) | (rb(sp1) << 8)", "wb = c.write_byte", "wb(sp1, c.h)", "wb(sp, c.l)", "c.h = w >> 8", "c.l = w & 0xFF", "c.wz = w", "c.q = 0", ], 19, ) if claim(0xE9): plain(0xE9, "_op_jp_hl", [f"c.pc = {HL}", "c.q = 0"], 4) plain( 0xEB, "_op_ex_de_hl", ["d, e = c.d, c.e", "c.d = c.h", "c.e = c.l", "c.h = d", "c.l = e", "c.q = 0"], 4, ) if claim(0xF9): plain(0xF9, "_op_ld_sp_hl", [f"c.sp = {HL}", "c.q = 0"], 6) plain( 0xF3, "_op_interrupt_enable", ["c.iff1 = False", "c.iff2 = False", "c._ei_delay = 0", "c.q = 0"], 4, ) plain( 0xFB, "_op_interrupt_enable", ["c.iff1 = True", "c.iff2 = True", "c._ei_delay = 1", "c._attention = True", "c.q = 0"], 4, ) # Opcodes a DD/FD prefix changes (reference INDEX_RULES with prefixed=True), # plus the prefix bytes and ED, which the prefix-run dispatcher handles. INDEX_REPLACED = ( [0x09, 0x19, 0x29, 0x39, 0x21, 0x22, 0x23, 0x24, 0x25, 0x2C, 0x2D, 0x26, 0x2E, 0x2A, 0x2B] + [0x34, 0x35, 0x36] + [0x44, 0x45, 0x4C, 0x4D, 0x54, 0x55, 0x5C, 0x5D, 0x7C, 0x7D] + [0x46, 0x4E, 0x56, 0x5E, 0x66, 0x6E, 0x7E] + [op for op in range(0x60, 0x70) if op & 7 in (0, 1, 2, 3, 7)] + [0x64, 0x65, 0x6C, 0x6D] + [0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x77] + [op for op in range(0x80, 0xC0) if op & 7 in (4, 5, 6)] + [0xCB, 0xE1, 0xE3, 0xE5, 0xE9, 0xF9] + [0xDD, 0xFD, 0xED] # H/L forms the prefix turns into IXH/IXL, which the reference routes to # the index handlers: LD r,H/L etc. are in the ranges above; the # remaining H/L forms of the plain groups below. + [ op for op in range(0x40, 0x80) if op != 0x76 and ((op >> 3) & 7 in (4, 5, 6) or op & 7 in (4, 5, 6)) ] + [0x04 | 4 << 3, 0x04 | 5 << 3, 0x05 | 4 << 3, 0x05 | 5 << 3, 0x06 | 4 << 3, 0x06 | 5 << 3] + [0xE5] ) def index_page(page: Page, ix: str) -> None: """The opcodes a DD/FD prefix turns into IX/IY forms (reference _index.py).""" X = f"c.{ix}" XH, XL = f"({X} >> 8)", f"({X} & 0xFF)" def half_read(slot: int) -> str: # slot 4 = high, 5 = low return XH if slot == 4 else XL def half_write(slot: int, value: str) -> list[str]: if slot == 4: return [f"{X} = (({value}) << 8) | ({X} & 0xFF)"] return [f"{X} = ({X} & 0xFF00) | ({value})"] def displaced() -> list[str]: """The reference _index_displacement_addr: WZ = IX+d.""" return [*fetch_byte("d"), f"w = ({X} + {signed('d')}) & 0xFFFF", "c.wz = w"] for p in range(4): value = X if p == 2 else PAIR_READ[p] page.add( 0x09 | p << 4, "_op_add_index_rr", [ f"x = {X}", f"v = {value if p != 2 else 'x'}", "c.wz = (x + 1) & 0xFFFF", "z = x + v", "r = z & 0xFFFF", "f = ((c._f & 0xC4) | ((r >> 8) & 0x28) | (((x ^ v ^ r) >> 8) & 0x10) | (z >> 16))", "c._f = f", f"{X} = r", "c.q = f", "return 15", ], ) page.add(0x21, "_op_ld_index_nn", [*fetch_word(), f"{X} = nn", "c.q = 0", "return 14"]) page.add( 0x22, "_op_ld_nn_index", [ *fetch_word(), f"x = {X}", "wb = c.write_byte", "wb(nn, x & 0xFF)", "w = (nn + 1) & 0xFFFF", "c.wz = w", "wb(w, x >> 8)", "c.q = 0", "return 20", ], ) page.add( 0x2A, "_op_ld_index_nn_from_mem", [ *fetch_word(), "lo = rb(nn)", "w = (nn + 1) & 0xFFFF", "c.wz = w", f"{X} = lo | (rb(w) << 8)", "c.q = 0", "return 20", ], ) page.add(0x23, "_op_inc_index", [f"{X} = ({X} + 1) & 0xFFFF", "c.q = 0", "return 10"]) page.add(0x2B, "_op_dec_index", [f"{X} = ({X} - 1) & 0xFFFF", "c.q = 0", "return 10"]) for slot in (4, 5): page.add( 0x04 | slot << 3, "_op_inc_dec_index_byte", [*inc8(half_read(slot)), "c._f = f", *half_write(slot, "r"), "c.q = f", "return 8"], ) page.add( 0x05 | slot << 3, "_op_inc_dec_index_byte", [*dec8(half_read(slot)), "c._f = f", *half_write(slot, "r"), "c.q = f", "return 8"], ) page.add( 0x06 | slot << 3, "_op_ld_index_byte_n", [*fetch_byte(), *half_write(slot, "n"), "c.q = 0", "return 11"], ) page.add( 0x34, "_op_inc_index_mem", [ *displaced(), *inc8("c.read_byte(w)"), "c._f = f", "c.write_byte(w, r)", "c.q = f", "return 23", ], ) page.add( 0x35, "_op_dec_index_mem", [ *displaced(), *dec8("c.read_byte(w)"), "c._f = f", "c.write_byte(w, r)", "c.q = f", "return 23", ], ) page.add( 0x36, "_op_ld_index_mem_n", [*displaced(), *fetch_byte(), "c.write_byte(w, n)", "c.q = 0", "return 19"], ) for op in range(0x40, 0x80): if op == 0x76: continue dest, src = (op >> 3) & 7, op & 7 if src == 6: # LD r,(IX+d): r is the plain register, H and L included page.add( op, "_op_ld_r_index_mem", [*displaced(), f"c.{REG[dest]} = c.read_byte(w)", "c.q = 0", "return 19"], ) elif dest == 6: # LD (IX+d),r page.add( op, "_op_ld_index_mem_r", [*displaced(), f"c.write_byte(w, c.{REG[src]})", "c.q = 0", "return 19"], ) elif dest in (4, 5) and src in (4, 5): body = [] if dest == src else half_write(dest, half_read(src)) page.add(op, "_op_ld_index_byte_index_byte", [*body, "c.q = 0", "return 8"]) elif src in (4, 5): page.add( op, "_op_ld_r_index_byte", [f"c.{REG[dest]} = {half_read(src)}", "c.q = 0", "return 8"], ) elif dest in (4, 5): page.add( op, "_op_ld_index_byte_r", [*half_write(dest, f"c.{REG[src]}"), "c.q = 0", "return 8"], ) for op in range(0x80, 0xC0): group, src = (op >> 3) & 7, op & 7 if src == 6: page.add( op, "_op_alu_index_mem", [*displaced(), *with_alu(group, "c.read_byte(w)"), "return 19"], ) elif src in (4, 5): page.add(op, "_op_alu_index_byte", [*with_alu(group, half_read(src)), "return 8"]) page.add(0xE1, "_op_pop_index", [*pop("w"), f"{X} = w", "c.q = 0", "return 14"]) page.add(0xE5, "_op_push_index", [*push(X), "c.q = 0", "return 15"]) page.add( 0xE3, "_op_ex_sp_index", [ "sp = c.sp", "rb = c.read_byte", "sp1 = (sp + 1) & 0xFFFF", "w = rb(sp) | (rb(sp1) << 8)", f"x = {X}", "wb = c.write_byte", "wb(sp1, x >> 8)", "wb(sp, x & 0xFF)", f"{X} = w", "c.wz = w", "c.q = 0", "return 23", ], ) page.add(0xE9, "_op_jp_index", [f"c.pc = {X}", "c.q = 0", "return 8"]) page.add(0xF9, "_op_ld_sp_index", [f"c.sp = {X}", "c.q = 0", "return 10"]) page.add( 0xCB, "_execute_index_cb", [ "pc = c.pc", "rb = c.read_byte", "d = rb(pc)", "op = rb((pc + 1) & 0xFFFF)", "c.pc = (pc + 2) & 0xFFFF", f"return {'DDCB' if ix == 'ix' else 'FDCB'}[op](c, d)", ], ) def cb_page(page: Page) -> None: for op in range(0x100): group, reg = (op >> 3) & 7, op & 7 if op < 0x40: if reg == 6: body = [f"w = {HL}", "x = c.read_byte(w)", *rotate(group)] body += ["c._f = f", "c.write_byte(w, r)", "c.q = f", "return 15"] else: body = [f"x = c.{REG[reg]}", *rotate(group), f"c.{REG[reg]} = r"] body += ["c._f = f", "c.q = f", "return 8"] page.add(op, "_op_rot", body) elif op < 0x80: if reg == 6: body = [ f"x = c.read_byte({HL})", f"f = {bit_flags(group, 'x', '(c.wz >> 8)')}", "c._f = f", "c.q = f", "return 12", ] else: body = [ f"x = c.{REG[reg]}", f"f = {bit_flags(group, 'x', 'x')}", "c._f = f", "c.q = f", "return 8", ] page.add(op, "_op_bit", body) else: setting = op >= 0xC0 expr = f"x | {1 << group:#04x}" if setting else f"x & {~(1 << group) & 0xFF:#04x}" if reg == 6: body = [f"w = {HL}", "x = c.read_byte(w)", f"c.write_byte(w, {expr})"] body += ["c.q = 0", "return 15"] else: body = [f"x = c.{REG[reg]}", f"c.{REG[reg]} = {expr}", "c.q = 0", "return 8"] page.add(op, "_op_set" if setting else "_op_res", body) def index_cb_page(page: Page, ix: str) -> None: X = f"c.{ix}" addr = [f"w = ({X} + {signed('d')}) & 0xFFFF", "c.wz = w"] for op in range(0x100): group, reg = (op >> 3) & 7, op & 7 copy = [] if reg == 6 else [f"c.{REG[reg]} = r"] if op < 0x40: body = [*addr, "x = c.read_byte(w)", *rotate(group), "c._f = f"] body += ["c.write_byte(w, r)", *copy, "c.q = f", "return 23"] page.add(op, "_op_index_rot", body, "c, d") elif op < 0x80: body = [*addr, "x = c.read_byte(w)", f"f = {bit_flags(group, 'x', '(w >> 8)')}"] body += ["c._f = f", "c.q = f", "return 20"] page.add(op, "_op_index_bit", body, "c, d") else: setting = op >= 0xC0 expr = f"x | {1 << group:#04x}" if setting else f"x & {~(1 << group) & 0xFF:#04x}" body = [*addr, "x = c.read_byte(w)", f"r = {expr}", "c.write_byte(w, r)", *copy] body += ["c.q = 0", "return 23"] page.add(op, "_op_index_res_set", body, "c, d") def ed_page(page: Page) -> None: for reg in range(8): op = 0x40 | reg << 3 store = [] if reg == 6 else [f"c.{REG[reg]} = v"] page.add( op, "_op_in_r_c", [ "bc = (c.b << 8) | c.c", "c.wz = (bc + 1) & 0xFFFF", "v = c.read_port(bc)", "f = (c._f & 0x01) | SZXYP[v]", "c._f = f", *store, "c.q = f", "return 12", ], ) op = 0x41 | reg << 3 value = "(0xFF if c.cmos_out_c_zero else 0)" if reg == 6 else f"c.{REG[reg]}" page.add( op, "_op_out_c_r", [ "bc = (c.b << 8) | c.c", f"c.write_port(bc, {value})", "c.wz = (bc + 1) & 0xFFFF", "c.q = 0", "return 12", ], ) for p in range(4): for op, reference, sign in ( (0x42 | p << 4, "_op_sbc_hl_rr", "-"), (0x4A | p << 4, "_op_adc_hl_rr", "+"), ): if sign == "+": flags = ( "f = (((r >> 8) & 0xA8) | (0x40 if r == 0 else 0) | (((x ^ y ^ r) >> 8) & 0x10)" " | (((x ^ y ^ 0x8000) & (x ^ r) & 0x8000) >> 13) | (z >> 16))" ) else: flags = ( "f = (((r >> 8) & 0xA8) | (0x40 if r == 0 else 0) | (((x ^ y ^ r) >> 8) & 0x10)" " | (((x ^ y) & (x ^ r) & 0x8000) >> 13) | 0x02 | ((z >> 16) & 0x01))" ) page.add( op, reference, [ f"x = {HL}", "c.wz = (x + 1) & 0xFFFF", f"y = {PAIR_READ[p]}", f"z = x {sign} y {sign} (c._f & 0x01)", "r = z & 0xFFFF", flags, "c._f = f", "c.h = r >> 8", "c.l = r & 0xFF", "c.q = f", "return 15", ], ) page.add( 0x43 | p << 4, "_op_ld_nn_rr", [ *fetch_word(), f"v = {PAIR_READ[p]}", "wb = c.write_byte", "wb(nn, v & 0xFF)", "w = (nn + 1) & 0xFFFF", "c.wz = w", "wb(w, v >> 8)", "c.q = 0", "return 20", ], ) page.add( 0x4B | p << 4, "_op_ld_rr_nn_from_mem", [ *fetch_word(), "lo = rb(nn)", "w = (nn + 1) & 0xFFFF", "c.wz = w", *write_pair(p, "lo | (rb(w) << 8)"), "c.q = 0", "return 20", ], ) for op in range(0x44, 0x80, 8): page.add( op, "_op_neg", ["v = c.a", "c.a = 0", *alu(2, "v"), "c._f = f", "c.q = f", "return 8"] ) for op in (0x45, 0x55, 0x65, 0x75, 0x4D, 0x5D, 0x6D, 0x7D): page.add( op, "_op_retn" if (op & 0x08) == 0 else "_op_reti", [*pop("w"), "c.wz = w", "c.pc = w", "c.iff1 = c.iff2", "c.q = 0", "return 14"], ) for ops, mode in (((0x46, 0x4E, 0x66, 0x6E), 0), ((0x56, 0x76), 1), ((0x5E, 0x7E), 2)): for op in ops: page.add(op, "_op_im", [f"c.im = {mode}", "c.q = 0", "return 8"]) page.add(0x47, "_op_ld_i_a", ["c.i = c.a", "c.q = 0", "return 9"]) page.add(0x4F, "_op_ld_r_a", ["c.r = c.a", "c.q = 0", "return 9"]) for op, src in ((0x57, "c.i"), (0x5F, "c.r")): page.add( op, "_op_ld_a_i" if op == 0x57 else "_op_ld_a_r", [ f"a = {src}", "c.a = a", "f = (c._f & 0x01) | SZXY[a] | (0x04 if c.iff2 else 0)", "c._f = f", "c.q = f", "return 9", ], ) for op, reference, new_mem, new_a in ( (0x67, "_op_rrd", "((x >> 4) | (a << 4)) & 0xFF", "(a & 0xF0) | (x & 0x0F)"), (0x6F, "_op_rld", "((x << 4) | (a & 0x0F)) & 0xFF", "(a & 0xF0) | (x >> 4)"), ): page.add( op, reference, [ f"w = {HL}", "c.wz = (w + 1) & 0xFFFF", "x = c.read_byte(w)", "a = c.a", f"c.write_byte(w, {new_mem})", f"a = {new_a}", "c.a = a", "f = (c._f & 0x01) | SZXYP[a]", "c._f = f", "c.q = f", "return 18", ], ) for op, reference, increment, repeat in ( (0xA0, "_op_ldi", True, False), (0xA8, "_op_ldd", False, False), (0xB0, "_op_ldir", True, True), (0xB8, "_op_lddr", False, True), ): step = "+ 1" if increment else "- 1" body = [ "hl = (c.h << 8) | c.l", "data = c.read_byte(hl)", "de = (c.d << 8) | c.e", "c.write_byte(de, data)", f"hl = (hl {step}) & 0xFFFF", f"de = (de {step}) & 0xFFFF", "c.h = hl >> 8", "c.l = hl & 0xFF", "c.d = de >> 8", "c.e = de & 0xFF", "bc = (((c.b << 8) | c.c) - 1) & 0xFFFF", "c.b = bc >> 8", "c.c = bc & 0xFF", "n = c.a + data", "f = (c._f & 0xC1) | (n & 0x08) | ((n & 0x02) << 4) | (0x04 if bc else 0)", ] if repeat: body += [ "if bc:", " pc = (c.pc - 2) & 0xFFFF", " c.pc = pc", " c.wz = (pc + 1) & 0xFFFF", " f = (f & ~0x28) | ((pc >> 8) & 0x28)", " c._f = f", " c.q = f", " return 21", ] body += ["c._f = f", "c.q = f", "return 16"] page.add(op, reference, body) for op, reference, increment, repeat in ( (0xA1, "_op_cpi", True, False), (0xA9, "_op_cpd", False, False), (0xB1, "_op_cpir", True, True), (0xB9, "_op_cpdr", False, True), ): step = "+ 1" if increment else "- 1" body = [ "src = (c.h << 8) | c.l", "data = c.read_byte(src)", f"c.wz = (c.wz {step}) & 0xFFFF", f"hl = (src {step}) & 0xFFFF", "c.h = hl >> 8", "c.l = hl & 0xFF", "a = c.a", "result = (a - data) & 0xFF", "bc = (((c.b << 8) | c.c) - 1) & 0xFFFF", "c.b = bc >> 8", "c.c = bc & 0xFF", "half = (a ^ data ^ result) & 0x10", "n = result - (half >> 4)", "f = ((c._f & 0x01) | (result & 0x80) | (0 if result else 0x40) | half" " | (n & 0x08) | ((n & 0x02) << 4) | (0x04 if bc else 0) | 0x02)", ] if repeat: body += [ "if bc and result:", " pc = (c.pc - 2) & 0xFFFF", " c.pc = pc", " c.wz = (pc + 1) & 0xFFFF", " f = (f & ~0x28) | ((pc >> 8) & 0x28)", " c._f = f", " c.q = f", " return 21", ] body += ["c._f = f", "c.q = f", "return 16"] page.add(op, reference, body) # Block I/O (reference _block_ini/_block_outi, _post_in_o_r). post = [ " pc = (c.pc - 2) & 0xFFFF", " c.pc = pc", " c.wz = (pc + 1) & 0xFFFF", " f = (f & ~0x28) | ((pc >> 8) & 0x28)", # _post_in_o_r: X/Y again from PC's high byte, then PV/H corrections. " f = (f & ~0x28) | ((pc >> 8) & 0x28)", " if f & 0x01:", " if data & 0x80:", " f ^= PARITY[(b - 1) & 7] ^ 0x04", " f = (f & ~0x10) | (0x10 if (b & 0x0F) == 0 else 0)", " else:", " f ^= PARITY[(b + 1) & 7] ^ 0x04", " f = (f & ~0x10) | (0x10 if (b & 0x0F) == 0x0F else 0)", " else:", " f ^= PARITY[b & 7] ^ 0x04", " c._f = f", " c.q = f", " return 21", ] for op, reference, increment, repeat in ( (0xA2, "_op_ini", True, False), (0xAA, "_op_ind", False, False), (0xB2, "_op_inir", True, True), (0xBA, "_op_indr", False, True), ): body = [ "bc = (c.b << 8) | c.c", f"c.wz = (bc {'+ 1' if increment else '- 1'}) & 0xFFFF", "data = c.read_port(bc)", f"adj = (c.c {'+ 1' if increment else '- 1'}) & 0xFF", "c._io_data = data", "b = (c.b - 1) & 0xFF", "c.b = b", "hl = (c.h << 8) | c.l", "c.write_byte(hl, data)", f"hl = (hl {'+ 1' if increment else '- 1'}) & 0xFFFF", "c.h = hl >> 8", "c.l = hl & 0xFF", "total = adj + data", "f = (SZXY[b] | ((data >> 6) & 0x02) | PARITY[(total & 7) ^ b]" " | (0x11 if total > 0xFF else 0))", ] if repeat: body += ["if b:", *post] body += ["c._f = f", "c.q = f", "return 16"] page.add(op, reference, body) for op, reference, increment, repeat in ( (0xA3, "_op_outi", True, False), (0xAB, "_op_outd", False, False), (0xB3, "_op_otir", True, True), (0xBB, "_op_otdr", False, True), ): step = "+ 1" if increment else "- 1" body = [ "hl = (c.h << 8) | c.l", "data = c.read_byte(hl)", "c._io_data = data", f"hl = (hl {step}) & 0xFFFF", "c.h = hl >> 8", "l = hl & 0xFF", "c.l = l", "b = (c.b - 1) & 0xFF", "c.b = b", "bc = (b << 8) | c.c", "c.write_port(bc, data)", f"c.wz = (bc {step}) & 0xFFFF", "total = l + data", "f = (SZXY[b] | ((data >> 6) & 0x02) | PARITY[(total & 7) ^ b]" " | (0x11 if total > 0xFF else 0))", ] if repeat: body += ["if b:", *post] body += ["c._f = f", "c.q = f", "return 16"] page.add(op, reference, body) for op in range(0x100): if op not in page.functions: page.add(op, "_op_ed_nop", ["c.q = 0", "return 8"]) def build() -> str: main = Page("op", b"") main_page(main) # The prefixes: CB/ED fetch their sub-opcode (an M1: R moves); DD/FD # start a prefix run. main.add(0xCB, "_execute_cb", [*m1_fetch("op"), "return CB[op](c)"]) main.add(0xED, "_execute_ed", [*m1_fetch("op"), "return ED[op](c)"]) for prefix, name in ((0xDD, "DD"), (0xFD, "FD")): main.add( prefix, "_execute_index", [ *m1_fetch("op"), "if op == 0xDD or op == 0xFD or op == 0xED:", f" return _prefix_run(c, {prefix:#04x}, op)", f"return {name}[op](c)", ], ) cb = Page("cb", b"\xcb") cb_page(cb) ed = Page("ed", b"\xed") ed_page(ed) pages = [main, cb, ed] for ix, prefix, name in (("ix", 0xDD, "dd"), ("iy", 0xFD, "fd")): page = Page(name, bytes([prefix])) main_page(page, index=ix) index_page(page, ix) for op in (0xDD, 0xFD, 0xED): page.add(op, "_prefix_run", ["raise AssertionError('handled by _prefix_run')"]) icb = Page(f"{name}cb", bytes([prefix, 0xCB])) index_cb_page(icb, ix) pages += [page, icb] for page in pages: missing = [op for op in range(256) if op not in page.functions] if missing: raise ValueError(f"page {page.prefix}: missing {' '.join(f'{m:02X}' for m in missing)}") return render(pages) def m1_fetch(name: str) -> list[str]: """An opcode fetch: an M1 cycle, so R's low 7 bits count it.""" return [ "pc = c.pc", f"{name} = c.read_byte(pc)", "c.pc = (pc + 1) & 0xFFFF", "r = c.r", "c.r = (r & 0x80) | ((r + 1) & 0x7F)", ] HEADER = '''"""GENERATED by tools/gen_ops.py from the reference handlers. Do not edit. One function per opcode per page. Each comment names the instruction and the z80-python reference handler it transcribes; the reference's docstring there cites the manual page and the oracle that pins it. Regenerate with ``python tools/gen_ops.py``; tests/test_generated_ops.py fails if this file and the generator disagree. """ # ruff: noqa: E501, E701, E702, SIM102, SIM108, PLR2004, RUF100 from z80_python_fast._flags import PARITY, SZXY, SZXYP def _prefix_run(c, prefix, op): """A run of DD/FD prefixes, or DD/FD before ED (reference _execute_index). Each stray prefix is its own M1 (4 T-states, R+1, already counted); the last one decides the index register. An ED after any of them starts an ED instruction the prefix cannot touch (Young 3.7). """ stray = 0 while op == 0xDD or op == 0xFD: prefix = op pc = c.pc op = c.read_byte(pc) c.pc = (pc + 1) & 0xFFFF r = c.r c.r = (r & 0x80) | ((r + 1) & 0x7F) stray += 4 if op == 0xED: pc = c.pc op = c.read_byte(pc) c.pc = (pc + 1) & 0xFFFF r = c.r c.r = (r & 0x80) | ((r + 1) & 0x7F) return stray + 4 + ED[op](c) return stray + (DD if prefix == 0xDD else FD)[op](c) ''' def render(pages: list[Page]) -> str: out = [HEADER] label_operands = b"\x12\x34" for page in pages: for op in range(256): reference, body, args = page.functions[op] if page.prefix in ("ddcb", "fdcb"): data = page.label_bytes + b"\x05" + bytes([op]) else: data = page.label_bytes + bytes([op]) + label_operands if page.prefix == "op" and op in (0x10, 0x18, 0x20, 0x28, 0x30, 0x38): data = bytes([op, 0x12]) prefix = reference.startswith(("_execute", "_prefix")) text = "prefix" if prefix else label(data) out.append(f"\n\ndef {page.name(op)}({args}): # {text} -- {reference}\n") out.extend(f" {line}\n" for line in body) for page in pages: table = page.prefix.upper() if page.prefix != "op" else "MAIN" names = ", ".join(page.name(op) for op in range(256)) out.append(f"\n\n{table} = ({names})\n") return "".join(out) def main() -> int: source = build() if "--check" in sys.argv[1:]: if OUT.read_text() != source: print(f"{OUT} is stale; run python tools/gen_ops.py", file=sys.stderr) return 1 return 0 OUT.write_text(source) print(f"wrote {OUT} ({source.count(chr(10)):,} lines)") return 0 if __name__ == "__main__": raise SystemExit(main())