rx82 0.5.0

An emulator for the RX82 fantasy retro computer system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
use core::fmt::{Display, Formatter};

use crate::{
    bus::Bus,
    instructions::{InstructionKind, Operands},
    regs::{Reg, Regs, source_and_target_from, source_from},
    system::Device,
};

use State::*;

/// Trap code for the 'illegal instruction' trap.
pub const TRAP_ILLEGAL: u8 = 0x00;

/// The hard-wired reset vector address.
pub const VEC_RESET: u16 = 0xFFFE;

/// The system CPU.
#[non_exhaustive]
#[derive(Debug)]
pub struct Cpu {
    /// Flags.
    pub flags: Flags,
    /// Is the CPU halted?
    pub halt: bool,
    /// The current instruction.
    pub ins: InstructionKind,
    /// The current operand (high byte).
    pub op_hi: u8,
    /// The current operand (low byte).
    pub op_lo: u8,
    /// The program counter.
    pub pc: u16,
    /// The CPU's registers.
    pub regs: Regs,
    /// The current state.
    pub state: State,
}

impl Default for Cpu {
    #[inline]
    fn default() -> Self {
        Self {
            flags: Flags::default(),
            halt: Default::default(),
            ins: InstructionKind::Nop,
            op_hi: Default::default(),
            op_lo: Default::default(),
            pc: Default::default(),
            state: State::default(),
            regs: Regs::default(),
        }
    }
}

impl Device for Cpu {
    /// Transitions to the next state.
    #[expect(clippy::too_many_lines, reason = "it's just long")]
    #[inline]
    fn tick(&mut self, bus: &mut Bus) {
        self.state = match self.state {
            Decode => {
                let opcode = bus.data;
                let Ok(ins) = InstructionKind::try_from(opcode) else {
                    self.trap(TRAP_ILLEGAL, bus);
                    return;
                };
                self.ins = ins;
                match self.ins.operands() {
                    Operands::Zero => {
                        // No operands needed, go straight to 'execute'
                        bus.disable_mem();
                        Execute
                    }
                    Operands::One => {
                        self.fetch_and_advance(bus);
                        WaitOp
                    }
                    Operands::Two => {
                        self.fetch_and_advance(bus);
                        WaitOpLo
                    }
                }
            }
            Execute => {
                let ins = self.ins;
                // default next state, but may be overridden by instruction
                self.state = FetchOpcode;
                ins.execute(self, bus);
                self.state
            }
            FetchOpcode => {
                if self.halt {
                    FetchOpcode
                } else {
                    self.fetch_and_advance(bus);
                    WaitOpcode
                }
            }
            ReadDec(addr) => {
                let mut val = bus.data;
                val = val.wrapping_sub(1);
                bus.write_mem(addr, val);
                self.flags.zero = val == 0;
                FetchOpcode
            }
            ReadInc(addr) => {
                let mut val = bus.data;
                val = val.wrapping_add(1);
                bus.write_mem(addr, val);
                self.flags.zero = val == 0;
                FetchOpcode
            }
            ReadLoad(reg) => {
                self.op_lo = bus.data;
                self.regs.set(reg, self.op());
                FetchOpcode
            }
            ReadOp => {
                self.op_hi = 0;
                self.op_lo = bus.data;
                Execute
            }
            ReadOpLo => {
                self.op_lo = bus.data;
                self.fetch_and_advance(bus);
                WaitOpHi
            }
            ReadOpHi => {
                self.op_hi = bus.data;
                Execute
            }
            ReadResetLo => {
                self.op_lo = bus.data;
                bus.read_mem(VEC_RESET.wrapping_add(1));
                WaitAddrHi
            }
            ReadAddrHi => {
                self.op_hi = bus.data;
                self.pc = self.op();
                FetchOpcode
            }
            ReadRetHi => {
                self.op_hi = bus.data;
                self.stack_pop(bus);
                WaitRetLo
            }
            ReadRetLo => {
                self.op_lo = bus.data;
                self.pc = self.op();
                FetchOpcode
            }
            ReadStackHi(reg) => {
                self.op_hi = bus.data;
                self.stack_pop(bus);
                WaitLoad(reg)
            }
            ReadTrapVecLo(addr) => {
                self.op_lo = bus.data;
                bus.read_mem(addr);
                WaitAddrHi
            }
            WaitCall(hi, subr_addr) => {
                self.stack_push(hi, bus);
                self.pc = subr_addr;
                FetchOpcode
            }
            WaitDec(addr) => ReadDec(addr),
            WaitInc(addr) => ReadInc(addr),
            WaitLoad(reg) => ReadLoad(reg),
            WaitOp => ReadOp,
            WaitOpLo => ReadOpLo,
            WaitOpHi => ReadOpHi,
            WaitOpcode => Decode,
            WaitResetLo => ReadResetLo,
            WaitAddrHi => ReadAddrHi,
            WaitStackHi(reg) => ReadStackHi(reg),
            WaitPush(val) => {
                self.stack_push(val, bus);
                FetchOpcode
            }
            WaitRetHi => ReadRetHi,
            WaitRetLo => ReadRetLo,
            WaitTrapCode(trap_code) => {
                let mut vec_addr = u16::from(trap_code.strict_mul(2));
                bus.read_mem(vec_addr);
                vec_addr = vec_addr.wrapping_add(1);
                WaitTrapVecLo(vec_addr)
            }
            WaitTrapLo(hi, trap_code) => {
                self.stack_push(hi, bus);
                WaitTrapHi(trap_code)
            }
            WaitTrapHi(trap_code) => {
                self.stack_push(trap_code, bus);
                WaitTrapCode(trap_code)
            }
            WaitTrapVecLo(addr) => ReadTrapVecLo(addr),
        };
    }
}

