neser 1.2.0

NESER - Nintendo Emulation Systems Engine (Rust). Desktop and WebAssembly frontends.
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
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Breakpoint engine for the NES and GB debuggers.
//!
//! Supports multiple condition types: PC match, CPU cycle count, CPU frame count,
//! CPU write-address, and GB-specific interrupt breakpoints.

use std::fmt;

/// Game Boy interrupt types for interrupt breakpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GbInterruptKind {
    /// VBlank interrupt (bit 0 of IF/IE)
    VBlank,
    /// STAT (LCD) interrupt (bit 1 of IF/IE)
    Stat,
    /// Timer interrupt (bit 2 of IF/IE)
    Timer,
    /// Serial interrupt (bit 3 of IF/IE)
    Serial,
    /// Joypad interrupt (bit 4 of IF/IE)
    Joypad,
}

impl fmt::Display for GbInterruptKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GbInterruptKind::VBlank => write!(f, "VBlank"),
            GbInterruptKind::Stat => write!(f, "STAT"),
            GbInterruptKind::Timer => write!(f, "Timer"),
            GbInterruptKind::Serial => write!(f, "Serial"),
            GbInterruptKind::Joypad => write!(f, "Joypad"),
        }
    }
}

impl GbInterruptKind {
    /// Get the interrupt bit mask for this interrupt type.
    pub fn bit_mask(self) -> u8 {
        match self {
            GbInterruptKind::VBlank => 0x01,
            GbInterruptKind::Stat => 0x02,
            GbInterruptKind::Timer => 0x04,
            GbInterruptKind::Serial => 0x08,
            GbInterruptKind::Joypad => 0x10,
        }
    }

    /// Parse interrupt kind from string.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "vblank" => Some(GbInterruptKind::VBlank),
            "stat" => Some(GbInterruptKind::Stat),
            "timer" => Some(GbInterruptKind::Timer),
            "serial" => Some(GbInterruptKind::Serial),
            "joypad" => Some(GbInterruptKind::Joypad),
            _ => None,
        }
    }
}

/// The condition that triggers a breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakpointKind {
    /// Break when the program counter reaches the given address.
    Pc(u16),
    /// Break when the CPU cycle count equals the given value.
    Cycle(u64),
    /// Break when execution reaches the first instruction boundary on the given frame.
    Frame(u64),
    /// Break when the CPU writes to the given address (non-dummy write).
    WriteAddress(u16),
    /// Break when a specific GB interrupt is about to fire (GB only).
    GbInterrupt(GbInterruptKind),
}

impl fmt::Display for BreakpointKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BreakpointKind::Pc(addr) => write!(f, "PC={:04X}", addr),
            BreakpointKind::Cycle(n) => write!(f, "CYC={}", n),
            BreakpointKind::Frame(n) => write!(f, "FRM={}", n),
            BreakpointKind::WriteAddress(addr) => write!(f, "WR={:04X}", addr),
            BreakpointKind::GbInterrupt(kind) => write!(f, "INT={}", kind),
        }
    }
}

/// A single breakpoint with a condition and an enabled state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Breakpoint {
    pub kind: BreakpointKind,
    pub enabled: bool,
}

impl Breakpoint {
    pub fn new(kind: BreakpointKind) -> Self {
        Self {
            kind,
            enabled: true,
        }
    }

    /// Returns true if this breakpoint is enabled and its condition matches `ctx`.
    pub fn is_hit(&self, ctx: &EvalContext) -> bool {
        if !self.enabled {
            return false;
        }
        match self.kind {
            BreakpointKind::Pc(addr) => ctx.pc == addr,
            BreakpointKind::Cycle(target) => {
                ctx.prev_cpu_cycles < target && ctx.cpu_cycles >= target
            }
            BreakpointKind::Frame(target) => ctx.prev_frame < target && ctx.frame >= target,
            BreakpointKind::WriteAddress(addr) => ctx.write_addr == Some(addr),
            BreakpointKind::GbInterrupt(kind) => {
                // Check if GB interrupt is about to fire
                if let (Some(ie), Some(if_reg), Some(ime)) = (ctx.gb_ie, ctx.gb_if, ctx.gb_ime) {
                    let mask = kind.bit_mask();
                    // Interrupt is pending and enabled
                    ime && (ie & if_reg & mask) != 0
                } else {
                    false
                }
            }
        }
    }

