tetanes-core 0.14.0

A NES Emulator written in Rust
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
//! 6502 Central Processing Unit (CPU) implementation.
//!
//! <https://wiki.nesdev.org/w/index.php/CPU>

use crate::{
    bus::Bus,
    common::{Clock, NesRegion, Regional, Reset, ResetKind},
    mem::{Read, Write},
};
use crate::{
    cpu::instr::{
        AddrMode,
        Instr::{JMP, JSR},
        InstrRef,
    },
    mapper::Map,
};
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
use std::fmt::{self};
use tracing::trace;

pub mod instr;

bitflags! {
    #[derive(Default, Serialize, Deserialize, Debug, Copy, Clone)]
    #[must_use]
    pub struct IrqFlags: u8 {
        const NMI = 1 << 0;
        const PREV_NMI = 1 << 1;
        const PREV_NMI_PENDING = 1 << 2;
        const RUN_IRQ = 1 << 3;
        const PREV_RUN_IRQ = 1 << 4;
        const DMA_DMC = 1 << 5;
        const DMA_HALT = 1 << 6;
        const DMA_DUMMY_READ = 1 << 7;
    }
}

// Status Registers
// https://wiki.nesdev.org/w/index.php/Status_flags
// 7654 3210
// NVUB DIZC
// |||| ||||
// |||| |||+- Carry
// |||| ||+-- Zero
// |||| |+--- Interrupt Disable
// |||| +---- Decimal Mode - Not used in the NES but still has to function
// |||+------ Break - 1 when pushed to stack from PHP/BRK, 0 from IRQ/NMI
// ||+------- Unused - always set to 1 when pushed to stack
// |+-------- Overflow
// +--------- Negative
bitflags! {
    /// CPU Status Registers.
    #[derive(Default, Serialize, Deserialize, Debug, Copy, Clone)]
    #[must_use]
    pub struct Status: u8 {
        const C = 1;      // Carry
        const Z = 1 << 1; // Zero
        const I = 1 << 2; // Disable Interrupt
        const D = 1 << 3; // Decimal Mode
        const B = 1 << 4; // Break
        const U = 1 << 5; // Unused
        const V = 1 << 6; // Overflow
        const N = 1 << 7; // Negative
    }
}

/// The Central Processing Unit status and registers
#[derive(Default, Clone, Serialize, Deserialize)]
#[must_use]
#[repr(C)]
pub struct Cpu {
    pub cycle: u32, // total number of cycles ran
    pub master_clock: u32,
    // start/end cycle counts for reads/writes
    pub start_cycles: u8,
    pub end_cycles: u8,
    pub pc: u16,             // program counter
    pub operand: u16,        // opcode operand
    pub addr_mode: AddrMode, // Addressing mode
    pub sp: u8,              // stack pointer - stack is at $0100-$01FF
    pub acc: u8,             // accumulator
    pub x: u8,               // x register
    pub y: u8,               // y register
    pub status: Status,      // Status Registers
    pub irq_flags: IrqFlags,
    pub dma_oam_addr: Option<u16>,
    pub bus: Bus,
    #[serde(skip)]
    pub corrupted: bool, // Encountering an invalid opcode corrupts CPU processing
    #[serde(skip)]
    pub disasm: String,
}

impl Cpu {
    const NTSC_MASTER_CLOCK_RATE: f32 = 21_477_272.0;
    const NTSC_CPU_CLOCK_RATE: f32 = Self::NTSC_MASTER_CLOCK_RATE / 12.0;
    const PAL_MASTER_CLOCK_RATE: f32 = 26_601_712.0;
    const PAL_CPU_CLOCK_RATE: f32 = Self::PAL_MASTER_CLOCK_RATE / 16.0;
    const DENDY_CPU_CLOCK_RATE: f32 = Self::PAL_MASTER_CLOCK_RATE / 15.0;

    // Represents CPU/PPU alignment and would range from 1..=ppu.clock_divider-1
    // if random PPU alignment was emulated
    // See: https://www.nesdev.org/wiki/PPU_frame_timing#CPU-PPU_Clock_Alignment
    const PPU_OFFSET: u32 = 1;

    const NMI_VECTOR: u16 = 0xFFFA; // NMI Vector address
    const IRQ_VECTOR: u16 = 0xFFFE; // IRQ Vector address
    const RESET_VECTOR: u16 = 0xFFFC; // Vector address at reset
    const POWER_ON_STATUS: Status = Status::U.union(Status::I);
    const POWER_ON_SP: u8 = 0xFD;
    const SP_BASE: u16 = 0x0100; // Stack-pointer starting address