impl Cpu {
    /// Branches to PC+`dis`.
    #[expect(clippy::cast_possible_wrap, reason = "i8 to u16 is sound")]
    #[expect(clippy::cast_sign_loss, reason = "okay with wrapping_add")]
    #[inline]
    pub fn branch(&mut self, dis: u8) {
        self.pc = self.pc.wrapping_add(dis as i8 as u16); // sign-extend displacement
    }

    /// Calls the subroutine at `addr`, pushing the return address on the stack.
    #[inline]
    pub fn call(&mut self, addr: u16, bus: &mut Bus) {
        let ret_addr = self.pc;
        let [hi, lo] = ret_addr.to_be_bytes();
        self.stack_push(lo, bus);
        self.state = WaitCall(hi, addr);
    }

    /// Compares the value in register `reg` with the operand, updating flags.
    #[inline]
    pub fn cmp(&mut self, reg: Reg, rhs: u16) {
        let lhs = self.regs.get(reg);
        self.flags.zero = lhs == rhs;
        self.flags.carry = lhs >= rhs;
    }

    /// Decrements the value at the address in `reg`, updating flags.
    #[inline]
    pub fn dec_indirect(&mut self, bus: &mut Bus) {
        if let Some(source) = source_from(self.op_lo)
            && source.is16()
        {
            let addr = self.regs.get(source);
            self.dec_mem(addr, bus);
        } else {
            self.trap(TRAP_ILLEGAL, bus);
        }
    }

    /// Decrements the value at the address `addr`, updating flags.
    #[inline]
    pub fn dec_mem(&mut self, addr: u16, bus: &mut Bus) {
        bus.read_mem(addr);
        self.state = WaitDec(addr);
    }

    /// Decrements the value in register `reg`, updating flags.
    #[inline]
    pub fn decrement(&mut self, reg: Reg) {
        let value = self.regs.get(reg).wrapping_sub(1);
        self.flags.zero = self.regs.set(reg, value) == 0;
    }

    /// Issues a memory fetch and advances PC.
    #[inline]
    pub fn fetch_and_advance(&mut self, bus: &mut Bus) {
        bus.read_mem(self.pc);
        self.pc = self.pc.wrapping_add(1);
    }

    /// Halts the CPU.
    #[inline]
    pub fn halt(&mut self) {
        self.halt = true;
    }

    /// Increments the value at the address in `reg`, updating flags.
    #[inline]
    pub fn inc_indirect(&mut self, bus: &mut Bus) {
        if let Some(source) = source_from(self.op_lo)
            && source.is16()
        {
            let addr = self.regs.get(source);
            self.inc_mem(addr, bus);
        } else {
            self.trap(TRAP_ILLEGAL, bus);
        }
    }

    /// Increments the value at the address `addr`, updating flags.
    #[inline]
    pub fn inc_mem(&mut self, addr: u16, bus: &mut Bus) {
        bus.read_mem(addr);
        self.state = WaitInc(addr);
    }

