All files / src 6502.opcodes.js

95.17% Statements 473/497
91.83% Branches 326/355
100% Functions 44/44
95.66% Lines 441/461

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        12233x 12233x 6235x 6235x 6235x 3236x   2999x     5998x 5998x 5998x 2999x   2999x     12233x 12233x       598x 268x   330x       598x 330x         92288x 92288x 92288x 92288x       463764x 254272x 254272x   463764x 463764x 463764x 185469x 185469x 185469x 278295x       387946x       75818x       97465x       59633x   59633x 21457x 59633x 59633x       34203x 34203x 34203x 34203x 34203x       31396x 31396x       8442x 8442x       75818x 75818x 75818x       14468x 112x 112x   14356x 136x   14220x         90113x 90113x 90113x 90113x 302103x 103914x 103914x   198189x 89290x 50332x 50332x   38958x   89290x   198189x 198189x   90113x 90113x 41432x 41432x   48681x     90113x 708948x       14295x           14295x 14295x 14295x 14295x 14295x 14295x   14295x 71475x 44130x 44130x           212889x       14295x                     63698x   6667x   268x   268x   268x   268x   268x   268x   268x   268x   2175x   1340x   1340x   1907x   804x   804x   1103x           1103x           268x   268x   268x   268x   2175x   2412x   629x     31x   598x         1340x   1340x             1340x   1340x   2175x   2175x   2175x   2175x         804x         804x         268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   268x   31x   31x   268x   268x   31x   31x   268x         268x                             268x                   567x       62x           62x           31x   124x           948x   237x       1659x           237x   237x   1422x         237x         1659x           1659x           474x         237x         237x   1659x           237x         1659x           237x         474x           237x           1659x                         88x                         88x                         88x                 88x             114x 114x 114x 24016x 3534x 3534x   20482x     114x     38x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             38x                                                                                                                                                                                                                                                                                                                                                                           38x                                                                       38x       268x 268x 268x       24211x 24211x       11330x 11330x 11330x 2x 2x   11330x 11330x 11330x 46x   11284x 11284x 11330x 9412x   1872x 11330x 11330x 11330x 11330x 787x 787x 787x   1872x   345x   842x 842x 842x     81x 81x     512x   17x 17x             51x   16x 16x 16x     1x 1x 1x             1x 1x 1x     6x       5x                                     210x 210x   210x 210x 210x 210x 13440x 13440x 13440x 23698x 10662x 10662x 10662x 947x   10662x 308x 15x 15x   308x   10354x     210x           63698x 63698x 63698x 63698x 63698x   63698x 63698x   63698x     8246x 8246x 8246x 8246x 8246x     2175x     176x 176x 176x 176x 176x       176x 176x 176x         16708x 8504x 8504x   8204x 8204x   16708x 14564x 14564x 6298x     16708x 16708x 16708x     8390x 8390x 8390x 6782x 6782x   8390x 8390x   8390x       12182x 12182x 12182x 12182x 12182x 12182x 6215x   527x     5688x   6215x 5967x 4452x   186x       186x 186x     186x     4266x 4266x 4266x   1515x 1515x     93x   93x     1422x 1422x   948x       12182x 12182x 12182x     6060x     6060x     6060x 6060x 6060x 6060x     1134x 1134x 1134x 1134x 1134x     4040x 4040x 4040x 4040x 4040x 4040x 4040x 3535x 3535x   4040x 4040x 4040x     4040x 4040x 4040x 4040x 4040x 4040x 4040x 4040x 4040x   2113x 2113x 1896x   217x   2113x 1927x   1422x 1422x 1422x 505x 505x         31x     474x 474x   237x       4040x 4040x 4040x     268x 268x 268x 31x   237x   268x 268x 268x 268x 268x 268x     31x 31x 31x 31x 31x 31x 31x 31x       248x 248x 248x 248x 248x 248x 248x 248x 248x 248x               68608x 68608x                                 268x 268x 68608x 68608x 68608x 63698x           63698x 4910x 68608x 68608x   268x 1203091x         1x       1x                                                                                 1x 1x   1x             268x 268x       268x   268x                 237x       20x       11x    
import { signExtend } from "./binary.js";
import { hexbyte, hexword } from "./hex.js";
 
function rotate(left, logical) {
    const lines = [];
    if (!left) {
        if (!logical) lines.push("const newTopBit = cpu.p.c ? 0x80 : 0x00;");
        lines.push("cpu.p.c = !!(REG & 0x01);");
        if (logical) {
            lines.push("REG >>>= 1;");
        } else {
            lines.push("REG = (REG >>> 1) | newTopBit;");
        }
    } else {
        if (!logical) lines.push("const newBotBit = cpu.p.c ? 0x01 : 0x00;");
        lines.push("cpu.p.c = !!(REG & 0x80);");
        if (logical) {
            lines.push("REG = (REG << 1) & 0xff;");
        } else {
            lines.push("REG = ((REG << 1) & 0xff) | newBotBit;");
        }
    }
    lines.push("cpu.p.setzn(REG);");
    return lines;
}
 
function pull(reg) {
    if (reg === "p") {
        return ["cpu.p.setFromByte(cpu.pull());"];
    }
    return [`cpu.${reg} = cpu.p.setzn(cpu.pull());`];
}
 
function push(reg) {
    if (reg === "p") return "cpu.push(cpu.p.asByte());";
    return `cpu.push(cpu.${reg});`;
}
 
class InstructionGen {
    constructor(is65c12, cycleAccurate = true) {
        this.is65c12 = is65c12;
        this.cycleAccurate = cycleAccurate;
        this.ops = {};
        this.cycle = 0;
    }
 
    appendOrPrepend(combiner, cycle, op, exact, addr) {
        if (op === undefined) {
            op = cycle;
            cycle = this.cycle;
        }
        exact = exact || false;
        if (typeof op === "string") op = [op];
        if (this.ops[cycle]) {
            this.ops[cycle].op = combiner(this.ops[cycle].op, op);
            if (exact) this.ops[cycle].exact = true;
            if (!this.ops[cycle].addr) this.ops[cycle].addr = addr;
        } else this.ops[cycle] = { op: op, exact: exact, addr: addr };
    }
 
    append(cycle, op, exact, addr) {
        this.appendOrPrepend((lhs, rhs) => lhs.concat(rhs), cycle, op, exact, addr);
    }
 
    prepend(cycle, op, exact, addr) {
        this.appendOrPrepend((lhs, rhs) => rhs.concat(lhs), cycle, op, exact, addr);
    }
 
    tick(cycles) {
        this.cycle += cycles || 1;
    }
 
    readOp(addr, reg, spurious) {
        this.cycle++;
        let op;
        if (reg) op = `${reg} = cpu.readmem(${addr});`;
        else op = `cpu.readmem(${addr});`;
        if (spurious) op += " // spurious";
        this.append(this.cycle, op, true, addr);
    }
 
    writeOp(addr, reg, spurious) {
        this.cycle++;
        let op = `cpu.writemem(${addr}, ${reg});`;
        if (spurious) op += " // spurious";
        this.append(this.cycle, op, true, addr);
        this.ops[this.cycle].isWrite = true;
    }
 
    zpReadOp(addr, reg) {
        this.cycle++;
        this.append(this.cycle, `${reg} = cpu.readmemZpStack(${addr});`, false);
    }
 
    zpWriteOp(addr, reg) {
        this.cycle++;
        this.append(this.cycle, `cpu.writememZpStack(${addr}, ${reg});`, true);
    }
 
