checksmix 0.4.2

An assembler, emulator and source-level debugger for Knuth's MMIX.
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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! TRAP opcodes (file I/O, time, debug) and the Host they route through.

use super::*;

// ========== TRAP Handler Tests ==========

/// Points `$255` at the two-octa (buffer address, byte count) block
/// `Fread`/`Fwrite` share, at a fixed scratch address.
fn write_two_octa_params(mmix: &mut MMix, buffer_addr: u64, size: u64) {
    let param_addr = 200_000u64;
    mmix.write_octa(param_addr, buffer_addr);
    mmix.write_octa(param_addr + 8, size);
    mmix.set_register(255, param_addr);
}

/// A `Host` whose first `write` succeeds and every later one fails, as a
/// full pipe fails a long request partway.
struct FailsAfterFirstWrite {
    writes: usize,
}

impl Host for FailsAfterFirstWrite {
    fn write(&mut self, _fd: u8, _bytes: &[u8]) -> std::io::Result<()> {
        self.writes += 1;
        if self.writes == 1 {
            Ok(())
        } else {
            Err(std::io::Error::other("FailsAfterFirstWrite: later write"))
        }
    }

    fn now_micros(&mut self) -> u64 {
        0
    }

    fn diagnostic(&mut self, _msg: &str) {}
}

/// A `Host` whose every `write` fails, recording the length of each request.
struct FailsEveryWrite {
    requests: std::rc::Rc<std::cell::RefCell<Vec<usize>>>,
}

impl Host for FailsEveryWrite {
    fn write(&mut self, _fd: u8, bytes: &[u8]) -> std::io::Result<()> {
        self.requests.borrow_mut().push(bytes.len());
        Err(std::io::Error::other("FailsEveryWrite"))
    }

    fn now_micros(&mut self) -> u64 {
        0
    }

    fn diagnostic(&mut self, _msg: &str) {}
}

/// `len` bytes of a pattern that repeats every 251, so a dropped, repeated
/// or reordered chunk changes the stream.
fn patterned(len: usize) -> Vec<u8> {
    (0..len).map(|i| (i % 251) as u8).collect()
}

/// `Fwrite` moves a `size` past one chunk whole and in order, and reports 0.
#[test]
fn test_trap_fwrite_stdout_moves_a_size_past_one_chunk_whole() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let buffer_addr = 1_000_000u64;
    let data = patterned(1_048_576 + 3);
    for (i, &byte) in data.iter().enumerate() {
        mmix.write_byte(buffer_addr + i as u64, byte);
    }

    write_two_octa_params(&mut mmix, buffer_addr, data.len() as u64);
    mmix.write_tetra(0, 0x00000601); // TRAP 0, Fwrite (6), 1 (stdout)
    assert!(mmix.execute_instruction());

    assert_eq!(handle.stdout(), data);
    assert_eq!(mmix.get_register(255), 0);
}

/// A later chunk that fails to write reports the short write as `n - size`;
/// a `size` of exactly one chunk writes it all and reports 0.
#[test]
fn test_trap_fwrite_stdout_reports_short_write_when_a_later_chunk_fails() {
    let mut mmix = MMix::with_host(FailsAfterFirstWrite { writes: 0 });

    write_two_octa_params(&mut mmix, 10_000, 0x100003);
    mmix.write_tetra(0, 0x00000601); // TRAP 0, Fwrite (6), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-3i64) as u64);

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    write_two_octa_params(&mut mmix, 10_000, 0x100000);
    mmix.write_tetra(0, 0x00000601);
    assert!(mmix.execute_instruction());
    assert_eq!(handle.stdout().len(), 1_048_576);
    assert_eq!(mmix.get_register(255), 0);
}

/// `Fwrite` to a handle a negate can't hold safely — the result and the
/// failure value are both mod 2^64, never a signed overflow.
#[test]
fn test_trap_fwrite_stdin_rejects_and_does_not_negate_overflow() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);

    write_two_octa_params(&mut mmix, 10_000, 0x8000000000000000);
    mmix.write_tetra(0, 0x00000600); // TRAP 0, Fwrite (6), 0 (stdin)
    assert!(mmix.execute_instruction());
    assert!(handle.stdout().is_empty());
    assert_eq!(mmix.get_register(255), 0x8000000000000000);
}

/// `Fwrite` to a writable handle with a `size` above `i64::MAX`: pins the
/// wrapping (not signed) subtraction that turns the bytes written and the
/// guest's size into the result. The write fails after its first chunk, so
/// `n` is one chunk.
#[test]
fn test_trap_fwrite_stdout_size_above_i64_max_wraps_correctly() {
    let mut mmix = MMix::with_host(FailsAfterFirstWrite { writes: 0 });

    write_two_octa_params(&mut mmix, 10_000, 0x8000000000000000);
    mmix.write_tetra(0, 0x00000601); // TRAP 0, Fwrite (6), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0x8000000000100000);
}

/// `Fwrite` of a `size` no buffer could hold, against a host that fails
/// after its first chunk: the result is the chunk's bytes minus `size`,
/// mod 2^64.
#[test]
fn test_trap_fwrite_stdout_size_u64_max_reports_one_chunk_written() {
    let mut mmix = MMix::with_host(FailsAfterFirstWrite { writes: 0 });

    write_two_octa_params(&mut mmix, 10_000, u64::MAX);
    mmix.write_tetra(0, 0x00000601); // TRAP 0, Fwrite (6), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0x100001);
}