    /// Increments the value in register `reg`, updating flags.
    #[inline]
    pub fn increment(&mut self, reg: Reg) {
        let value = self.regs.get(reg).wrapping_add(1);
        self.flags.zero = self.regs.set(reg, value) == 0;
    }

    /// Executes a load register indirect instruction.
    #[inline]
    pub fn ld_reg_indirect(&mut self, bus: &mut Bus) {
        if let Some((source, target)) = source_and_target_from(self.op_lo) {
            bus.read_mem(self.regs.get(source));
            self.state = WaitLoad(target);
        } else {
            self.trap(TRAP_ILLEGAL, bus);
        }
    }

    /// Executes a load register register instruction.
    #[inline]
    pub fn ld_reg_reg(&mut self, bus: &mut Bus) {
        if let Some((source, target)) = source_and_target_from(self.op_lo)
            && source.is16() == target.is16()
        {
            self.regs.set(target, self.regs.get(source));
        } else {
            self.trap(TRAP_ILLEGAL, bus);
        }
    }

    /// Returns the 16-bit value of the two operand registers.
    #[inline]
    #[must_use]
    pub fn op(&self) -> u16 {
        u16::from_be_bytes([self.op_hi, self.op_lo])
    }

    /// Executes a `pop` instruction with `reg`.
    #[inline]
    pub fn pop(&mut self, reg: Reg, bus: &mut Bus) {
        self.stack_pop(bus);
        if reg.is16() {
            self.state = WaitStackHi(reg);
        } else {
            self.op_hi = 0;
            self.state = WaitLoad(reg);
        }
    }

    /// Executes a `push` instruction with `reg`.
    #[expect(clippy::cast_possible_truncation, reason = "truncation is correct")]
    #[inline]
    pub fn push(&mut self, reg: Reg, bus: &mut Bus) {
        let val = self.regs.get(reg);
        if reg.is16() {
            let [hi, lo] = val.to_be_bytes();
            self.stack_push(lo, bus);
            self.state = WaitPush(hi);
        } else {
            self.stack_push(val as u8, bus);
        }
    }

    /// Resets the CPU to its power-on state.
    ///
    /// The initial state is: all registers and flags zero, not halted, state
    /// [`WaitResetLo`]. On the next tick, the CPU will request the low byte of the
    /// reset vector from the address [`VEC_RESET`].
    #[inline]
    pub fn reset(&mut self, bus: &mut Bus) {
        *self = Self::default();
        bus.read_mem(VEC_RESET);
        self.state = WaitResetLo;
    }

    /// Returns from a subroutine to a return address on the stack.
    #[inline]
    pub fn ret(&mut self, bus: &mut Bus) {
        self.stack_pop(bus);
        self.state = WaitRetHi;
    }

    /// Returns from a trap to a return address on the stack.
    #[inline]
    pub fn rti(&mut self, bus: &mut Bus) {
        let mut addr = self.regs.get(Reg::SP);
        addr = addr.wrapping_add(2); // skip trap code
        bus.read_mem(addr);
        self.regs.set(Reg::SP, addr);
        self.state = WaitRetHi;
    }

    /// Reads the current top-of-stack value, adjusting SP.
    #[inline]
    pub fn stack_pop(&mut self, bus: &mut Bus) {
        let mut addr = self.regs.get(Reg::SP);
        addr = addr.wrapping_add(1);
        bus.read_mem(addr);
        self.regs.set(Reg::SP, addr);
    }

    /// Writes `val` to the stack, adjusting SP.
    #[inline]
    pub fn stack_push(&mut self, val: u8, bus: &mut Bus) {
        let mut addr = self.regs.get(Reg::SP);
        bus.write_mem(addr, val);
        addr = addr.wrapping_sub(1);
        self.regs.set(Reg::SP, addr);
    }

    /// Executes a store register direct instruction.
    #[expect(clippy::cast_possible_truncation, reason = "truncation is correct")]
    #[inline]
    pub fn store_reg_direct(&mut self, reg: Reg, bus: &mut Bus) {
        bus.write_mem(self.op(), self.regs.get(reg) as u8);
    }