    render(startCycle) {
        Iif (this.cycle < 2) this.cycle = 2;
        this.prepend(this.cycle - 1, "cpu.checkInt();", true);
        return this.renderInternal(startCycle);
    }
 
    spuriousOp(addr, reg) {
        if (!this.cycleAccurate) {
            this.cycle++;
            return;
        }
        if (this.is65c12) {
            this.readOp(addr, "", true);
        } else {
            this.writeOp(addr, reg, true);
        }
    }
 
    renderInternal(startCycle) {
        startCycle = startCycle || 0;
        let toSkip = 0;
        let out = [];
        for (let i = startCycle; i < this.cycle; ++i) {
            if (!this.ops[i]) {
                toSkip++;
                continue;
            }
            if (this.cycleAccurate && toSkip && this.ops[i].exact) {
                if (this.ops[i].addr) {
                    const isWrite = this.ops[i].isWrite ? "true" : "false";
                    out.push(`cpu.polltimeAddr(${toSkip}, ${this.ops[i].addr}, ${isWrite});`);
                } else {
                    out.push(`cpu.polltime(${toSkip});`);
                }
                toSkip = 0;
            }
            out = out.concat(this.ops[i].op);
            toSkip++;
        }
        Eif (toSkip) {
            if (this.cycleAccurate && this.ops[this.cycle] && this.ops[this.cycle].addr) {
                const isWrite = this.ops[this.cycle].isWrite ? "true" : "false";
                out.push(`cpu.polltimeAddr(${toSkip}, ${this.ops[this.cycle].addr}, ${isWrite});`);
            } else {
                out.push(`cpu.polltime(${toSkip});`);
            }
        }
        if (this.ops[this.cycle]) out = out.concat(this.ops[this.cycle].op);
        return out.filter((l) => l);
    }
 
    split(condition) {
        return new SplitInstruction(this, condition, this.is65c12, this.cycleAccurate);
    }
}
 
class SplitInstruction {
    constructor(preamble, condition, is65c12, cycleAccurate = true) {
        this.preamble = preamble;
        this.condition = condition;
        this.ifTrue = new InstructionGen(is65c12, cycleAccurate);
        this.ifTrue.tick(preamble.cycle);
        this.ifFalse = new InstructionGen(is65c12, cycleAccurate);
        this.ifFalse.tick(preamble.cycle);
 
        ["append", "prepend", "readOp", "writeOp", "spuriousOp"].forEach((op) => {
            this[op] = (...args) => {
                this.ifTrue[op](...args);
                this.ifFalse[op](...args);
            };
        });
    }
 
    indent(lines) {
        return lines.map((line) => `  ${line}`);
    }
 
    render() {
        return this.preamble
            .renderInternal()
            .concat(`if (${this.condition}) {`)
            .concat(this.indent(this.ifTrue.render(this.preamble.cycle)))
            .concat("} else {")
            .concat(this.indent(this.ifFalse.render(this.preamble.cycle)))
            .concat("}");
    }
}
 