/// An empty `Fputs` or `Fputws` string, or an `Fwrite` `size` of 0, reaches `Host::write` as one
/// call with an empty slice, and the host's failure of it is the result.
#[test]
fn test_trap_empty_request_makes_one_empty_host_write() {
    let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let mut mmix = MMix::with_host(FailsEveryWrite {
        requests: requests.clone(),
    });
    mmix.set_register(255, 10_000); // no bytes stored: an empty string
    mmix.write_tetra(0, 0x00000701); // TRAP 0, Fputs (7), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
    assert_eq!(*requests.borrow(), vec![0]);

    let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let mut mmix = MMix::with_host(FailsEveryWrite {
        requests: requests.clone(),
    });
    write_two_octa_params(&mut mmix, 10_000, 0);
    mmix.write_tetra(0, 0x00000601); // TRAP 0, Fwrite (6), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0);
    assert_eq!(*requests.borrow(), vec![0]);

    let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let mut mmix = MMix::with_host(FailsEveryWrite {
        requests: requests.clone(),
    });
    mmix.set_register(255, 10_000);
    mmix.write_tetra(0, 0x00000801); // TRAP 0, Fputws (8), 1 (stdout)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
    assert_eq!(*requests.borrow(), vec![0]);
}

/// A `Host` implementing every method but `read`, so the trait's own
/// default -- `Err` of kind `Unsupported` -- is what a handle-0 call sees.
struct NoReadHost;

impl Host for NoReadHost {
    fn write(&mut self, _fd: u8, _bytes: &[u8]) -> std::io::Result<()> {
        Ok(())
    }

    fn now_micros(&mut self) -> u64 {
        0
    }

    fn diagnostic(&mut self, _msg: &str) {}
}

/// `Fread` on handle 0 reads the host's queued bytes: a full read returns
/// 0, and a short read at end of input returns `n - size`. `CaptureHost`
/// hands out one byte per `read` call, so this also proves `Fread`'s chunk
/// loop accumulates across several host calls rather than assuming one call
/// fills the request.
#[test]
fn test_trap_fread_handle0_reads_host_bytes() {
    let (mut host, _handle) = CaptureHost::new();
    host.queue_input(b"ABCDE");
    let mut mmix = MMix::with_host(host);
    let buffer_addr = 5_000u64;

    write_two_octa_params(&mut mmix, buffer_addr, 5);
    mmix.write_tetra(0, 0x00000300); // TRAP 0, Fread (3), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0);
    assert_eq!(
        (0..5)
            .map(|i| mmix.read_byte(buffer_addr + i))
            .collect::<Vec<_>>(),
        b"ABCDE"
    );

    let (mut host, _handle) = CaptureHost::new();
    host.queue_input(b"XYZ");
    let mut mmix = MMix::with_host(host);
    write_two_octa_params(&mut mmix, buffer_addr, 5);
    mmix.write_tetra(0, 0x00000300); // TRAP 0, Fread (3), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (3u64).wrapping_sub(5));
    assert_eq!(
        (0..3)
            .map(|i| mmix.read_byte(buffer_addr + i))
            .collect::<Vec<_>>(),
        b"XYZ"
    );
}

/// `Fgets` on handle 0 stops after a newline, stores the terminator and
/// returns the count.
#[test]
fn test_trap_fgets_handle0_stops_at_newline() {
    let (mut host, _handle) = CaptureHost::new();
    host.queue_input(b"hi\nignored");
    let mut mmix = MMix::with_host(host);
    let buffer_addr = 6_000u64;
    for i in 0..16 {
        mmix.write_byte(buffer_addr + i, 0xFF);
    }

    write_two_octa_params(&mut mmix, buffer_addr, 16);
    mmix.write_tetra(0, 0x00000400); // TRAP 0, Fgets (4), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 3);
    assert_eq!(
        (0..3)
            .map(|i| mmix.read_byte(buffer_addr + i))
            .collect::<Vec<_>>(),
        b"hi\n"
    );
    assert_eq!(mmix.read_byte(buffer_addr + 3), 0);
}

/// `Fgetws` on handle 0 reads whole wydes and stops at `#000A`.
/// `CaptureHost` hands out one byte per `read` call, so this also proves
/// `Fgetws` assembles each wyde from two host calls rather than one.
#[test]
fn test_trap_fgetws_handle0_reads_whole_wydes_and_stops_at_000a() {
    let (mut host, _handle) = CaptureHost::new();
    host.queue_input(&[0x00, 0x41, 0x00, 0x0A, 0x00, 0x42]);
    let mut mmix = MMix::with_host(host);
    let buffer_addr = 7_000u64;
    for i in 0..8 {
        mmix.write_byte(buffer_addr + i, 0xFF);
    }

    write_two_octa_params(&mut mmix, buffer_addr, 8);
    mmix.write_tetra(0, 0x00000500); // TRAP 0, Fgetws (5), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 2);
    assert_eq!(
        (0..4)
            .map(|i| mmix.read_byte(buffer_addr + i))
            .collect::<Vec<_>>(),
        vec![0x00, 0x41, 0x00, 0x0A]
    );
    assert_eq!(mmix.read_byte(buffer_addr + 4), 0);
    assert_eq!(mmix.read_byte(buffer_addr + 5), 0);
}