    /// Executes a store register indirect instruction.
    #[expect(clippy::cast_possible_truncation, reason = "truncation is correct")]
    #[inline]
    pub fn store_reg_indirect(&mut self, bus: &mut Bus) {
        if let Some((source, target)) = source_and_target_from(self.op_lo) {
            bus.write_mem(self.regs.get(target), self.regs.get(source) as u8);
        } else {
            self.trap(TRAP_ILLEGAL, bus);
        }
    }

    /// Executes a trap.
    ///
    /// The `trap_code` is used to select a vector from the trap table, and the CPU jumps
    /// to that address after pushing the return address and the trap code to the stack.
    #[expect(clippy::cast_possible_truncation, reason = "truncation is correct")]
    #[inline]
    pub fn trap(&mut self, mut trap_code: u8, bus: &mut Bus) {
        if trap_code == 0x20 {
            print!("{}", self.regs.get(Reg::A) as u8 as char);
        }
        if trap_code >= 0x40 {
            trap_code = TRAP_ILLEGAL;
        }
        let ret_addr = self.pc;
        let [hi, lo] = ret_addr.to_be_bytes();
        self.stack_push(lo, bus);
        self.state = WaitTrapLo(hi, trap_code);
    }
}

/// The state of the CPU's flag bits.
#[non_exhaustive]
#[derive(Debug, Default)]
pub struct Flags {
    /// Indicates carry (from addition) or 'no borrow' (from subtraction or comparison).
    pub carry: bool,
    /// Indicates a zero result from the last operation.
    pub zero: bool,
}

/// The state of the CPU on the next tick.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum State {
    /// Reads the opcode from the data bus.
    Decode,
    /// Executes the current instruction.
    Execute,
    /// Requests the next opcode from memory.
    #[default]
    FetchOpcode,
    /// Reads the high byte of the address to jump to.
    ReadAddrHi,
    /// Reads a byte from memory for a `dec` instruction.
    ReadDec(u16),
    /// Reads a byte from memory for an `inc` instruction.
    ReadInc(u16),
    /// Loads a register from the bus.
    ReadLoad(Reg),
    /// Reads a single operand from the bus.
    ReadOp,
    /// Reads the second of two operands from the bus.
    ReadOpHi,
    /// Reads the first of two operands from the bus.
    ReadOpLo,
    /// Reads the low byte of the reset vector from the bus.
    ReadResetLo,
    /// Reads the high byte of the return address for a `ret` instruction.
    ReadRetHi,
    /// Reads the low byte of the return address for a `ret` instruction.
    ReadRetLo,
    /// Reads the first of two stack values from the bus.
    ReadStackHi(Reg),
    /// Reads the low byte of the selected trap vector.
    ReadTrapVecLo(u16),
    /// Waits for the high byte of the address to jump to.
    WaitAddrHi,
    /// Waits for the low byte of the return address to be pushed for a `call`
    /// instruction.
    WaitCall(u8, u16),
    /// Waits for a byte from memory for a `dec` instruction.
    WaitDec(u16),
    /// Waits for a byte from memory for an `inc` instruction.
    WaitInc(u16),
    /// Waits for a byte from memory to load a register.
    WaitLoad(Reg),
    /// Waits for a single operand read from memory.
    WaitOp,
    /// Waits for the second of two operands from memory.
    WaitOpHi,
    /// Waits for the first of two operands from memory.
    WaitOpLo,
    /// Waits for an opcode fetch to complete.
    WaitOpcode,
    /// Waits for a stack push, before pushing another value.
    WaitPush(u8),
    /// Waits for the low byte of the reset vector.
    WaitResetLo,
    /// Waits for the high byte of the return address for a `ret` instruction.
    WaitRetHi,
    /// Waits for the low byte of the return address for a `ret` instruction.
    WaitRetLo,
    /// Waits for the first of 2 stack pops to a register.
    WaitStackHi(Reg),
    /// Waits for the trap code to be pushed following a trap.
    WaitTrapCode(u8),
    /// Waits for the high byte of the return address to be pushed following a trap.
    WaitTrapHi(u8),
    /// Waits for the low byte of the return address to be pushed following a trap.
    WaitTrapLo(u8, u8),
    /// Waits for the low byte of the trap vector following a trap.
    WaitTrapVecLo(u16),
}