    /// Serialize to a plain-text line suitable for a `.debug` file.
    pub fn serialize(&self) -> String {
        let state = if self.enabled { "enabled" } else { "disabled" };
        match self.kind {
            BreakpointKind::Pc(addr) => format!("pc {:#06X} {}", addr, state),
            BreakpointKind::Cycle(n) => format!("cycle {} {}", n, state),
            BreakpointKind::Frame(n) => format!("frame {} {}", n, state),
            BreakpointKind::WriteAddress(addr) => format!("write {:#06X} {}", addr, state),
            BreakpointKind::GbInterrupt(kind) => {
                let name = match kind {
                    GbInterruptKind::VBlank => "vblank",
                    GbInterruptKind::Stat => "stat",
                    GbInterruptKind::Timer => "timer",
                    GbInterruptKind::Serial => "serial",
                    GbInterruptKind::Joypad => "joypad",
                };
                format!("gbinterrupt {} {}", name, state)
            }
        }
    }

    /// Parse a plain-text line from a `.debug` file. Returns `None` for comments/blank lines.
    pub fn parse(line: &str) -> Option<Self> {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            return None;
        }
        let parts: Vec<&str> = line.splitn(3, ' ').collect();
        if parts.len() != 3 {
            return None;
        }
        let enabled = parts[2] != "disabled";
        let kind = match parts[0] {
            "pc" => {
                let addr = parse_u16(parts[1])?;
                BreakpointKind::Pc(addr)
            }
            "cycle" => {
                let n: u64 = parts[1].parse().ok()?;
                BreakpointKind::Cycle(n)
            }
            "frame" => {
                let n: u64 = parts[1].parse().ok()?;
                BreakpointKind::Frame(n)
            }
            "write" => {
                let addr = parse_u16(parts[1])?;
                BreakpointKind::WriteAddress(addr)
            }
            "gbinterrupt" => {
                let int_kind = GbInterruptKind::parse(parts[1])?;
                BreakpointKind::GbInterrupt(int_kind)
            }
            _ => return None,
        };
        Some(Self { kind, enabled })
    }
}

/// Parses a `u16` from either a hex string (`0x`/`0X` prefix) or a decimal string.
fn parse_u16(s: &str) -> Option<u16> {
    if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        u16::from_str_radix(hex, 16).ok()
    } else {
        s.parse().ok()
    }
}

/// Execution context passed to breakpoint evaluation after each CPU instruction.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct EvalContext {
    /// Current program counter value.
    pub pc: u16,
    /// Total CPU cycles before this instruction executed.
    pub prev_cpu_cycles: u64,
    /// Total CPU cycles after this instruction executed.
    pub cpu_cycles: u64,
    /// PPU frame counter value before this instruction executed.
    pub prev_frame: u64,
    /// PPU frame counter value after this instruction executed.
    pub frame: u64,
    /// Address written during this instruction (non-dummy write), if any.
    pub write_addr: Option<u16>,
    /// GB interrupt enable register (IE at $FFFF) - for GB interrupt breakpoints.
    pub gb_ie: Option<u8>,
    /// GB interrupt flag register (IF at $FF0F) - for GB interrupt breakpoints.
    pub gb_if: Option<u8>,
    /// GB IME (Interrupt Master Enable) flag - for GB interrupt breakpoints.
    pub gb_ime: Option<bool>,
}

/// An ordered list of persistent breakpoints.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct BreakpointList {
    items: Vec<Breakpoint>,
}

