// 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 = "LSR"; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = 0x46, .addressing_mode = .@"Zero Page", .cycles = 5, }, .{ .opcode = 0x4a, .addressing_mode = .Implied, .cycles = 2, }, .{ .opcode = 0x4e, .addressing_mode = .Absolute, .cycles = 6, }, .{ .opcode = 0x56, .addressing_mode = .@"Zero Page, X", .cycles = 6, }, .{ .opcode = 0x5e, .addressing_mode = .@"Absolute, X", .cycles = 7, }, }; /// 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) *const fn (*CPU) error{}!void { const f = struct { /// Shifts the accumulator or the addressed byte right one bit. /// Bit 0 falls into carry and a zero comes in at the top. /// /// (MOS Technology, 1976, Section 10.1, p. 148) /// (Carr, 1984, p. 265) pub fn LSR(cpu: *CPU) error{}!void { var address: ?u16 = null; const value = switch (addressing_mode) { .Implied => value: { // the operand fetch every single byte instruction // performs and discards cpu.program_counter.phantomRead(); break :value cpu.registers.get(.A); }, else => value: { address = cpu.addressing_modes.decode(addressing_mode, .modify); const current = cpu.memory.read(u8, address.?); // A read-modify-write spends a cycle on the // bus before it writes: the NMOS part drives the // unmodified value back, and the CMOS part reads // the address again. switch (CPU.processor) { .@"6502", .RP2A03 => cpu.memory.write(u8, address.?, current), .@"65C02", .R65C02, .W65C02 => _ = cpu.memory.read(u8, address.?), } break :value current; }, }; cpu.flags.update(.C, value & 0x01 == 0x01); const result = @shrExact(value & 0xfe, 1); cpu.flags.updateNZ(result); switch (addressing_mode) { .Implied => cpu.registers.set(.A, result), else => cpu.memory.write(u8, address.?, result), } } }; return f.LSR; } }; }