hg80 1.0.0

Z80 and Z80N CPU core, stepped one clock edge at a time
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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
// Portions of this file are derived from the T80 Z80-compatible microprocessor core,
// Copyright (c) 2001-2002 Daniel Wallner, and from the T80N modifications made for the
// ZX Spectrum Next Project, Copyright 2020 Fabio Belavenuto, Victor Trucco, Charlie Ingley,
// Garry Lancaster, ACX. Redistributed under the three-clause BSD licence reproduced in NOTICE.

//! An instruction-stepped execution layer, built against the edge-stepped core as its
//! specification.
//!
//! The edge-stepped core re-decides what to commit sixteen times per instruction because that is
//! what a clocked state machine does. Nothing a machine observes is finer than a machine cycle, so
//! this layer runs an instruction at a time and emits the cycles the instruction would have
//! performed.
//!
//! **It is verified against the other implementation rather than inspected.** The two are driven
//! over generated programs and every host interaction is compared — kinds, addresses, values, the
//! order they arrive in, the offset at which each transfer completes and how many times the machine
//! is asked. The edge-stepped core already agrees with a simulation of the hardware cycle by cycle,
//! so agreeing with it carries that guarantee across.

use crate::alu::{self, AluOp};
use crate::consts::flag;
use crate::control::mask;
use crate::extended::{self, Barrel};
use crate::flags;
use crate::host::{BusCycle, BusRequest, Host};
use crate::mcode::InstructionSet;
use crate::types::{InterruptMode, Registers, UndocumentedFlags, Z80nCommand};

// The same values the edge-stepped core reports, and for the same reason: an instruction-stepped
// layer cannot inherit them from when a callback happens to fire, so it has to carry them.
const FETCH_AT: u32 = 2;
const MEMORY_AT: u32 = 3;
const PORT_AT: u32 = 4;

#[cfg(test)]
#[derive(Clone, Copy, Default, Debug)]
pub(crate) struct Seen {
    pub base: [u64; 4],
    pub bits: [u64; 4],
    pub extended: [u64; 4],
    pub z80n: [u64; 4],
    pub indexed: [u64; 4],
    pub indexed_bits: [u64; 4],
}

#[cfg(test)]
fn mark(table: &mut [u64; 4], opcode: u8) {
    table[usize::from(opcode >> 6)] |= 1 << (opcode & 0x3F);
}