    /// Create a new CPU with the given bus.
    pub fn new(bus: Bus) -> Self {
        let mut cpu = Self {
            cycle: 0,
            master_clock: 0,
            start_cycles: 6,
            end_cycles: 6,
            pc: 0x0000,
            operand: 0,
            addr_mode: AddrMode::default(),
            sp: 0x00,
            acc: 0x00,
            x: 0x00,
            y: 0x00,
            status: Self::POWER_ON_STATUS,
            irq_flags: IrqFlags::default(),
            dma_oam_addr: None,
            bus,
            corrupted: false,
            disasm: String::new(),
        };
        cpu.set_region(cpu.bus.region);
        cpu
    }

    /// Load a CPU state.
    pub fn load(&mut self, mut cpu: Self) {
        // Doesn't make sense to load a debugger from a previous state
        cpu.bus.ppu.debugger = std::mem::take(&mut self.bus.ppu.debugger);
        *self = cpu;
    }

    /// Returns the CPU clock rate based on [`NesRegion`].
    #[inline]
    #[must_use]
    pub const fn region_clock_rate(region: NesRegion) -> f32 {
        match region {
            NesRegion::Auto | NesRegion::Ntsc => Self::NTSC_CPU_CLOCK_RATE,
            NesRegion::Pal => Self::PAL_CPU_CLOCK_RATE,
            NesRegion::Dendy => Self::DENDY_CPU_CLOCK_RATE,
        }
    }

    /// Clock rate based on currently configured NES region.
    #[inline]
    #[must_use]
    pub const fn clock_rate(&self) -> f32 {
        Self::region_clock_rate(self.bus.region)
    }

    /// Peek at the next instruction.
    #[inline]
    pub fn next_instr(&self) -> InstrRef {
        let opcode = self.peek(self.pc);
        Cpu::INSTR_REF[usize::from(opcode)]
    }

    /// Start OAM DMA.
    #[inline]
    pub fn start_oam_dma(&mut self, addr: u16) {
        self.irq_flags.insert(IrqFlags::DMA_HALT);
        self.dma_oam_addr = Some(addr);
    }

    /// Process an interrupted request.
    ///
    /// <https://wiki.nesdev.org/w/index.php/IRQ>
    ///  #  address R/W description
    /// --- ------- --- -----------------------------------------------
    ///  1    PC     R  fetch PCH
    ///  2    PC     R  fetch PCL
    ///  3  $0100,S  W  push PCH to stack, decrement S
    ///  4  $0100,S  W  push PCL to stack, decrement S
    ///  5  $0100,S  W  push P to stack, decrement S
    ///  6    PC     R  fetch low byte of interrupt vector
    ///  7    PC     R  fetch high byte of interrupt vector
    #[cold]
    #[inline(never)]
    pub fn irq(&mut self) {
        if self.irq_flags(IrqFlags::DMA_HALT) && self.region() == NesRegion::Pal {
            // Check for DMA on PAL
            self.handle_dma(self.pc);
        }

        self.read(self.pc); // Dummy read
        self.read(self.pc); // Dummy read
        self.push_word(self.pc);

        // Pushing status to the stack has to happen after checking NMI since it can hijack the BRK
        // IRQ when it occurs between cycles 4 and 5.
        // https://www.nesdev.org/wiki/CPU_interrupts#Interrupt_hijacking
        //
        // Set U and !B during push
        let status = ((self.status | Status::U) & !Status::B).bits();
        let nmi = self.irq_flags(IrqFlags::NMI);
        self.push_byte(status);
        self.status.set(Status::I, true);

        if nmi {
            self.clear_irq_flags(IrqFlags::NMI);
            self.pc = self.read_word(Self::NMI_VECTOR);
            self.clock_sync();
            trace!(
                "NMI - PPU:{:3},{:3} CYC:{}",
                self.bus.ppu.cycle, self.bus.ppu.scanline, self.cycle
            );
        } else {
            self.pc = self.read_word(Self::IRQ_VECTOR);
            trace!(
                "IRQ - PPU:{:3},{:3} CYC:{}",
                self.bus.ppu.cycle, self.bus.ppu.scanline, self.cycle
            );
        }
    }

