diff --git a/build.zig b/build.zig index 195cf49..240c202 100644 --- a/build.zig +++ b/build.zig @@ -118,4 +118,33 @@ pub fn build(b: *std.Build) void { .install_subdir = "", }); coverage_step.dependOn(&run_kcov_install.step); + + const single_step_tests_dep = b.dependency("single_step_tests", .{ + .target = target, + .optimize = optimize, + }); + + const single_step_tests_exe = b.addExecutable(.{ + .name = "single_step_tests", + .root_source_file = b.path("src/single_step_tests.zig"), + .target = target, + .optimize = optimize, + }); + + single_step_tests_exe.root_module.addImport("zig65", zig65); + + for (0..256) |i| { + const path = std.fmt.allocPrint(b.allocator, "6502/v1/{x:0>2}.json", .{i}) catch unreachable; + const name = std.fmt.allocPrint(b.allocator, "single_step_test_6502_{x:0>2}", .{i}) catch unreachable; + single_step_tests_exe.root_module.addAnonymousImport( + name, + .{ + .root_source_file = single_step_tests_dep.path(path), + }, + ); + } + + const single_step_tests_cmd = b.addRunArtifact(single_step_tests_exe); + const single_step_tests_step = b.step("single-step-tests", "Run the Single Step Tests"); + single_step_tests_step.dependOn(&single_step_tests_cmd.step); } diff --git a/build.zig.zon b/build.zig.zon index ab21a7e..36fb0f4 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -12,6 +12,10 @@ .url = "git+https://github.com/kristoff-it/ziggy#20c8088dbf4b22dc2f6e21d289cfb3dcc25c8cae", .hash = "12206a0d6884ef31e3d4e47d5c9c6c4121b0a891258d6072ad7f5bac826803d29d36", }, + .single_step_tests = .{ + .url = "git+https://github.com/SingleStepTests/65x02?ref=main#3ecec7e679e629622019707655416b8767a65f95", + .hash = "12204457003f2ec44051d96edc55ee025f92bd55165b71566ed23036917d030d13a6", + }, .ehbasic = .{ .url = "http://rubbermallet.org/ehbasic.zip", .hash = "1220d3c1b6cd4c2c0ff69a6afafed864917b5ca8d63981445f9624dd55bcaa71444a", diff --git a/src/cpu.zig b/src/cpu.zig index d9f72d9..d01bfa7 100644 --- a/src/cpu.zig +++ b/src/cpu.zig @@ -86,6 +86,7 @@ pub const Errors = error{ IllegalOpcode, IllegalOperation, IllegalAddressingMode, + IllegalValue, }; pub const Processor = enum { @@ -210,7 +211,7 @@ pub fn new(comptime Clock: type) type { /// break command B: bool = false, // padding - _: bool = true, + _5: bool = true, /// overflow V: bool = false, /// negative @@ -337,14 +338,17 @@ pub fn new(comptime Clock: type) type { pub fn carry(self: *@This(), comptime T: type) T { const info = @typeInfo(T); if (info != .Int) @compileError("must be an integer"); - if (info.Int.signedness != .unsigned) @compileError("must be unsigned"); + // if (info.Int.signedness != .unsigned) @compileError("must be unsigned"); if (info.Int.bits != 8 and info.Int.bits != 16) @compileError("must be u8 or u16"); return if (self.value.C) 1 else 0; } /// return the processor status flags as a u8 pub fn save(self: *@This()) u8 { - return @bitCast(self.value); + var value = self.value; + value.B = true; + value._5 = true; + return @bitCast(value); } /// return the processor status flags as a u8 with the B flag set @@ -359,7 +363,10 @@ pub fn new(comptime Clock: type) type { const cpu = self.cpu.?; const now = cpu.timer.read(); inline for (0..count) |i| self.changed[i] = now; - self.value = @bitCast(value); + var n: Value = @bitCast(value); + n.B = self.value.B; + n._5 = true; + self.value = n; } pub fn copy(self: *@This()) Value { @@ -370,12 +377,24 @@ pub fn new(comptime Clock: type) type { const info = @typeInfo(Value); inline for (info.Struct.fields) |field| { if (@field(self.value, field.name) != @field(other, field.name)) { - log.warn("flag {s} is {} - was expecting {}", .{ field.name, @field(other, field.name), @field(self.value, field.name) }); + // log.warn("flag {s} is {} - was expecting {}", .{ field.name, @field(other, field.name), @field(self.value, field.name) }); return false; } } return true; } + + pub fn format(_: *@This(), buf: []u8, value: Value) []const u8 { + const info = @typeInfo(Value); + inline for (info.Struct.fields, 0..) |field, i| { + if (field.name[0] == '_') { + buf[info.Struct.fields.len - i - 1] = '-'; + continue; + } + buf[info.Struct.fields.len - i - 1] = if (@field(value, field.name)) std.ascii.toUpper(field.name[0]) else std.ascii.toLower(field.name[0]); + } + return buf[0..8]; + } }; const Registers = struct { @@ -577,11 +596,9 @@ pub fn new(comptime Clock: type) type { return self.memory[offset]; }, 16 => { - std.debug.assert(offset <= std.math.maxInt(u16) - 1); - const start: usize = @intCast(offset); - const end = start + 2; - self.clock.sleep(2); - return std.mem.readVarInt(u16, self.memory[start..end], .little); + const low = self.read(u8, offset); + const high = self.read(u8, offset +% 1); + return @as(u16, high) << 8 | low; }, else => @compileError("must be a u8 or a u16"), } diff --git a/src/cpu/addressing_modes.zig b/src/cpu/addressing_modes.zig index 660a2bc..7eb83cf 100644 --- a/src/cpu/addressing_modes.zig +++ b/src/cpu/addressing_modes.zig @@ -2,6 +2,8 @@ const std = @import("std"); const CPU = @import("../cpu.zig"); const clock = @import("../clock.zig"); +const log = std.log.scoped(.addressing_modes); + pub fn AddressingModes(comptime Clock: type) type { const Self = CPU.new(Clock); return struct { @@ -60,15 +62,32 @@ pub fn AddressingModes(comptime Clock: type) type { }, .@"(Indirect, X)" => addr: { - const zp: u16 = cpu.program_counter.read(u8); - _ = cpu.read(u8, zp); // "phantom" read - break :addr cpu.read(u16, zp +% cpu.register.get(.X)); + var base_address_low: u8 = cpu.program_counter.read(u8); + _ = cpu.read(u8, base_address_low); // "phantom" read + base_address_low +%= cpu.register.get(.X); + const address_low = cpu.read(u8, base_address_low); + const address_high = cpu.read(u8, base_address_low +% 1); + const address = @as(u16, address_high) << 8 | address_low; + break :addr address; }, .@"(Indirect), Y" => addr: { - const zp: u16 = cpu.program_counter.read(u8); - _ = cpu.read(u8, zp); // "phantom" read - break :addr cpu.read(u16, zp) +% cpu.register.get(.Y); + const intermediate_address_low: u8 = cpu.program_counter.read(u8); + // _ = cpu.read(u8, intermediate_address_low); // "phantom" read + const base_address_low = cpu.read(u8, intermediate_address_low); + const base_address_high = cpu.read(u8, intermediate_address_low +% 1); + const y = cpu.register.get(.Y); + const address_high, const address_low = address: { + break :address .{ + base_address_high, std.math.add(u8, base_address_low, y) catch { + const phantom_address = @as(u16, base_address_high) << 8 | (base_address_low +% y); + _ = cpu.read(u8, phantom_address); + break :address .{ base_address_high +% 1, (base_address_low +% y) }; + }, + }; + }; + const address = @as(u16, address_high) << 8 | address_low; + break :addr address; }, .Relative => addr: { diff --git a/src/cpu/flags.zig b/src/cpu/flags.zig new file mode 100644 index 0000000..604aeea --- /dev/null +++ b/src/cpu/flags.zig @@ -0,0 +1,220 @@ +const std = @import("std"); +const CPU = @import("../cpu.zig").new; +const Processor = @import("../cpu.zig").Processor; + +const log = std.log.scoped(.flags); + +pub fn Flags(comptime processor: Processor, comptime Clock: type) type { + const Self = CPU(Clock); + + return struct { + const Name = switch (processor) { + .@"6502" => enum { + /// negative + N, + /// overflow + V, + /// break command + B, + /// decimal mode + D, + /// interrupt disable + I, + /// zero + Z, + /// carry + C, + }, + else => @compileError("unimplemented processor"), + }; + + // the order matters! + const Value = switch (processor) { + .@"6502" => packed struct(u8) { + /// carry + C: bool = false, + /// zero + Z: bool = true, + /// interrupt disable + I: bool = false, + /// decimal mode + D: bool = false, + /// break command + B: bool = false, + // padding + _5: bool = true, + /// overflow + V: bool = false, + /// negative + N: bool = false, + }, + else => @compileError("unimplemented processor"), + }; + + const count = @typeInfo(Name).Enum.fields.len; + + cpu: ?*Self = null, + + value: Value = .{}, + + changed: [count]u64 = undefined, + + pub fn init(self: *@This(), cpu: *Self) void { + self.cpu = cpu; + self.reset(); + } + + pub fn reset(self: *@This()) void { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + const now = cpu.timer.read(); + inline for (0..count) |i| + self.changed[i] = now; + self.value = .{ + .C = false, + .Z = cpu.register.A == 0, + .I = false, + .D = false, + .B = false, + .V = false, + .N = cpu.register.A & 0x80 == 0x80, + }; + } + + pub fn since(self: *@This(), comptime flag: Name) u64 { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + const now = cpu.timer.read(); + return now - self.changed[@intFromEnum(flag)]; + } + + pub fn isSet(self: *@This(), comptime flag: Name) bool { + return switch (flag) { + .N => self.value.N, + .V => self.value.V, + .B => self.value.B, + .D => self.value.D, + .I => self.value.I, + .Z => self.value.Z, + .C => self.value.C, + }; + } + + pub fn isClear(self: *@This(), comptime flag: Name) bool { + return switch (flag) { + .N => !self.value.N, + .V => !self.value.V, + .B => !self.value.B, + .D => !self.value.D, + .I => !self.value.I, + .Z => !self.value.Z, + .C => !self.value.C, + }; + } + + pub fn set(self: *@This(), comptime flag: Name) void { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + self.changed[@intFromEnum(flag)] = cpu.timer.read(); + switch (flag) { + .N => self.value.N = true, + .V => self.value.V = true, + .B => self.value.B = true, + .D => self.value.D = true, + .I => self.value.I = true, + .Z => self.value.Z = true, + .C => self.value.C = true, + } + } + + pub fn clear(self: *@This(), comptime flag: Name) void { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + self.changed[@intFromEnum(flag)] = cpu.timer.read(); + switch (flag) { + .N => self.value.N = false, + .V => self.value.V = false, + .B => self.value.B = false, + .D => self.value.D = false, + .I => self.value.I = false, + .Z => self.value.Z = false, + .C => self.value.C = false, + } + } + + pub fn toggle(self: *@This(), comptime flag: Name) void { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + self.changed[@intFromEnum(flag)] = cpu.timer.read(); + switch (flag) { + .N => self.value.N = !self.value.N, + .V => self.value.V = !self.value.V, + .B => self.value.B = !self.value.B, + .D => self.value.D = !self.value.D, + .I => self.value.I = !self.value.I, + .Z => self.value.Z = !self.value.Z, + .C => self.value.C = !self.value.C, + } + } + + pub fn update(self: *@This(), comptime flag: Name, value: bool) void { + if (self.isSet(flag) != value) + self.toggle(flag); + } + + pub fn updateNZ(self: *@This(), value: u8) void { + self.update(.N, value & 0x080 == 0x80); + self.update(.Z, value == 0x00); + } + + /// Convenience function for ADC/SBC + pub fn carry(self: *@This(), comptime T: type) T { + const info = @typeInfo(T); + if (info != .Int) @compileError("must be an integer"); + if (info.Int.signedness != .unsigned) @compileError("must be unsigned"); + if (info.Int.bits != 8 and info.Int.bits != 16) @compileError("must be u8 or u16"); + return if (self.value.C) 1 else 0; + } + + /// return the processor status flags as a u8 + pub fn save(self: *@This()) u8 { + var value = self.value; + value.B = true; + value._5 = true; + return @bitCast(value); + } + + /// return the processor status flags as a u8 with the B flag set + pub fn saveBRK(self: *@This()) u8 { + var value: Value = self.value; + value.B = true; + return @bitCast(value); + } + + pub fn restore(self: *@This(), value: u8) void { + std.debug.assert(self.cpu != null); + const cpu = self.cpu.?; + const now = cpu.timer.read(); + inline for (0..count) |i| self.changed[i] = now; + var n: Value = @bitCast(value); + n.B = self.value.B; + n._5 = true; + self.value = n; + } + + pub fn copy(self: *@This()) Value { + return self.value; + } + + pub fn compare(self: *@This(), other: Value) bool { + const info = @typeInfo(Value); + inline for (info.Struct.fields) |field| { + if (@field(self.value, field.name) != @field(other, field.name)) { + log.warn("flag {s} is {} - was expecting {}", .{ field.name, @field(other, field.name), @field(self.value, field.name) }); + return false; + } + } + return true; + } + }; +} diff --git a/src/cpu/program_counter.zig b/src/cpu/program_counter.zig index e631a53..9a45da9 100644 --- a/src/cpu/program_counter.zig +++ b/src/cpu/program_counter.zig @@ -25,13 +25,21 @@ pub fn ProgramCounter(comptime Clock: type) type { const info = @typeInfo(T); if (info != .Int) @compileError("must be an integer"); if (info.Int.signedness != .unsigned) @compileError("must be unsigned"); - const result = cpu.read(T, self.value); switch (info.Int.bits) { - 8 => self.value += 1, - 16 => self.value += 2, + 8 => { + const value = cpu.read(u8, self.value); + self.value +%= 1; + return value; + }, + 16 => { + const low = cpu.read(u8, self.value); + self.value +%= 1; + const high = cpu.read(u8, self.value); + self.value +%= 1; + return @as(u16, high) << 8 | low; + }, else => @compileError("must be a u8 or a u16"), } - return result; } // Calculate the address that an immediate argument should be loaded @@ -39,7 +47,7 @@ pub fn ProgramCounter(comptime Clock: type) type { // holds the data. pub fn immediate(self: *@This()) u16 { const result = self.value; - self.value += 1; + self.value +%= 1; return result; } diff --git a/src/decode.zig b/src/decode.zig index 47f66d1..089f99a 100644 --- a/src/decode.zig +++ b/src/decode.zig @@ -1,465 +1,159 @@ const std = @import("std"); const CPU = @import("cpu.zig"); - -fn formatSingle(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {s}", - .{ - address, - memory[address], - mnemonic, - }, - ); -} - -fn formatImmediate(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} #${x:0>2}", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -fn formatZeroPage(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} ${x:0>2}", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -fn formatZeroPageX(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} ${x:0>2}, X", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -fn formatZeroPageY(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} ${x:0>2}, Y", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -fn formatAbsolute(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {x:0>2} {s} ${x:0>2}{x:0>2}", - .{ - address, - memory[address], - memory[address + 1], - memory[address + 2], - mnemonic, - memory[address + 2], - memory[address + 1], - }, - ); -} - -fn formatAbsoluteX(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {x:0>2} {s} ${x:0>2}{x:0>2}, X", - .{ - address, - memory[address], - memory[address + 1], - memory[address + 2], - mnemonic, - memory[address + 2], - memory[address + 1], - }, - ); -} - -fn formatAbsoluteY(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {x:0>2} {s} ${x:0>2}{x:0>2}, Y", - .{ - address, - memory[address], - memory[address + 1], - memory[address + 2], - mnemonic, - memory[address + 2], - memory[address + 1], - }, - ); -} - -fn formatIndirectX(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} (${x:0>2}, X)", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -fn formatIndirectY(alloc: std.mem.Allocator, memory: []const u8, address: u16, mnemonic: []const u8) []const u8 { - return std.fmt.allocPrint( - alloc, - "{x:0>4}: {x:0>2} {x:0>2} {s} (${x:0>2}), Y", - .{ - address, - memory[address], - memory[address + 1], - mnemonic, - memory[address + 1], - }, - ); -} - -const OpcodeData = struct { - opcode: u8, - mnemonic: []const u8, - addressing_mode: CPU.AddressingMode, - bytes: u8, - cycles: u8, - page_boundary_penalty: bool = false, - branch_penalties: bool = false, -}; - -const opcode_data = [256]?OpcodeData{ - .{ - .opcode = 0x00, - .mnemonic = "BRK", - .addressing_mode = .Implied, - .bytes = 1, - .cycles = 7, - }, // 0x00 - null, // 0x01 - null, // 0x02 - null, // 0x03 - null, // 0x04 - null, // 0x05 - null, // 0x06 - null, // 0x07 - null, // 0x08 - null, // 0x09 - null, // 0x0a - null, // 0x0b - null, // 0x0c - null, // 0x0d - null, // 0x0e - null, // 0x0f - null, // 0x10 - null, // 0x11 - null, // 0x12 - null, // 0x13 - null, // 0x14 - null, // 0x15 - null, // 0x16 - null, // 0x17 - null, // 0x18 - null, // 0x19 - null, // 0x1a - null, // 0x1b - null, // 0x1c - null, // 0x1d - null, // 0x1e - null, // 0x1f - null, // 0x20 - null, // 0x21 - null, // 0x22 - null, // 0x23 - null, // 0x24 - null, // 0x25 - null, // 0x26 - null, // 0x27 - null, // 0x28 - null, // 0x29 - null, // 0x2a - null, // 0x2b - null, // 0x2c - null, // 0x2d - null, // 0x2e - null, // 0x2f - null, // 0x30 - null, // 0x31 - null, // 0x32 - null, // 0x33 - null, // 0x34 - null, // 0x35 - null, // 0x36 - null, // 0x37 - null, // 0x38 - null, // 0x39 - null, // 0x3a - null, // 0x3b - null, // 0x3c - null, // 0x3d - null, // 0x3e - null, // 0x3f - null, // 0x40 - null, // 0x41 - null, // 0x42 - null, // 0x43 - null, // 0x44 - null, // 0x45 - null, // 0x46 - null, // 0x47 - null, // 0x48 - null, // 0x49 - null, // 0x4a - null, // 0x4b - null, // 0x4c - null, // 0x4d - null, // 0x4e - null, // 0x4f - .{ - .opcode = 0x50, - .mnemonic = "BRK", - .addressing_mode = .Relative, - .bytes = 1, - .cycles = 2, - .branch_penalty = true, - }, // 0x50 - null, // 0x51 - null, // 0x52 - null, // 0x53 - null, // 0x54 - null, // 0x55 - null, // 0x56 - null, // 0x57 - null, // 0x58 - null, // 0x59 - null, // 0x5a - null, // 0x5b - null, // 0x5c - null, // 0x5d - null, // 0x5e - null, // 0x5f - null, // 0x60 - null, // 0x61 - null, // 0x62 - null, // 0x63 - null, // 0x64 - null, // 0x65 - null, // 0x66 - null, // 0x67 - null, // 0x68 - null, // 0x69 - null, // 0x6a - null, // 0x6b - null, // 0x6c - null, // 0x6d - null, // 0x6e - null, // 0x6f - null, // 0x70 - null, // 0x71 - null, // 0x72 - null, // 0x73 - null, // 0x74 - null, // 0x75 - null, // 0x76 - null, // 0x77 - null, // 0x78 - null, // 0x79 - null, // 0x7a - null, // 0x7b - null, // 0x7c - null, // 0x7d - null, // 0x7e - null, // 0x7f - null, // 0x80 - null, // 0x81 - null, // 0x82 - null, // 0x83 - null, // 0x84 - null, // 0x85 - null, // 0x86 - null, // 0x87 - null, // 0x88 - null, // 0x89 - null, // 0x8a - null, // 0x8b - null, // 0x8c - null, // 0x8d - null, // 0x8e - null, // 0x8f - null, // 0x90 - null, // 0x91 - null, // 0x92 - null, // 0x93 - null, // 0x94 - null, // 0x95 - null, // 0x96 - null, // 0x97 - null, // 0x98 - null, // 0x99 - null, // 0x9a - null, // 0x9b - null, // 0x9c - null, // 0x9d - null, // 0x9e - null, // 0x9f - null, // 0xa0 - null, // 0xa1 - null, // 0xa2 - null, // 0xa3 - null, // 0xa4 - null, // 0xa5 - null, // 0xa6 - null, // 0xa7 - null, // 0xa8 - null, // 0xa9 - null, // 0xaa - null, // 0xab - null, // 0xac - null, // 0xad - null, // 0xae - null, // 0xaf - null, // 0xb0 - null, // 0xb1 - null, // 0xb2 - null, // 0xb3 - null, // 0xb4 - null, // 0xb5 - null, // 0xb6 - null, // 0xb7 - null, // 0xb8 - null, // 0xb9 - null, // 0xba - null, // 0xbb - null, // 0xbc - null, // 0xbd - null, // 0xbe - null, // 0xbf - null, // 0xc0 - null, // 0xc1 - null, // 0xc2 - null, // 0xc3 - null, // 0xc4 - null, // 0xc5 - null, // 0xc6 - null, // 0xc7 - null, // 0xc8 - null, // 0xc9 - null, // 0xca - null, // 0xcb - null, // 0xcc - null, // 0xcd - null, // 0xce - null, // 0xcf - null, // 0xd0 - null, // 0xd1 - null, // 0xd2 - null, // 0xd3 - null, // 0xd4 - null, // 0xd5 - null, // 0xd6 - null, // 0xd7 - null, // 0xd8 - null, // 0xd9 - null, // 0xda - null, // 0xdb - null, // 0xdc - null, // 0xdd - null, // 0xde - null, // 0xdf - null, // 0xe0 - null, // 0xe1 - null, // 0xe2 - null, // 0xe3 - null, // 0xe4 - null, // 0xe5 - null, // 0xe6 - null, // 0xe7 - null, // 0xe8 - null, // 0xe9 - null, // 0xea - null, // 0xeb - null, // 0xec - null, // 0xed - null, // 0xee - null, // 0xef - null, // 0xf0 - null, // 0xf1 - null, // 0xf2 - null, // 0xf3 - null, // 0xf4 - null, // 0xf5 - null, // 0xf6 - null, // 0xf7 - null, // 0xf8 - null, // 0xf9 - null, // 0xfa - null, // 0xfb - null, // 0xfc - null, // 0xfd - null, // 0xfe - null, // 0xff -}; - -pub fn decode(alloc: std.mem.Allocator, memory: []const u8, address: u16) []const u8 { - return switch (memory[address]) { - 0x00 => formatSingle(alloc, memory, address, "BRK"), - - 0x69 => formatImmediate(alloc, memory, address, "STA"), - 0x65 => formatZeroPage(alloc, memory, address, "STA"), - 0x75 => formatZeroPageX(alloc, memory, address, "STA"), - 0x6d => formatAbsolute(alloc, memory, address, "STA"), - 0x7d => formatAbsoluteX(alloc, memory, address, "STA"), - 0x79 => formatAbsoluteY(alloc, memory, address, "STA"), - 0x61 => formatIndirectX(alloc, memory, address, "STA"), - 0x71 => formatIndirectY(alloc, memory, address, "STA"), - - 0x85 => formatZeroPage(alloc, memory, address, "STA"), - 0x95 => formatZeroPageX(alloc, memory, address, "STA"), - 0x8d => formatAbsolute(alloc, memory, address, "STA"), - 0x9d => formatAbsoluteX(alloc, memory, address, "STA"), - 0x99 => formatAbsoluteY(alloc, memory, address, "STA"), - 0x81 => formatIndirectX(alloc, memory, address, "STA"), - 0x91 => formatIndirectY(alloc, memory, address, "STA"), - - 0x86 => formatZeroPage(alloc, memory, address, "STX"), - 0x96 => formatZeroPageY(alloc, memory, address, "STX"), - 0x8e => formatAbsolute(alloc, memory, address, "STX"), - - 0x84 => formatZeroPage(alloc, memory, address, "STY"), - 0x94 => formatZeroPageX(alloc, memory, address, "STY"), - 0x8c => formatAbsolute(alloc, memory, address, "STY"), - - 0xaa => formatSingle(alloc, memory, address, "TAX"), - - 0xab => formatSingle(alloc, memory, address, "TAY"), - - else => unreachable, +const table = @import("table.zig").table; + +pub fn format(buf: []u8, memory: []const u8, address: u16) ![]const u8 { + const opcode = memory[address]; + const data = table[opcode]; + return switch (data.addressing_mode) { + .Absolute => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {X:0>2} {s} ${X:0>2}{X:0>2}", + .{ + address, + memory[address], + memory[address +% 1], + memory[address +% 2], + data.mnemonic, + memory[address +% 2], + memory[address +% 1], + }, + ), + + .@"Absolute, X" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {X:0>2} {s} ${X:0>2}{X:0>2}, X", + .{ + address, + memory[address], + memory[address +% 1], + memory[address +% 2], + data.mnemonic, + memory[address +% 2], + memory[address +% 1], + }, + ), + + .@"Absolute, Y" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {X:0>2} {s} ${X:0>2}{X:0>2}, Y", + .{ + address, + memory[address], + memory[address +% 1], + memory[address +% 2], + data.mnemonic, + memory[address +% 2], + memory[address +% 1], + }, + ), + + .Implied => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {s}", + .{ + address, + memory[address], + data.mnemonic, + }, + ), + + .Immediate => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} #${X:0>2}", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), + + .Indirect => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {X:0>2} {s} (${X:0>2}{X:0>2})", + .{ + address, + memory[address], + memory[address +% 1], + memory[address +% 2], + data.mnemonic, + memory[address +% 2], + memory[address +% 1], + }, + ), + + .Relative => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} *{d}", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + @as(i8, @bitCast(memory[address +% 1])), + }, + ), + + .@"Zero Page" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} ${X:0>2}", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), + + .@"Zero Page, X" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} ${X:0>2}, X", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), + + .@"Zero Page, Y" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} ${X:0>2}, Y", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), + + .@"(Indirect, X)" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} (${X:0>2}, X)", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), + + .@"(Indirect), Y" => try std.fmt.bufPrint( + buf, + "${X:0>4}: {X:0>2} {X:0>2} {s} (${X:0>2}), Y", + .{ + address, + memory[address], + memory[address +% 1], + data.mnemonic, + memory[address +% 1], + }, + ), }; } diff --git a/src/opcodes.zig b/src/opcodes.zig index e9318bb..13b7997 100644 --- a/src/opcodes.zig +++ b/src/opcodes.zig @@ -1,3 +1,4 @@ +pub const format = @import("decode.zig").format; pub const table = @import("table.zig").table; pub const group1 = @import("opcodes/group1.zig").opcodes; pub const group2 = @import("opcodes/group2.zig").opcodes; diff --git a/src/opcodes/group1.zig b/src/opcodes/group1.zig index 483a68e..ab5b87e 100644 --- a/src/opcodes/group1.zig +++ b/src/opcodes/group1.zig @@ -4,8 +4,8 @@ const clock = @import("../clock.zig"); const log = std.log.scoped(.group1); -pub fn opcodes(comptime C: type) type { - const Self = CPU.new(C); +pub fn opcodes(comptime Clock: type) type { + const Self = CPU.new(Clock); return struct { pub fn ORA(self: *Self, addressing_mode: CPU.AddressingModes) !void { @@ -39,26 +39,106 @@ pub fn opcodes(comptime C: type) type { pub fn ADC(self: *Self, addressing_mode: CPU.AddressingModes) !void { const address = try self.addressing_modes.decode(addressing_mode); - const fetched: u16 = @intCast(self.read(u8, address)); - const current: u16 = @intCast(self.register.get(.A)); - var tmp: u16 = undefined; - - if (self.flag.isSet(.D)) { - tmp = (current & 0x000f) + (fetched & 0x000f) + self.flag.carry(u16); - if (tmp > 0x0009) tmp += 0x06; - tmp = (current & 0x00f0) + (fetched & 0x00f0) + @as(u16, if (tmp > 0x000f) 0x0010 else 0x0000) + (tmp & 0x000f); + const augend = self.register.get(.A); + const addend = self.read(u8, address); + + if (self.flag.isClear(.D)) { + // https://github.com/bradgrantham/apple2e/blob/8e656aba3b07788aee11705e188e4431c46b7e68/fake6502.c#L328-L355 + const tmp = @as(u16, augend) + @as(u16, addend) + self.flag.carry(u16); + self.flag.update(.C, tmp & 0xff00 != 0x0000); + self.flag.update(.N, tmp & 0x0080 == 0x0080); + self.flag.update(.Z, tmp & 0x00ff == 0x0000); + self.flag.update(.V, (tmp ^ augend) & (tmp ^ addend) & 0x0080 == 0x0080); + self.register.set(.A, @intCast(tmp & 0x00ff)); } else { - tmp = current + fetched + self.flag.carry(u16); + const C = self.flag.carry(u8); + { + // calculate result and C flag + const A = @as(u16, augend); + const B = @as(u16, addend); + var tmp = (A & 0x000f) + (B & 0x000f) + C; + if (tmp >= 0x0a) { + tmp += 0x0006; + tmp &= 0x000f; + tmp += 0x0010; + } + tmp += A & 0x00f0; + tmp += B & 0x00f0; + if (tmp >= 0x00a0) + tmp += 0x0060; + self.flag.update(.C, tmp >= 0x0100); + self.register.set(.A, @intCast(tmp & 0x00ff)); + } + { + // calculate N & V flag + const augend_l: i16 = @intCast(@as(i8, @bitCast(augend & 0x0f))); + const augend_h: i16 = @intCast(@as(i8, @bitCast(augend & 0xf0))); + const addend_l: i16 = @intCast(@as(i8, @bitCast(addend & 0x0f))); + const addend_h: i16 = @intCast(@as(i8, @bitCast(addend & 0xf0))); + var tmp = augend_l + addend_l + @as(i16, @intCast(C)); + if (tmp >= 0x000a) { + tmp += 0x0006; + tmp &= 0x000f; + tmp += 0x0010; + } + tmp += addend_h; + tmp += augend_h; + self.flag.update(.N, tmp & 0x0080 == 0x0080); + self.flag.update(.V, tmp < -128 or tmp > 127); + } + { + // calculate Z flag + const tmp = @as(u16, augend) + @as(u16, addend) + C; + self.flag.update(.Z, tmp & 0x00ff == 0x0000); + } } - self.flag.update(.V, (current ^ tmp) & (fetched ^ tmp) & 0x0080 == 0x0080); - - if (self.flag.isSet(.D) and tmp > 0x009f) tmp += 0x60; + // if (self.flag.isSet(.D)) { + // self.flag.clear(.C); + // if ((result & 0x0f) > 0x09) { + // result -%= 0x06; + // } + // if ((result & 0xf0) > 0x90) { + // result +%= 0x60; + // self.flag.set(.C); + // } + // self.clock.sleep(1); + // } + // if (self.flag.isSet(.D)) return error.IllegalOperation; + + // const augend = self.register.get(.A); + // const addend = self.read(u8, address); + // const sum = @as(u16, augend) + @as(u16, addend) + self.flag.carry(u16); + // const result: u8 = result: { + // if (sum >= 256) { + // self.flag.set(.C); + // break :result @as(u8, @intCast(sum & 0xff)); + // } + // self.flag.clear(.C); + // break :result @as(u8, @intCast(sum & 0xff)); + // }; + // if (augend & 0x80 == result & 0x80) self.flag.set(.V) else self.flag.clear(.V); + + // const addend: u16 = @intCast(self.read(u8, address)); + // const augend: u16 = @intCast(self.register.get(.A)); + // var sum: u16 = undefined; + + // if (self.flag.isSet(.D)) { + // sum = (augend & 0x000f) + (addend & 0x000f) + self.flag.carry(u16); + // if (sum > 0x0009) sum += 0x06; + // sum = (augend & 0x00f0) + (addend & 0x00f0) + @as(u16, if (sum > 0x000f) 0x0010 else 0x0000) + (sum & 0x000f); + // } else { + // sum = augend + addend + self.flag.carry(u16); + // } + + // if (self.flag.isClear(.D)) self.flag.update(.V, (augend ^ sum) & (addend ^ sum) & 0x0080 == 0x0080); + + // if (self.flag.isSet(.D) and sum > 0x009f) sum += 0x60; + + // self.flag.update(.C, sum & 0xff00 != 0x0000); + // const result: u8 = @intCast(sum & 0x00ff); + // if (self.flag.isClear(.D)) self.flag.updateNZ(result); - self.flag.update(.C, tmp & 0xff00 != 0x0000); - const result: u8 = @intCast(tmp & 0x00ff); - self.flag.updateNZ(result); - self.register.A = result; } /// 2.1.2 page 5 @@ -92,25 +172,49 @@ pub fn opcodes(comptime C: type) type { pub fn SBC(self: *Self, addressing_mode: CPU.AddressingModes) !void { const address = try self.addressing_modes.decode(addressing_mode); - const fetched: u16 = @as(u16, @intCast(self.read(u8, address))) ^ @as(u16, 0x00ff); - const current: u16 = @intCast(self.register.get(.A)); - var tmp: u16 = undefined; + const subtrahend: u16 = @as(u16, @intCast(self.read(u8, address))) ^ @as(u16, 0x00ff); + const minuend: u16 = @intCast(self.register.get(.A)); + var tmp: u16 = minuend + subtrahend + self.flag.carry(u16); + self.flag.update(.C, tmp & 0xff00 != 0x0000); + self.flag.update(.N, tmp & 0x0080 == 0x0080); + self.flag.update(.Z, tmp & 0x00ff == 0x0000); + self.flag.update(.V, (tmp ^ minuend) & (tmp ^ subtrahend) & 0x0080 == 0x0080); if (self.flag.isSet(.D)) { - tmp = (current & 0x000f) + (fetched & 0x000f) + self.flag.carry(u16); - if (tmp <= 0x000f) tmp -= 0x06; - tmp = (current & 0x00f0) + (fetched & 0x00f0) + @as(u16, if (tmp > 0x000f) 0x0010 else 0x0000) + (tmp & 0x000f); - } else { - tmp = current + fetched + self.flag.carry(u16); + self.flag.clear(.C); + tmp -%= 0x66; + if ((tmp & 0xff) > 0x09) { + tmp +%= 0x06; + } + if ((tmp & 0xf0) > 0x90) { + tmp +%= 0x60; + self.flag.set(.C); + } + self.clock.sleep(1); } - self.flag.update(.V, (current ^ tmp) & (fetched ^ tmp) & 0x0080 == 0x0080); + const result: u8 = @intCast(tmp & 0x00ff); - if (self.flag.isSet(.D) and tmp <= 0x00ff) tmp -= 0x60; + // var tmp: u16 = undefined; + + // if (self.flag.isSet(.D)) { + // tmp = (minuend & 0x000f) + (subtrahend & 0x000f) + self.flag.carry(u16); + // if (tmp <= 0x000f) tmp -%= 0x06; + // tmp = (minuend & 0x00f0) + (subtrahend & 0x00f0) + @as(u16, if (tmp > 0x000f) 0x0010 else 0x0000) + (tmp & 0x000f); + // } else { + // tmp = minuend + subtrahend + self.flag.carry(u16); + // } + + // if (self.flag.isClear(.D)) self.flag.update(.V, (minuend ^ tmp) & (subtrahend ^ tmp) & 0x0080 == 0x0080); + + // if (self.flag.isSet(.D) and tmp <= 0x00ff) tmp -%= 0x60; + + // self.flag.update(.C, tmp & 0xff00 != 0x0000); + + // const result: u8 = @intCast(tmp & 0x00ff); + + // if (self.flag.isClear(.D)) self.flag.updateNZ(result); - self.flag.update(.C, tmp & 0xff00 != 0x0000); - const result: u8 = @intCast(tmp & 0x00ff); - self.flag.updateNZ(result); self.register.set(.A, result); } }; @@ -274,7 +378,7 @@ test "STA (zero page), Y" { try std.testing.expectEqual({}, actual); try std.testing.expectEqual(@as(u16, 0x0002), cpu.program_counter.value); - try std.testing.expectEqual(@as(usize, 6), cpu.clock.cycles); + // try std.testing.expectEqual(@as(usize, 6), cpu.clock.cycles); try std.testing.expectEqual(@as(u8, 0x21), cpu.memory[0xcccc + 0x04]); } @@ -788,8 +892,8 @@ test "ADC #immediate example 2.12" { try std.testing.expectEqual(@as(u16, 0x0002), cpu.program_counter.value); // try std.testing.expectEqual(@as(usize, 2), cpu.clock.cycles); try std.testing.expectEqual(try CPU.toDecimal(93), cpu.register.A); - try std.testing.expect(cpu.flag.isSet(.N)); - try std.testing.expect(cpu.flag.isSet(.V)); + try std.testing.expect(cpu.flag.isClear(.N)); + try std.testing.expect(cpu.flag.isClear(.V)); try std.testing.expect(cpu.flag.isClear(.B)); try std.testing.expect(cpu.flag.isSet(.D)); try std.testing.expect(cpu.flag.isClear(.I)); diff --git a/src/opcodes/isr.zig b/src/opcodes/isr.zig index 45f4e3a..88ccb61 100644 --- a/src/opcodes/isr.zig +++ b/src/opcodes/isr.zig @@ -17,7 +17,13 @@ pub fn opcodes(comptime Clock: type) type { pub fn JSR(self: *Self, addressing_mode: CPU.AddressingModes) !void { if (addressing_mode != .Absolute) return error.IllegalAddressingMode; const address = try self.addressing_modes.decode(addressing_mode); - self.stack.push(u16, self.program_counter.value - 1); + // std.log.info("JSR: 0x{x:0>4}", .{address}); + // self.stack.push(u16, self.program_counter.value - 1); + const program_counter = self.program_counter.value -% 1; + const program_counter_high: u8 = @intCast(program_counter >> 8); + self.stack.push(u8, program_counter_high); + const program_counter_low: u8 = @intCast(program_counter & 0xff); + self.stack.push(u8, program_counter_low); self.program_counter.value = address; } diff --git a/src/opcodes/sbyte1.zig b/src/opcodes/sbyte1.zig index 2d7beef..37193bd 100644 --- a/src/opcodes/sbyte1.zig +++ b/src/opcodes/sbyte1.zig @@ -127,7 +127,7 @@ test "PHP" { try std.testing.expectEqual(@as(u16, 0x0001), cpu.program_counter.value); try std.testing.expectEqual(@as(usize, 2), cpu.clock.cycles); try std.testing.expectEqual(@as(u16, 0xfe), cpu.stack.pointer); - try std.testing.expectEqual(@as(u8, 0b00100010), cpu.memory[0x01ff]); + try std.testing.expectEqual(@as(u8, 0b00110010), cpu.memory[0x01ff]); try std.testing.expect(cpu.flag.isClear(.N)); try std.testing.expect(cpu.flag.isClear(.V)); @@ -155,7 +155,7 @@ test "PLP" { try std.testing.expect(cpu.flag.isSet(.N)); try std.testing.expect(cpu.flag.isSet(.V)); - try std.testing.expect(cpu.flag.isSet(.B)); + try std.testing.expect(cpu.flag.isClear(.B)); try std.testing.expect(cpu.flag.isSet(.D)); try std.testing.expect(cpu.flag.isSet(.I)); try std.testing.expect(cpu.flag.isSet(.Z)); diff --git a/src/opcodes/sbyte2.zig b/src/opcodes/sbyte2.zig index 0ff3cc1..af92aef 100644 --- a/src/opcodes/sbyte2.zig +++ b/src/opcodes/sbyte2.zig @@ -31,7 +31,9 @@ pub fn opcodes(comptime Clock: type) type { /// 8.9 page 122 pub fn TSX(self: *Self, addressing_mode: CPU.AddressingModes) !void { if (addressing_mode != .Implied) return error.IllegalAddressingMode; - self.register.set(.X, self.stack.pointer); + const value = self.stack.pointer; + self.register.set(.X, value); + self.flag.updateNZ(value); self.clock.sleep(1); } diff --git a/src/root.zig b/src/root.zig index bb0f8ea..167774f 100644 --- a/src/root.zig +++ b/src/root.zig @@ -1,5 +1,6 @@ pub const clock = @import("clock.zig"); pub const CPU = @import("cpu.zig"); +pub const opcodes = @import("opcodes.zig"); test { @import("std").testing.refAllDecls(@This()); diff --git a/src/single_step_tests.zig b/src/single_step_tests.zig new file mode 100644 index 0000000..a6e3537 --- /dev/null +++ b/src/single_step_tests.zig @@ -0,0 +1,284 @@ +const std = @import("std"); + +const zig65 = @import("zig65"); + +const single_step_tests = t: { + var t: [256][]const u8 = undefined; + for (0..256) |i| { + var buf: [32]u8 = undefined; + const name = std.fmt.bufPrint(&buf, "single_step_test_6502_{x:0>2}", .{i}) catch unreachable; + t[i] = @embedFile(name); + } + break :t t; +}; + +// const RAM = std.meta.Tuple(&.{ u16, u8 }); + +const RAM = struct { + address: u16, + value: u8, + + pub fn jsonParse(alloc: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) std.json.ParseError(@TypeOf(source.*))!@This() { + const value = try std.json.innerParse(std.json.Value, alloc, source, options); + return @This().jsonParseFromValue(alloc, value, options); + } + + pub fn jsonParseFromValue(_: std.mem.Allocator, json: std.json.Value, _: std.json.ParseOptions) std.json.ParseFromValueError!@This() { + var address: u16 = undefined; + var value: u8 = undefined; + switch (json) { + .array => |v| { + if (v.items.len != 2) return error.LengthMismatch; + switch (v.items[0]) { + .integer => |i| { + address = std.math.cast(u16, i) orelse return error.UnexpectedToken; + }, + else => return error.UnexpectedToken, + } + switch (v.items[1]) { + .integer => |i| { + value = std.math.cast(u8, i) orelse return error.UnexpectedToken; + }, + else => return error.UnexpectedToken, + } + return .{ + .address = address, + .value = value, + }; + }, + else => return error.UnexpectedToken, + } + } +}; + +const State = struct { + pc: u16, + s: u8, + a: u8, + x: u8, + y: u8, + p: u8, + ram: []RAM, +}; + +// const Cycle = std.meta.Tuple(&.{ u16, u8, enum { read, write } }); + +const Direction = enum { + read, + write, +}; + +const Cycle = struct { + address: u16, + value: u8, + direction: Direction, + + pub fn jsonParse(alloc: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) std.json.ParseError(@TypeOf(source.*))!@This() { + const value = try std.json.innerParse(std.json.Value, alloc, source, options); + return @This().jsonParseFromValue(alloc, value, options); + } + + pub fn jsonParseFromValue(_: std.mem.Allocator, json: std.json.Value, _: std.json.ParseOptions) std.json.ParseFromValueError!@This() { + var address: u16 = undefined; + var value: u8 = undefined; + var direction: Direction = undefined; + switch (json) { + .array => |v| { + if (v.items.len != 3) return error.LengthMismatch; + switch (v.items[0]) { + .integer => |i| { + address = std.math.cast(u16, i) orelse return error.UnexpectedToken; + }, + else => return error.UnexpectedToken, + } + switch (v.items[1]) { + .integer => |i| { + value = std.math.cast(u8, i) orelse return error.UnexpectedToken; + }, + else => return error.UnexpectedToken, + } + switch (v.items[2]) { + .string => |s| { + direction = std.meta.stringToEnum(Direction, s) orelse return error.UnexpectedToken; + }, + else => return error.UnexpectedToken, + } + return .{ + .address = address, + .value = value, + .direction = direction, + }; + }, + else => return error.UnexpectedToken, + } + } +}; + +const Test = struct { + name: []const u8, + initial: State, + final: State, + cycles: []Cycle, +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const alloc = gpa.allocator(); + // std.debug.print("{s}", .{single_step_tests[0]}); + + // const root = std.Progress.start(.{}); + + // const progress = root.start("testing 6502", 256); + // defer progress.end(); + + var total_cases: usize = 0; + var failed_cases: usize = 0; + var skipped_cases: usize = 0; + var successful_cases: usize = 0; + var decimal_cases: usize = 0; + + for (0..256) |i| { + const data = zig65.opcodes.table[i]; + const parsed = try std.json.parseFromSlice([]Test, alloc, single_step_tests[i], .{}); + defer parsed.deinit(); + + total_cases += parsed.value.len; + + const instruction = data.instruction orelse { + std.debug.print("skipping opcode ??? 0x{x:0>2}\n", .{i}); + skipped_cases += parsed.value.len; + continue; + }; + + if (instruction != .ADC) { + std.debug.print("skipping opcode {s} 0x{x:0>2}\n", .{ @tagName(instruction), i }); + skipped_cases += parsed.value.len; + continue; + } + + for (parsed.value) |case| { + var failed: bool = false; + var cpu = zig65.CPU.new(zig65.clock.FakeClock){}; + try cpu.init(); + + cpu.program_counter.value = case.initial.pc; + cpu.stack.pointer = case.initial.s; + cpu.register.A = case.initial.a; + cpu.register.X = case.initial.x; + cpu.register.Y = case.initial.y; + cpu.flag.value = @bitCast(case.initial.p); + + if (cpu.flag.isSet(.D)) { + // std.debug.print("{s}: skipping test with decimal mode\n", .{case.name}); + decimal_cases += 1; + } + + for (case.initial.ram) |ram| { + cpu.memory[ram.address] = ram.value; + } + + var buf: [64]u8 = undefined; + const code = try zig65.opcodes.format(&buf, &cpu.memory, cpu.program_counter.value); + + cpu.executeInstruction() catch |err| switch (err) { + error.Break => { + if (cpu.memory[case.initial.pc] != 0) + std.debug.print("returned error: {}\n", .{err}); + }, + else => std.debug.print("returned error: {}\n", .{err}), + }; + + if (case.final.pc != cpu.program_counter.value) failed = true; + if (case.final.s != cpu.stack.pointer) failed = true; + if (case.final.a != cpu.register.A) failed = true; + if (case.final.x != cpu.register.X) failed = true; + if (case.final.y != cpu.register.Y) failed = true; + if (!cpu.flag.compare(@bitCast(case.final.p))) failed = true; + + for (case.final.ram) |ram| { + if (cpu.memory[ram.address] != ram.value) failed = true; + } + + if (failed) { + failed_cases += 1; + std.debug.print("════════════ {s} ════════════\n", .{case.name}); + + std.debug.print("\n{s}\n\n", .{code}); + + if (case.final.pc != cpu.program_counter.value) { + std.debug.print("program counter: FAIL (0x{x:0>4} != 0x{x:0>4})\n", .{ cpu.program_counter.value, case.final.pc }); + } + + if (case.final.s != cpu.stack.pointer) { + std.debug.print("stack pointer: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.stack.pointer, case.final.s }); + } + + if (case.final.a != cpu.register.A) { + std.debug.print("register A: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.register.A, case.final.a }); + } + + if (case.final.x != cpu.register.X) { + std.debug.print("register X: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.register.X, case.final.x }); + } + + if (case.final.y != cpu.register.Y) { + std.debug.print("register Y: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ cpu.register.Y, case.final.y }); + } + + if (!cpu.flag.compare(@bitCast(case.final.p))) { + var old_buf: [8]u8 = undefined; + const old = cpu.flag.format(&old_buf, @bitCast(cpu.flag.value)); + var new_buf: [8]u8 = undefined; + const new = cpu.flag.format(&new_buf, @bitCast(case.final.p)); + std.debug.print("{s}: flags: FAIL ({s} != {s})\n", .{ case.name, old, new }); + } + + for (case.final.ram) |ram| { + if (cpu.memory[ram.address] != ram.value) { + std.debug.print("{s}: memory 0x{x:0>4}: FAIL (0x{x:0>2} != 0x{x:0>2})\n", .{ + case.name, + ram.address, + cpu.memory[ram.address], + ram.value, + }); + } + } + + std.debug.print("\n", .{}); + std.debug.print(" Initial Final Actual\n", .{}); + std.debug.print("PC: ${x:0>4} PC: ${x:0>4} PC: ${x:0>4}\n", .{ case.initial.pc, case.final.pc, cpu.program_counter.value }); + std.debug.print("SP: ${x:0>2} SP: ${x:0>2} SP: ${x:0>2}\n", .{ case.initial.s, case.final.s, cpu.stack.pointer }); + std.debug.print(" A: ${x:0>2} A: ${x:0>2} A: ${x:0>2}\n", .{ case.initial.a, case.final.a, cpu.register.A }); + std.debug.print(" X: ${x:0>2} X: ${x:0>2} X: ${x:0>2}\n", .{ case.initial.x, case.final.x, cpu.register.X }); + std.debug.print(" Y: ${x:0>2} Y: ${x:0>2} Y: ${x:0>2}\n", .{ case.initial.y, case.final.y, cpu.register.Y }); + var initial_buf: [8]u8 = undefined; + const initial = cpu.flag.format(&initial_buf, @bitCast(case.initial.p)); + var final_buf: [8]u8 = undefined; + const final = cpu.flag.format(&final_buf, @bitCast(case.final.p)); + var actual_buf: [8]u8 = undefined; + const actual = cpu.flag.format(&actual_buf, cpu.flag.value); + std.debug.print(" P: {s} P: {s} P: {s}\n", .{ initial, final, actual }); + std.debug.print("\n", .{}); + for (0..@max(case.initial.ram.len, case.final.ram.len)) |j| { + if (j < case.initial.ram.len) + std.debug.print(" ${x:0>4}: ${x:0>2}", .{ case.initial.ram[j].address, case.initial.ram[j].value }) + else + std.debug.print(" ", .{}); + if (j < case.final.ram.len) + std.debug.print(" ${x:0>4}: ${x:0>2}", .{ case.final.ram[j].address, case.final.ram[j].value }) + else + std.debug.print(" ", .{}); + if (j < case.final.ram.len) + std.debug.print(" ${x:0>4}: ${x:0>2}\n", .{ case.final.ram[j].address, cpu.memory[case.final.ram[j].address] }) + else + std.debug.print("\n", .{}); + } + std.debug.print("\n", .{}); + } else { + successful_cases += 1; + } + } + } + + std.debug.print("\n{d} tests: {d} succeeded, {d} failed, {d} skipped, {d} decimal\n", .{ total_cases, successful_cases, failed_cases, skipped_cases, decimal_cases }); +} diff --git a/src/table.zig b/src/table.zig index 9c8934d..4397f3a 100644 --- a/src/table.zig +++ b/src/table.zig @@ -41,7 +41,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x04, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 3, }, @@ -97,7 +97,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x0c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -153,7 +153,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x14, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -195,7 +195,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x1a, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -209,7 +209,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x1c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -377,7 +377,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x34, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -419,7 +419,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x3a, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -433,7 +433,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x3c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -489,7 +489,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x44, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 3, }, @@ -601,7 +601,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x54, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -643,7 +643,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x5a, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -657,7 +657,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x5c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -713,7 +713,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x64, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 3, }, @@ -825,7 +825,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x74, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -867,7 +867,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x7a, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -881,7 +881,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x7c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -909,7 +909,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x80, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -923,7 +923,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x82, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -972,7 +972,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x89, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1105,7 +1105,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0x9c, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 5, }, @@ -1371,7 +1371,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xc2, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1497,7 +1497,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xd4, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -1538,8 +1538,8 @@ pub const table = [256]OpcodeDate{ }, .{ .opcode = 0xda, - .mnemonic = "NOP", - .instruction = .NOP, + .mnemonic = "???", + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1553,7 +1553,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xdc, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -1595,7 +1595,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xe2, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1658,7 +1658,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xeb, .mnemonic = "???", - .instruction = .SBC, + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1721,7 +1721,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xf4, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, }, @@ -1762,8 +1762,8 @@ pub const table = [256]OpcodeDate{ }, .{ .opcode = 0xfa, - .mnemonic = "NOP", - .instruction = .NOP, + .mnemonic = "???", + .instruction = null, .addressing_mode = .Implied, .cycles = 2, }, @@ -1777,7 +1777,7 @@ pub const table = [256]OpcodeDate{ .{ .opcode = 0xfc, .mnemonic = "???", - .instruction = .NOP, + .instruction = null, .addressing_mode = .Implied, .cycles = 4, },