impl BreakpointList {
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of breakpoints.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns `true` if there are no breakpoints.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Add a breakpoint. Deduplicates by kind — if the kind already exists, the add is a no-op.
    pub fn add(&mut self, kind: BreakpointKind) {
        if !self.items.iter().any(|b| b.kind == kind) {
            self.items.push(Breakpoint::new(kind));
        }
    }

    /// Remove the breakpoint at the given index. No-op if out of bounds.
    pub fn remove(&mut self, index: usize) {
        if index < self.items.len() {
            self.items.remove(index);
        }
    }

    /// Remove the first breakpoint that matches the given kind. No-op if not found.
    pub fn remove_first_matching(&mut self, kind: &BreakpointKind) {
        if let Some(index) = self.items.iter().position(|b| &b.kind == kind) {
            self.items.remove(index);
        }
    }

    /// Enable the breakpoint at the given index. No-op if out of bounds.
    pub fn enable(&mut self, index: usize) {
        self.set_enabled(index, true);
    }

    /// Disable the breakpoint at the given index. No-op if out of bounds.
    pub fn disable(&mut self, index: usize) {
        self.set_enabled(index, false);
    }

    fn set_enabled(&mut self, index: usize, enabled: bool) {
        if let Some(bp) = self.items.get_mut(index) {
            bp.enabled = enabled;
        }
    }

    /// Returns an iterator over all breakpoints.
    pub fn iter(&self) -> std::slice::Iter<'_, Breakpoint> {
        self.items.iter()
    }

    /// Returns `true` if there is any PC breakpoint at `addr`, regardless of enabled state.
    /// Useful for checking pre-existence before conditionally adding a temporary breakpoint.
    pub fn has_pc_breakpoint_at(&self, addr: u16) -> bool {
        self.items
            .iter()
            .any(|b| b.kind == BreakpointKind::Pc(addr))
    }

    /// Returns `true` if there is an enabled PC breakpoint at `addr`.
    pub fn has_enabled_pc_breakpoint_at(&self, addr: u16) -> bool {
        self.items
            .iter()
            .any(|b| b.kind == BreakpointKind::Pc(addr) && b.enabled)
    }

    /// Force-enables the PC breakpoint at `addr` and returns its previous enabled state.
    /// Returns `None` if no PC breakpoint exists at `addr`.
    pub fn force_enable_pc_breakpoint_at(&mut self, addr: u16) -> Option<bool> {
        self.items
            .iter_mut()
            .find(|b| b.kind == BreakpointKind::Pc(addr))
            .map(|b| {
                let was_enabled = b.enabled;
                b.enabled = true;
                was_enabled
            })
    }

    /// Sets the enabled state of the PC breakpoint at `addr`.
    pub fn set_pc_breakpoint_enabled(&mut self, addr: u16, enabled: bool) {
        if let Some(b) = self
            .items
            .iter_mut()
            .find(|b| b.kind == BreakpointKind::Pc(addr))
        {
            b.enabled = enabled;
        }
    }

    /// Serialize all breakpoints to a multi-line string for `.debug` file storage.
    pub fn save_to_string(&self) -> String {
        self.items
            .iter()
            .map(|bp| bp.serialize())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Parse breakpoints from a `.debug` file string, skipping blank/comment lines.
    pub fn load_from_str(text: &str) -> Self {
        let items = text.lines().filter_map(Breakpoint::parse).collect();
        Self { items }
    }
}