    /// Handle CPU interrupt requests, if any are pending.
    #[inline(always)]
    fn handle_interrupts(&mut self) {
        let irq_pending_mapper = self.bus.ppu.mapper.irq_pending();
        let dma_pending_mapper = self.bus.ppu.mapper.dma_pending();
        let nmi_pending = self.bus.ppu.nmi_pending;
        let irq_pending_apu = self.bus.apu.irq_pending();
        let dma_pending_apu = self.bus.apu.dma_pending();

        if dma_pending_apu {
            self.bus.apu.clear_dma_pending();
            self.irq_flags
                .insert(IrqFlags::DMA_DMC | IrqFlags::DMA_HALT | IrqFlags::DMA_DUMMY_READ);
        } else if dma_pending_mapper {
            self.bus.ppu.mapper.clear_dma_pending();
            self.irq_flags
                .insert(IrqFlags::DMA_DMC | IrqFlags::DMA_HALT | IrqFlags::DMA_DUMMY_READ);
        }

        let flags = &mut self.irq_flags;

        // https://www.nesdev.org/wiki/CPU_interrupts
        //
        // The internal signal goes high during φ1 of the cycle that follows the one where
        // the edge is detected, and stays high until the NMI has been handled. NMI is handled only
        // when `prev_nmi` is true.
        flags.set(IrqFlags::PREV_NMI, flags.contains(IrqFlags::NMI));

        // This edge detector polls the status of the NMI line during φ2 of each CPU cycle (i.e.,
        // during the second half of each cycle, hence here in `end_cycle`) and raises an internal
        // signal if the input goes from being high during one cycle to being low during the
        // next.
        let prev_nmi_pending = flags.contains(IrqFlags::PREV_NMI_PENDING);
        if !prev_nmi_pending & nmi_pending {
            flags.insert(IrqFlags::NMI);
        }
        flags.set(IrqFlags::PREV_NMI_PENDING, nmi_pending);

        // The IRQ status at the end of the second-to-last cycle is what matters,
        // so keep the second-to-last status.
        flags.set(IrqFlags::PREV_RUN_IRQ, flags.contains(IrqFlags::RUN_IRQ));
        let run_irq = (irq_pending_mapper | irq_pending_apu) & !self.status.intersects(Status::I);
        flags.set(IrqFlags::RUN_IRQ, run_irq);

        #[cfg(feature = "trace")]
        if !flags.contains(IrqFlags::PREV_NMI_PENDING) && flags.contains(IrqFlags::RUN_IRQ) {
            trace!(
                "IRQ: {} - CYC:{}",
                irq_pending_mapper | irq_pending_apu,
                self.cycle
            );
        }
    }

    /// Start a CPU cycle.
    #[inline(always)]
    fn start_cycle(&mut self, increment: u8) {
        self.master_clock = self.master_clock.wrapping_add(u32::from(increment));
        self.cycle = self.cycle.wrapping_add(1);
        self.bus.ppu.clock_to(self.master_clock - Self::PPU_OFFSET);
        self.bus.cpu_clock();
    }

    /// End a CPU cycle.
    #[inline(always)]
    fn end_cycle(&mut self, increment: u8) {
        self.master_clock = self.master_clock.wrapping_add(u32::from(increment));
        self.bus.ppu.clock_to(self.master_clock - Self::PPU_OFFSET);

        self.handle_interrupts();
    }

    /// Start a direct-memory access (DMA) cycle.
    #[inline(always)]
    fn start_dma_cycle(&mut self) {
        // OAM DMA cycles count as halt/dummy reads for DMC DMA when both run at the same time
        if self.irq_flags(IrqFlags::DMA_HALT) {
            self.clear_irq_flags(IrqFlags::DMA_HALT);
        } else {
            self.clear_irq_flags(IrqFlags::DMA_DUMMY_READ);
        }
        self.start_cycle(self.start_cycles - 1);
    }

