mos6502 0.9.0

A MOS 6502 Emulator
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
// Copyright (C) 2014 The 6502-rs Developers
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the names of the copyright holders nor the names of any
//    contributors may be used to endorse or promote products derived from this
//    software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

use crate::ArithmeticOutput;

use core::fmt::{Display, Error, Formatter};

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Instruction {
    // ADd with Carry
    ADC,

    // ADd with Carry. This one has no decimal mode.
    ADCnd,

    // logical AND (bitwise)
    AND,

    // Arithmetic Shift Left
    ASL,

    // Branch if Carry Clear
    BCC,

    // Branch if Carry Set
    BCS,

    // Branch if Equal (to zero?)
    BEQ,

    // BIT test
    BIT,

    // Branch if Minus
    BMI,

    // Branch if Not Equal
    BNE,

    // Branch if Positive
    BPL,

    // Unconditional BRAnch
    BRA,

    // BReaK
    BRK,

    // BReaK, clearing decimal flag
    BRKcld,

    // Branch if oVerflow Clear
    BVC,

    // Branch if oVerflow Set
    BVS,

    // CLear Carry flag
    CLC,

    // Clear Decimal Mode
    CLD,

    // Clear Interrupt Disable
    CLI,

    // Clear oVerflow flag
    CLV,

    // Compare
    CMP,

    // Compare X register
    CPX,

    // Compare Y register
    CPY,

    // DECrement memory
    DEC,

    // DEcrement X register
    DEX,

    // DEcrement Y register
    DEY,

    // Exclusive OR (bitwise)
    EOR,

    // INCrement memory
    INC,

    // INcrement X register
    INX,

    // INcrement Y register
    INY,

    // JuMP
    JMP,

    // Jump to SubRoutine
    JSR,

    // LoaD Accumulator
    LDA,

    // LoaD X register
    LDX,

    // LoaD Y register
    LDY,

    // Logical Shift Right
    LSR,

    // No OPeration
    NOP,

    // inclusive OR (bitwise)
    ORA,

    // PusH Accumulator
    PHA,

    // PusH X
    PHX,

    // PusH Y
    PHY,

    // PusH Processor status
    PHP,

    // PuLl Accumulator
    PLA,

    // PuLl X
    PLX,

    // PuLl Y
    PLY,

    // PuLl Processor status
    PLP,

    // ROtate Left
    ROL,

    // ROtate Right
    ROR,

    // ReTurn from Interrupt
    RTI,

    // ReTurn from Subroutine
    RTS,

    // SuBtract with Carry
    SBC,

    // SuBtract with Carry. This one has no decimal mode.
    SBCnd,

    // SEt Carry flag
    SEC,

    // SEt Decimal flag
    SED,

    // SEt Interrupt disable
    SEI,

    // STore Accumulator
    STA,

    // STore X register
    STX,

    // STore Y register
    STY,

    // STore Zero
    STZ,

    // STore A & X
    SAX,

    // Transfer Accumulator to X
    TAX,

    // Transfer Accumulator to Y
    TAY,

    // Test and Reset Bits
    TRB,

    // Test and Set Bits
    TSB,

    // Transfer Stack pointer to X
    TSX,

    // Transfer X to Accumulator
    TXA,

    // Transfer X to Stack pointer
    TXS,

    // Transfer Y to Accumulator
    TYA,

    // Wait for Interrupt (65C02 only)
    WAI,

    // SToP processor (65C02 only)
    STP,

    // Branch on Bit Reset (65C02 only) - BBRn zp,rel
    BBR(u8),

    // Branch on Bit Set (65C02 only) - BBSn zp,rel
    BBS(u8),

    // Reset Memory Bit (65C02 only) - RMBn zp
    RMB(u8),

    // Set Memory Bit (65C02 only) - SMBn zp
    SMB(u8),

    // XAA, (transfer X to A, and then ANDs the accumulator with an immediate value)
    XAA,

    // ALR, (ANDs the accumulator with an immediate value, and then does LSR)
    ALR,

    // ANC, (ANDs the accumulator and then copies bit 7 into carry flag)
    ANC,

    // ARR, (ANDs the accumulator with an immediate value, then RORs with special flag handling)
    ARR,

    // DCP (DCM), (Decrements memory, then compares with accumulator)
    DCP,

    // ISC (ISB/INS), (Increments memory, then SBCs from accumulator)
    ISC,

    // JAM (KIL/HLT), (Halts the CPU - requires reset)
    JAM,

    // LAS (LAR), (ANDs memory with SP, loads result into A, X, and SP)
    LAS,

    // LAX, (Loads both A and X with the same value from memory)
    LAX,

    // NOP with addressing modes (reads memory but does nothing)
    // 1-cycle NOP (65C02 undefined opcodes: $x3, $xB groups)
    NOP1,
    // Immediate NOP
    NOPI,
    // Zero Page NOP
    NOPZ,
    // Zero Page,X NOP
    NOPZX,
    // Absolute NOP
    NOPA,
    // Absolute,X NOP
    NOPAX,
    // Absolute,X NOP - 8 cycle variant (65C02 $5C)
    NOPAX8,

    // RLA, (Rotates memory left, then ANDs with accumulator)
    RLA,

    // RRA, (Rotates memory right, then ADCs with accumulator)
    RRA,

    // SBX (AXS), ((A AND X) - immediate -> X, sets flags like CMP)
    SBX,

    // SLO (ASO), (Shifts memory left, then ORs with accumulator)
    SLO,

    // SRE (LSE), (Shifts memory right, then EORs with accumulator)
    SRE,

    // USBC, (Same as SBC immediate)
    USBC,
}