/// Serialize a slice of watch addresses to lines suitable for a `.debug` file.
///
/// Returns an empty string when `addresses` is empty.
pub fn serialize_watch_addresses(addresses: &[u16]) -> String {
    addresses
        .iter()
        .map(|a| format!("watch {:#06X}", a))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Parse watch addresses from the text of a `.debug` file.
///
/// Lines that look like `watch 0x????` are collected; all other lines are
/// silently ignored so this function can be called on the full file content.
pub fn parse_watch_addresses(text: &str) -> Vec<u16> {
    text.lines()
        .filter_map(|line| {
            let line = line.trim();
            line.strip_prefix("watch ").and_then(parse_u16)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- BreakpointKind display ---

    #[test]
    fn test_breakpoint_kind_pc_displays_as_hex() {
        assert_eq!(format!("{}", BreakpointKind::Pc(0xC000)), "PC=C000");
    }

    #[test]
    fn test_breakpoint_kind_cycle_displays_with_count() {
        assert_eq!(format!("{}", BreakpointKind::Cycle(12345)), "CYC=12345");
    }

    #[test]
    fn test_breakpoint_kind_frame_displays_with_count() {
        assert_eq!(format!("{}", BreakpointKind::Frame(42)), "FRM=42");
    }

    #[test]
    fn test_breakpoint_kind_write_address_displays_as_hex() {
        assert_eq!(
            format!("{}", BreakpointKind::WriteAddress(0x2006)),
            "WR=2006"
        );
    }

    // --- PC breakpoint evaluation ---

    #[test]
    fn test_pc_breakpoint_hits_when_pc_matches() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_pc_breakpoint_does_not_hit_when_pc_differs() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC001,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_pc_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- Cycle breakpoint evaluation ---

    #[test]
    fn test_cycle_breakpoint_hits_when_cycle_crosses_threshold() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 998,
            cpu_cycles: 1002,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_hits_when_cycle_matches_exactly() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 999,
            cpu_cycles: 1000,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_hit_before_target_cycle() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 999,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_fire_again_after_threshold_crossed() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        // Both prev and current are past the target — threshold already crossed, should not re-fire.
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 1001,
            cpu_cycles: 1003,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_cycle_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Cycle(1000));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 999,
            cpu_cycles: 1002,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- Frame breakpoint evaluation ---

    #[test]
    fn test_frame_breakpoint_hits_when_frame_crosses_threshold() {
        let bp = Breakpoint::new(BreakpointKind::Frame(5));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 4,
            frame: 5,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_frame_breakpoint_does_not_hit_before_target_frame() {
        let bp = Breakpoint::new(BreakpointKind::Frame(5));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 4,
            frame: 4,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- WriteAddress breakpoint evaluation ---

    #[test]
    fn test_write_address_breakpoint_hits_when_write_matches() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_on_read() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_on_different_address_write() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2007),
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    #[test]
    fn test_write_address_breakpoint_does_not_hit_when_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        bp.enabled = false;
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!bp.is_hit(&ctx));
    }

    // --- BreakpointList management ---

    #[test]
    fn test_breakpoint_list_starts_empty() {
        let list = BreakpointList::new();
        assert_eq!(list.len(), 0);
    }

    #[test]
    fn test_breakpoint_list_add_pc_breakpoint() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_pc() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Pc(0xC000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_cycle() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Cycle(1000));
        list.add(BreakpointKind::Cycle(1000));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_frame() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Frame(60));
        list.add(BreakpointKind::Frame(60));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_add_does_not_duplicate_write_address() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::WriteAddress(0x2006));
        list.add(BreakpointKind::WriteAddress(0x2006));
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_remove_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Cycle(500));
        list.remove(0);
        assert_eq!(list.len(), 1);
        assert!(matches!(
            list.iter().next().map(|b| &b.kind),
            Some(BreakpointKind::Cycle(500))
        ));
    }

    #[test]
    fn test_breakpoint_list_remove_out_of_bounds_is_noop() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.remove(5); // no-op
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn test_breakpoint_list_enable_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        list.enable(0);
        assert!(list.iter().next().map(|b| b.enabled).unwrap_or(false));
    }

    #[test]
    fn test_breakpoint_list_disable_by_index() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        assert!(!list.iter().next().map(|b| b.enabled).unwrap_or(true));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_pc() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_cycle() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Cycle(500));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 498,
            cpu_cycles: 501,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_true_on_matching_write_address() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::WriteAddress(0x2006));
        let ctx = EvalContext {
            pc: 0x0000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: Some(0x2006),
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_no_match() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        let ctx = EvalContext {
            pc: 0xD000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_disabled() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.disable(0);
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 0,
            cpu_cycles: 0,
            write_addr: None,
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    #[test]
    fn test_breakpoint_list_check_hit_returns_false_when_empty() {
        let list = BreakpointList::new();
        let ctx = EvalContext {
            pc: 0xC000,
            prev_cpu_cycles: 498,
            cpu_cycles: 501,
            write_addr: Some(0x2006),
            gb_ie: None,
            gb_if: None,
            gb_ime: None,
            prev_frame: 0,
            frame: 0,
        };
        assert!(!list.iter().any(|bp| bp.is_hit(&ctx)));
    }

    // --- Serialization (plain text .debug format) ---

    #[test]
    fn test_breakpoint_kind_serialize_pc() {
        let bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        assert_eq!(bp.serialize(), "pc 0xC000 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_cycle() {
        let bp = Breakpoint::new(BreakpointKind::Cycle(12345));
        assert_eq!(bp.serialize(), "cycle 12345 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_frame() {
        let bp = Breakpoint::new(BreakpointKind::Frame(42));
        assert_eq!(bp.serialize(), "frame 42 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_write_address() {
        let bp = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        assert_eq!(bp.serialize(), "write 0x2006 enabled");
    }

    #[test]
    fn test_breakpoint_kind_serialize_disabled() {
        let mut bp = Breakpoint::new(BreakpointKind::Pc(0xC000));
        bp.enabled = false;
        assert_eq!(bp.serialize(), "pc 0xC000 disabled");
    }

    #[test]
    fn test_breakpoint_list_parse_pc_line() {
        let bp = Breakpoint::parse("pc 0xC000 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Pc(0xC000)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_cycle_line() {
        let bp = Breakpoint::parse("cycle 12345 disabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Cycle(12345)));
        assert!(!bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_frame_line() {
        let bp = Breakpoint::parse("frame 42 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::Frame(42)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_write_line() {
        let bp = Breakpoint::parse("write 0x2006 enabled").unwrap();
        assert!(matches!(bp.kind, BreakpointKind::WriteAddress(0x2006)));
        assert!(bp.enabled);
    }

    #[test]
    fn test_breakpoint_list_parse_ignores_comment_lines() {
        assert!(Breakpoint::parse("# this is a comment").is_none());
    }

    #[test]
    fn test_breakpoint_list_parse_ignores_empty_lines() {
        assert!(Breakpoint::parse("").is_none());
    }

    #[test]
    fn test_breakpoint_list_roundtrip_serialize_parse() {
        let original = Breakpoint::new(BreakpointKind::WriteAddress(0x2006));
        let serialized = original.serialize();
        let parsed = Breakpoint::parse(&serialized).unwrap();
        assert_eq!(parsed.kind, original.kind);
        assert_eq!(parsed.enabled, original.enabled);
    }

    #[test]
    fn test_breakpoint_list_save_and_load_roundtrip() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0xC000));
        list.add(BreakpointKind::Cycle(500));
        list.add(BreakpointKind::WriteAddress(0x2006));
        list.disable(1);

        let text = list.save_to_string();
        let loaded = BreakpointList::load_from_str(&text);

        assert_eq!(loaded.len(), 3);
        assert!(matches!(
            loaded.iter().next().map(|b| &b.kind),
            Some(BreakpointKind::Pc(0xC000))
        ));
        assert!(loaded.iter().next().map(|b| b.enabled).unwrap_or(false));
        assert!(matches!(
            loaded.iter().nth(1).map(|b| &b.kind),
            Some(BreakpointKind::Cycle(500))
        ));
        assert!(!loaded.iter().nth(1).map(|b| b.enabled).unwrap_or(true));
        assert!(matches!(
            loaded.iter().nth(2).map(|b| &b.kind),
            Some(BreakpointKind::WriteAddress(0x2006))
        ));
    }

    #[test]
    fn test_force_enable_pc_breakpoint_enables_disabled() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0x8000));
        list.disable(0);
        assert!(!list.has_enabled_pc_breakpoint_at(0x8000));

        let was_enabled = list.force_enable_pc_breakpoint_at(0x8000);
        assert_eq!(was_enabled, Some(false));
        assert!(list.has_enabled_pc_breakpoint_at(0x8000));
    }

    #[test]
    fn test_force_enable_pc_breakpoint_returns_true_when_already_enabled() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0x8000));

        let was_enabled = list.force_enable_pc_breakpoint_at(0x8000);
        assert_eq!(was_enabled, Some(true));
        assert!(list.has_enabled_pc_breakpoint_at(0x8000));
    }

    #[test]
    fn test_force_enable_pc_breakpoint_returns_none_when_missing() {
        let mut list = BreakpointList::new();
        let was_enabled = list.force_enable_pc_breakpoint_at(0x8000);
        assert_eq!(was_enabled, None);
    }

    #[test]
    fn test_set_pc_breakpoint_enabled_disables() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0x8000));
        assert!(list.has_enabled_pc_breakpoint_at(0x8000));

        list.set_pc_breakpoint_enabled(0x8000, false);
        assert!(!list.has_enabled_pc_breakpoint_at(0x8000));
        assert!(list.has_pc_breakpoint_at(0x8000));
    }

    #[test]
    fn test_set_pc_breakpoint_enabled_re_enables() {
        let mut list = BreakpointList::new();
        list.add(BreakpointKind::Pc(0x8000));
        list.disable(0);

        list.set_pc_breakpoint_enabled(0x8000, true);
        assert!(list.has_enabled_pc_breakpoint_at(0x8000));
    }

    // ── Watch address serialization (#1860) ───────────────────────────────────

    #[test]
    fn test_serialize_watch_addresses_empty() {
        assert_eq!(serialize_watch_addresses(&[]), "");
    }

    #[test]
    fn test_serialize_watch_addresses_single() {
        assert_eq!(serialize_watch_addresses(&[0x0300]), "watch 0x0300");
    }

    #[test]
    fn test_serialize_watch_addresses_multiple() {
        let s = serialize_watch_addresses(&[0x0300, 0x00FF]);
        assert_eq!(s, "watch 0x0300\nwatch 0x00FF");
    }

    #[test]
    fn test_parse_watch_addresses_empty_string() {
        assert!(parse_watch_addresses("").is_empty());
    }

    #[test]
    fn test_parse_watch_addresses_single_hex() {
        assert_eq!(parse_watch_addresses("watch 0x0300"), vec![0x0300u16]);
    }

    #[test]
    fn test_parse_watch_addresses_multiple_lines() {
        let text = "watch 0x0300\nwatch 0x00FF";
        assert_eq!(parse_watch_addresses(text), vec![0x0300u16, 0x00FF]);
    }

    #[test]
    fn test_parse_watch_addresses_ignores_breakpoint_lines() {
        let text = "pc 0x8000 enabled\nwatch 0x0300\ncycle 100 disabled";
        assert_eq!(parse_watch_addresses(text), vec![0x0300u16]);
    }

    #[test]
    fn test_watch_address_roundtrip() {
        let original = vec![0x0300u16, 0x00FF, 0x2006];
        let serialized = serialize_watch_addresses(&original);
        let parsed = parse_watch_addresses(&serialized);
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_breakpoint_list_load_from_str_ignores_watch_lines() {
        // Watch lines must be silently ignored when loading breakpoints so
        // files with both kinds parse correctly.
        let text = "pc 0x8000 enabled\nwatch 0x0300\nframe 5 disabled";
        let list = BreakpointList::load_from_str(text);
        assert_eq!(list.len(), 2, "only the two breakpoints should be loaded");
    }
}