    /// Handle a direct-memory access (DMA) request.
    #[cold]
    #[inline(never)]
    fn handle_dma(&mut self, addr: u16) {
        trace!("Starting DMA - CYC:{}", self.cycle);

        self.start_cycle(self.start_cycles - 1);
        self.bus.read(addr);
        self.end_cycle(self.start_cycles + 1);
        self.clear_irq_flags(IrqFlags::DMA_HALT);

        let skip_dummy_reads = addr == 0x4016 || addr == 0x4017;

        let mut oam_offset = 0;
        let mut oam_dma_count = 0;
        let mut read_val = 0;

        loop {
            let dma_dmc = self.irq_flags(IrqFlags::DMA_DMC);
            let dma_oam_addr = self.dma_oam_addr;
            if !dma_dmc & dma_oam_addr.is_none() {
                break;
            }

            if self.cycle & 0x01 == 0x00 {
                if dma_dmc
                    & !self.irq_flags(IrqFlags::DMA_HALT)
                    & !self.irq_flags(IrqFlags::DMA_DUMMY_READ)
                {
                    // DMC DMA ready to read a byte (halt and dummy read done before)
                    self.start_dma_cycle();
                    let dma_addr = self.bus.apu.dmc.dma_addr();
                    read_val = self.bus.read(dma_addr);
                    trace!(
                        "Loaded DMC DMA byte. ${dma_addr:04X}: {read_val} - CYC:{}",
                        self.cycle
                    );
                    self.end_cycle(self.start_cycles + 1);
                    self.bus.apu.dmc.load_buffer(read_val);
                    self.clear_irq_flags(IrqFlags::DMA_DMC);
                } else if let Some(oam_addr) = dma_oam_addr {
                    // DMC DMA not running or ready, run OAM DMA
                    self.start_dma_cycle();
                    read_val = self.bus.read(oam_addr + oam_offset);
                    self.end_cycle(self.start_cycles + 1);
                    oam_offset += 1;
                    oam_dma_count += 1;
                } else {
                    // DMC DMA running, but not ready yet (needs to halt, or dummy read) and OAM
                    // DMA isn't running
                    debug_assert!(
                        self.irq_flags(IrqFlags::DMA_HALT)
                            | self.irq_flags(IrqFlags::DMA_DUMMY_READ)
                    );
                    self.start_dma_cycle();
                    if !skip_dummy_reads {
                        self.bus.read(addr); // throw away
                    }
                    self.end_cycle(self.start_cycles + 1);
                }
            } else if dma_oam_addr.is_some() & (oam_dma_count & 0x01 == 0x01) {
                // OAM DMA write cycle, done on odd cycles after a read on even cycles
                self.start_dma_cycle();
                self.bus.write(0x2004, read_val);
                self.end_cycle(self.start_cycles + 1);
                oam_dma_count += 1;
                if oam_dma_count == 0x200 {
                    self.dma_oam_addr.take();
                }
            } else {
                // Align to read cycle before starting OAM DMA (or align to perform DMC read)
                self.start_dma_cycle();
                if !skip_dummy_reads {
                    self.bus.read(addr); // throw away
                }
                self.end_cycle(self.start_cycles + 1);
            }
        }
    }

    // Interrupt flag functions

    /// Clear [`IrqFlags`] flags for the given bits.
    #[inline(always)]
    fn clear_irq_flags(&mut self, flags: IrqFlags) {
        self.irq_flags &= !flags;
    }

    /// Returns `true` if the [`IrqFlags`] register is set.
    #[inline(always)]
    fn irq_flags(&self, flags: IrqFlags) -> bool {
        (self.irq_flags & flags).bits() == flags.bits()
    }

    // Status Register functions

    /// Set [`Status`] flags for the given bits.
    #[inline(always)]
    fn set_status(&mut self, status: Status) {
        self.status = status & !Status::U & !Status::B;
    }

    /// Returns the [`Status`] register as a byte.
    #[inline(always)]
    const fn status_bit(&self, reg: Status) -> u8 {
        self.status.intersection(reg).bits()
    }

    /// Set accumulator and update [`Status`] flags based on value.
    #[inline(always)]
    fn set_acc(&mut self, val: u8) {
        self.set_zn_status(val);
        self.acc = val;
    }

    /// Set x and update [`Status`] flags based on value.
    #[inline(always)]
    fn set_x(&mut self, val: u8) {
        self.set_zn_status(val);
        self.x = val;
    }

    /// Set y and update [`Status`] flags based on value.
    #[inline(always)]
    fn set_y(&mut self, val: u8) {
        self.set_zn_status(val);
        self.y = val;
    }

    /// Set stack pointer.
    #[inline(always)]
    const fn set_sp(&mut self, val: u8) {
        self.sp = val;
    }

    /// Set both [`Status::Z`] and [`Status::N`] flags based on value.
    #[inline(always)]
    fn set_zn_status(&mut self, val: u8) {
        self.status.set(Status::Z, val == 0x00);
        self.status.set(Status::N, val & 0x80 > 0);
    }

    // Stack Functions

