huc6280/
alu.rs

1// SPDX-License-Identifier: MIT
2//! Arithmetic, logic and compare: ADC SBC AND ORA EOR CMP CPX CPY BIT
3//! (`_alu.py`).
4//!
5//! C13, decimal ADC and SBC (rewritten 2026-11-19, docs/restart.md; the
6//! reference's docs/restart.md). Neither Hudson manual says what the digit
7//! adjust does with a digit above 9, and no hardware result is known, so two
8//! emulators' behaviour is kept, each written in the reference from its own
9//! result table alone:
10//!
11//! - [`DecimalFormula::Mednafen`] (default): the table recorded by running
12//!   Mednafen 1.32.1 (patched for tracing only) as a closed box over every A,
13//!   operand and carry (the reference's `scripts/decimal_tables.py`).
14//!   OBSERVED, provisional; closed-box measurement (emulator tier, Mednafen
15//!   1.32.1).
16//! - [`DecimalFormula::Mesen`]: the 11,346 decimal ADC/SBC cases of
17//!   SingleStepTests huc6280 (MIT test data recorded from Mesen). OBSERVED,
18//!   provisional; closed-box measurement (emulator tier, the corpus's Mesen).
19//!
20//! The two agree whenever both digits of both inputs are 0-9. In both tables V
21//! is left as it was and N and Z come from the stored result (TEST ROM tier for
22//! the valid digits: the corpus and the Mednafen run agree, and both pass
23//! Dormann's and Rockwell's decimal cases).
24//!
25//! Differences forced by Rust: the formula is an enum, so the reference's
26//! `ValueError` for an unknown formula (raised when a decimal ADC or SBC runs)
27//! has no counterpart; the digit arithmetic is in `i32`, where Python's
28//! integers would go negative or past a byte.
29
30use crate::core::{nz, Bus, HuC6280, C, D, N, V, Z, ZERO_PAGE};
31use crate::dispatch::Mode;
32
33/// C13: the decimal digit adjust of ADC and SBC (the reference's
34/// `DECIMAL_FORMULAS = ("mednafen", "mesen")`).
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum DecimalFormula {
37    /// `"mednafen"` (default): Mednafen 1.32.1's results, recorded closed box.
38    Mednafen,
39    /// `"mesen"`: the SingleStepTests corpus's (Mesen's) results.
40    Mesen,
41}
42
43/// Decimal A + M + C: the 8-bit result and the carry out.
44fn decimal_add(a: u8, operand: u8, carry: u8, formula: DecimalFormula) -> (u8, bool) {
45    let (a, operand, carry) = (a as i32, operand as i32, carry as i32);
46    let mut low = (a & 0x0F) + (operand & 0x0F) + carry;
47    if formula == DecimalFormula::Mesen {
48        // Each digit on its own: above 9 it gains 6, and passes a carry of 1 to the next.
49        if low > 9 {
50            low += 6;
51        }
52        let mut high = (a >> 4) + (operand >> 4) + (low > 0x0F) as i32;
53        if high > 9 {
54            high += 6;
55        }
56        return (((high << 4) | (low & 0x0F)) as u8, high > 0x0F);
57    }
58    // Mednafen: the binary sum, plus 6 when the low digits' sum is above 9, then plus $60
59    // when what stands above the low digit is above 9 (so a low digit past $1F carries 2).
60    let mut total = a + operand + carry;
61    if low > 9 {
62        total += 0x06;
63    }
64    if total >> 4 > 9 {
65        total += 0x60;
66    }
67    (total as u8, total > 0xFF)
68}
69
70/// Decimal A - M - (1 - C): the 8-bit result and the carry out (no borrow).
71fn decimal_subtract(a: u8, operand: u8, carry: u8, formula: DecimalFormula) -> (u8, bool) {
72    let (a, operand) = (a as i32, operand as i32);
73    let borrow = 1 - carry as i32;
74    let mut low = (a & 0x0F) - (operand & 0x0F) - borrow;
75    if formula == DecimalFormula::Mesen {
76        // Each digit on its own: below 0 it loses 6, and takes a borrow of 1 from the next.
77        if low < 0 {
78            low -= 6;
79        }
80        let mut high = (a >> 4) - (operand >> 4) - (low < 0) as i32;
81        if high < 0 {
82            high -= 6;
83        }
84        return (((high << 4) | (low & 0x0F)) as u8, high >= 0);
85    }
86    // Mednafen: the binary difference, minus 6 when the low digits borrow, minus $60 when
87    // the whole subtraction borrows; the carry is the binary one.
88    let difference = a - operand - borrow;
89    let mut result = difference;
90    if low < 0 {
91        result -= 0x06;
92    }
93    if difference < 0 {
94        result -= 0x60;
95    }
96    (result as u8, difference >= 0)
97}
98
99/// ADC: (result, new P). Binary: N V Z C as the 6502 (SW SB-17); decimal: C13
100/// (the module's head).
101pub fn add(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
102    let carry = p & C;
103    if p & D != 0 {
104        let (result, carry_out) = decimal_add(a, operand, carry, formula);
105        return (
106            result,
107            (p & !(N | Z | C)) | nz(result) | if carry_out { C } else { 0 },
108        );
109    }
110    let total = a as u16 + operand as u16 + carry as u16;
111    let result = total as u8;
112    let overflow = !(a ^ operand) & (a ^ result) & 0x80;
113    let p = (p & !(N | V | Z | C)) | nz(result) | if overflow != 0 { V } else { 0 };
114    (result, p | if total > 0xFF { C } else { 0 })
115}
116
117/// SBC: (result, new P). Binary: N V Z C as the 6502 (SW SB-74); decimal: C13
118/// (the module's head).
119pub fn subtract(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
120    let carry = p & C;
121    if p & D != 0 {
122        let (result, carry_out) = decimal_subtract(a, operand, carry, formula);
123        return (
124            result,
125            (p & !(N | Z | C)) | nz(result) | if carry_out { C } else { 0 },
126        );
127    }
128    let difference = a as i32 - operand as i32 - (1 - carry as i32);
129    let result = difference as u8;
130    let overflow = (a ^ operand) & (a ^ result) & 0x80;
131    let p = (p & !(N | V | Z | C)) | nz(result) | if overflow != 0 { V } else { 0 };
132    (result, p | if difference >= 0 { C } else { 0 })
133}
134
135/// ADC's or SBC's arithmetic: [`add`] or [`subtract`].
136type Arithmetic = fn(u8, u8, u8, DecimalFormula) -> (u8, u8);
137
138impl<B: Bus> HuC6280<B> {
139    /// U4: T set, so the operation's other operand is M($2000 + X) and the
140    /// result goes back.
141    ///
142    /// The three extra cycles are a read, an internal cycle (two in decimal
143    /// mode, where the adjust takes one more) and a write.
144    fn memory_mode(
145        &mut self,
146        operand: u8,
147        operation: impl FnOnce(&mut Self, u8, u8) -> u8,
148        extra_cycle: bool,
149    ) {
150        let address = ZERO_PAGE | self.x as u16;
151        let memory = self.cycle_read(address);
152        self.io();
153        if extra_cycle {
154            self.io();
155        }
156        let result = operation(self, memory, operand);
157        self.set_nz(result);
158        self.cycle_write(address, result);
159    }
160
161    /// ORA -- A OR M -> A, or M(X) OR M -> M(X) with T set (SW SB-58).
162    pub(crate) fn op_ora(&mut self, mode: Mode) {
163        let address = self.ea(mode);
164        let operand = self.load(address);
165        if self.t != 0 {
166            self.memory_mode(operand, |_, memory, value| memory | value, false);
167        } else {
168            self.a = self.set_nz(self.a | operand);
169        }
170    }
171
172    /// AND -- A AND M -> A, or M(X) AND M -> M(X) with T set (SW SB-18).
173    pub(crate) fn op_and(&mut self, mode: Mode) {
174        let address = self.ea(mode);
175        let operand = self.load(address);
176        if self.t != 0 {
177            self.memory_mode(operand, |_, memory, value| memory & value, false);
178        } else {
179            self.a = self.set_nz(self.a & operand);
180        }
181    }
182
183    /// EOR -- A EOR M -> A, or M(X) EOR M -> M(X) with T set (SW SB-47).
184    pub(crate) fn op_eor(&mut self, mode: Mode) {
185        let address = self.ea(mode);
186        let operand = self.load(address);
187        if self.t != 0 {
188            self.memory_mode(operand, |_, memory, value| memory ^ value, false);
189        } else {
190            self.a = self.set_nz(self.a ^ operand);
191        }
192    }
193
194    fn arithmetic(&mut self, mode: Mode, operation: Arithmetic, uses_t: bool) {
195        let address = self.ea(mode);
196        let operand = self.load(address);
197        let decimal = self.p & D != 0;
198        if uses_t && self.t != 0 {
199            // The adjust's extra cycle (U14) sits among the memory-mode cycles.
200            self.memory_mode(
201                operand,
202                |cpu, memory, value| {
203                    let (result, p) = operation(memory, value, cpu.p, cpu.decimal_formula);
204                    cpu.p = p;
205                    result
206                },
207                decimal,
208            );
209            return;
210        }
211        if decimal {
212            // U14: the extra cycle. A dummy read at the next opcode, or an
213            // internal cycle for SBC while T is set (it does not use the
214            // memory mode but keeps its cycle; what the SingleStepTests
215            // corpus records, emulator tier).
216            if self.t != 0 {
217                self.io();
218            } else {
219                self.dummy(self.pc);
220            }
221        }
222        (self.a, self.p) = operation(self.a, operand, self.p, self.decimal_formula);
223    }
224
225    /// ADC -- A + M + C -> A, or M(X) + M + C -> M(X) with T set (SW SB-17).
226    pub(crate) fn op_adc(&mut self, mode: Mode) {
227        self.arithmetic(mode, add, true);
228    }
229
230    /// SBC -- A - M - (1 - C) -> A; T is ignored (C5) (SW SB-74).
231    pub(crate) fn op_sbc(&mut self, mode: Mode) {
232        self.arithmetic(mode, subtract, self.sbc_honours_t);
233    }
234
235    fn compare(&mut self, register: u8, operand: u8) {
236        let difference = register.wrapping_sub(operand);
237        let mut p = self.p & !(N | Z | C);
238        if register >= operand {
239            p |= C;
240        }
241        self.p = p | crate::core::nz(difference);
242    }
243
244    /// CMP -- A - M, flags only (SW SB-41).
245    pub(crate) fn op_cmp(&mut self, mode: Mode) {
246        let address = self.ea(mode);
247        let operand = self.load(address);
248        self.compare(self.a, operand);
249    }
250
251    /// CPX -- X - M, flags only (SW SB-42).
252    pub(crate) fn op_cpx(&mut self, mode: Mode) {
253        let address = self.ea(mode);
254        let operand = self.load(address);
255        self.compare(self.x, operand);
256    }
257
258    /// CPY -- Y - M, flags only (SW SB-43).
259    pub(crate) fn op_cpy(&mut self, mode: Mode) {
260        let address = self.ea(mode);
261        let operand = self.load(address);
262        self.compare(self.y, operand);
263    }
264
265    fn bit_flags(&mut self, operand: u8, mask_with: u8) {
266        // U19: N and V come from the operand, Z from the AND; HW HB-5, SW BIT.
267        let mut p = (self.p & !(N | V | Z)) | (operand & (N | V));
268        if mask_with & operand == 0 {
269            p |= Z;
270        }
271        self.p = p;
272    }
273
274    /// BIT -- A AND M sets Z; M bits 7 and 6 -> N and V, immediate form too
275    /// (U19) (SW SB-25).
276    pub(crate) fn op_bit(&mut self, mode: Mode) {
277        let address = self.ea(mode);
278        let operand = self.load(address);
279        self.bit_flags(operand, self.a);
280    }
281}