impl Instruction {
    /// Returns the base cycle count for this instruction with the given addressing mode.
    ///
    /// This returns the minimum number of cycles required. Additional cycles may be added for:
    /// - Page boundary crossings (+1 for certain addressing modes)
    /// - Decimal mode on 65C02 (+1 for ADC/SBC when D flag is set)
    /// - Branch instructions (+1 if taken, +2 if taken and crosses page)
    #[must_use]
    pub fn base_cycles(self, mode: AddressingMode) -> u8 {
        #[allow(clippy::enum_glob_use)]
        use AddressingMode::*;
        #[allow(clippy::enum_glob_use)]
        use Instruction::*;

        match (self, mode) {
            // ADC - Add with Carry (2-6 cycles, +1 for page crossing on some modes, +1 for decimal on 65C02)
            (ADC | ADCnd, Immediate) => 2,
            (ADC | ADCnd, ZeroPage) => 3,
            (ADC | ADCnd, ZeroPageX) => 4,
            (ADC | ADCnd, Absolute) => 4,
            (ADC | ADCnd, AbsoluteX) => 4, // +1 if page crossed
            (ADC | ADCnd, AbsoluteY) => 4, // +1 if page crossed
            (ADC | ADCnd, IndexedIndirectX) => 6,
            (ADC | ADCnd, IndirectIndexedY) => 5, // +1 if page crossed
            (ADC | ADCnd, ZeroPageIndirect) => 5, // 65C02 only

            // AND - Logical AND (2-6 cycles)
            (AND, Immediate) => 2,
            (AND, ZeroPage) => 3,
            (AND, ZeroPageX) => 4,
            (AND, Absolute) => 4,
            (AND, AbsoluteX) => 4, // +1 if page crossed
            (AND, AbsoluteY) => 4, // +1 if page crossed
            (AND, IndexedIndirectX) => 6,
            (AND, IndirectIndexedY) => 5, // +1 if page crossed
            (AND, ZeroPageIndirect) => 5, // 65C02 only

            // ASL - Arithmetic Shift Left (2-7 cycles)
            (ASL, Accumulator) => 2,
            (ASL, ZeroPage) => 5,
            (ASL, ZeroPageX) => 6,
            (ASL, Absolute) => 6,
            (ASL, AbsoluteX) => 7,

            // Branch instructions - 2 cycles base, +1 if taken, +1 more if page crossed
            (BCC | BCS | BEQ | BMI | BNE | BPL | BVC | BVS, Relative) => 2,

            // BRA - Branch Always (65C02 only) - 3 cycles, +1 if page crossed
            (BRA, Relative) => 3,

            // BIT - Bit Test (2-4 cycles)
            (BIT, ZeroPage) => 3,
            (BIT, Absolute) => 4,
            (BIT, ZeroPageX) => 4, // 65C02 only
            (BIT, AbsoluteX) => 4, // 65C02 only, +1 if page crossed
            (BIT, Immediate) => 2, // 65C02 only

            // BRK - Break (7 cycles)
            (BRK | BRKcld, Implied) => 7,

            // CMP - Compare Accumulator (2-6 cycles)
            (CMP, Immediate) => 2,
            (CMP, ZeroPage) => 3,
            (CMP, ZeroPageX) => 4,
            (CMP, Absolute) => 4,
            (CMP, AbsoluteX) => 4, // +1 if page crossed
            (CMP, AbsoluteY) => 4, // +1 if page crossed
            (CMP, IndexedIndirectX) => 6,
            (CMP, IndirectIndexedY) => 5, // +1 if page crossed
            (CMP, ZeroPageIndirect) => 5, // 65C02 only

            // CPX - Compare X Register (2-4 cycles)
            (CPX, Immediate) => 2,
            (CPX, ZeroPage) => 3,
            (CPX, Absolute) => 4,

            // CPY - Compare Y Register (2-4 cycles)
            (CPY, Immediate) => 2,
            (CPY, ZeroPage) => 3,
            (CPY, Absolute) => 4,

            // DEC - Decrement Memory (2-7 cycles)
            (DEC, Accumulator) => 2, // 65C02 only
            (DEC, ZeroPage) => 5,
            (DEC, ZeroPageX) => 6,
            (DEC, Absolute) => 6,
            (DEC, AbsoluteX) => 7,

            // DEX/DEY - Decrement X/Y (2 cycles)
            (DEX | DEY, Implied) => 2,

            // EOR - Exclusive OR (2-6 cycles)
            (EOR, Immediate) => 2,
            (EOR, ZeroPage) => 3,
            (EOR, ZeroPageX) => 4,
            (EOR, Absolute) => 4,
            (EOR, AbsoluteX) => 4, // +1 if page crossed
            (EOR, AbsoluteY) => 4, // +1 if page crossed
            (EOR, IndexedIndirectX) => 6,
            (EOR, IndirectIndexedY) => 5, // +1 if page crossed
            (EOR, ZeroPageIndirect) => 5, // 65C02 only

            // Flag instructions (2 cycles)
            (CLC | CLD | CLI | CLV | SEC | SED | SEI, Implied) => 2,

            // INC - Increment Memory (2-7 cycles)
            (INC, Accumulator) => 2, // 65C02 only
            (INC, ZeroPage) => 5,
            (INC, ZeroPageX) => 6,
            (INC, Absolute) => 6,
            (INC, AbsoluteX) => 7,

            // INX/INY - Increment X/Y (2 cycles)
            (INX | INY, Implied) => 2,

            // JMP - Jump (3-6 cycles)
            (JMP, Absolute) => 3,
            (JMP, BuggyIndirect) => 5,           // NMOS with bug
            (JMP, Indirect) => 6,                // 65C02 fixed version
            (JMP, AbsoluteIndexedIndirect) => 6, // 65C02 only

            // JSR - Jump to Subroutine (6 cycles)
            (JSR, Absolute) => 6,

            // LDA - Load Accumulator (2-6 cycles)
            (LDA, Immediate) => 2,
            (LDA, ZeroPage) => 3,
            (LDA, ZeroPageX) => 4,
            (LDA, Absolute) => 4,
            (LDA, AbsoluteX) => 4, // +1 if page crossed
            (LDA, AbsoluteY) => 4, // +1 if page crossed
            (LDA, IndexedIndirectX) => 6,
            (LDA, IndirectIndexedY) => 5, // +1 if page crossed
            (LDA, ZeroPageIndirect) => 5, // 65C02 only

            // LDX - Load X Register (2-4 cycles)
            (LDX, Immediate) => 2,
            (LDX, ZeroPage) => 3,
            (LDX, ZeroPageY) => 4,
            (LDX, Absolute) => 4,
            (LDX, AbsoluteY) => 4, // +1 if page crossed

            // LDY - Load Y Register (2-4 cycles)
            (LDY, Immediate) => 2,
            (LDY, ZeroPage) => 3,
            (LDY, ZeroPageX) => 4,
            (LDY, Absolute) => 4,
            (LDY, AbsoluteX) => 4, // +1 if page crossed

            // LSR - Logical Shift Right (2-7 cycles)
            (LSR, Accumulator) => 2,
            (LSR, ZeroPage) => 5,
            (LSR, ZeroPageX) => 6,
            (LSR, Absolute) => 6,
            (LSR, AbsoluteX) => 7,

            // NOP - No Operation (2 cycles)
            (NOP, Implied) => 2,

            // ORA - Logical OR (2-6 cycles)
            (ORA, Immediate) => 2,
            (ORA, ZeroPage) => 3,
            (ORA, ZeroPageX) => 4,
            (ORA, Absolute) => 4,
            (ORA, AbsoluteX) => 4, // +1 if page crossed
            (ORA, AbsoluteY) => 4, // +1 if page crossed
            (ORA, IndexedIndirectX) => 6,
            (ORA, IndirectIndexedY) => 5, // +1 if page crossed
            (ORA, ZeroPageIndirect) => 5, // 65C02 only

            // PHA/PHP - Push Accumulator/Processor Status (3 cycles)
            (PHA | PHP, Implied) => 3,

            // PHX/PHY - Push X/Y (65C02 only, 3 cycles)
            (PHX | PHY, Implied) => 3,

            // PLA/PLP - Pull Accumulator/Processor Status (4 cycles)
            (PLA | PLP, Implied) => 4,

            // PLX/PLY - Pull X/Y (65C02 only, 4 cycles)
            (PLX | PLY, Implied) => 4,

            // ROL - Rotate Left (2-7 cycles)
            (ROL, Accumulator) => 2,
            (ROL, ZeroPage) => 5,
            (ROL, ZeroPageX) => 6,
            (ROL, Absolute) => 6,
            (ROL, AbsoluteX) => 7,

            // ROR - Rotate Right (2-7 cycles)
            (ROR, Accumulator) => 2,
            (ROR, ZeroPage) => 5,
            (ROR, ZeroPageX) => 6,
            (ROR, Absolute) => 6,
            (ROR, AbsoluteX) => 7,

            // RTI - Return from Interrupt (6 cycles)
            (RTI, Implied) => 6,

            // RTS - Return from Subroutine (6 cycles)
            (RTS, Implied) => 6,

            // SBC - Subtract with Carry (2-6 cycles, +1 for page crossing, +1 for decimal on 65C02)
            (SBC | SBCnd, Immediate) => 2,
            (SBC | SBCnd, ZeroPage) => 3,
            (SBC | SBCnd, ZeroPageX) => 4,
            (SBC | SBCnd, Absolute) => 4,
            (SBC | SBCnd, AbsoluteX) => 4, // +1 if page crossed
            (SBC | SBCnd, AbsoluteY) => 4, // +1 if page crossed
            (SBC | SBCnd, IndexedIndirectX) => 6,
            (SBC | SBCnd, IndirectIndexedY) => 5, // +1 if page crossed
            (SBC | SBCnd, ZeroPageIndirect) => 5, // 65C02 only

            // STA - Store Accumulator (3-6 cycles, NO page crossing penalty)
            (STA, ZeroPage) => 3,
            (STA, ZeroPageX) => 4,
            (STA, Absolute) => 4,
            (STA, AbsoluteX) => 5,
            (STA, AbsoluteY) => 5,
            (STA, IndexedIndirectX) => 6,
            (STA, IndirectIndexedY) => 6,
            (STA, ZeroPageIndirect) => 5, // 65C02 only

            // STX - Store X Register (3-4 cycles)
            (STX, ZeroPage) => 3,
            (STX, ZeroPageY) => 4,
            (STX, Absolute) => 4,

            // STY - Store Y Register (3-4 cycles)
            (STY, ZeroPage) => 3,
            (STY, ZeroPageX) => 4,
            (STY, Absolute) => 4,

            // STZ - Store Zero (65C02 only, 3-5 cycles)
            (STZ, ZeroPage) => 3,
            (STZ, ZeroPageX) => 4,
            (STZ, Absolute) => 4,
            (STZ, AbsoluteX) => 5,

            // Transfer instructions (2 cycles)
            (TAX | TAY | TSX | TXA | TXS | TYA, Implied) => 2,

            // TRB/TSB - Test and Reset/Set Bits (65C02 only, 5-6 cycles)
            (TRB | TSB, ZeroPage) => 5,
            (TRB | TSB, Absolute) => 6,

            // STP - Stop (65C02 only, 3 cycles before halting)
            (STP, Implied) => 3,

            // WAI - Wait for Interrupt (65C02 only, 3 cycles before waiting)
            (WAI, Implied) => 3,

            // BBR/BBS - Branch on Bit Reset/Set (65C02 only, 5 cycles)
            (BBR(_), ZeroPageRelative) => 5,
            (BBS(_), ZeroPageRelative) => 5,

            // RMB/SMB - Reset/Set Memory Bit (65C02 only, 5 cycles)
            (RMB(_), ZeroPage) => 5,
            (SMB(_), ZeroPage) => 5,

            // Illegal opcodes - SAX (Store A AND X)
            (SAX, ZeroPage) => 3,
            (SAX, ZeroPageY) => 4,
            (SAX, Absolute) => 4,
            (SAX, IndexedIndirectX) => 6,

            // Illegal opcodes - XAA (Transfer X to A, then AND)
            (XAA, Immediate) => 2,

            // Illegal opcodes - ALR (AND then LSR)
            (ALR, Immediate) => 2,

            // Illegal opcodes - ANC (AND then copy bit 7 to carry)
            (ANC, Immediate) => 2,

            // Illegal opcodes - ARR (AND then ROR with special flags)
            (ARR, Immediate) => 2,

            // Illegal opcodes - DCP (Decrement then Compare)
            (DCP, ZeroPage) => 5,
            (DCP, ZeroPageX) => 6,
            (DCP, Absolute) => 6,
            (DCP, AbsoluteX) => 7,
            (DCP, AbsoluteY) => 7,
            (DCP, IndexedIndirectX) => 8,
            (DCP, IndirectIndexedY) => 8,

            // Illegal opcodes - ISC (Increment then SBC)
            (ISC, ZeroPage) => 5,
            (ISC, ZeroPageX) => 6,
            (ISC, Absolute) => 6,
            (ISC, AbsoluteX) => 7,
            (ISC, AbsoluteY) => 7,
            (ISC, IndexedIndirectX) => 8,
            (ISC, IndirectIndexedY) => 8,

            // Illegal opcodes - JAM (Halt CPU)
            (JAM, Implied) => 2,

            // Illegal opcodes - LAS (AND with SP, load to A, X, SP)
            (LAS, AbsoluteY) => 4, // +1 if page crossed

            // Illegal opcodes - LAX (Load A and X)
            (LAX, ZeroPage) => 3,
            (LAX, ZeroPageY) => 4,
            (LAX, Absolute) => 4,
            (LAX, AbsoluteY) => 4, // +1 if page crossed
            (LAX, IndexedIndirectX) => 6,
            (LAX, IndirectIndexedY) => 5, // +1 if page crossed

            // Illegal opcodes - NOP variants
            (NOP1, Implied) => 1,
            (NOPI, Immediate) => 2,
            (NOPZ, ZeroPage) => 3,
            (NOPZX, ZeroPageX) => 4,
            (NOPA, Absolute) => 4,
            (NOPAX, AbsoluteX) => 4, // +1 if page crossed
            (NOPAX8, AbsoluteX) => 8,

            // Illegal opcodes - RLA (Rotate Left then AND)
            (RLA, ZeroPage) => 5,
            (RLA, ZeroPageX) => 6,
            (RLA, Absolute) => 6,
            (RLA, AbsoluteX) => 7,
            (RLA, AbsoluteY) => 7,
            (RLA, IndexedIndirectX) => 8,
            (RLA, IndirectIndexedY) => 8,

            // Illegal opcodes - RRA (Rotate Right then ADC)
            (RRA, ZeroPage) => 5,
            (RRA, ZeroPageX) => 6,
            (RRA, Absolute) => 6,
            (RRA, AbsoluteX) => 7,
            (RRA, AbsoluteY) => 7,
            (RRA, IndexedIndirectX) => 8,
            (RRA, IndirectIndexedY) => 8,

            // Illegal opcodes - SBX (A AND X - immediate -> X)
            (SBX, Immediate) => 2,

            // Illegal opcodes - SLO (Shift Left then OR)
            (SLO, ZeroPage) => 5,
            (SLO, ZeroPageX) => 6,
            (SLO, Absolute) => 6,
            (SLO, AbsoluteX) => 7,
            (SLO, AbsoluteY) => 7,
            (SLO, IndexedIndirectX) => 8,
            (SLO, IndirectIndexedY) => 8,

            // Illegal opcodes - SRE (Shift Right then EOR)
            (SRE, ZeroPage) => 5,
            (SRE, ZeroPageX) => 6,
            (SRE, Absolute) => 6,
            (SRE, AbsoluteX) => 7,
            (SRE, AbsoluteY) => 7,
            (SRE, IndexedIndirectX) => 8,
            (SRE, IndirectIndexedY) => 8,

            // Illegal opcodes - USBC (Same as SBC)
            (USBC, Immediate) => 2,

            // Invalid combinations cause a panic to indicate a bug in the decoder
            _ => unreachable!("undecoded instruction"),
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum OpInput {
    UseImplied,
    UseImmediate(u8),
    UseRelative(u16),
    UseAddress { address: u16, page_crossed: bool },
    // BBR/BBS: zero-page address to test, plus sign-extended relative offset
    UseBitBranch { zp_address: u8, relative: u16 },
}

impl OpInput {
    /// Returns true if a page boundary was crossed during address calculation.
    ///
    /// Only relevant for `UseAddress` - all other addressing modes return false.
    #[must_use]
    pub const fn page_crossed(&self) -> bool {
        match self {
            OpInput::UseAddress { page_crossed, .. } => *page_crossed,
            _ => false,
        }
    }
}

impl Display for OpInput {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match self {
            OpInput::UseImplied => write!(f, ""),
            OpInput::UseImmediate(v) => write!(f, "#${v:02X}"),
            OpInput::UseRelative(v) => write!(f, "${v:04X}"),
            OpInput::UseAddress { address, .. } => write!(f, "${address:04X}"),
            OpInput::UseBitBranch {
                zp_address,
                relative,
            } => {
                write!(f, "${zp_address:02X},${relative:04X}")
            }
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub enum AddressingMode {
    // work directly on accumulator, e. g. `lsr a`.
    Accumulator,

    // BRK
    Implied,

    // 8-bit constant in instruction, e. g. `lda #10`.
    Immediate,

    // zero-page address, e. g. `lda $00`.
    ZeroPage,

    // address is X register + 8-bit constant, e. g. `lda $80,x`.
    ZeroPageX,

    // address is Y register + 8-bit constant, e. g. `ldx $10,y`.
    ZeroPageY,

    // branch target as signed relative offset, e. g. `bne label`.
    Relative,

    // full 16-bit address, e. g. `jmp $1000`.
    Absolute,

    // full 16-bit address plus X register, e. g. `sta $1000,X`.
    AbsoluteX,

    // full 16-bit address plus Y register, e. g. `sta $1000,Y`.
    AbsoluteY,

    // jump to address stored at address, with the page-crossing bug found in NMOS chips, e. g. `jmp ($1000)`.
    BuggyIndirect,

    // jump to address stored at address, e. g. `jmp ($1000)`.
    Indirect,

    // load from address stored at (constant zero page address plus X register), e. g. `lda ($10,X)`.
    IndexedIndirectX,

    // load from (address stored at constant zero page address) plus Y register, e. g. `lda ($10),Y`.
    IndirectIndexedY,

    // Address stored at constant zero page address
    ZeroPageIndirect,

    // jump to address stored at (absolute address plus X register), e. g. `jmp ($1000,X)`.
    // 65C02 only
    AbsoluteIndexedIndirect,

    // Zero page address + relative offset, used for BBR/BBS (65C02 only).
    // Encodes two operand bytes: zp_address, relative_offset.
    ZeroPageRelative,
}

impl AddressingMode {
    #[must_use]
    pub const fn extra_bytes(self) -> u16 {
        match self {
            AddressingMode::Accumulator => 0,
            AddressingMode::Implied => 0,
            AddressingMode::Immediate => 1,
            AddressingMode::ZeroPage => 1,
            AddressingMode::ZeroPageX => 1,
            AddressingMode::ZeroPageY => 1,
            AddressingMode::Relative => 1,
            AddressingMode::Absolute => 2,
            AddressingMode::AbsoluteX => 2,
            AddressingMode::AbsoluteY => 2,
            AddressingMode::Indirect => 2,
            AddressingMode::BuggyIndirect => 2,
            AddressingMode::IndexedIndirectX => 1,
            AddressingMode::IndirectIndexedY => 1,
            AddressingMode::ZeroPageIndirect => 1,
            AddressingMode::AbsoluteIndexedIndirect => 2,
            AddressingMode::ZeroPageRelative => 2,
        }
    }
}

/// A decoded instruction containing the instruction type, addressing mode, operand data,
/// and whether a page boundary was crossed during address calculation (used for cycle counting).
pub type DecodedInstr = (Instruction, AddressingMode, OpInput);

/// The NMOS 6502 variant. This one is present in the Commodore 64, early Apple IIs, etc.
#[derive(Copy, Clone, Debug, Default)]
pub struct Nmos6502;

impl crate::Variant for Nmos6502 {
    fn decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
        match opcode {
            0x00 => Some((Instruction::BRK, AddressingMode::Implied)),
            0x01 => Some((Instruction::ORA, AddressingMode::IndexedIndirectX)),
            0x02 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x03 => Some((Instruction::SLO, AddressingMode::IndexedIndirectX)),
            0x04 => Some((Instruction::NOPZ, AddressingMode::ZeroPage)),
            0x05 => Some((Instruction::ORA, AddressingMode::ZeroPage)),
            0x06 => Some((Instruction::ASL, AddressingMode::ZeroPage)),
            0x07 => Some((Instruction::SLO, AddressingMode::ZeroPage)),
            0x08 => Some((Instruction::PHP, AddressingMode::Implied)),
            0x09 => Some((Instruction::ORA, AddressingMode::Immediate)),
            0x0a => Some((Instruction::ASL, AddressingMode::Accumulator)),
            0x0b => Some((Instruction::ANC, AddressingMode::Immediate)),
            0x0c => Some((Instruction::NOPA, AddressingMode::Absolute)),
            0x0d => Some((Instruction::ORA, AddressingMode::Absolute)),
            0x0e => Some((Instruction::ASL, AddressingMode::Absolute)),
            0x0f => Some((Instruction::SLO, AddressingMode::Absolute)),
            0x10 => Some((Instruction::BPL, AddressingMode::Relative)),
            0x11 => Some((Instruction::ORA, AddressingMode::IndirectIndexedY)),
            0x12 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x13 => Some((Instruction::SLO, AddressingMode::IndirectIndexedY)),
            0x14 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0x15 => Some((Instruction::ORA, AddressingMode::ZeroPageX)),
            0x16 => Some((Instruction::ASL, AddressingMode::ZeroPageX)),
            0x17 => Some((Instruction::SLO, AddressingMode::ZeroPageX)),
            0x18 => Some((Instruction::CLC, AddressingMode::Implied)),
            0x19 => Some((Instruction::ORA, AddressingMode::AbsoluteY)),
            0x1a => Some((Instruction::NOP, AddressingMode::Implied)),
            0x1b => Some((Instruction::SLO, AddressingMode::AbsoluteY)),
            0x1c => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0x1d => Some((Instruction::ORA, AddressingMode::AbsoluteX)),
            0x1e => Some((Instruction::ASL, AddressingMode::AbsoluteX)),
            0x1f => Some((Instruction::SLO, AddressingMode::AbsoluteX)),
            0x20 => Some((Instruction::JSR, AddressingMode::Absolute)),
            0x21 => Some((Instruction::AND, AddressingMode::IndexedIndirectX)),
            0x22 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x23 => Some((Instruction::RLA, AddressingMode::IndexedIndirectX)),
            0x24 => Some((Instruction::BIT, AddressingMode::ZeroPage)),
            0x25 => Some((Instruction::AND, AddressingMode::ZeroPage)),
            0x26 => Some((Instruction::ROL, AddressingMode::ZeroPage)),
            0x27 => Some((Instruction::RLA, AddressingMode::ZeroPage)),
            0x28 => Some((Instruction::PLP, AddressingMode::Implied)),
            0x29 => Some((Instruction::AND, AddressingMode::Immediate)),
            0x2a => Some((Instruction::ROL, AddressingMode::Accumulator)),
            0x2b => Some((Instruction::ANC, AddressingMode::Immediate)),
            0x2c => Some((Instruction::BIT, AddressingMode::Absolute)),
            0x2d => Some((Instruction::AND, AddressingMode::Absolute)),
            0x2e => Some((Instruction::ROL, AddressingMode::Absolute)),
            0x2f => Some((Instruction::RLA, AddressingMode::Absolute)),
            0x30 => Some((Instruction::BMI, AddressingMode::Relative)),
            0x31 => Some((Instruction::AND, AddressingMode::IndirectIndexedY)),
            0x32 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x33 => Some((Instruction::RLA, AddressingMode::IndirectIndexedY)),
            0x34 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0x35 => Some((Instruction::AND, AddressingMode::ZeroPageX)),
            0x36 => Some((Instruction::ROL, AddressingMode::ZeroPageX)),
            0x37 => Some((Instruction::RLA, AddressingMode::ZeroPageX)),
            0x38 => Some((Instruction::SEC, AddressingMode::Implied)),
            0x39 => Some((Instruction::AND, AddressingMode::AbsoluteY)),
            0x3a => Some((Instruction::NOP, AddressingMode::Implied)),
            0x3b => Some((Instruction::RLA, AddressingMode::AbsoluteY)),
            0x3c => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0x3d => Some((Instruction::AND, AddressingMode::AbsoluteX)),
            0x3e => Some((Instruction::ROL, AddressingMode::AbsoluteX)),
            0x3f => Some((Instruction::RLA, AddressingMode::AbsoluteX)),
            0x40 => Some((Instruction::RTI, AddressingMode::Implied)),
            0x41 => Some((Instruction::EOR, AddressingMode::IndexedIndirectX)),
            0x42 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x43 => Some((Instruction::SRE, AddressingMode::IndexedIndirectX)),
            0x44 => Some((Instruction::NOPZ, AddressingMode::ZeroPage)),
            0x45 => Some((Instruction::EOR, AddressingMode::ZeroPage)),
            0x46 => Some((Instruction::LSR, AddressingMode::ZeroPage)),
            0x47 => Some((Instruction::SRE, AddressingMode::ZeroPage)),
            0x48 => Some((Instruction::PHA, AddressingMode::Implied)),
            0x49 => Some((Instruction::EOR, AddressingMode::Immediate)),
            0x4a => Some((Instruction::LSR, AddressingMode::Accumulator)),
            0x4b => Some((Instruction::ALR, AddressingMode::Immediate)),
            0x4c => Some((Instruction::JMP, AddressingMode::Absolute)),
            0x4d => Some((Instruction::EOR, AddressingMode::Absolute)),
            0x4e => Some((Instruction::LSR, AddressingMode::Absolute)),
            0x4f => Some((Instruction::SRE, AddressingMode::Absolute)),
            0x50 => Some((Instruction::BVC, AddressingMode::Relative)),
            0x51 => Some((Instruction::EOR, AddressingMode::IndirectIndexedY)),
            0x52 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x53 => Some((Instruction::SRE, AddressingMode::IndirectIndexedY)),
            0x54 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0x55 => Some((Instruction::EOR, AddressingMode::ZeroPageX)),
            0x56 => Some((Instruction::LSR, AddressingMode::ZeroPageX)),
            0x57 => Some((Instruction::SRE, AddressingMode::ZeroPageX)),
            0x58 => Some((Instruction::CLI, AddressingMode::Implied)),
            0x59 => Some((Instruction::EOR, AddressingMode::AbsoluteY)),
            0x5a => Some((Instruction::NOP, AddressingMode::Implied)),
            0x5b => Some((Instruction::SRE, AddressingMode::AbsoluteY)),
            0x5c => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0x5d => Some((Instruction::EOR, AddressingMode::AbsoluteX)),
            0x5e => Some((Instruction::LSR, AddressingMode::AbsoluteX)),
            0x5f => Some((Instruction::SRE, AddressingMode::AbsoluteX)),
            0x60 => Some((Instruction::RTS, AddressingMode::Implied)),
            0x61 => Some((Instruction::ADC, AddressingMode::IndexedIndirectX)),
            0x62 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x63 => Some((Instruction::RRA, AddressingMode::IndexedIndirectX)),
            0x64 => Some((Instruction::NOPZ, AddressingMode::ZeroPage)),
            0x65 => Some((Instruction::ADC, AddressingMode::ZeroPage)),
            0x66 => Some((Instruction::ROR, AddressingMode::ZeroPage)),
            0x67 => Some((Instruction::RRA, AddressingMode::ZeroPage)),
            0x68 => Some((Instruction::PLA, AddressingMode::Implied)),
            0x69 => Some((Instruction::ADC, AddressingMode::Immediate)),
            0x6a => Some((Instruction::ROR, AddressingMode::Accumulator)),
            0x6b => Some((Instruction::ARR, AddressingMode::Immediate)),
            0x6c => Some((Instruction::JMP, AddressingMode::BuggyIndirect)),
            0x6d => Some((Instruction::ADC, AddressingMode::Absolute)),
            0x6e => Some((Instruction::ROR, AddressingMode::Absolute)),
            0x6f => Some((Instruction::RRA, AddressingMode::Absolute)),
            0x70 => Some((Instruction::BVS, AddressingMode::Relative)),
            0x71 => Some((Instruction::ADC, AddressingMode::IndirectIndexedY)),
            0x72 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x73 => Some((Instruction::RRA, AddressingMode::IndirectIndexedY)),
            0x74 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0x75 => Some((Instruction::ADC, AddressingMode::ZeroPageX)),
            0x76 => Some((Instruction::ROR, AddressingMode::ZeroPageX)),
            0x77 => Some((Instruction::RRA, AddressingMode::ZeroPageX)),
            0x78 => Some((Instruction::SEI, AddressingMode::Implied)),
            0x79 => Some((Instruction::ADC, AddressingMode::AbsoluteY)),
            0x7a => Some((Instruction::NOP, AddressingMode::Implied)),
            0x7b => Some((Instruction::RRA, AddressingMode::AbsoluteY)),
            0x7c => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0x7d => Some((Instruction::ADC, AddressingMode::AbsoluteX)),
            0x7e => Some((Instruction::ROR, AddressingMode::AbsoluteX)),
            0x7f => Some((Instruction::RRA, AddressingMode::AbsoluteX)),
            0x80 => Some((Instruction::NOPI, AddressingMode::Immediate)),
            0x81 => Some((Instruction::STA, AddressingMode::IndexedIndirectX)),
            0x82 => Some((Instruction::NOPI, AddressingMode::Immediate)),
            0x83 => Some((Instruction::SAX, AddressingMode::IndexedIndirectX)),
            0x84 => Some((Instruction::STY, AddressingMode::ZeroPage)),
            0x85 => Some((Instruction::STA, AddressingMode::ZeroPage)),
            0x86 => Some((Instruction::STX, AddressingMode::ZeroPage)),
            0x87 => Some((Instruction::SAX, AddressingMode::ZeroPage)),
            0x88 => Some((Instruction::DEY, AddressingMode::Implied)),
            0x89 => Some((Instruction::NOPI, AddressingMode::Immediate)),
            0x8a => Some((Instruction::TXA, AddressingMode::Implied)),
            0x8b => Some((Instruction::XAA, AddressingMode::Immediate)),
            0x8c => Some((Instruction::STY, AddressingMode::Absolute)),
            0x8d => Some((Instruction::STA, AddressingMode::Absolute)),
            0x8e => Some((Instruction::STX, AddressingMode::Absolute)),
            0x8f => Some((Instruction::SAX, AddressingMode::Absolute)),
            0x90 => Some((Instruction::BCC, AddressingMode::Relative)),
            0x91 => Some((Instruction::STA, AddressingMode::IndirectIndexedY)),
            0x92 => Some((Instruction::JAM, AddressingMode::Implied)),
            0x93 => None, // SHA (zp),Y - unstable, skip
            0x94 => Some((Instruction::STY, AddressingMode::ZeroPageX)),
            0x95 => Some((Instruction::STA, AddressingMode::ZeroPageX)),
            0x96 => Some((Instruction::STX, AddressingMode::ZeroPageY)),
            0x97 => Some((Instruction::SAX, AddressingMode::ZeroPageY)),
            0x98 => Some((Instruction::TYA, AddressingMode::Implied)),
            0x99 => Some((Instruction::STA, AddressingMode::AbsoluteY)),
            0x9a => Some((Instruction::TXS, AddressingMode::Implied)),
            0x9b => None, // TAS abs,Y - unstable, skip
            0x9c => None, // SHY abs,X - unstable, skip
            0x9d => Some((Instruction::STA, AddressingMode::AbsoluteX)),
            0x9e => None, // SHX abs,Y - unstable, skip
            0x9f => None, // SHA abs,Y - unstable, skip
            0xa0 => Some((Instruction::LDY, AddressingMode::Immediate)),
            0xa1 => Some((Instruction::LDA, AddressingMode::IndexedIndirectX)),
            0xa2 => Some((Instruction::LDX, AddressingMode::Immediate)),
            0xa3 => Some((Instruction::LAX, AddressingMode::IndexedIndirectX)),
            0xa4 => Some((Instruction::LDY, AddressingMode::ZeroPage)),
            0xa5 => Some((Instruction::LDA, AddressingMode::ZeroPage)),
            0xa6 => Some((Instruction::LDX, AddressingMode::ZeroPage)),
            0xa7 => Some((Instruction::LAX, AddressingMode::ZeroPage)),
            0xa8 => Some((Instruction::TAY, AddressingMode::Implied)),
            0xa9 => Some((Instruction::LDA, AddressingMode::Immediate)),
            0xaa => Some((Instruction::TAX, AddressingMode::Implied)),
            0xab => None, // LXA #imm - unstable, skip
            0xac => Some((Instruction::LDY, AddressingMode::Absolute)),
            0xad => Some((Instruction::LDA, AddressingMode::Absolute)),
            0xae => Some((Instruction::LDX, AddressingMode::Absolute)),
            0xaf => Some((Instruction::LAX, AddressingMode::Absolute)),
            0xb0 => Some((Instruction::BCS, AddressingMode::Relative)),
            0xb1 => Some((Instruction::LDA, AddressingMode::IndirectIndexedY)),
            0xb2 => Some((Instruction::JAM, AddressingMode::Implied)),
            0xb3 => Some((Instruction::LAX, AddressingMode::IndirectIndexedY)),
            0xb4 => Some((Instruction::LDY, AddressingMode::ZeroPageX)),
            0xb5 => Some((Instruction::LDA, AddressingMode::ZeroPageX)),
            0xb6 => Some((Instruction::LDX, AddressingMode::ZeroPageY)),
            0xb7 => Some((Instruction::LAX, AddressingMode::ZeroPageY)),
            0xb8 => Some((Instruction::CLV, AddressingMode::Implied)),
            0xb9 => Some((Instruction::LDA, AddressingMode::AbsoluteY)),
            0xba => Some((Instruction::TSX, AddressingMode::Implied)),
            0xbb => Some((Instruction::LAS, AddressingMode::AbsoluteY)),
            0xbc => Some((Instruction::LDY, AddressingMode::AbsoluteX)),
            0xbd => Some((Instruction::LDA, AddressingMode::AbsoluteX)),
            0xbe => Some((Instruction::LDX, AddressingMode::AbsoluteY)),
            0xbf => Some((Instruction::LAX, AddressingMode::AbsoluteY)),
            0xc0 => Some((Instruction::CPY, AddressingMode::Immediate)),
            0xc1 => Some((Instruction::CMP, AddressingMode::IndexedIndirectX)),
            0xc2 => Some((Instruction::NOPI, AddressingMode::Immediate)),
            0xc3 => Some((Instruction::DCP, AddressingMode::IndexedIndirectX)),
            0xc4 => Some((Instruction::CPY, AddressingMode::ZeroPage)),
            0xc5 => Some((Instruction::CMP, AddressingMode::ZeroPage)),
            0xc6 => Some((Instruction::DEC, AddressingMode::ZeroPage)),
            0xc7 => Some((Instruction::DCP, AddressingMode::ZeroPage)),
            0xc8 => Some((Instruction::INY, AddressingMode::Implied)),
            0xc9 => Some((Instruction::CMP, AddressingMode::Immediate)),
            0xca => Some((Instruction::DEX, AddressingMode::Implied)),
            0xcb => Some((Instruction::SBX, AddressingMode::Immediate)),
            0xcc => Some((Instruction::CPY, AddressingMode::Absolute)),
            0xcd => Some((Instruction::CMP, AddressingMode::Absolute)),
            0xce => Some((Instruction::DEC, AddressingMode::Absolute)),
            0xcf => Some((Instruction::DCP, AddressingMode::Absolute)),
            0xd0 => Some((Instruction::BNE, AddressingMode::Relative)),
            0xd1 => Some((Instruction::CMP, AddressingMode::IndirectIndexedY)),
            0xd2 => Some((Instruction::JAM, AddressingMode::Implied)),
            0xd3 => Some((Instruction::DCP, AddressingMode::IndirectIndexedY)),
            0xd4 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0xd5 => Some((Instruction::CMP, AddressingMode::ZeroPageX)),
            0xd6 => Some((Instruction::DEC, AddressingMode::ZeroPageX)),
            0xd7 => Some((Instruction::DCP, AddressingMode::ZeroPageX)),
            0xd8 => Some((Instruction::CLD, AddressingMode::Implied)),
            0xd9 => Some((Instruction::CMP, AddressingMode::AbsoluteY)),
            0xda => Some((Instruction::NOP, AddressingMode::Implied)),
            0xdb => Some((Instruction::DCP, AddressingMode::AbsoluteY)),
            0xdc => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0xdd => Some((Instruction::CMP, AddressingMode::AbsoluteX)),
            0xde => Some((Instruction::DEC, AddressingMode::AbsoluteX)),
            0xdf => Some((Instruction::DCP, AddressingMode::AbsoluteX)),
            0xe0 => Some((Instruction::CPX, AddressingMode::Immediate)),
            0xe1 => Some((Instruction::SBC, AddressingMode::IndexedIndirectX)),
            0xe2 => Some((Instruction::NOPI, AddressingMode::Immediate)),
            0xe3 => Some((Instruction::ISC, AddressingMode::IndexedIndirectX)),
            0xe4 => Some((Instruction::CPX, AddressingMode::ZeroPage)),
            0xe5 => Some((Instruction::SBC, AddressingMode::ZeroPage)),
            0xe6 => Some((Instruction::INC, AddressingMode::ZeroPage)),
            0xe7 => Some((Instruction::ISC, AddressingMode::ZeroPage)),
            0xe8 => Some((Instruction::INX, AddressingMode::Implied)),
            0xe9 => Some((Instruction::SBC, AddressingMode::Immediate)),
            0xea => Some((Instruction::NOP, AddressingMode::Implied)),
            0xeb => Some((Instruction::USBC, AddressingMode::Immediate)),
            0xec => Some((Instruction::CPX, AddressingMode::Absolute)),
            0xed => Some((Instruction::SBC, AddressingMode::Absolute)),
            0xee => Some((Instruction::INC, AddressingMode::Absolute)),
            0xef => Some((Instruction::ISC, AddressingMode::Absolute)),
            0xf0 => Some((Instruction::BEQ, AddressingMode::Relative)),
            0xf1 => Some((Instruction::SBC, AddressingMode::IndirectIndexedY)),
            0xf2 => Some((Instruction::JAM, AddressingMode::Implied)),
            0xf3 => Some((Instruction::ISC, AddressingMode::IndirectIndexedY)),
            0xf4 => Some((Instruction::NOPZX, AddressingMode::ZeroPageX)),
            0xf5 => Some((Instruction::SBC, AddressingMode::ZeroPageX)),
            0xf6 => Some((Instruction::INC, AddressingMode::ZeroPageX)),
            0xf7 => Some((Instruction::ISC, AddressingMode::ZeroPageX)),
            0xf8 => Some((Instruction::SED, AddressingMode::Implied)),
            0xf9 => Some((Instruction::SBC, AddressingMode::AbsoluteY)),
            0xfa => Some((Instruction::NOP, AddressingMode::Implied)),
            0xfb => Some((Instruction::ISC, AddressingMode::AbsoluteY)),
            0xfc => Some((Instruction::NOPAX, AddressingMode::AbsoluteX)),
            0xfd => Some((Instruction::SBC, AddressingMode::AbsoluteX)),
            0xfe => Some((Instruction::INC, AddressingMode::AbsoluteX)),
            0xff => Some((Instruction::ISC, AddressingMode::AbsoluteX)),
        }
    }

    /// NMOS 6502 ADC implementation in binary mode
    ///
    /// - Standard binary arithmetic
    /// - All flags calculated from binary result
    ///
    /// # References
    ///
    /// - [6502.org ADC documentation](http://www.6502.org/tutorials/decimal_mode.html)
    /// - [NESdev 6502 reference](https://www.nesdev.org/obelisk-6502-guide/reference.html#ADC)
    fn adc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Binary addition with carry detection
        let carry = u8::from(carry_set);
        let result_16 = u16::from(accumulator) + u16::from(value) + u16::from(carry);
        let did_carry = result_16 > 0xFF;
        // Convert to 8-bit result using little-endian byte conversion
        let result = result_16.to_le_bytes()[0];

        // Calculate overflow from binary result
        let overflow = (!(accumulator ^ value) & (accumulator ^ result)) & 0x80 != 0;

        // Negative flag is set if the result's sign bit is set, which is the 8th bit.
        let negative = (result & 0x80) != 0;

        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// NMOS 6502 ADC implementation in decimal mode (BCD)
    ///
    /// - Binary Coded Decimal (BCD) arithmetic using 4-bit decimal digits
    /// - Each nibble represents a digit from 0-9
    /// - In decimal mode: N and Z flags are unreliable/undefined
    /// - In decimal mode: V flag calculated from binary result (documented behavior)
    ///
    /// # References
    ///
    /// - [6502.org ADC documentation](http://www.6502.org/tutorials/decimal_mode.html)
    /// - [NESdev 6502 reference](https://www.nesdev.org/obelisk-6502-guide/reference.html#ADC)
    fn adc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Perform binary addition first for overflow calculation
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_add(value).wrapping_add(carry);

        // Decimal mode: treat each nibble as a decimal digit (0-9)
        let mut low_nibble = (accumulator & 0x0f)
            .wrapping_add(value & 0x0f)
            .wrapping_add(carry);

        let mut high_nibble = (accumulator >> 4).wrapping_add(value >> 4);
        let mut carry_to_high = false;

        // If low nibble is > 9, adjust it and carry to high nibble
        if low_nibble > 9 {
            low_nibble = low_nibble.wrapping_sub(10);
            carry_to_high = true;
        }

        high_nibble = high_nibble.wrapping_add(u8::from(carry_to_high));

        // Adjust high nibble if it's > 9 and set final carry flag
        let (adjusted_high, did_carry) = if high_nibble > 9 {
            (high_nibble.wrapping_sub(10), true)
        } else {
            (high_nibble, false)
        };

        let result = (adjusted_high << 4) | (low_nibble & 0x0f);

        // Calculate overflow from binary result (even in decimal mode)
        let overflow = (!(accumulator ^ value) & (accumulator ^ temp_result)) & 0x80 != 0;

        // Calculate other flags from final result
        let negative = (result & 0x80) != 0;
        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// NMOS 6502 SBC (Subtract with Carry) implementation in binary mode
    ///
    /// - Standard binary subtraction with borrow handling
    /// - All flags calculated from binary result
    ///
    /// # References
    ///
    /// - [6502.org SBC documentation](http://www.6502.org/tutorials/decimal_mode.html)
    /// - [NESdev 6502 reference](https://www.nesdev.org/obelisk-6502-guide/reference.html#SBC)
    fn sbc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // SBC performs: A = A - M - (1 - C)
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_sub(value).wrapping_sub(1 - carry);

        // Check for borrow (unsigned underflow)
        // Borrow occurs when we need to "borrow" from a higher bit
        let did_borrow = u16::from(accumulator) < (u16::from(value) + u16::from(1 - carry));
        let did_carry = !did_borrow; // Carry is inverse of borrow in SBC

        // Calculate overflow: occurs when signs of A and M are different,
        // and the result has a different sign than A
        let overflow = (accumulator ^ value) & (accumulator ^ temp_result) & 0x80 != 0;

        // Calculate other flags
        let negative = (temp_result & 0x80) != 0;
        let zero = temp_result == 0;

        ArithmeticOutput {
            result: temp_result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// NMOS 6502 SBC implementation in decimal mode (BCD)
    ///
    /// - Binary Coded Decimal (BCD) subtraction using 4-bit decimal digits
    /// - Each nibble represents a digit from 0-9
    /// - In decimal mode: N and Z flags are unreliable/undefined (NMOS behavior)
    /// - V flag calculated from binary result (even in decimal mode)
    ///
    /// # References
    ///
    /// - [6502.org SBC documentation](http://www.6502.org/tutorials/decimal_mode.html)
    /// - [NESdev 6502 reference](https://www.nesdev.org/obelisk-6502-guide/reference.html#SBC)
    fn sbc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Perform binary subtraction first for overflow calculation
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_sub(value).wrapping_sub(1 - carry);

        // Decimal mode: treat each nibble as a decimal digit (0-9)
        let mut low_nibble = (accumulator & 0x0f)
            .wrapping_sub(value & 0x0f)
            .wrapping_sub(1 - carry);
        let mut high_nibble = (accumulator >> 4).wrapping_sub(value >> 4);
        let mut borrow = false;

        // If low nibble underflowed (bit 4 set), correct it and set borrow
        if (low_nibble & 0x10) != 0 {
            low_nibble = (low_nibble.wrapping_add(10)) & 0x0f;
            borrow = true;
        }

        // Subtract borrow from high nibble
        high_nibble = high_nibble.wrapping_sub(u8::from(borrow));

        // If high nibble underflowed, correct it and set final borrow
        if (high_nibble & 0x10) != 0 {
            high_nibble = (high_nibble.wrapping_add(10)) & 0x0f;
            borrow = true;
        } else {
            borrow = false;
        }

        let result = (high_nibble << 4) | low_nibble;
        let did_carry = !borrow; // Carry is inverse of borrow

        // Calculate overflow from binary result (even in decimal mode)
        let overflow = (accumulator ^ value) & (accumulator ^ temp_result) & 0x80 != 0;

        // Calculate other flags from final result
        let negative = (result & 0x80) != 0;
        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }
}

/// The Ricoh variant which has no decimal mode. This is what to use if you want
/// to emulate the NES.
#[derive(Copy, Clone, Debug, Default)]
pub struct Ricoh2a03;

impl crate::Variant for Ricoh2a03 {
    fn decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
        // It's the same as on NMOS, but doesn't support decimal mode.
        match Nmos6502::decode(opcode) {
            Some((Instruction::ADC, addressing_mode)) => {
                Some((Instruction::ADCnd, addressing_mode))
            }
            Some((Instruction::SBC, addressing_mode)) => {
                Some((Instruction::SBCnd, addressing_mode))
            }
            other_instruction => other_instruction,
        }
    }

    /// `Ricoh2A03` (NES) ADC implementation in binary mode
    ///
    /// Same as NMOS 6502 ADC for binary.
    ///
    /// - Always performs binary arithmetic
    /// - All flags (N, Z, V, C) behave consistently like binary mode
    /// - Used in Nintendo Entertainment System (NES) and Famicom
    ///
    /// # References
    /// - [NESdev Ricoh2A03 reference](https://www.nesdev.org/wiki/CPU)
    #[inline]
    fn adc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Ricoh2a03 behaves the same as NMOS 6502 for ADC
        Nmos6502::adc_binary(accumulator, value, carry_set)
    }

    /// `Ricoh2A03` (NES) ADC implementation - decimal mode not supported
    ///
    /// The `Ricoh2A03` removed the decimal mode circuitry entirely to save cost,
    /// so BCD operations are not supported. This method calls `adc_binary` instead.
    ///
    /// # References
    /// - [NESdev Ricoh2A03 reference](https://www.nesdev.org/wiki/CPU)
    #[inline]
    fn adc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        Self::adc_binary(accumulator, value, carry_set)
    }

    /// `Ricoh2A03` (NES) SBC implementation in binary mode
    ///
    /// Same as NMOS 6502 SBC for binary.
    ///
    /// - Always performs binary subtraction
    /// - All flags (N, Z, V, C) behave consistently like binary mode
    /// - Used in Nintendo Entertainment System (NES) and Famicom
    ///
    /// # References
    /// - [NESdev Ricoh2A03 reference](https://www.nesdev.org/wiki/CPU)
    #[inline]
    fn sbc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Ricoh2a03 behaves the same as NMOS 6502 for SBC
        Nmos6502::sbc_binary(accumulator, value, carry_set)
    }