    /// Push a byte to the stack.
    #[inline(always)]
    fn push_byte(&mut self, val: u8) {
        self.write(Self::SP_BASE | u16::from(self.sp), val);
        self.sp = self.sp.wrapping_sub(1);
    }

    /// Pull a byte from the stack.
    #[inline(always)]
    #[must_use]
    fn pop_byte(&mut self) -> u8 {
        self.sp = self.sp.wrapping_add(1);
        self.read(Self::SP_BASE | u16::from(self.sp))
    }

    /// Peek byte at the top of the stack.
    #[inline]
    #[must_use]
    pub fn peek_stack(&self) -> u8 {
        self.peek(Self::SP_BASE | u16::from(self.sp.wrapping_add(1)))
    }

    /// Peek at the top of the stack.
    #[inline]
    #[must_use]
    pub fn peek_stack_u16(&self) -> u16 {
        let lo = self.peek(Self::SP_BASE | u16::from(self.sp));
        let hi = self.peek(Self::SP_BASE | u16::from(self.sp.wrapping_add(1)));
        u16::from_le_bytes([lo, hi])
    }

    /// Push a word (two bytes) to the stack
    #[inline(always)]
    fn push_word(&mut self, val: u16) {
        let [lo, hi] = val.to_le_bytes();
        self.push_byte(hi);
        self.push_byte(lo);
    }

    /// Pull a word (two bytes) from the stack
    #[inline(always)]
    fn pop_word(&mut self) -> u16 {
        let lo = self.pop_byte();
        let hi = self.pop_byte();
        u16::from_le_bytes([lo, hi])
    }

    // Memory accesses

    /// Fetch a byte and increments PC by 1.
    #[inline(always)]
    #[must_use]
    fn fetch_byte(&mut self) -> u8 {
        let val = self.read(self.pc);
        self.pc = self.pc.wrapping_add(1);
        val
    }

    /// Fetch opcode operand based on addressing mode.
    #[inline(always)]
    #[must_use]
    fn fetch_operand(&mut self) -> u16 {
        match self.addr_mode {
            AddrMode::ACC | AddrMode::IMP => self.acc_imp(),
            AddrMode::IMM | AddrMode::REL | AddrMode::ZP0 => self.imm_rel_zp(),
            AddrMode::ZPX => self.zpx(),
            AddrMode::ZPY => self.zpy(),
            AddrMode::IND => self.ind(),
            AddrMode::IDX => self.idx(),
            AddrMode::IDY => self.idy(false),
            AddrMode::IDYW => self.idy(true),
            AddrMode::ABS => self.abs(),
            AddrMode::ABX => self.abx(false),
            AddrMode::ABXW => self.abx(true),
            AddrMode::ABY => self.aby(false),
            AddrMode::ABYW => self.aby(true),
            AddrMode::OTH => 0,
        }
    }

    /// Fetch a 16-bit word and increments PC by 2.
    #[inline(always)]
    #[must_use]
    fn fetch_word(&mut self) -> u16 {
        let lo = self.fetch_byte();
        let hi = self.fetch_byte();
        u16::from_le_bytes([lo, hi])
    }

    /// Read operand value.
    #[inline(always)]
    #[must_use]
    fn read_operand(&mut self) -> u8 {
        if matches!(
            self.addr_mode,
            AddrMode::ACC | AddrMode::IMP | AddrMode::IMM | AddrMode::REL
        ) {
            self.operand as u8
        } else {
            self.read(self.operand)
        }
    }

    /// Read a 16-bit word.
    #[inline(always)]
    #[must_use]
    pub fn read_word(&mut self, addr: u16) -> u16 {
        let lo = self.read(addr);
        let hi = self.read(addr.wrapping_add(1));
        u16::from_le_bytes([lo, hi])
    }

    /// Peek a 16-bit word without side effects.
    #[inline]
    #[must_use]
    pub fn peek_word(&self, addr: u16) -> u16 {
        let lo = self.peek(addr);
        let hi = self.peek(addr.wrapping_add(1));
        u16::from_le_bytes([lo, hi])
    }