/// A host that leaves `read` at its default: `Fread` reports
/// `-(size + 1)` for a nonzero size and 0 for size 0; `Fgets` and `Fgetws`
/// both report -1.
#[test]
fn test_trap_default_host_read_fails_on_handle0_but_fread_size_0_succeeds() {
    let mut mmix = MMix::with_host(NoReadHost);
    write_two_octa_params(&mut mmix, 8_000, 10);
    mmix.write_tetra(0, 0x00000300); // TRAP 0, Fread (3), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), u64::MAX.wrapping_sub(10));

    let mut mmix = MMix::with_host(NoReadHost);
    write_two_octa_params(&mut mmix, 8_000, 0);
    mmix.write_tetra(0, 0x00000300); // TRAP 0, Fread (3), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0);

    let mut mmix = MMix::with_host(NoReadHost);
    for i in 0..16 {
        mmix.write_byte(8_000 + i, 0xFF);
    }
    write_two_octa_params(&mut mmix, 8_000, 16);
    mmix.write_tetra(0, 0x00000400); // TRAP 0, Fgets (4), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
    assert_eq!(
        mmix.read_byte(8_000),
        0,
        "the zero terminator is still stored"
    );

    let mut mmix = MMix::with_host(NoReadHost);
    for i in 0..8 {
        mmix.write_byte(8_000 + i, 0xFF);
    }
    write_two_octa_params(&mut mmix, 8_000, 8);
    mmix.write_tetra(0, 0x00000500); // TRAP 0, Fgetws (5), 0 (StdIn)
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
    assert_eq!(
        mmix.read_byte(8_000),
        0,
        "the zero terminator is still stored"
    );
    assert_eq!(mmix.read_byte(8_001), 0);
}

#[test]
fn test_trap_halt() {
    let mut mmix = MMix::new();
    // TRAP 0, Halt, 0
    mmix.write_tetra(0, 0x00000000); // TRAP 0,0,0
    let should_continue = mmix.execute_instruction();
    assert!(!should_continue); // Should halt
    assert_eq!(mmix.get_pc(), 4); // PC still advances
}

/// An `X != 0` trap halts as unsimulated and exits 1, like every other
/// halt but the `Halt` trap.
#[test]
fn test_trap_x_nonzero_halts_unsimulated_and_exits_1() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(2, 10);
    mmix.set_register(3, 20);
    mmix.write_tetra(0, 0x00010203); // TRAP 1,$2,$3
    assert!(!mmix.execute_instruction());
    assert_eq!(mmix.get_exit_code(), 1);
    assert_eq!(handle.diagnostics().len(), 1);
    assert_eq!(
        handle.diagnostics()[0],
        "unsimulated TRAP 1,2,3 at PC=0x0000000000000000"
    );
}

/// `X = 0` with a `Y` `TrapCode::from_u8` does not name halts as
/// unsimulated, with the TRAP page's registers set from the pre-trap
/// machine state.
#[test]
fn test_trap_x_zero_unknown_code_halts_with_trap_page_registers() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(99, 0x1111);
    mmix.set_register(7, 0x2222);
    mmix.set_register(255, 0x3333);
    mmix.set_special(SpecialReg::RJ, 0x4444);
    mmix.write_tetra(0, 0x00006307); // TRAP 0,99,7

    assert!(!mmix.execute_instruction());
    assert_eq!(mmix.get_exit_code(), 1);
    assert_eq!(mmix.get_pc(), 0);
    assert_eq!(handle.diagnostics().len(), 1);
    assert_eq!(
        handle.diagnostics()[0],
        "unsimulated TRAP 0,99,7 at PC=0x0000000000000000"
    );
    assert_eq!(mmix.get_special(SpecialReg::RBB), 0x3333);
    assert_eq!(mmix.get_register(255), 0x4444);
    assert_eq!(mmix.get_special(SpecialReg::RWW), 4);
    assert_eq!(mmix.get_special(SpecialReg::RXX), 0x8000_0000_0000_6307);
    assert_eq!(mmix.get_special(SpecialReg::RYY), 0x1111);
    assert_eq!(mmix.get_special(SpecialReg::RZZ), 0x2222);
}

/// `X != 0` sets the TRAP page's registers from full-width `$Y`/`$Z`
/// contents.
#[test]
fn test_trap_x_nonzero_sets_trap_page_registers_from_full_width_y() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(10, 0x1234_0000_0000_0000);
    mmix.set_register(20, 0xABCD);
    mmix.set_register(255, 0x5555);
    mmix.set_special(SpecialReg::RJ, 0x6666);
    mmix.write_tetra(0, 0x00050A14); // TRAP 5,10,20

    assert!(!mmix.execute_instruction());
    assert_eq!(mmix.get_exit_code(), 1);
    assert_eq!(mmix.get_pc(), 0);
    assert_eq!(handle.diagnostics().len(), 1);
    assert_eq!(
        handle.diagnostics()[0],
        "unsimulated TRAP 5,10,20 at PC=0x0000000000000000"
    );
    assert_eq!(mmix.get_special(SpecialReg::RBB), 0x5555);
    assert_eq!(mmix.get_register(255), 0x6666);
    assert_eq!(mmix.get_special(SpecialReg::RWW), 4);
    assert_eq!(mmix.get_special(SpecialReg::RXX), 0x8000_0000_0005_0A14);
    assert_eq!(mmix.get_special(SpecialReg::RYY), 0x1234_0000_0000_0000);
    assert_eq!(mmix.get_special(SpecialReg::RZZ), 0xABCD);
}

