// 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 = "BIT"; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = 0x24, .addressing_mode = .@"Direct Page", .cycles = 3, }, .{ .opcode = 0x2c, .addressing_mode = .Absolute, .cycles = 4, }, .{ .opcode = 0x34, .addressing_mode = .@"Direct Page, X", .cycles = 4, }, .{ .opcode = 0x3c, .addressing_mode = .@"Absolute, X", .cycles = 4, }, .{ .opcode = 0x89, .addressing_mode = .Immediate, .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 { const f = struct { /// Tests bits of the operand against the accumulator. pub fn BIT(cpu: *CPU) !void { if (comptime widths) |w| { if (comptime w.m) at(cpu, u8) else at(cpu, u16); } else { if (cpu.flags.isSet(.M)) at(cpu, u8) else at(cpu, u16); } } /// The operand, at whichever width is in force. An immediate /// one is part of the instruction and comes out of the program /// bank; everything else is data at wherever the mode worked /// out. fn operand(cpu: *CPU, comptime T: type) T { return if (comptime addressing_mode == .Immediate) cpu.program_counter.read(T) else cpu.addressing_modes.readData( addressing_mode, T, cpu.addressing_modes.decode(addressing_mode, .read), ); } fn at(cpu: *CPU, comptime T: type) void { const value = operand(cpu, T); // Against a constant only the zero flag moves. Everywhere // else the top two bits of the operand are copied out // whether or not the accumulator has anything in common // with it, which is what makes this the way to read a // status register without disturbing it. if (comptime addressing_mode != .Immediate) { const bits = @typeInfo(T).int.bits; cpu.flags.update(.N, value & (@as(T, 1) << (bits - 1)) != 0); cpu.flags.update(.V, value & (@as(T, 1) << (bits - 2)) != 0); } cpu.flags.update(.Z, cpu.registers.getNarrow(.A, T) & value == 0); } }; return f.BIT; } }; }