    /// `Ricoh2A03` (NES) SBC implementation - decimal mode not supported
    ///
    /// The `Ricoh2A03` removed the decimal mode circuitry entirely to save cost,
    /// so BCD operations are not supported. This method calls `sbc_binary` instead.
    ///
    /// # References
    /// - [NESdev Ricoh2A03 reference](https://www.nesdev.org/wiki/CPU)
    #[inline]
    fn sbc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Ricoh2a03 (NES) has no decimal mode, so always use binary arithmetic
        Self::sbc_binary(accumulator, value, carry_set)
    }
}

/// Emulates some very early 6502s which have no ROR instruction. This one is used in very early
/// KIM-1s.
#[derive(Copy, Clone, Debug, Default)]
pub struct RevisionA;

impl crate::Variant for RevisionA {
    fn decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
        // It's the same as on NMOS, but has no ROR instruction.
        match Nmos6502::decode(opcode) {
            Some((Instruction::ROR, _)) => None,
            other_instruction => other_instruction,
        }
    }

    /// Revision A 6502 ADC implementation in binary mode
    ///
    /// - Identical ADC behavior to NMOS 6502
    /// - Found in very early 6502 processors (KIM-1, etc.)
    ///
    /// # References:
    ///
    /// - [Rev. A 6502 (Pre-June 1976) "ROR Bug"](https://www.masswerk.at/6502/6502_instruction_set.html#ror-bug)
    #[inline]
    fn adc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // RevisionA behaves the same as NMOS 6502 for ADC
        Nmos6502::adc_binary(accumulator, value, carry_set)
    }

    /// Revision A 6502 ADC implementation in decimal mode (BCD)
    ///
    /// - Identical ADC behavior to NMOS 6502
    /// - Supports decimal (BCD) mode with same flag behavior as NMOS
    /// - Found in very early 6502 processors (KIM-1, etc.)
    ///
    /// # Difference from NMOS 6502
    ///
    /// `RevisionA` lacks the ROR (Rotate Right) instruction entirely, but ADC
    /// behavior is identical to the standard NMOS 6502.
    ///
    /// # References:
    ///
    /// - [Rev. A 6502 (Pre-June 1976) "ROR Bug"](https://www.masswerk.at/6502/6502_instruction_set.html#ror-bug)
    #[inline]
    fn adc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // RevisionA behaves the same as NMOS 6502 for ADC
        Nmos6502::adc_decimal(accumulator, value, carry_set)
    }

    /// Revision A 6502 SBC implementation in binary mode
    ///
    /// - Identical SBC behavior to NMOS 6502
    /// - Found in very early 6502 processors (KIM-1, etc.)
    #[inline]
    fn sbc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // RevisionA behaves the same as NMOS 6502 for SBC
        Nmos6502::sbc_binary(accumulator, value, carry_set)
    }

    /// Revision A 6502 SBC implementation in decimal mode (BCD)
    ///
    /// - Identical SBC behavior to NMOS 6502
    /// - Supports decimal (BCD) mode with same flag behavior as NMOS
    /// - Found in very early 6502 processors (KIM-1, etc.)
    #[inline]
    fn sbc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // RevisionA behaves the same as NMOS 6502 for SBC
        Nmos6502::sbc_decimal(accumulator, value, carry_set)
    }
}