    /// Disassemble the instruction at the given program counter.
    pub fn disassemble(&mut self, pc: &mut u16) -> &str {
        use fmt::Write;

        self.disasm.clear();

        let addr = { *pc };
        let opcode = {
            let byte = self.peek(*pc);
            *pc = pc.wrapping_add(1);
            byte
        };
        let _ = write!(self.disasm, "${addr:04X} ${opcode:02X} ");

        let mut peek_byte = || {
            let byte = self.peek(*pc);
            *pc = pc.wrapping_add(1);
            byte
        };
        let mut peek_word = || {
            let lo = peek_byte();
            let hi = peek_byte();
            (lo, hi, u16::from_le_bytes([lo, hi]))
        };

        let instr_ref = Cpu::INSTR_REF[usize::from(opcode)];
        match instr_ref.addr_mode {
            AddrMode::ACC | AddrMode::IMP => {
                let _ = write!(self.disasm, "        {instr_ref}");
            }
            AddrMode::IMM => {
                let byte = peek_byte();
                let _ = write!(self.disasm, "${byte:02X}     {instr_ref} #${byte:02X}");
            }
            AddrMode::REL => {
                let byte = peek_byte();
                let addr = (*pc as i16).wrapping_add(i16::from(byte as i8)) as u16;
                let _ = write!(self.disasm, "${byte:02X}     {instr_ref} ${addr:04X}");
            }
            AddrMode::ZP0 => {
                let byte = peek_byte();
                let val = self.peek(byte.into());
                let _ = write!(
                    self.disasm,
                    "${byte:02X}     {instr_ref} ${byte:02X} = #${val:02X}"
                );
            }
            AddrMode::ZPX => {
                let byte = peek_byte();
                let addr = byte.wrapping_add(self.x);
                let val = self.peek(addr.into());
                let _ = write!(
                    self.disasm,
                    "${byte:02X}     {instr_ref} ${byte:02X},X @ ${addr:02X} = #${val:02X}"
                );
            }
            AddrMode::ZPY => {
                let byte = peek_byte();
                let addr = byte.wrapping_add(self.y);
                let val = self.peek(addr.into());
                let _ = write!(
                    self.disasm,
                    "${byte:02X}     {instr_ref} ${byte:02X},Y @ ${addr:02X} = #${val:02X}"
                );
            }
            AddrMode::IND => {
                let (byte1, byte2, base_addr) = peek_word();
                let val = if (base_addr & 0xFF) == 0xFF {
                    let lo = self.peek(base_addr);
                    let hi = self.peek(base_addr - 0xFF);
                    u16::from_le_bytes([lo, hi])
                } else {
                    self.peek_word(base_addr)
                };
                let _ = write!(
                    self.disasm,
                    "${byte1:02X} ${byte2:02X} {instr_ref} (${base_addr:04X}) = ${val:04X}"
                );
            }
            AddrMode::IDX => {
                let byte = peek_byte();
                let zero_addr = byte.wrapping_add(self.x);
                let lo = self.peek(u16::from(zero_addr));
                let hi = self.peek(u16::from(zero_addr.wrapping_add(1)));
                let addr = u16::from_le_bytes([lo, hi]);
                let val = self.peek(addr);
                let _ = write!(
                    self.disasm,
                    "${byte:02X}     {instr_ref} (${byte:02X},X) @ ${addr:04X} = #${val:02X}"
                );
            }
            AddrMode::IDY | AddrMode::IDYW => {
                let byte = peek_byte();
                let base_addr = {
                    let lo = self.peek(u16::from(byte));
                    let hi = self.peek(u16::from(byte.wrapping_add(1)));
                    u16::from_le_bytes([lo, hi])
                };
                let addr = base_addr.wrapping_add(u16::from(self.y));
                let val = self.peek(addr);
                let _ = write!(
                    self.disasm,
                    "${byte:02X}     {instr_ref} (${byte:02X}),Y @ ${addr:04X} = #${val:02X}"
                );
            }
            AddrMode::ABS => {
                let (byte1, byte2, addr) = peek_word();
                if instr_ref.instr == JMP {
                    let _ = write!(
                        self.disasm,
                        "${byte1:02X} ${byte2:02X} {instr_ref} ${addr:04X}"
                    );
                } else {
                    let val = self.peek(addr);
                    let _ = write!(
                        self.disasm,
                        "${byte1:02X} ${byte2:02X} {instr_ref} ${addr:04X} = #${val:02X}"
                    );
                }
            }
            AddrMode::ABX | AddrMode::ABXW => {
                let (byte1, byte2, base_addr) = peek_word();
                let addr = base_addr.wrapping_add(self.x.into());
                let val = self.peek(addr);
                let _ = write!(
                    self.disasm,
                    "${byte1:02X} ${byte2:02X} {instr_ref} ${base_addr:04X},X @ ${addr:04X} = #${val:02X}"
                );
            }
            AddrMode::ABY | AddrMode::ABYW => {
                let (byte1, byte2, base_addr) = peek_word();
                let addr = base_addr.wrapping_add(self.y.into());
                let val = self.peek(addr);
                let _ = write!(
                    self.disasm,
                    "${byte1:02X} ${byte2:02X} {instr_ref} ${base_addr:04X},Y @ ${addr:04X} = #${val:02X}"
                );
            }
            AddrMode::OTH => {
                let (byte1, byte2, addr) = peek_word();
                if instr_ref.instr == JSR {
                    let _ = write!(
                        self.disasm,
                        "${byte1:02X} ${byte2:02X} {instr_ref} ${addr:04X}"
                    );
                } else {
                    let val = self.peek(addr);
                    let _ = write!(
                        self.disasm,
                        "${byte1:02X} ${byte2:02X} {instr_ref} ${addr:04X} = #${val:02X}"
                    );
                }
            }
        };
        &self.disasm
    }