/// `Y` and `Z` naming `$255` still read the pre-trap value: the reads
/// happen before `$255 ← rJ` overwrites it.
#[test]
fn test_trap_y_and_z_as_255_read_before_255_is_overwritten() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(255, 0x1357);
    mmix.set_special(SpecialReg::RJ, 0x2468);
    mmix.write_tetra(0, 0x0005FFFF); // TRAP 5,255,255

    assert!(!mmix.execute_instruction());
    assert_eq!(handle.diagnostics().len(), 1);
    assert_eq!(mmix.get_special(SpecialReg::RYY), 0x1357);
    assert_eq!(mmix.get_special(SpecialReg::RZZ), 0x1357);
    assert_eq!(mmix.get_special(SpecialReg::RBB), 0x1357);
    assert_eq!(mmix.get_register(255), 0x2468);
}

#[test]
fn test_trap_fputs_stdout() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let test_string = b"Hello, MMIX!\0";
    let str_addr = 1000u64;

    for (i, &byte) in test_string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }

    mmix.set_register(255, str_addr); // Fputs reads string address from $255
    mmix.write_tetra(0, 0x00000701); // TRAP 0, Fputs (7), 1 (stdout)
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_pc(), 4);
    assert_eq!(mmix.get_register(255), 12); // bytes written
    assert_eq!(handle.stdout(), b"Hello, MMIX!");
    assert!(handle.stderr().is_empty());
}

#[test]
fn test_trap_fputs_stderr() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let test_string = b"Error message\0";
    let str_addr = 2000u64;

    for (i, &byte) in test_string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000702); // TRAP 0, Fputs (7), 2 (stderr)
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_pc(), 4);
    assert_eq!(mmix.get_register(255), 13);
    assert_eq!(handle.stderr(), b"Error message");
    assert!(handle.stdout().is_empty());
}

#[test]
fn test_trap_fputc_stdout() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(255, b'X' as u64);
    mmix.write_tetra(0, 0x00008001); // TRAP 0, Fputc (#80), 1 (stdout)
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_register(255), 0); // Success (return code 0 in $255)
    assert_eq!(mmix.get_pc(), 4);
    assert_eq!(handle.stdout(), b"X");
}

#[test]
fn test_trap_fputws() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    // One wyde ("Hi") then a terminating zero wyde.
    let str_addr = 3000u64;
    for (i, &byte) in [b'H', b'i', 0x00, 0x00].iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }

    mmix.set_register(255, str_addr); // $255 contains string address
    mmix.write_tetra(0, 0x00000801); // TRAP 0, Fputws (8), 1 (stdout)
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_register(255), 1); // wyde count returned in $255
    assert_eq!(handle.stdout(), b"Hi");
}

/// A string of exactly one chunk, followed by its zero, writes whole.
#[test]
fn test_trap_fputs_of_exactly_one_chunk_writes_whole() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let str_addr = 10_000u64;
    for i in 0..1_048_576u64 {
        mmix.write_byte(str_addr + i, b'A');
    }
    mmix.write_byte(str_addr + 1_048_576, 0);

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000701); // TRAP 0, Fputs (7), 1 (stdout)
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), 1_048_576);
    assert_eq!(handle.stdout().len(), 1_048_576);
    assert!(handle.diagnostics().is_empty());
}

/// A string one byte past a chunk writes whole, in order, with the full
/// count in `$255` and no diagnostic.
#[test]
fn test_trap_fputs_past_one_chunk_writes_whole() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let str_addr = 1_000_000u64;
    let string: Vec<u8> = patterned(1_048_577).into_iter().map(|b| b.max(1)).collect();
    for (i, &byte) in string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }
    mmix.write_byte(str_addr + string.len() as u64, 0);

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000701);
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), 1_048_577);
    assert_eq!(handle.stdout(), string);
    assert!(handle.diagnostics().is_empty());
}

/// A write error after an earlier chunk landed still returns -1.
#[test]
fn test_trap_fputs_returns_minus_one_when_a_later_chunk_fails() {
    let mut mmix = MMix::with_host(FailsAfterFirstWrite { writes: 0 });
    let str_addr = 1_000_000u64;
    for i in 0..1_048_577u64 {
        mmix.write_byte(str_addr + i, b'A');
    }

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000701);
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), (-1i64) as u64);
}

/// A string of exactly one chunk of wydes, followed by the terminating zero
/// wyde, writes whole.
#[test]
fn test_trap_fputws_of_exactly_one_chunk_writes_whole() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let str_addr = 20_000u64;
    for i in 0..524_288u64 {
        mmix.write_byte(str_addr + i * 2, 0x00);
        mmix.write_byte(str_addr + i * 2 + 1, 0x41);
    }
    mmix.write_byte(str_addr + 524_288 * 2, 0);
    mmix.write_byte(str_addr + 524_288 * 2 + 1, 0);

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000801); // TRAP 0, Fputws (8), 1 (stdout)
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), 524_288);
    assert_eq!(handle.stdout().len(), 1_048_576);
    assert!(handle.diagnostics().is_empty());
}

/// A string one wyde past a chunk writes whole, in order, with the full
/// wyde count in `$255` and no diagnostic.
#[test]
fn test_trap_fputws_past_one_chunk_writes_whole() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let str_addr = 1_000_000u64;
    let wydes = 524_289usize;
    let mut string = Vec::with_capacity(wydes * 2);
    for i in 0..wydes {
        string.push((i % 251) as u8);
        string.push(0x41);
    }
    for (i, &byte) in string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }
    mmix.write_byte(str_addr + string.len() as u64, 0);
    mmix.write_byte(str_addr + string.len() as u64 + 1, 0);

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000801);
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), wydes as u64);
    assert_eq!(handle.stdout(), string);
    assert!(handle.diagnostics().is_empty());
}