/// Configurable emulation of a 65C02-family CMOS microprocessor.
///
/// The 65C02 is a CMOS version of the NMOS 6502, which offers several
/// improvements while maintaining backward compatibility.
///
/// Two const parameters select which optional extension sets are present:
///
/// - `ROCKWELL` — enables the Rockwell bit-manipulation instructions
///   (BBR, BBS, RMB, SMB). Present on the Rockwell R65C02 (1987) and
///   WDC W65C02S/-SB, but absent from the original WDC 65C02.
/// - `WDC` — enables the WDC low-power instructions (WAI, STP).
///   Present on the WDC W65C02 (1990) and later, but absent from the
///   Rockwell R65C02.
///
/// # Key Improvements Over NMOS 6502
///
/// ## Bug Fixes
/// - The NMOS 6502 had a bug when JMP (addr) crossed a page boundary.
///   The 65C02 correctly fetches both bytes of the target address.
/// - The N and Z flags now work correctly in decimal
///   (BCD) mode, whereas they were undefined in the NMOS 6502.
/// - The BRK instruction now properly clears the decimal
///   flag, preventing issues in interrupt handlers.
///
/// ## New Instructions
/// - `BRA`: Branch Always (unconditional relative branch)
/// - `PHX/PHY`: Push X/Y registers onto stack
/// - `PLX/PLY`: Pull X/Y registers from stack
/// - `STZ`: Store Zero to memory
/// - `TRB/TSB`: Test and Reset/Set memory Bits
/// - `INC A/DEC A`: Increment/Decrement Accumulator
///
/// ## New Addressing Modes
/// - **Zero Page Indirect**: `(zp)` for ORA, AND, EOR, ADC, STA, LDA, CMP, SBC
/// - **Absolute Indexed Indirect**: `JMP (abs,X)` - indexed indirect jump
/// - **Indexed addressing for BIT**: `BIT zp,X` and `BIT abs,X`
/// - **Immediate addressing for BIT**: `BIT #imm`
///
/// # References
/// - [WDC 65C02 Datasheet](http://www.westerndesigncenter.com/wdc/documentation/w65c02s.pdf)
/// - [65C02 Wikipedia Article](https://en.wikipedia.org/wiki/WDC_65C02)
#[derive(Copy, Clone, Debug, Default)]
pub struct Mos65C02<const ROCKWELL: bool, const WDC: bool>;

