// 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 = "JSR"; pub const opcodes = [_]CPU.Opcodes.Init{ .{ .opcode = 0x20, .addressing_mode = .Absolute, .cycles = 6, }, .{ .opcode = 0xfc, .addressing_mode = .@"(Absolute, X)", .cycles = 8, }, }; /// 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 { _ = widths; const f = struct { /// Calls a subroutine in this bank, leaving the way back on the stack. pub fn JSR(cpu: *CPU) !void { switch (addressing_mode) { .Absolute => { const started = cpu.program_counter.value; const target = cpu.program_counter.read(u16); cpu.memory.internal(cpu.program_counter.addressOf(started +% 1)); // What goes on the stack is the address of the // last byte of this instruction, not of the next // one, which is why the return adds one back. cpu.stack.push(u16, .page_one, cpu.program_counter.value -% 1); cpu.program_counter.jump(target); }, .@"(Absolute, X)" => { // The return address goes on the stack between the // two halves of the operand, which is a shape // nothing else has and not one to tidy up: by then // the counter is already pointing at the last byte // of the instruction, which is exactly what a // return wants to come back to. const low_byte: u16 = cpu.program_counter.read(u8); cpu.stack.push(u16, .page_one, cpu.program_counter.value); const at_operand = cpu.program_counter.address(); const high_byte: u16 = cpu.program_counter.read(u8); cpu.memory.internal(at_operand); const bank = @as(u24, cpu.registers.program_bank) << 16; const offset = (high_byte << 8 | low_byte) +% cpu.registers.get(.X); const low: u16 = cpu.memory.read(bank | offset, .data); const high: u16 = cpu.memory.read(bank | (offset +% 1), .data); cpu.program_counter.jump(high << 8 | low); }, else => @compileError("illegal addressing mode"), } } }; return f.JSR; } }; }