/// A write error after an earlier chunk landed still returns -1.
#[test]
fn test_trap_fputws_returns_minus_one_when_a_later_chunk_fails() {
    let mut mmix = MMix::with_host(FailsAfterFirstWrite { writes: 0 });
    let str_addr = 1_000_000u64;
    for i in 0..524_289u64 {
        mmix.write_byte(str_addr + i * 2, 0x00);
        mmix.write_byte(str_addr + i * 2 + 1, 0x41);
    }

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000801);
    assert!(mmix.execute_instruction());

    assert_eq!(mmix.get_register(255), (-1i64) as u64);
}

#[test]
fn test_host_trap_hook_reports_arg_and_both_255_values() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let test_string = b"Hi\0";
    let str_addr = 4000u64;

    for (i, &byte) in test_string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }

    mmix.set_register(255, str_addr);
    mmix.write_tetra(0, 0x00000701); // TRAP 0, Fputs (7), 1 (stdout)
    assert!(mmix.execute_instruction());

    let traps = handle.traps();
    assert_eq!(traps.len(), 1);
    let (code, arg, arg255, result255) = traps[0];
    assert_eq!(code, TrapCode::Fputs);
    assert_eq!(arg, 1); // fd 1 (stdout)
    assert_eq!(arg255, str_addr); // $255 before: the string address
    assert_eq!(result255, 2); // $255 after: the byte count
    assert!(handle.diagnostics().is_empty()); // a clean write logs no diagnostic
}

#[test]
fn test_halt_routes_diagnostic_and_flush_to_host() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_register(255, 42);
    mmix.write_tetra(0, 0x00000000); // TRAP 0, Halt (0), 0
    let should_continue = mmix.execute_instruction();
    assert!(!should_continue);
    assert_eq!(
        handle.diagnostics(),
        vec!["HALT trap at PC=0x0000000000000000, exit code=42".to_string()]
    );
    assert_eq!(handle.flushes(), 1);
    assert!(handle.stderr().is_empty()); // no stray fd-2 write alongside it
    assert_eq!(handle.traps(), vec![(TrapCode::Halt, 0, 42, 42)]);
}

#[test]
fn test_boxed_host_delegates_every_method() {
    let (mut host, handle) = CaptureHost::with_clock(7_000_000);
    host.queue_input(b"Q");
    let boxed: Box<dyn Host> = Box::new(host);
    let mut mmix = MMix::with_host(boxed);

    mmix.set_register(255, u64::from(b'Z'));
    mmix.write_tetra(0, 0x00008001); // TRAP 0, Fputc (#80), fd 1 -> write
    assert!(mmix.execute_instruction());

    mmix.set_pc(4);
    mmix.write_tetra(4, 0x00008100); // TRAP 0, Time (#81), unit 0 -> now_micros
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 7);

    mmix.set_pc(8);
    let buffer_addr = 100u64;
    write_two_octa_params(&mut mmix, buffer_addr, 1);
    mmix.write_tetra(8, 0x00000300); // TRAP 0, Fread (3), 0 (StdIn) -> read
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), 0);
    assert_eq!(mmix.read_byte(buffer_addr), b'Q');

    mmix.set_pc(12);
    mmix.set_register(255, 9);
    mmix.write_tetra(12, 0x00000000); // TRAP 0, Halt (0) -> flush + diagnostic
    assert!(!mmix.execute_instruction());

    // One assertion per trait method, so a missed delegation names itself.
    assert_eq!(handle.stdout(), b"Z"); // write
    assert_eq!(handle.flushes(), 1); // flush
    assert_eq!(handle.diagnostics().len(), 1); // diagnostic
    assert_eq!(
        handle.traps(),
        vec![
            (TrapCode::Fputc, 1, u64::from(b'Z'), 0),
            // $255 enters Time as 0: Fputc stored 0 there on success.
            (TrapCode::Time, 0, 0, 7),
            // $255 enters Fread holding write_two_octa_params' own scratch
            // address; a successful single-byte read reports 0.
            (TrapCode::Fread, 0, 200_000, 0),
            (TrapCode::Halt, 0, 9, 9),
        ]
    ); // trap
}

#[test]
fn test_injected_clock_drives_handle_time() {
    let (host, _handle) = CaptureHost::with_clock(5_000_000); // 5s since epoch
    let mut mmix = MMix::with_host(host);
    mmix.write_tetra(0, 0x00008100); // TRAP 0, Time (#81), unit=0 (seconds)
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_register(255), 5);
}

#[test]
fn test_trap_fclose_error() {
    let mut mmix = MMix::new();
    // Try to close a handle that was never opened.
    mmix.write_tetra(0, 0x00000263); // TRAP 0, Fclose (2), 99
    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_register(255), (-1i64) as u64); // Error returned in $255
}

#[test]
fn test_trap_time_microseconds() {
    let mut mmix = MMix::new();
    // TRAP 0, Time, 2 (get time in microseconds)
    mmix.write_tetra(0, 0x00008102); // TRAP 0, Time (#81), 2 (microseconds)

    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_pc(), 4); // PC advanced

    let time_us = mmix.get_register(255);
    // Time should be greater than 0 (some time has passed since Unix epoch)
    assert!(time_us > 0);
    // Time should be reasonable (after Jan 1, 2020)
    // Jan 1, 2020 00:00:00 UTC = 1577836800 seconds = 1577836800000000 microseconds
    assert!(time_us > 1_577_836_800_000_000);
    // Time should be before year 3000 (approximately)
    // Jan 1, 3000 00:00:00 UTC ≈ 32503680000 seconds ≈ 32503680000000000 microseconds
    assert!(time_us < 32_503_680_000_000_000);
}

