# SPDX-License-Identifier: MIT """Rung 6: directed tests, one or more per entry of docs/undocumented-behavior.md. Each test pins what the core does about one unknown (U) or contradiction (C) and names the source the expected values were written from: DS, RDS, GDS, VDS, NDS (tier 2), CL, LK, GF, GW, LT (tier 3), CAP (tier 1). Where no source decides, the test says it pins a default. The last test checks that every entry has one. The expected bus sequences are written out by hand from docs/timing.md, not taken from the core. """ import ast import random import re from pathlib import Path import pytest from w65c02_python import CMOS65C02, G65SC02, R65C02, W65C02S, Lynx2Cell from w65c02_python._alu import decimal_add, decimal_subtract from w65c02_python._dispatch import BIT_OPCODES, FORM_BYTES, opcodes_for ROOT = Path(__file__).resolve().parents[1] ROWS = (W65C02S, R65C02, G65SC02, Lynx2Cell) ROW_IDS = [row.__name__ for row in ROWS] N, V, B, D, I, Z, C = 0x80, 0x40, 0x10, 0x08, 0x04, 0x02, 0x01 ORG = 0x0200 class Machine: """64 KB of RAM around one CPU, recording every bus cycle of the last step. ``bus`` holds ``(kind, address, value)`` per cycle, ``pins`` the ``(sync, fetch)`` the callback saw. ``hook(machine, cycle, kind, address)`` runs inside each callback before the access (cycle counts from 1). """ def __init__(self, row: type = W65C02S, *program: int, at: int = ORG) -> None: self.memory = bytearray(0x10000) self.bus: list[tuple[str, int, int]] = [] self.pins: list[tuple[bool, bool]] = [] self.hook = None self.cpu = row(self.read_byte, self.write_byte) self.memory[at : at + len(program)] = bytes(program) self.cpu.pc = at self.cpu.s = 0xFD def read_byte(self, address: int) -> int: if self.hook: self.hook(self, len(self.bus) + 1, "r", address) value = self.memory[address] self.bus.append(("r", address, value)) self.pins.append((self.cpu.sync, self.cpu.fetch)) return value def write_byte(self, address: int, value: int) -> None: if self.hook: self.hook(self, len(self.bus) + 1, "w", address) self.memory[address] = value self.bus.append(("w", address, value)) self.pins.append((self.cpu.sync, self.cpu.fetch)) def step(self) -> int: self.bus.clear() self.pins.clear() cycles = self.cpu.step() assert cycles == len(self.bus), "step() returns the number of callbacks" return cycles def cycles(self) -> list[tuple[str, int]]: """The last step's bus as (kind, address).""" return [(kind, address) for kind, address, _value in self.bus] def vector(self, address: int, target: int) -> None: self.memory[address] = target & 0xFF self.memory[address + 1] = target >> 8 def r(address: int) -> tuple[str, int]: return ("r", address) def w(address: int) -> tuple[str, int]: return ("w", address) # --------------------------------------------------------------------------------------- # U1, U2, C4: reset # --------------------------------------------------------------------------------------- def reset(row: type) -> Machine: machine = Machine(row) machine.vector(0xFFFC, 0x8000) machine.cpu.pc = 0x1234 machine.cpu.s = 0xFD machine.cpu.p = 0x20 | D | N | C # I clear, D set: reset must set I and clear D machine.cpu.a, machine.cpu.x, machine.cpu.y = 0x11, 0x22, 0x33 machine.cpu.request_reset() return machine def test_u1_the_w65c02s_reset_reads_the_stack() -> None: """U1: no capture of a W65C02S reset exists; the default is three stack reads, as the captured R65C02 does (CAP). DS 3.11: seven cycles, I set, D cleared, nothing else.""" machine = reset(W65C02S) assert W65C02S.reset_writes_stack is False assert machine.step() == 7 assert machine.cycles() == [ r(0x1234), r(0x1234), r(0x01FD), r(0x01FC), r(0x01FB), r(0xFFFC), r(0xFFFD), ] # fmt: skip cpu = machine.cpu assert (cpu.pc, cpu.s) == (0x8000, 0xFA) assert cpu.p & I and not cpu.p & D assert (cpu.a, cpu.x, cpu.y) == (0x11, 0x22, 0x33) # DS 3.11: not initialised assert cpu.p & (N | C) == N | C def test_u1_the_r65c02_reset_reads_the_stack() -> None: """U1's captured neighbour (CAP, a BBC B's R65C02): RnW stays high through reset.""" machine = reset(R65C02) machine.step() assert [kind for kind, _ in machine.cycles()] == list("rrrrrrr") @pytest.mark.parametrize("row", [G65SC02, Lynx2Cell], ids=lambda row: row.__name__) def test_u2_the_lynx_rows_write_pc_and_p_at_reset(row: type) -> None: """U2: nothing says what the Lynx cells do at reset; the default is the captured G65SC12's three writes of PCH, PCL and P with B clear (CAP: `$AF` pushed; GDS Table V "Writes program counter and status register to stack").""" machine = reset(row) assert row.reset_writes_stack is True assert machine.step() == 7 assert machine.cycles() == [ r(0x1234), r(0x1234), w(0x01FD), w(0x01FC), w(0x01FB), r(0xFFFC), r(0xFFFD), ] # fmt: skip assert machine.memory[0x01FB:0x01FE] == bytes([0x20 | D | N | C, 0x34, 0x12]) assert (machine.cpu.pc, machine.cpu.s) == (0x8000, 0xFA) assert machine.cpu.p & I and not machine.cpu.p & D @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_c4_reset_takes_seven_cycles_not_six(row: type) -> None: """C4: GDS, VDS and NDS say six cycles; CAP shows seven on both captured parts, counted from the cycle with SYNC high, and DS 3.11 and RDS say seven.""" machine = reset(row) assert machine.step() == 7 assert machine.pins[0] == (True, True) # CAP: SYNC is high in the first cycle assert all(not sync for sync, _fetch in machine.pins[1:]) def test_reset_ends_wai_and_stp_and_does_not_poll() -> None: """DS 3.11 and Table 7-1: reset restarts a stopped processor. The frame's rule (U5): the first instruction after reset runs before a pending interrupt is taken.""" machine = Machine(W65C02S, 0xDB) # STP machine.vector(0xFFFC, 0x8000) machine.vector(0xFFFA, 0x9000) machine.memory[0x8000] = 0xEA machine.step() assert machine.cpu.stopped and machine.cpu.halted machine.cpu.request_reset() machine.cpu.request_non_maskable_interrupt() machine.step() assert not machine.cpu.stopped and not machine.cpu.halted and machine.cpu.pc == 0x8000 machine.step() assert machine.cpu.pc == 0x8001 # the NOP at the reset vector ran first machine.step() assert machine.cpu.pc == 0x9000 # --------------------------------------------------------------------------------------- # U3, C3, C5, C7, C8: $CB and $DB # --------------------------------------------------------------------------------------- @pytest.mark.parametrize("row", [R65C02, G65SC02, Lynx2Cell], ids=lambda row: row.__name__) @pytest.mark.parametrize("opcode", [0xCB, 0xDB]) def test_u3_cb_and_db_are_one_cycle_nops_without_wai_and_stp(row: type, opcode: int) -> None: """U3: GDS Table V, VDS Table 2 and NDS say `XB`: one byte, one cycle; CL's grid the same; Dormann's test built with `wdc_op = 0` expects one-byte NOPs. No capture executes them: a default.""" machine = Machine(row, opcode, 0xEA) before = machine.cpu.capture_state() assert machine.step() == 1 assert machine.cycles() == [r(ORG)] assert machine.cpu.pc == ORG + 1 and not machine.cpu.halted after = machine.cpu.capture_state() assert (after.a, after.x, after.y, after.s, after.p) == ( before.a, before.x, before.y, before.s, before.p, ) # fmt: skip def test_c3_the_corpus_gives_cb_two_cycles_and_db_two_bytes() -> None: """C3: SST's Rockwell and Synertek sets have `$CB` as 1 byte, 2 cycles and `$DB` as 2 bytes, 4 cycles; the data sheets (GDS, VDS, NDS; tier 2) and CL say 1 byte, 1 cycle, and the core follows them. Rung 1 counts the 40,000 cases.""" for row in (R65C02, G65SC02): table = opcodes_for(row) for opcode in (0xCB, 0xDB): _handler, _mode, mnemonic, form, cycles = table[opcode] assert (mnemonic, FORM_BYTES[form], cycles) == ("NOP", 1, 1) def test_c5_the_r65c02_has_no_wai_or_stp() -> None: """C5: RDS's opcode matrix has neither, and CL and GW say WDC only; MAME's `r65c02` device has both. A `$CB` on the R65C02 row does not wait.""" assert R65C02.wai_stp is False machine = Machine(R65C02, 0xCB, 0xDB, 0xA9, 0x55) machine.step() machine.step() machine.step() assert machine.cpu.a == 0x55 and not machine.cpu.halted def test_c7_the_vl65nc02_is_the_178_opcode_part() -> None: """C7: VDS's feature list says 178 opcodes and its note that columns 7 and F are NOPs in the 65NC02; its shared tables list more. The G65SC02 row is the 178, with `$CB`/`$DB` by its Table 2 (`XB`: one byte, one cycle).""" table = opcodes_for(G65SC02) documented = [opcode for opcode, row in table.items() if not row[0].startswith("nop_")] assert len(documented) == 178 for opcode in (*BIT_OPCODES, 0xCB, 0xDB): assert table[opcode][2:] == ("NOP", "imp", 1) def test_c8_cb_and_db_are_nops_on_both_lynx_rows_and_a_board_can_switch_them() -> None: """C8: Handy runs `$CB`/`$DB` as WAI and STP on the Lynx; MAME, Felix and VDS Table 2 say NOPs. Core: NOPs, and `wai_stp` is a row attribute a board can turn on (the Lynx's request 4: "WAI/STP switchable, default off").""" for row in (G65SC02, Lynx2Cell): machine = Machine(row, 0xCB) assert machine.step() == 1 and not machine.cpu.waiting class LynxWithWai(Lynx2Cell): wai_stp = True machine = Machine(LynxWithWai, 0xCB) assert machine.step() == 3 and machine.cpu.waiting assert Machine(Lynx2Cell, 0xCB).step() == 1 # the row it was made from is unchanged # --------------------------------------------------------------------------------------- # U4, C9, C13 to C18: the bus of every sequence # --------------------------------------------------------------------------------------- P0 = ORG # the opcode's address in the cases below #: (name, program bytes, register settings, memory settings, expected bus). X = $10, Y = $20 #: unless set; `ptr` cells are set through memory. BUS_CASES = [ ("LDA #", (0xA9, 0x44), {}, {}, [r(P0), r(P0 + 1)]), ("LDA zp", (0xA5, 0x44), {}, {}, [r(P0), r(P0 + 1), r(0x44)]), ("STA zp", (0x85, 0x44), {}, {}, [r(P0), r(P0 + 1), w(0x44)]), ("LDA zp,X", (0xB5, 0x44), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x54)]), ("LDA zp,X wraps", (0xB5, 0xF8), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x08)]), ("STA zp,X", (0x95, 0x44), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), w(0x54)]), ("LDX zp,Y", (0xB6, 0x44), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x64)]), ("LDA abs", (0xAD, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1234)]), ("LDA abs,X", (0xBD, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244)]), ( "LDA abs,X across a page", (0xBD, 0xF8, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1308)], ), ( "LDA abs,Y across a page", (0xB9, 0xF8, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1318)], ), ( "STA abs,X", (0x9D, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244), w(0x1244)], ), ( "STA abs,X across a page", (0x9D, 0xF8, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), w(0x1308)], ), ( "STA abs,Y", (0x99, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1254), w(0x1254)], ), ( "STZ abs,X", (0x9E, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244), w(0x1244)], ), ( "LDA (zp,X)", (0xA1, 0x44), {}, {0x54: 0x34, 0x55: 0x12}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x54), r(0x55), r(0x1234)], ), ( "STA (zp,X)", (0x81, 0x44), {}, {0x54: 0x34, 0x55: 0x12}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x54), r(0x55), w(0x1234)], ), ( "LDA (zp),Y", (0xB1, 0x44), {}, {0x44: 0x34, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x1254)], ), ( "LDA (zp),Y across a page", (0xB1, 0x44), {}, {0x44: 0xF8, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x45), r(0x1318)], ), ( "STA (zp),Y", (0x91, 0x44), {}, {0x44: 0x34, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x45), w(0x1254)], ), ( "STA (zp),Y across a page", (0x91, 0x44), {}, {0x44: 0xF8, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x45), w(0x1318)], ), ( "LDA (zp)", (0xB2, 0x44), {}, {0x44: 0x34, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x1234)], ), ( "LDA (zp) with the pointer at $FF", (0xB2, 0xFF), {}, {0xFF: 0x34, 0x00: 0x12}, [r(P0), r(P0 + 1), r(0xFF), r(0x00), r(0x1234)], ), ("ASL zp", (0x06, 0x44), {}, {}, [r(P0), r(P0 + 1), r(0x44), r(0x44), w(0x44)]), ( "ASL zp,X", (0x16, 0x44), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x54), r(0x54), w(0x54)], ), ( "ASL abs", (0x0E, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1234), r(0x1234), w(0x1234)], ), ( "ASL abs,X", (0x1E, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244), r(0x1244), w(0x1244)], ), ( "ASL abs,X across a page", (0x1E, 0xF8, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1308), r(0x1308), w(0x1308)], ), ( "INC abs,X", (0xFE, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244), r(0x1244), r(0x1244), w(0x1244)], ), ( "DEC abs,X across a page", (0xDE, 0xF8, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1308), r(0x1308), w(0x1308)], ), ("TSB zp", (0x04, 0x44), {}, {}, [r(P0), r(P0 + 1), r(0x44), r(0x44), w(0x44)]), ( "TRB abs", (0x1C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1234), r(0x1234), w(0x1234)], ), ("INX", (0xE8,), {}, {}, [r(P0), r(P0 + 1)]), ("INC A", (0x1A,), {}, {}, [r(P0), r(P0 + 1)]), ("NOP", (0xEA,), {}, {}, [r(P0), r(P0 + 1)]), ("PHA", (0x48,), {}, {}, [r(P0), r(P0 + 1), w(0x01FD)]), ("PHX", (0xDA,), {}, {}, [r(P0), r(P0 + 1), w(0x01FD)]), ("PLA", (0x68,), {}, {}, [r(P0), r(P0 + 1), r(0x01FD), r(0x01FE)]), ("PLY", (0x7A,), {}, {}, [r(P0), r(P0 + 1), r(0x01FD), r(0x01FE)]), ("PLP", (0x28,), {}, {0x01FE: 0x20}, [r(P0), r(P0 + 1), r(0x01FD), r(0x01FE)]), ( "JSR", (0x20, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(0x01FD), w(0x01FD), w(0x01FC), r(P0 + 2)], ), ( "RTS", (0x60,), {}, {0x01FE: 0x33, 0x01FF: 0x12}, [r(P0), r(P0 + 1), r(0x01FD), r(0x01FE), r(0x01FF), r(0x1233)], ), ( "RTI", (0x40,), {"s": 0xFC}, {0x01FD: 0x20, 0x01FE: 0x34, 0x01FF: 0x12}, [r(P0), r(P0 + 1), r(0x01FC), r(0x01FD), r(0x01FE), r(0x01FF)], ), ("JMP abs", (0x4C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2)]), ( "JMP (abs)", (0x6C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1234), r(0x1235)], ), ( "JMP (abs) at $xxFF", (0x6C, 0xFF, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x12FF), r(0x1300)], ), ( "JMP (abs,X)", (0x7C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1244), r(0x1245)], ), ("BNE not taken", (0xD0, 0x10), {"p": 0x20 | Z}, {}, [r(P0), r(P0 + 1)]), ("BNE taken", (0xD0, 0x10), {"p": 0x20}, {}, [r(P0), r(P0 + 1), r(P0 + 2)]), ( "BNE taken across a page", (0xD0, 0x80), {"p": 0x20}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2)], ), ("BRA", (0x80, 0x10), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2)]), ("BRA across a page", (0x80, 0x80), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2)]), ("BIT #", (0x89, 0x44), {}, {}, [r(P0), r(P0 + 1)]), ("BIT abs,X", (0x3C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1244)]), ("STZ zp", (0x64, 0x44), {}, {}, [r(P0), r(P0 + 1), w(0x44)]), ("NOP #", (0x02, 0x44), {}, {}, [r(P0), r(P0 + 1)]), ("NOP one cycle", (0x03,), {}, {}, [r(P0)]), ("NOP zp", (0x44, 0x44), {}, {}, [r(P0), r(P0 + 1), r(0x44)]), ("NOP zp,X", (0x54, 0x44), {}, {}, [r(P0), r(P0 + 1), r(P0 + 1), r(0x54)]), ("NOP abs", (0xDC, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0x1234)]), ( "NOP $5C", (0x5C, 0x34, 0x12), {}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(0xFF34), r(0xFFFF), r(0xFFFF), r(0xFFFF), r(0xFFFF)], ), ( "ADC # in decimal", (0x69, 0x44), {"p": 0x20 | D}, {}, [r(P0), r(P0 + 1), r(P0 + 2)], ), ( "ADC zp in decimal", (0x65, 0x44), {"p": 0x20 | D}, {}, [r(P0), r(P0 + 1), r(0x44), r(P0 + 2)], ), ( "SBC abs,X in decimal across a page", (0xFD, 0xF8, 0x12), {"p": 0x20 | D}, {}, [r(P0), r(P0 + 1), r(P0 + 2), r(P0 + 2), r(0x1308), r(P0 + 3)], ), ( "SBC (zp),Y in decimal across a page", (0xF1, 0x44), {"p": 0x20 | D}, {0x44: 0xF8, 0x45: 0x12}, [r(P0), r(P0 + 1), r(0x44), r(0x45), r(0x45), r(0x1318), r(P0 + 2)], ), ] @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) @pytest.mark.parametrize("case", BUS_CASES, ids=[case[0] for case in BUS_CASES]) def test_u4_the_bus_of_every_sequence(row: type, case: tuple) -> None: """U4: every cycle's direction and address, as docs/timing.md gives them. The counts and directions are CAP's; the dummy addresses are CAP's (rung 4) on the two captured parts and assumed the same on the W65C02S and the Lynx II's cell.""" _name, program, registers, memory, expected = case machine = Machine(row, *program) machine.cpu.x, machine.cpu.y = 0x10, 0x20 for name, value in registers.items(): setattr(machine.cpu, name, value) for address, value in memory.items(): machine.memory[address] = value assert machine.step() == len(expected) assert machine.cycles() == expected def test_c9_dummy_reads_follow_the_captures_not_either_emulator() -> None: """C9: SST and MAME's two patterns disagree about dummy addresses and cite nothing. CAP (rung 4) decides: `zp,X` re-reads PC+1 (MAME's w65c02s, not SST), a read-modify-write reads its operand twice (SST, not w65c02s's `ea+1`), a pull reads the stack before the increment (SST, not w65c02s's second read of PC).""" machine = Machine(G65SC02, 0xB5, 0x44, 0xE6, 0x80, 0x68) machine.cpu.x = 0x10 machine.step() assert machine.cycles()[2] == r(ORG + 1) machine.step() assert machine.cycles()[2:] == [r(0x80), r(0x80), w(0x80)] machine.step() assert machine.cycles()[2:] == [r(0x01FD), r(0x01FE)] def test_c13_the_decimal_cycle_reads_the_next_opcode() -> None: """C13: CAP, both parts: in every decimal ADC and SBC the extra cycle's byte is the opcode fetched next. SST re-reads the operand (for the immediate forms, a constant address).""" machine = Machine(R65C02, 0xF8, 0x6D, 0x34, 0x12, 0xEA) # SED; ADC $1234; NOP machine.memory[0x1234] = 0x19 machine.cpu.a = 0x23 machine.step() assert machine.step() == 5 # DS Table 7-1: one additional cycle assert machine.bus[-1] == ("r", ORG + 4, 0xEA) assert machine.pins[-1] == (False, True) # a read at PC: the instruction stream assert machine.cpu.a == 0x42 def test_c14_an_indexed_store_within_a_page_reads_its_own_address() -> None: """C14: CAP, both parts: the extra cycle of `STA abs,X`, `STA abs,Y`, `STZ abs,X` and of `INC`/`DEC abs,X` reads the operand's address when no page is crossed, the last instruction byte when one is (DS Table 7-1). SST always re-reads PC+2.""" for opcode in (0x9D, 0x9E, 0xDE, 0xFE): machine = Machine(G65SC02, opcode, 0x00, 0x30) machine.cpu.x = 0x7F machine.step() assert machine.cycles()[3] == r(0x307F), hex(opcode) machine = Machine(G65SC02, opcode, 0x81, 0x30) machine.cpu.x = 0x7F machine.step() assert machine.cycles()[3] == r(ORG + 2), hex(opcode) def test_c15_the_extra_cycle_of_zp_indirect_y_rereads_the_pointer() -> None: """C15: CAP, both parts: `(zp),Y`'s extra cycle reads the pointer's high byte again (SST: PC+1); in every execution of `STA (zp),Y`, across a page for a read.""" machine = Machine(R65C02, 0x91, 0xFF, 0xB1, 0xFF) machine.memory[0xFF], machine.memory[0x00] = 0x80, 0x40 # the pointer wraps in page zero machine.cpu.y = 0x7F machine.step() assert machine.cycles()[4] == r(0x00) machine.step() assert len(machine.bus) == 5 # no page crossed: no extra cycle machine.cpu.pc = ORG + 2 machine.cpu.y = 0x80 machine.step() assert machine.cycles() == [r(ORG + 2), r(ORG + 3), r(0xFF), r(0x00), r(0x00), r(0x4100)] def test_c16_a_branch_across_a_page_reads_the_next_opcode_twice() -> None: """C16: CAP, both parts: cycles 3 and 4 of a branch taken across a page return the same byte, the next opcode's. SST reads the old page with the target's low byte.""" machine = Machine(G65SC02, 0xF0, 0x7F, at=0x02F0) machine.cpu.p |= Z assert machine.step() == 4 assert machine.cycles() == [r(0x02F0), r(0x02F1), r(0x02F2), r(0x02F2)] assert machine.cpu.pc == 0x0371 def test_c17_the_indirect_jumps_reread_the_operand_then_read_the_pointer() -> None: """C17: CAP, both parts: `JMP (abs)` is PC+2 again, pointer, pointer+1, with the carry into the page (DS Table 7-1 "Jump indirect, operand = XXFF": fixed, one more cycle); `JMP (abs,X)` re-reads PC+2. SST orders `JMP (abs)` differently and re-reads PC+1 in `JMP (abs,X)`.""" machine = Machine(R65C02, 0x6C, 0xFF, 0x30) machine.memory[0x30FF], machine.memory[0x3100], machine.memory[0x3000] = 0x34, 0x12, 0x99 assert machine.step() == 6 assert machine.cycles()[3:] == [r(ORG + 2), r(0x30FF), r(0x3100)] assert machine.cpu.pc == 0x1234 # not $9934: the NMOS bug is fixed (LT `cpu` test 5) machine = Machine(R65C02, 0x7C, 0xF0, 0x30) machine.cpu.x = 0x20 machine.memory[0x3110], machine.memory[0x3111] = 0x78, 0x56 assert machine.step() == 6 assert machine.cycles()[3:] == [r(ORG + 2), r(0x3110), r(0x3111)] assert machine.cpu.pc == 0x5678 def test_c18_zero_page_indexing_rereads_the_operand_byte() -> None: """C18: CAP, both parts: the third cycle of `zp,X`, `zp,Y` and `(zp,X)` reads the operand byte (PC+1) again. SST reads the unindexed zero-page address, as the NMOS part does.""" for program in ((0xB5, 0x44), (0xB6, 0x44), (0xA1, 0x44), (0x74, 0x44), (0x34, 0x44)): machine = Machine(G65SC02, *program) machine.step() assert machine.cycles()[2] == r(ORG + 1), hex(program[0]) # --------------------------------------------------------------------------------------- # U5, C6: the poll # --------------------------------------------------------------------------------------- def interrupts(row: type, *program: int) -> Machine: machine = Machine(row, *program) machine.vector(0xFFFE, 0x9000) machine.vector(0xFFFA, 0xA000) for address in (0x9000, 0xA000): machine.memory[address : address + 4] = b"\xea\xea\xea\xea" machine.cpu.p = 0x20 # I clear return machine @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_u5_cli_admits_a_pending_irq_only_after_the_next_instruction(row: type) -> None: """U5: LT `cpu` test 1 (real Lynxes): with IRQ pending, CLI is followed by one more instruction before the interrupt. The frame's rule (the NMOS part's) gives the same.""" machine = interrupts(row, 0x58, 0xE8, 0xE8) # CLI; INX; INX machine.cpu.p |= I machine.cpu.request_maskable_interrupt() machine.step() assert machine.cpu.pc == ORG + 1 machine.step() assert machine.cpu.x == 1 # the instruction after CLI ran assert machine.step() == 7 assert machine.cpu.pc == 0x9000 assert machine.memory[0x01FC] | machine.memory[0x01FD] << 8 == ORG + 2 def test_u5_an_irq_polled_before_sei_is_taken_after_it() -> None: """U5 (a default: the NMOS rule, no CMOS source): SEI's own poll sees I clear, so an IRQ that arrived by SEI's first cycle is taken after SEI, with I set in the pushed P.""" machine = interrupts(G65SC02, 0x78, 0xEA) # SEI; NOP def raise_in_first_cycle(machine: Machine, cycle: int, kind: str, address: int) -> None: if cycle == 1: machine.cpu.request_maskable_interrupt() machine.hook = raise_in_first_cycle machine.step() machine.hook = None assert machine.step() == 7 assert machine.cpu.pc == 0x9000 assert machine.memory[0x01FB] & I def test_u5_plp_delays_the_new_i_like_cli() -> None: """U5 (the frame's rule): PLP clearing I admits a pending IRQ after the next instruction.""" machine = interrupts(G65SC02, 0x28, 0xE8, 0xE8) # PLP; INX; INX machine.cpu.p |= I machine.memory[0x01FE] = 0x20 # the P pulled: I clear machine.cpu.request_maskable_interrupt() machine.step() machine.step() assert machine.cpu.x == 1 machine.step() assert machine.cpu.pc == 0x9000 def test_u5_a_request_in_the_last_cycle_waits_one_instruction() -> None: """U5 (the frame's rule): requests are sampled at the end of the second-to-last cycle, so one that arrives in the last cycle is taken after the following instruction.""" machine = interrupts(R65C02, 0xA5, 0x10, 0xE8, 0xE8) # LDA $10; INX; INX def raise_in_cycle(wanted: int): def hook(machine: Machine, cycle: int, kind: str, address: int) -> None: if cycle == wanted: machine.cpu.request_maskable_interrupt() return hook machine.hook = raise_in_cycle(3) machine.step() machine.hook = None machine.step() assert machine.cpu.x == 1 machine.step() assert machine.cpu.pc == 0x9000 machine = interrupts(R65C02, 0xA5, 0x10, 0xE8, 0xE8) machine.hook = raise_in_cycle(2) machine.step() machine.hook = None machine.step() assert machine.cpu.pc == 0x9000 and machine.cpu.x == 0 def test_u5_a_taken_branch_polls_like_any_instruction() -> None: """U5 (a default): the NMOS part's taken branch within a page polls a cycle early, so a request in its second cycle waits an instruction. Nothing says the CMOS part does (GW: "there seems to be a difference between NMOS and CMOS in this area"); the core has no exception: the request is taken right after the branch.""" machine = interrupts(G65SC02, 0x80, 0x02, 0xEA, 0xEA, 0xE8) # BRA +2 def hook(machine: Machine, cycle: int, kind: str, address: int) -> None: if cycle == 2: machine.cpu.request_maskable_interrupt() machine.hook = hook assert machine.step() == 3 machine.hook = None machine.step() assert machine.cpu.pc == 0x9000 and machine.cpu.x == 0 def test_u5_d_is_cleared_and_i_set_by_an_interrupt_entry() -> None: """DS Table 7-1 "Decimal flag ... (D=0) after reset and interrupts"; LT `cpu` test 2. The pushed P keeps D and has B clear (CL section 6); the entry is seven cycles with SYNC high in the first (CAP).""" machine = interrupts(G65SC02, 0xEA) machine.cpu.p |= D | C machine.cpu.request_maskable_interrupt() assert machine.step() == 7 assert machine.cycles() == [ r(ORG), r(ORG), w(0x01FD), w(0x01FC), w(0x01FB), r(0xFFFE), r(0xFFFF), ] # fmt: skip assert machine.pins[0] == (True, True) and machine.pins[1] == (False, True) assert machine.memory[0x01FB] == 0x20 | D | C assert machine.cpu.p == 0x20 | I | C machine.cpu.clear_maskable_interrupt() machine.cpu.request_non_maskable_interrupt() machine.step() # the frame's rule: the handler's first instruction runs assert machine.step() == 7 assert machine.cycles()[5:] == [r(0xFFFA), r(0xFFFB)] assert not machine.cpu.non_maskable_interrupt_pending # the edge is used up @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_c6_brk_with_an_interrupt_pending_runs_as_brk(row: type) -> None: """C6: DS Table 7-1 (and GDS, RDS, NDS): "BRK is executed, and then interrupt is executed". MAME pushes B clear with an NMI pending. Core: B set, `$FFFE`, then the NMI, after one instruction of the BRK handler (U5: BRK does not poll, the frame's rule).""" machine = interrupts(row, 0x00, 0xFF) machine.cpu.p |= D def nmi_in_second_cycle(machine: Machine, cycle: int, kind: str, address: int) -> None: if cycle == 2: machine.cpu.request_non_maskable_interrupt() machine.hook = nmi_in_second_cycle assert machine.step() == 7 machine.hook = None assert machine.cycles() == [ r(ORG), r(ORG + 1), w(0x01FD), w(0x01FC), w(0x01FB), r(0xFFFE), r(0xFFFF), ] # fmt: skip assert machine.memory[0x01FB] == 0x20 | B | D # B set, D as it was assert machine.memory[0x01FC] | machine.memory[0x01FD] << 8 == ORG + 2 # two bytes (LT 4) assert machine.cpu.pc == 0x9000 and machine.cpu.p == 0x20 | I # D cleared (CL section 6) machine.step() assert machine.cpu.pc == 0x9001 machine.step() assert machine.cpu.pc == 0xA000 # --------------------------------------------------------------------------------------- # U6: WAI and STP # --------------------------------------------------------------------------------------- def test_u6_wai_waits_one_cycle_a_step_and_the_step_that_finds_an_irq_takes_it() -> None: """U6 (a default): GF saw WAI as three cycles and "the next opcode repeated" while waiting. Each waiting step is one read of the next opcode's address; the first step that finds a request is the interrupt entry itself. How many cycles a real chip takes to wake is not known (GW: "no more than 1 cycle" with I set).""" machine = interrupts(W65C02S, 0xCB, 0xE8) # WAI; INX assert machine.step() == 3 assert machine.cycles() == [r(ORG), r(ORG + 1), r(ORG + 1)] assert machine.cpu.waiting and machine.cpu.halted for _ in range(3): assert machine.step() == 1 assert machine.cycles() == [r(ORG + 1)] assert machine.pins == [(False, True)] machine.cpu.request_maskable_interrupt() assert machine.step() == 7 assert not machine.cpu.waiting and machine.cpu.pc == 0x9000 assert machine.memory[0x01FC] | machine.memory[0x01FD] << 8 == ORG + 1 # returns after WAI def test_u6_wai_with_i_set_continues_with_the_next_instruction() -> None: """DS 3.4 and CL section 5: with I set, an IRQ ends the wait and execution continues with the next instruction, with no vectoring. An NMI ends it through its vector.""" machine = interrupts(W65C02S, 0xCB, 0xE8, 0xCB) # WAI; INX; WAI machine.cpu.p |= I machine.step() machine.step() machine.cpu.request_maskable_interrupt() assert machine.step() == 2 # the INX itself assert machine.cpu.x == 1 and machine.cpu.pc == ORG + 2 and not machine.cpu.waiting machine.cpu.clear_maskable_interrupt() machine.step() assert machine.cpu.waiting machine.cpu.request_non_maskable_interrupt() assert machine.step() == 7 assert machine.cpu.pc == 0xA000 def test_u6_wai_does_not_wait_when_irq_is_already_low() -> None: """GF: "if IRQ is already asserted, WAI is a three-cycle instruction".""" machine = interrupts(W65C02S, 0xCB, 0xE8) machine.cpu.p |= I machine.cpu.request_maskable_interrupt() assert machine.step() == 3 assert not machine.cpu.waiting and not machine.cpu.halted machine.step() assert machine.cpu.x == 1 def test_u6_a_request_made_in_a_waiting_cycle_ends_the_wait() -> None: """A board's devices run inside the callbacks: an IRQ raised during a waiting cycle is found by the next step.""" machine = interrupts(W65C02S, 0xCB, 0xE8) machine.step() def hook(machine: Machine, cycle: int, kind: str, address: int) -> None: machine.cpu.request_maskable_interrupt() machine.hook = hook assert machine.step() == 1 machine.hook = None assert machine.step() == 7 and machine.cpu.pc == 0x9000 def test_stp_stops_until_reset() -> None: """DS Table 6-4 and CL section 5: STP stops the processor until reset; GF: the bus shows the next opcode's address. Interrupts do not restart it.""" machine = interrupts(W65C02S, 0xDB, 0xE8) assert machine.step() == 3 assert machine.cycles() == [r(ORG), r(ORG + 1), r(ORG + 1)] machine.cpu.request_maskable_interrupt() machine.cpu.request_non_maskable_interrupt() for _ in range(3): assert machine.step() == 1 and machine.cycles() == [r(ORG + 1)] assert machine.cpu.stopped and machine.cpu.x == 0 # --------------------------------------------------------------------------------------- # U7: one-cycle NOPs # --------------------------------------------------------------------------------------- @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_u7_no_interrupt_is_taken_directly_after_a_one_cycle_nop(row: type) -> None: """U7: CL section 9 (Laughton's bench): "an interrupt sequence will never begin immediately after a one-cycle NOP ... even multiple consecutive one-cycle NOPs will jointly merge execution with whatever non-one-cycle-NOP instruction is eventually encountered". LT `cpu` test 8 expects the same of real Lynxes.""" # CLI with an IRQ pending, then five one-cycle NOPs: CLI admits the IRQ after the # next instruction, and that instruction is not over until the block's end. machine = interrupts(row, 0x58, 0x03, 0x0B, 0x13, 0x1B, 0x23, 0xE8, 0xE8) machine.cpu.p |= I machine.cpu.request_maskable_interrupt() machine.step() for _ in range(5): assert machine.step() == 1 assert machine.cpu.pc == ORG + 6 machine.step() assert machine.cpu.x == 1 # the instruction after the block ran assert machine.step() == 7 and machine.cpu.pc == 0x9000 assert machine.memory[0x01FC] | machine.memory[0x01FD] << 8 == ORG + 7 def test_u7_the_default_is_a_setting() -> None: """U7's default is named: with `one_cycle_nops_poll` on, the NOP polls like any other instruction, and the interrupt CLI admitted begins right after it.""" assert CMOS65C02.one_cycle_nops_poll is False class Polling(G65SC02): one_cycle_nops_poll = True machine = interrupts(Polling, 0x58, 0x03, 0x0B, 0xE8) machine.cpu.p |= I machine.cpu.request_maskable_interrupt() machine.step() assert machine.step() == 1 assert machine.step() == 7 and machine.cpu.pc == 0x9000 assert machine.memory[0x01FC] | machine.memory[0x01FD] << 8 == ORG + 2 # --------------------------------------------------------------------------------------- # U8, U10, U11, U13: the rows # --------------------------------------------------------------------------------------- def test_u8_there_are_four_rows_and_a_board_adds_its_own() -> None: """U8: early WDC, Synertek and NCR parts get no row of their own; a board starts from `G65SC02` and sets attributes.""" import w65c02_python rows = {name for name in w65c02_python.__all__ if name not in ("CMOS65C02", "CPUState")} assert rows == {"W65C02S", "R65C02", "G65SC02", "Lynx2Cell"} class EarlyWdc(G65SC02): wai_stp = True reset_writes_stack = False machine = Machine(EarlyWdc, 0x07, 0xCB) assert machine.step() == 1 # still no bit instructions assert machine.step() == 3 and machine.cpu.waiting def test_u10_the_lynx_i_cell_is_the_g65sc02_row() -> None: """U10: that Mikey's cell is the VL65NC02 is an inference from LS ("the VTI specification"); LT `cpu` test 7 shows the Lynx I's bit opcodes are one-byte NOPs, as VDS says of the 65NC02. The Lynx I's row is `G65SC02`; the Lynx II's is `Lynx2Cell`.""" assert (G65SC02.bit_instructions, G65SC02.wai_stp) == (False, False) assert (Lynx2Cell.bit_instructions, Lynx2Cell.wai_stp) == (True, False) assert Lynx2Cell.reset_writes_stack == G65SC02.reset_writes_stack @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_u11_decimal_results_are_the_same_on_every_row(row: type) -> None: """U11: BC Appendix A is stated for "the 65C02" and CAP confirms it on two parts; the others are assumed the same. CL section 8's example: `SED; SEC; LDA #$20; SBC #$0F` leaves $0B on a 65C02 ($1B on the NMOS part).""" machine = Machine(row, 0xF8, 0x38, 0xA9, 0x20, 0xE9, 0x0F) for _ in range(3): machine.step() assert machine.step() == 3 # one more cycle in decimal mode assert machine.cpu.a == 0x0B assert machine.cpu.p & C and not machine.cpu.p & (N | Z) def test_u11_decimal_flags_are_valid() -> None: """DS Table 7-1 "Flags after decimal operation: valid flags": N and Z are the decimal result's (CL section 8); V is as on the NMOS part (CL section 8); C is the decimal carry.""" machine = Machine(G65SC02, 0xF8, 0x18, 0xA9, 0x99, 0x69, 0x01) # 99 + 1 = 00, carry for _ in range(4): machine.step() assert machine.cpu.a == 0x00 assert machine.cpu.p & Z and machine.cpu.p & C and not machine.cpu.p & N machine = Machine(G65SC02, 0xF8, 0x18, 0xA9, 0x79, 0x69, 0x01) # 79 + 1 = 80 for _ in range(4): machine.step() assert machine.cpu.a == 0x80 assert machine.cpu.p & N and machine.cpu.p & V and not machine.cpu.p & (Z | C) def test_u11_the_decimal_functions_are_pure_and_total() -> None: """BC Appendix A, sequences 1 and 4, for all 131,072 inputs each: valid BCD operands give the decimal sum and difference.""" for a in range(256): for operand in range(256): for carry in (0, 1): result, carry_out = decimal_add(a, operand, carry) assert 0 <= result <= 0xFF and carry_out in (0, 1) difference, borrow = decimal_subtract(a, operand, carry) assert 0 <= difference <= 0xFF and borrow in (0, 1) if a & 0x0F < 10 and a < 0xA0 and operand & 0x0F < 10 and operand < 0xA0: left = (a >> 4) * 10 + (a & 0x0F) right = (operand >> 4) * 10 + (operand & 0x0F) total = left + right + carry assert result == (total % 100 // 10) << 4 | total % 10 assert carry_out == total // 100 total = left - right - (1 - carry) assert difference == (total % 100 // 10) << 4 | total % 10 assert borrow == (total >= 0) def test_u13_the_core_has_no_set_overflow_input() -> None: """U13: SOB, VPB, MLB and BE are not modelled. A board that needs SOB sets V between steps.""" machine = Machine(W65C02S, 0x70, 0x10) # BVS +16 assert not hasattr(machine.cpu, "set_overflow") machine.cpu.p |= V machine.step() assert machine.cpu.pc == ORG + 0x12 # --------------------------------------------------------------------------------------- # U9, C1, C10, C11: the NOPs and the timing exceptions # --------------------------------------------------------------------------------------- @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_c1_5c_takes_eight_cycles(row: type) -> None: """C1: DS Table 7-1, GDS, VDS, NDS and CL: 3 bytes, 8 cycles; CAP: 8 on the G65SC12 and on the R65C02. SST says 4.""" machine = Machine(row, 0x5C, 0x34, 0x12, 0xEA) assert machine.step() == 8 assert machine.cpu.pc == ORG + 3 assert all(kind == "r" for kind, _ in machine.cycles()) def test_u9_5c_reads_ffxx_then_ffff() -> None: """U9: LK (Laughton's observation of one chip): `$5C` reads `$FF00 + low operand`, then `$FFFF` four times. CAP: the last four bytes are `$FFFF`'s in every execution. A default for the parts not captured; "pc" is the other reading.""" assert CMOS65C02.nop_5c_reads == "ff_page" machine = Machine(W65C02S, 0x5C, 0x34, 0x12) machine.step() assert machine.cycles()[3:] == [r(0xFF34), r(0xFFFF), r(0xFFFF), r(0xFFFF), r(0xFFFF)] class OtherReading(W65C02S): nop_5c_reads = "pc" machine = Machine(OtherReading, 0x5C, 0x34, 0x12) assert machine.step() == 8 assert machine.cycles()[3:] == [r(ORG + 3)] * 5 def test_c10_dc_and_fc_read_the_absolute_address() -> None: """C10: CL section 9 note i and LK: `$DC` and `$FC` "use absolute address mode to read memory"; CAP agrees in the 8 executions it can tell. SST re-reads PC+2; "operand" is that reading.""" assert CMOS65C02.nop_dc_fc_reads == "absolute" for opcode in (0xDC, 0xFC): machine = Machine(G65SC02, opcode, 0x34, 0x12) assert machine.step() == 4 assert machine.cycles()[3] == r(0x1234) class CorpusReading(G65SC02): nop_dc_fc_reads = "operand" machine = Machine(CorpusReading, 0xDC, 0x34, 0x12) assert machine.step() == 4 assert machine.cycles()[3] == r(ORG + 2) def test_c11_inc_and_dec_absolute_x_always_take_seven_cycles() -> None: """C11: GDS Table IV prints 6 for `INC`/`DEC abs,X`; CL section 7: "always take 7"; CAP: `$DE` and `$FE` 7 in every execution. The shifts take 6 within a page (DS Table 7-1; CAP) and 7 across.""" for opcode in (0xDE, 0xFE): for x in (0x00, 0xFF): machine = Machine(R65C02, opcode, 0x80, 0x30) machine.cpu.x = x assert machine.step() == 7 for opcode in (0x1E, 0x3E, 0x5E, 0x7E): machine = Machine(R65C02, opcode, 0x80, 0x30) assert machine.step() == 6 machine = Machine(R65C02, opcode, 0x80, 0x30) machine.cpu.x = 0xFF assert machine.step() == 7 @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_c19_the_absolute_x_shifts_take_six_cycles_within_a_page(row: type) -> None: """C19: DS Table 7-1 "Read/Modify/Write instructions absolute indexed in same page: six cycles"; GDS Table IV; CAP: 6 in every execution on both parts. MAME's base CMOS device takes 7, as the NMOS part.""" for opcode in (0x1E, 0x3E, 0x5E, 0x7E): machine = Machine(row, opcode, 0x34, 0x12) machine.cpu.x = 0x10 assert machine.step() == 6 assert machine.cycles()[3:] == [r(0x1244), r(0x1244), w(0x1244)] # --------------------------------------------------------------------------------------- # C2, C12: the bit instructions # --------------------------------------------------------------------------------------- def test_c2_the_bit_opcodes_are_one_cycle_nops_on_the_g65sc02() -> None: """C2: GDS Table V, VDS Table 2 and NDS: `X7` and `XF` are one byte, one cycle; CAP on the G65SC12: one cycle each, and Dormann's test, which checks their length, runs through. SST's Synertek set has two- and three-byte NOPs.""" for opcode in BIT_OPCODES: machine = Machine(G65SC02, opcode, 0x44, 0x7F) machine.memory[0x44] = 0xA5 assert machine.step() == 1, hex(opcode) assert machine.cycles() == [r(ORG)] assert machine.cpu.pc == ORG + 1 and machine.memory[0x44] == 0xA5 def lynx_test_7(row: type) -> tuple[int, int, bool, bool]: """LT `cpu` test 7's four probes: `$07 $EA` (RMB0), `$87 $EA` (SMB0), `$0F $EA off` (BBR0) and `$8F $EA off` (BBS0), all on zero-page `$EA`. Returns the byte after RMB0, after SMB0, and whether each branch was taken.""" machine = Machine(row, 0x07, 0xEA, 0xEA) machine.memory[0xEA] = 0xFF machine.step() after_rmb = machine.memory[0xEA] machine = Machine(row, 0x87, 0xEA, 0xEA) machine.step() after_smb = machine.memory[0xEA] taken = [] for opcode, value in ((0x0F, 0x00), (0x8F, 0x01)): machine = Machine(row, opcode, 0xEA, 0x10) machine.memory[0xEA] = value machine.step() taken.append(machine.cpu.pc == ORG + 0x13) return after_rmb, after_smb, taken[0], taken[1] def test_c12_the_lynx_ii_cell_executes_the_bit_instructions() -> None: """C12: LT `cpu` test 7 (expectations from real hardware) and 42Bastian: the bit opcodes are one-byte NOPs on a Lynx I (memory unchanged, no branch, the `$EA` after each runs as its own instruction) and work on a Lynx II. VDS and MAME say NOPs for the cell.""" assert lynx_test_7(G65SC02) == (0xFF, 0x00, False, False) assert lynx_test_7(Lynx2Cell) == (0xFE, 0x01, True, True) assert lynx_test_7(R65C02) == lynx_test_7(Lynx2Cell) == lynx_test_7(W65C02S) def test_c12_bit_instruction_cycles_are_the_r65c02s() -> None: """C12: LT checks results, not cycles; the Lynx II's counts are assumed to be the captured R65C02's: RMB/SMB 5, BBR/BBS 5, 6 taken (CAP), 7 taken across a page (SST).""" for row in (R65C02, Lynx2Cell): machine = Machine(row, 0x17, 0x44) assert machine.step() == 5 assert machine.cycles() == [r(ORG), r(ORG + 1), r(0x44), r(0x44), w(0x44)] machine = Machine(row, 0x1F, 0x44, 0x10) # BBR1: the bit is clear, taken assert machine.step() == 6 assert machine.cycles() == [ r(ORG), r(ORG + 1), r(0x44), r(0x44), r(ORG + 2), r(ORG + 3), ] # fmt: skip machine = Machine(row, 0x9F, 0x44, 0x10) # BBS1: not taken assert machine.step() == 5 machine = Machine(row, 0x1F, 0x44, 0x80) # taken across a page assert machine.step() == 7 assert machine.cycles()[5:] == [r(ORG + 3), r(ORG + 3)] assert machine.cpu.pc == ORG + 3 - 0x80 # --------------------------------------------------------------------------------------- # U12 and the bus contract (docs/handoff-brief.md) # --------------------------------------------------------------------------------------- def test_u12_a_stretched_write_cycle_polls_what_arrived_during_it() -> None: """U12: RDY stops the CMOS part on write cycles too (DS 3.10 "on all cycles including write cycles"; Table 7-1). The core has no RDY input: a host that holds a write calls `note_stall()` as the hold begins and after each held cycle, and a request raised during the hold is polled at the end of that cycle even though it is the instruction's last (the frame's semantics for a read, applied to a write: the Lynx's Suzy does this).""" machine = interrupts(Lynx2Cell, 0x85, 0x10, 0xE8, 0xE8) # STA $10; INX; INX def hold(machine: Machine, cycle: int, kind: str, address: int) -> None: if kind == "w": machine.cpu.note_stall() # the hold begins machine.cpu.request_maskable_interrupt() # a device raises IRQ while the CPU is held machine.cpu.note_stall() # one held cycle has passed machine.hook = hold assert machine.step() == 3 machine.hook = None assert machine.step() == 7 and machine.cpu.pc == 0x9000 # taken at once # Without the hold, a request in the last cycle waits an instruction. machine = interrupts(Lynx2Cell, 0x85, 0x10, 0xE8, 0xE8) def late(machine: Machine, cycle: int, kind: str, address: int) -> None: if kind == "w": machine.cpu.request_maskable_interrupt() machine.hook = late machine.step() machine.hook = None machine.step() assert machine.cpu.x == 1 def test_sync_fetch_and_opcode_are_readable_in_the_callback() -> None: """The bus contract: `sync` is True in the opcode fetch only; `fetch` in every read of the instruction stream at PC (opcode, operands, the dropped read of a one-byte instruction); `opcode` is the instruction in progress from its second cycle on.""" machine = Machine(G65SC02, 0xBD, 0xF8, 0x12, 0xE8, 0x20, 0x00, 0x30) machine.cpu.x = 0x10 seen = [] def hook(machine: Machine, cycle: int, kind: str, address: int) -> None: seen.append(machine.cpu.opcode) machine.hook = hook machine.step() # LDA $12F8,X across a page: fetch, fetch, fetch, re-read, data assert machine.pins == [(True, True), (False, True), (False, True), (False, False), (False, False)] # fmt: skip assert seen[1:] == [0xBD] * 4 machine.step() # INX: the dropped read is at PC assert machine.pins == [(True, True), (False, True)] seen.clear() machine.step() # JSR: opcode, operand, stack read, two pushes, operand assert machine.pins == [ (True, True), (False, True), (False, False), (False, False), (False, False), (False, True), ] # fmt: skip assert seen[0] == 0xE8 and seen[1:] == [0x20] * 5 def test_a_callback_may_take_as_long_as_it_likes_and_change_requests() -> None: """The Lynx's request 3: Suzy draws inside the write to CPUSLEEP. Nothing in the core times a callback; requests made and withdrawn inside one are honoured as they stand.""" machine = interrupts(G65SC02, 0x8D, 0x91, 0xFD, 0xE8) # STA $FD91; INX def sleep(machine: Machine, cycle: int, kind: str, address: int) -> None: if address == 0xFD91: machine.cpu.note_stall() machine.cpu.request_maskable_interrupt() machine.cpu.clear_maskable_interrupt() # raised and acknowledged while held machine.cpu.request_non_maskable_interrupt() machine.cpu.note_stall() machine.hook = sleep machine.step() machine.hook = None assert machine.step() == 7 and machine.cpu.pc == 0xA000 def test_tsb_trb_and_bit_immediate_flags() -> None: """DS Table 6-4: TSB and TRB set Z from A AND M and leave N and V; GDS Table IV note 5 and CL section 2: BIT # changes Z only.""" machine = Machine(G65SC02, 0x04, 0x44, 0x14, 0x44, 0x89, 0xC0, 0x89, 0x01) machine.memory[0x44] = 0xC0 machine.cpu.a = 0x0F machine.cpu.p = 0x20 | N | V machine.step() assert machine.memory[0x44] == 0xCF and machine.cpu.p == 0x20 | N | V | Z machine.step() assert machine.memory[0x44] == 0xC0 and machine.cpu.p == 0x20 | N | V machine.cpu.p = 0x20 machine.step() assert machine.cpu.p == 0x20 | Z # A AND #$C0 is zero; N and V not copied from the operand machine.step() assert machine.cpu.p == 0x20 @pytest.mark.parametrize("row", ROWS, ids=ROW_IDS) def test_step_returns_the_number_of_callbacks_for_every_opcode(row: type) -> None: """The bus contract: `cycles = cpu.step()` is the number of callbacks made, for every opcode, in binary and decimal mode, with random operands and registers.""" rng = random.Random(6502) for opcode in range(256): for _ in range(40): machine = Machine(row, opcode, rng.randrange(256), rng.randrange(256)) for address in range(0x100): machine.memory[address] = rng.randrange(256) cpu = machine.cpu cpu.a, cpu.x, cpu.y = rng.randrange(256), rng.randrange(256), rng.randrange(256) cpu.p = (rng.randrange(256) | 0x20) & ~B cycles = machine.step() # asserts the count assert 1 <= cycles <= 8 # --------------------------------------------------------------------------------------- # every entry has a test # --------------------------------------------------------------------------------------- def test_every_unknown_and_contradiction_has_a_directed_test() -> None: """Rung 6's exit: every U and C entry of docs/undocumented-behavior.md has a test here that is named for it and cites it.""" entries = re.findall( r"^\*\*([UC]\d+)\.", (ROOT / "docs" / "undocumented-behavior.md").read_text(encoding="utf-8"), re.MULTILINE, ) assert len(entries) == len(set(entries)) >= 31 tests = { node.name: ast.get_docstring(node) or "" for node in ast.parse(Path(__file__).read_text(encoding="utf-8")).body if isinstance(node, ast.FunctionDef) and node.name.startswith("test_") } for entry in entries: named = [name for name in tests if name.startswith(f"test_{entry.lower()}_")] assert named, f"{entry} has no directed test" assert any(re.search(rf"\b{entry}\b", tests[name]) for name in named), entry