#[cfg(test)]
pub(crate) fn was_seen(table: &[u64; 4], opcode: u8) -> bool {
    table[usize::from(opcode >> 6)] & (1 << (opcode & 0x3F)) != 0
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Index {
    Ix,
    Iy,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Ran {
    Yes(u32),
    NotYet,
}

#[derive(Clone, Debug)]
pub(crate) struct Stepped {
    pub registers: Registers,
    pub undocumented_flags: UndocumentedFlags,
    // The cycle whose report is due when the next one opens, held here so this layer reproduces
    // the ordering `BusCycle` promises.
    pub(crate) pending: Option<(BusRequest, u32)>,
    pub(crate) bus_address: u16,
    index: Option<Index>,
    // The extended instructions assemble their operand over several cycles and it outlives the
    // instruction that assembled it, so a later report carries whatever the last one left.
    pub(crate) z80n_operand: u16,
    #[cfg(test)]
    pub seen: Seen,
    signals: u8,
}

mod signal {
    pub const HALTED: u8 = 1 << 0;
    pub const DISPLACED: u8 = 1 << 1;
    pub const INTERRUPT_REQUESTED: u8 = 1 << 2;
    pub const NMI_REQUESTED: u8 = 1 << 3;
    // `EI` enables interrupts but the next instruction still runs, so a handler entered from a
    // polling loop cannot pre-empt the `RET` that leaves it.
    pub const AFTER_EI: u8 = 1 << 4;
    pub const TAKE_NMI: u8 = 1 << 5;
    pub const TAKE_INTERRUPT: u8 = 1 << 6;
    pub const Z80N: u8 = 1 << 7;
}

impl Default for Stepped {
    fn default() -> Self {
        Self::new()
    }
}

impl Stepped {
    pub(crate) fn new() -> Self {
        Self {
            registers: Registers::default(),
            undocumented_flags: UndocumentedFlags::Combined,
            pending: None,
            bus_address: 0,
            index: None,
            z80n_operand: 0,
            signals: 0,
            #[cfg(test)]
            seen: Seen::default(),
        }
    }

    const fn on(&self, signal: u8) -> bool {
        self.signals & signal != 0
    }

    const fn set(&mut self, signal: u8, on: bool) {
        if on {
            self.signals |= signal;
        } else {
            self.signals &= !signal;
        }
    }

    pub(crate) const fn set_interrupt_requested(&mut self, requested: bool) {
        self.set(signal::INTERRUPT_REQUESTED, requested);
    }

    pub(crate) const fn is_halted(&self) -> bool {
        self.on(signal::HALTED)
    }

    pub(crate) const fn set_halted(&mut self, halted: bool) {
        self.set(signal::HALTED, halted);
    }

    pub(crate) const fn set_z80n_enabled(&mut self, enabled: bool) {
        self.set(signal::Z80N, enabled);
    }

    // These belong to the processor rather than to this layer, so they are handed over at each
    // boundary rather than kept here.
    pub(crate) const fn latches(&self) -> (bool, bool, bool) {
        (
            self.on(signal::AFTER_EI),
            self.on(signal::TAKE_NMI),
            self.on(signal::TAKE_INTERRUPT),
        )
    }

    pub(crate) const fn set_latches(&mut self, (after_ei, nmi, interrupt): (bool, bool, bool)) {
        self.set(signal::AFTER_EI, after_ei);
        self.set(signal::TAKE_NMI, nmi);
        self.set(signal::TAKE_INTERRUPT, interrupt);
    }

    pub(crate) const fn is_interrupt_requested(&self) -> bool {
        self.on(signal::INTERRUPT_REQUESTED)
    }

    pub(crate) const fn is_nmi_requested(&self) -> bool {
        self.on(signal::NMI_REQUESTED)
    }

    pub(crate) const fn set_nmi_requested(&mut self, requested: bool) {
        self.set(signal::NMI_REQUESTED, requested);
    }

    fn accumulator(&self) -> u8 {
        self.registers.af.to_be_bytes()[0]
    }

    fn set_accumulator(&mut self, value: u8) {
        self.registers.af = u16::from_be_bytes([value, self.flags()]);
    }

    fn flags(&self) -> u8 {
        self.registers.af.to_be_bytes()[1]
    }

    fn set_flags(&mut self, value: u8) {
        self.registers.af = u16::from_be_bytes([self.accumulator(), value]);
    }

    // `preserve_carry` is the increments' rule: they set every flag but leave the carry alone,
    // which the unit itself does not know — the sequencer puts the old carry back afterwards, and
    // so does this.
    fn alu(&mut self, op: AluOp, ir: u8, left: u8, right: u8, preserve_carry: bool) -> u8 {
        self.alu_in(
            alu::Inputs {
                op,
                ir,
                instruction_set: InstructionSet::Base,
                bus_a: left,
                bus_b: right,
                flags: 0,
                preserve_result_flags: false,
                combine_zero: false,
            },
            preserve_carry,
        )
    }

    fn alu_holding(
        &mut self,
        op: AluOp,
        ir: u8,
        left: u8,
        right: u8,
        preserve_carry: bool,
        holding: bool,
    ) -> u8 {
        self.alu_in(
            alu::Inputs {
                op,
                ir,
                instruction_set: InstructionSet::Base,
                bus_a: left,
                bus_b: right,
                flags: 0,
                preserve_result_flags: holding,
                combine_zero: false,
            },
            preserve_carry,
        )
    }

    // The unit distinguishes the accumulator rotates from the prefixed ones by the instruction
    // set: the accumulator forms leave the sign, zero and overflow flags alone and the prefixed
    // ones describe their result.
    fn alu_in(&mut self, inputs: alu::Inputs, preserve_carry: bool) -> u8 {
        let (result, produced) = alu::execute(alu::Inputs {
            flags: self.flags(),
            ir: inputs.ir & mask::ALU_OPCODE,
            ..inputs
        });
        let flags = if preserve_carry {
            (produced & !flag::C_MASK) | (self.flags() & flag::C_MASK)
        } else {
            produced
        };
        self.set_flags(flags);
        result
    }

    fn register(&self, code: u8) -> u8 {
        if code == 7 {
            return self.accumulator();
        }
        let [high, low] = match code {
            0 | 1 => self.registers.bc,
            2 | 3 => self.registers.de,
            _ => self.pair_for_hl(),
        }
        .to_be_bytes();
        if code & 1 == 0 { high } else { low }
    }

    fn pair_for_hl(&self) -> u16 {
        match self.index {
            Some(Index::Ix) if !self.on(signal::DISPLACED) => self.registers.ix,
            Some(Index::Iy) if !self.on(signal::DISPLACED) => self.registers.iy,
            _ => self.registers.hl,
        }
    }

    fn set_pair_for_hl(&mut self, value: u16) {
        *match self.index {
            Some(Index::Ix) if !self.on(signal::DISPLACED) => &mut self.registers.ix,
            Some(Index::Iy) if !self.on(signal::DISPLACED) => &mut self.registers.iy,
            _ => &mut self.registers.hl,
        } = value;
    }

    // The displacement is signed and is added to whichever register the prefix named. Marking the
    // operand displaced is what puts the register halves back to being H and L for the rest of the
    // instruction, so it has to happen before anything else reads them.
    fn displaced<H: Host>(&mut self, host: &mut H) -> (u16, u32) {
        let base = self.pair_for_hl();
        let (displacement, read) = self.immediate(host);
        self.set(signal::DISPLACED, true);
        let address = base.wrapping_add_signed(i16::from(displacement.cast_signed()));
        self.registers.wz = address;
        (address, read)
    }

    fn memory_operand<H: Host>(&mut self, host: &mut H, taken: &mut u32) -> u16 {
        if self.index.is_none() {
            return self.registers.hl;
        }
        let (address, read) = self.displaced(host);
        *taken += read + self.internal(host, 5);
        address
    }

    fn set_register(&mut self, code: u8, value: u8) {
        if code == 7 {
            self.set_accumulator(value);
            return;
        }
        if code == 4 || code == 5 {
            let [high, low] = self.pair_for_hl().to_be_bytes();
            let pair = if code == 4 {
                u16::from_be_bytes([value, low])
            } else {
                u16::from_be_bytes([high, value])
            };
            self.set_pair_for_hl(pair);
            return;
        }
        let pair = match code {
            0 | 1 => &mut self.registers.bc,
            _ => &mut self.registers.de,
        };
        let [high, low] = pair.to_be_bytes();
        *pair = if code & 1 == 0 {
            u16::from_be_bytes([value, low])
        } else {
            u16::from_be_bytes([high, value])
        };
    }

    fn open<H: Host>(&mut self, host: &mut H, request: BusRequest) -> u32 {
        if let Some((request, t_states)) = self.pending.take() {
            host.bus_cycle(&BusCycle { request, t_states });
        }
        host.wait_states(&request)
    }

    fn close(&mut self, request: BusRequest, t_states: u32) {
        self.pending = Some((request, t_states));
    }

    fn fetch<H: Host>(&mut self, host: &mut H) -> (u8, u32) {
        let address = self.registers.pc;
        let request = BusRequest::OpcodeFetch { address };
        let waits = self.open(host, request);
        let opcode = host.fetch(address, FETCH_AT + waits);
        self.registers.pc = self.registers.pc.wrapping_add(1);
        // The refresh half drives the vector base and the refresh counter, and leaves them there.
        self.refresh();
        let t_states = 4 + waits;
        self.close(request, t_states);
        (opcode, t_states)
    }

    fn read<H: Host>(&mut self, host: &mut H, address: u16) -> (u8, u32) {
        self.read_taking(host, address, 3)
    }

    fn read_taking<H: Host>(&mut self, host: &mut H, address: u16, base: u32) -> (u8, u32) {
        let request = BusRequest::MemoryRead { address };
        let waits = self.open(host, request);
        let value = host.read(address, MEMORY_AT + waits);
        self.bus_address = address;
        let t_states = base + waits;
        self.close(request, t_states);
        (value, t_states)
    }

    fn write<H: Host>(&mut self, host: &mut H, address: u16, value: u8) -> u32 {
        let request = BusRequest::MemoryWrite { address, value };
        let waits = self.open(host, request);
        host.write(address, value, MEMORY_AT + waits);
        self.bus_address = address;
        let t_states = 3 + waits;
        self.close(request, t_states);
        t_states
    }

    // It carries whatever was last driven onto it, which a machine that contends its memory
    // reads, so it is not free to be anything convenient. After a fetch that is the refresh
    // address; after a read it is the address read from. Modelling the bus rather than picking a
    // value per instruction is what makes both come out right.
    fn internal<H: Host>(&mut self, host: &mut H, t_states: u32) -> u32 {
        let request = BusRequest::Internal {
            address: self.bus_address,
        };
        let waits = self.open(host, request);
        let took = t_states + waits;
        self.close(request, took);
        took
    }

    // A few instructions do their work inside `M1` rather than in a cycle of their own, so the
    // fetch runs longer than four T-states and nothing else happens.
    fn lengthen_fetch(&mut self, extra: u32) {
        if let Some((request, t_states)) = self.pending.take() {
            self.pending = Some((request, t_states + extra));
        }
    }

    fn immediate<H: Host>(&mut self, host: &mut H) -> (u8, u32) {
        let address = self.registers.pc;
        let (value, t_states) = self.read(host, address);
        self.registers.pc = self.registers.pc.wrapping_add(1);
        (value, t_states)
    }

    fn pair(&self, code: u8) -> u16 {
        match code {
            0 => self.registers.bc,
            1 => self.registers.de,
            2 => self.pair_for_hl(),
            _ => self.registers.sp,
        }
    }

    fn set_pair(&mut self, code: u8, value: u16) {
        if code == 2 {
            self.set_pair_for_hl(value);
            return;
        }
        *match code {
            0 => &mut self.registers.bc,
            1 => &mut self.registers.de,
            _ => &mut self.registers.sp,
        } = value;
    }

    fn stacked(&self, code: u8) -> u16 {
        if code == 3 {
            self.registers.af
        } else {
            self.pair(code)
        }
    }

    fn set_stacked(&mut self, code: u8, value: u16) {
        if code == 3 {
            self.registers.af = value;
        } else {
            self.set_pair(code, value);
        }
    }

    fn push<H: Host>(&mut self, host: &mut H, value: u16) -> u32 {
        let [high, low] = value.to_be_bytes();
        self.registers.sp = self.registers.sp.wrapping_sub(1);
        let first = self.write(host, self.registers.sp, high);
        self.registers.sp = self.registers.sp.wrapping_sub(1);
        let second = self.write(host, self.registers.sp, low);
        first + second
    }

    fn pop<H: Host>(&mut self, host: &mut H) -> (u16, u32) {
        let (low, first) = self.read(host, self.registers.sp);
        self.registers.sp = self.registers.sp.wrapping_add(1);
        let (high, second) = self.read(host, self.registers.sp);
        self.registers.sp = self.registers.sp.wrapping_add(1);
        (u16::from_be_bytes([high, low]), first + second)
    }

    fn write_taking<H: Host>(&mut self, host: &mut H, address: u16, value: u8, base: u32) -> u32 {
        let request = BusRequest::MemoryWrite { address, value };
        let waits = self.open(host, request);
        host.write(address, value, MEMORY_AT + waits);
        self.bus_address = address;
        let t_states = base + waits;
        self.close(request, t_states);
        t_states
    }

    fn port_read<H: Host>(&mut self, host: &mut H, port: u16) -> (u8, u32) {
        self.port_read_taking(host, port, 4)
    }

    fn port_read_taking<H: Host>(&mut self, host: &mut H, port: u16, base: u32) -> (u8, u32) {
        let request = BusRequest::PortRead { port };
        let waits = self.open(host, request);
        let value = host.input(port, PORT_AT + waits);
        self.bus_address = port;
        let t_states = base + waits;
        self.close(request, t_states);
        (value, t_states)
    }

    fn port_write<H: Host>(&mut self, host: &mut H, port: u16, value: u8) -> u32 {
        let request = BusRequest::PortWrite { port, value };
        let waits = self.open(host, request);
        host.output(port, value, PORT_AT + waits);
        self.bus_address = port;
        let t_states = 4 + waits;
        self.close(request, t_states);
        t_states
    }

    fn immediate_taking<H: Host>(&mut self, host: &mut H, base: u32) -> (u8, u32) {
        let address = self.registers.pc;
        let (value, t_states) = self.read_taking(host, address, base);
        self.registers.pc = self.registers.pc.wrapping_add(1);
        (value, t_states)
    }

    fn immediate_word<H: Host>(&mut self, host: &mut H) -> (u16, u32) {
        let (low, first) = self.immediate(host);
        let (high, second) = self.immediate(host);
        (u16::from_be_bytes([high, low]), first + second)
    }

    // A step ends at a boundary, so the instruction's last cycle has nothing following it to
    // trigger its report. Flushing here means every cycle a step ran has been described by the
    // time it returns, without changing the order anything arrives in.
    fn flush<H: Host>(&mut self, host: &mut H) {
        if let Some((request, t_states)) = self.pending.take() {
            host.bus_cycle(&BusCycle { request, t_states });
        }
    }

    pub(crate) fn step<H: Host>(&mut self, host: &mut H) -> Ran {
        if self.on(signal::TAKE_NMI) {
            self.set(signal::TAKE_NMI, false);
            let taken = self.accept_nmi(host);
            self.flush(host);
            return Ran::Yes(taken);
        }
        if self.on(signal::TAKE_INTERRUPT) {
            self.set(signal::TAKE_INTERRUPT, false);
            let taken = self.accept_interrupt(host);
            self.flush(host);
            return Ran::Yes(taken);
        }
        if self.on(signal::HALTED) {
            let taken = self.halted_fetch(host);
            self.sample();
            self.flush(host);
            return Ran::Yes(taken);
        }
        let (opcode, mut taken) = self.fetch(host);
        if self.execute(host, opcode, &mut taken) {
            self.sample();
            self.flush(host);
            Ran::Yes(taken)
        } else {
            Ran::NotYet
        }
    }

    // Both lines are read at the end of an instruction, never at the start of one, so the sequence
    // that follows belongs to the instruction that has just finished. A prefix and what it prefixes
    // run inside a single step, so there is no boundary between them for either line to land on.
    fn sample(&mut self) {
        if self.on(signal::NMI_REQUESTED) {
            self.set(signal::NMI_REQUESTED, false);
            self.registers.iff1 = false;
            self.set(signal::TAKE_NMI, true);
        } else if self.registers.iff1
            && self.on(signal::INTERRUPT_REQUESTED)
            && !self.on(signal::AFTER_EI)
        {
            self.registers.iff1 = false;
            self.registers.iff2 = false;
            self.set(signal::TAKE_INTERRUPT, true);
        }
        self.set(signal::AFTER_EI, false);
    }

    // Halted, the machine keeps fetching from where it stopped and executing nothing. The program
    // counter is left one past the `HALT`, which is also the address an interrupt has to return to.
    fn halted_fetch<H: Host>(&mut self, host: &mut H) -> u32 {
        let address = self.registers.pc;
        let request = BusRequest::OpcodeFetch { address };
        let waits = self.open(host, request);
        host.fetch(address, FETCH_AT + waits);
        self.refresh();
        let t_states = 4 + waits;
        self.close(request, t_states);
        t_states
    }

    fn refresh(&mut self) {
        self.registers.r = (self.registers.r & 0x80) | (self.registers.r.wrapping_add(1) & 0x7F);
        self.bus_address = u16::from_be_bytes([self.registers.i, self.registers.r]);
    }

    fn accept_nmi<H: Host>(&mut self, host: &mut H) -> u32 {
        self.set(signal::HALTED, false);
        let address = self.registers.pc;
        let request = BusRequest::OpcodeFetch { address };
        let waits = self.open(host, request);
        host.fetch(address, FETCH_AT + waits);
        self.refresh();
        let mut taken = 5 + waits;
        self.close(request, taken);
        let announced = self.on(signal::Z80N);
        let [high, low] = address.to_be_bytes();
        if announced {
            self.report_z80n(host, Z80nCommand::NmiAcknowledgeHigh);
        }
        self.registers.sp = self.registers.sp.wrapping_sub(1);
        taken += self.write(host, self.registers.sp, high);
        if announced {
            self.report_z80n(host, Z80nCommand::NmiAcknowledgeLow);
        }
        self.registers.sp = self.registers.sp.wrapping_sub(1);
        taken += self.write(host, self.registers.sp, low);
        self.registers.pc = 0x0066;
        taken
    }

    // The acknowledge is a fetch the interrupting device answers instead of memory, and it carries
    // two wait states of its own on top of anything the host asks for.
    fn acknowledge<H: Host>(&mut self, host: &mut H) -> (u8, u32) {
        let address = self.registers.pc;
        let request = BusRequest::InterruptAcknowledge { address };
        let waits = self.open(host, request);
        let vector = host.interrupt_vector();
        self.refresh();
        let t_states = 6 + waits;
        self.close(request, t_states);
        (vector, t_states)
    }

    fn accept_interrupt<H: Host>(&mut self, host: &mut H) -> u32 {
        self.set(signal::HALTED, false);
        let (vector, mut taken) = self.acknowledge(host);
        match self.registers.interrupt_mode {
            InterruptMode::Mode0 => {
                self.execute(host, vector, &mut taken);
            }
            InterruptMode::Mode1 => {
                self.execute(host, 0xFF, &mut taken);
            }
            InterruptMode::Mode2 => {
                self.lengthen_fetch(1);
                taken += 1 + self.push(host, self.registers.pc);
                let table = u16::from_be_bytes([self.registers.i, vector]);
                let (low, first) = self.read(host, table);
                let (high, second) = self.read(host, table.wrapping_add(1));
                taken += first + second;
                self.registers.pc = u16::from_be_bytes([high, low]);
                self.registers.wz = self.registers.pc;
            }
        }
        taken
    }

    #[allow(
        clippy::too_many_lines,
        reason = "a dispatch table; splitting it once to halve it measured 0.8% slower and would \
                  still be over the threshold"
    )]
    fn execute<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) -> bool {
        #[cfg(test)]
        if self.index.is_some() {
            mark(&mut self.seen.indexed, opcode);
        } else {
            mark(&mut self.seen.base, opcode);
        }
        match opcode {
            0x76 => {
                self.set(signal::HALTED, true);
                true
            }
            0xF3 => {
                self.registers.iff1 = false;
                self.registers.iff2 = false;
                true
            }
            0xFB => {
                self.registers.iff1 = true;
                self.registers.iff2 = true;
                self.set(signal::AFTER_EI, true);
                true
            }
            0x40..=0x7F if opcode & 0x07 != 6 && (opcode >> 3) & 0x07 != 6 => {
                let value = self.register(opcode & 0x07);
                self.set_register((opcode >> 3) & 0x07, value);
                true
            }
            0x46 | 0x4E | 0x56 | 0x5E | 0x66 | 0x6E | 0x7E => {
                let address = self.memory_operand(host, taken);
                let (value, t) = self.read(host, address);
                *taken += t;
                self.set_register((opcode >> 3) & 0x07, value);
                true
            }
            0x70..=0x75 | 0x77 => {
                let address = self.memory_operand(host, taken);
                let value = self.register(opcode & 0x07);
                *taken += self.write(host, address, value);
                true
            }
            0x06 | 0x0E | 0x16 | 0x1E | 0x26 | 0x2E | 0x3E => {
                let (value, t) = self.immediate(host);
                *taken += t;
                self.set_register((opcode >> 3) & 0x07, value);
                true
            }
            0x36 => {
                // Behind an index prefix the byte to store is read *after* the displacement, and
                // that read is where the addition happens, so it runs for five T-states rather
                // than an internal cycle of its own.
                if self.index.is_some() {
                    let (address, first) = self.displaced(host);
                    let (value, second) = self.immediate_taking(host, 5);
                    let third = self.write(host, address, value);
                    *taken += first + second + third;
                } else {
                    let (value, first) = self.immediate(host);
                    let second = self.write(host, self.registers.hl, value);
                    *taken += first + second;
                }
                true
            }
            0x0A | 0x1A => {
                let address = if opcode == 0x0A {
                    self.registers.bc
                } else {
                    self.registers.de
                };
                let (value, t) = self.read(host, address);
                *taken += t;
                self.set_accumulator(value);
                self.registers.wz = address.wrapping_add(1);
                true
            }
            0x02 | 0x12 => {
                let address = if opcode == 0x02 {
                    self.registers.bc
                } else {
                    self.registers.de
                };
                let value = self.accumulator();
                *taken += self.write(host, address, value);
                self.registers.wz =
                    u16::from_be_bytes([value, address.wrapping_add(1).to_be_bytes()[1]]);
                true
            }
            0x3A => {
                let (address, first) = self.immediate_word(host);
                let (value, second) = self.read(host, address);
                *taken += first + second;
                self.set_accumulator(value);
                self.registers.wz = address.wrapping_add(1);
                true
            }
            0x32 => {
                let (address, first) = self.immediate_word(host);
                let value = self.accumulator();
                let second = self.write(host, address, value);
                *taken += first + second;
                self.registers.wz =
                    u16::from_be_bytes([value, address.wrapping_add(1).to_be_bytes()[1]]);
                true
            }
            0x80..=0xBF if opcode & 0x07 != 6 => {
                let right = self.register(opcode & 0x07);
                self.arithmetic(opcode, right);
                true
            }
            0x86 | 0x8E | 0x96 | 0x9E | 0xA6 | 0xAE | 0xB6 | 0xBE => {
                let address = self.memory_operand(host, taken);
                let (right, t) = self.read(host, address);
                *taken += t;
                self.arithmetic(opcode, right);
                true
            }
            0xC6 | 0xCE | 0xD6 | 0xDE | 0xE6 | 0xEE | 0xF6 | 0xFE => {
                let (right, t) = self.immediate(host);
                *taken += t;
                self.arithmetic(opcode, right);
                true
            }
            0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x3C | 0x05 | 0x0D | 0x15 | 0x1D | 0x25
            | 0x2D | 0x3D => {
                let code = (opcode >> 3) & 0x07;
                let op = if opcode & 1 == 0 {
                    AluOp::Add
                } else {
                    AluOp::Sub
                };
                let value = self.alu(op, opcode, self.register(code), 1, true);
                self.set_register(code, value);
                true
            }
            0x34 | 0x35 => {
                let address = self.memory_operand(host, taken);
                let (value, first) = self.read_taking(host, address, 4);
                let op = if opcode == 0x34 {
                    AluOp::Add
                } else {
                    AluOp::Sub
                };
                let result = self.alu(op, opcode, value, 1, true);
                let second = self.write(host, address, result);
                *taken += first + second;
                true
            }
            0x01 | 0x11 | 0x21 | 0x31 => {
                let (value, t) = self.immediate_word(host);
                *taken += t;
                self.set_pair((opcode >> 4) & 0x03, value);
                true
            }
            0x03 | 0x13 | 0x23 | 0x33 | 0x0B | 0x1B | 0x2B | 0x3B => {
                let code = (opcode >> 4) & 0x03;
                let value = self.pair(code);
                self.set_pair(
                    code,
                    if opcode & 0x08 == 0 {
                        value.wrapping_add(1)
                    } else {
                        value.wrapping_sub(1)
                    },
                );
                *taken += 2;
                self.lengthen_fetch(2);
                true
            }
            0xF9 => {
                self.registers.sp = self.pair_for_hl();
                *taken += 2;
                self.lengthen_fetch(2);
                true
            }
            0xC5 | 0xD5 | 0xE5 | 0xF5 => {
                let value = self.stacked((opcode >> 4) & 0x03);
                *taken += 1;
                self.lengthen_fetch(1);
                *taken += self.push(host, value);
                true
            }
            0xC1 | 0xD1 | 0xE1 | 0xF1 => {
                let (value, t) = self.pop(host);
                *taken += t;
                self.set_stacked((opcode >> 4) & 0x03, value);
                true
            }
            0x2A => {
                let (address, first) = self.immediate_word(host);
                let (low, second) = self.read(host, address);
                self.registers.wz = address.wrapping_add(1);
                let (high, third) = self.read(host, self.registers.wz);
                *taken += first + second + third;
                self.set_pair_for_hl(u16::from_be_bytes([high, low]));
                true
            }
            0x22 => {
                let (address, first) = self.immediate_word(host);
                let [high, low] = self.pair_for_hl().to_be_bytes();
                let second = self.write(host, address, low);
                self.registers.wz = address.wrapping_add(1);
                let third = self.write(host, self.registers.wz, high);
                *taken += first + second + third;
                true
            }
            0xE3 => {
                let sp = self.registers.sp;
                let (low, first) = self.read(host, sp);
                let (high, second) = self.read_taking(host, sp.wrapping_add(1), 4);
                let [held_high, held_low] = self.pair_for_hl().to_be_bytes();
                let third = self.write(host, sp.wrapping_add(1), held_high);
                let fourth = self.write_taking(host, sp, held_low, 5);
                *taken += first + second + third + fourth;
                let swapped = u16::from_be_bytes([high, low]);
                self.set_pair_for_hl(swapped);
                self.registers.wz = swapped;
                true
            }
            0xEB => {
                core::mem::swap(&mut self.registers.de, &mut self.registers.hl);
                true
            }
            0x08 => {
                core::mem::swap(&mut self.registers.af, &mut self.registers.af_alt);
                true
            }
            0xD9 => {
                core::mem::swap(&mut self.registers.bc, &mut self.registers.bc_alt);
                core::mem::swap(&mut self.registers.de, &mut self.registers.de_alt);
                core::mem::swap(&mut self.registers.hl, &mut self.registers.hl_alt);
                true
            }
            0x09 | 0x19 | 0x29 | 0x39 => {
                let [high, low] = self.pair((opcode >> 4) & 0x03).to_be_bytes();
                let [left_high, left_low] = self.pair_for_hl().to_be_bytes();
                let result_low = self.alu_holding(AluOp::Add, opcode, left_low, low, false, true);
                let result_high =
                    self.alu_holding(AluOp::Adc, opcode, left_high, high, false, true);
                self.registers.wz = self.pair_for_hl().wrapping_add(1);
                self.set_pair_for_hl(u16::from_be_bytes([result_high, result_low]));
                *taken += self.internal(host, 4) + self.internal(host, 3);
                true
            }
            0x07 | 0x0F | 0x17 | 0x1F => {
                let value = self.accumulator();
                let result = self.alu(AluOp::Rotate, opcode, value, value, false);
                self.set_accumulator(result);
                true
            }
            0xDD | 0xFD => {
                self.index = Some(if opcode == 0xDD { Index::Ix } else { Index::Iy });
                self.set(signal::DISPLACED, false);
                let (next, t) = self.fetch(host);
                *taken += t;
                let ran = if next == 0xCB {
                    self.indexed_bit(host, taken);
                    true
                } else {
                    self.execute(host, next, taken)
                };
                self.index = None;
                self.set(signal::DISPLACED, false);
                ran
            }
            0xDB => {
                let (low, first) = self.immediate(host);
                let port = u16::from_be_bytes([self.accumulator(), low]);
                let (value, second) = self.port_read(host, port);
                *taken += first + second;
                self.set_accumulator(value);
                self.registers.wz = port.wrapping_add(1);
                true
            }
            0xD3 => {
                let (low, first) = self.immediate(host);
                let accumulator = self.accumulator();
                let port = u16::from_be_bytes([accumulator, low]);
                *taken += first + self.port_write(host, port, accumulator);
                self.registers.wz = u16::from_be_bytes([accumulator, low.wrapping_add(1)]);
                true
            }
            0xCB => {
                let (prefixed, t) = self.fetch(host);
                *taken += t;
                self.prefixed(host, prefixed, taken);
                true
            }
            0x27 => {
                let value = self.accumulator();
                let result = self.alu(AluOp::Daa, opcode, value, value, false);
                self.set_accumulator(result);
                true
            }
            0x2F | 0x37 | 0x3F => {
                self.accumulator_flags(opcode);
                true
            }
            0xC3 | 0xC2 | 0xCA | 0xD2 | 0xDA | 0xE2 | 0xEA | 0xF2 | 0xFA => {
                let (target, t) = self.immediate_word(host);
                *taken += t;
                self.registers.wz = target;
                if opcode == 0xC3 || self.condition((opcode >> 3) & 0x07) {
                    self.registers.pc = target;
                }
                true
            }
            0xE9 => {
                self.registers.pc = self.pair_for_hl();
                true
            }
            0x18 | 0x20 | 0x28 | 0x30 | 0x38 => {
                let (displacement, t) = self.immediate(host);
                *taken += t;
                let jump = opcode == 0x18 || self.condition((opcode >> 3) & mask::CONDITION);
                if jump {
                    *taken += self.jump_relative(host, displacement);
                }
                true
            }
            0x10 => {
                *taken += 1;
                self.lengthen_fetch(1);
                let counter = self.register(0).wrapping_sub(1);
                self.set_register(0, counter);
                let (displacement, t) = self.immediate(host);
                *taken += t;
                if counter != 0 {
                    *taken += self.jump_relative(host, displacement);
                }
                true
            }
            // The second half of the address is read for four T-states when the call is taken and
            // three when it is not: the extra one is where the stack pointer is stepped down.
            0xCD | 0xC4 | 0xCC | 0xD4 | 0xDC | 0xE4 | 0xEC | 0xF4 | 0xFC => {
                let (low, first) = self.immediate(host);
                let calling = opcode == 0xCD || self.condition((opcode >> 3) & 0x07);
                let (high, second) = self.immediate_taking(host, if calling { 4 } else { 3 });
                *taken += first + second;
                let target = u16::from_be_bytes([high, low]);
                self.registers.wz = target;
                if calling {
                    *taken += self.push(host, self.registers.pc);
                    self.registers.pc = target;
                }
                true
            }
            0xC9 => {
                let (target, t) = self.pop(host);
                *taken += t;
                self.registers.wz = target;
                self.registers.pc = target;
                true
            }
            0xC0 | 0xC8 | 0xD0 | 0xD8 | 0xE0 | 0xE8 | 0xF0 | 0xF8 => {
                *taken += 1;
                self.lengthen_fetch(1);
                if self.condition((opcode >> 3) & 0x07) {
                    let (target, t) = self.pop(host);
                    *taken += t;
                    self.registers.wz = target;
                    self.registers.pc = target;
                }
                true
            }
            0xC7 | 0xCF | 0xD7 | 0xDF | 0xE7 | 0xEF | 0xF7 | 0xFF => {
                *taken += 1;
                self.lengthen_fetch(1);
                *taken += self.push(host, self.registers.pc);
                let target = u16::from(opcode & mask::RESTART_TARGET);
                self.registers.wz = target;
                self.registers.pc = target;
                true
            }
            0xED => {
                let (next, t) = self.fetch(host);
                *taken += t;
                self.extended(host, next, taken)
            }
            0x00 => true,
            _ => false,
        }
    }
}