#[test]
fn test_trap_time_milliseconds() {
    let mut mmix = MMix::new();
    // TRAP 0, Time, 1 (get time in milliseconds)
    mmix.write_tetra(0, 0x00008101); // TRAP 0, Time (#81), 1 (milliseconds)

    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_pc(), 4);

    let time_ms = mmix.get_register(255);
    assert!(time_ms > 0);
    // After Jan 1, 2020 in milliseconds
    assert!(time_ms > 1_577_836_800_000);
    // Before year 3000 in milliseconds
    assert!(time_ms < 32_503_680_000_000);
}

#[test]
fn test_trap_time_seconds() {
    let mut mmix = MMix::new();
    // TRAP 0, Time, 0 (get time in seconds)
    mmix.write_tetra(0, 0x00008100); // TRAP 0, Time (#81), 0 (seconds)

    let should_continue = mmix.execute_instruction();
    assert!(should_continue);
    assert_eq!(mmix.get_pc(), 4);

    let time_s = mmix.get_register(255);
    assert!(time_s > 0);
    // After Jan 1, 2020 in seconds
    assert!(time_s > 1_577_836_800);
    // Before year 3000 in seconds
    assert!(time_s < 32_503_680_000);
}

#[test]
fn test_trap_time_monotonic() {
    let mut mmix = MMix::new();
    // Get time twice and ensure second is >= first (monotonic)
    mmix.write_tetra(0, 0x00008102); // TRAP 0, Time (#81), 2 (microseconds)
    mmix.execute_instruction();
    let time1 = mmix.get_register(255);

    // Reset PC and execute again
    mmix.set_pc(0);
    mmix.execute_instruction();
    let time2 = mmix.get_register(255);

    // Time should be monotonic (second time >= first time)
    assert!(time2 >= time1);
}

#[test]
fn test_trap_fputs_unknown_fd_returns_error() {
    // Fputs to a closed/unknown fd must report -1, not the byte count.
    let mut mmix = MMix::new();
    let test_string = b"data\0";
    let str_addr = 200u64;
    for (i, &byte) in test_string.iter().enumerate() {
        mmix.write_byte(str_addr + i as u64, byte);
    }
    mmix.set_register(255, str_addr);
    // TRAP 0, Fputs (7), 99 (no such fd)
    mmix.write_tetra(0, 0x00000763);
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
}

#[test]
fn test_trap_fputc_unknown_fd_returns_error() {
    let mut mmix = MMix::new();
    mmix.set_register(255, b'A' as u64);
    // TRAP 0, Fputc (#80), 99
    mmix.write_tetra(0, 0x00008063);
    assert!(mmix.execute_instruction());
    assert_eq!(mmix.get_register(255), (-1i64) as u64);
}

/// End-to-end proof of the `debug` contract: a subroutine that sets
/// locals, prints, makes a nested call with `rJ` saved and restored,
/// prints again, then returns, leaves its caller's locals, `rL`, `rJ`
/// and the returned value exactly as an equivalent program without the
/// two `debug` lines would.
#[test]
fn test_debug_preserves_every_register_around_a_nested_call() {
    use crate::debugger::{entry_point, write_image};
    use crate::mmixal::MMixAssembler;

    const SOURCE: &str = "\
\tLOC\t#100
Main\tSET\t$1,11
\tPUSHJ\t$2,Sub
\tTRAP\t0,Halt,0
Sub\tSET\t$0,5
\tSET\t$1,7
\tdebug\t\"first\"
\tGET\t$2,rJ
\tPUSHJ\t$3,Nested
\tPUT\trJ,$2
\tdebug\t\"second\"
\tPOP\t1,0
Nested\tSET\t$0,42
\tPOP\t0,0
";
    let mut asm = MMixAssembler::new(SOURCE, "<test>");
    asm.parse().expect("program must assemble");
    let main_addr = *asm.labels.get("Main").expect("Main label");

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    write_image(&mut mmix, &asm);
    mmix.set_pc(entry_point(&asm));

    let (_, stop) = mmix.run_bounded(10_000);
    assert_eq!(stop, Stop::Halted);

    let stdout = String::from_utf8(handle.stdout()).expect("valid utf8");
    assert!(stdout.contains("first\n"), "got {stdout:?}");
    assert!(stdout.contains("second\n"), "got {stdout:?}");
    assert!(
        stdout.find("first").unwrap() < stdout.find("second").unwrap(),
        "the two debug lines must print in order, got {stdout:?}"
    );

    // Main's own local, staged below PUSHJ's hole, survives Sub's whole
    // call -- including both debug lines and the nested call inside it.
    assert_eq!(mmix.get_register(1), 11, "caller's local $1 must survive");
    // Sub's $0, set before either debug line, is what POP 1,0 returns
    // to the hole -- proof debug left it untouched across both calls.
    assert_eq!(mmix.get_register(2), 5, "returned value");
    assert_eq!(mmix.get_special(SpecialReg::RL), 3);
    // rJ lands back on Main's own PUSHJ (the second instruction) + 4:
    // Sub's own POP read it straight, with nothing to restore, since
    // nothing after Sub's own GET/PUT round trip ever touched it.
    assert_eq!(mmix.get_special(SpecialReg::RJ), main_addr + 8);
    // TRAP's own handler advances pc past itself before halting.
    assert_eq!(mmix.get_pc(), main_addr + 12, "halt address");
    assert_eq!(mmix.call_depth(), 0);
}