    /// Logs the disassembled instruction being executed.
    #[cold]
    #[inline(never)]
    pub fn trace_instr(&mut self) {
        if !tracing::enabled!(tracing::Level::TRACE) {
            return;
        }
        let mut pc = self.pc;
        let status = self.status;
        let acc = self.acc;
        let x = self.x;
        let y = self.y;
        let sp = self.sp;
        let ppu_cycle = self.bus.ppu.cycle;
        let ppu_scanline = self.bus.ppu.scanline;
        let cycle = self.cycle;
        let n = if status.contains(Status::N) { 'N' } else { 'n' };
        let v = if status.contains(Status::V) { 'V' } else { 'v' };
        let i = if status.contains(Status::I) { 'I' } else { 'i' };
        let z = if status.contains(Status::Z) { 'Z' } else { 'z' };
        let c = if status.contains(Status::C) { 'C' } else { 'c' };
        println!(
            "{:<50} A:{acc:02X} X:{x:02X} Y:{y:02X} P:{n}{v}--d{i}{z}{c} SP:{sp:02X} PPU:{ppu_cycle:3},{ppu_scanline:3} CYC:{cycle}",
            self.disassemble(&mut pc),
        );
    }

    // Utilities

    /// Returns whether two addresses are on different memory pages.
    #[inline(always)]
    #[must_use]
    const fn pages_differ(addr1: u16, addr2: u16) -> bool {
        (addr1 & 0xFF00) != (addr2 & 0xFF00)
    }

    /// Returns whether a memory page is crossed using relative address.
    #[inline(always)]
    #[must_use]
    const fn page_crossed(addr: u16, offset: i16) -> bool {
        ((addr as i16 + offset) as u16 & 0xFF00) != (addr & 0xFF00)
    }

    /// Runs all componnets up to master clock, synchronizing them.
    #[inline(always)]
    pub fn clock_sync(&mut self) {
        self.bus.ppu.clock_to(self.master_clock);
        self.master_clock = self.master_clock.saturating_sub(self.bus.ppu.master_clock);
        self.bus.ppu.master_clock = 0;
        self.bus.apu.clock_sync();
    }
}

impl Clock for Cpu {
    /// Runs the CPU one instruction.
    #[inline(always)]
    fn clock(&mut self) {
        #[cfg(feature = "trace")]
        self.trace_instr();

        let opcode = self.fetch_byte(); // Cycle 1
        let op = Cpu::OPS[usize::from(opcode)];
        self.addr_mode = op.addr_mode();
        self.operand = self.fetch_operand();
        op.run(self);

        if self
            .irq_flags
            .intersects(IrqFlags::PREV_RUN_IRQ | IrqFlags::PREV_NMI)
        {
            self.irq();
        }
    }
}

impl Read for Cpu {
    #[inline(always)]
    fn read(&mut self, addr: u16) -> u8 {
        if self.irq_flags(IrqFlags::DMA_HALT) {
            self.handle_dma(addr);
        }

        self.start_cycle(self.start_cycles - 1);
        let val = self.bus.read(addr);
        self.end_cycle(self.end_cycles + 1);
        val
    }

    fn peek(&self, addr: u16) -> u8 {
        self.bus.peek(addr)
    }
}

impl Write for Cpu {
    #[inline(always)]
    fn write(&mut self, addr: u16, val: u8) {
        self.start_cycle(self.start_cycles + 1);
        if addr == 0x4014 {
            self.start_oam_dma(u16::from(val) << 8);
        } else {
            self.bus.write(addr, val);
        }
        self.end_cycle(self.end_cycles - 1);
    }
}