/// Backward-compatible alias for `Mos65C02<false, true>`, an early W65C02.
pub type Cmos6502 = Mos65C02<false, true>;
/// Value constant for backward compatibility with unit struct.
#[allow(non_upper_case_globals)]
pub const Cmos6502: Cmos6502 = Cmos6502 {};

/// Alias for a modern W65C02S, with both Rockwell and WDC extensions.
pub type W65C02S = Mos65C02<true, true>;
/// Value constant to avoid braces.
pub const W65C02S: W65C02S = W65C02S {};

/// Decode opcodes shared by all 65C02 variants (base CMOS instruction set).
const fn cmos_base_decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
    match opcode {
        0x00 => Some((Instruction::BRKcld, AddressingMode::Implied)),
        0x02 => Some((Instruction::NOPI, AddressingMode::Immediate)),
        0x22 => Some((Instruction::NOPI, AddressingMode::Immediate)),
        0x42 => Some((Instruction::NOPI, AddressingMode::Immediate)),
        0x62 => Some((Instruction::NOPI, AddressingMode::Immediate)),
        0x03 | 0x13 | 0x23 | 0x33 | 0x43 | 0x53 | 0x63 | 0x73 | 0x83 | 0x93 | 0xa3 | 0xb3
        | 0xc3 | 0xd3 | 0xe3 | 0xf3 | 0x0b | 0x1b | 0x2b | 0x3b | 0x4b | 0x5b | 0x6b | 0x7b
        | 0x8b | 0x9b | 0xab | 0xbb | 0xeb | 0xfb => {
            Some((Instruction::NOP1, AddressingMode::Implied))
        }
        0x5c => Some((Instruction::NOPAX8, AddressingMode::AbsoluteX)),
        0x1a => Some((Instruction::INC, AddressingMode::Accumulator)),
        0x3a => Some((Instruction::DEC, AddressingMode::Accumulator)),
        0x6c => Some((Instruction::JMP, AddressingMode::Indirect)),
        0x7c => Some((Instruction::JMP, AddressingMode::AbsoluteIndexedIndirect)),
        0x80 => Some((Instruction::BRA, AddressingMode::Relative)),
        0x64 => Some((Instruction::STZ, AddressingMode::ZeroPage)),
        0x74 => Some((Instruction::STZ, AddressingMode::ZeroPageX)),
        0x9c => Some((Instruction::STZ, AddressingMode::Absolute)),
        0x9e => Some((Instruction::STZ, AddressingMode::AbsoluteX)),
        0x7a => Some((Instruction::PLY, AddressingMode::Implied)),
        0xfa => Some((Instruction::PLX, AddressingMode::Implied)),
        0x5a => Some((Instruction::PHY, AddressingMode::Implied)),
        0xda => Some((Instruction::PHX, AddressingMode::Implied)),
        0x04 => Some((Instruction::TSB, AddressingMode::ZeroPage)),
        0x14 => Some((Instruction::TRB, AddressingMode::ZeroPage)),
        0x0c => Some((Instruction::TSB, AddressingMode::Absolute)),
        0x1c => Some((Instruction::TRB, AddressingMode::Absolute)),
        0x12 => Some((Instruction::ORA, AddressingMode::ZeroPageIndirect)),
        0x32 => Some((Instruction::AND, AddressingMode::ZeroPageIndirect)),
        0x34 => Some((Instruction::BIT, AddressingMode::ZeroPageX)),
        0x3c => Some((Instruction::BIT, AddressingMode::AbsoluteX)),
        0x52 => Some((Instruction::EOR, AddressingMode::ZeroPageIndirect)),
        0x72 => Some((Instruction::ADC, AddressingMode::ZeroPageIndirect)),
        0x92 => Some((Instruction::STA, AddressingMode::ZeroPageIndirect)),
        0xb2 => Some((Instruction::LDA, AddressingMode::ZeroPageIndirect)),
        0xd2 => Some((Instruction::CMP, AddressingMode::ZeroPageIndirect)),
        0xf2 => Some((Instruction::SBC, AddressingMode::ZeroPageIndirect)),
        0x89 => Some((Instruction::BIT, AddressingMode::Immediate)),
        _ => None,
    }
}