/// At `rG = 255`, every register but `rG` itself is local. `debug`
/// assembles to a single `TRAP` that touches no register, so it neither
/// inspects nor cares about `rG`'s value: the directive prints and the
/// program halts normally.
#[test]
fn test_debug_at_rg_255_prints_and_continues() {
    use crate::debugger::{entry_point, write_image};
    use crate::mmixal::MMixAssembler;

    const SOURCE: &str = "\
\tLOC\t#100
\tSET\t$1,255
\tPUT\trG,$1
\tdebug\t\"reachable\"
\tTRAP\t0,Halt,0
";
    let mut asm = MMixAssembler::new(SOURCE, "<test>");
    asm.parse().expect("program must assemble");

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    write_image(&mut mmix, &asm);
    mmix.set_pc(entry_point(&asm));

    let (_, stop) = mmix.run_bounded(100);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(handle.stdout(), b"reachable\n");
    assert_eq!(mmix.get_special(SpecialReg::RG), 255);
}

/// Assembles `source`, runs it under a fresh `CaptureHost` for up to
/// `budget` instructions, and returns the machine, the run's outcome,
/// and captured stdout. Shared by the `debug`-expansion regression
/// tests below.
fn assemble_and_run_bounded(source: &str, budget: usize) -> (MMix, Stop, String) {
    use crate::debugger::{entry_point, write_image};
    use crate::mmixal::MMixAssembler;

    let mut asm = MMixAssembler::new(source, "<test>");
    asm.parse().expect("program must assemble");

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    write_image(&mut mmix, &asm);
    mmix.set_pc(entry_point(&asm));
    let (_, stop) = mmix.run_bounded(budget);

    let stdout = String::from_utf8(handle.stdout()).expect("valid utf8");
    (mmix, stop, stdout)
}

/// A `debug` line followed by a trailing blank line at end of file, with
/// nothing after it to halt on: falling off the end reads zeroed
/// memory, which decodes as `TRAP 0,Halt,0`, so the program halts and
/// the text prints exactly once.
#[test]
fn test_debug_directive_followed_by_a_blank_line_at_eof() {
    let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n\n";
    let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
    assert_eq!(stdout, "hi\n");
}

/// A `debug` line followed by a trailing comment line at end of file.
#[test]
fn test_debug_directive_followed_by_a_comment_line_at_eof() {
    let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n% nothing else follows\n";
    let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
    assert_eq!(stdout, "hi\n");
}

/// A `debug` line as the source's last statement, with nothing after
/// it at all -- not even a blank or comment line.
#[test]
fn test_debug_directive_as_the_last_statement() {
    let source = "\tLOC\t#100\nMain\tdebug \"hi\"\n";
    let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted, "must not loop, got {stdout:?}");
    assert_eq!(stdout, "hi\n");
}

/// An `IS` line right after `debug`: unrelated to the call's own return
/// address, it binds its own constant and every later instruction
/// still runs in order.
#[test]
fn test_debug_directive_followed_by_an_is_line() {
    let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Ret2\tIS\t#10C
\tSET\t$1,7
\tSET\t$2,Ret2
\tTRAP\t0,Halt,0
";
    let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(stdout, "hi\n");
    assert_eq!(mmix.get_register(1), 7);
    assert_eq!(mmix.get_register(2), 0x10C, "Ret2 must still bind #10C");
}

/// A `GREG` line right after `debug`: it allocates its own register
/// exactly as it would without `debug` in front of it.
#[test]
fn test_debug_directive_followed_by_a_greg_line() {
    let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Foo\tGREG\t@
\tSET\tFoo,42
\tSET\t$1,Foo
\tTRAP\t0,Halt,0
";
    let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(stdout, "hi\n");
    assert_eq!(mmix.get_register(1), 42, "Foo must still hold 42");
}

/// A label-only line (no instruction) right after `debug`.
#[test]
fn test_debug_directive_followed_by_a_label_only_line() {
    let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
Done
\tSET\t$1,7
\tTRAP\t0,Halt,0
";
    let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(stdout, "hi\n");
    assert_eq!(mmix.get_register(1), 7);
}