function getOp(op, arg) {
    switch (op) {
        case "NOP":
            return { op: "", read: arg !== undefined };
        case "BRK":
            return { op: "cpu.brk(false);" };
        case "CLC":
            return { op: "cpu.p.c = false;" };
        case "SEC":
            return { op: "cpu.p.c = true;" };
        case "CLD":
            return { op: "cpu.p.d = false;" };
        case "SED":
            return { op: "cpu.p.d = true;" };
        case "CLI":
            return { op: "cpu.p.i = false;" };
        case "SEI":
            return { op: "cpu.p.i = true;" };
        case "CLV":
            return { op: "cpu.p.v = false;" };
        case "LDA":
            return { op: ["cpu.a = cpu.p.setzn(REG);"], read: true };
        case "LDX":
            return { op: ["cpu.x = cpu.p.setzn(REG);"], read: true };
        case "LDY":
            return { op: ["cpu.y = cpu.p.setzn(REG);"], read: true };
        case "STA":
            return { op: "REG = cpu.a;", write: true };
        case "STX":
            return { op: "REG = cpu.x;", write: true };
        case "STY":
            return { op: "REG = cpu.y;", write: true };
        case "INC":
            return {
                op: ["REG = cpu.p.setzn(REG + 1);"],
                read: true,
                write: true,
            };
        case "DEC":
            return {
                op: ["REG = cpu.p.setzn(REG - 1);"],
                read: true,
                write: true,
            };
        case "INX":
            return { op: ["cpu.x = cpu.p.setzn(cpu.x + 1);"] };
        case "INY":
            return { op: ["cpu.y = cpu.p.setzn(cpu.y + 1);"] };
        case "DEX":
            return { op: ["cpu.x = cpu.p.setzn(cpu.x - 1);"] };
        case "DEY":
            return { op: ["cpu.y = cpu.p.setzn(cpu.y - 1);"] };
        case "ADC":
            return { op: "cpu.adc(REG);", read: true };
        case "SBC":
            return { op: "cpu.sbc(REG);", read: true };
        case "BIT":
            if (arg === "imm") {
                // According to: http://forum.6502.org/viewtopic.php?f=2&t=2241&p=27243#p27239
                // the v and n flags are unaffected by BIT #xx
                return { op: "cpu.p.z = !(cpu.a & REG);", read: true };
            }
            return {
                op: ["cpu.p.z = !(cpu.a & REG);", "cpu.p.v = !!(REG & 0x40);", "cpu.p.n = !!(REG & 0x80);"],
                read: true,
            };
        case "ROL":
            return { op: rotate(true, false), read: true, write: true, rotate: true };
        case "ROR":
            return {
                op: rotate(false, false),
                read: true,
                write: true,
                rotate: true,
            };
        case "ASL":
            return { op: rotate(true, true), read: true, write: true, rotate: true };
        case "LSR":
            return { op: rotate(false, true), read: true, write: true, rotate: true };
        case "EOR":
            return { op: ["cpu.a = cpu.p.setzn(cpu.a ^ REG);"], read: true };
        case "AND":
            return { op: ["cpu.a = cpu.p.setzn(cpu.a & REG);"], read: true };
        case "ORA":
            return { op: ["cpu.a = cpu.p.setzn(cpu.a | REG);"], read: true };
        case "CMP":
            return {
                op: ["cpu.p.setzn(cpu.a - REG);", "cpu.p.c = cpu.a >= REG;"],
                read: true,
            };
        case "CPX":
            return {
                op: ["cpu.p.setzn(cpu.x - REG);", "cpu.p.c = cpu.x >= REG;"],
                read: true,
            };
        case "CPY":
            return {
                op: ["cpu.p.setzn(cpu.y - REG);", "cpu.p.c = cpu.y >= REG;"],
                read: true,
            };
        case "TXA":
            return { op: ["cpu.a = cpu.p.setzn(cpu.x);"] };
        case "TAX":
            return { op: ["cpu.x = cpu.p.setzn(cpu.a);"] };
        case "TXS":
            return { op: "cpu.s = cpu.x;" };
        case "TSX":
            return { op: ["cpu.x = cpu.p.setzn(cpu.s);"] };
        case "TYA":
            return { op: ["cpu.a = cpu.p.setzn(cpu.y);"] };
        case "TAY":
            return { op: ["cpu.y = cpu.p.setzn(cpu.a);"] };
        case "BEQ":
            return { op: "cpu.branch(cpu.p.z);" };
        case "BNE":
            return { op: "cpu.branch(!cpu.p.z);" };
        case "BCS":
            return { op: "cpu.branch(cpu.p.c);" };
        case "BCC":
            return { op: "cpu.branch(!cpu.p.c);" };
        case "BMI":
            return { op: "cpu.branch(cpu.p.n);" };
        case "BPL":
            return { op: "cpu.branch(!cpu.p.n);" };
        case "BVS":
            return { op: "cpu.branch(cpu.p.v);" };
        case "BVC":
            return { op: "cpu.branch(!cpu.p.v);" };
        case "PLA":
            return { op: pull("a"), extra: 3 };
        case "PLP":
            return { op: pull("p"), extra: 3 };
        case "PLX":
            return { op: pull("x"), extra: 3 };
        case "PLY":
            return { op: pull("y"), extra: 3 };
        case "PHA":
            return { op: push("a"), extra: 2 };
        case "PHP":
            return { op: push("p"), extra: 2 };
        case "PHX":
            return { op: push("x"), extra: 2 };
        case "PHY":
            return { op: push("y"), extra: 2 };
        case "RTS":
            return {
                op: ["let temp = cpu.pull();", "temp |= cpu.pull() << 8;", "cpu.pc = (temp + 1) & 0xffff;"],
                extra: 5,
            };
        case "RTI":
            return {
                preop: [
                    "let temp = cpu.pull();",
                    "cpu.p.c = !!(temp & 0x01);",
                    "cpu.p.z = !!(temp & 0x02);",
                    "cpu.p.i = !!(temp & 0x04);",
                    "cpu.p.d = !!(temp & 0x08);",
                    "cpu.p.v = !!(temp & 0x40);",
                    "cpu.p.n = !!(temp & 0x80);",
                    "temp = cpu.pull();",
                    "cpu.pc = temp | (cpu.pull() << 8);",
                ],
                extra: 5,
            };
        case "JSR":
            return {
                op: [
                    "const pushAddr = cpu.pc - 1;",
                    "cpu.push(pushAddr >>> 8);",
                    "cpu.push(pushAddr & 0xff);",
                    "cpu.pc = addr;",
                ],
                extra: 3,
            };
        case "JMP":
            return { op: "cpu.pc = addr;" };
 
        // 65c12 opcodes
        case "TSB":
            return {
                op: ["cpu.p.z = !(REG & cpu.a);", "REG |= cpu.a;"],
                read: true,
                write: true,
            };
        case "TRB":
            return {
                op: ["cpu.p.z = !(REG & cpu.a);", "REG &= ~cpu.a;"],
                read: true,
                write: true,
            };
        case "BRA":
            return { op: "cpu.branch(true);" };
        case "STZ":
            return { op: "REG = 0;", write: true };
 
        // Undocumented opcodes.
        // first 3 used by Zalaga, http://stardot.org.uk/forums/viewtopic.php?f=2&t=3584&p=30514
 
        case "SAX": // stores (A AND X)
            return { op: "REG = cpu.a & cpu.x;", write: true };
        case "ASR": // aka ALR equivalent to AND #&AA:LSR A
            return {
                op: ["REG &= cpu.a;"].concat(rotate(false, true)).concat(["cpu.a = REG;"]),
            };
        case "SLO": // equivalent to ASL zp:ORA zp
            return {
                op: rotate(true, true).concat(["cpu.a |= REG;", "cpu.p.setzn(cpu.a);"]),
                read: true,
                write: true,
            };
        case "SHX":
            return { op: "REG = (cpu.x & ((addr >>> 8)+1)) & 0xff;", write: true, zpQuirk: true };
        case "SHY":
            return { op: "REG = (cpu.y & ((addr >>> 8)+1)) & 0xff;", write: true, zpQuirk: true };
        case "LAX": // NB uses the c64 value for the magic in the OR here. I don't know what would happen on a beeb.
            return {
                op: ["const magic = 0xff;", "cpu.a = cpu.x = cpu.p.setzn((cpu.a|magic) & REG);"],
                read: true,
            };
        case "LXA": // NB uses the c64 value for the magic in the OR here. I don't know what would happen on a beeb.
            return {
                op: ["const magic = 0xee;", "cpu.a = cpu.x = cpu.p.setzn((cpu.a|magic) & REG);"],
                read: true,
            };
        case "SRE":
            return {
                op: rotate(false, true).concat(["cpu.a = cpu.p.setzn(cpu.a ^ REG);"]),
                read: true,
                write: true,
            };
        case "RLA":
            return {
                op: rotate(true, false).concat(["cpu.a = cpu.p.setzn(cpu.a & REG);"]),
                read: true,
                write: true,
            };
        case "ANC":
            return {
                op: ["cpu.a = cpu.p.setzn(cpu.a & REG); cpu.p.c = cpu.p.n;"],
                read: true,
            };
        case "ANE":
            return {
                op: ["cpu.a = cpu.p.setzn((cpu.a | 0xee) & REG & cpu.x);"],
                read: true,
            };
        case "ARR":
            return { op: "cpu.arr(REG);", read: true };
        case "DCP":
            return {
                op: ["REG = cpu.p.setzn(REG - 1);", "cpu.p.setzn(cpu.a - REG);", "cpu.p.c = cpu.a >= REG;"],
                read: true,
                write: true,
            };
        case "LAS":
            return {
                op: ["cpu.a = cpu.x = cpu.s = cpu.p.setzn(cpu.s & REG);"],
                read: true,
            };
        case "RRA":
            return {
                op: rotate(false, false).concat(["cpu.adc(REG);"]),
                read: true,
                write: true,
            };
        case "SBX":
            return {
                op: ["const temp = cpu.a & cpu.x;", "cpu.p.c = temp >= REG;", "cpu.x = cpu.p.setzn(temp - REG);"],
                read: true,
            };
        case "SHA":
            return {
                op: ["REG = cpu.a & cpu.x & ((addr >>> 8) + 1) & 0xff;"],
                write: true,
                zpQuirk: true,
            };
        case "SHS":
            return {
                op: ["cpu.s = cpu.a & cpu.x;", "REG = cpu.a & cpu.x & ((addr >>> 8) + 1) & 0xff;"],
                write: true,
                zpQuirk: true,
            };
        case "ISB":
            return {
                op: ["REG = (REG + 1) & 0xff;", "cpu.sbc(REG);"],
                read: true,
                write: true,
            };
        case "RMB0":
        case "RMB1":
        case "RMB2":
        case "RMB3":
        case "RMB4":
        case "RMB5":
        case "RMB6":
        case "RMB7":
            return {
                op: [`REG = REG & (${~(1 << (op[3] - "0"))});`],
                read: true,
                write: true,
            };
        case "SMB0":
        case "SMB1":
        case "SMB2":
        case "SMB3":
        case "SMB4":
        case "SMB5":
        case "SMB6":
        case "SMB7":
            return {
                op: [`REG = REG | ${1 << (op[3] - "0")};`],
                read: true,
                write: true,
            };
        case "BBR0":
        case "BBR1":
        case "BBR2":
        case "BBR3":
        case "BBR4":
        case "BBR5":
        case "BBR6":
        case "BBR7":
            return { op: `cpu.branch(!(REG & ${1 << (op[3] - "0")}));`, read: true };
        case "BBS0":
        case "BBS1":
        case "BBS2":
        case "BBS3":
        case "BBS4":
        case "BBS5":
        case "BBS6":
        case "BBS7":
            return { op: `cpu.branch(REG & ${1 << (op[3] - "0")});`, read: true };
    }
    throw new Error(`Unrecognised operation '${op}'`);
}
 