/// Decode WDC low-power extension opcodes (WAI, STP).
const fn wdc_decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
    match opcode {
        0xcb => Some((Instruction::WAI, AddressingMode::Implied)),
        0xdb => Some((Instruction::STP, AddressingMode::Implied)),
        _ => None,
    }
}

/// Decode Rockwell bit-manipulation extension opcodes (BBR, BBS, RMB, SMB).
const fn rockwell_decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
    let bit = (opcode >> 4) & 0x07;
    if opcode & 0x0f == 0x0f {
        // BBR/BBS - Branch on Bit Reset/Set (low nibble 0xf, high nibble < 8 for BBR, BBS otherwise)
        if opcode < 0x80 {
            Some((Instruction::BBR(bit), AddressingMode::ZeroPageRelative))
        } else {
            Some((Instruction::BBS(bit), AddressingMode::ZeroPageRelative))
        }
    } else if opcode & 0x0f == 0x07 {
        // RMB/SMB - Reset/Set Memory Bit (low nibble 0x7, high nibble < 8 for RMB, SMB otherwise)
        if opcode < 0x80 {
            Some((Instruction::RMB(bit), AddressingMode::ZeroPage))
        } else {
            Some((Instruction::SMB(bit), AddressingMode::ZeroPage))
        }
    } else {
        None
    }
}