impl Regional for Cpu {
    #[inline(always)]
    fn region(&self) -> NesRegion {
        self.bus.region
    }

    fn set_region(&mut self, region: NesRegion) {
        let (start_cycles, end_cycles) = match region {
            NesRegion::Auto | NesRegion::Ntsc => (6, 6), // NTSC_MASTER_CLOCK_DIVIDER / 2
            NesRegion::Pal => (8, 8),                    // PAL_MASTER_CLOCK_DIVIDER / 2
            NesRegion::Dendy => (7, 8),                  // DENDY_MASTER_CLOCK_DIVIDER / 2
        };
        self.start_cycles = start_cycles;
        self.end_cycles = end_cycles;
        self.bus.set_region(region);
        self.clock_sync();
    }
}

impl Reset for Cpu {
    /// Resets the CPU
    ///
    /// Updates the PC, SP, and Status values to defined constants.
    ///
    /// These operations take the CPU 7 cycles.
    fn reset(&mut self, kind: ResetKind) {
        trace!("{:?} RESET", kind);

        match kind {
            ResetKind::Soft => {
                self.status.set(Status::I, true);
                // Reset pushes to the stack similar to IRQ, but since the read bit is set, nothing is
                // written except the SP being decremented
                self.sp = self.sp.wrapping_sub(0x03);
            }
            ResetKind::Hard => {
                self.acc = 0x00;
                self.x = 0x00;
                self.y = 0x00;
                self.status = Self::POWER_ON_STATUS;
                self.sp = Self::POWER_ON_SP;
            }
        }

        self.bus.reset(kind);
        self.cycle = 0;
        self.master_clock = 0;
        self.irq_flags = IrqFlags::default();
        self.corrupted = false;

        // Read directly from bus so as to not clock other components during reset
        let lo = self.bus.read(Self::RESET_VECTOR);
        let hi = self.bus.read(Self::RESET_VECTOR + 1);
        self.pc = u16::from_le_bytes([lo, hi]);

        // The CPU takes 7 cycles to reset/power on
        // See:
        // * <https://www.nesdev.org/wiki/CPU_interrupts>
        // * <http://archive.6502.org/datasheets/synertek_programming_manual.pdf>
        for _ in 0..7 {
            self.start_cycle(self.start_cycles - 1);
            self.end_cycle(self.start_cycles + 1);
        }
    }
}

impl fmt::Debug for Cpu {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::result::Result<(), fmt::Error> {
        f.debug_struct("Cpu")
            .field("cycle", &self.cycle)
            .field("pc", &format_args!("${:04X}", self.pc))
            .field("sp", &format_args!("${:02X}", self.sp))
            .field("acc", &format_args!("${:02X}", self.acc))
            .field("x", &format_args!("${:02X}", self.x))
            .field("y", &format_args!("${:02X}", self.y))
            .field("status", &self.status)
            .field("bus", &self.bus)
            .field("interrupt_flags", &self.irq_flags)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use crate::{cart::Cart, cpu::instr::Instr::*, mapper::Nrom, mem::Memory};

    #[test]
    fn cycle_timing() {
        use super::*;
        let mut cpu = Cpu::new(Bus::default());
        let mut cart = Cart::empty();
        cart.mapper = Nrom::load(
            &cart,
            Memory::new(cart.chr_rom_size),
            Memory::new(cart.prg_rom_size),
        )
        .unwrap();
        cpu.bus.load_cart(cart);
        cpu.reset(ResetKind::Hard);
        cpu.clock();

        assert_eq!(cpu.cycle, 14, "cpu after power + one clock");

        for instr_ref in Cpu::INSTR_REF.iter() {
            let extra_cycle = match instr_ref.instr {
                BCC | BNE | BPL | BVC => 1,
                _ => 0,
            };
            // Ignore invalid opcodes
            if instr_ref.instr == HLT {
                continue;
            }
            cpu.reset(ResetKind::Hard);
            cpu.bus.write(0x0000, instr_ref.opcode);
            cpu.clock();
            let cpu_cyc = u32::from(7 + instr_ref.cycles + extra_cycle);
            assert_eq!(
                cpu.cycle, cpu_cyc,
                "cpu ${:02X} {:?} #{:?}",
                instr_ref.opcode, instr_ref.instr, instr_ref.addr_mode
            );
        }
    }
}