impl Display for State {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{}",
            match *self {
                Decode => "DCOD",
                Execute => "EXEC",
                FetchOpcode => "FOPC",
                ReadAddrHi => "RDAH",
                ReadDec(_) => "RDEC",
                ReadInc(_) => "RINC",
                ReadLoad(_) => "RDLD",
                ReadOp => "RDOP",
                ReadOpHi => "ROPH",
                ReadOpLo => "ROPL",
                ReadResetLo => "RRSL",
                ReadRetHi => "RRTH",
                ReadRetLo => "RRTL",
                ReadStackHi(_) => "RSTH",
                ReadTrapVecLo(_) => "RTVL",
                WaitCall(_, _) => "WCAL",
                WaitDec(_) => "WDEC",
                WaitInc(_) => "WINC",
                WaitLoad(_) => "WTLD",
                WaitOp => "WTOP",
                WaitOpHi => "WOPH",
                WaitOpLo => "WOPL",
                WaitOpcode => "WOPC",
                WaitPush(_) => "WPSH",
                WaitAddrHi => "WTAH",
                WaitResetLo => "WRSL",
                WaitRetHi => "WRTH",
                WaitRetLo => "WRTL",
                WaitStackHi(_) => "WSTH",
                WaitTrapCode(_) => "WTTC",
                WaitTrapHi(_) => "WTTH",
                WaitTrapLo(_, _) => "WTTL",
                WaitTrapVecLo(_) => "WTVL",
            }
        )
    }
}

#[cfg(test)]
#[expect(clippy::unwrap_used, reason = "test")]
mod tests {
    use crate::{
        asm::{as_hex, assemble},
        instructions::InstructionKind::Halt,
        regs::Reg::*,
        system::System,
    };

    use super::*;

    #[test]
    fn cpu_states_are_correct_for_1_byte_instruction() {
        let mut sys = System::default();
        let source = "
        nop
        halt";
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        assert_eq!(sys.cpu.pc, 0x0100);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        assert_eq!(sys.cpu.pc, 0x0101);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        assert_eq!(sys.cpu.pc, 0x0101);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        assert_eq!(sys.cpu.pc, 0x0101);
        sys.tick();
        assert_eq!(sys.cpu.state, FetchOpcode);
        assert_eq!(sys.cpu.pc, 0x0101);
    }