impl<const ROCKWELL: bool, const WDC: bool> crate::Variant for Mos65C02<ROCKWELL, WDC> {
    fn decode(opcode: u8) -> Option<(Instruction, AddressingMode)> {
        cmos_base_decode(opcode)
            .or_else(|| if WDC { wdc_decode(opcode) } else { None })
            .or_else(|| {
                if ROCKWELL {
                    rockwell_decode(opcode)
                } else {
                    None
                }
            })
            .or_else(|| Nmos6502::decode(opcode))
    }

    /// 65C02 (CMOS) ADC implementation in binary mode
    ///
    /// - Standard binary arithmetic
    /// - All flags calculated from binary result
    ///
    /// # References
    ///
    /// - [65C02 Programming Manual](http://www.westerndesigncenter.com/wdc/documentation/w65c02s.pdf)
    /// - [6502.org CMOS differences](http://www.6502.org/tutorials/65c02opcodes.html)
    fn adc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Binary addition with carry detection
        let carry = u8::from(carry_set);
        let result_16 = u16::from(accumulator) + u16::from(value) + u16::from(carry);
        let did_carry = result_16 > 0xFF;
        #[allow(clippy::cast_possible_truncation)]
        let result = result_16 as u8;

        // Calculate overflow from binary result
        let overflow = (!(accumulator ^ value) & (accumulator ^ result)) & 0x80 != 0;