// Undocumented opcodes carry a leading "*", as 6502 listings conventionally show them.
function splitUndocumented(markedOpcodes) {
    const opcodes = {};
    const undocumented = new Set();
    for (const [op, text] of Object.entries(markedOpcodes)) {
        if (text.startsWith("*")) {
            undocumented.add(Number(op));
            opcodes[op] = text.slice(1);
        } else {
            opcodes[op] = text;
        }
    }
    return { opcodes, undocumented };
}
 
const { opcodes: opcodes6502, undocumented: undocumented6502 } = splitUndocumented({
    0x00: "BRK",
    0x01: "ORA (,x)",
    0x03: "*SLO (,x)",
    0x04: "*NOP zp",
    0x05: "ORA zp",
    0x06: "ASL zp",
    0x07: "*SLO zp",
    0x08: "PHP",
    0x09: "ORA imm",
    0x0a: "ASL A",
    0x0b: "*ANC imm",
    0x0c: "*NOP abs",
    0x0d: "ORA abs",
    0x0e: "ASL abs",
    0x0f: "*SLO abs",
    0x10: "BPL branch",
    0x11: "ORA (),y",
    0x13: "*SLO (),y",
    0x14: "*NOP zp,x",
    0x15: "ORA zp,x",
    0x16: "ASL zp,x",
    0x17: "*SLO zp,x",
    0x18: "CLC",
    0x19: "ORA abs,y",
    0x1a: "*NOP",
    0x1b: "*SLO abs,y",
    0x1c: "*NOP abs,x",
    0x1d: "ORA abs,x",
    0x1e: "ASL abs,x",
    0x1f: "*SLO abs,x",
    0x20: "JSR abs",
    0x21: "AND (,x)",
    0x23: "*RLA (,x)",
    0x24: "BIT zp",
    0x25: "AND zp",
    0x26: "ROL zp",
    0x27: "*RLA zp",
    0x28: "PLP",
    0x29: "AND imm",
    0x2a: "ROL A",
    0x2b: "*ANC imm",
    0x2c: "BIT abs",
    0x2d: "AND abs",
    0x2e: "ROL abs",
    0x2f: "*RLA abs",
    0x30: "BMI branch",
    0x31: "AND (),y",
    0x33: "*RLA (),y",
    0x34: "*NOP zp,x",
    0x35: "AND zp,x",
    0x36: "ROL zp,x",
    0x37: "*RLA zp,x",
    0x38: "SEC",
    0x39: "AND abs,y",
    0x3a: "*NOP",
    0x3b: "*RLA abs,y",
    0x3c: "*NOP abs,x",
    0x3d: "AND abs,x",
    0x3e: "ROL abs,x",
    0x3f: "*RLA abs,x",
    0x40: "RTI",
    0x41: "EOR (,x)",
    0x43: "*SRE (,x)",
    0x44: "*NOP zp",
    0x45: "EOR zp",
    0x46: "LSR zp",
    0x47: "*SRE zp",
    0x48: "PHA",
    0x49: "EOR imm",
    0x4a: "LSR A",
    0x4b: "*ASR imm",
    0x4c: "JMP abs",
    0x4d: "EOR abs",
    0x4e: "LSR abs",
    0x4f: "*SRE abs",
    0x50: "BVC branch",
    0x51: "EOR (),y",
    0x53: "*SRE (),y",
    0x54: "*NOP zp,x",
    0x55: "EOR zp,x",
    0x56: "LSR zp,x",
    0x57: "*SRE zp,x",
    0x58: "CLI",
    0x59: "EOR abs,y",
    0x5a: "*NOP",
    0x5b: "*SRE abs,y",
    0x5c: "*NOP abs,x",
    0x5d: "EOR abs,x",
    0x5e: "LSR abs,x",
    0x5f: "*SRE abs,x",
    0x60: "RTS",
    0x61: "ADC (,x)",
    0x63: "*RRA (,x)",
    0x64: "*NOP zp",
    0x65: "ADC zp",
    0x66: "ROR zp",
    0x67: "*RRA zp",
    0x68: "PLA",
    0x69: "ADC imm",
    0x6a: "ROR A",
    0x6b: "*ARR imm",
    0x6c: "JMP (abs)",
    0x6d: "ADC abs",
    0x6e: "ROR abs",
    0x6f: "*RRA abs",
    0x70: "BVS branch",
    0x71: "ADC (),y",
    0x73: "*RRA (),y",
    0x74: "*NOP zp,x",
    0x75: "ADC zp,x",
    0x76: "ROR zp,x",
    0x77: "*RRA zp,x",
    0x78: "SEI",
    0x79: "ADC abs,y",
    0x7a: "*NOP",
    0x7b: "*RRA abs,y",
    0x7c: "*NOP abs,x",
    0x7d: "ADC abs,x",
    0x7e: "ROR abs,x",
    0x7f: "*RRA abs,x",
    0x80: "*NOP imm",
    0x81: "STA (,x)",
    0x82: "*NOP imm",
    0x83: "*SAX (,x)",
    0x84: "STY zp",
    0x85: "STA zp",
    0x86: "STX zp",
    0x87: "*SAX zp",
    0x88: "DEY",
    0x89: "*NOP imm",
    0x8a: "TXA",
    0x8b: "*ANE imm",
    0x8c: "STY abs",
    0x8d: "STA abs",
    0x8e: "STX abs",
    0x8f: "*SAX abs",
    0x90: "BCC branch",
    0x91: "STA (),y",
    0x93: "*SHA (),y",
    0x94: "STY zp,x",
    0x95: "STA zp,x",
    0x96: "STX zp,y",
    0x97: "*SAX zp,y",
    0x98: "TYA",
    0x99: "STA abs,y",
    0x9a: "TXS",
    0x9b: "*SHS abs,y",
    0x9c: "*SHY abs,x",
    0x9d: "STA abs,x",
    0x9e: "*SHX abs,y",
    0x9f: "*SHA abs,y",
    0xa0: "LDY imm",
    0xa1: "LDA (,x)",
    0xa2: "LDX imm",
    0xa3: "*LAX (,x)",
    0xa4: "LDY zp",
    0xa5: "LDA zp",
    0xa6: "LDX zp",
    0xa7: "*LAX zp",
    0xa8: "TAY",
    0xa9: "LDA imm",
    0xaa: "TAX",
    0xab: "*LXA imm",
    0xac: "LDY abs",
    0xad: "LDA abs",
    0xae: "LDX abs",
    0xaf: "*LAX abs",
    0xb0: "BCS branch",
    0xb1: "LDA (),y",
    0xb3: "*LAX (),y",
    0xb4: "LDY zp,x",
    0xb5: "LDA zp,x",
    0xb6: "LDX zp,y",
    0xb7: "*LAX zp,y",
    0xb8: "CLV",
    0xb9: "LDA abs,y",
    0xba: "TSX",
    0xbb: "*LAS abs,y",
    0xbc: "LDY abs,x",
    0xbd: "LDA abs,x",
    0xbe: "LDX abs,y",
    0xbf: "*LAX abs,y",
    0xc0: "CPY imm",
    0xc1: "CMP (,x)",
    0xc2: "*NOP imm",
    0xc3: "*DCP (,x)",
    0xc4: "CPY zp",
    0xc5: "CMP zp",
    0xc6: "DEC zp",
    0xc7: "*DCP zp",
    0xc8: "INY",
    0xc9: "CMP imm",
    0xca: "DEX",
    0xcb: "*SBX imm",
    0xcc: "CPY abs",
    0xcd: "CMP abs",
    0xce: "DEC abs",
    0xcf: "*DCP abs",
    0xd0: "BNE branch",
    0xd1: "CMP (),y",
    0xd3: "*DCP (),y",
    0xd4: "*NOP zp,x",
    0xd5: "CMP zp,x",
    0xd6: "DEC zp,x",
    0xd7: "*DCP zp,x",
    0xd8: "CLD",
    0xd9: "CMP abs,y",
    0xda: "*NOP",
    0xdb: "*DCP abs,y",
    0xdc: "*NOP abs,x",
    0xdd: "CMP abs,x",
    0xde: "DEC abs,x",
    0xdf: "*DCP abs,x",
    0xe0: "CPX imm",
    0xe1: "SBC (,x)",
    0xe2: "*NOP imm",
    0xe3: "*ISB (,x)",
    0xe4: "CPX zp",
    0xe5: "SBC zp",
    0xe6: "INC zp",
    0xe7: "*ISB zp",
    0xe8: "INX",
    0xe9: "SBC imm",
    0xea: "NOP",
    0xeb: "*SBC imm",
    0xec: "CPX abs",
    0xed: "SBC abs",
    0xee: "INC abs",
    0xef: "*ISB abs",
    0xf0: "BEQ branch",
    0xf1: "SBC (),y",
    0xf3: "*ISB (),y",
    0xf4: "*NOP zp,x",
    0xf5: "SBC zp,x",
    0xf6: "INC zp,x",
    0xf7: "*ISB zp,x",
    0xf8: "SED",
    0xf9: "SBC abs,y",
    0xfa: "*NOP",
    0xfb: "*ISB abs,y",
    0xfc: "*NOP abs,x",
    0xfd: "SBC abs,x",
    0xfe: "INC abs,x",
    0xff: "*ISB abs,x",
});
 
