// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT const std = @import("std"); /// The stack pointer, and the pushes and pulls that move it. The stack lives in /// page one and wraps within it rather than overflowing. Embedded in CPU, and /// finds its way back to it with @fieldParentPtr rather than holding a pointer, /// so the whole processor can be built in place. pub fn Stack(comptime CPU: type) type { return struct { const Self = @This(); const page: u16 = 0x0100; pointer: u8, underflows: usize, overflows: usize, /// The CPU this belongs to, recovered from the field it is embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("stack", self)); } /// Puts the pointer at the top of the stack page and clears the wrap /// counters. pub fn init(self: *Self) void { self.reset(); } /// As init. The 6502 does not clear the stack on reset either; it only /// moves the pointer. pub fn reset(self: *Self) void { self.pointer = 0xff; self.underflows = 0; self.overflows = 0; } /// The read the chip performs at the slot the pointer is sitting on /// and throws away, before the pointer moves. pub fn phantomRead(self: *Self) void { const cpu = self.getCPU(); _ = cpu.memory.read(u8, page + self.pointer); } /// Moves the pointer up and reads. A word comes back low byte first, /// the order the processor pushed it in. Running off the end wraps /// within the stack page and is counted rather than reported, because /// that is what the hardware does. pub fn pop(self: *Self, comptime T: type) T { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { self.pointer = sp: { break :sp std.math.add(u8, self.pointer, 1) catch { self.underflows += 1; break :sp 0x00; }; }; return cpu.memory.read(u8, page + self.pointer); }, 16 => { return @as(u16, self.pop(u8)) | (@as(u16, self.pop(u8)) << 8); }, else => @compileError("must be u8 or u16"), } } /// Writes at the pointer and moves it down. A word goes out high byte /// first. Running off the end wraps, as in pop. pub fn push(self: *Self, comptime T: type, value: T) void { const cpu = self.getCPU(); const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { cpu.memory.write(u8, page + self.pointer, value); self.pointer = sp: { break :sp std.math.sub(u8, self.pointer, 1) catch { self.overflows += 1; break :sp 0xff; }; }; }, 16 => { self.push(u8, @intCast((value & 0xff00) >> 8)); self.push(u8, @intCast(value & 0xff)); }, else => @compileError("must be u8 or u16"), } } }; }