        // Calculate other flags
        let negative = (result & 0x80) != 0;
        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// 65C02 (CMOS) ADC implementation in decimal mode (BCD)
    ///
    /// - Supports decimal (BCD) mode with **corrected flag behavior**
    /// - In decimal mode: N and Z flags are **reliable** (calculated from BCD result)
    /// - In decimal mode: V flag behavior still undefined but calculated from binary result
    /// - In decimal mode: **Extra cycle** consumed (not implemented in this emulator yet)
    ///
    /// # Difference from NMOS 6502
    ///
    /// The 65C02 fixed the unreliable N and Z flags in decimal mode. These flags
    /// now correctly reflect the BCD result, making decimal arithmetic more predictable.
    ///
    /// # References
    ///
    /// - [65C02 Programming Manual](http://www.westerndesigncenter.com/wdc/documentation/w65c02s.pdf)
    /// - [6502.org CMOS differences](http://www.6502.org/tutorials/65c02opcodes.html)
    fn adc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Perform binary addition first for overflow calculation
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_add(value).wrapping_add(carry);

        // Decimal mode: treat each nibble as a decimal digit (0-9)
        let mut low_nibble = (accumulator & 0x0f)
            .wrapping_add(value & 0x0f)
            .wrapping_add(carry);

        let mut high_nibble = (accumulator >> 4).wrapping_add(value >> 4);
        let mut carry_to_high = false;

        // If low nibble is > 9, adjust it and carry to high nibble
        if low_nibble > 9 {
            low_nibble = low_nibble.wrapping_sub(10);
            carry_to_high = true;
        }

        high_nibble = high_nibble.wrapping_add(u8::from(carry_to_high));

        // Adjust high nibble if it's > 9 and set final carry flag
        let (adjusted_high, did_carry) = if high_nibble > 9 {
            (high_nibble.wrapping_sub(10), true)
        } else {
            (high_nibble, false)
        };

        let result = (adjusted_high << 4) | (low_nibble & 0x0f);

        // Calculate overflow from binary result (even in decimal mode)
        let overflow = (!(accumulator ^ value) & (accumulator ^ temp_result)) & 0x80 != 0;

        // On 65C02, N and Z flags are valid in decimal mode (calculated from BCD result)
        // V flag behavior is still undocumented but calculated from binary result
        let negative = (result & 0x80) != 0;
        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// 65C02 (CMOS) SBC implementation in binary mode
    ///
    /// - Standard binary subtraction with borrow handling
    /// - All flags calculated from binary result
    ///
    /// # References
    ///
    /// - [65C02 Programming Manual](http://www.westerndesigncenter.com/wdc/documentation/w65c02s.pdf)
    /// - [6502.org CMOS differences](http://www.6502.org/tutorials/65c02opcodes.html)
    fn sbc_binary(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Binary subtraction with borrow handling
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_sub(value).wrapping_sub(1 - carry);

        // Check for borrow (unsigned underflow)
        let did_borrow = u16::from(accumulator) < (u16::from(value) + u16::from(1 - carry));
        let did_carry = !did_borrow; // Carry is inverse of borrow in SBC

        // Calculate overflow
        let overflow = (accumulator ^ value) & (accumulator ^ temp_result) & 0x80 != 0;

        // Calculate other flags
        let negative = (temp_result & 0x80) != 0;
        let zero = temp_result == 0;

        ArithmeticOutput {
            result: temp_result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    /// 65C02 (CMOS) SBC implementation in decimal mode (BCD)
    ///
    /// - Supports decimal (BCD) mode with **corrected flag behavior**
    /// - In decimal mode: N and Z flags are **reliable** (calculated from BCD result)
    /// - V flag calculated from binary result (even in decimal mode)
    /// - In decimal mode: **Extra cycle** consumed (not implemented in this emulator yet)
    ///
    /// # Difference from NMOS 6502
    ///
    /// The 65C02 fixed the unreliable N and Z flags in decimal mode. These flags
    /// now correctly reflect the BCD result, making decimal arithmetic more predictable.
    ///
    /// # References
    ///
    /// - [65C02 Programming Manual](http://www.westerndesigncenter.com/wdc/documentation/w65c02s.pdf)
    /// - [6502.org CMOS differences](http://www.6502.org/tutorials/65c02opcodes.html)
    fn sbc_decimal(accumulator: u8, value: u8, carry_set: bool) -> ArithmeticOutput {
        // Perform binary subtraction first for overflow calculation
        let carry = u8::from(carry_set);
        let temp_result = accumulator.wrapping_sub(value).wrapping_sub(1 - carry);

        // Decimal mode: treat each nibble as a decimal digit (0-9)
        let mut low_nibble = (accumulator & 0x0f)
            .wrapping_sub(value & 0x0f)
            .wrapping_sub(1 - carry);
        let mut high_nibble = (accumulator >> 4).wrapping_sub(value >> 4);
        let mut borrow = false;

        // If low nibble underflowed (bit 4 set), correct it and set borrow
        if (low_nibble & 0x10) != 0 {
            low_nibble = (low_nibble.wrapping_add(10)) & 0x0f;
            borrow = true;
        }

        // Subtract borrow from high nibble
        high_nibble = high_nibble.wrapping_sub(u8::from(borrow));

        // If high nibble underflowed, correct it and set final borrow
        if (high_nibble & 0x10) != 0 {
            high_nibble = (high_nibble.wrapping_add(10)) & 0x0f;
            borrow = true;
        } else {
            borrow = false;
        }

        let result = (high_nibble << 4) | low_nibble;
        let did_carry = !borrow; // Carry is inverse of borrow

        // Calculate overflow from binary result (even in decimal mode)
        let overflow = (accumulator ^ value) & (accumulator ^ temp_result) & 0x80 != 0;

        // On 65C02, N and Z flags are valid in decimal mode (calculated from BCD result)
        // V flag behavior is still undocumented but calculated from binary result
        let negative = (result & 0x80) != 0;
        let zero = result == 0;

        ArithmeticOutput {
            result,
            did_carry,
            overflow,
            negative,
            zero,
        }
    }

    fn penalty_cycles_for_decimal_mode() -> u8 {
        1 // 65C02 adds 1 cycle for ADC/SBC in decimal mode
    }

    fn penalty_cycles_for_indirect_jmp() -> u8 {
        1 // 65C02 takes 6 cycles for JMP (indirect) instead of 5
    }
}