const { opcodes: opcodes65c12, undocumented: undocumented65c12 } = splitUndocumented({
    0x00: "BRK",
    0x01: "ORA (,x)",
    0x04: "TSB zp",
    0x05: "ORA zp",
    0x06: "ASL zp",
    0x08: "PHP",
    0x09: "ORA imm",
    0x0a: "ASL A",
    0x0c: "TSB abs",
    0x0d: "ORA abs",
    0x0e: "ASL abs",
    0x10: "BPL branch",
    0x11: "ORA (),y",
    0x12: "ORA ()",
    0x14: "TRB zp",
    0x15: "ORA zp,x",
    0x16: "ASL zp,x",
    0x18: "CLC",
    0x19: "ORA abs,y",
    0x1a: "INC A",
    0x1c: "TRB abs",
    0x1d: "ORA abs,x",
    0x1e: "ASL abs,x",
    0x20: "JSR abs",
    0x21: "AND (,x)",
    0x24: "BIT zp",
    0x25: "AND zp",
    0x26: "ROL zp",
    0x28: "PLP",
    0x29: "AND imm",
    0x2a: "ROL A",
    0x2c: "BIT abs",
    0x2d: "AND abs",
    0x2e: "ROL abs",
    0x30: "BMI branch",
    0x31: "AND (),y",
    0x32: "AND ()",
    0x34: "BIT zp,x",
    0x35: "AND zp,x",
    0x36: "ROL zp,x",
    0x38: "SEC",
    0x39: "AND abs,y",
    0x3a: "DEC A",
    0x3c: "BIT abs,x",
    0x3d: "AND abs,x",
    0x3e: "ROL abs,x",
    0x40: "RTI",
    0x41: "EOR (,x)",
    0x45: "EOR zp",
    0x46: "LSR zp",
    0x48: "PHA",
    0x49: "EOR imm",
    0x4a: "LSR A",
    0x4c: "JMP abs",
    0x4d: "EOR abs",
    0x4e: "LSR abs",
    0x50: "BVC branch",
    0x51: "EOR (),y",
    0x52: "EOR ()",
    0x55: "EOR zp,x",
    0x56: "LSR zp,x",
    0x58: "CLI",
    0x59: "EOR abs,y",
    0x5a: "PHY",
    0x5d: "EOR abs,x",
    0x5e: "LSR abs,x",
    0x60: "RTS",
    0x61: "ADC (,x)",
    0x64: "STZ zp",
    0x65: "ADC zp",
    0x66: "ROR zp",
    0x68: "PLA",
    0x69: "ADC imm",
    0x6a: "ROR A",
    0x6c: "JMP (abs)",
    0x6d: "ADC abs",
    0x6e: "ROR abs",
    0x70: "BVS branch",
    0x71: "ADC (),y",
    0x72: "ADC ()",
    0x74: "STZ zp,x",
    0x75: "ADC zp,x",
    0x76: "ROR zp,x",
    0x78: "SEI",
    0x79: "ADC abs,y",
    0x7a: "PLY",
    0x7c: "JMP (abs,x)",
    0x7d: "ADC abs,x",
    0x7e: "ROR abs,x",
    0x80: "BRA branch",
    0x81: "STA (,x)",
    0x84: "STY zp",
    0x85: "STA zp",
    0x86: "STX zp",
    0x88: "DEY",
    0x89: "BIT imm",
    0x8a: "TXA",
    0x8c: "STY abs",
    0x8d: "STA abs",
    0x8e: "STX abs",
    0x90: "BCC branch",
    0x91: "STA (),y",
    0x92: "STA ()",
    0x94: "STY zp,x",
    0x95: "STA zp,x",
    0x96: "STX zp,y",
    0x98: "TYA",
    0x99: "STA abs,y",
    0x9a: "TXS",
    0x9c: "STZ abs",
    0x9d: "STA abs,x",
    0x9e: "STZ abs,x",
    0xa0: "LDY imm",
    0xa1: "LDA (,x)",
    0xa2: "LDX imm",
    0xa4: "LDY zp",
    0xa5: "LDA zp",
    0xa6: "LDX zp",
    0xa8: "TAY",
    0xa9: "LDA imm",
    0xaa: "TAX",
    0xac: "LDY abs",
    0xad: "LDA abs",
    0xae: "LDX abs",
    0xb0: "BCS branch",
    0xb1: "LDA (),y",
    0xb2: "LDA ()",
    0xb4: "LDY zp,x",
    0xb5: "LDA zp,x",
    0xb6: "LDX zp,y",
    0xb8: "CLV",
    0xb9: "LDA abs,y",
    0xba: "TSX",
    0xbc: "LDY abs,x",
    0xbd: "LDA abs,x",
    0xbe: "LDX abs,y",
    0xc0: "CPY imm",
    0xc1: "CMP (,x)",
    0xc4: "CPY zp",
    0xc5: "CMP zp",
    0xc6: "DEC zp",
    0xc8: "INY",
    0xc9: "CMP imm",
    0xca: "DEX",
    //0xCB: "WAI", // was "WAI" but testing by @tom-seddon indicate this isn't a 65c12 thing
    0xcc: "CPY abs",
    0xcd: "CMP abs",
    0xce: "DEC abs",
    0xd0: "BNE branch",
    0xd1: "CMP (),y",
    0xd2: "CMP ()",
    0xd5: "CMP zp,x",
    0xd6: "DEC zp,x",
    0xd8: "CLD",
    0xd9: "CMP abs,y",
    0xda: "PHX",
    0xdd: "CMP abs,x",
    0xde: "DEC abs,x",
    0xe0: "CPX imm",
    0xe1: "SBC (,x)",
    0xe4: "CPX zp",
    0xe5: "SBC zp",
    0xe6: "INC zp",
    0xe8: "INX",
    0xe9: "SBC imm",
    0xea: "NOP",
    0xec: "CPX abs",
    0xed: "SBC abs",
    0xee: "INC abs",
    0xf0: "BEQ branch",
    0xf1: "SBC (),y",
    0xf2: "SBC ()",
    0xf5: "SBC zp,x",
    0xf6: "INC zp,x",
    0xf8: "SED",
    0xf9: "SBC abs,y",
    0xfa: "PLX",
    0xfd: "SBC abs,x",
    0xfe: "INC abs,x",
});
 
