// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT /// Describes one instruction: its mnemonic, and every opcode that selects it /// together with that opcode's addressing mode and cycle count. Opcodes /// collects these at comptime to build the dispatch table. pub fn data(comptime CPU: type) type { return struct { pub const mnemonic = "BEQ"; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = 0xf0, .addressing_mode = .Relative, // Three when it is taken, and four when it is taken across a // page while emulating. A branch that is not taken is the // cheapest instruction there is. .cycles = 2, }, }; /// The implementation for a single addressing mode. Resolved at /// comptime so the dispatch table holds a plain function pointer with /// no mode left to branch on at runtime. pub fn func( comptime addressing_mode: CPU.AddressingModes, comptime widths: ?CPU.Widths, ) *const fn (*CPU) CPU.Opcodes.Error!void { if (addressing_mode != .Relative) @compileError("illegal addressing mode"); _ = widths; const f = struct { /// Branches when the last answer was zero. pub fn BEQ(cpu: *CPU) !void { const displacement: i8 = @bitCast(cpu.program_counter.read(u8)); if (!(cpu.flags.isSet(.Z))) return; // Taken, so a cycle to add the offset, with the offset's // own address on the bus while it happens — the same place // every other internal cycle in this core keeps. const from = cpu.program_counter.value; const target = @as(u16, @bitCast(@as(i16, @bitCast(from)) +% displacement)); cpu.memory.internal(cpu.program_counter.addressOf(from -% 1)); // And a second cycle when the target turns out to be in // another page — but only while emulating. Natively the // chip fixes the high half without spending anything on // it, which is one of the quiet reasons native code runs // faster than the same code in emulation. // The 6502 spent that cycle at the address it had built // before fixing the high half, which is an address nobody // meant. This one does not go anywhere at all: it holds // the offset's address again, as the cycle before it did. if (cpu.flags.emulation and from & 0xff00 != target & 0xff00) cpu.memory.internal(cpu.program_counter.addressOf(from -% 1)); cpu.program_counter.jump(target); } }; return f.BEQ; } }; }