impl Stepped {
    fn extended<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) -> bool {
        #[cfg(test)]
        mark(&mut self.seen.extended, opcode);
        if self.on(signal::Z80N) && self.z80n(host, opcode, taken) {
            #[cfg(test)]
            mark(&mut self.seen.z80n, opcode);
            return true;
        }
        match opcode {
            0xA0 | 0xA8 | 0xB0 | 0xB8 => {
                self.block_transfer(host, opcode, taken);
                true
            }
            0xA1 | 0xA9 | 0xB1 | 0xB9 => {
                self.block_compare(host, opcode, taken);
                true
            }
            0xA2 | 0xAA | 0xB2 | 0xBA | 0xA3 | 0xAB | 0xB3 | 0xBB => {
                self.port_block(host, opcode, taken);
                true
            }
            _ => self.extended_regular(host, opcode, taken),
        }
    }

    fn extended_regular<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) -> bool {
        match opcode {
            0x57 | 0x5F | 0x47 | 0x4F => {
                self.interrupt_register(opcode, taken);
                true
            }
            0x4B | 0x5B | 0x6B | 0x7B => {
                self.wide_load(host, opcode, taken);
                true
            }
            0x43 | 0x53 | 0x63 | 0x73 => {
                self.wide_store(host, opcode, taken);
                true
            }
            0x46 | 0x4E | 0x66 | 0x6E => {
                self.registers.interrupt_mode = InterruptMode::Mode0;
                true
            }
            0x56 | 0x76 => {
                self.registers.interrupt_mode = InterruptMode::Mode1;
                true
            }
            0x5E | 0x7E => {
                self.registers.interrupt_mode = InterruptMode::Mode2;
                true
            }
            0x4A | 0x5A | 0x6A | 0x7A | 0x42 | 0x52 | 0x62 | 0x72 => {
                self.wide_arithmetic(host, opcode, taken);
                true
            }
            0x44 | 0x4C | 0x54 | 0x5C | 0x64 | 0x6C | 0x74 | 0x7C => {
                let value = self.accumulator();
                let result = self.alu(AluOp::Sub, opcode, 0, value, false);
                self.set_accumulator(result);
                true
            }
            0x6F | 0x67 => {
                self.nibble_rotate(host, opcode, taken);
                true
            }
            0x4D | 0x45 | 0x55 | 0x5D | 0x65 | 0x6D | 0x75 | 0x7D => {
                // A machine that keeps the return address somewhere other than the stack watches
                // for these and answers the two reads itself, so each is announced before it runs.
                let announced = self.on(signal::Z80N) && opcode != 0x4D;
                if announced {
                    self.report_z80n(host, Z80nCommand::ReturnFromNmiLow);
                }
                let (low, first) = self.read(host, self.registers.sp);
                self.registers.sp = self.registers.sp.wrapping_add(1);
                if announced {
                    self.report_z80n(host, Z80nCommand::ReturnFromNmiHigh);
                }
                let (high, second) = self.read(host, self.registers.sp);
                self.registers.sp = self.registers.sp.wrapping_add(1);
                let target = u16::from_be_bytes([high, low]);
                *taken += first + second;
                self.registers.wz = target;
                self.registers.pc = target;
                self.registers.iff1 = self.registers.iff2;
                if opcode == 0x4D {
                    host.return_from_interrupt();
                }
                true
            }
            0x40 | 0x48 | 0x50 | 0x58 | 0x60 | 0x68 | 0x70 | 0x78 => {
                self.port_in(host, opcode, taken);
                true
            }
            0x41 | 0x49 | 0x51 | 0x59 | 0x61 | 0x69 | 0x71 | 0x79 => {
                self.port_out(host, opcode, taken);
                true
            }
            // Everything else in the extended page is a two-fetch no-operation.
            _ => true,
        }
    }

    fn report_z80n<H: Host>(&mut self, host: &mut H, command: Z80nCommand) {
        host.z80n_command(command, self.z80n_operand);
    }

    // The report leaves at the end of the first cycle whose decode carries it, which for most of
    // these is the fetch that has just happened.
    fn z80n<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) -> bool {
        match opcode {
            0x23 => {
                let swapped = extended::swap_nibbles(self.accumulator());
                self.set_accumulator(swapped);
                self.report_z80n(host, Z80nCommand::SwapNibbleA);
            }
            0x24 => {
                let mirrored = extended::mirror(self.accumulator());
                self.set_accumulator(mirrored);
                self.report_z80n(host, Z80nCommand::MirrorA);
            }
            0x30 => {
                self.registers.de = extended::multiply(self.registers.de);
                self.report_z80n(host, Z80nCommand::MulDe);
            }
            0x31..=0x33 => {
                let (command, code) = match opcode {
                    0x31 => (Z80nCommand::AddHlA, 2),
                    0x32 => (Z80nCommand::AddDeA, 1),
                    _ => (Z80nCommand::AddBcA, 0),
                };
                let sum = extended::add_accumulator(self.pair(code), self.accumulator());
                self.set_pair(code, sum);
                self.set_flags(self.flags() & !flag::C_MASK);
                self.report_z80n(host, command);
            }
            0x93 => {
                self.registers.hl = extended::pixel_down(self.registers.hl);
                self.report_z80n(host, Z80nCommand::PixelDown);
            }
            0x94 => {
                self.registers.hl = extended::pixel_address(self.registers.de);
                self.report_z80n(host, Z80nCommand::PixelAddress);
            }
            0x95 => {
                let selected = extended::bit_from_low_three(self.registers.de.to_be_bytes()[1]);
                self.set_accumulator(selected);
                self.report_z80n(host, Z80nCommand::SetAE);
            }
            0x28..=0x2C => {
                let (command, kind) = match opcode {
                    0x28 => (Z80nCommand::BslaDeB, Barrel::Left),
                    0x29 => (Z80nCommand::BsraDeB, Barrel::ArithmeticRight),
                    0x2A => (Z80nCommand::BsrlDeB, Barrel::LogicalRight),
                    0x2B => (Z80nCommand::BsrfDeB, Barrel::FillRight),
                    _ => (Z80nCommand::BrlcDeB, Barrel::Rotate),
                };
                let count = self.registers.bc.to_be_bytes()[0];
                self.registers.de = extended::barrel(self.registers.de, count, kind);
                self.report_z80n(host, command);
            }
            _ => return self.z80n_operands(host, opcode, taken),
        }
        true
    }

    // Both forms announce the assembled word part way through, then spend a cycle re-reading an
    // operand they have already had.
    fn write_extended_register<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let (register, first) = if opcode == 0x91 {
            self.immediate(host)
        } else {
            self.read(host, self.registers.pc)
        };
        let (value, second) = if opcode == 0x91 {
            self.read(host, self.registers.pc)
        } else {
            (self.accumulator(), 0)
        };
        self.z80n_operand = u16::from_be_bytes([register, value]);
        let (_, third) = self.read(host, self.registers.pc);
        self.report_z80n(host, Z80nCommand::NextRegWrite);
        let (_, fourth) = self.immediate(host);
        *taken += first + second + third + fourth;
    }

    fn z80n_operands<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) -> bool {
        match opcode {
            0x27 => {
                let (value, t) = self.immediate(host);
                *taken += t;
                let left = self.accumulator();
                self.alu(AluOp::And, opcode, left, value, false);
            }
            0x34..=0x36 => {
                let (command, code) = match opcode {
                    0x34 => (Z80nCommand::AddHlImmediate, 2),
                    0x35 => (Z80nCommand::AddDeImmediate, 1),
                    _ => (Z80nCommand::AddBcImmediate, 0),
                };
                self.report_z80n(host, command);
                let (low, first) = self.immediate_taking(host, 4);
                let (high, second) = self.immediate_taking(host, 4);
                *taken += first + second;
                let sum = extended::add_immediate(self.pair(code), u16::from_be_bytes([high, low]));
                self.set_pair(code, sum);
            }
            0x8A => {
                let (high, first) = self.immediate(host);
                self.registers.sp = self.registers.sp.wrapping_sub(1);
                let second = self.write(host, self.registers.sp, high);
                let (low, third) = self.read(host, self.registers.pc);
                self.registers.sp = self.registers.sp.wrapping_sub(1);
                let fourth = self.write(host, self.registers.sp, low);
                let (_, fifth) = self.immediate(host);
                *taken += first + second + third + fourth + fifth;
            }
            0x90 => {
                self.lengthen_fetch(1);
                let (value, first) = self.read(host, self.registers.hl);
                self.registers.hl = self.registers.hl.wrapping_add(1);
                *taken += 1 + first + self.port_write(host, self.registers.bc, value);
            }
            0x91 | 0x92 => self.write_extended_register(host, opcode, taken),
            0x98 => {
                self.report_z80n(host, Z80nCommand::JpC);
                // A T-state longer than every other port cycle, because the decode asks for four
                // before the automatic wait rather than three.
                let (value, t) = self.port_read_taking(host, self.registers.bc, 5);
                *taken += t;
                let target = (u16::from(value) << mask::JUMP_SHIFT) & mask::JUMP_TARGET;
                self.registers.pc = (self.registers.pc & mask::JUMP_REGION) | target;
            }
            0xA4 | 0xB4 | 0xAC | 0xBC => {
                let up = opcode & 0x08 == 0;
                let (value, first) = self.read(host, self.registers.hl);
                *taken += first;
                let step = if up { 1 } else { 1u16.wrapping_neg() };
                self.registers.hl = self.registers.hl.wrapping_add(step);
                self.copy_out(host, value, false, taken);
                self.repeat_block(host, opcode, taken, !up);
            }
            0xA5 => {
                let (value, first) = self.read(host, self.registers.hl);
                let second = self.write(host, self.registers.de, value);
                *taken += first + second;
                let [high, low] = self.registers.hl.to_be_bytes();
                let stepped = self.alu(AluOp::Add, opcode, low, 1, false);
                self.registers.hl = u16::from_be_bytes([high, stepped]);
                let [high, low] = self.registers.de.to_be_bytes();
                let stepped = self.alu(AluOp::Add, opcode, high, 1, false);
                self.registers.de = u16::from_be_bytes([stepped, low]);
            }
            0xB6 => {
                self.report_z80n(host, Z80nCommand::LdirScale);
                let (value, first) = self.read(host, self.registers.hl);
                *taken += first;
                self.registers.hl = self.registers.hl.wrapping_add(1);
                self.copy_out(host, value, false, taken);
                self.repeat_block(host, opcode, taken, true);
            }
            0xB7 => {
                self.report_z80n(host, Z80nCommand::LdPirx);
                let pattern = (self.registers.hl & mask::PATTERN_BASE)
                    | (self.registers.de & mask::PATTERN_OFFSET);
                let (value, first) = self.read(host, pattern);
                *taken += first;
                self.copy_out(host, value, true, taken);
                self.repeat_block(host, opcode, taken, true);
            }
            _ => return false,
        }
        true
    }

    // The two undocumented flags come from an operation the copies name and the pattern form does
    // not: the copies ask for the accumulator plus the byte, the pattern form leaves both inputs at
    // their defaults and so gets `B` or'd with the byte, with `B` already counted down.
    fn copy_out<H: Host>(&mut self, host: &mut H, value: u8, from_pattern: bool, taken: &mut u32) {
        // Skipping the write does not skip the cycle: it stays the same length and reads the
        // destination instead, which a machine that contends its memory is charged for.
        *taken += if self.accumulator() == value {
            self.read_taking(host, self.registers.de, 5).1
        } else {
            self.write_taking(host, self.registers.de, value, 5)
        };
        self.registers.de = self.registers.de.wrapping_add(1);
        self.registers.bc = self.registers.bc.wrapping_sub(1);

        let reported = if from_pattern {
            self.registers.bc.to_be_bytes()[0] | value
        } else {
            self.accumulator().wrapping_add(value)
        };
        self.report_block(
            reported,
            flag::XY_MASK | flag::H_MASK | flag::N_MASK | flag::P_MASK,
        );
    }

    // The repeating forms hold the address bus over their last cycle. Two of them leave the program
    // counter on it where the plain block copies leave the destination, which a machine that
    // contends its memory can tell apart.
    fn repeat_block<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32, on_pc: bool) {
        if opcode & 0x10 == 0 || self.registers.bc == 0 {
            return;
        }
        if on_pc {
            self.bus_address = self.registers.pc;
        }
        *taken += self.internal(host, 5);
        self.registers.pc = self.registers.pc.wrapping_sub(2);
    }

    // The interrupt and refresh registers reach no bus, so the whole instruction is one longer
    // fetch. Copying one into the accumulator is the only way the second enable flip-flop becomes
    // observable, which is what puts it in the parity flag.
    fn interrupt_register(&mut self, opcode: u8, taken: &mut u32) {
        *taken += 1;
        self.lengthen_fetch(1);
        match opcode {
            0x47 => self.registers.i = self.accumulator(),
            0x4F => self.registers.r = self.accumulator(),
            _ => {
                let value = if opcode == 0x57 {
                    self.registers.i
                } else {
                    self.registers.r
                };
                self.set_accumulator(value);
                self.report_byte(value, self.registers.iff2);
            }
        }
    }

    fn wide_load<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let (address, first) = self.immediate_word(host);
        let (low, second) = self.read(host, address);
        self.registers.wz = address.wrapping_add(1);
        let (high, third) = self.read(host, self.registers.wz);
        *taken += first + second + third;
        self.set_pair((opcode >> 4) & 0x03, u16::from_be_bytes([high, low]));
    }

    fn wide_store<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let (address, first) = self.immediate_word(host);
        let [high, low] = self.pair((opcode >> 4) & 0x03).to_be_bytes();
        let second = self.write(host, address, low);
        self.registers.wz = address.wrapping_add(1);
        let third = self.write(host, self.registers.wz, high);
        *taken += first + second + third;
    }

    // Two eight-bit passes, low half first, so the carry chains between them.
    fn wide_arithmetic<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let op = if opcode & 0x08 == 0 {
            AluOp::Sbc
        } else {
            AluOp::Adc
        };
        let [high, low] = self.pair((opcode >> 4) & 0x03).to_be_bytes();
        let [left_high, left_low] = self.registers.hl.to_be_bytes();
        let result_low = self.alu_in(
            alu::Inputs {
                op,
                ir: opcode,
                instruction_set: InstructionSet::Ed,
                bus_a: left_low,
                bus_b: low,
                flags: 0,
                preserve_result_flags: false,
                combine_zero: false,
            },
            false,
        );
        let result_high = self.alu_zeroing(op, opcode, left_high, high);
        self.registers.wz = self.registers.hl.wrapping_add(1);
        self.registers.hl = u16::from_be_bytes([result_high, result_low]);
        *taken += self.internal(host, 4) + self.internal(host, 3);
    }

    fn nibble_rotate<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let address = self.registers.hl;
        let (value, first) = self.read(host, address);
        let accumulator = self.accumulator();
        let (kept, stored) = if opcode == 0x6F {
            (
                (accumulator & 0xF0) | (value >> 4),
                (value << 4) | (accumulator & 0x0F),
            )
        } else {
            (
                (accumulator & 0xF0) | (value & 0x0F),
                (accumulator << 4) | (value >> 4),
            )
        };
        self.set_accumulator(kept);
        self.report_value(kept);
        self.registers.wz = address.wrapping_add(1);
        *taken += first + self.internal(host, 4) + self.write(host, address, stored);
    }

    // The register code that names (HL) everywhere else has no register here: reading keeps only
    // the flags, and writing puts out zero.
    fn port_in<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let port = self.registers.bc;
        let (value, t) = self.port_read(host, port);
        *taken += t;
        self.registers.wz = port.wrapping_add(1);
        let code = (opcode >> 3) & 0x07;
        if code != 6 {
            self.set_register(code, value);
        }
        self.report_value(value);
    }

    fn port_out<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let port = self.registers.bc;
        let code = (opcode >> 3) & 0x07;
        let value = if code == 6 { 0 } else { self.register(code) };
        *taken += self.port_write(host, port, value);
        self.registers.wz = port.wrapping_add(1);
    }

    // The counter comes down whether the instruction repeats or not; what repeating adds is a
    // fifth cycle and a program counter that goes back two, so the same instruction is fetched
    // again. That is why a repeated block copy shows two fetches per iteration rather than one.
    fn block_transfer<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let up = opcode & 0x08 == 0;
        let (value, first) = self.read(host, self.registers.hl);
        let second = self.write_taking(host, self.registers.de, value, 5);
        *taken += first + second;

        let step = if up { 1u16.wrapping_neg() } else { 1 };
        self.registers.hl = self.registers.hl.wrapping_sub(step);
        self.registers.de = self.registers.de.wrapping_sub(step);
        self.registers.bc = self.registers.bc.wrapping_sub(1);

        // The byte the undocumented flags are taken from is the accumulator plus the one moved.
        let reported = self.accumulator().wrapping_add(value);
        self.report_block(
            reported,
            flag::XY_MASK | flag::H_MASK | flag::N_MASK | flag::P_MASK,
        );

        let repeating = opcode & 0x10 != 0;
        if repeating && self.registers.bc != 0 {
            *taken += self.internal(host, 5);
            self.registers.pc = self.registers.pc.wrapping_sub(2);
            self.registers.wz = self.registers.pc.wrapping_add(1);
        }
    }

    // Two things are only true behind both prefixes. The opcode is read as an ordinary memory access
    // rather than a fetch — it is the fourth byte of the instruction, and the processor has
    // already committed to what it is doing — and that read is where the displacement is added, so
    // it runs for five T-states. And the result is written back to a register as well as to
    // memory, unless the code names `(HL)`, which is undocumented but is what the part does.
    fn indexed_bit<H: Host>(&mut self, host: &mut H, taken: &mut u32) {
        let (address, first) = self.displaced(host);
        let (opcode, second) = self.immediate_taking(host, 5);
        #[cfg(test)]
        mark(&mut self.seen.indexed_bits, opcode);
        let (value, third) = self.read_taking(host, address, 4);
        *taken += first + second + third;

        let op = match opcode {
            0x00..=0x3F => AluOp::Rotate,
            0x40..=0x7F => AluOp::Bit,
            0x80..=0xBF => AluOp::Res,
            _ => AluOp::Set,
        };
        let result = self.alu_in(
            alu::Inputs {
                op,
                ir: opcode,
                instruction_set: InstructionSet::Cb,
                bus_a: value,
                bus_b: value,
                flags: 0,
                preserve_result_flags: false,
                combine_zero: false,
            },
            false,
        );

        if matches!(op, AluOp::Bit) {
            // Behind a displacement every test takes its two undocumented flags from the address
            // latch, not only the ones whose code names `(HL)`.
            let flags = self.flags();
            let high = self.registers.wz.to_be_bytes()[0];
            self.set_flags((flags & !flag::XY_MASK) | (high & flag::XY_MASK));
            return;
        }

        *taken += self.write(host, address, result);
        let code = opcode & 0x07;
        if code != 6 {
            self.set_register(code, result);
        }
    }

    fn block_compare<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let up = opcode & 0x08 == 0;
        let (value, first) = self.read(host, self.registers.hl);
        *taken += first;

        let left = self.accumulator();
        self.alu(AluOp::Cp, opcode, left, value, true);

        let step = if up { 1u16 } else { 1u16.wrapping_neg() };
        self.registers.hl = self.registers.hl.wrapping_add(step);
        self.registers.bc = self.registers.bc.wrapping_sub(1);
        self.registers.wz = self.registers.wz.wrapping_add(step);

        // A compare takes them from the difference less the half-carry it borrowed, where a
        // transfer takes them from a sum.
        let borrowed = self.flags() & flag::H_MASK != 0;
        let reported = left.wrapping_sub(value).wrapping_sub(u8::from(borrowed));
        self.report_block(reported, flag::XY_MASK | flag::P_MASK);

        *taken += self.internal(host, 5);

        let repeating = opcode & 0x10 != 0;
        let matched = self.flags() & flag::Z_MASK != 0;
        if repeating && self.registers.bc != 0 && !matched {
            *taken += self.internal(host, 5);
            self.registers.pc = self.registers.pc.wrapping_sub(2);
            self.registers.wz = self.registers.pc.wrapping_add(1);
        }
    }

    fn report_value(&mut self, value: u8) {
        self.report_byte(value, value.count_ones().is_multiple_of(2));
    }

    fn report_byte(&mut self, value: u8, parity: bool) {
        let reported = flags::report_byte(self.flags(), value, parity);
        self.set_flags(flags::take_undocumented(reported, value));
    }

    // The pair is zero only when both halves are, so the high half folds in the low half's zero.
    fn alu_zeroing(&mut self, op: AluOp, ir: u8, left: u8, right: u8) -> u8 {
        let (result, produced) = alu::execute(alu::Inputs {
            op,
            ir: ir & mask::ALU_OPCODE,
            instruction_set: InstructionSet::Ed,
            bus_a: left,
            bus_b: right,
            flags: self.flags(),
            preserve_result_flags: false,
            combine_zero: true,
        });
        self.set_flags(produced);
        result
    }

    fn port_block<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        let up = opcode & 0x08 == 0;
        let outward = opcode & 0x01 != 0;

        // The counter comes down inside the fetch, and the two directions differ in whether their
        // port address sees that: an inward transfer is addressed before the decrement lands and
        // an outward one after it, because the outward form spends a cycle reading memory first.
        let before = self.registers.bc;
        let counter = self.register(0).wrapping_sub(1);
        self.set_register(0, counter);
        *taken += 1;
        self.lengthen_fetch(1);

        let (value, port) = if outward {
            let (byte, read) = self.read(host, self.registers.hl);
            *taken += read;
            let port = self.registers.bc;
            *taken += self.port_write(host, port, byte);
            (byte, port)
        } else {
            let (byte, read) = self.port_read(host, before);
            *taken += read;
            *taken += self.write(host, self.registers.hl, byte);
            (byte, before)
        };

        let step = if up { 1u16 } else { 1u16.wrapping_neg() };
        self.registers.hl = self.registers.hl.wrapping_add(step);
        self.registers.wz = port.wrapping_add(step);
        self.report_port_block(opcode, value);

        let repeating = opcode & 0x10 != 0;
        if repeating && counter != 0 {
            *taken += self.internal(host, 5);
            self.registers.pc = self.registers.pc.wrapping_sub(2);
        }
    }

    fn report_port_block(&mut self, opcode: u8, value: u8) {
        let reported = flags::port_block(
            self.flags(),
            self.registers.bc,
            self.registers.hl,
            opcode,
            value,
        );
        self.set_flags(reported);
    }

    fn prefixed<H: Host>(&mut self, host: &mut H, opcode: u8, taken: &mut u32) {
        #[cfg(test)]
        mark(&mut self.seen.bits, opcode);
        let code = opcode & 0x07;
        let through_memory = code == 6;
        let op = match opcode {
            0x00..=0x3F => AluOp::Rotate,
            0x40..=0x7F => AluOp::Bit,
            0x80..=0xBF => AluOp::Res,
            _ => AluOp::Set,
        };

        let (value, address) = if through_memory {
            let address = self.registers.hl;
            let (value, t) = self.read_taking(host, address, 4);
            *taken += t;
            (value, Some(address))
        } else {
            (self.register(code), None)
        };

        let result = self.alu_in(
            alu::Inputs {
                op,
                ir: opcode,
                instruction_set: InstructionSet::Cb,
                bus_a: value,
                bus_b: value,
                flags: 0,
                preserve_result_flags: false,
                combine_zero: false,
            },
            false,
        );

        // A test through memory takes its two undocumented flags from the address latch rather
        // than from the byte, which is the one place the tests and the registers differ.
        if matches!(op, AluOp::Bit) {
            if through_memory {
                let flags = self.flags();
                let high = self.registers.wz.to_be_bytes()[0];
                self.set_flags((flags & !flag::XY_MASK) | (high & flag::XY_MASK));
            }
            return;
        }

        match address {
            Some(address) => *taken += self.write(host, address, result),
            None => self.set_register(code, result),
        }
    }

    fn undocumented_carry_source(&self, accumulator: u8, flags: u8) -> u8 {
        flags::undocumented_carry_source(self.undocumented_flags, accumulator, flags)
    }

    fn accumulator_flags(&mut self, opcode: u8) {
        let accumulator = self.accumulator();
        let flags = self.flags();
        if opcode == 0x2F {
            self.set_accumulator(!accumulator);
            let taken = (self.flags() & !flag::XY_MASK) | (!accumulator & flag::XY_MASK);
            self.set_flags(taken | flag::H_MASK | flag::N_MASK);
            return;
        }

        let reported = self.undocumented_carry_source(accumulator, flags);
        let mut taken = (flags & !flag::XY_MASK) | (reported & flag::XY_MASK);
        taken &= !(flag::N_MASK | flag::H_MASK);
        // Complementing an already-set carry is the one case that moves it into the half-carry
        // instead of setting it; setting it is otherwise unconditional.
        if opcode == 0x3F && flags & flag::C_MASK != 0 {
            taken = (taken | flag::H_MASK) & !flag::C_MASK;
        } else {
            taken |= flag::C_MASK;
        }
        self.set_flags(taken);
    }

    // Relative to the address after the displacement, which the read has already moved past.
    fn jump_relative<H: Host>(&mut self, host: &mut H, displacement: u8) -> u32 {
        let taken = self.internal(host, 5);
        self.registers.pc = self
            .registers
            .pc
            .wrapping_add_signed(i16::from(displacement.cast_signed()));
        self.registers.wz = self.registers.pc;
        taken
    }

    // Y comes from bit 1 of the reported byte rather than bit 5, and the parity flag reports
    // whether the counter has anything left. `cleared` is the only thing that differs between the
    // block instructions: a transfer clears the half-carry and subtract flags, a compare keeps the
    // ones its subtraction wrote.
    fn report_block(&mut self, reported: u8, cleared: u8) {
        let mut flags = self.flags() & !cleared;
        flags |= reported & flag::X_MASK;
        if reported & 0x02 != 0 {
            flags |= flag::Y_MASK;
        }
        if self.registers.bc != 0 {
            flags |= flag::P_MASK;
        }
        self.set_flags(flags);
    }

    fn condition(&self, code: u8) -> bool {
        flags::condition_holds(self.flags(), code)
    }

    fn arithmetic(&mut self, opcode: u8, right: u8) {
        let op = AluOp::from_bits((opcode >> 3) & 0x07);
        let left = self.accumulator();
        let result = self.alu(op, opcode, left, right, false);
        // A comparison writes flags and discards its result, which is the whole of the difference
        // between it and a subtraction.
        if !matches!(op, AluOp::Cp) {
            self.set_accumulator(result);
        }
    }
}

#[cfg(test)]
#[path = "stepped_tests.rs"]
mod tests;