const { opcodes: opcodes65c02, undocumented: undocumented65c02 } = splitUndocumented({
    ...opcodes65c12,
    0x07: "RMB0 zp",
    0x17: "RMB1 zp",
    0x27: "RMB2 zp",
    0x37: "RMB3 zp",
    0x47: "RMB4 zp",
    0x57: "RMB5 zp",
    0x67: "RMB6 zp",
    0x77: "RMB7 zp",
    0x87: "SMB0 zp",
    0x97: "SMB1 zp",
    0xa7: "SMB2 zp",
    0xb7: "SMB3 zp",
    0xc7: "SMB4 zp",
    0xd7: "SMB5 zp",
    0xe7: "SMB6 zp",
    0xf7: "SMB7 zp",
    0x0f: "BBR0 zp,branch",
    0x1f: "BBR1 zp,branch",
    0x2f: "BBR2 zp,branch",
    0x3f: "BBR3 zp,branch",
    0x4f: "BBR4 zp,branch",
    0x5f: "BBR5 zp,branch",
    0x6f: "BBR6 zp,branch",
    0x7f: "BBR7 zp,branch",
    0x8f: "BBS0 zp,branch",
    0x9f: "BBS1 zp,branch",
    0xaf: "BBS2 zp,branch",
    0xbf: "BBS3 zp,branch",
    0xcf: "BBS4 zp,branch",
    0xdf: "BBS5 zp,branch",
    0xef: "BBS6 zp,branch",
    0xff: "BBS7 zp,branch",
});
 
const PrevInstructionWindow = 64;
 
class Disassemble6502 {
    constructor(cpu, opcodes, undocumented) {
        this.cpu = cpu;
        this.opcodes = opcodes;
        this.undocumented = undocumented;
    }
 
    isDocumented(addr) {
        const op = this.cpu.peekmem(addr);
        return op in this.opcodes && !this.undocumented.has(op);
    }
 
    disassemble(addr, plain) {
        let formatAddr = (addr) => `<span class="instr_mem_ref" data-ref="${addr}">${hexword(addr)}</span>`;
        let formatJumpAddr = (addr) => `<span class="instr_instr_ref" data-ref="${addr}">${hexword(addr)}</span>`;
        if (plain) {
            formatAddr = hexword;
            formatJumpAddr = hexword;
        }
        const opcodeByte = this.cpu.peekmem(addr);
        const opcode = this.opcodes[opcodeByte];
        if (!opcode) {
            return ["???", addr + 1];
        }
        const [mnemonic, ...rest] = opcode.split(" ");
        const split = [(this.undocumented.has(opcodeByte) ? "*" : "") + mnemonic, ...rest];
        if (!split[1]) {
            return [split[0], addr + 1];
        }
        let param = split[1] || "";
        let suffix = "";
        let suffix2 = "";
        const index = param.match(/(.*),([xy])$/);
        if (index) {
            param = index[1];
            suffix = `,${index[2].toUpperCase()}`;
            suffix2 = ` + ${index[2].toUpperCase()}`;
        }
        switch (param) {
            case "imm":
                return [`${split[0]} #$${hexbyte(this.cpu.peekmem(addr + 1))}${suffix}`, addr + 2];
            case "abs": {
                const formatter = split[0] === "JMP" || split[0] === "JSR" ? formatJumpAddr : formatAddr;
                const destAddr = this.cpu.peekmem(addr + 1) | (this.cpu.peekmem(addr + 2) << 8);
                return [`${split[0]} $${formatter(destAddr)}${suffix}`, addr + 3, destAddr];
            }
            case "branch": {
                const destAddr = addr + signExtend(this.cpu.peekmem(addr + 1)) + 2;
                return [`${split[0]} $${formatJumpAddr(destAddr)}${suffix}`, addr + 2, destAddr];
            }
            case "zp":
                return [`${split[0]} $${hexbyte(this.cpu.peekmem(addr + 1))}${suffix}`, addr + 2];
            case "zp,branch": {
                const destAddr = addr + signExtend(this.cpu.peekmem(addr + 2)) + 3;
                return [
                    `${split[0]} $${hexbyte(this.cpu.peekmem(addr + 1))}, $${formatJumpAddr(destAddr)}`,
                    addr + 3,
                    destAddr,
                ];
            }
            case "(,x)":
                return [`${split[0]} ($${hexbyte(this.cpu.peekmem(addr + 1))}, X)${suffix}`, addr + 2];
            case "()": {
                const zp = this.cpu.peekmem(addr + 1);
                const destAddr = this.cpu.peekmem(zp) | (this.cpu.peekmem(zp + 1) << 8);
                return [`${split[0]} ($${hexbyte(zp)})${suffix} ; $${hexword(destAddr)}${suffix2}`, addr + 2];
            }
            case "(abs)": {
                const destAddr = this.cpu.peekmem(addr + 1) | (this.cpu.peekmem(addr + 2) << 8);
                const indDest = this.cpu.peekmem(destAddr) | (this.cpu.peekmem(destAddr + 1) << 8);
                return [
                    `${split[0]} ($${formatJumpAddr(destAddr)})${suffix} ; $${hexword(indDest)}${suffix2}`,
                    addr + 3,
                    indDest,
                ];
            }
            case "(abs,x)": {
                const destAddr = this.cpu.peekmem(addr + 1) | (this.cpu.peekmem(addr + 2) << 8);
                const indDest = this.cpu.peekmem(destAddr) | (this.cpu.peekmem(destAddr + 1) << 8);
                return [`${split[0]} ($${formatJumpAddr(destAddr)},x)${suffix}`, addr + 3, indDest];
            }
        }
        return [split.join(" "), addr + 1];
    }
 
    nextInstruction(address) {
        return this.disassemble(address)[1] & 0xffff;
    }
 
    /**
     * Guesses the address of the instruction before the given one by scoring
     * each run of instructions in the preceding window that lands exactly on
     * it: a point per "common" instruction (loads, stores, branches, compares,
     * arithmetic and carry-set/clear that avoid unusual indexing modes) and a
     * large boost for a run that passes through pc. Runs through undocumented
     * opcodes are discarded. The highest-scoring run's last instruction wins;
     * any run beats none, since a wrong parse resynchronises within a few
     * instructions and so nearly always shares the true stream's last one.
     * Good test cases:
     *   Repton 2 @ 2cbb
     *   MOS @ cfc8, and the unrolled STA abs,X screen clear @ cc63
     * also, just starting from the back of ROM and going up...
     */
    prevInstruction(address, pc) {
        const commonInstructions =
            /(RTS|B..|JMP|JSR|LD[AXY]|ST[AXY]|TA[XY]|T[XY]A|AD[DC]|SUB|SBC|CLC|SEC|CMP|EOR|ORA|AND|INC|DEC).*/;
        const uncommonInstructions = /.*,\s*([XY]|X\))$/;
 