/// A `:`-prefixed (global-namespace) label-only line right after `debug`.
#[test]
fn test_debug_directive_followed_by_a_colon_prefixed_label() {
    let source = "\
\tLOC\t#100
Main\tdebug\t\"hi\"
:Done
\tSET\t$1,7
\tTRAP\t0,Halt,0
";
    let (mmix, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(stdout, "hi\n");
    assert_eq!(mmix.get_register(1), 7);
}

/// `debug "text"` writes the source text's own UTF-8 bytes: `€`
/// (U+20AC) is `E2 82 AC`, three bytes, not its low byte alone.
#[test]
fn test_debug_directive_writes_non_ascii_text_as_utf8_bytes() {
    let source = "\tLOC\t#100\nMain\tdebug\t\"€\"\n\tTRAP\t0,Halt,0\n";
    let (_, stop, stdout) = assemble_and_run_bounded(source, 1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(stdout.as_bytes(), [0xE2, 0x82, 0xAC, b'\n']);
}

/// `TRAP 0,Debug,K` writes its string and a newline to handle 1 and
/// changes no register -- not even `$255`. Reverting to the stub
/// expansion (a `JMP`/`SAVE`/`GETA`/`TRAP`/`UNSAVE` sequence) would move
/// the PC through several extra instructions and touch `$254`/`$255`.
#[test]
fn test_debug_trap_writes_text_and_a_newline_touching_no_register() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_debug_strings(vec![b"hello".to_vec()]);

    for reg in 0..=255u8 {
        mmix.set_register(reg, 0xABCD_0000 | u64::from(reg));
    }
    let before: Vec<u64> = (0..=255u8).map(|r| mmix.get_register(r)).collect();

    mmix.write_tetra(0, 0x00008200); // TRAP 0, Debug (#82), K=0
    assert!(mmix.execute_instruction());

    assert_eq!(handle.stdout(), b"hello\n");
    assert_eq!(mmix.get_pc(), 4);
    for reg in 0..=255u8 {
        assert_eq!(
            mmix.get_register(reg),
            before[reg as usize],
            "$#{reg} must survive debug untouched"
        );
    }
}

/// A `K` past the table's end prints nothing, reports a diagnostic, and
/// leaves execution running.
#[test]
fn test_debug_trap_index_past_the_table_reports_and_continues() {
    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    mmix.set_debug_strings(vec![b"only one".to_vec()]);

    mmix.write_tetra(0, 0x00008201); // TRAP 0, Debug (#82), K=1 (no such string)
    assert!(mmix.execute_instruction());

    assert!(handle.stdout().is_empty());
    assert_eq!(mmix.get_pc(), 4);
    assert_eq!(handle.diagnostics().len(), 1);
    assert!(handle.diagnostics()[0].contains('1'));
}

/// Two translation units each print their own `debug` string: the
/// second unit's directive picks up `K` where the first left off.
#[test]
fn test_two_translation_units_each_print_their_own_debug_string() {
    use crate::debugger::{entry_point, write_image};
    use crate::mmixal::MMixAssembler;

    let mut asm = MMixAssembler::new("\tLOC\t#100\nMain\tdebug\t\"from a\"\n", "a.mms");
    asm.add_source("\tdebug\t\"from b\"\n\tTRAP\t0,Halt,0\n", "b.mms");
    asm.parse().expect("program must assemble");

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    write_image(&mut mmix, &asm);
    mmix.set_pc(entry_point(&asm));
    let (_, stop) = mmix.run_bounded(1_000);

    // Wrong K assignment across units would print "from a" twice.
    assert_eq!(stop, Stop::Halted);
    assert_eq!(handle.stdout(), b"from a\nfrom b\n");
}

/// The `.mmo` round trip prints the same text a direct run does: the
/// string table survives `generate_object_code` -> `MmoDecoder::decode`
/// -> `set_debug_strings` unchanged.
#[test]
fn test_debug_string_survives_the_mmo_round_trip() {
    use crate::debugger::{entry_point, write_image};
    use crate::mmixal::MMixAssembler;
    use crate::mmo::MmoDecoder;

    let source = "\tLOC\t#100\nMain\tdebug\t\"roundtrip\"\n\tTRAP\t0,Halt,0\n";
    let mut asm = MMixAssembler::new(source, "<test>");
    asm.parse().expect("program must assemble");
    let object_code = asm.generate_object_code();

    let (host, handle) = CaptureHost::new();
    let mut mmix = MMix::with_host(host);
    let decoder = MmoDecoder::new(object_code);
    let entry = decoder
        .decode(|addr, byte| mmix.write_byte(addr, byte))
        .expect("well-formed object code");
    mmix.set_debug_strings(decoder.debug_strings());
    mmix.set_pc(entry);

    let (_, stop) = mmix.run_bounded(1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(handle.stdout(), b"roundtrip\n");

    // The direct-run reference: write_image's table must match too.
    let (host2, handle2) = CaptureHost::new();
    let mut mmix2 = MMix::with_host(host2);
    write_image(&mut mmix2, &asm);
    mmix2.set_pc(entry_point(&asm));
    mmix2.run_bounded(1_000);
    assert_eq!(handle.stdout(), handle2.stdout());
}

/// A `TRIP` handler at `#00` built to `.mmo` and loaded with `load` is
/// reachable: `write_loaded_byte` (not plain `write_byte`) is what makes
/// vector 0 count as loaded rather than tripping "unloaded vector 0x00".
#[test]
fn trip_handler_at_vector_zero_is_reachable_after_an_mmo_load() {
    use crate::mmixal::MMixAssembler;
    use crate::mmo::{MmoDecoder, MmoGenerator};

    let source = "\
        LOC     #00
        SETI    $9,42
        RESUME  0
        LOC     #100
Main    TRIP    0,0,0
        SETI    $10,7
        TRAP    0,Halt,0
";
    let mut asm = MMixAssembler::new(source, "<test>");
    asm.parse().expect("program must assemble");

    let mmo_data = MmoGenerator::new(asm.instructions.clone(), asm.labels.clone())
        .with_debug_strings(asm.debug_strings().to_vec())
        .with_greg_inits(asm.greg_inits.clone())
        .generate();

    let mut mmix = MMix::new();
    let decoder = MmoDecoder::new(mmo_data);
    let entry = decoder.load(&mut mmix).expect("well-formed object code");
    mmix.set_pc(entry);

    let (_, stop) = mmix.run_bounded(1_000);
    assert_eq!(stop, Stop::Halted);
    assert_eq!(mmix.get_register(9), 42, "the TRIP handler at #00 must run");
    assert_eq!(mmix.get_register(10), 7, "RESUME must return to Main");
}