// 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 = "LDX"; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = 0xa2, .addressing_mode = .Immediate, .cycles = 2, }, .{ .opcode = 0xa6, .addressing_mode = .@"Direct Page", .cycles = 3, }, .{ .opcode = 0xae, .addressing_mode = .Absolute, .cycles = 4, }, .{ .opcode = 0xb6, .addressing_mode = .@"Direct Page, Y", .cycles = 4, }, .{ .opcode = 0xbe, .addressing_mode = .@"Absolute, Y", .cycles = 4, }, }; /// 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 { /// Loads index register X from memory. /// /// How much of it is what the X flag says, and that decides /// how long the instruction is as well as what it does: an /// immediate load is two bytes or three, and every other mode /// spends one cycle on the operand or two. The branch is on a /// flag rather than resolved at comptime, which is the open /// question this core has yet to settle — see the note in /// cpu16.zig. pub fn LDX(cpu: *CPU) !void { // Under `.tables` the width is already settled and this // folds away; under `.branch` it is the test the whole // measurement is about. if (comptime widths) |w| { if (comptime w.x) at(cpu, u8) else at(cpu, u16); } else { if (cpu.flags.isSet(.X)) at(cpu, u8) else at(cpu, u16); } } fn at(cpu: *CPU, comptime T: type) void { const value = if (comptime addressing_mode == .Immediate) // The operand is part of the instruction, so it is // fetched from the program bank and shows on the bus // as an instruction byte rather than as data. cpu.program_counter.read(T) else cpu.addressing_modes.readData( addressing_mode, T, cpu.addressing_modes.decode(addressing_mode, .read), ); cpu.registers.setNarrow(.X, T, value); cpu.flags.updateNZ(T, value); } }; return f.LDX; } }; }