        address &= 0xffff;
        let bestAddr = address - 1;
        let bestScore = -1;
        for (let startingPoint = address - PrevInstructionWindow; startingPoint !== address; startingPoint++) {
            let score = 0;
            let addr = startingPoint & 0xffff;
            while (addr < address) {
                if (!this.isDocumented(addr)) break;
                const result = this.disassemble(addr);
                if (addr === pc) score += 10;
                if (result[0].match(commonInstructions) && !result[0].match(uncommonInstructions)) {
                    score++;
                }
                if (result[1] === address) {
                    if (score > bestScore) {
                        bestScore = score;
                        bestAddr = addr;
                    }
                    break;
                }
                addr = result[1];
            }
        }
        return bestAddr & 0xffff;
    }
}
 
function makeCpuFunctions(cpu, opcodes, undocumented, is65c12, cycleAccurate = true) {
    function getInstruction(opcodeString, needsReg) {
        const split = opcodeString.split(" ");
        const opcode = split[0];
        const arg = split[1];
        const op = getOp(opcode, arg);
        Iif (!op) return null;
 
        let ig = new InstructionGen(is65c12, cycleAccurate);
        Eif (needsReg) ig.append("let REG = 0|0;");
 
        switch (arg) {
            case undefined:
                // Many of these ops need a little special casing.
                Iif (op.read || op.write) throw new Error(`Unsupported ${opcodeString}`);
                ig.append(op.preop);
                ig.tick(Math.max(2, 1 + (op.extra || 0)));
                ig.append(op.op);
                return ig.render();
 
            case "branch":
                return [op.op]; // special cased here, would be nice to pull out of cpu
 
            case "zp,branch":
                ig.tick(2);
                ig.append("const addr = cpu.getb() | 0;");
                Eif (op.read) {
                    ig.zpReadOp("addr", "REG");
                    Iif (op.write) {
                        ig.tick(1); // Spurious write
                    }
                }
                ig.append(op.op);
                Iif (op.write) ig.zpWriteOp("addr", "REG");
                return ig.render();
 
            case "zp":
            case "zp,x":
            case "zp,y":
                if (arg === "zp") {
                    ig.tick(2);
                    ig.append("const addr = cpu.getb() | 0;");
                } else {
                    ig.tick(3);
                    ig.append(`const addr = (cpu.getb() + cpu.${arg[3]}) & 0xff;`);
                }
                if (op.read) {
                    ig.zpReadOp("addr", "REG");
                    if (op.write) {
                        ig.tick(1); // Spurious write
                    }
                }
                ig.append(op.op);
                if (op.write) ig.zpWriteOp("addr", "REG");
                return ig.render();
 
            case "abs":
                ig.tick(3 + (op.extra || 0));
                ig.append("const addr = cpu.getw() | 0;");
                if (op.read) {
                    ig.readOp("addr", "REG");
                    if (op.write) ig.spuriousOp("addr", "REG");
                }
                ig.append(op.op);
                if (op.write) ig.writeOp("addr", "REG");
 
                return ig.render();
 
            case "abs,x":
            case "abs,y":
                ig.append("const addr = cpu.getw() | 0;");
                ig.append(`let addrWithCarry = (addr + cpu.${arg[4]}) & 0xffff;`);
                ig.append("const addrNonCarry = (addr & 0xff00) | (addrWithCarry & 0xff);");
                ig.tick(3);
                ig = ig.split("addrWithCarry !== addrNonCarry");
                if (op.read && !op.write) {
                    if (is65c12) {
                        // the 65c12 reads the instruction byte again while it's carrying.
                        ig.ifTrue.tick(1);
                    } else {
                        // the 6502 reads the uncarried address
                        ig.ifTrue.readOp("addrNonCarry");
                    }
                    ig.readOp("addrWithCarry", "REG");
                } else if (op.read) {
                    if (is65c12) {
                        // RMWs on 65c12 burn a cycle reading the instruction byte again while carrying.
                        ig.ifTrue.tick(1);
                        // For anything but rotates, there's a bug: during carrying the CPU reads again.
                        // beebjit reads the carried address, but I can't see how that could be the case,
                        // so I read the non-carry here.
                        if (!op.rotate) ig.ifFalse.readOp("addrNonCarry", "REG");
                        ig.readOp("addrWithCarry", "REG");
                        // 65c12 does "two reads and one write" for RMW (not the 6502's
                        // "one read and two writes"). The spurious cycle is a read.
                        ig.readOp("addrWithCarry", "", true);
                    } else {
                        // For RMW we always have a spurious read and then a spurious read or write
                        ig.readOp("addrNonCarry");
                        ig.readOp("addrWithCarry", "REG");
                        ig.spuriousOp("addrWithCarry", "REG");
                    }
                } else Eif (op.write) {
                    if (is65c12) {
                        // Discovered on Stardot: https://stardot.org.uk/forums/viewtopic.php?f=55&t=25298&sid=86e65177447d407aa6510f1f98efca87&start=30
                        // With page crossing, the CPU re-reads the third byte of the instruction.
                        ig.ifTrue.tick(1);
                        // Without page crossing, the CPU still has the bug of reading the non-carried address(!)
                        ig.ifFalse.readOp("addrNonCarry");
                    } else {
                        // Pure stores still exhibit a read at the non-carried address.
                        ig.readOp("addrNonCarry");
                        if (op.zpQuirk) {
                            // with this quirk on undocumented instructions, a page crossing writes to 00XX
                            ig.append("if (addrWithCarry !== addrNonCarry) addrWithCarry &= 0xff;");
                        }
                    }
                }
                ig.append(op.op);
                if (op.write) ig.writeOp("addrWithCarry", "REG");
                return ig.render();
 
            case "imm":
                Iif (op.write) {
                    throw new Error("This isn't possible");
                }
                if (op.read) {
                    // NOP imm
                }
                ig.tick(2);
                ig.append("REG = cpu.getb() | 0;");
                ig.append(op.op);
                return ig.render();
 
            case "A":
                ig.tick(2);
                ig.append("REG = cpu.a;");
                ig.append(op.op);
                ig.append("cpu.a = REG;");
                return ig.render();
 
            case "(,x)":
                ig.tick(3); // two, plus one for the seemingly spurious extra read of zp
                ig.append("const zpAddr = (cpu.getb() + cpu.x) & 0xff;");
                ig.append("let lo, hi;");
                ig.zpReadOp("zpAddr", "lo");
                ig.zpReadOp("(zpAddr + 1) & 0xff", "hi");
                ig.append("const addr = lo | (hi << 8);");
                if (op.read) {
                    ig.readOp("addr", "REG");
                    if (op.write) ig.spuriousOp("addr", "REG");
                }
                ig.append(op.op);
                if (op.write) ig.writeOp("addr", "REG");
                return ig.render();
 
            case "(),y":
                ig.tick(2);
                ig.append("const zpAddr = cpu.getb() | 0;");
                ig.append("let lo, hi;");
                ig.zpReadOp("zpAddr", "lo");
                ig.zpReadOp("(zpAddr + 1) & 0xff", "hi");
                ig.append("const addr = lo | (hi << 8);");
                ig.append("let addrWithCarry = (addr + cpu.y) & 0xffff;");
                ig.append("const addrNonCarry = (addr & 0xff00) | (addrWithCarry & 0xff);");
                if (op.read && !op.write) {
                    // For non-RMW, we only pay the cost of the spurious read if the address carried on 6502
                    ig = ig.split("addrWithCarry !== addrNonCarry");
                    if (!is65c12) {
                        ig.ifTrue.readOp("addrNonCarry");
                    } else {
                        ig.ifTrue.tick(1);
                    }
                    ig.readOp("addrWithCarry", "REG");
                } else if (op.read) {
                    // For RMW we always have a spurious read and then a spurious read or write
                    ig.readOp("addrNonCarry");
                    ig.readOp("addrWithCarry", "REG");
                    ig.spuriousOp("addrWithCarry", "REG");
                } else Eif (op.write) {
                    if (is65c12) {
                        // On the 65c12, the dead cycle reads the Previous Bus Address (PBA)
                        // rather than the partially-formed or target address. Since PBA is
                        // always a zero-page or instruction-fetch address (2MHz), it never
                        // triggers 1MHz bus stretching. We model this as tick(1).
                        ig.tick(1);
                    } else {
                        // Pure stores still exhibit a read at the non-carried address.
                        ig.readOp("addrNonCarry");
                        if (op.zpQuirk) {
                            // with this quirk on undocumented instructions, a page crossing writes to 00XX
                            ig.append("if (addrWithCarry !== addrNonCarry) addrWithCarry &= 0xff;");
                        }
                    }
                }
                ig.append(op.op);
                if (op.write) ig.writeOp("addrWithCarry", "REG");
                return ig.render();
 
            case "(abs)":
                ig.tick(is65c12 ? 4 : 3);
                ig.append("const absAddr = cpu.getw() | 0;");
                if (is65c12) {
                    ig.append("const nextAddr = (absAddr + 1) & 0xffff;");
                } else {
                    ig.append("const nextAddr = ((absAddr + 1) & 0xff) | (absAddr & 0xff00);");
                }
                ig.append("let lo, hi;");
                ig.readOp("absAddr", "lo");
                ig.readOp("nextAddr", "hi");
                ig.append("const addr = lo | (hi << 8);");
                ig.append(op.op);
                return ig.render();
 
            case "(abs,x)":
                ig.tick(4);
                ig.append("const absAddr = (cpu.getw() + cpu.x) | 0;");
                ig.append("let lo, hi;");
                ig.readOp("absAddr", "lo");
                ig.readOp("(absAddr + 1) & 0xffff", "hi");
                ig.append("const addr = lo | (hi << 8);");
                ig.append(op.op);
                return ig.render();
 
            case "()":
                // Timing here is guessed at, but appears to be correct.
                ig.tick(2);
                ig.append("const zpAddr = cpu.getb() | 0;");
                ig.append("let lo, hi;");
                ig.zpReadOp("zpAddr", "lo");
                ig.zpReadOp("(zpAddr + 1) & 0xff", "hi");
                ig.append("const addr = lo | (hi << 8);");
                if (op.read) ig.readOp("addr", "REG");
                ig.append(op.op);
                if (op.write) ig.writeOp("addr", "REG");
                return ig.render();
 
            default:
                throw new Error(`Unknown arg type ${arg}`);
        }
    }
 
    function getIndentedSource(indent, opcodeNum, needsReg) {
        const opcode = opcodes[opcodeNum];
        return (
            indent +
            [
                '"use strict";',
                `// ${hexbyte(opcodeNum)} - ${opcode}
`,
            ].concat(
                opcode ? getInstruction(opcode, !!needsReg) : [`this.invalidOpcode(cpu, 0x${hexbyte(opcodeNum)});`],
            ).join(`
${indent}`)
        );
    }
 
    // Empty to hold prototypical stuff.
    function Runner() {}
 
    function generate6502JumpTable() {
        const funcs = [];
        for (let opcodeNum = 0; opcodeNum < 256; ++opcodeNum) {
            const opcodeFunc = new Function("cpu", getIndentedSource("  ", opcodeNum, true));
            let funcName = `exec_${hexbyte(opcodeNum)}_`;
            if (opcodes[opcodeNum]) {
                const instrName = opcodes[opcodeNum]
                    .replace("()", "ind")
                    .replace("(,x)", "ind_x")
                    .replace("(abs)", "ind_abs")
                    .replace(/[^A-Za-z0-9]/g, "_")
                    .toLowerCase();
                funcName += instrName;
            } else funcName += "undef";
            Object.defineProperty(opcodeFunc, "name", { writable: true, value: funcName });
            funcs[opcodeNum] = opcodeFunc;
        }
        return function exec(opcode) {
            return funcs[opcode].call(this, this.cpu);
        };
    }
 
    function invalidOpcode(cpu, opcode) {
        Eif (is65c12) {
            // All undefined opcodes are NOPs on 65c12 (of varying lengths)
            // http://6502.org/tutorials/65c02opcodes.html has a list.
            // The default case is to treat them as one-cycle NOPs. Anything more than this is picked up below.
            switch (opcode) {
                case 0x02:
                case 0x22:
                case 0x42:
                case 0x62:
                case 0x82:
                case 0xc2:
                case 0xe2:
                    // two bytes, two cycles
                    cpu.getb();
                    cpu.polltime(2);
                    break;
 
                case 0x44:
                    // two bytes, three cycles
                    cpu.getb();
                    cpu.polltime(3);
                    break;
 
                case 0x54:
                case 0xd4:
                case 0xf4:
                    // two bytes, four cycles
                    cpu.getb();
                    cpu.polltime(4);
                    break;
 
                case 0x5c:
                    // three bytes, eight cycles
                    cpu.getw();
                    cpu.polltime(8);
                    break;
 
                case 0xdc:
                case 0xfc:
                    // three bytes, four cycles (plus a memory access)
                    cpu.polltimeAddr(4, cpu.getw());
                    break;
 
                default:
                    // one byte one cycle
                    cpu.polltime(1);
                    break;
            }
            return;
        }
        // Anything else is a HLT. Just hang forever...
        cpu.pc--; // Account for the fact we've already incremented pc.
        cpu.polltime(1); // Take up some time though. Else we'll spin forever
    }
 
    Runner.prototype.invalidOpcode = invalidOpcode;
    Runner.prototype.cpu = cpu;
    // We used to use jump tables for Firefox, and binary search for everything else.
    // Chrome used to have a problem with 256 entries in a switch, but that seems to have been fixed.
    // We now use a jump table for everything.
    Runner.prototype.run = generate6502JumpTable();
 
    return {
        disassembler: new Disassemble6502(cpu, opcodes, undocumented),
        runInstruction: new Runner(),
        opcodes: opcodes,
        getInstruction: getInstruction,
    };
}
 
export function Cpu6502(cpu, { cycleAccurate = true } = {}) {
    return makeCpuFunctions(cpu, opcodes6502, undocumented6502, false, cycleAccurate);
}
 
export function Cpu65c12(cpu, { cycleAccurate = true } = {}) {
    return makeCpuFunctions(cpu, opcodes65c12, undocumented65c12, true, cycleAccurate);
}
 
export function Cpu65c02(cpu, { cycleAccurate = true } = {}) {
    return makeCpuFunctions(cpu, opcodes65c02, undocumented65c02, true, cycleAccurate);
}