    #[test]
    fn cpu_states_are_correct_for_2_byte_instruction() {
        let mut sys = System::default();
        let source = "
        ld a, 0xFF
        halt";
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.pc, 0x0101);
        assert_eq!(sys.cpu.state, WaitOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOp);
        assert_eq!(sys.cpu.pc, 0x0102);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOp);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.regs.get(A), 0x00FF);
        assert_eq!(sys.cpu.pc, 0x0102);
    }

    #[test]
    fn cpu_states_are_correct_for_3_byte_instruction() {
        let mut sys = System::default();
        let source = "
        ld ab, 0xBEEF
        halt";
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        assert_eq!(sys.cpu.pc, 0x0101);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpLo);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOpLo);
        assert_eq!(sys.cpu.pc, 0x0102);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpHi);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOpHi);
        assert_eq!(sys.cpu.pc, 0x0103);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.regs.get(AB), 0xBEEF);
        assert_eq!(sys.cpu.pc, 0x0103);
    }

    #[test]
    fn cpu_states_are_correct_for_mem_read_instruction() {
        let mut sys = System::default();
        let source = "
        ld b, (cd)
        halt";
        sys.mem.set(0x0110, 0xFF);
        sys.cpu.regs.set(Reg::CD, 0x0110);
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        assert_eq!(sys.cpu.pc, 0x0101);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOp);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOp);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.pc, 0x0102);
        assert_eq!(sys.cpu.state, WaitLoad(B));
        sys.tick();
        assert_eq!(sys.cpu.state, ReadLoad(B));
        sys.tick();
        assert_eq!(sys.cpu.regs.get(B), 0x00FF);
        assert_eq!(sys.cpu.pc, 0x0102);
        assert_eq!(sys.cpu.state, FetchOpcode);
    }

    #[test]
    fn cpu_states_are_correct_for_mem_write_instruction() {
        let mut sys = System::default();
        let source = "
        ld 0xBEEF, a
        halt";
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        sys.cpu.regs.set(A, 0xFF);
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpLo);
        assert_eq!(sys.cpu.pc, 0x0102);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOpLo);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpHi);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadOpHi);
        assert_eq!(sys.cpu.pc, 0x0103);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        assert_eq!(sys.cpu.pc, 0x0104);
    }

    #[test]
    fn cpu_states_are_correct_for_16_bit_pop_instruction() {
        let mut sys = System::default();
        let source = "
        pop cd
        halt";
        sys.mem.load(0xBFFE, &[0xBA, 0xBE]).unwrap();
        sys.cpu.regs.set(SP, 0xBFFD);
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitStackHi(CD));
        sys.tick();
        assert_eq!(sys.cpu.state, ReadStackHi(CD));
        sys.tick();
        assert_eq!(sys.cpu.state, WaitLoad(CD));
        sys.tick();
        assert_eq!(sys.cpu.state, ReadLoad(CD));
        sys.tick();
        assert_eq!(sys.cpu.state, FetchOpcode);
    }

    #[test]
    fn cpu_states_are_correct_for_16_bit_push_instruction() {
        let mut sys = System::default();
        let source = "
        push ab
        halt";
        sys.cpu.regs.set(SP, 0xBFFF);
        sys.cpu.regs.set(AB, 0xCAFE);
        sys.mem.load(0x0100, &assemble(source)).unwrap();
        sys.cpu.pc = 0x0100;
        assert_eq!(sys.cpu.state, FetchOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitOpcode);
        sys.tick();
        assert_eq!(sys.cpu.state, Decode);
        sys.tick();
        assert_eq!(sys.cpu.state, Execute);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitPush(0xCA));
        sys.tick();
        assert_eq!(sys.cpu.state, FetchOpcode);
    }

    #[test]
    fn cpu_traps_for_various_illegal_programs() {
        let mut sys = System::default();
        // dummy trap 0x00 handler, jumps to `halt` at 0x0002
        sys.mem.load(0x0000, &[0x02, 0x00, u8::from(Halt)]).unwrap();
        let cases: &[&[u8]] = &[
            &[0x01, 0xFF], // reserved opcode
            &[0x2D, 0xFF], // `ld R, (RR)` with invalid regs
            &[0x2E, 0xFF], // `ld (RR), R` with invalid regs
            &[0x2F, 0x08], // `ld R, R` with mixed 8/16 regs
            &[0x3D, 0xFF], // `inc (RR)` with invalid regs
            &[0x4D, 0xFF], // `dec (RR)` with invalid regs
            &[0xF9, 0x40], // `trap` with invalid code
        ];
        for prog in cases {
            // initialise stack
            sys.cpu.regs.set(SP, 0xBFFF);
            // junk to be overwritten by trap stack frame
            sys.mem.load(0xBFFD, &[0xFF, 0xFF, 0xFF]).unwrap();
            sys.trace_program(prog).unwrap();
            // verify trap stack frame
            assert_eq!(
                sys.mem.get(0xBFFD),
                TRAP_ILLEGAL,
                "{}: wrong trap code",
                as_hex(prog)
            );
            assert_eq!(
                sys.mem.get(0xBFFE),
                0x01,
                "{}: wrong return address high byte",
                as_hex(prog)
            );
            assert_eq!(
                sys.mem.get(0xBFFF),
                u8::try_from(prog.len()).unwrap(),
                "{}: wrong return address low byte",
                as_hex(prog)
            );
        }
    }

    #[expect(clippy::bool_assert_comparison, reason = "clarity")]
    #[test]
    fn reset_resets_cpu() {
        let mut sys = System::default();
        sys.cpu.regs.set(AB, 0xBEEF);
        sys.cpu.regs.set(SP, 0xFFFD);
        sys.cpu.pc = 0x0000;
        sys.cpu.flags.carry = true;
        sys.cpu.flags.zero = true;
        sys.cpu.reset(&mut sys.bus);
        assert_eq!(sys.cpu.state, WaitResetLo);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadResetLo);
        sys.tick();
        assert_eq!(sys.cpu.state, WaitAddrHi);
        sys.tick();
        assert_eq!(sys.cpu.state, ReadAddrHi);
        sys.tick();
        assert_eq!(sys.cpu.state, FetchOpcode);
        assert_eq!(sys.cpu.regs.get(AB), 0x0000, "AB not reset");
        assert_eq!(sys.cpu.regs.get(SP), 0x0000, "SP not reset");
        assert_eq!(sys.cpu.pc, 0xC000, "PC not initialized from reset vector");
        assert_eq!(sys.cpu.flags.carry, false, "carry not reset");
        assert_eq!(sys.cpu.flags.zero, false, "zero not reset");
    }
}