systemless 0.1.1

High-Level Emulation for classic Macintosh applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
//! Memory Manager trap handlers.

use crate::cpu::{CpuOps, Register};
use crate::machine_profile::ORACLE_MACHINE_PROFILE;
use crate::memory::{MacMemoryBus, MemoryBus};
use crate::{Error, Result};
use std::collections::HashMap;
use std::sync::OnceLock;

static TRACE_MEMORY: OnceLock<bool> = OnceLock::new();
static TRACE_VIDEO_DRIVER: OnceLock<bool> = OnceLock::new();
static TRACE_ENTROPY: OnceLock<bool> = OnceLock::new();
static TRACE_VBL: OnceLock<bool> = OnceLock::new();

fn trace_memory_enabled() -> bool {
    *TRACE_MEMORY.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_MEMORY").is_some())
}

fn trace_vbl_enabled() -> bool {
    *TRACE_VBL.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_VBL").is_some())
}

/// Estimate free application heap from ApplLimit + HeapEnd low-mem globals,
/// clamped to [24MB, 64MB]. The 24MB floor satisfies games that sanity-check
/// for free memory before proceeding at higher screen resolutions; the 64MB
/// cap protects legacy callers that store FreeMem in a signed LONG.
fn free_heap_estimate(bus: &MacMemoryBus) -> u32 {
    use crate::memory::globals::addr;
    let heap_end = bus.read_long(addr::HEAP_END);
    let appl_limit = bus.read_long(addr::APPL_LIMIT);
    let avail = appl_limit.saturating_sub(heap_end);
    avail.clamp(24 * 1024 * 1024, 64 * 1024 * 1024)
}

fn init_zone_header(
    bus: &mut MacMemoryBus,
    start: u32,
    limit: u32,
    more_masters_raw: u16,
    grow_zone: u32,
) {
    // Zone record layout per Inside Macintosh Volume II (1985), p. II-22.
    // Only the caller-observable header fields are initialized here.
    let more_masters = i16::from_be_bytes(more_masters_raw.to_be_bytes()).max(0) as u32;
    let free_bytes = limit
        .saturating_sub(start)
        .saturating_sub(72 + (4 * more_masters));
    let first_master_ptr = if more_masters == 0 {
        0
    } else {
        start.wrapping_add(60)
    };

    bus.write_long(start, limit); // bkLim
    bus.write_long(start + 4, 0); // purgePtr
    bus.write_long(start + 8, first_master_ptr); // hFstFree
    bus.write_long(start + 12, free_bytes); // zcbFree
    bus.write_long(start + 16, grow_zone); // gzProc
    bus.write_word(start + 20, more_masters_raw); // moreMast
    bus.write_word(start + 22, 0); // flags
    bus.write_word(start + 24, 0); // cntRel
    bus.write_word(start + 26, 0); // maxRel
    bus.write_word(start + 28, 0); // cntNRel
    bus.write_word(start + 30, 0); // maxNRel
    bus.write_word(start + 32, 0); // cntEmpty
    bus.write_word(start + 34, 0); // cntHandles
    bus.write_long(start + 36, free_bytes); // minCBFree
    bus.write_long(start + 40, 0); // purgeProc
    bus.write_long(start + 44, 0); // sparePtr
    bus.write_long(start + 48, start.wrapping_add(52)); // allocPtr
}

const NO_ERR: u32 = 0;
const BAD_UNIT_ERR: u32 = (-21i32) as u32;
const PARAM_ERR: u32 = (-50i32) as u32;
const DT_QTYPE: u16 = 7;
const NOT_HELD_ERR: u32 = (-621i32) as u32;
const NOT_LOCKED_ERR: u32 = (-623i32) as u32;
const VM_PAGE_SHIFT: u32 = 12;
const VM_PAGE_SIZE: u32 = 1 << VM_PAGE_SHIFT;

#[inline]
fn return_noerr<C: CpuOps>(cpu: &mut C) -> Result<()> {
    cpu.write_reg(Register::D0, NO_ERR);
    Ok(())
}

fn vm_page_span(start: u32, count: u32) -> Option<(u32, u32)> {
    if count == 0 {
        return None;
    }
    let page_start = start >> VM_PAGE_SHIFT;
    let end_exclusive = (start as u64).saturating_add(count as u64);
    let page_end_exclusive =
        end_exclusive.saturating_add((VM_PAGE_SIZE - 1) as u64) >> VM_PAGE_SHIFT;
    let page_end_exclusive = page_end_exclusive.min(u32::MAX as u64) as u32;
    if page_end_exclusive <= page_start {
        None
    } else {
        Some((page_start, page_end_exclusive))
    }
}

fn vm_required_physical_entries(start: u32, count: u32) -> u32 {
    vm_page_span(start, count)
        .map(|(page_start, page_end_exclusive)| page_end_exclusive - page_start)
        .unwrap_or(0)
}

fn vm_range_is_logical_ram(bus: &MacMemoryBus, start: u32, count: u32) -> bool {
    let ram_size = bus.ram_size() as u64;
    let start = start as u64;
    // Zero-length ranges are only valid if they still start inside logical RAM.
    if start >= ram_size {
        return false;
    }
    if count == 0 {
        return true;
    }
    let end_exclusive = start.saturating_add(count as u64);
    start < ram_size && end_exclusive <= ram_size
}

fn vm_range_is_fully_tracked(
    page_counts: &HashMap<u32, u16>,
    page_start: u32,
    page_end_exclusive: u32,
) -> bool {
    (page_start..page_end_exclusive).all(|page| page_counts.get(&page).copied().unwrap_or(0) > 0)
}

fn vm_increment_pages(
    page_counts: &mut HashMap<u32, u16>,
    page_start: u32,
    page_end_exclusive: u32,
) {
    for page in page_start..page_end_exclusive {
        let count = page_counts.entry(page).or_insert(0);
        *count = count.saturating_add(1);
    }
}

fn vm_try_decrement_pages(
    page_counts: &mut HashMap<u32, u16>,
    page_start: u32,
    page_end_exclusive: u32,
) -> bool {
    if !vm_range_is_fully_tracked(page_counts, page_start, page_end_exclusive) {
        return false;
    }
    let mut remove_pages = Vec::new();
    for page in page_start..page_end_exclusive {
        if let Some(count) = page_counts.get_mut(&page) {
            if *count <= 1 {
                remove_pages.push(page);
            } else {
                *count -= 1;
            }
        }
    }
    for page in remove_pages {
        page_counts.remove(&page);
    }
    true
}

fn trace_memory_site(trap_site: u32) -> bool {
    trace_memory_enabled() && matches!(trap_site, 0x0007B4FE | 0x0025793E | 0x0007B51E | 0x0007B526)
}

fn trace_video_driver_enabled() -> bool {
    *TRACE_VIDEO_DRIVER.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_VIDEO_DRIVER").is_some())
}

fn trace_entropy_enabled() -> bool {
    *TRACE_ENTROPY.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_ENTROPY").is_some())
}

fn apply_memory_manager_dispatcher_ccr<C: CpuOps>(cpu: &mut C) {
    // Memory Manager assembly-language callers observe the trap dispatcher's
    // TST.W D0 behavior on return. Preserve X, set N/Z from the low word,
    // and clear V/C as TST.W would.
    // Inside Macintosh Volume II, II-14; Memory 1992, 2-14
    let mut ccr = cpu.get_ccr() & 0x10;
    let low_word = cpu.read_reg(Register::D0) as u16;
    if low_word == 0 {
        ccr |= 0x04;
    } else if (low_word & 0x8000) != 0 {
        ccr |= 0x08;
    }
    cpu.set_ccr(ccr);
}

fn memory_manager_trap_updates_dispatcher_ccr(is_tool: bool, trap_num: u16) -> bool {
    matches!(
        (is_tool, trap_num),
        (
            false,
            0x1C | 0x1D
                | 0x1E
                | 0x1F
                | 0x20
                | 0x21
                | 0x22
                | 0x23
                | 0x24
                | 0x25
                | 0x27
                | 0x28
                | 0x29
                | 0x2A
                | 0x2D
                | 0x2E
                | 0x36
                | 0x40
                | 0x4C
                | 0x62
                | 0x63
                | 0x64
                | 0x66
                | 0x69
                | 0x8D
                | 0x88
                | 0xAE
                | 0xA4
        ) | (true, 0x1E1..=0x1E3)
    )
}

impl super::TrapDispatcher {
    fn sync_vbl_links(&mut self, bus: &mut MacMemoryBus) {
        let len = self.vbl_tasks.len();
        for index in 0..len {
            let next = self
                .vbl_tasks
                .get(index + 1)
                .map(|task| task.task_ptr)
                .unwrap_or(0);
            bus.write_long(self.vbl_tasks[index].task_ptr, next);
        }
    }

    fn looks_like_callable_proc(bus: &MacMemoryBus, proc_ptr: u32) -> bool {
        if proc_ptr == 0 || proc_ptr > bus.ram_size().saturating_sub(2) {
            return false;
        }
        matches!(
            bus.read_word(proc_ptr),
            0x4E56 | 0x48E7 | 0x4EF9 | 0x4EFA
        )
    }

    fn get_or_create_defer_user_fn_trampoline(&mut self, bus: &mut MacMemoryBus) -> u32 {
        if self.defer_user_fn_trampoline != 0 {
            return self.defer_user_fn_trampoline;
        }

        let tramp = bus.alloc(24);
        if tramp == 0 {
            return 0;
        }

        // Layout:
        //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)
        //   +4:  MOVEA.L #imm,A0        ; patched with argument
        //   +10: JSR abs.L             ; patched with userFunction
        //   +16: MOVEM.L (SP)+,D0-D3/A0-A3
        //   +20: MOVEQ #0,D0           ; noErr
        //   +22: RTS
        bus.write_word(tramp, 0x48E7);
        bus.write_word(tramp + 2, 0xF0F0);
        bus.write_word(tramp + 4, 0x207C);
        bus.write_word(tramp + 10, 0x4EB9);
        bus.write_word(tramp + 16, 0x4CDF);
        bus.write_word(tramp + 18, 0x0F0F);
        bus.write_word(tramp + 20, 0x7000);
        bus.write_word(tramp + 22, 0x4E75);
        self.defer_user_fn_trampoline = tramp;
        tramp
    }

    fn install_vbl_task(
        &mut self,
        bus: &mut MacMemoryBus,
        task_ptr: u32,
        slot: Option<i16>,
    ) -> i16 {
        if trace_vbl_enabled() {
            let q_type = bus.read_word(task_ptr + 4) as i16;
            let vbl_addr = bus.read_long(task_ptr + 6);
            let vbl_count = bus.read_word(task_ptr + 10) as i16;
            let vbl_phase = bus.read_word(task_ptr + 12) as i16;
            eprintln!(
                "[VBL] install tick={} task=${:08X} qType={} addr=${:08X} count={} phase={} slot={:?}",
                self.tick_count, task_ptr, q_type, vbl_addr, vbl_count, vbl_phase, slot
            );
        }
        if task_ptr == 0 || bus.read_word(task_ptr + 4) as i16 != 1 {
            return -2; // vTypErr
        }
        // BasiliskII accepts slot = -1 for slot-based VBL install/remove.
        // Preserve the documented slotNumErr for more-negative values.
        if matches!(slot, Some(s) if s < -1) {
            return -360; // slotNumErr
        }

        let vbl_count = bus.read_word(task_ptr + 10) as i16;
        let vbl_phase = bus.read_word(task_ptr + 12) as i16;
        bus.write_word(task_ptr + 10, vbl_count.wrapping_add(vbl_phase) as u16);

        self.vbl_tasks.retain(|task| task.task_ptr != task_ptr);
        self.vbl_tasks
            .push(super::dispatch::VblTask { task_ptr, slot });
        self.sync_vbl_links(bus);
        0
    }

    fn remove_vbl_task(&mut self, bus: &mut MacMemoryBus, task_ptr: u32, slot: Option<i16>) -> i16 {
        if task_ptr == 0 || bus.read_word(task_ptr + 4) as i16 != 1 {
            return -2; // vTypErr
        }
        if matches!(slot, Some(s) if s < -1) {
            return -360; // slotNumErr
        }

        // Real ROM's (Slot)VRemove returns qErr (-1) if the task isn't
        // currently in the VBL queue.
        let was_in_queue = self.vbl_tasks.iter().any(|task| task.task_ptr == task_ptr);
        if !was_in_queue {
            return -1; // qErr
        }
        self.vbl_tasks.retain(|task| task.task_ptr != task_ptr);
        bus.write_long(task_ptr, 0);
        self.sync_vbl_links(bus);
        0
    }

    pub(crate) fn dispatch_memory<C: CpuOps>(
        &mut self,
        is_tool: bool,
        trap_num: u16,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
    ) -> Option<Result<()>> {
        let result = match (is_tool, trap_num) {
            // ========== Memory Manager ==========
            // NewPtr ($A01E) / NewPtrSys ($A11E) / NewPtrClear ($A31E) / NewPtrSysClear ($A71E)
            // Allocates a nonrelocatable block. CLEAR variants zero the memory.
            // Inside Macintosh Volume II, II-37
            // NewPtr / NewPtrClear / NewPtrSys ($A01E): Allocates via `bus.alloc()`, returns ptr in A0; CLEAR variant ($A31E) zeros memory per IM:II II-37
            (false, 0x1E) => {
                let size = cpu.read_reg(Register::D0);
                let ptr = bus.alloc(size);
                if ptr == 0 && size > 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                } else {
                    // Check CLEAR bit (bit 9 = 0x0200 in trap word)
                    if (self.current_trap_word & 0x0200) != 0 && size > 0 {
                        bus.fill_zeros(ptr, size);
                    }
                    cpu.write_reg(Register::A0, ptr);
                    cpu.write_reg(Register::D0, 0);
                }
                Ok(())
            }

            // NewHandle ($A022)
            // Allocates a new relocatable block and returns a handle to it. CLEAR variants zero the memory.
            // FUNCTION NewHandle (logicalSize: Size): Handle;
            // Inside Macintosh Volume II, II-27
            (false, 0x22) => {
                let size = cpu.read_reg(Register::D0);
                let ptr = bus.alloc(size);
                if ptr == 0 && size > 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    return Some(Ok(()));
                }
                // Check CLEAR bit (bit 9 = 0x0200 in trap word)
                if (self.current_trap_word & 0x0200) != 0 && size > 0 {
                    bus.fill_zeros(ptr, size);
                }
                let handle = bus.alloc(4);
                bus.write_long(handle, ptr);
                // Track the ptr → handle mapping so RecoverHandle can find
                // this handle later given just its master pointer's data
                // address. Inside Macintosh Volume V, V-579.
                self.ptr_to_handle.insert(ptr, handle);
                cpu.write_reg(Register::A0, handle);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // NewEmptyHandle ($A166)
            // Allocates a master pointer set to NIL without allocating a data block.
            // FUNCTION NewEmptyHandle: Handle;
            // Inside Macintosh: Memory, 2-33
            // NewEmptyHandle ($A066): Allocates master pointer set to NIL, no data block
            (false, 0x66) => {
                let handle = bus.alloc(4);
                if handle == 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                } else {
                    bus.write_long(handle, 0); // master pointer = NIL
                    cpu.write_reg(Register::A0, handle);
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // DisposePtr ($A01F): A0 = pointer to free
            // DisposePtr ($A01F): Frees pointer via bus.free(), returns noErr
            (false, 0x1F) => {
                let ptr = cpu.read_reg(Register::A0);
                bus.free(ptr);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // DisposeHandle ($A023)
            // Releases the relocatable block and frees the master pointer for other uses.
            // PROCEDURE DisposeHandle (h: Handle);
            // Inside Macintosh: Memory 1992, 2-34..2-35
            (false, 0x23) => {
                let handle = cpu.read_reg(Register::A0);
                let trap_site = cpu.read_reg(Register::PC).wrapping_sub(2);
                if let Some((_ptr, res_type, res_id)) = self.loaded_handles.get(&handle).copied() {
                    if &res_type == b".256" {
                        eprintln!(
                            "[MEM] DisposeHandle .256 id={} handle=${:08X}",
                            res_id, handle
                        );
                    }
                }
                self.detached_handles.remove(&handle);
                self.resource_handle_files.remove(&handle);
                self.detached_handle_files.remove(&handle);
                self.handle_state_bits.remove(&handle);
                if handle != 0 {
                    let data_ptr = bus.read_long(handle);
                    if trace_memory_site(trap_site) {
                        eprintln!(
                            "[MEM] DisposeHandle @${:08X} handle=${:08X} ptr=${:08X}",
                            trap_site, handle, data_ptr
                        );
                    }
                    // Do NOT remove data_ptr from ptr_to_handle here. On real
                    // Mac OS, DisposeHandle frees the master pointer but does
                    // not zero it; the freed slot still holds the old data
                    // address. RecoverHandle scans all master pointer slots
                    // (including freed ones), so it returns the stale handle
                    // rather than nil. We replicate this by leaving the stale
                    // entry in ptr_to_handle; NewHandle will overwrite it if
                    // the address is ever reused. (IM:V V-579)
                    bus.free(data_ptr);
                    bus.free(handle);
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // VInstall ($A033)
            // Installs a VBL task record into the system-based vertical
            // retrace queue. The task's vblAddr routine is executed when
            // its vblCount expires.
            // FUNCTION VInstall (vblTaskPtr: QElemPtr): OSErr;
            // Inside Macintosh: Processes (1994), pp. 4-24..4-25
            //
            // Register convention (IM:Processes 1994 p. 4-24):
            //   On entry: A0 = pointer to the VBL task record.
            //   On exit:  D0 = result code (noErr 0 | vTypErr -2).
            //
            // OS-bit FUNCTION ABI: no Pascal stack frame, no result slot —
            // A0 carries the input, D0 carries the OSErr result. The MPW
            // Universal Headers Retrace.h exposes:
            //   #pragma parameter __D0 VInstall(__A0)
            //   EXTERN_API(OSErr) VInstall(QElemPtr vblTaskPtr)
            //       ONEWORDINLINE(0xA033);
            //
            // VBLTask record layout (IM:Processes 1994 p. 4-7..4-8):
            //   +0   qLink     QElemPtr   set by VInstall
            //   +4   qType     INTEGER    must be ORD(vType) = 1
            //   +6   vblAddr   ProcPtr    interrupt-time routine
            //  +10   vblCount  INTEGER    interrupts until next call
            //  +12   vblPhase  INTEGER    phase shift added on install
            //
            // Result codes (IM:Processes 1994 p. 4-25):
            //   noErr   (0)  — task added to the system VBL queue.
            //   vTypErr (-2) — qType field is not ORD(vType).
            //
            // Strict bake witness: a033_a034_vinstall_vremove_strict
            // (engines-agree on both noErr and vTypErr return paths).
            // Contract tests: src/trap/memory.rs vinstall_consumes_a0_taskptr_...,
            // vinstall_invalid_qtype_returns_vtyperr,
            // vinstall_then_vremove_roundtrip_returns_noerr_on_both_and_qerr_on_second_remove.
            (false, 0x33) => {
                let task_ptr = cpu.read_reg(Register::A0);
                cpu.write_reg(
                    Register::D0,
                    self.install_vbl_task(bus, task_ptr, None) as u16 as u32,
                );
                Ok(())
            }

            // VRemove ($A034)
            // Removes a VBL task record from the system-based vertical
            // retrace queue.
            // FUNCTION VRemove (vblTaskPtr: QElemPtr): OSErr;
            // Inside Macintosh: Processes (1994), pp. 4-25..4-26
            //
            // Register convention (IM:Processes 1994 p. 4-26):
            //   On entry: A0 = pointer to the VBL task record.
            //   On exit:  D0 = result code (noErr 0 | qErr -1 | vTypErr -2).
            //
            // OS-bit FUNCTION ABI: same register-only shape as VInstall.
            // MPW Universal Headers Retrace.h:
            //   #pragma parameter __D0 VRemove(__A0)
            //   EXTERN_API(OSErr) VRemove(QElemPtr vblTaskPtr)
            //       ONEWORDINLINE(0xA034);
            //
            // Result codes (IM:Processes 1994 p. 4-26):
            //   noErr   (0)  — task removed from the queue.
            //   qErr    (-1) — task record isn't in the queue.
            //   vTypErr (-2) — qType field is not ORD(vType).
            //
            // Strict bake witness: a033_a034_vinstall_vremove_strict
            // (engines-agree on both noErr and qErr return paths).
            // Contract tests: src/trap/memory.rs vremove_consumes_a0_taskptr_...,
            // vremove_task_not_in_queue_returns_qerr,
            // vinstall_then_vremove_roundtrip_returns_noerr_on_both_and_qerr_on_second_remove.
            (false, 0x34) => {
                let task_ptr = cpu.read_reg(Register::A0);
                cpu.write_reg(
                    Register::D0,
                    self.remove_vbl_task(bus, task_ptr, None) as u16 as u32,
                );
                Ok(())
            }

            // HLock ($A029) / HUnlock ($A02A) / MoveHHi ($A064)
            // Locks or unlocks a relocatable block in its heap zone.
            // PROCEDURE HLock (h: Handle); PROCEDURE HUnlock (h: Handle);
            // Inside Macintosh Volume II, II-34
            (false, 0x29) | (false, 0x2A) | (false, 0x64) => {
                let handle = cpu.read_reg(Register::A0);
                if handle != 0 {
                    match trap_num {
                        0x29 => {
                            let bits = self.handle_state_bits.entry(handle).or_insert(0);
                            *bits |= 0x80; // lock bit
                        }
                        0x2A => {
                            let bits = self.handle_state_bits.entry(handle).or_insert(0);
                            *bits &= !0x80;
                        }
                        _ => {
                            if self.res_purge {
                                let _ = self.write_resource_backing_if_changed(handle);
                            }
                        }
                    }
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // GetHandleSize ($A025)
            // Returns the logical size in bytes of the relocatable block whose handle is h.
            // FUNCTION GetHandleSize (h: Handle): Size;
            // Inside Macintosh Volume II, II-31
            (false, 0x25) => {
                let handle = cpu.read_reg(Register::A0);
                let trap_site = cpu.read_reg(Register::PC).wrapping_sub(2);
                if handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                } else {
                    let ptr = bus.read_long(handle);
                    let size = bus.get_alloc_size(ptr).unwrap_or(0);
                    if trace_memory_site(trap_site) {
                        eprintln!(
                            "[MEM] GetHandleSize @${:08X} handle=${:08X} ptr=${:08X} size={}",
                            trap_site, handle, ptr, size
                        );
                    }
                    cpu.write_reg(Register::D0, size);
                }
                Ok(())
            }

            // GetTrapAddress ($A046/$A146/$A346/$A746)
            // Returns the address of a trap handler. Used by apps to check
            // if a trap is implemented (comparing against _Unimplemented).
            // Register-based: D0.W = trap number -> A0 = trap address
            // Inside Macintosh Volume II, II-384
            //
            // Tool traps get a 2-byte trampoline stub (auto-pop variant
            // of the trap word) so games that `JSR (A0)` through the
            // returned address re-enter the trap dispatcher cleanly
            // instead of executing garbage memory at a bare fake-ptr.
            // OS traps fall back to the simple `$00F0xxxx` fake-ptr
            // because they have no auto-pop semantics. See
            // `TrapDispatcher::get_or_create_tool_trap_trampoline`.
            // GetTrapAddress ($A046): Checks native_trap_table; tool traps return a callable trampoline (auto-pop variant), OS traps return $F0xxxx fake-ptr per IM:II II-384
            (false, 0x46) => {
                let trap_word = cpu.read_reg(Register::D0) as u16;
                let trap_variant = self.current_trap_word & 0x0FFF;
                // Check native trap table first (returns address set by SetTrapAddress)
                if let Some(&addr) = self.native_trap_table.get(&trap_word) {
                    cpu.write_reg(Register::A0, addr);
                } else if trap_variant == 0x746 {
                    // Real GetToolTrapAddress/GetToolBoxTrapAddress
                    // (trap word $A746) passes a bare tool-trap number
                    // in D0. Return a callable tool-trap trampoline so
                    // guests can JSR/JMP through the result.
                    //
                    // DockingDispatch (0x257) is absent on the generic
                    // target, so collapse that probe to _Unimplemented
                    // (0xA89F) just like the other probe forms.
                    let trap_num = trap_word & 0x03FF;
                    let canonical_tool_trap = if trap_num == 0x257 {
                        0xA89F
                    } else {
                        0xA800 | trap_num
                    };
                    let addr = self.get_or_create_tool_trap_trampoline(bus, canonical_tool_trap);
                    cpu.write_reg(Register::A0, addr);
                } else if trap_word == 0xAA57 {
                    // DockingDispatch is PowerBook-only. On the generic
                    // non-PowerBook target we alias the probe to the
                    // existing _Unimplemented trampoline so callers that
                    // compare against GetTrapAddress($A89F) see the trap
                    // as absent rather than as a callable DockingDispatch
                    // entry. IM:II II-384; IM:I I-89.
                    let addr = self.get_or_create_tool_trap_trampoline(bus, 0xA89F);
                    cpu.write_reg(Register::A0, addr);
                } else if trap_word == 0x257 {
                    // NGetTrapAddress() probe for DockingDispatch uses
                    // the low-number tool-trap form. Alias that probe to
                    // the same unimplemented sentinel used for 0x09F so
                    // selector-0 availability checks compare equal.
                    cpu.write_reg(Register::A0, 0xCAFE0000 + 0x09F);
                } else if (trap_word & 0x0800) != 0 {
                    // Tool trap (bit 11 set in the word): hand back a
                    // callable trampoline so JSR-through-fake-ptr works.
                    let addr = self.get_or_create_tool_trap_trampoline(bus, trap_word);
                    cpu.write_reg(Register::A0, addr);
                } else {
                    // OS trap (or bare trap number from NGetTrapAddress
                    // where the caller only intends address comparison):
                    // unique fake address per word so it never matches
                    // _Unimplemented.
                    let fake_addr = 0x00F00000 | (trap_word as u32);
                    cpu.write_reg(Register::A0, fake_addr);
                }
                Ok(())
            }

            // BlockMove ($A02E)
            // Copies a block of bytes from one location to another.
            // A0 = source, A1 = destination, D0 = byte count.
            // Works correctly even when the ranges overlap.
            // Inside Macintosh Volume II, II-44; Memory 1992, 2-59 to 2-60
            // BlockMove / BlockMoveData ($A02E): Copies D0 bytes from A0 to A1 and preserves overlap semantics; BlockMoveData ($A22E) handled identically (no caches in emulator)
            (false, 0x2E) => {
                let src = cpu.read_reg(Register::A0);
                let dst = cpu.read_reg(Register::A1);
                let count = cpu.read_reg(Register::D0);
                let trap_site = cpu.read_reg(Register::PC).wrapping_sub(2);
                if trace_memory_site(trap_site) {
                    let preview_len = count.min(16) as usize;
                    eprintln!(
                        "[MEM] BlockMove @${:08X} src=${:08X} dst=${:08X} count={} bytes={:02X?}",
                        trap_site,
                        src,
                        dst,
                        count,
                        bus.read_bytes(src, preview_len)
                    );
                }
                // Fast path via MacMemoryBus::block_move — uses
                // slice::copy_within for in-RAM copies with overlap
                // handling, falls back to byte-at-a-time for edge
                // cases (watchpoint armed, crosses RAM boundary).
                bus.block_move(src, dst, count);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // Phantom GetToolTrapAddress arm for is_tool=true && idx=0x346.
            //
            // Real GetTrapAddress / GetOSTrapAddress / GetToolTrapAddress
            // (trap words $A046 / $A146 / $A346 / $A746) all have bit
            // 11 = 0, so they reach the (false, 0x46) handler above —
            // *not* this arm. No assigned trap word in the IM trap
            // tables has lower-10-bits 0x346 with bit 11 set, so this
            // handler is unreachable from real guest code.
            //
            // Kept (rather than excised) only because legacy lib tests
            // call dispatch_memory(true, 0x346, ...) directly to
            // exercise the historical $CAFE0xxx fake-ptr emit path —
            // that path's *decoder* in runner.rs::decode_fakeptr_pc is
            // still active diagnostic surface (see
            // decode_fakeptr_pc_recognizes_tool_style_range).
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::phantom_gettooltrapaddress_returns_native_table_entry_and_preserves_stack
            //   src/trap/memory.rs::tests::test_get_tool_trap_address_docking_dispatch_aliases_unimplemented_probe
            //   src/trap/memory.rs::tests::phantom_gettooltrapaddress_creates_stable_trampoline_for_tool_trap_word
            //   src/trap/memory.rs::tests::test_get_tool_trap_address_tool
            // Inside Macintosh Volume II, II-384
            // (phantom GetToolTrapAddress) ($AB46): Unreachable from real guest code; emits $CAFE0xxx fake-ptr only via direct dispatch_memory test calls
            (true, 0x346) => {
                let trap_word = cpu.read_reg(Register::D0) as u16;
                if let Some(&addr) = self.native_trap_table.get(&trap_word) {
                    cpu.write_reg(Register::A0, addr);
                } else if trap_word == 0x257 {
                    // DockingDispatch probe uses the low-number tool-trap
                    // form when callers go through NGetTrapAddress.
                    // Mirror the same fake-ptr sentinel as the Unimplemented
                    // tool trap probe so the two addresses compare equal.
                    cpu.write_reg(Register::A0, 0xCAFE0000 + 0x09F);
                } else if (trap_word & 0x0800) != 0 {
                    let addr = self.get_or_create_tool_trap_trampoline(bus, trap_word);
                    cpu.write_reg(Register::A0, addr);
                } else {
                    let t = trap_word as u32 & 0x3FF;
                    cpu.write_reg(Register::A0, 0xCAFE0000 + t);
                }
                Ok(())
            }

            // SetTrapAddress ($A047/$A647 = (false, 0x47))
            // Installs a native 68K trap handler.
            // D0.W = trap number, A0 = new handler address
            // Inside Macintosh Volume II, II-384
            // SetTrapAddress ($A047): Installs native 68K trap handler via D0=trap word, A0=handler; per IM:II II-384
            (false, 0x47) => {
                let trap_word = cpu.read_reg(Register::D0) as u16;
                let handler_addr = cpu.read_reg(Register::A0);
                // Restore-to-default detection: when SetTrapAddress
                // sees an address that *we* handed back from a prior
                // GetTrapAddress (either the legacy $00F0xxxx fake-ptr
                // range OR a tool-trap trampoline allocated by
                // get_or_create_tool_trap_trampoline), the game is
                // saying "put it back the way you found it" and the
                // correct response is to remove our native_trap_table
                // entry so subsequent traps go through the HLE
                // dispatcher chain again.
                //
                // Without the trampoline arm, games that read +
                // restore tool-trap addresses (e.g. Steel Fighters'
                // ExitToShell shim) would store the trampoline
                // address back into native_trap_table, and dispatch
                // would JMP to the trampoline, which re-traps with
                // auto-pop, which re-enters dispatch, which JMPs to
                // the trampoline … infinite loop.
                let is_legacy_fakeptr = (handler_addr & 0xFFFF0000) == 0x00F00000;
                let is_trampoline = self
                    .tool_trap_trampolines
                    .values()
                    .any(|&addr| addr == handler_addr);
                if is_legacy_fakeptr || is_trampoline {
                    self.native_trap_table.remove(&trap_word);
                } else {
                    self.native_trap_table.insert(trap_word, handler_addr);
                }
                Ok(())
            }

            // StripAddress ($A055)
            // Strips the high byte of a 24-bit address. No-op in 32-bit mode.
            // Inside Macintosh Volume V, V-593
            // StripAddress ($A055): Returns A0 unchanged
            (false, 0x55) => Ok(()),

            // SwapMMUMode ($A05D)
            // Sets the addressing mode to the value in D0 (0=24-bit, 1=32-bit)
            // and returns the previous mode in D0.
            // PROCEDURE SwapMMUMode (VAR mode: Byte);
            // Inside Macintosh Volume V, V-593
            // SwapMMUMode ($A05D): Sets addressing mode (D0=0 for 24-bit, 1 for 32-bit), returns previous mode in D0
            (false, 0x5D) => {
                let new_mode = cpu.read_reg(Register::D0) & 0xFF;
                let old_mode = self.mmu_mode as u32;
                self.mmu_mode = (new_mode & 1) as u8;
                cpu.write_reg(Register::D0, old_mode);
                Ok(())
            }

            // SlotVInstall ($A06F): A0 = VBLTaskPtr, D0 = slot, D0 = result code
            // Processes 1994, 4-22 to 4-23
            // SlotVInstall ($A06F): Installs slot-VBLTask via install_vbl_task with slot from D0; A0=VBLTaskPtr, D0=OSErr
            (false, 0x6F) => {
                let task_ptr = cpu.read_reg(Register::A0);
                let slot = cpu.read_reg(Register::D0) as u16 as i16;
                cpu.write_reg(
                    Register::D0,
                    self.install_vbl_task(bus, task_ptr, Some(slot)) as u16 as u32,
                );
                Ok(())
            }

            // SlotVRemove ($A070) shares trap space with a compatibility
            // register-based GetNextEvent shim in event.rs. Only claim it when
            // A0 clearly points at a VBLTask record.
            // Processes 1994, 4-23 to 4-24
            // SlotVRemove ($A070): Removes slot-VBLTask via remove_vbl_task; gated to claim only when A0 points at VBLTask record (qType=1) — defers to event.rs GetNextEvent shim otherwise
            (false, 0x70) => {
                let task_ptr = cpu.read_reg(Register::A0);
                if task_ptr == 0 || bus.read_word(task_ptr + 4) as i16 != 1 {
                    return None;
                }
                let slot = cpu.read_reg(Register::D0) as u16 as i16;
                cpu.write_reg(
                    Register::D0,
                    self.remove_vbl_task(bus, task_ptr, Some(slot)) as u16 as u32,
                );
                Ok(())
            }

            // PurgeSpace ($A062)
            // Returns total purgeable space in A0 and contiguous
            // largest free block (after purging) in D0.
            // PROCEDURE PurgeSpace(VAR total: LongInt; VAR contig: LongInt);
            // Inside Macintosh Volume IV, IV-14 (assembly note:
            // A0 = total free if all purgeable blocks were
            // purged; D0 = largest contiguous free block).
            //
            // HLE compromise: Systemless doesn't model heap
            // fragmentation OR purgeable resource blocks (every
            // allocation is permanent until explicitly freed),
            // so "total" and "contiguous" both collapse to the
            // free_heap_estimate value (ApplLimit - HeapEnd
            // clamped to [24MB, 64MB] — same helper used by
            // FreeMem / MaxMem / CompactMem). Apps that probe
            // PurgeSpace before a large allocation to gate "do
            // I have enough room?" see the same 24MB-floor
            // answer those companion traps return — consistent
            // across the heap-introspection family.
            //
            // Previous stub returned a hardcoded 4MB constant
            // which underestimated the available memory and
            // could trip games that gate at "free >= 8 MB" type
            // checks. The free_heap_estimate floor at 24MB
            // satisfies all known minimum-RAM gates while still
            // reading real low-mem state.
            // PurgeSpace ($A062): Per IM:IV IV-14 returns total free space (after purging purgeable blocks) in A0 and largest contiguous free block in D0; Systemless doesn't model fragmentation or purgeable blocks so both registers get the free_heap_estimate value (ApplLimit - HeapEnd clamped to [24MB, 64MB] — same helper used by FreeMem / MaxMem / CompactMem). Replaces a prior hardcoded 4MB constant that was below modern minimum-RAM gates.
            (false, 0x62) => {
                let free = free_heap_estimate(bus);
                cpu.write_reg(Register::A0, free); // total purgeable
                cpu.write_reg(Register::D0, free); // largest contiguous
                Ok(())
            }

            // SysEnvirons ($A090)
            // FUNCTION SysEnvirons (versionRequested: INTEGER; VAR theWorld: SysEnvRec): OSErr;
            // Inside Macintosh Volume V, V-6
            // SysEnvirons ($A090): Hardcoded: sysVers=0x0700, machType=9, FPU/Color/68020 all true
            (false, 0x90) => {
                let mut a0 = cpu.read_reg(Register::A0);
                let _version = cpu.read_reg(Register::D0) & 0xFFFF;
                let a5 = cpu.read_reg(Register::A5);

                if a5 == 0 {
                    let saved_a5 = bus.read_long(0x904); // CurrentA5
                    cpu.write_reg(Register::A5, saved_a5);
                    if a0 == 0x30 && saved_a5 != 0 {
                        a0 = saved_a5 + 0x30;
                    }
                }

                if a0 < 0x100 {
                    cpu.write_reg(Register::D0, 0xFFFF_FFCE); // -50 (paramErr)
                    return Some(Ok(()));
                }

                let rec_ptr = a0;
                bus.write_word(rec_ptr, 2); // environsVersion
                bus.write_word(rec_ptr + 2, ORACLE_MACHINE_PROFILE.gestalt_machine_type);
                bus.write_word(rec_ptr + 4, ORACLE_MACHINE_PROFILE.system_version_bcd);
                bus.write_word(
                    rec_ptr + 6,
                    ORACLE_MACHINE_PROFILE.gestalt_processor_type as u16,
                );
                bus.write_byte(rec_ptr + 8, u8::from(ORACLE_MACHINE_PROFILE.has_fpu()));
                bus.write_byte(rec_ptr + 9, 1); // hasColorQD
                bus.write_word(rec_ptr + 10, 0);
                bus.write_word(rec_ptr + 12, 0);
                bus.write_word(rec_ptr + 14, 0);

                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // FlushCodeCache ($A0BD)
            // Flushes the instruction cache.
            // PROCEDURE FlushCodeCache;
            // Memory 1992, 4-31
            // FlushCodeCache ($A0BD): Memory 1992, 4-31
            (false, 0xBD) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // Debugger / DebugStr ($ABFF)
            // Enters the system debugger if one is installed; otherwise returns immediately.
            // On System 7 without MacsBug, this is a no-op.
            // Steel Fighters and similar mid-90s titles call this trap
            // many times in tight self-check loops, so the log line is
            // gated behind SYSTEMLESS_TRACE_DEBUGGER_TRAP=1 to avoid
            // drowning stderr when those games run.
            // PROCEDURE Debugger;
            // Inside Macintosh: Processes (1994), p. 7-9;
            // Inside Macintosh: Memory (1992), p. 3-23
            // Debugger / DebugStr ($ABFF): HLE no-op when no debugger is installed
            (true, 0x3FF) => {
                if std::env::var_os("SYSTEMLESS_TRACE_DEBUGGER_TRAP").is_some() {
                    eprintln!(
                        "[TRAP] Debugger/DebugStr called - no debugger installed, continuing"
                    );
                }
                Ok(())
            }

            // SetApplLimit ($A02D)
            // Sets the application heap limit beyond which the heap can't expand.
            // PROCEDURE SetApplLimit (zoneLimit: Ptr);
            // Inside Macintosh: Memory 1992, 2-84..2-85; Inside Macintosh Volume II, II-30
            // SetApplLimit ($A02D): Writes zoneLimit to ApplLimit unless the current
            // heap already extends past zoneLimit, in which case the heap is not cut back.
            (false, 0x2D) => {
                let zone_limit = cpu.read_reg(Register::A0);
                let heap_end = bus.read_long(crate::memory::globals::addr::HEAP_END);
                let appl_limit = bus.read_long(crate::memory::globals::addr::APPL_LIMIT);

                if zone_limit >= heap_end {
                    if zone_limit != appl_limit {
                        bus.write_long(crate::memory::globals::addr::APPL_LIMIT, zone_limit);
                    }
                } else {
                    // IM:Memory 1992, p. 2-85:
                    // "If the zone already extends beyond the specified limit,
                    // the Memory Manager does not cut it back."
                    bus.write_long(crate::memory::globals::addr::APPL_LIMIT, appl_limit);
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // MaxApplZone ($A063)
            // PROCEDURE MaxApplZone;
            // Inside Macintosh: Memory 1992, pp. 2-27 and 2-74..2-75;
            // Inside Macintosh Volume II, II-30.
            //
            // Per IM:Memory 1-39: "If you call MaxApplZone at the
            // beginning of your program, the heap immediately extends
            // all the way up to ApplLimit." Systemless models that visible
            // effect by aligning the live heap end with the application
            // limit when the zone can still grow.
            (false, 0x63) => {
                let heap_end = bus.read_long(crate::memory::globals::addr::HEAP_END);
                let appl_limit = bus.read_long(crate::memory::globals::addr::APPL_LIMIT);
                if heap_end != appl_limit {
                    bus.write_long(crate::memory::globals::addr::HEAP_END, appl_limit);
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // MoreMasters ($A036)
            // PROCEDURE MoreMasters;
            // Inside Macintosh: Memory 1992, 1-43 + 2-50.
            //
            // Per IM:Memory 1-43 + 1-993: "The Memory Manager
            // allocates one master pointer block (containing 64
            // master pointers) for your application at launch
            // time, and you can call MoreMasters to request that
            // additional master pointer blocks be allocated."
            // HLE no-op: Systemless doesn't model a fixed-capacity
            // master-pointer table — handles are allocated via
            // bus.alloc(4) on demand, so there's no master-
            // pointer pool to grow. Apps that call MoreMasters
            // multiple times at startup (the canonical
            // "MoreMasters * 4" pattern that pre-allocates 256
            // handles to avoid fragmentation later) see no
            // observable difference — subsequent NewHandle calls
            // succeed regardless of how many times MoreMasters
            // was called.
            // MoreMasters ($A036): PROCEDURE MoreMasters — per IM:Memory 1992 1-43
            // and IM:II II-31 allocates an additional master pointer block
            // (64 master pointers). HLE no-op: Systemless doesn't model a fixed-capacity
            // master-pointer table, so the startup pre-allocation pattern has no
            // observable effect. Return noErr in D0 for assembly-language callers.
            (false, 0x36) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // ReadDateTime ($A039)
            // Reads seconds since midnight January 1, 1904 from the RTC chip.
            // FUNCTION ReadDateTime(VAR time: LongInt): OSErr;
            // Inside Macintosh Volume II, II-378; Operating System Utilities 1994, 4-17
            //
            // Per IM:II II-378: "ReadDateTime copies the current date-time information
            // from the clock chip into low memory." The RTC chip is authoritative;
            // ReadDateTime first reads the chip, then writes to the Time global ($020C),
            // then returns the value. On BasiliskII the RTC chip is the host clock, so
            // ReadDateTime always returns the host time regardless of any prior
            // SetDateTime write. Systemless matches this by reading from the host clock too.
            (false, 0x39) => {
                // Mac epoch = Jan 1, 1904. Unix epoch = Jan 1, 1970.
                // Offset = 66 years = 2082844800 seconds.
                const MAC_UNIX_OFFSET: u32 = 2_082_844_800;
                let unix_secs = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let mac_time = (unix_secs as u32).wrapping_add(MAC_UNIX_OFFSET);
                bus.write_long(0x020C, mac_time); // Time global
                let a0 = cpu.read_reg(Register::A0);
                if a0 != 0 {
                    bus.write_long(a0, mac_time);
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // ========== Heap-introspection family ==========
            //
            // Three register-based OS traps that report free /
            // largest-block / compactable space in the current
            // heap. All three share `free_heap_estimate(bus)`
            // which reads the ApplLimit + HeapEnd low-mem
            // globals, computes ApplLimit - HeapEnd, and clamps
            // to [24MB, 64MB] (24MB floor satisfies games that
            // sanity-check free memory before booting at higher
            // resolutions; 64MB cap protects legacy callers that
            // store the result in a signed LONG).
            //
            // HLE compromise: Systemless does NOT model heap
            // fragmentation — the "free", "max contiguous", and
            // "compactable" answers all collapse to the same
            // ApplLimit-HeapEnd-clamped estimate. Real Mac would
            // diverge: FreeMem returns the SUM of free blocks
            // (potentially fragmented), MaxMem returns the
            // largest single contiguous free block (smaller than
            // FreeMem when the heap is fragmented), CompactMem
            // returns the largest block AFTER compacting purgeable
            // resources. In our flat allocator there's no
            // fragmentation to expose, so the three traps share
            // the estimate. Apps that probe these values to gate
            // large allocations see the clamped 24MB-floor as
            // "plenty of memory available" — which lets games
            // that sanity-check 16MB / 24MB minimums proceed.

            // FreeMem ($A01C) — return total free memory in D0
            // FUNCTION FreeMem: LongInt;
            // Inside Macintosh Volume II, II-39
            // FreeMem ($A01C): Per IM:II II-39 returns total free memory in current heap; Systemless returns ApplLimit - HeapEnd clamped to [24MB, 64MB] via free_heap_estimate (Systemless doesn't model fragmentation so FreeMem == MaxMem == CompactMem). The 24MB floor satisfies legacy 16/24 MB minimum-RAM checks; the 64MB cap protects callers that store the result in a signed LONG.
            (false, 0x1C) => {
                cpu.write_reg(Register::D0, free_heap_estimate(bus));
                Ok(())
            }

            // MaxMem ($A01D / $A11D — both alias the same arm via
            // the OS-trap low-byte dispatch) — return max
            // contiguous block in D0, total free in A0
            // FUNCTION MaxMem(VAR grow: Size): Size;
            // Inside Macintosh Volume II, II-39
            // MaxMem ($A01D): Per IM:II II-39 returns largest contiguous free block in D0 and total free in A0 (assembly-language convention); Systemless returns free_heap_estimate in D0 and the same value in A0 (no fragmentation modeled, so largest contiguous == total free). $A11D variant (with grow zone) dispatches to the same arm via the OS-trap low-byte (0x1D) decode.
            (false, 0x1D) => {
                let free = free_heap_estimate(bus);
                cpu.write_reg(Register::D0, free);
                cpu.write_reg(Register::A0, free);
                Ok(())
            }

            // CompactMem ($A04C) — try to compact the heap until
            // a contiguous block of cbNeeded bytes is available;
            // return the largest block actually obtained in D0
            // FUNCTION CompactMem(cbNeeded: Size): Size;
            // Inside Macintosh Volume II, II-40
            // CompactMem ($A04C): Per IM:II II-40 takes cbNeeded in D0 and returns the largest free block (after compacting purgeable resources) in D0; Systemless doesn't model heap compaction so the cbNeeded input is IGNORED — returns the free_heap_estimate clamped to [24MB, 64MB], which is always > any sane cbNeeded that an app would pass.
            (false, 0x4C) => {
                cpu.write_reg(Register::D0, free_heap_estimate(bus));
                Ok(())
            }

            // SetHandleSize ($A024)
            // Changes the logical size of the relocatable block whose handle is h.
            // PROCEDURE SetHandleSize (h: Handle; newSize: Size);
            // On entry: A0 = handle, D0 = new size
            // On exit: D0 = result code
            // Inside Macintosh Volume II, II-43; Memory 1992, 2-58
            // SetHandleSize ($A024): Resizes handle: allocs new block, copies data, frees old, updates handle ptr
            (false, 0x24) => {
                let handle = cpu.read_reg(Register::A0);
                let new_size = cpu.read_reg(Register::D0);
                if let Some((ptr, res_type, res_id)) = self.loaded_handles.get(&handle).copied() {
                    if &res_type == b".256" {
                        let old_size = bus.get_alloc_size(ptr).unwrap_or(0);
                        eprintln!(
                            "[MEM] SetHandleSize .256 id={} handle=${:08X} ptr=${:08X} {} -> {}",
                            res_id, handle, ptr, old_size, new_size
                        );
                    }
                }
                if handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let old_ptr = bus.read_long(handle);
                let old_size = bus.get_alloc_size(old_ptr).unwrap_or(0);
                if old_size == new_size || (new_size + 3) & !3 == (old_size + 3) & !3 {
                    // Same aligned size — no work needed
                    cpu.write_reg(Register::D0, 0);
                } else {
                    let new_ptr = bus.alloc(new_size);
                    if new_ptr == 0 && new_size > 0 {
                        cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    } else {
                        // Copy min(old, new) bytes
                        let copy_len = old_size.min(new_size);
                        let bytes = bus.read_bytes(old_ptr, copy_len as usize);
                        bus.write_bytes(new_ptr, &bytes);
                        bus.free(old_ptr);
                        bus.write_long(handle, new_ptr);
                        // Update the ptr→handle map: the handle's data
                        // pointer just moved.
                        self.ptr_to_handle.remove(&old_ptr);
                        self.ptr_to_handle.insert(new_ptr, handle);
                        cpu.write_reg(Register::D0, 0); // noErr
                    }
                }
                Ok(())
            }

            // ReallocateHandle ($A027)
            // Allocates a new relocatable block for a handle whose master pointer is nil
            // (purged or disposed), updating the master pointer to the new block.
            // PROCEDURE ReallocateHandle (h: Handle; logicalSize: Size);
            // Inside Macintosh: Memory 1992, 2-44
            (false, 0x27) => {
                let handle = cpu.read_reg(Register::A0);
                let size = cpu.read_reg(Register::D0);
                let ptr = bus.alloc(size);
                if ptr == 0 && size > 0 {
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                } else {
                    // Drop the old ptr→handle mapping (if any) and
                    // install the new one.
                    let old_ptr = bus.read_long(handle);
                    if old_ptr != 0 {
                        self.ptr_to_handle.remove(&old_ptr);
                    }
                    bus.write_long(handle, ptr);
                    self.ptr_to_handle.insert(ptr, handle);
                    cpu.write_reg(Register::D0, 0);
                }
                Ok(())
            }

            // HandToHand ($A9E1 = toolbox 0x1E1) - register-based calling convention
            // Duplicates a handle: allocates a new relocatable block of the same
            // size and copies the data.
            // FUNCTION HandToHand (VAR theHndl: Handle): OSErr;
            // On entry: A0 = handle to duplicate
            // On exit:  A0 = new handle (copy), D0 = result code
            // Inside Macintosh Volume II, II-374; Memory 1992, 2-62
            // HandToHand ($A9E1): Duplicates handle: A0=src handle in, A0=new handle out, D0=result
            (true, 0x1E1) => {
                let src_handle = cpu.read_reg(Register::A0);
                if src_handle == 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let src_ptr = bus.read_long(src_handle);
                if src_ptr == 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let size = bus.get_alloc_size(src_ptr).unwrap_or(0);
                let new_ptr = bus.alloc(size);
                if new_ptr == 0 && size > 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    return Some(Ok(()));
                }
                let bytes = bus.read_bytes(src_ptr, size as usize);
                bus.write_bytes(new_ptr, &bytes);
                let new_handle = bus.alloc(4);
                bus.write_long(new_handle, new_ptr);
                cpu.write_reg(Register::A0, new_handle);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // PtrToXHand ($A9E2 = toolbox 0x1E2) - register-based calling convention
            // Copies data from a pointer into an existing relocatable block.
            // On entry: A0 = source pointer, A1 = destination handle, D0 = size
            // On exit:  A0 = destination handle, D0 = result code
            // Inside Macintosh Volume III, III-38; Memory 1992, 2-61
            // PtrToXHand ($A9E2): Copies ptr data into existing handle: A0=src ptr, A1=dst handle, D0=size
            (true, 0x1E2) => {
                let src_ptr = cpu.read_reg(Register::A0);
                let dst_handle = cpu.read_reg(Register::A1);
                let size = cpu.read_reg(Register::D0);
                cpu.write_reg(Register::A0, dst_handle);
                if dst_handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                // Resize destination handle to fit the data
                let dst_ptr = bus.read_long(dst_handle);
                let old_size = bus.get_alloc_size(dst_ptr).unwrap_or(0);
                let final_ptr = if (old_size + 3) & !3 != (size + 3) & !3 {
                    let new_ptr = bus.alloc(size);
                    if new_ptr == 0 && size > 0 {
                        cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                        return Some(Ok(()));
                    }
                    if dst_ptr != 0 {
                        bus.free(dst_ptr);
                    }
                    bus.write_long(dst_handle, new_ptr);
                    new_ptr
                } else {
                    // PtrToXHand's contract is about the handle's logical
                    // size, not just its aligned backing bucket. When the
                    // resize stays within the same 4-byte bucket (for
                    // example 3 -> 4 or 4 -> 1), update the recorded size
                    // so subsequent GetHandleSize observes the exact byte
                    // count the caller requested.
                    if dst_ptr != 0 {
                        bus.set_alloc_size(dst_ptr, size);
                    }
                    dst_ptr
                };
                let bytes = bus.read_bytes(src_ptr, size as usize);
                bus.write_bytes(final_ptr, &bytes);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // PtrToHand ($A9E3 = toolbox 0x1E3) - register-based calling convention
            // Copies data from a pointer into a new relocatable block.
            // On entry: A0 = source pointer, D0 = size
            // On exit:  A0 = new handle, D0 = result code
            // Inside Macintosh Volume III, III-38; Memory 1992, 2-60
            // PtrToHand ($A9E3): Copies ptr data into new handle: A0=src ptr, D0=size, A0=new handle out
            (true, 0x1E3) => {
                let src_ptr = cpu.read_reg(Register::A0);
                let size = cpu.read_reg(Register::D0);
                let ptr = bus.alloc(size);
                if ptr == 0 && size > 0 {
                    cpu.write_reg(Register::A0, 0);
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    return Some(Ok(()));
                }
                let bytes = bus.read_bytes(src_ptr, size as usize);
                bus.write_bytes(ptr, &bytes);
                let handle = bus.alloc(4);
                bus.write_long(handle, ptr);
                cpu.write_reg(Register::A0, handle);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // HandAndHand ($A9E4 = toolbox 0x1E4) - register-based calling convention
            // Concatenates the data from one handle onto the end of another.
            // FUNCTION HandAndHand(hand1, hand2: Handle): OSErr;
            // On entry: A0 = source handle (hand1), A1 = destination handle (hand2)
            // On exit:  A0 = destination handle (hand2), D0 = result code
            // Inside Macintosh Volume II, II-374; Memory 1992, 2-63
            // HandAndHand ($A9E4): Appends source handle data to destination handle: A0=src handle, A1=dst handle, D0=result; per IM:II II-374
            (true, 0x1E4) => {
                let src_handle = cpu.read_reg(Register::A0);
                let dst_handle = cpu.read_reg(Register::A1);
                cpu.write_reg(Register::A0, dst_handle);
                if src_handle == 0 || dst_handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let src_ptr = bus.read_long(src_handle);
                let dst_ptr = bus.read_long(dst_handle);
                if src_ptr == 0 || dst_ptr == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let src_size = bus.get_alloc_size(src_ptr).unwrap_or(0);
                let dst_size = bus.get_alloc_size(dst_ptr).unwrap_or(0);
                let new_size = dst_size + src_size;
                // Allocate new block for combined data
                let new_ptr = bus.alloc(new_size);
                if new_ptr == 0 && new_size > 0 {
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    return Some(Ok(()));
                }
                // Copy existing dst data, then append src data.
                let dst_bytes = bus.read_bytes(dst_ptr, dst_size as usize);
                bus.write_bytes(new_ptr, &dst_bytes);
                let src_bytes = bus.read_bytes(src_ptr, src_size as usize);
                bus.write_bytes(new_ptr.wrapping_add(dst_size), &src_bytes);
                bus.free(dst_ptr);
                bus.write_long(dst_handle, new_ptr);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // PtrAndHand ($A9EF = toolbox 0x1EF) - register-based calling convention
            // Concatenates data referenced by a pointer onto the end of a handle.
            // FUNCTION PtrAndHand(ptr1: Ptr; hand2: Handle; size: LongInt): OSErr;
            // On entry: A0 = source pointer (ptr1), A1 = destination handle (hand2), D0 = size
            // On exit:  A0 = destination handle (hand2), D0 = result code
            // Inside Macintosh Volume II, II-375; Memory 1992, 2-64
            // PtrAndHand ($A9EF): Appends ptr data to destination handle: A0=src ptr, A1=dst handle, D0=size in/result out; per IM:II II-375
            (true, 0x1EF) => {
                let src_ptr = cpu.read_reg(Register::A0);
                let dst_handle = cpu.read_reg(Register::A1);
                let append_size = cpu.read_reg(Register::D0);
                cpu.write_reg(Register::A0, dst_handle);
                if dst_handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let dst_ptr = bus.read_long(dst_handle);
                if dst_ptr == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let dst_size = bus.get_alloc_size(dst_ptr).unwrap_or(0);
                let new_size = dst_size + append_size;
                let new_ptr = bus.alloc(new_size);
                if new_ptr == 0 && new_size > 0 {
                    cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                    return Some(Ok(()));
                }
                // Copy existing dst data, then append source data.
                let dst_bytes = bus.read_bytes(dst_ptr, dst_size as usize);
                bus.write_bytes(new_ptr, &dst_bytes);
                let src_bytes = bus.read_bytes(src_ptr, append_size as usize);
                bus.write_bytes(new_ptr.wrapping_add(dst_size), &src_bytes);
                bus.free(dst_ptr);
                bus.write_long(dst_handle, new_ptr);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // RecoverHandle ($A128)
            // Searches the master pointer table for the handle pointing to p.
            // FUNCTION RecoverHandle (p: Ptr): Handle;
            // Inside Macintosh Volume V, V-579
            //
            // Scans all master pointer slots including freed ones. ptr_to_handle
            // retains stale entries after DisposeHandle (freed slots still hold
            // the old data address in ROM), so this correctly returns the stale
            // freed handle rather than nil — matching real Mac OS behavior.
            (false, 0x28) => {
                let ptr = cpu.read_reg(Register::A0);
                let handle = self.ptr_to_handle.get(&ptr).copied().unwrap_or(0);
                cpu.write_reg(Register::A0, handle);
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // SetPtrSize ($A020)
            // Changes the logical size of a nonrelocatable block.
            // On entry: A0 = pointer, D0 = newSize
            // On exit:  D0 = result code (noErr or memFullErr)
            // Inside Macintosh: Memory 1992, 2-44. Critical contract:
            // "SetPtrSize doesn't move the pointer" — the block stays at
            // its current address whether shrinking or growing.
            //
            // The current allocator is a bump allocator with a free-list;
            // in-place grow beyond the original 4-byte-aligned capacity
            // isn't tractable without a compaction pass. For shrink +
            // in-capacity-grow we update the stored logical size and keep
            // the pointer stable. For grow beyond the aligned capacity we
            // return memFullErr.
            // SetPtrSize ($A020): Resizes nonrelocatable block: allocs new, copies data, frees old, updates A0; per IM:II II-38
            (false, 0x20) => {
                let ptr = cpu.read_reg(Register::A0);
                let new_size = cpu.read_reg(Register::D0);
                if ptr == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                    return Some(Ok(()));
                }
                let old_size = bus.get_alloc_size(ptr).unwrap_or(0);
                let old_aligned = (old_size + 3) & !3;
                let new_aligned = (new_size + 3) & !3;
                if new_aligned <= old_aligned {
                    // Fits in the existing block — just update the
                    // logical size and zero the newly "freed" tail so
                    // the block reads clean for any subsequent
                    // SetPtrSize grow.
                    if new_size < old_size {
                        bus.fill_zeros(ptr.wrapping_add(new_size), old_size - new_size);
                    }
                    bus.set_alloc_size(ptr, new_size);
                    cpu.write_reg(Register::D0, 0); // noErr
                    return Some(Ok(()));
                }
                // Can't grow beyond aligned capacity without moving —
                // spec requires memFullErr rather than silently
                // moving the pointer.
                cpu.write_reg(Register::D0, (-108i32) as u32); // memFullErr
                Ok(())
            }

            // GetPtrSize ($A021)
            // Returns the logical size of the nonrelocatable block pointed to by A0.
            // On exit: D0 = size (or negative error code)
            // Inside Macintosh Volume II, II-39
            // GetPtrSize ($A021): Returns actual allocation size via `get_alloc_size`; per IM:II II-39
            (false, 0x21) => {
                let ptr = cpu.read_reg(Register::A0);
                let size = bus.get_alloc_size(ptr).unwrap_or(0);
                cpu.write_reg(Register::D0, size);
                Ok(())
            }

            // ========== Time Manager ==========

            // InsTime ($A058)
            // Installs a task record into the Time Manager queue.
            // PROCEDURE InsTime(tmTaskPtr: QElemPtr);
            // Processes 1994, 3-18
            // TMTask layout: qLink(+0,4) qType(+4,2) tmAddr(+6,4) tmCount(+10,4)
            (false, 0x58) => {
                let task_ptr = cpu.read_reg(Register::A0);
                let tm_addr = bus.read_long(task_ptr + 6);
                // Remove any existing task for the same record address
                self.timer_tasks.retain(|t| t.task_ptr != task_ptr);
                self.timer_tasks.push(super::dispatch::TimerTask {
                    task_ptr,
                    tm_addr,
                    active: false,
                    fire_at_tick: 0,
                });
                // InsTime clears the qType high-order bit (task inactive until PrimeTime).
                // Processes 1994, 3-12: "InsTime procedure initially clears this bit."
                let q = bus.read_word(task_ptr + 4);
                bus.write_word(task_ptr + 4, q & 0x7FFF);
                Ok(())
            }

            // RmvTime ($A059)
            // Removes a task from the Time Manager queue.
            // PROCEDURE RmvTime(tmTaskPtr: QElemPtr);
            // Processes 1994, 3-19
            (false, 0x59) => {
                let task_ptr = cpu.read_reg(Register::A0);
                self.timer_tasks.retain(|t| t.task_ptr != task_ptr);
                // RmvTime clears the qType high-order bit (task no longer active).
                // Processes 1994, 3-20: "RmvTime sets the high-order bit of the qType field to 0."
                let q = bus.read_word(task_ptr + 4);
                bus.write_word(task_ptr + 4, q & 0x7FFF);
                Ok(())
            }

            // PrimeTime ($A05A)
            // Activates a Time Manager task after a specified delay.
            // PROCEDURE PrimeTime(tmTaskPtr: QElemPtr; count: LongInt);
            // Positive delay = milliseconds, negative = negated microseconds.
            // Processes 1994, 3-19
            (false, 0x5A) => {
                let task_ptr = cpu.read_reg(Register::A0);
                let delay = cpu.read_reg(Register::D0) as i32;
                let current_ticks = bus.read_long(0x016A);
                // Convert delay to 60.15 Hz ticks (VBL rate per Guide to Macintosh Family
                // Hardware, 2nd Ed., p. 6-798: "once every 16.63 ms").
                // We use 60 (not 60.15) to keep integer arithmetic exact for common
                // millisecond values and avoid spurious ceil rounding.
                // Positive = milliseconds, negative = negated microseconds.
                // Round up so coarse tick emulation never fires earlier than requested.
                let delay_ticks = if delay == 0 {
                    1 // Fire ASAP (next tick)
                } else if delay > 0 {
                    (((delay as u64) * 60).div_ceil(1000) as u32).max(1)
                } else {
                    let us = (-delay) as u64;
                    ((us * 60).div_ceil(1_000_000) as u32).max(1)
                };
                let fire_at = current_ticks.wrapping_add(delay_ticks);
                if let Some(task) = self.timer_tasks.iter_mut().find(|t| t.task_ptr == task_ptr) {
                    task.active = true;
                    task.fire_at_tick = fire_at;
                    // Re-read tmAddr in case it changed between InsTime and PrimeTime
                    task.tm_addr = bus.read_long(task_ptr + 6);
                }
                // PrimeTime sets the qType high-order bit (task now active/primed).
                // Processes 1994, 3-20: "PrimeTime sets the high-order bit of the qType field to 1."
                let q = bus.read_word(task_ptr + 4);
                bus.write_word(task_ptr + 4, q | 0x8000);
                Ok(())
            }

            // Microseconds ($A193)
            // Returns the number of microseconds elapsed since system startup.
            // PROCEDURE Microseconds (VAR microTickCount: UnsignedWide);
            //
            // Calling convention (Inside Macintosh: Operating System
            // Utilities 1994, p. 4-49 + p. 6-805 and the MPW Universal
            // Headers Timer.h FOURWORDINLINE form):
            //
            //   Microseconds(UnsignedWide *buf)
            //     FOURWORDINLINE($A193, $225F, $22C8, $2280);
            //
            // After the inline expansion:
            //   1. Caller pushes `buf` onto A7.
            //   2. _Microseconds ($A193) — the trap returns the 64-bit
            //      microsecond count in registers (D0 = low 32 bits,
            //      A0 = high 32 bits). The trap itself does *not* write
            //      through any caller pointer; A0 on entry is scratch.
            //   3. MOVEA.L (A7)+, A1 ($225F) — pop `buf` into A1.
            //   4. MOVE.L A0, (A1)+ ($22C8) — write `hi` to *(buf+0)
            //      and post-increment A1 to buf+4.
            //   5. MOVE.L D0, (A1) ($2280) — write `lo` to *(buf+4).
            //
            // Systemless mirrors the register-return half of the trap; the
            // FOURWORDINLINE glue (emitted at every caller's call site
            // by MPW C) is responsible for storing the result through
            // the caller-supplied buffer. The HLE deliberately does
            // NOT pre-write through A0 because A0 is uninitialised on
            // entry under the FOURWORDINLINE pattern — speculatively
            // writing through it would corrupt unrelated guest memory.
            //
            // 1 tick = 1/60.15 s ≈ 16,625 µs (VBL fires every 16.63 ms
            // per Guide to Macintosh Family Hardware 2nd Ed., p. 6-798;
            // matches what the MPW Universal Headers FOURWORDINLINE
            // glue then materialises into the caller's UnsignedWide
            // buffer with `hi` at offset 0 and `lo` at offset 4).
            // Microseconds ($A193): returns D0=low 32 bits / A0=high 32 bits; per MPW Universal Headers Timer.h FOURWORDINLINE glue, the caller writes the 64-bit count through its UnsignedWide buffer pointer using these register values
            (false, 0x93) => {
                let ticks = bus.read_long(0x016A);
                let usecs = (ticks as u64) * 16_625;
                cpu.write_reg(Register::D0, usecs as u32);
                cpu.write_reg(Register::A0, (usecs >> 32) as u32);
                if trace_entropy_enabled() {
                    eprintln!(
                        "[ENTROPY] Microseconds pc=${:08X} ticks={} usecs={}",
                        cpu.read_reg(Register::PC),
                        ticks,
                        usecs
                    );
                }
                Ok(())
            }

            // ========== Handle state management ==========

            // HPurge ($A049) - mark handle as purgeable
            // Inside Macintosh Volume II, II-41
            // HPurge ($A049): Sets purgeable bit (0x40) in handle_state_bits per IM:II II-41
            (false, 0x49) => {
                let handle = cpu.read_reg(Register::A0);
                if handle != 0 {
                    let bits = self.handle_state_bits.entry(handle).or_insert(0);
                    *bits |= 0x40;
                }
                Ok(())
            }

            // HNoPurge ($A04A) - mark handle as non-purgeable
            // Inside Macintosh Volume II, II-41
            // HNoPurge ($A04A): Clears purgeable bit (0x40) in handle_state_bits per IM:II II-41
            (false, 0x4A) => {
                let handle = cpu.read_reg(Register::A0);
                if let Some(bits) = self.handle_state_bits.get_mut(&handle) {
                    *bits &= !0x40;
                    if *bits == 0 {
                        self.handle_state_bits.remove(&handle);
                    }
                }
                Ok(())
            }

            // HLock ($A029) / HUnlock ($A02A) already handled above

            // HGetState ($A069)
            // Returns a signed byte containing the flags of the master pointer for the given handle.
            // FUNCTION HGetState (h: Handle): SignedByte;
            // Memory 1992, 2-54
            (false, 0x69) => {
                let handle = cpu.read_reg(Register::A0);
                let mut state = self.handle_state_bits.get(&handle).copied().unwrap_or(0);
                if self.loaded_handles.contains_key(&handle) {
                    state |= 0x20; // resource bit
                }
                cpu.write_reg(Register::D0, state as u32);
                Ok(())
            }

            // HSetState ($A06A) - set handle state flags
            // HSetState ($A06A): Sets lock/purge bits (0xC0 mask) in handle_state_bits
            (false, 0x6A) => {
                let handle = cpu.read_reg(Register::A0);
                if handle != 0 {
                    let bits = (cpu.read_reg(Register::D0) as u8) & 0xC0;
                    if bits == 0 {
                        self.handle_state_bits.remove(&handle);
                    } else {
                        self.handle_state_bits.insert(handle, bits);
                    }
                }
                Ok(())
            }

            // HWPriv ($A198)
            // Hardware privilege trap for processor cache control.
            // Selector in D0: 0=SwapInstructionCache, 1=FlushInstructionCache,
            // 2=SwapDataCache, 3=FlushDataCache, 4-6=ExtCache, 9=FlushCodeCacheRange
            // Memory 1992, 4-29
            // HWPriv ($A198): Cache-control selectors (0/2 swap return previous
            // state and update the simulated enable bit; 1/3/4/5/6 flush no-op;
            // 9 range flush no-op) — Systemless has no physical caches but preserves
            // the documented stateful Boolean surface per Memory 1992, 4-29..4-33
            (false, 0x98) => {
                let selector = cpu.read_reg(Register::D0);
                match selector {
                    0 => {
                        // SwapInstructionCache:
                        // cacheEnable arrives in A0 as a register Boolean,
                        // and the previous state is returned in A0 on exit.
                        // The trap returns the previous state and installs the
                        // requested new state.
                        let requested_enabled = cpu.read_reg(Register::A0) != 0;
                        let previous_enabled = self.instruction_cache_enabled;
                        self.instruction_cache_enabled = requested_enabled;
                        let previous = if previous_enabled { 1 } else { 0 };
                        cpu.write_reg(Register::A0, previous);
                        cpu.write_reg(Register::D0, previous);
                    }
                    2 => {
                        // SwapDataCache: same stateful Boolean contract as
                        // SwapInstructionCache, but for the data cache.
                        let requested_enabled = cpu.read_reg(Register::A0) != 0;
                        let previous_enabled = self.data_cache_enabled;
                        self.data_cache_enabled = requested_enabled;
                        let previous = if previous_enabled { 1 } else { 0 };
                        cpu.write_reg(Register::A0, previous);
                        cpu.write_reg(Register::D0, previous);
                    }
                    1 | 3 | 4 | 5 | 6 => {
                        // Flush/enable/disable caches — no-op in emulation
                        cpu.write_reg(Register::D0, 0);
                    }
                    9 => {
                        // FlushCodeCacheRange: A0=address, A1=count
                        cpu.write_reg(Register::D0, 0); // noErr
                    }
                    _ => {
                        eprintln!("[TRAP] HWPriv: unknown selector {}", selector);
                        cpu.write_reg(Register::D0, 0);
                    }
                }
                Ok(())
            }

            // ========== Device Manager ==========

            // _Control ($A004)
            // Device Manager control call. Register-based: A0 = param block ptr.
            // FUNCTION PBControl (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh: Devices 1994, p. 1-16
            // _Control ($A004): Handles cscSetMode (csCode=2) by returning page/base address through the csParam VDPgInfoPtr and cscSetEntries (csCode=3) via VDSetEntryRecord; returns noErr
            (false, 0x04) => {
                let pb = cpu.read_reg(Register::A0);
                if pb != 0 {
                    let cs_code = bus.read_word(pb + 26) as i16;
                    // cscSetMode (csCode=2): switch mode/page and return base address.
                    // CntrlParam.csParam stores a VDPgInfoPtr for this call.
                    // VDPgInfo layout:
                    //   csMode [word] @ +0
                    //   csData [long] @ +2
                    //   csPage [word] @ +6
                    //   csBaseAddr [long] @ +8
                    // Designing Cards and Drivers 3rd Ed 1992, p. 219, 235
                    // Devices 1994, p. 2-128, 6-68
                    if cs_code == 2 {
                        let vdpg_info = bus.read_long(pb + 28);
                        let cs_mode = if vdpg_info != 0 {
                            bus.read_word(vdpg_info) as i16
                        } else {
                            0
                        };
                        let cs_data = if vdpg_info != 0 {
                            bus.read_long(vdpg_info + 2)
                        } else {
                            0
                        };
                        let cs_page = if vdpg_info != 0 {
                            bus.read_word(vdpg_info + 6) as i16
                        } else {
                            0
                        };
                        let mut screen_base = self.screen_mode.0;
                        if screen_base == 0 {
                            let gdh = self.ensure_main_gdevice(bus);
                            if gdh != 0 {
                                let gd = bus.read_long(gdh);
                                if gd != 0 {
                                    let pm_handle = bus.read_long(gd + 22); // gdPMap
                                    if pm_handle != 0 {
                                        let pm = bus.read_long(pm_handle);
                                        if pm != 0 {
                                            screen_base = bus.read_long(pm);
                                        }
                                    }
                                }
                            }
                        }

                        if trace_video_driver_enabled() {
                            eprintln!(
                                "[VIDEO] cscSetMode mode={} data=${:08X} page={} screen_mode=({}, {}, {}, {}, {})",
                                cs_mode,
                                cs_data,
                                cs_page,
                                self.screen_mode.0,
                                self.screen_mode.1,
                                self.screen_mode.2,
                                self.screen_mode.3,
                                self.screen_mode.4,
                            );
                        }

                        if vdpg_info != 0 {
                            // Single-screen HLE currently exposes page 0.
                            bus.write_word(vdpg_info + 6, 0); // csPage
                            bus.write_long(vdpg_info + 8, screen_base); // csBaseAddr
                        }
                    }

                    // cscSetEntries (csCode=3): update device CLUT via video driver.
                    // csParam[0..3] stores a Ptr to a VDSetEntryRecord on the
                    // caller's stack (see cseries.lib devices.c LowLevelSetEntries).
                    // VDSetEntryRecord layout (as compiled by MPW C for 68k):
                    //   csTable:  Ptr      {+0, pointer to ColorSpec array}
                    //   csStart:  INTEGER  {+4, first entry, or -1 for indexed mode}
                    //   csCount:  INTEGER  {+6, number of entries minus 1}
                    // Designing Cards and Drivers 3rd Ed 1992, p. 245-248
                    // Inside Macintosh: Devices 1994, p. 1-16 (CntrlParam.csParam)
                    if cs_code == 3 {
                        let trap_pc = cpu.read_reg(Register::PC).wrapping_sub(2);
                        let vd_ptr = bus.read_long(pb + 28);
                        let cs_table = bus.read_long(vd_ptr);
                        let cs_start = bus.read_word(vd_ptr + 4) as i16;
                        let cs_count = bus.read_word(vd_ptr + 6) as i16;
                        // Clamp to valid range for 8-bit device (0..255).
                        // csCount can contain stale stack data; treat negative
                        // values as full-CLUT (255) and cap oversized values.
                        let safe_count = if cs_count < 0 { 255 } else { cs_count.min(255) };
                        if trace_video_driver_enabled() {
                            eprintln!(
                                "[VIDEO] cscSetEntries table=${:08X} start={} count={} safe_count={}",
                                cs_table, cs_start, cs_count, safe_count
                            );
                            let preview_entries = (safe_count as u32 + 1).min(4);
                            for i in 0..preview_entries {
                                let entry_addr = cs_table + i * 8;
                                eprintln!(
                                    "[VIDEO]   spec[{}] value={} rgb=({:04X},{:04X},{:04X})",
                                    i,
                                    bus.read_word(entry_addr) as i16,
                                    bus.read_word(entry_addr + 2),
                                    bus.read_word(entry_addr + 4),
                                    bus.read_word(entry_addr + 6),
                                );
                            }
                            for i in [43u32, 100, 150, 185, 220, 245] {
                                if i > safe_count as u32 {
                                    continue;
                                }
                                let entry_addr = cs_table + i * 8;
                                eprintln!(
                                    "[VIDEO]   spec[{}] value={} rgb=({:04X},{:04X},{:04X})",
                                    i,
                                    bus.read_word(entry_addr) as i16,
                                    bus.read_word(entry_addr + 2),
                                    bus.read_word(entry_addr + 4),
                                    bus.read_word(entry_addr + 6),
                                );
                            }
                        }
                        // Apply palette BEFORE logging so screenshots see updated CLUT.
                        self.apply_set_entries(bus, cs_table, cs_start, safe_count);
                        if let Err(err) = self.record_oracle_event(
                            bus,
                            trap_pc,
                            "video_set_entries",
                            Self::oracle_palette_field_map(bus, cs_table, cs_start, safe_count),
                            true,
                        ) {
                            return Some(Err(err));
                        }
                    }

                    // cscSetGamma (csCode=4): install a per-channel gamma
                    // correction table. csParam[0..3] stores a Ptr to a
                    // GammaTbl in Pascal format (version, type, formula size,
                    // chan count, data count, data width, data bytes).
                    //
                    // Systemless does NOT yet install a runtime gamma — we have
                    // a fixed Mac HiRes linear-interpolated gamma LUT in
                    // `display.rs`. Stub returns noErr.
                    //
                    // Designing Cards and Drivers 3rd Ed 1992, p. 245-248
                    // Inside Macintosh: Devices 1994, p. 6-71
                    if cs_code == 4 && trace_video_driver_enabled() {
                        let gamma_ptr = bus.read_long(pb + 28);
                        let g_version = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr) as i16
                        } else {
                            -1
                        };
                        let g_type = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr + 2) as i16
                        } else {
                            -1
                        };
                        let g_formula_size = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr + 4) as i16
                        } else {
                            -1
                        };
                        let g_chan_cnt = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr + 6) as i16
                        } else {
                            -1
                        };
                        let g_data_cnt = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr + 8) as i16
                        } else {
                            -1
                        };
                        let g_data_width = if gamma_ptr != 0 {
                            bus.read_word(gamma_ptr + 10) as i16
                        } else {
                            -1
                        };
                        eprintln!(
                                "[VIDEO] cscSetGamma gamma_ptr=${:08X} version={} type={} formulaSize={} chanCnt={} dataCnt={} dataWidth={}",
                                gamma_ptr,
                                g_version,
                                g_type,
                                g_formula_size,
                                g_chan_cnt,
                                g_data_cnt,
                                g_data_width,
                            );
                        // Preview first 16 data bytes for confirmation
                        if gamma_ptr != 0 && g_data_cnt > 0 && g_data_width == 8 {
                            let data_base = gamma_ptr + 12 + g_formula_size.max(0) as u32;
                            let preview_n = g_data_cnt.min(16) as u32;
                            let mut bytes = Vec::with_capacity(preview_n as usize);
                            for i in 0..preview_n {
                                bytes.push(bus.read_byte(data_base + i));
                            }
                            eprintln!("[VIDEO]   gamma data[0..{}] = {:02X?}", preview_n, bytes);
                        }
                    }
                    // Succeed without applying — keeps Marathon from
                    // thinking its gamma setup failed. Actual gamma
                    // application pending full implementation.
                    bus.write_word(pb + 16, 0); // ioResult = noErr
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PBStatus (_Status, 0xA005)
            // Invokes the Status routine of the driver whose reference number is in
            // the ioRefNum field of the parameter block.
            // FUNCTION PBStatus (paramBlock: ParmBlkPtr; async: BOOLEAN): OSErr;
            // Inside Macintosh: Devices (1994), pp. 1-79 to 1-80;
            // Inside Macintosh Volume II (1985), p. II-189.
            //
            // Per IM:Devices 1994 p. 1-80 + IM:II 1985 p. II-189 the trap
            // is an OS-bit FUNCTION (bit 11 of the trap word is clear)
            // with a register-only ABI:
            //
            //   Registers on entry:
            //     A0  Pointer to the parameter block (ParmBlkPtr)
            //
            //   Registers on exit:
            //     D0  Result code (OSErr)
            //
            // No Pascal stack argument frame is consumed.
            //
            // Per IM:II 1985 p. II-114 (Device Manager parameter-block
            // dispatcher convention), the OSErr returned by the driver
            // Status routine is mirrored into BOTH D0 AND the ioResult
            // field of the parameter block at offset +16:
            //
            //   ioCompletion @ +12  (NIL for synchronous calls)
            //   ioResult     @ +16  (function result mirrored from D0)
            //   ioNamePtr    @ +18  (unused by PBStatus)
            //   ioVRefNum    @ +22  (unused by PBStatus)
            //   ioRefNum     @ +24  (driver reference number)
            //
            // MPW Universal Headers Devices.h declares:
            //   #pragma parameter __D0 PBStatusSync(__A0)
            //   EXTERN_API(OSErr) PBStatusSync(ParmBlkPtr paramBlock)
            //                                  ONEWORDINLINE(0xA005);
            // plus #define PBStatus(pb,async) macro dispatching to
            // PBStatusSync/PBStatusAsync. The Async ($A405) and Immed
            // ($A205) variants share the same A0/D0 register convention.
            //
            // Systemless HLE compromise: the single-threaded synchronous-I/O
            // HLE has no installed Device Manager drivers and no Status
            // routines to invoke. The trap returns noErr (0) for the
            // zero/refNum-cleared path and collapses any non-zero ioRefNum
            // to badUnitErr (-21), mirroring that into pb.ioResult. That
            // keeps the dispatcher convention (D0 == ioResult) intact while
            // making the bogus-refnum path visibly non-successful.
            //
            // Apple-vs-BasiliskII engine divergence: the absolute OSErr
            // returned for a bogus ioRefNum (e.g. 9999) diverges between
            // engines — Systemless collapses the miss to badUnitErr (-21),
            // while BasiliskII dispatches the real ROM trap and is expected
            // to return badUnitErr (-21) or unitEmptyErr (-22) for a refNum
            // that does not map to an installed driver. Both engines obey
            // the dispatcher convention writing the SAME value to BOTH D0
            // and ioResult, so the engines-agree witness is "D0 == ioResult
            // AND ioResult != pre-poison sentinel" (proved by the strict
            // bake) rather than an absolute OSErr value.
            //
            // Strict bake: a005_pbstatus_strict
            // witnesses:
            //   * A005:pbstatus_writes_same_oserr_to_d0_and_ioresult
            //   * A005:pbstatus_register_only_calling_convention_preserves_stack
            //
            // Regression coverage:
            //   src/trap/memory.rs::status_writes_ioresult_and_returns_noerr_in_d0
            //   src/trap/memory.rs::status_nil_paramblock_returns_noerr_and_preserves_stack
            //   src/trap/memory.rs::pbstatus_writes_same_oserr_to_d0_and_ioresult_preserving_stack
            (false, 0x05) => {
                let pb = cpu.read_reg(Register::A0);
                if pb != 0 {
                    let io_ref_num = bus.read_word(pb + 24);
                    let result = if io_ref_num == 0 {
                        NO_ERR
                    } else {
                        BAD_UNIT_ERR
                    };
                    bus.write_word(pb + 16, result as u16); // ioResult mirrors D0
                    cpu.write_reg(Register::D0, result);
                    return Some(Ok(()));
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // InitZone ($A019)
            // PROCEDURE InitZone(pGrowZone: ProcPtr; cMoreMasters: INTEGER;
            //                    limitPtr, startPtr: Ptr);
            // Inside Macintosh: Memory (1992), 2-86..2-87
            //
            // Assembly-language calling convention (IM:Memory 2-87):
            //   On entry: A0 = pointer to InitZone parameter block
            //   On exit:  D0 = result code
            //
            // Systemless does not implement secondary heap zones (single flat
            // allocator), so InitZone is a no-op that returns noErr while
            // preserving A7.
            //
            // Regression coverage:
            //   src/trap/memory.rs::initzone_uses_a0_parameter_block_and_returns_noerr_in_d0
            //   src/trap/memory.rs::initzone_initializes_zone_header_and_makes_startptr_current_zone
            //   src/trap/memory.rs::initzone_uses_register_calling_convention_without_stack_arguments
            // InitZone ($A019): Initializes the observable zone header
            // from the A0 parameter block, makes startPtr current via
            // TheZone, and returns D0=noErr; no stack-argument pop
            // (IM:Memory 1992 2-87)
            (false, 0x19) => {
                use crate::memory::globals::addr;
                let param_block = cpu.read_reg(Register::A0);
                let start = bus.read_long(param_block);
                let limit = bus.read_long(param_block + 4);
                let more_masters = bus.read_word(param_block + 8);
                let grow_zone = bus.read_long(param_block + 10);
                init_zone_header(bus, start, limit, more_masters, grow_zone);
                bus.write_long(addr::THE_ZONE, start);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // SetDateTime ($A03A)
            // Sets the date and time in the clock chip and the Time global.
            // FUNCTION SetDateTime(secs: LongInt): OSErr;
            // Inside Macintosh Volume II (1985), pp. II-378 to II-379 and II-391;
            // Operating System Utilities (1994), pp. 4-36 to 4-37
            //
            // Per IM:II II-378 + II-391 the trap is an OS-bit FUNCTION
            // (bit 11 of the trap word is clear) with a register-only
            // ABI:
            //
            //   Registers on entry:
            //     D0  Seconds since 1904-01-01 00:00:00 (LONGINT)
            //
            //   Registers on exit:
            //     D0  Result code (noErr 0 | clkWrErr | clkRdErr)
            //
            // No Pascal stack argument frame is consumed and no result
            // slot is allocated on the stack — D0 carries both the
            // input and the OSErr result.
            //
            // MPW Universal Headers DateTimeUtils.h declares:
            //   #pragma parameter __D0 SetDateTime(__D0)
            //   EXTERN_API(OSErr) SetDateTime(unsigned long time)
            //                                   ONEWORDINLINE(0xA03A);
            // which maps the single C argument and the FUNCTION result
            // to D0.
            //
            // Per IM:II II-378: "SetDateTime sets the current date and
            // time in the clock chip and also sets the Time global
            // variable." Systemless writes D0 to the Time global ($020C)
            // and returns D0 = noErr.
            //
            // Apple-vs-BasiliskII divergence: BasiliskII's VBL interrupt
            // fires every ~16ms and overwrites $020C with the host
            // clock. Even a sub-microsecond read of $020C immediately
            // after _SetDateTime returns the host clock value, not the
            // value passed in. The Time-global write semantic is
            // therefore engines-divergent and pinned via the in-Rust
            // contract test
            // src/trap/memory.rs::setdatetime_updates_time_global_from_d0_seconds_argument.
            //
            // The engines-agree subset — register-only OS-bit FUNCTION
            // calling convention + noErr return on the nominal call
            // path — is witnessed by the strict bake fixture
            // a03a_setdatetime_strict.
            //
            // Regression coverage:
            //   src/trap/memory.rs::setdatetime_updates_time_global_from_d0_seconds_argument
            //   src/trap/memory.rs::setdatetime_returns_noerr_result_code_in_d0_for_nominal_call
            //   src/trap/memory.rs::setdatetime_returns_noerr_regardless_of_secs_input
            (false, 0x3A) => {
                let secs = cpu.read_reg(Register::D0);
                bus.write_long(0x020C, secs); // Time global ($020C)
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // WriteParam ($A038)
            // Writes the low-memory copy of parameter RAM to the clock chip.
            // FUNCTION WriteParam: OSErr;
            // Inside Macintosh Volume II (1985), pp. II-381 to II-382 and p. II-391
            // Operating System Utilities (1994), pp. 7-12 to 7-13
            //
            // Per IM:II II-381 + IM:OSUtils 1994 p. 7-13 the trap is an
            // OS-bit FUNCTION (bit 11 of the trap word is clear) with a
            // register-only ABI:
            //
            //   Registers on entry:
            //     A0  SysParam     (pointer to low-memory copy of parameter
            //                       RAM at the global $01F8)
            //     D0  MinusOne     (long word $FFFFFFFF — "you have to pass
            //                       the values of these global variables
            //                       for historical reasons")
            //
            //   Registers on exit:
            //     D0  Result code  (noErr 0 | prWrErr -87)
            //
            // No Pascal stack argument frame is consumed and no result slot
            // is allocated on the stack — A0 and D0 carry both inputs, and
            // D0 carries the OSErr result.
            //
            // MPW Universal Headers OSUtils.h declares:
            //     EXTERN_API(OSErr) WriteParam(void);
            // exposed via InterfaceLib only with NO ONEWORDINLINE glue
            // published in the public header. Callers either link through
            // InterfaceLib (which performs the A0/D0 register setup) or use
            // a fixture-local `#pragma parameter __D0 kx_WriteParam(__A0,
            // __D0)` inline thunk that emits the trap word directly with
            // the documented register inputs.
            //
            // Documented contract per IM:OSUtils 1994 p. 7-13:
            //   "The WriteParam function writes the modified values in the
            //    system parameters record to parameter RAM. ... The
            //    WriteParam function also attempts to verify the values
            //    written by reading them back in and comparing them to the
            //    values in the low-memory copy."
            //
            // The 20-byte low-memory SysParam record at $01F8 is the SOURCE
            // the trap propagates OUT to the clock chip and the reference
            // it compares against on the verify path; the trap never
            // modifies the low-memory copy.
            //
            // Engines-agree subset (witnessed by strict bake
            // a038_writeparam_strict band B1 + B2):
            //   - D0 = noErr (0) on nominal exit. BII's emulated clock
            //     chip and SysParam agree on a freshly-booted system, so
            //     the verify path succeeds.
            //   - SysParam bytes at $01F8..$020B byte-for-byte preserved
            //     across the call. The Systemless HLE doesn't touch them;
            //     BII reads them on the write+verify path without writing
            //     back.
            //   - A7 unchanged across the call (register-only ABI; no
            //     Pascal stack frame). Witnessed by in-Rust contract test
            //     `writeparam_returns_noerr_in_d0_for_nominal_call`.
            //
            // BII-vs-Systemless divergence: BII propagates the SysParam record
            // to its emulated clock chip and verifies; Systemless returns
            // D0=0 unconditionally without modeling the clock chip (per
            // IM:II II-381 historical note, the low-memory SysParam copy
            // is the canonical store anyway).
            //
            // Regression coverage:
            //   writeparam_writes_parameter_ram
            //   src/trap/memory.rs:tests::writeparam_returns_noerr_in_d0_for_nominal_call
            //   src/trap/memory.rs:tests::writeparam_does_not_modify_low_memory_sysparam_copy
            //   src/trap/memory.rs:tests::writeparam_five_call_composition_preserves_stack_across_varying_minusone_register_state
            // WriteParam ($A038): No-op in emulator (no clock chip); returns noErr per IM:II II-381 + IM:OSUtils 1994 p. 7-13
            (false, 0x38) => {
                // In our emulator there is no real clock chip.
                // Just return noErr — the low-memory copy at SysParam ($01F8)
                // is already the canonical store.
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // InitUtil ($A03F)
            // Reads parameter RAM out of the clock chip into the 20-byte
            // SysParam record at low-memory $01F8 and stamps the first
            // byte (SPValid) with $A8 to mark the in-memory copy as
            // authoritative. Per IM:II II-380 + IM:OSUtils 1994 p. 7-9
            // this is the canonical "initialize parameter RAM" entry
            // point invoked once during boot.
            //
            // FUNCTION InitUtil: OSErr;     {trap macro _InitUtil $A03F}
            //
            // Inside Macintosh Volume II (1985), pp. II-375, II-380 to
            // II-381, II-391; Operating System Utilities (1994),
            // pp. 7-8 to 7-10.
            //
            // OS-bit FUNCTION (bit 11 of the trap word is clear) with
            // a register-only ABI per IM:OSUtils 1994 p. 7-9:
            //   Registers on entry:  (none)
            //   Registers on exit:   D0 = OSErr (0 noErr | -88 prInitErr)
            // No Pascal stack frame is consumed and no result slot is
            // allocated on the stack — D0 alone carries the result.
            //
            // MPW Universal Headers OSUtils.h declares InitUtil as
            //   EXTERN_API(OSErr) InitUtil(void)
            // exposed via InterfaceLib only; no ONEWORDINLINE glue is
            // published in the public header. Strict-bake fixtures
            // dispatch the trap via the inline thunk
            //   #pragma parameter __D0 kx_InitUtil()
            //   pascal long kx_InitUtil(void) = {0xA03F};
            // mapping the FUNCTION result slot to D0.
            //
            // SPValid sentinel: per IM:II II-375 + II-380 the first
            // byte of SysParam is the validity stamp. $A8 means
            // "parameter RAM has been validated by InitUtil since the
            // last reset"; any other value means "invalid" and apps
            // must invoke InitUtil before relying on SysParam contents.
            //
            // BII-vs-Systemless divergence: BII System 7.5.3 ROM reads
            // the host-emulated clock chip and propagates the full
            // 20-byte record into low memory before stamping SPValid.
            // Systemless HLE writes only the SPValid stamp (the rest of
            // SysParam is initialised by other paths or remains zero);
            // the engines agree on the documented post-conditions
            // (D0 = noErr and SPValid = $A8 on a freshly-booted
            // default-configuration system).
            //
            // Runtime proof: a03f_initutil_strict
            //   B1: D0 lowbyte == 0 (noErr) for the nominal call.
            //   B2: SPValid ($01F8) == $A8 after dispatch (pre-poisoned
            //       to $5A to defeat no-op stubs).
            //
            // Regression coverage:
            //   src/trap/memory.rs:initutil_returns_noerr_in_d0_for_nominal_call
            //   src/trap/memory.rs:initutil_sets_spvalid_byte_to_a8_on_success
            //   src/trap/memory.rs:initutil_rewrites_spvalid_when_pre_poisoned_to_invalid
            (false, 0x3F) => {
                // Mark parameter RAM as valid: SPValid ($01F8) = $A8
                bus.write_byte(0x01F8, 0xA8);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // UprString ($A054)
            // Converts lowercase letters in a string to uppercase.
            // PROCEDURE UprString(VAR theString: Str255; diacSens: BOOLEAN);
            // Inside Macintosh Volume II, II-377
            //
            // Assembly calling convention:
            //   On entry: A0 = pointer to first character, D0.W = length
            //   On exit:  A0 = pointer to first character (unchanged)
            //   Bit 9 of trap word: if set, diacSens=FALSE (strip diacriticals)
            //
            // Regression coverage:
            //   uprstring_uppercases_pascal_string
            //   uprstring_preserves_non_alpha
            // UprString ($A054): Converts lowercase→uppercase in place; bit 9=strip diacriticals; per IM:II II-377
            (false, 0x54) => {
                let ptr = cpu.read_reg(Register::A0);
                let len = cpu.read_reg(Register::D0) & 0xFFFF;
                let strip_marks = (self.current_trap_word & 0x0200) != 0;
                for i in 0..len {
                    let ch = bus.read_byte(ptr + i);
                    let upper = mac_roman_to_upper(ch, strip_marks);
                    bus.write_byte(ptr + i, upper);
                }
                Ok(())
            }

            // LowerText ($A056) / StripText ($A256) / UpperText ($A456) /
            // StripUpperText ($A656)
            // Text conversion utilities selected by trap-word variants.
            // Inside Macintosh Volume VI (1991), 14-62 to 14-63 and
            // Appendix C table C-2 (C-3); Mac Roman accent table per
            // Inside Macintosh Volume IV (1985), IV-235.
            //
            // Per IM:VI 14-62 ("Call shape" line for each variant):
            //   On entry:  A0 = pointer to first character of text buffer
            //              D0.W = byte length of buffer (zero-extended to D0.L)
            //   On exit:   D0 = result code (noErr = 0, resNotFound = -192)
            //
            // Bits 9-10 of the dispatched trap word select the operation
            // per IM:VI Appendix C table C-2 (C-3):
            //   bit 10 = 0, bit 9 = 0 → $A056 LowerText
            //   bit 10 = 0, bit 9 = 1 → $A256 StripText
            //   bit 10 = 1, bit 9 = 0 → $A456 UpperText
            //   bit 10 = 1, bit 9 = 1 → $A656 StripUpperText
            //
            // MPW Universal Headers (`TextUtils.h`) declare each variant
            // as ONEWORDINLINE with `#pragma parameter Foo(__A0, __D0)`:
            //   pascal void LowerText(Ptr textPtr, short len)        = { 0xA056 };
            //   pascal void StripText(Ptr textPtr, short len)        = { 0xA256 };
            //   pascal void UpperText(Ptr textPtr, short len)        = { 0xA456 };
            //   pascal void StripUpperText(Ptr textPtr, short len)   = { 0xA656 };
            // The void return type elides D0 from the C side; the strict
            // bake fixture uses inline `pascal short Do*Text` thunks that
            // pop the args into A0/D0 and write D0.W back to the function
            // result slot, but witnesses byte-output rather than D0 so the
            // golden subset stays insensitive to the IM:VI 14-63
            // "checking D0 is unreliable on System 7 PowerMacs" caveat.
            //
            // Strict runtime proof:
            //   a056_text_conversion_variants_strict (5 of 6 assertions
            //   witnessed on BasiliskII; the 6th `text_conversion_variants_
            //   return_noerr_in_d0_for_nominal_calls` is contract-only).
            //
            // Contract coverage in this file:
            //   lowertext_converts_to_lowercase
            //   uppertext_converts_to_uppercase
            //   striptext_strips_diacriticals
            //   stripuppertext_strips_and_uppercases
            //   lowertext_family_returns_noerr_in_d0_for_each_trap_word_variant
            //
            // LowerText/UpperText/StripText/StripUpperText ($A056): text
            // conversion utility family selected by trap-word variants
            // ($A056/$A256/$A456/$A656); D0 returns result code (noErr or
            // resNotFound) per IM:VI 14-62 to 14-63.
            (false, 0x56) => {
                let ptr = cpu.read_reg(Register::A0);
                let len = cpu.read_reg(Register::D0) & 0xFFFF;
                let bits = (self.current_trap_word >> 9) & 0x03;
                let do_upper = (bits & 0x02) != 0;
                let do_strip = (bits & 0x01) != 0;
                let do_lower = bits == 0x00;
                for i in 0..len {
                    let ch = bus.read_byte(ptr + i);
                    let result = if do_upper && do_strip {
                        mac_roman_to_upper(ch, true)
                    } else if do_upper {
                        mac_roman_to_upper(ch, false)
                    } else if do_strip {
                        mac_roman_strip_diacriticals(ch)
                    } else if do_lower {
                        mac_roman_to_lower(ch)
                    } else {
                        ch
                    };
                    bus.write_byte(ptr + i, result);
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // RelString ($A050)
            // Compares two strings relationally, returning -1, 0, or 1.
            // FUNCTION RelString(aStr, bStr: Str255; caseSens, diacSens: BOOLEAN): INTEGER;
            // Inside Macintosh Volume IV, IV-234
            //
            // Assembly calling convention:
            //   On entry: A0 = ptr to first string, A1 = ptr to second string
            //             D0 high word = length of first, D0 low word = length of second
            //   On exit:  D0 = -1 (less), 0 (equal), or 1 (greater) as long word
            //   Bit 9: if set, diacSens=FALSE (strip diacriticals)
            //   Bit 10: if set, caseSens=TRUE
            //
            // Regression coverage:
            //   relstring_compares_equal_strings
            //   relstring_compares_less_than
            //   relstring_compares_greater_than
            //   relstring_case_insensitive
            // RelString ($A050): Compares strings relationally: A0/A1=ptrs, D0=lengths; bit 9=strip marks, bit 10=case-sensitive; per IM:IV IV-234
            (false, 0x50) => {
                let ptr_a = cpu.read_reg(Register::A0);
                let ptr_b = cpu.read_reg(Register::A1);
                let d0 = cpu.read_reg(Register::D0);
                let len_a = (d0 >> 16) & 0xFFFF;
                let len_b = d0 & 0xFFFF;
                let strip_marks = (self.current_trap_word & 0x0200) != 0;
                let case_sens = (self.current_trap_word & 0x0400) != 0;

                let min_len = std::cmp::min(len_a, len_b);
                let mut result: i32 = 0;
                for i in 0..min_len {
                    let mut a = bus.read_byte(ptr_a + i);
                    let mut b = bus.read_byte(ptr_b + i);
                    if strip_marks {
                        a = mac_roman_strip_diacriticals(a);
                        b = mac_roman_strip_diacriticals(b);
                    }
                    if !case_sens {
                        a = mac_roman_to_upper(a, false);
                        b = mac_roman_to_upper(b, false);
                    }
                    if a < b {
                        result = -1;
                        break;
                    } else if a > b {
                        result = 1;
                        break;
                    }
                }
                if result == 0 {
                    if len_a < len_b {
                        result = -1;
                    } else if len_a > len_b {
                        result = 1;
                    }
                }
                cpu.write_reg(Register::D0, result as u32);
                Ok(())
            }

            // Translate24To32 ($A091)
            // Translates a 24-bit address to a 32-bit clean address.
            // Inside Macintosh Volume VI, 28-10
            //
            // Assembly calling convention:
            //   On entry: D0 = 24-bit address
            //   On exit:  D0 = 32-bit address
            //
            // BasiliskII's default System 7.5.3 boot runs in 32-bit
            // addressing mode and returns the full D0 input unchanged
            // for tagged values like 0xAB123456. Systemless follows that
            // operational behavior so 32-bit-clean guests see the same
            // identity result.
            //
            // Regression coverage:
            //   src/trap/memory.rs::translate24to32_preserves_full_input_in_32bit_mode
            //   src/trap/memory.rs::translate24to32_uses_d0_register_calling_convention_and_preserves_a7
            // Translate24To32 ($A091): Register-only D0-in/D0-out call;
            // current 32-bit-mode convergence target returns the full
            // D0 input unchanged.
            (false, 0x91) => {
                let addr = cpu.read_reg(Register::D0);
                cpu.write_reg(Register::D0, addr);
                Ok(())
            }

            // ReadXPRam ($A051)
            // PROCEDURE ReadXPRam (count: INTEGER; whichByte: INTEGER; destPtr: Ptr);
            // Reads `count` bytes from extended parameter RAM (the 236-byte
            // region beyond the 20-byte standard SysParam record) starting
            // at byte offset `whichByte` in the 256-byte PRAM record, into
            // the caller-supplied destination buffer at `destPtr`.
            // Inside Macintosh Volume V (1986), p. V-519; Operating System
            // Utilities (1994), pp. 7-1 to 7-14.
            //
            // OS-bit FUNCTION (bit 11 of the trap word is clear) with a
            // register-only ABI per IM:V V-519:
            //
            //     Registers on entry:
            //       D0  packed long: (count << 16) | whichByte_offset
            //       A0  destPtr (caller's destination buffer)
            //
            //     Registers on exit:
            //       D0  Result code (noErr 0 on the nominal path)
            //
            // No Pascal stack frame is consumed and no result slot is
            // allocated on the stack — A0 and D0 carry both inputs and
            // D0 carries the OSErr result. Per IM:OSUtils 1994 p. 7-3
            // WARNING block: applications "should rarely use them
            // [_ReadXPRam / _WriteXPRam]; instead, use the appropriate
            // Toolbox routines to indirectly manipulate values in
            // parameter RAM" (e.g. ReadLocation per IM:OSUtils 1994
            // p. 7-12).
            //
            // The MPW Universal Headers expose the trap word as the
            // `_ReadXPRam = 0xA051` constant in Traps.h only — there is
            // no public EXTERN_API declaration in OSUtils.h or Memory.h.
            // Strict bake fixtures use a fixture-local inline thunk via
            // `#pragma parameter __D0 kx_ReadXPRam(__D0, __A0)`.
            //
            // BII-vs-Systemless divergence: BasiliskII reads the actual
            // emulated clock-chip XPRAM bytes; the Systemless HLE here
            // zero-fills the destination because no persistent extended
            // PRAM is modeled. Both engines agree on the documented
            // OS-bit register convention + noErr return on the
            // default-configuration nominal-call path.
            //
            // Strict bake fixture:
            //   a051_a052_xpram_strict
            // Engines-agree assertions witnessed:
            //   A051:readxpram_returns_noerr_in_d0_for_nominal_call
            //   A051:readxpram_uses_d0_count_offset_and_a0_destptr_register_calling_convention
            // Systemless-only contract assertion:
            //   A051:readxpram_zero_fills_requested_count_in_systemless_no_xpram_model
            //
            // In-Rust contract tests:
            //   readxpram_zero_fills_requested_count_and_returns_noerr
            //   readxpram_uses_d0_count_offset_and_a0_destptr_register_calling_convention
            //   readxpram_five_call_composition_preserves_stack_across_varying_count_offset
            (false, 0x51) => {
                let d0 = cpu.read_reg(Register::D0);
                let count = (d0 >> 16) & 0xFFFF;
                let ptr = cpu.read_reg(Register::A0);
                for i in 0..count {
                    bus.write_byte(ptr + i, 0);
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // WriteXPRam ($A052)
            // PROCEDURE WriteXPRam (count: INTEGER; whichByte: INTEGER; srcPtr: Ptr);
            // Writes `count` bytes from the caller's source buffer at
            // `srcPtr` into extended parameter RAM starting at byte
            // offset `whichByte` in the 256-byte PRAM record.
            // Inside Macintosh Volume V (1986), p. V-519; Operating System
            // Utilities (1994), pp. 7-1 to 7-14.
            //
            // OS-bit FUNCTION with the same register convention as
            // ReadXPRam, except A0 is the SOURCE pointer:
            //
            //     Registers on entry:
            //       D0  packed long: (count << 16) | whichByte_offset
            //       A0  srcPtr (caller's source buffer; READ-ONLY)
            //
            //     Registers on exit:
            //       D0  Result code (noErr 0 on the nominal path)
            //
            // BII-vs-Systemless divergence: BasiliskII writes the source
            // bytes to its emulated clock-chip XPRAM and verifies by
            // readback; the Systemless HLE here is a no-op because no
            // persistent extended PRAM is modeled. Both engines preserve
            // the caller's source buffer (read-only access) and agree on
            // the documented OS-bit register convention + noErr return.
            //
            // Strict bake fixture:
            //   a051_a052_xpram_strict
            // Engines-agree assertions witnessed:
            //   A052:writexpram_returns_noerr_in_d0_for_nominal_call
            //   A052:writexpram_uses_d0_count_offset_and_a0_srcptr_register_calling_convention
            //
            // In-Rust contract tests:
            //   writexpram_noop_returns_noerr_in_hle_without_persistent_xpram
            //   writexpram_uses_d0_count_offset_and_a0_srcptr_register_calling_convention
            //   writexpram_five_call_composition_preserves_stack_and_source_across_varying_count_offset
            (false, 0x52) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // GetDefaultStartup ($A07D)
            // Reads the default startup device information.
            // PROCEDURE GetDefaultStartup(VAR paramBlock: DefStartRec);
            // Inside Macintosh Volume V, V-529
            //
            // A0 = pointer to 4-byte DefStartRec (sdSlot:1, sdSResource:1, sdExtDev:1, sdFlags:1)
            // In our emulator, return the dispatcher's in-session
            // startup record (initialized to the zero-filled first-device
            // default).
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::getdefaultstartup_fills_4_byte_defstartrec_through_a0
            // GetDefaultStartup ($A07D): Returns the current in-session
            // DefStartRec bytes through A0; per IM:V V-529
            (false, 0x7D) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    bus.write_long(ptr, self.default_startup_rec);
                }
                Ok(())
            }

            // SetDefaultStartup ($A07E)
            // Sets the default startup device information.
            // PROCEDURE SetDefaultStartup(paramBlock: DefStartRec);
            // Inside Macintosh Volume V, V-529
            //
            // A0 = pointer to DefStartRec. Capture the caller's
            // 4-byte record for subsequent GetDefaultStartup calls.
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::setdefaultstartup_updates_getdefaultstartup_and_preserves_stack_pointer
            // SetDefaultStartup ($A07E): Stores the caller-provided
            // DefStartRec for later GetDefaultStartup calls; per IM:V V-529
            (false, 0x7E) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    self.default_startup_rec = bus.read_long(ptr);
                }
                Ok(())
            }

            // GetVideoDefault ($A080)
            // Reads the default video device information.
            // Inside Macintosh Volume V, V-354
            //
            // A0 = pointer to DefVideoRec (sdSlot:1, sdSResource:1)
            // Returns the current Start Manager default video bytes.
            //
            // Regression coverage:
            //   getvideodefault_returns_default_video
            // GetVideoDefault ($A080): Writes DefVideoRec.sdSlot and
            // sdSResource at A0; per IM:V V-354.
            (false, 0x80) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    bus.write_word(ptr, self.default_video_rec);
                }
                Ok(())
            }

            // SetVideoDefault ($A081)
            // Sets the default video device.
            // Inside Macintosh Volume V, V-354 to V-355
            // A0 points to DefVideoRec.
            //
            // Regression coverage:
            //   setvideodefault_sets_default_video
            // SetVideoDefault ($A081): Updates in-session Start Manager
            // defaults from DefVideoRec; per IM:V V-354 to V-355.
            (false, 0x81) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    self.default_video_rec = bus.read_word(ptr);
                }
                Ok(())
            }

            // DTInstall ($A082)
            // Installs a deferred task into the deferred task queue.
            // FUNCTION DTInstall(dtEntryPtr: DeferredTaskPtr): OSErr;
            // Inside Macintosh Volume V (1986), p. V-467; and
            // Inside Macintosh: Processes (1994), pp. 6-12 to 6-13.
            //
            // A0 = pointer to DeferredTask record. Returns noErr for a
            // valid qType and vTypErr when qType != ORD(dtQType) = 7.
            // In our emulator, deferred task queue insertion is not modeled.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::dtinstall_uses_a0_dttaskptr_register_calling_convention
            //   src/trap/memory.rs::tests::dtinstall_valid_record_returns_noerr_in_d0
            //   src/trap/memory.rs::tests::dtinstall_invalid_qtype_returns_vtyperr_and_preserves_stack_pointer
            (false, 0x82) => {
                let task_ptr = cpu.read_reg(Register::A0);
                let result = if task_ptr == 0 || bus.read_word(task_ptr + 4) != DT_QTYPE {
                    (-2i32) as u32 // vTypErr
                } else {
                    0
                };
                cpu.write_reg(Register::D0, result);
                Ok(())
            }

            // GetOSDefault ($A084)
            // Gets the default OS.
            // Inside Macintosh Volume V, V-355
            //
            // A0 = pointer to DefOSRec (sdReserved:1, sdOSType:1).
            // sdReserved returns 0; sdOSType identifies default OS.
            //
            // Regression coverage:
            //   getosdefault_returns_default_os
            // GetOSDefault ($A084): Writes DefOSRec.sdReserved and
            // sdOSType at A0; per IM:V V-355.
            (false, 0x84) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    bus.write_word(ptr, self.default_os_rec);
                }
                Ok(())
            }

            // SetOSDefault ($A083)
            // Specifies the default startup operating system.
            // PROCEDURE SetOSDefault(paramBlock: DefOSPtr);
            // Inside Macintosh Volume V (1986), p. V-355.
            //
            // Per IM:V V-355 trap-macro summary the trap is an OS-bit
            // PROCEDURE (bit 11 of the trap word is clear) with a
            // register-only ABI:
            //   Registers on entry:
            //     A0  paramBlock  pointer to DefOSRec (2 bytes)
            //   DefOSRec layout:
            //     +0  sdReserved (Byte)  reserved; should be 0 (`→` input)
            //     +1  sdOSType   (Byte)  startup OS identifier (`→` input)
            //   Registers on exit: (none documented)
            //
            // MPW Universal Headers Start.h declares the trap as:
            //   #pragma parameter SetOSDefault(__A0)
            //   EXTERN_API(void) SetOSDefault(DefOSPtr paramBlock)
            //                                                 ONEWORDINLINE(0xA083);
            // i.e. C-level void return with A0 carrying the DefOSRec pointer.
            // No Pascal stack argument frame is consumed and no result slot
            // is allocated; both inputs travel exclusively through A0.
            //
            // Systemless HLE behavior:
            //   - Reads byte +1 (sdOSType) from the caller-supplied DefOSRec.
            //   - Updates self.default_os_rec so subsequent A084 GetOSDefault
            //     observes the new value (IM:V V-355 Apple-canonical
            //     round-trip semantic).
            //   - Does NOT write back to the caller's buffer at A0; the
            //     DefOSRec is a read-only input per the `→` direction arrows
            //     in IM:V V-355.
            //
            // Apple-vs-BasiliskII divergence:
            //   BasiliskII System 7.5 ROM treats $A083 as a no-op: it
            //   accepts the call but does not propagate sdOSType to the
            //   in-session default record. After Set(sdOSType=2) → Get
            //   returns sdOSType=1 (the BII Mac OS boot default).
            //   This is engines-divergent and pinned via the in-Rust
            //   contract test setosdefault_roundtrips_sdostype_and_
            //   getosdefault_reports_reserved_zero
            //   (witness_kind = "contract" in the catalogue row).
            //
            //   The engines AGREE on the documented register-only PROCEDURE
            //   calling convention (A0 input, void return, no stack frame)
            //   and on the read-only treatment of the caller's DefOSRec
            //   input buffer. The bake fixture
            //   a083_setosdefault_strict witnesses only
            //   that engines-agree subset:
            //     A083:setosdefault_preserves_caller_defosrec_input_bytes
            //     A083:setosdefault_register_only_calling_convention_preserves_stack
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::setosdefault_roundtrips_sdostype_and_getosdefault_reports_reserved_zero
            //   src/trap/memory.rs::tests::setosdefault_preserves_caller_defosrec_input_bytes_read_only_a0
            (false, 0x83) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr != 0 {
                    let os_type = bus.read_byte(ptr + 1);
                    self.default_os_rec = os_type as u16;
                }
                Ok(())
            }

            // PowerOff ($A05B)
            // Turns off power. In our emulator, halt.
            // Inside Macintosh Volume V
            // PowerOff ($A05B): Halts emulation; per IM:V
            (false, 0x5B) => Err(Error::Halted),

            // DeferUserFn ($A08F)
            // Defers a user function call until paging is safe.
            // FUNCTION DeferUserFn (userFunction: ProcPtr; argument: UNIV Ptr): OSErr;
            // Inside Macintosh Volume VI (1991), p. 28-30; and
            // Inside Macintosh: Memory (1992), p. 3-33.
            //
            // OS-bit FUNCTION (bit 11 of the trap word is clear). Per
            // IM:Memory 1992 p. 3-33 register convention:
            //     Registers on entry:
            //         A0  Address of function (userFunction ProcPtr)
            //         D0  Argument (UNIV Ptr) — passed in A0 to the
            //             userFunction if it is called immediately
            //     Registers on exit:
            //         D0  Result code (noErr 0 | cannotDeferErr -625)
            // No Pascal stack argument frame is consumed and no result
            // slot is allocated. The MPW Universal Headers Memory.h
            // declaration is `pascal OSErr DeferUserFn(ProcPtr, void *)`
            // exposed via InterfaceLib only; no ONEWORDINLINE glue is
            // published in the public header, so callers either link
            // through InterfaceLib or use a fixture-local
            // `#pragma parameter __D0 fn(__A0, __D0)` thunk emitting
            // the trap word directly.
            //
            // Systemless HLE behavior: if userFunction looks like real
            // 68K code, inject a tiny trampoline that copies the
            // argument into A0, calls the function immediately, and
            // returns noErr in D0 after restoring the scratch
            // registers. Non-callable placeholders fall back to a
            // safe no-op noErr. We do not model the VMM deferred
            // queue or the cannotDeferErr path.
            //
            // Strict bake & contract coverage:
            //   a08f_deferuserfn_strict (BII)
            //   src/trap/memory.rs::tests::deferuserfn_uses_register_calling_convention_without_stack_arguments
            //   src/trap/memory.rs::tests::deferuserfn_callable_pointer_installs_trampoline_and_returns_noerr
            //   src/trap/memory.rs::tests::deferuserfn_two_call_composition_preserves_stack_across_varying_args
            //   src/trap/memory.rs::tests::deferuserfn_five_call_composition_preserves_stack_across_varying_args
            (false, 0x8F) => {
                let user_function = cpu.read_reg(Register::A0);
                let argument = cpu.read_reg(Register::D0);

                if Self::looks_like_callable_proc(bus, user_function) {
                    let trampoline = self.get_or_create_defer_user_fn_trampoline(bus);
                    if trampoline != 0 {
                        bus.write_long(trampoline + 6, argument);
                        bus.write_long(trampoline + 12, user_function);

                        let current_pc = cpu.read_reg(Register::PC);
                        let sp = cpu.read_reg(Register::A7);
                        let new_sp = sp.wrapping_sub(4);
                        bus.write_long(new_sp, current_pc);
                        cpu.write_reg(Register::A7, new_sp);
                        cpu.write_reg(Register::PC, trampoline);
                    }
                }

                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // InternalWait ($A07F)
            // Start Manager timeout selector trap for GetTimeout/SetTimeout.
            // PROCEDURE GetTimeout (VAR count: Integer);
            // PROCEDURE SetTimeout (count: Integer);
            // Inside Macintosh: Operating System Utilities (1994), pp. 9-27 to 9-28;
            // Inside Macintosh Volume V (1986), p. V-356.
            //
            // OS-bit trap (bit 11 of the trap word is clear). Per
            // IM:Operating_System_Utils 1994 p. 9-27 "Trap Macros Requiring
            // Routine Selectors" table:
            //     | Selector | Routine     |
            //     | $0000    | GetTimeout  |
            //     | $0001    | SetTimeout  |
            //
            // Register convention (per IM:OS_Utils 1994 p. 9-27..9-28):
            //     A0 entry  selector ($0000 or $0001)
            //     D0 entry  count word (read for SetTimeout)
            //     D0 exit   count word (written for GetTimeout)
            // No Pascal stack frame is consumed; no FUNCTION result slot is
            // allocated. Startup-drive spin-up timing is not modeled in
            // Systemless — both selectors are accepted as a no-op stub, and
            // the absolute D0 timeout value diverges between BasiliskII
            // (which surfaces a real ROM timeout register) and Systemless
            // (which leaves D0 unchanged). The engines-agree subset is the
            // register-only OS-bit-trap calling convention, witnessed via
            // a07f_internalwait_strict.
            //
            // MPW Universal Headers expose this trap via OSUtils.h as the
            // `GetTimeout`/`SetTimeout` glue — both compile to inline
            // thunks that load A0 with the selector before invoking $A07F.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::internalwait_routes_gettimeout_and_settimeout_selector_paths
            //   src/trap/memory.rs::tests::internalwait_stub_preserves_stack_pointer_in_noop_path
            //   src/trap/memory.rs::tests::internalwait_five_call_composition_preserves_stack_across_alternating_selectors
            // Strict bake:
            //   a07f_internalwait_strict
            (false, 0x7F) => Ok(()),

            // PMgrOp ($A085)
            // Power Manager operations.
            // Inside Macintosh Volume V
            //
            // D0 = selector. No-op — we don't have hardware power management.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::pmgrop_returns_noerr_and_preserves_stack_pointer_in_noop_path
            // Strict bake:
            //   a08a_sleepqinstall_strict
            // PMgrOp ($A085): Returns noErr; no hardware power management; per IM:V
            (false, 0x85) => {
                return_noerr(cpu)
            }

            // IOPInfoAccess ($A086)
            // Access IOP information.
            // Inside Macintosh Volume VI
            // No-op — no IOP hardware.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::iopinfoaccess_returns_noerr_and_preserves_stack_pointer
            // IOPInfoAccess ($A086): Returns noErr; no IOP hardware; per IM:VI
            (false, 0x86) => {
                return_noerr(cpu)
            }

            // IOPMsgRequest ($A087)
            // Send message to IOP.
            // Inside Macintosh Volume VI
            // No-op.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::iopmsgrequest_returns_noerr_and_preserves_stack_pointer
            // IOPMsgRequest ($A087): Returns noErr; per IM:VI
            (false, 0x87) => {
                return_noerr(cpu)
            }

            // IOPMoveData ($A088)
            // Move data to/from IOP.
            // Inside Macintosh Volume VI
            // No-op; mirror noErr through the dispatcher CCR path
            // so 68K callers see a clean OSErr return.
            //
            // Regression coverage:
            //   iopmovedata_moves_iop_data
            // IOPMoveData ($A088): Returns noErr; per IM:VI
            (false, 0x88) => {
                return_noerr(cpu)
            }

            // EgretDispatch ($A092)
            // Egret processor dispatch.
            // Inside Macintosh Volume VI
            // No-op.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::egretdispatch_returns_noerr_and_preserves_stack_pointer
            // EgretDispatch ($A092): Returns noErr; no Egret processor; per IM:VI
            (false, 0x92) => {
                return_noerr(cpu)
            }

            // SleepQInstall ($A28A) / SleepQRemove ($A48A)
            // Sleep queue management.
            // Inside Macintosh: Devices (1994), p. 6-33.
            // No-op behavior in HLE — we don't have sleep/wake hardware.
            // Both variants take one SleepQRecPtr Pascal argument on stack.
            //
            // Regression coverage:
            //   sleepqinstall_installs_sleep_queue_entry
            //   sleepqremove_removes_sleep_queue_entry
            // SleepQInstall/SleepQRemove ($A08A): Returns noErr; no sleep/wake hardware; per IM:VI
            (false, 0x8A) => {
                // Variant trap words: $A28A (install), $A48A (remove).
                // Appendix C table C-2 (IM:VI 1991, p. C-3).
                match self.current_trap_word {
                    0xA28A | 0xA48A => {
                        let sp = cpu.read_reg(Register::A7);
                        let _q_rec_ptr = bus.read_long(sp);
                        cpu.write_reg(Register::A7, sp.wrapping_add(4));
                    }
                    _ => {}
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // SCSIAtomic ($A089)
            // SCSI Manager 4.3 dispatch.
            // Inside Macintosh: Devices (1994), pp. 4-49 to 4-50.
            // Systemless models the SCSIGetVirtualIDInfo branch used by
            // SCSIAtomic: the request header must be well formed, the
            // nominal missing-ID lookup returns noErr / scsiExists =
            // false, and malformed headers are rejected before the
            // lookup path with scsiQLinkInvalid / scsiPBLengthError /
            // scsiRequestInvalid.
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::scsiaction_scsigetvirtualidinfo_missing_virtual_id_clears_exists_and_preserves_stack
            // SCSIAtomic ($A089): selector $0001 (SCSIAction) / SCSIGetVirtualIDInfo virtual-ID lookup, no virtual bus -> noErr + scsiExists false
            (false, 0x89) => {
                const SCSI_PB_Q_LINK_OFFSET: u32 = 0;
                const SCSI_PB_LENGTH_OFFSET: u32 = 6;
                const SCSI_PB_FUNCTION_CODE_OFFSET: u32 = 8;
                const SCSI_PB_RESULT_OFFSET: u32 = 10;
                const SCSI_PB_COMPLETION_OFFSET: u32 = 16;
                const SCSI_PB_LENGTH_MIN: u16 = 40;
                const SCSI_PB_EXISTS_OFFSET: u32 = 38;
                const SCSI_REQUEST_INVALID: i16 = -7870;
                const SCSI_PB_LENGTH_ERROR: i16 = -7872;
                const SCSI_Q_LINK_INVALID: i16 = -7881;
                const SCSI_GET_VIRTUAL_ID_INFO_FUNCTION_CODE: u8 = 0x80;

                let scsi_pb = cpu.read_reg(Register::A0);
                if scsi_pb == 0 {
                    cpu.write_reg(Register::D0, SCSI_REQUEST_INVALID as u32);
                    return Some(Ok(()));
                }
                let q_link = bus.read_long(scsi_pb + SCSI_PB_Q_LINK_OFFSET);
                if q_link != 0 {
                    bus.write_word(scsi_pb + SCSI_PB_RESULT_OFFSET, SCSI_Q_LINK_INVALID as u16);
                    cpu.write_reg(Register::D0, SCSI_Q_LINK_INVALID as u32);
                    return Some(Ok(()));
                }

                let pb_length = bus.read_word(scsi_pb + SCSI_PB_LENGTH_OFFSET);
                if pb_length < SCSI_PB_LENGTH_MIN {
                    bus.write_word(
                        scsi_pb + SCSI_PB_RESULT_OFFSET,
                        SCSI_PB_LENGTH_ERROR as u16,
                    );
                    cpu.write_reg(Register::D0, SCSI_PB_LENGTH_ERROR as u32);
                    return Some(Ok(()));
                }

                let completion = bus.read_long(scsi_pb + SCSI_PB_COMPLETION_OFFSET);
                if completion != 0 {
                    bus.write_word(
                        scsi_pb + SCSI_PB_RESULT_OFFSET,
                        SCSI_REQUEST_INVALID as u16,
                    );
                    cpu.write_reg(Register::D0, SCSI_REQUEST_INVALID as u32);
                    return Some(Ok(()));
                }

                let function_code = bus.read_byte(scsi_pb + SCSI_PB_FUNCTION_CODE_OFFSET);
                bus.write_word(scsi_pb + SCSI_PB_RESULT_OFFSET, 0);
                if function_code == SCSI_GET_VIRTUAL_ID_INFO_FUNCTION_CODE {
                    bus.write_byte(scsi_pb + SCSI_PB_EXISTS_OFFSET, 0);
                } else {
                    bus.write_word(
                        scsi_pb + SCSI_PB_RESULT_OFFSET,
                        SCSI_REQUEST_INVALID as u16,
                    );
                    cpu.write_reg(Register::D0, SCSI_REQUEST_INVALID as u32);
                    return Some(Ok(()));
                }
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // PowerDispatch ($A09F)
            // Power management dispatch.
            // Inside Macintosh Volume VI
            // No-op.
            //
            // Regression coverage:
            //   powerdispatch_routes_power_selectors
            // PowerDispatch ($A09F): Returns noErr; per IM:VI
            (false, 0x9F) => {
                cpu.write_reg(Register::D0, 0);
                Ok(())
            }

            // CommToolboxDispatch ($A08B)
            // Communications Toolbox dispatch.
            // Inside Macintosh Volume VI (1991), Appendix C table C-3 (p. C-4).
            // Selector-dispatch trap (e.g. $0402 AppendDITL, $0403 CountDITL,
            // $0404 ShortenDITL).
            //
            // Systemless HLE currently implements the common CountDITL selector
            // ($0403): it returns the dialog's current item count through the
            // Pascal function result slot. The MPW C call frame observed in
            // the strict fixture places the 4-byte result slot at SP+0..3,
            // the selector word at SP+4..5, and the DialogPtr argument at
            // SP+6..9. The remaining selectors stay as no-op stubs for now.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::commtoolboxdispatch_countditl_returns_dialog_item_count_and_preserves_stack_pointer
            //   src/trap/memory.rs::tests::commtoolboxdispatch_countditl_preserves_non_d0_registers
            (false, 0x8B) => {
                fn count_dialog_items(bus: &MacMemoryBus, dialog_ptr: u32) -> u16 {
                    if dialog_ptr == 0 {
                        return 0;
                    }

                    let items_handle = bus.read_long(dialog_ptr + 156);
                    if items_handle != 0 {
                        let ditl_ptr = bus.read_long(items_handle);
                        if ditl_ptr != 0 {
                            return bus.read_word(ditl_ptr).wrapping_add(1);
                        }
                    }

                    0
                }

                let sp = cpu.read_reg(Register::A7);
                let selector_stack = bus.read_word(sp + 4);
                let selector_d0 = cpu.read_reg(Register::D0) as u16;
                let dialog_ptr = if selector_stack == 0x0403 {
                    bus.read_long(sp + 6)
                } else if selector_d0 == 0x0403 {
                    bus.read_long(sp + 6)
                } else {
                    cpu.write_reg(Register::D0, 0);
                    return Some(Ok(()));
                };

                let mut resolved_ptr = dialog_ptr;
                let mut count = count_dialog_items(bus, resolved_ptr);
                if count == 0 {
                    count = self
                        .dialog_items
                        .get(&resolved_ptr)
                        .map(|items| items.len() as u16)
                        .unwrap_or(0);
                }
                if count == 0 && self.front_window != 0 && self.front_window != resolved_ptr {
                    resolved_ptr = self.front_window;
                    count = count_dialog_items(bus, resolved_ptr);
                    if count == 0 {
                        count = self
                            .dialog_items
                            .get(&resolved_ptr)
                            .map(|items| items.len() as u16)
                            .unwrap_or(0);
                    }
                }

                cpu.write_reg(Register::D0, count as u32);
                Ok(())
            }

            // DebugUtil ($A08D)
            // Debug utility selector-dispatch trap.
            // Inside Macintosh Volume VI (1991), pp. 28-30..28-31; and
            // Appendix C table C-3 (p. C-4) selector map:
            //     | Selector | Routine             |
            //     | $0000    | DebuggerGetMax      |
            //     | $0001    | DebuggerEnter       |
            //     | $0002    | DebuggerExit        |
            //     | $0003    | DebuggerPoll        |
            //     | $0004    | GetPageState        |
            //     | $0005    | PageFaultFatal      |
            //     | $0006    | DebuggerLockMemory  |
            //     | $0007    | DebuggerUnlockMemory|
            //     | $0008    | EnterSupervisorMode |
            //
            // Register convention:
            //     D0 entry: selector (and selector-specific arg for some)
            //     D0 exit:  result code or selector-specific return value
            //     A0/A1 entry: selector-specific args (e.g. address)
            // No Pascal stack frame is consumed and no result slot is
            // allocated.
            //
            // MPW Universal Headers (MacMemory.h) expose each selector as
            // a separate TWOWORDINLINE thunk, e.g.
            //   EXTERN_API( long )
            //   DebuggerGetMax(void) TWOWORDINLINE(0x7000, 0xA08D);
            // which inlines "MOVEQ #0,D0" followed by the trap word.
            //
            // Systemless HLE models the safe selector-query path for
            // DebuggerGetMax ($0000): it returns the highest documented
            // selector number without entering the debugger, mutating
            // page state, or changing supervisor mode. The other
            // documented helper selectors are modelled as safe no-ops
            // that still preserve the register-only OS-bit-trap calling
            // convention (stack discipline).
            //
            // Strict runtime proof:
            //   a08d_debugutil_strict/
            //     witnesses the engines-agree stack-discipline subset
            //     across single and 5-call composed _DebugUtil($0000)
            //     dispatches, and the selector $0000 return value
            //     matches the documented max selector number.
            //
            // Contract coverage:
            //   src/trap/memory.rs::tests::debugutil_debuggergetmax_returns_max_selector_and_preserves_stack_pointer
            //   src/trap/memory.rs::tests::debugutil_other_selectors_preserve_non_d0_registers
            //   src/trap/memory.rs::tests::debugutil_five_call_composition_preserves_stack_across_documented_selectors
            //   src/trap/memory.rs::tests::debugutil_debuggerpoll_five_call_composition_preserves_stack_across_repeated_selector_three_calls
            (false, 0x8D) => match cpu.read_reg(Register::D0) {
                0 => {
                    cpu.write_reg(Register::D0, 8);
                    Ok(())
                }
                1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 => {
                    cpu.write_reg(Register::D0, 0);
                    Ok(())
                }
                _ => {
                    cpu.write_reg(Register::D0, 0);
                    Ok(())
                }
            },

            // NMInstall ($A05E)
            // Installs a notification request.
            // FUNCTION NMInstall(nmReqPtr: NMRecPtr): OSErr;
            // Inside Macintosh Volume VI (1991), p. 24-10
            //
            // A0 = NMRecPtr. Returns noErr — notifications are not displayed
            // in the emulator, but we accept the request silently.
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::nminstall_returns_noerr_for_nominal_notification_request
            //   src/trap/memory.rs::tests::nminstall_uses_a0_nmrecptr_register_calling_convention
            // NMInstall ($A05E): Returns noErr on nominal requests; per IM:VI 24-10
            (false, 0x5E) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // NMRemove ($A05F)
            // Removes a notification request.
            // FUNCTION NMRemove(nmReqPtr: NMRecPtr): OSErr;
            // Inside Macintosh Volume VI (1991), p. 24-11
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::nmremove_returns_noerr_for_nominal_notification_request
            //   src/trap/memory.rs::tests::nmremove_uses_a0_nmrecptr_register_calling_convention
            // NMRemove ($A05F): Returns noErr on nominal requests; per IM:VI 24-11
            (false, 0x5F) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // ========== ADB Manager ==========

            // CountADBs ($A077)
            // Returns the number of ADB devices.
            // FUNCTION CountADBs: INTEGER;
            // Inside Macintosh Volume V, V-372
            //
            // Returns count in D0. We report 2 devices (keyboard + mouse).
            //
            // Regression coverage:
            //   countadbs_returns_device_count
            // CountADBs ($A077): Returns 2 (keyboard + mouse) per IM:V V-372
            (false, 0x77) => {
                cpu.write_reg(Register::D0, 2); // keyboard + mouse
                Ok(())
            }

            // GetIndADB ($A078) — ADB Manager
            //
            // Per IM:V V-373: "GetIndADB returns information from the
            // ADB device-table entry whose index number is given by
            // devTableIndex. ... GetIndADB returns the current ADB
            // address of the device. If it is unable to complete
            // execution successfully, GetIndADB returns a negative
            // value."
            //
            // Per IM:V V-373 + IM:Devices 1994 pp. 5-43..5-44:
            // GetIndADB is an OS-bit trap with register-only ABI.
            //   On entry  A0 = pointer to ADBDataBlock
            //             D0 = devTableIndex (byte, range 1..CountADBs)
            //   On exit   D0 = positive current ADB address (byte) OR
            //                  negative error code (byte)
            //
            // ADBDataBlock layout (IM:V V-373, 10 bytes):
            //     +0  devType        SignedByte  {handler ID}
            //     +1  origADBAddr    SignedByte  {original ADB addr}
            //     +2  dbServiceRtPtr Ptr (4)     {service routine}
            //     +6  dbDataAreaAddr Ptr (4)     {data area for rtn}
            //
            // MPW Universal Headers (DeskBus.h) exposes GetIndADB
            // as an inline OS trap with `#pragma parameter __D0
            // GetIndADB(__A0, __D0)` mapping the FUNCTION result to
            // D0, the info pointer to A0, and devTableIndex to D0:
            //   #pragma parameter __D0 GetIndADB(__A0, __D0)
            //   EXTERN_API( ADBAddress )
            //   GetIndADB(ADBDataBlock *info, short devTableIndex)
            //     ONEWORDINLINE(0xA078);
            //
            // Engines-divergence note (engines-agree on the documented
            // API surface; only the specific byte values written
            // through *info diverge): BasiliskII System 7.5.3 ROM
            // walks its real ADB device table populated by the boot
            // sequence, writing actual handler-ID + service-routine
            // + data-area-pointer bytes. Systemless HLE hardcodes the
            // System 7.5 default-address scheme from IM:V V-364..V-365
            // (index 1 -> keyboard at ADB address 2, index 2 -> mouse
            // at ADB address 3) and zero-fills devType / service-rtn
            // / data-area fields since neither pointer is meaningful
            // in the HLE event model. Both engines agree on:
            //   * positive ADB-address return for valid indices
            //   * negative error return for out-of-range indices
            //   * caller's ADBDataBlock written through A0
            // The catalogue row declares `hle_matches = "apple"` for
            // this engines-agree subset; per-byte exact values are
            // NOT engines-agree (kx_GetIndADB rec_b1 contents differ
            // byte-for-byte between BII and Systemless).
            //
            // Strict witness:
            //   a078_getindadb_strict (4-band
            //   1bpp 520x50 canvas: valid-index-returns-positive +
            //   out-of-range-returns-negative + ADBDataBlock-window-
            //   overwritten-with-trailing-sentinel-preservation).
            //
            // Regression coverage (in-Rust):
            //   getindadb_returns_device_info
            //   src/trap/memory.rs `mod tests`:
            //     - getindadb_valid_index_returns_positive_adb_address
            //     - getindadb_out_of_range_index_returns_negative_result
            //     - getindadb_writes_adbdatablock_for_valid_index
            //     - getindadb_preserves_caller_memory_beyond_adbdatablock
            (false, 0x78) => {
                let index = cpu.read_reg(Register::D0) & 0xFF;
                let info_ptr = cpu.read_reg(Register::A0);
                if let Some(adb_addr) = match index {
                    1 => Some(2u32), // keyboard
                    2 => Some(3u32), // mouse
                    _ => None,
                } {
                    if info_ptr != 0 {
                        // ADBDataBlock: devType(1), origADBAddr(1), dbServiceRtPtr(4), dbDataAreaAddr(4).
                        // HLE exposes two canonical devices and zeroes pointer fields.
                        for i in 0..10u32 {
                            bus.write_byte(info_ptr + i, 0);
                        }
                        bus.write_byte(info_ptr + 1, adb_addr as u8);
                    }
                    cpu.write_reg(Register::D0, adb_addr);
                } else {
                    // IM:Devices 5-43 / IM:V V-373: unknown entry -> negative result.
                    cpu.write_reg(Register::D0, 0xFFFF_FFFF);
                }
                Ok(())
            }

            // GetADBInfo ($A079)
            // Returns ADB device info by address.
            // FUNCTION GetADBInfo(VAR info: ADBDataBlock; adbAddr: ADBAddress): OSErr;
            // Inside Macintosh Volume V, V-373
            //
            // Regression coverage:
            //   getadbinfo_returns_device_data
            // GetADBInfo ($A079): Zero-fills the 10-byte ADBDataBlock, returns noErr per IM:V V-373
            (false, 0x79) => {
                let info_ptr = cpu.read_reg(Register::A0);
                if info_ptr != 0 {
                    for i in 0..10u32 {
                        bus.write_byte(info_ptr + i, 0);
                    }
                }
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // SetADBInfo ($A07A)
            // Sets ADB device info.
            // FUNCTION SetADBInfo(VAR info: ADBSetInfoBlock; adbAddr: ADBAddress): OSErr;
            // Inside Macintosh Volume V, V-374
            // No-op.
            //
            // Regression coverage:
            //   setadbinfo_sets_device_data
            // SetADBInfo ($A07A): Returns noErr per IM:V V-374
            (false, 0x7A) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // ADBReInit ($A07B)
            // Reinitializes ADB.
            // PROCEDURE ADBReInit;
            // Inside Macintosh Volume V, V-371
            // No-op.
            //
            // Regression coverage:
            //   adbreinit_reinitializes_adb
            // ADBReInit ($A07B): Per IM:V V-371
            (false, 0x7B) => Ok(()),

            // ADBOp ($A07C) — ADB Manager
            //
            // Per IM:V V-368: "ADBOp is used to send commands to ADB
            // devices. The data parameter points to a data buffer; the
            // compRout parameter points to a completion routine; the
            // buffer parameter points to a data area for the
            // completion routine; and the commandNum parameter is the
            // ADB command byte."
            //
            // Per IM:V V-371 + Devices 1994 pp. 5-39..5-45: ADBOp is
            // an OS-bit trap with a register-only ABI — the C-visible
            // Pascal signature `FUNCTION ADBOp(data: Ptr;
            // compRout: ProcPtr; buffer: Ptr; commandNum: INTEGER):
            // OSErr` is informational; the actual interface is
            // A0=ADBOpBlock pointer, D0=commandNum (byte), D0=OSErr
            // result. No Pascal stack arguments are consumed.
            //
            // ADBOpBlock layout (IM:V V-368, 12 bytes):
            //     +0  dataBuffPtr      Ptr {data buffer}
            //     +4  opServiceRtPtr   Ptr {completion routine}
            //     +8  opDataAreaPtr    Ptr {data area for service rtn}
            //
            // ADB command byte format (IM:V V-368 Table 35):
            //     bits 7..4 = ADB device address (0..15)
            //     bits 3..2 = command type:
            //                   00 = SendReset (reserved/internal)
            //                   01 = Flush
            //                   10 = Listen
            //                   11 = Talk
            //     bits 1..0 = ADB register (0..3) for Listen/Talk
            //
            // MPW Universal Headers: <Devices.h> exposes ADBOp via
            // an inline thunk; callers wishing to capture the D0
            // result use `#pragma parameter __D0 kx_ADBOp(__A0, __D0)
            // pascal long kx_ADBOp(Ptr block, short commandNum) =
            // {0xA07C};` to map the FUNCTION result and arg registers.
            //
            // Inside Macintosh Volume V (1986), pp. V-367 to V-368
            // Inside Macintosh: Devices (1994), pp. 5-39 to 5-45
            //
            // Engines divergence on D0 return value:
            //   BasiliskII System 7.5.3 ROM returns a non-zero result
            //   code in D0 for synthetic ADBOp calls with no completion
            //   routine wired (the emulated ADB Manager rejects calls
            //   it cannot complete asynchronously). Systemless HLE returns
            //   D0 = 0 unconditionally per its Stub (no-op)
            //   classification — ADB hardware events are sourced by
            //   the host event loop, so the ADB command queue is
            //   silently accepted as a no-op.
            //
            //   The Apple-canonical "ADBOp returns noErr on queued
            //   accept" contract from IM:V V-368 is pinned in-Rust via
            //   the `adbop_returns_noerr_when_command_queue_accepts_request`
            //   regression test below with `witness_kind = "contract"`
            //   in the catalogue row, since the engines disagree on
            //   the absolute D0 value.
            //
            //   The engines-agree subset is the register-only OS-bit-
            //   trap calling convention (A0 + D0 inputs, D0 output, no
            //   Pascal stack frame), witnessed by the strict bake
            //   fixture a07c_adbop_strict.
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::adbop_returns_noerr_when_command_queue_accepts_request
            //   src/trap/memory.rs::tests::adbop_uses_a0_parameter_block_and_d0_commandnum_without_stack_arguments
            //   src/trap/memory.rs::tests::adbop_repeated_calls_balance_stack_no_drift
            //   a07c_adbop_strict
            (false, 0x7C) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // VADBProc ($A0AE)
            // Virtual ADB dispatch.
            // Inside Macintosh: Devices (1994), pp. 5-39 to 5-40
            // (ADBReInit/JADBProc path).
            // No-op — preserves D0/A7; ADB not modeled.
            //
            // Regression coverage:
            //   src/trap/memory.rs::tests::vadbproc_preserves_d0_and_stack_and_updates_ccr
            //   a0ae_vadbproc_strict
            // VADBProc ($A0AE): Preserves caller D0/A7; per IM:Devices 5-39..5-40
            (false, 0xAE) => {
                Ok(())
            }

            // ========== Heap Zone Management ==========

            // GetZone ($A11A)
            // Returns the current heap zone.
            // FUNCTION GetZone: THz;
            // Inside Macintosh: Memory 1992, 2-80
            //
            // Returns TheZone low-mem global ($0118) in A0.
            //
            // Regression coverage:
            //   src/trap/memory.rs::getzone_returns_thezone_pointer_and_noerr
            //   src/trap/memory.rs::setzone_writes_thezone_and_getzone_roundtrips
            // GetZone ($A11A): Returns TheZone ($0118) in A0; D0=noErr; per IM:Memory 1992 2-80
            (false, 0x1A) => {
                let the_zone = bus.read_long(0x0118);
                cpu.write_reg(Register::A0, the_zone);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // SetZone ($A01B)
            // Sets the current heap zone.
            // PROCEDURE SetZone(hz: THz);
            // Inside Macintosh: Memory (1992), pp. 2-80 to 2-81
            //
            // Per IM:Memory 1992 p. 2-81 the trap is an OS-bit
            // PROCEDURE (bit 11 of the trap word is clear) with a
            // register-only ABI:
            //
            //   Registers on entry:
            //     A0  hz  pointer to a heap zone (THz)
            //
            //   Registers on exit:
            //     D0  Result code (noErr by Memory Manager dispatcher
            //                      convention)
            //
            // No Pascal stack argument frame is consumed and no result
            // slot is allocated.
            //
            // MPW Universal Headers MacMemory.h declares:
            //   #pragma parameter SetZone(__A0)
            //   EXTERN_API(void) SetZone(THz hz) ONEWORDINLINE(0xA01B);
            //
            // Documented contract per IM:Memory 1992 p. 2-81:
            //   "SetZone makes the zone to which hz points the
            //    current heap zone. ... Assembly-language note:
            //    Assembly-language callers can set TheZone directly."
            //
            // Both engines (BasiliskII System 7.5.3 ROM and Systemless
            // HLE) implement this as a single write of A0 into the
            // low-memory TheZone global at $0118. Subsequent GetZone
            // calls read $0118 and return the value in A0, so the
            // SetZone -> GetZone roundtrip preserves the supplied
            // zone pointer.
            //
            // Engines-agree subset (witnessed by strict bake
            // a01b_setzone_strict bands B1 + B2):
            //   - Low-memory TheZone ($0118) equals the supplied
            //     zone pointer after the call.
            //   - GetZone after SetZone(hz) returns A0=hz.
            //
            // Regression coverage:
            //   a01b_setzone_strict (BII golden)
            //   src/trap/memory.rs::setzone_writes_thezone_and_getzone_roundtrips
            //   src/trap/memory.rs::setzone_roundtrip_with_saved_original_restores_thezone
            (false, 0x1B) => {
                let zone = cpu.read_reg(Register::A0);
                bus.write_long(0x0118, zone);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // InitApplZone ($A02C)
            // Initializes the application heap zone.
            // PROCEDURE InitApplZone;
            // Inside Macintosh Volume II, II-28
            //
            // In emulation, the heap is managed by the bus allocator.
            // No-op — returns noErr.
            //
            // Regression coverage:
            //   src/trap/memory.rs::initapplzone_returns_noerr_result_code_in_d0
            //   src/trap/memory.rs::initapplzone_reinitializes_application_zone_and_makes_it_current
            //   src/trap/memory.rs::initapplzone_takes_no_arguments_and_preserves_stack_pointer
            // InitApplZone ($A02C): Reinitializes the observable
            // application-zone header, clears the grow-zone pointer,
            // makes ApplZone current, and returns D0=noErr; per IM:II
            // II-28
            (false, 0x2C) => {
                use crate::memory::globals::addr;
                let appl_zone = bus.read_long(addr::APP_L_ZONE);
                let appl_limit = bus.read_long(addr::APPL_LIMIT);
                init_zone_header(bus, appl_zone, appl_limit, 64, 0);
                bus.write_long(addr::THE_ZONE, appl_zone);
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // ========== Memory Manager Utility Traps ==========

            // EmptyHandle ($A02B)
            // Purges the relocatable block and sets master pointer to NIL.
            // PROCEDURE EmptyHandle(h: Handle);
            // Inside Macintosh: Memory, 2-42
            //
            // Regression coverage:
            //   emptyhandle_sets_master_pointer_to_nil
            //   emptyhandle_frees_data_block
            //   emptyhandle_nil_handle_returns_error
            //   emptyhandle_preserves_handle_state_bits
            // EmptyHandle ($A02B): Frees data block and sets master pointer to NIL; returns nilHandleErr for NIL handle; per IM:Memory 2-42. Resource-backed handles preserve Resource Manager metadata so LoadResource can revalidate them after purge (MMTB 1993 1-80; Memory 1992 2-52).
            (false, 0x2B) => {
                let handle = cpu.read_reg(Register::A0);
                if handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                } else {
                    let master_ptr = bus.read_long(handle);
                    if master_ptr != 0 {
                        self.ptr_to_handle.remove(&master_ptr);
                        if !self.loaded_handles.contains_key(&handle) {
                            bus.free(master_ptr);
                        }
                    }
                    bus.write_long(handle, 0); // set master pointer to NIL
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // BlockMoveData ($A22E) — handled by the existing BlockMove ($A02E) arm
            // above. Both map to trap_num=0x2E; in emulation there is no cache
            // flush to skip, so behavior is identical. IM:Memory 2-76.

            // MaxBlock ($A061)
            // Returns the maximum contiguous free space available
            // in the current heap (after a hypothetical compaction
            // and purge of all purgeable blocks).
            // FUNCTION MaxBlock: LongInt;
            // Inside Macintosh: Memory 1992, 2-47
            //
            // Per IM:Memory 1992 2-47: "MaxBlock returns the
            // maximum contiguous space, in bytes, that you could
            // obtain after compacting the current heap. MaxBlock
            // does not actually do the compaction." Real Mac
            // computes this by walking the free-block list and
            // counting the largest contiguous span (smaller than
            // FreeMem when the heap is fragmented).
            //
            // HLE compromise: Systemless doesn't model fragmentation
            // — every allocation is permanent in the bus's flat
            // address space, so "max contiguous" == "total free"
            // == free_heap_estimate value. Routes through the
            // same helper used by FreeMem / MaxMem / CompactMem /
            // PurgeSpace (reads ApplLimit - HeapEnd, clamps to
            // [24MB, 64MB]). Replaces a prior hardcoded 2MB
            // constant which was BELOW modern minimum-block-size
            // gates — apps that probe MaxBlock to verify "do I
            // have a 4MB+ contiguous block for a sound buffer or
            // GWorld pixmap?" would have failed at the 2MB
            // constant; the 24MB floor passes those gates.
            // MaxBlock ($A061): Per IM:Memory 1992 2-47 returns max contiguous free space (after hypothetical compaction). Systemless doesn't model fragmentation so MaxBlock == FreeMem == MaxMem == CompactMem == PurgeSpace via the shared free_heap_estimate helper (ApplLimit - HeapEnd clamped to [24MB, 64MB]). Replaces a prior hardcoded 2MB constant that was below modern 4MB+ contiguous-block gates (sound buffer, GWorld pixmap allocations).
            (false, 0x61) => {
                cpu.write_reg(Register::D0, free_heap_estimate(bus));
                Ok(())
            }

            // StackSpace ($A065)
            // Returns the amount of stack space available.
            // FUNCTION StackSpace: LongInt;
            // Inside Macintosh: Memory, 2-48
            //
            // Returns SP minus ApplLimit (heap top). In emulation, we estimate
            // generously since we don't track the real heap boundary.
            //
            // Regression coverage:
            //   stackspace_returns_positive_value
            // StackSpace ($A065): Returns SP minus ApplLimit ($0130); per IM:Memory 2-48
            (false, 0x65) => {
                let sp = cpu.read_reg(Register::A7);
                // ApplLimit ($0130) — top of application heap zone
                let appl_limit = bus.read_long(0x0130);
                let space = if appl_limit != 0 && sp > appl_limit {
                    sp - appl_limit
                } else {
                    // If ApplLimit not set, return a reasonable default
                    sp.min(256 * 1024)
                };
                cpu.write_reg(Register::D0, space);
                Ok(())
            }

            // ResrvMem ($A040)
            // Reserves space at the bottom of the heap for a block.
            // PROCEDURE ReserveMem(cbNeeded: Size);
            // Inside Macintosh: Memory, 2-52
            //
            // In emulation, heap compaction isn't needed. This is a no-op that
            // always succeeds — the next NewHandle will allocate wherever it can.
            //
            // Regression coverage:
            //   resrvmem_succeeds
            // ResrvMem ($A040): No-op in emulation; per IM:Memory 2-52
            (false, 0x40) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // PurgeMem ($A04D)
            // Inside Macintosh: Memory (1992), pp. 2-73 to 2-74,
            // p. 2-87 (summary), p. 2-94 (assembly-language summary).
            //
            // PROCEDURE PurgeMem (cbNeeded: Size);
            //   Registers on entry: D0 = Size of block to make room for
            //   Registers on exit:  D0 = Result code (noErr / memFullErr)
            //
            // OS-bit PROCEDURE (trap-word bit 11 clear) with a register-
            // only ABI: no Pascal stack argument frame and no FUNCTION
            // result slot. The MPW Universal Headers MacMemory.h
            // exposes the C-level `PurgeMem(Size cbNeeded)` with
            //   #pragma parameter PurgeMem(__D0)
            //   EXTERN_API(void) PurgeMem(Size cbNeeded) ONEWORDINLINE(0xA04D);
            //
            // Apple-canonical behavior: sequentially purge blocks from
            // the current heap zone until either a contiguous block of
            // at least cbNeeded free bytes exists, or the entire zone
            // has been purged (per IM:Memory 1992 p. 2-73). Only
            // relocatable, unlocked, purgeable blocks are purged. If
            // the zone is exhausted without yielding cbNeeded bytes,
            // memFullErr (-108) is returned in D0. Per IM:Memory 1992
            // p. 2-73 "PurgeMem does not actually attempt to allocate
            // a block of cbNeeded bytes."
            //
            // Why the absolute D0 result is NOT engines-agree:
            //   BasiliskII System 7.5.3 ROM manages a real Mac heap
            //   with arbitrary purgeable blocks installed by the boot
            //   process; the absolute D0 result depends on the
            //   boot-time layout. Systemless HLE's host-backed allocator
            //   has no purgeable blocks at all, so PurgeMem is
            //   structurally a no-op that always returns noErr. The
            //   only documented engines-agree post-condition is the
            //   register-only calling convention itself.
            //
            // Systemless HLE compromise: D0 (cbNeeded) is read and
            // discarded; D0 is set to noErr. This matches BasiliskII
            // System 7.5.3 ROM behavior on the calling-convention
            // contract — both engines preserve A7 and consume no
            // Pascal stack frame.
            //
            // Engines-agree on (witnessed by strict bake
            // a04d_purgemem_strict bands B1 + B2):
            //   (1) register-only ABI: A7 preserved across a single
            //       PurgeMem(0) call.
            //   (2) cumulative pop discipline: a 5-call composition
            //       cycling cbNeeded values 0 -> 256 -> 0 -> 1024 -> 0
            //       preserves A7 in aggregate (defeats stubs that
            //       consume a Pascal arg frame on the cbNeeded>0 path
            //       or pop a 4-byte cbNeeded value via Pascal calling
            //       convention).
            //
            // Regression coverage:
            //   src/trap/memory.rs::purgemem_register_only_calling_convention_preserves_stack
            (false, 0x4D) => {
                // D0 = cbNeeded on entry (read and discarded; no
                // purgeable blocks exist in the host-backed allocator).
                // Per IM:Memory 1992 p. 2-73 D0 carries the result code
                // on exit. Return noErr.
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // SetGrowZone ($A04B)
            // Inside Macintosh: Memory (1992), pp. 2-55 to 2-56 and p. 2-93.
            //
            // PROCEDURE SetGrowZone (growZone: ProcPtr);
            //   Registers on entry: A0 = pointer to new grow-zone function
            //                       (NIL removes any existing grow-zone
            //                       function per IM:Memory 1992 p. 2-56)
            //   Registers on exit:  D0 = result code (noErr)
            //
            // OS-bit PROCEDURE (trap-word bit 11 clear) with a register-only
            // ABI: no Pascal stack argument frame and no FUNCTION result
            // slot. The MPW Universal Headers MacMemory.h exposes the
            // C-level `SetGrowZone(GrowZoneUPP growZone)` with
            //   #pragma parameter SetGrowZone(__A0)
            //   EXTERN_API(void) SetGrowZone(GrowZoneUPP growZone) ONEWORDINLINE(0xA04B);
            //
            // Apple-canonical behavior: install the supplied function
            // pointer as the current heap zone's grow-zone function. The
            // Memory Manager calls the grow-zone function only after
            // exhausting all other avenues of satisfying a memory request
            // (compaction, zone growth, purging). A NIL parameter removes
            // any previously installed grow-zone function.
            //
            // Why the visible Zone field is NOT a reliable witness:
            //   Per IM:Memory 1992 p. 2-20 the Zone record's `gzProc` field
            //   description explicitly warns: "Note that in current versions
            //   of system software, this field does not contain a pointer
            //   to the grow-zone function that your application defines."
            //   The system installs an opaque trampoline in `zone.gzProc`
            //   and stashes the caller-supplied pointer in a private slot,
            //   so the directly observable field is system-trampoline-
            //   opaque and engines-divergent. The only documented engines-
            //   agree post-condition is the register-only calling
            //   convention itself.
            //
            // Systemless HLE compromise: no real heap-exhaustion path exists
            // (the host-backed allocator never triggers compaction, growth
            // pressure, or purging), so the registered grow-zone function
            // would never be invoked even if it were stored. A0 is read
            // and discarded; D0 is set to noErr. This matches BasiliskII
            // System 7.5.3 ROM behavior on the calling-convention contract
            // — both engines preserve A7, accept any A0 (NIL or non-NIL),
            // and return noErr.
            //
            // Engines-agree on (witnessed by strict bake
            // a04b_setgrowzone_strict bands B1 + B2):
            //   (1) register-only ABI: A7 preserved across a single
            //       SetGrowZone(NIL) call.
            //   (2) cumulative pop discipline: a 5-call composition
            //       cycling NIL → synthetic ProcPtr → NIL → synthetic
            //       ProcPtr → NIL preserves A7 in aggregate (defeats
            //       stubs that consume a Pascal arg frame on the non-NIL
            //       path).
            //
            // Regression coverage:
            //   src/trap/memory.rs::setgrowzone_register_only_calling_convention_preserves_stack
            (false, 0x4B) => {
                // A0 = pointer to grow-zone function (NIL or non-NIL).
                // Per IM:Memory 1992 p. 2-20 the user-supplied pointer is
                // stashed by the system in a private slot (the visible
                // zone.gzProc field holds an opaque trampoline), so the
                // HLE has nothing observable to write. Return noErr.
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // HSetRBit ($A067)
            //
            // PROCEDURE HSetRBit(h: Handle);
            // Inside Macintosh: Memory (1992), pp. 2-49 to 2-50.
            //
            // IM:Memory 1992 p. 2-49 verbatim: "You can use the HSetRBit
            // procedure to set the resource flag of a relocatable block.
            // The Resource Manager uses this routine extensively, but you
            // should never need to use it. ... The HSetRBit procedure sets
            // the resource flag of the relocatable block to which h is a
            // handle. It does nothing if the flag is already set."
            //
            // Per IM:Memory 1992 p. 2-49 the resource flag is bit 5 of the
            // master pointer's flag byte (also exposed as
            // `kHandleIsResourceMask = 0x20` in MPW MacMemory.h). HGetState
            // ($A069) returns this byte so callers observe the bit
            // transition; the IM warning on p. 2-43 ("do not rely on the
            // structure of master pointers") makes HGetState the canonical
            // read path because the byte layout differs between 24-bit
            // and 32-bit addressing modes.
            //
            // Assembly calling convention (IM:Memory 1992 p. 2-50):
            //   Registers on entry: A0 = handle
            //   Registers on exit:  D0 = result code (OSErr)
            //     noErr        =    0  success
            //     nilHandleErr = -109  NIL master pointer / handle
            //     memWZErr     = -111  free block
            //
            // MPW Universal Headers (MacMemory.h):
            //   #pragma parameter HSetRBit(__A0)
            //   EXTERN_API(void) HSetRBit(Handle h) ONEWORDINLINE(0xA067);
            // The void declaration elides D0 from C callers; a fixture
            // that needs to witness D0 (the nilHandleErr return) declares
            // an inline thunk like
            //   #pragma parameter __D0 kx_HSetRBit_D0(__A0)
            //   pascal short kx_HSetRBit_D0(Handle h) = { 0xA067 };
            // (used by a067_a068_hresource_bit_strict).
            //
            // Systemless HLE: tracks resource-flag state in the dispatcher's
            // `handle_state_bits` HashMap rather than poking master
            // pointer bytes. This is functionally transparent because
            // applications must use HGetState/HSetState/HSetRBit/HClrRBit
            // for state observation (per the IM warning) — the HashMap
            // is in sync with HSetRBit/HClrRBit writes and HGetState
            // reads from it, so round-trip semantics match BII byte-for-
            // byte on the documented surface.
            //
            // Witnessed by:
            //   a067_a068_hresource_bit_strict
            //     (BasiliskII bake + Systemless runtime; HGetState
            //      round-trip + nilHandleErr + register convention)
            //   src/trap/memory.rs::test_memorydispatch_hsetrbit_sets_resource_flag
            //   src/trap/memory.rs::test_memorydispatch_hsetrbit_nil_handle_returns_error
            //   src/trap/memory.rs::hsetrbit_then_hgetstate_round_trips_resource_bit
            //
            // HSetRBit ($A067): Sets resource flag (0x20) in handle_state_bits; nilHandleErr for NIL; per IM:Memory 1992 2-49..2-50
            (false, 0x67) => {
                let handle = cpu.read_reg(Register::A0);
                if handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                } else {
                    let bits = self.handle_state_bits.entry(handle).or_insert(0);
                    *bits |= 0x20; // resource bit
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // HClrRBit ($A068)
            //
            // PROCEDURE HClrRBit(h: Handle);
            // Inside Macintosh: Memory (1992), pp. 2-50 to 2-51.
            //
            // IM:Memory 1992 p. 2-50 verbatim: "You can use the HClrRBit
            // procedure to clear the resource flag of a relocatable
            // block. The Resource Manager uses this routine extensively,
            // but you probably won't need to use it. ... The HClrRBit
            // procedure clears the resource flag of a relocatable block.
            // It does nothing if the flag is already cleared."
            //
            // Symmetric with HSetRBit ($A067): clears the same bit-5 of
            // the master pointer's flag byte (0x20 mask). The Resource
            // Manager uses HClrRBit when the resource handle is being
            // detached from its 'rsrc' fork so it no longer needs to be
            // treated as a resource block.
            //
            // Assembly calling convention (IM:Memory 1992 p. 2-51):
            //   Registers on entry: A0 = handle
            //   Registers on exit:  D0 = result code (OSErr)
            //     noErr        =    0  success
            //     nilHandleErr = -109  NIL master pointer / handle
            //     memWZErr     = -111  free block
            //
            // MPW Universal Headers (MacMemory.h):
            //   #pragma parameter HClrRBit(__A0)
            //   EXTERN_API(void) HClrRBit(Handle h) ONEWORDINLINE(0xA068);
            // The void declaration elides D0 from C callers (mirrors
            // HSetRBit); fixtures use the same inline-thunk pattern with
            //   #pragma parameter __D0 kx_HClrRBit_D0(__A0)
            //   pascal short kx_HClrRBit_D0(Handle h) = { 0xA068 };
            // (see a067_a068_hresource_bit_strict).
            //
            // Systemless HLE: clears 0x20 in `handle_state_bits[handle]` and
            // removes the entry entirely when no flag bits remain. The
            // HashMap mirrors what HGetState ($A069) returns; BasiliskII
            // System 7.5.3 ROM updates the master pointer flag byte
            // directly. Both engines agree on the observable HGetState
            // round-trip behavior — set → 0x20, clear → 0x00 — across
            // a067_a068_hresource_bit_strict.
            //
            // Witnessed by:
            //   a067_a068_hresource_bit_strict
            //   src/trap/memory.rs::test_memorydispatch_hclrrbit_clears_resource_flag
            //   src/trap/memory.rs::test_memorydispatch_hclrrbit_nil_handle_returns_error
            //   src/trap/memory.rs::hclrrbit_after_hsetrbit_round_trips_resource_bit_to_zero
            //
            // HClrRBit ($A068): Clears resource flag (0x20) in handle_state_bits; nilHandleErr for NIL; per IM:Memory 1992 2-50..2-51
            (false, 0x68) => {
                let handle = cpu.read_reg(Register::A0);
                if handle == 0 {
                    cpu.write_reg(Register::D0, (-109i32) as u32); // nilHandleErr
                } else {
                    if let Some(bits) = self.handle_state_bits.get_mut(&handle) {
                        *bits &= !0x20; // clear resource bit
                        if *bits == 0 {
                            self.handle_state_bits.remove(&handle);
                        }
                    }
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // HandleZone ($A126)
            // Returns the heap zone containing a handle's relocatable block.
            // FUNCTION HandleZone(h: Handle): THz;
            // Inside Macintosh: Memory, 2-66
            //
            // In emulation, all allocations live in a single zone.
            // Return TheZone ($0118) for all valid handles.
            // $A126 = OS trap, trap_num = 0x26 (SYS bit ignored).
            //
            // Regression coverage:
            //   src/trap/memory.rs::handlezone_valid_handle_returns_current_zone_pointer
            //   src/trap/memory.rs::handlezone_empty_handle_returns_zone_pointer
            //   src/trap/memory.rs::handlezone_disposed_handle_returns_memwzerr
            // HandleZone ($A126): Returns TheZone ($0118) for live valid/empty handles; noErr for NIL; memWZErr for freed handles; per BasiliskII-observed nil divergence from IM:Memory 1992 2-82..2-83
            (false, 0x26) => {
                let handle = cpu.read_reg(Register::A0);
                if handle == 0 {
                    cpu.write_reg(Register::D0, 0); // noErr
                } else if bus.get_alloc_size(handle) != Some(4) {
                    cpu.write_reg(Register::D0, (-111i32) as u32); // memWZErr
                } else {
                    let the_zone = bus.read_long(0x0118); // TheZone low-mem global
                    cpu.write_reg(Register::A0, the_zone);
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // PtrZone ($A148)
            // Returns the heap zone containing a nonrelocatable block.
            // FUNCTION PtrZone(p: Ptr): THz;
            // Inside Macintosh: Memory, 2-65
            //
            // In emulation, all allocations live in a single zone.
            // Return TheZone ($0118) for all valid pointers.
            // $A148 = OS trap, trap_num = 0x48 (SYS bit ignored).
            //
            // Regression coverage:
            //   src/trap/memory.rs::ptrzone_valid_pointer_returns_current_zone_pointer
            //   src/trap/memory.rs::ptrzone_nil_pointer_returns_memwzerr
            // PtrZone ($A148): Returns TheZone ($0118) for valid pointer; memWZErr for NIL; per IM:Memory 1992 2-83
            (false, 0x48) => {
                let ptr = cpu.read_reg(Register::A0);
                if ptr == 0 {
                    cpu.write_reg(Register::D0, (-111i32) as u32); // memWZErr
                } else {
                    let the_zone = bus.read_long(0x0118); // TheZone low-mem global
                    cpu.write_reg(Register::A0, the_zone);
                    cpu.write_reg(Register::D0, 0); // noErr
                }
                Ok(())
            }

            // ========== MemoryDispatch Virtual Memory ==========

            // MemoryDispatch ($A05C)
            // Dispatches virtual memory operations by selector in D0.
            // Inside Macintosh: Memory, 4-6
            //
            // Selectors:
            //   0 = HoldMemory
            //   1 = UnholdMemory
            //   2 = LockMemory
            //   3 = UnlockMemory
            //   4 = LockMemoryContiguous
            //   5 = GetPhysical
            //
            // HLE model:
            // - Track hold/lock by 4 KiB logical pages.
            // - LockMemoryContiguous shares LockMemory semantics (we do not
            //   model physical fragmentation).
            // - UnholdMemory returns notHeldErr for ranges whose pages were
            //   never held; a previously-held range is idempotent after it
            //   has already been released.
            // - BasiliskII returns noErr for HoldMemory/UnholdMemory on
            //   non-logical-RAM ranges; Systemless matches BasiliskII here.
            // - GetPhysical returns identity mappings (logical == physical)
            //   but enforces the documented "range must be locked" contract.
            // - A zero-sized requested_entries query on a non-empty locked
            //   range follows the BasiliskII-observed paramErr/required-count
            //   behavior and leaves the translation table untouched. In
            //   Systemless's flat-RAM model, that required count is one physical
            //   entry. Empty ranges also return paramErr and preserve A0/
            //   table contents.
            // - For selectors 2..5, reject out-of-logical-RAM ranges with
            //   paramErr (-50), matching IM result-code contracts. Hold/
            //   Unhold invalid-range probes follow the BasiliskII noErr
            //   behavior instead.
            //
            // Reference:
            //   Inside Macintosh: Memory (1992), Virtual Memory Manager
            //   Reference, pages 3-25..3-32.
            //
            // Regression coverage:
            //   src/trap/memory.rs::test_memorydispatch_unlockmemory_returns_notlockederr_for_unlocked_range
            //   src/trap/memory.rs::test_memorydispatch_unholdmemory_returns_nothelderr_for_never_held_range
            //   src/trap/memory.rs::test_memorydispatch_holdmemory_round_trip_releases_idempotently
            //   src/trap/memory.rs::test_memorydispatch_holdmemory_invalid_range_returns_noerr_and_preserves_stack
            //   src/trap/memory.rs::test_memorydispatch_unholdmemory_invalid_range_returns_noerr_and_preserves_stack
            //   src/trap/memory.rs::test_memorydispatch_lockmemory_invalid_range_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_lockmemorycontiguous_invalid_range_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_lockmemorycontiguous_zero_length_invalid_range_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_unlockmemory_invalid_range_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_unlockmemory_reverses_lockmemorycontiguous_on_page_rounded_range
            //   src/trap/memory.rs::test_memorydispatch_getphysical_requires_locked_range
            //   src/trap/memory.rs::test_memorydispatch_getphysical_invalid_logical_range_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_getphysical_null_table_returns_paramerr
            //   src/trap/memory.rs::test_memorydispatch_getphysical_fills_identity_mapping_when_locked
            //   src/trap/memory.rs::test_memorydispatch_getphysical_entrycount_zero_returns_paramerr_and_required_entries
            //   src/trap/memory.rs::test_memorydispatch_getphysical_entrycount_zero_on_empty_range_returns_paramerr_and_preserves_table
            //   src/trap/memory.rs::test_memorydispatch_getphysical_entrycount_zero_on_unlocked_range_returns_notlockederr
            //   src/trap/memory.rs::test_memorydispatch_getphysical_entrycount_zero_on_locked_multpage_range_returns_two_and_preserves_table
            // MemoryDispatch ($A05C): Tracks Hold/Lock page state and implements GetPhysical lock-check + identity mapping; selectors per IM:Memory 1992 pp.3-25..3-32
            (false, 0x5C) => {
                let selector = cpu.read_reg(Register::D0);
                let address = cpu.read_reg(Register::A0);
                let count = cpu.read_reg(Register::A1);
                match selector {
                    0 => {
                        if !vm_range_is_logical_ram(bus, address, count) {
                            cpu.write_reg(Register::D0, NO_ERR);
                            return Some(Ok(()));
                        }
                        // HoldMemory: mark each covered page held.
                        if let Some((page_start, page_end_exclusive)) = vm_page_span(address, count)
                        {
                            vm_increment_pages(
                                &mut self.vm_held_page_counts,
                                page_start,
                                page_end_exclusive,
                            );
                            self.vm_held_page_history
                                .extend(page_start..page_end_exclusive);
                        }
                        cpu.write_reg(Register::D0, NO_ERR);
                    }
                    1 => {
                        if !vm_range_is_logical_ram(bus, address, count) {
                            cpu.write_reg(Register::D0, NO_ERR);
                            return Some(Ok(()));
                        }
                        let result = if let Some((page_start, page_end_exclusive)) =
                            vm_page_span(address, count)
                        {
                            let ever_held = (page_start..page_end_exclusive)
                                .all(|page| self.vm_held_page_history.contains(&page));
                            if ever_held {
                                let _ = vm_try_decrement_pages(
                                    &mut self.vm_held_page_counts,
                                    page_start,
                                    page_end_exclusive,
                                );
                                NO_ERR
                            } else {
                                NOT_HELD_ERR
                            }
                        } else {
                            NO_ERR
                        };
                        cpu.write_reg(Register::D0, result);
                    }
                    2 | 4 => {
                        if !vm_range_is_logical_ram(bus, address, count) {
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }
                        // LockMemory / LockMemoryContiguous:
                        // mark each covered page locked.
                        //
                        // We intentionally model selector 4 as selector 2
                        // because Systemless does not model physical-page
                        // relocation/fragmentation; callers still get
                        // lock-state semantics for GetPhysical.
                        if let Some((page_start, page_end_exclusive)) = vm_page_span(address, count)
                        {
                            vm_increment_pages(
                                &mut self.vm_locked_page_counts,
                                page_start,
                                page_end_exclusive,
                            );
                        }
                        cpu.write_reg(Register::D0, NO_ERR);
                    }
                    3 => {
                        if !vm_range_is_logical_ram(bus, address, count) {
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }
                        // UnlockMemory: error when any page is not currently locked.
                        let result = if let Some((page_start, page_end_exclusive)) =
                            vm_page_span(address, count)
                        {
                            if vm_try_decrement_pages(
                                &mut self.vm_locked_page_counts,
                                page_start,
                                page_end_exclusive,
                            ) {
                                NO_ERR
                            } else {
                                NOT_LOCKED_ERR
                            }
                        } else {
                            NO_ERR
                        };
                        cpu.write_reg(Register::D0, result);
                    }
                    5 => {
                        // GetPhysical:
                        // A0 = LogicalToPhysicalTable pointer
                        // A1 = physicalEntryCount on entry
                        // A0 = translated entry count on exit
                        let table_ptr = address;
                        let requested_entries = count;
                        if table_ptr == 0 {
                            cpu.write_reg(Register::A0, 0);
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }

                        let logical_start = bus.read_long(table_ptr);
                        let logical_count = bus.read_long(table_ptr + 4);
                        if !vm_range_is_logical_ram(bus, logical_start, logical_count) {
                            cpu.write_reg(Register::A0, 0);
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }
                        if logical_count == 0 {
                            // BasiliskII leaves A0 pointing at the table on this
                            // empty-range error path.
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }

                        let logical_locked = vm_page_span(logical_start, logical_count)
                            .map(|(page_start, page_end_exclusive)| {
                                vm_range_is_fully_tracked(
                                    &self.vm_locked_page_counts,
                                    page_start,
                                    page_end_exclusive,
                                )
                            })
                            .unwrap_or(true);
                        if !logical_locked {
                            cpu.write_reg(Register::A0, 0);
                            cpu.write_reg(Register::D0, NOT_LOCKED_ERR);
                            return Some(Ok(()));
                        }

                        if requested_entries == 0 {
                            // Report the number of physical entries needed to cover the
                            // requested logical span. Systemless's VM model is page-based, so
                            // the count matches the number of tracked pages in the span.
                            let required_entries =
                                vm_required_physical_entries(logical_start, logical_count);
                            cpu.write_reg(Register::A0, required_entries);
                            cpu.write_reg(Register::D0, PARAM_ERR);
                            return Some(Ok(()));
                        }

                        // Identity mapping in HLE: one physical block with the
                        // same start/count as the logical range.
                        // LogicalToPhysicalTable layout:
                        //   +0  logical.address
                        //   +4  logical.count
                        //   +8  physical[0].address
                        //   +12 physical[0].count
                        bus.write_long(table_ptr + 8, logical_start);
                        bus.write_long(table_ptr + 12, logical_count);
                        cpu.write_reg(Register::A0, 1);
                        cpu.write_reg(Register::D0, NO_ERR);
                    }
                    _ => {
                        eprintln!("[TRAP] MemoryDispatch: unknown selector {}", selector);
                        cpu.write_reg(Register::D0, PARAM_ERR);
                    }
                }
                Ok(())
            }

            // HeapDispatch ($A0A4)
            // Heap Manager dispatch for extended heap operations.
            // Inside Macintosh Volume VI, Heap Manager section.
            //
            // No-op in emulation — returns noErr and follows the
            // Memory Manager dispatcher CCR discipline (TST.W D0)
            // so callers that inspect condition codes see Z set for
            // the noErr path.
            //
            // Regression coverage:
            //   heapdispatch_returns_noerr
            (false, 0xA4) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            // NewPtrSys ($A51E)
            // Allocates nonrelocatable block in system heap.
            // In emulation, same as NewPtr (single heap).
            // Inside Macintosh: Memory, 2-30
            //
            // Already handled by (false, 0x1E) since SYS bit is ignored.
            // This arm catches the explicit $A51E trap word.

            // SetApplBase ($A057)
            // Sets the application heap's base address to startPtr; per
            // IM:II II-28 + IM:Memory 1992 p. 2-88 the trap is an OS-bit
            // routine (bit 11 clear) with register-only ABI:
            //
            //   Registers on entry: A0 = startPtr (pointer to new heap base)
            //   Registers on exit:  D0 = OSErr (Memory Manager dispatcher
            //                                   convention; 0 = noErr)
            //
            // Pascal signature: PROCEDURE SetApplBase(startPtr: Ptr);
            // MPW Universal Headers MacMemory.h declaration:
            //   #pragma parameter SetApplBase(__A0)
            //   EXTERN_API(void) SetApplBase(void *startPtr)
            //                                ONEWORDINLINE(0xA057);
            //
            // Although the Pascal signature is PROCEDURE, the Memory
            // Manager dispatcher conventionally writes 0 in D0 on
            // success (this is the Memory Manager OS-bit dispatcher
            // convention even for traps declared as PROCEDURE in the
            // public Pascal/C wrapper). Both BII's System 7.5.3 ROM and
            // Systemless HLE return D0 = noErr on the nominal call path.
            //
            // Per IM:II II-28 "The procedure SetApplBase sets the
            // application heap to start at the address startPtr. ...
            // If startPtr is NIL, the procedure sets it to its preset
            // default."
            //
            // Systemless HLE compromise: the bus allocator manages the
            // heap centrally, so SetApplBase is a no-op that writes
            // D0 = 0 (noErr) and returns. The startPtr argument is
            // ignored because Systemless does not model a relocatable
            // application zone.
            //
            // Apple-vs-Systemless divergence on stack discipline:
            //   Per IM:II II-29 the trap has a register-only ABI and
            //   should preserve A7. Systemless HLE preserves A7 byte-for-
            //   byte (only D0 is written). BII's System 7.5.3 ROM does
            //   real heap-validation work during the trap, and the
            //   kx_StackSpace probe in the fixture-runtime reports
            //   sp_pre != sp_post even though the documented register
            //   table guarantees no Pascal stack frame is consumed.
            //   This stack-discipline divergence is engine-divergent
            //   and is therefore witnessed only by the in-Rust
            //   contract test setapplbase_uses_register_calling_
            //   convention_without_stack_arguments below, not by the
            //   BII strict bake.
            //
            // Witnessed by:
            //   a057_setapplbase_strict/  (BII bake;
            //     witnesses the engines-agree noErr-return path with
            //     startPtr echoing the current ApplZone low-memory
            //     pointer at $02AA)
            //   catalogue trap A057_SetApplBase
            //
            // Regression coverage:
            //   src/trap/memory.rs::setapplbase_uses_a0_startptr_and_returns_noerr_in_d0
            //   src/trap/memory.rs::setapplbase_uses_register_calling_convention_without_stack_arguments
            //   src/trap/memory.rs::setapplbase_returns_noerr_regardless_of_startptr_value
            (false, 0x57) => {
                cpu.write_reg(Register::D0, 0); // noErr
                Ok(())
            }

            _ => return None,
        };

        if result.is_ok() && memory_manager_trap_updates_dispatcher_ccr(is_tool, trap_num) {
            apply_memory_manager_dispatcher_ccr(cpu);
        }

        Some(result)
    }
}

/// Convert a Mac Roman character to uppercase per Inside Macintosh IV, IV-235.
/// If `strip_marks` is true, diacritical marks are also stripped.
///
/// Mac Roman uppercase conversion table (from IM:IV case conversion):
///   à(0x88)→À(0xCB), ã(0x8B)→Ã(0xCC), ä(0x8A)→Ä(0x80), å(0x8C)→Å(0x81),
///   æ(0xBE)→Æ(0xAE), ç(0x8D)→Ç(0x82), é(0x8E)→É(0x83), ñ(0x96)→Ñ(0x84),
///   ö(0x9A)→Ö(0x85), õ(0x9B)→Õ(0xCD), ø(0xBF)→Ø(0xAF), œ(0xCF)→Œ(0xCE),
///   ü(0x9F)→Ü(0x86)
fn mac_roman_to_upper(ch: u8, strip_marks: bool) -> u8 {
    if strip_marks {
        // Strip diacriticals first, then uppercase the base letter
        let stripped = mac_roman_strip_diacriticals(ch);
        if stripped.is_ascii_lowercase() {
            return stripped - 32;
        }
        return stripped;
    }
    // Standard ASCII lowercase → uppercase
    if ch.is_ascii_lowercase() {
        return ch - 32;
    }
    // Mac Roman accented lowercase → accented uppercase
    // Only the pairs that exist in Mac Roman per IM:IV IV-235
    match ch {
        0x88 => 0xCB, // à → À
        0x8A => 0x80, // ä → Ä
        0x8B => 0xCC, // ã → Ã
        0x8C => 0x81, // å → Å
        0x8D => 0x82, // ç → Ç
        0x8E => 0x83, // é → É
        0x96 => 0x84, // ñ → Ñ
        0x9A => 0x85, // ö → Ö
        0x9B => 0xCD, // õ → Õ
        0x9F => 0x86, // ü → Ü
        0xBE => 0xAE, // æ → Æ
        0xBF => 0xAF, // ø → Ø
        0xCF => 0xCE, // œ → Œ
        _ => ch,
    }
}

/// Convert a Mac Roman character to lowercase.
fn mac_roman_to_lower(ch: u8) -> u8 {
    if ch.is_ascii_uppercase() {
        return ch + 32;
    }
    // Mac Roman uppercase accented → lowercase accented (reverse of to_upper)
    match ch {
        0x80 => 0x8A, // Ä → ä
        0x81 => 0x8C, // Å → å
        0x82 => 0x8D, // Ç → ç
        0x83 => 0x8E, // É → é
        0x84 => 0x96, // Ñ → ñ
        0x85 => 0x9A, // Ö → ö
        0x86 => 0x9F, // Ü → ü
        0xAE => 0xBE, // Æ → æ
        0xAF => 0xBF, // Ø → ø
        0xCB => 0x88, // À → à
        0xCC => 0x8B, // Ã → ã
        0xCD => 0x9B, // Õ → õ
        0xCE => 0xCF, // Œ → œ
        _ => ch,
    }
}

/// Strip diacritical marks from a Mac Roman character without case conversion.
/// Per IM:IV IV-235 stripping table.
fn mac_roman_strip_diacriticals(ch: u8) -> u8 {
    match ch {
        // Uppercase accented → uppercase base
        0x80 => b'A', // Ä → A
        0x81 => b'A', // Å → A
        0x82 => b'C', // Ç → C
        0x83 => b'E', // É → E
        0x84 => b'N', // Ñ → N
        0x85 => b'O', // Ö → O
        0x86 => b'U', // Ü → U
        0xAE => b'A', // Æ → A
        0xAF => b'O', // Ø → O
        0xCB => b'A', // À → A
        0xCC => b'A', // Ã → A
        0xCD => b'O', // Õ → O
        0xCE => b'O', // Œ → O
        // Lowercase accented → lowercase base
        0x87 => b'a', // á → a
        0x88 => b'a', // à → a
        0x89 => b'a', // â → a
        0x8A => b'a', // ä → a
        0x8B => b'a', // ã → a
        0x8C => b'a', // å → a
        0x8D => b'c', // ç → c
        0x8E => b'e', // é → e
        0x8F => b'e', // è → e
        0x90 => b'e', // ê → e
        0x91 => b'e', // ë → e
        0x92 => b'i', // í → i
        0x93 => b'i', // ì → i
        0x94 => b'i', // î → i
        0x95 => b'i', // ï → i
        0x96 => b'n', // ñ → n
        0x97 => b'o', // ó → o
        0x98 => b'o', // ò → o
        0x99 => b'o', // ô → o
        0x9A => b'o', // ö → o
        0x9B => b'o', // õ → o
        0x9C => b'u', // ú → u
        0x9D => b'u', // ù → u
        0x9E => b'u', // û → u
        0x9F => b'u', // ü → u
        0xBB => b'a', // ª → a
        0xBC => b'o', // º → o
        0xBE => b'a', // æ → a
        0xBF => b'o', // ø → o
        0xCF => b'o', // œ → o
        0xD8 => b'y', // ÿ → y
        _ => ch,
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_helpers::{setup, TEST_SP};
    use crate::cpu::{CpuOps, Register};
    use crate::memory::MemoryBus;

    // ==================== OS Traps (is_tool=false) ====================

    #[test]
    fn test_new_ptr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 256);
        let result = dispatcher.dispatch_memory(false, 0x1E, &mut cpu, &mut bus);
        assert!(result.is_some(), "NewPtr should be handled");
        assert!(result.unwrap().is_ok(), "NewPtr should succeed");
        let ptr = cpu.read_reg(Register::A0);
        assert!(
            ptr >= 0x200000,
            "NewPtr should return a valid heap pointer, got ${:08X}",
            ptr
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NewPtr should set D0 to 0 (noErr)"
        );
    }

    #[test]
    fn test_new_handle() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 512);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.is_some(), "NewHandle should be handled");
        assert!(result.unwrap().is_ok(), "NewHandle should succeed");
        let handle = cpu.read_reg(Register::A0);
        assert!(
            handle >= 0x200000,
            "NewHandle should return a valid handle address, got ${:08X}",
            handle
        );
        let ptr = bus.read_long(handle);
        assert!(
            ptr >= 0x200000,
            "NewHandle's handle should point to a valid ptr, got ${:08X}",
            ptr
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NewHandle should set D0 to 0 (noErr)"
        );
    }

    #[test]
    fn test_dispose_ptr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x1F, &mut cpu, &mut bus);
        assert!(result.is_some(), "DisposePtr should be handled");
        assert!(result.unwrap().is_ok(), "DisposePtr should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DisposePtr should set D0 to 0"
        );
    }

    #[test]
    fn test_dispose_handle() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x23, &mut cpu, &mut bus);
        assert!(result.is_some(), "DisposeHandle should be handled");
        assert!(result.unwrap().is_ok(), "DisposeHandle should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DisposeHandle should set D0 to 0"
        );
    }

    #[test]
    fn test_hlock() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x29, &mut cpu, &mut bus);
        assert!(result.is_some(), "HLock should be handled");
        assert!(result.unwrap().is_ok(), "HLock should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "HLock should set D0 to 0");
    }

    #[test]
    fn test_hunlock() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x2A, &mut cpu, &mut bus);
        assert!(result.is_some(), "HUnlock should be handled");
        assert!(result.unwrap().is_ok(), "HUnlock should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "HUnlock should set D0 to 0");
    }

    #[test]
    fn test_heapdispatch_sets_noerr_and_ccr_like_other_memory_dispatchers() {
        let (mut dispatcher, mut cpu, mut bus) = setup();

        // Seed the CCR with non-zero flags so we can prove the trap
        // rewrites it instead of leaving stale condition codes behind.
        cpu.set_ccr(0x1F);

        let result = dispatcher.dispatch_memory(false, 0xA4, &mut cpu, &mut bus);
        assert!(result.is_some(), "HeapDispatch should be handled");
        assert!(result.unwrap().is_ok(), "HeapDispatch should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HeapDispatch should set D0 to 0"
        );
        assert_eq!(
            cpu.get_ccr() & 0x1F,
            0x14,
            "HeapDispatch should leave X set and Z asserted for the noErr path"
        );
    }

    fn assert_nohw_trap_preserves_d0_and_stack_and_updates_ccr(
        dispatcher: &mut crate::trap::TrapDispatcher,
        cpu: &mut impl CpuOps,
        bus: &mut crate::memory::MacMemoryBus,
        trap_num: u16,
        trap_name: &str,
        d0_seed: u32,
        expected_ccr: u8,
    ) {
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::D0, d0_seed);
        cpu.set_ccr(0x1F);

        let result = dispatcher.dispatch_memory(false, trap_num, cpu, bus);
        assert!(result.is_some(), "{trap_name} should be handled");
        assert!(result.unwrap().is_ok(), "{trap_name} should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            d0_seed,
            "{trap_name} should preserve D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "{trap_name} should not consume a Pascal argument frame"
        );
        assert_eq!(
            cpu.get_ccr() & 0x1F,
            expected_ccr,
            "{trap_name} should mirror the preserved D0 into the dispatcher CCR"
        );
    }

    #[test]
    fn vadbproc_preserves_d0_and_stack_and_updates_ccr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        assert_nohw_trap_preserves_d0_and_stack_and_updates_ccr(
            &mut dispatcher,
            &mut cpu,
            &mut bus,
            0xAE,
            "VADBProc",
            0x1234_5678,
            0x10,
        );
    }

    #[test]
    fn scsiaction_scsigetvirtualidinfo_missing_virtual_id_clears_exists_and_preserves_stack() {
        let (mut dispatcher, mut cpu, mut bus) = setup();

        const PB_SIZE: u32 = 40;
        const PB_LENGTH_OFFSET: usize = 6;
        const PB_FUNCTION_CODE_OFFSET: usize = 8;
        const PB_RESULT_OFFSET: usize = 10;
        const PB_OLD_CALL_ID_OFFSET: usize = 36;
        const PB_EXISTS_OFFSET: usize = 38;
        const SCSI_GET_VIRTUAL_ID_INFO_FUNCTION_CODE: u8 = 0x80;

        let scsi_pb = bus.alloc(PB_SIZE);
        let sp_before = cpu.read_reg(Register::A7);
        let mut i: usize = 0;

        while i < PB_SIZE as usize {
            bus.write_byte(scsi_pb + i as u32, 0);
            i += 1;
        }
        bus.write_word(scsi_pb + PB_LENGTH_OFFSET as u32, PB_SIZE as u16);
        bus.write_byte(
            scsi_pb + PB_FUNCTION_CODE_OFFSET as u32,
            SCSI_GET_VIRTUAL_ID_INFO_FUNCTION_CODE,
        );
        bus.write_word(scsi_pb + PB_RESULT_OFFSET as u32, 0x3FFF);
        bus.write_word(scsi_pb + PB_OLD_CALL_ID_OFFSET as u32, 0x1234);
        bus.write_byte(scsi_pb + PB_EXISTS_OFFSET as u32, 0xFF);

        cpu.write_reg(Register::A0, scsi_pb);
        cpu.write_reg(Register::D0, 0x0000_0001);

        let result = dispatcher.dispatch_memory(false, 0x89, &mut cpu, &mut bus);
        assert!(result.is_some(), "SCSIAtomic should be handled");
        assert!(result.unwrap().is_ok(), "SCSIAtomic should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SCSIAtomic should return noErr"
        );
        assert_eq!(
            bus.read_word(scsi_pb + PB_RESULT_OFFSET as u32),
            0,
            "SCSIAction should mirror noErr into scsiResult"
        );
        assert_eq!(
            bus.read_byte(scsi_pb + PB_EXISTS_OFFSET as u32),
            0,
            "SCSIGetVirtualIDInfo should clear scsiExists for a missing virtual ID"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SCSIAction should preserve StackSpace"
        );
    }

    #[test]
    fn scsiaction_scsigetvirtualidinfo_rejects_nonzero_qlink_with_qlink_invalid() {
        // Inside Macintosh: Devices (1994), pp. 4-49 to 4-50 and 4-21:
        // qLink is part of the common SCSIAction header and must be 0.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        const PB_SIZE: u32 = 40;
        const PB_RESULT_OFFSET: usize = 10;
        const PB_EXISTS_OFFSET: usize = 38;

        let scsi_pb = bus.alloc(PB_SIZE);
        let sp_before = cpu.read_reg(Register::A7);

        for i in 0..PB_SIZE as usize {
            bus.write_byte(scsi_pb + i as u32, 0);
        }
        bus.write_long(scsi_pb, 0x0000_0001);
        bus.write_word(scsi_pb + 6, PB_SIZE as u16);
        bus.write_byte(scsi_pb + 8, 0x80);
        bus.write_word(scsi_pb + PB_RESULT_OFFSET as u32, 0x3FFF);
        bus.write_byte(scsi_pb + PB_EXISTS_OFFSET as u32, 0xFF);

        cpu.write_reg(Register::A0, scsi_pb);
        cpu.write_reg(Register::D0, 0x0000_0001);

        let result = dispatcher.dispatch_memory(false, 0x89, &mut cpu, &mut bus);
        assert!(result.is_some(), "SCSIAtomic should be handled");
        assert!(result.unwrap().is_ok(), "SCSIAtomic should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -7881,
            "SCSIAtomic should return scsiQLinkInvalid for a nonzero qLink"
        );
        assert_eq!(
            bus.read_word(scsi_pb + PB_RESULT_OFFSET as u32) as i16,
            -7881,
            "SCSIAction should mirror scsiQLinkInvalid into scsiResult"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SCSIAction should preserve StackSpace on qLink errors"
        );
        assert_eq!(
            bus.read_byte(scsi_pb + PB_EXISTS_OFFSET as u32),
            0xFF,
            "SCSIGetVirtualIDInfo should leave scsiExists untouched on qLink errors"
        );
    }

    #[test]
    fn scsiaction_scsigetvirtualidinfo_rejects_short_parameter_block_with_length_error() {
        // Inside Macintosh: Devices (1994), pp. 4-49 to 4-50 and 4-21:
        // SCSIAction checks the parameter block length before attempting
        // to use SCSIGetVirtualIDInfo-specific fields.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        const PB_SIZE: u32 = 40;
        const PB_RESULT_OFFSET: usize = 10;
        const PB_EXISTS_OFFSET: usize = 38;

        let scsi_pb = bus.alloc(PB_SIZE);
        let sp_before = cpu.read_reg(Register::A7);

        for i in 0..PB_SIZE as usize {
            bus.write_byte(scsi_pb + i as u32, 0);
        }
        bus.write_word(scsi_pb + 6, 8);
        bus.write_byte(scsi_pb + 8, 0x80);
        bus.write_word(scsi_pb + PB_RESULT_OFFSET as u32, 0x3FFF);
        bus.write_byte(scsi_pb + PB_EXISTS_OFFSET as u32, 0xFF);

        cpu.write_reg(Register::A0, scsi_pb);
        cpu.write_reg(Register::D0, 0x0000_0001);

        let result = dispatcher.dispatch_memory(false, 0x89, &mut cpu, &mut bus);
        assert!(result.is_some(), "SCSIAtomic should be handled");
        assert!(result.unwrap().is_ok(), "SCSIAtomic should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -7872,
            "SCSIAtomic should return scsiPBLengthError for a short parameter block"
        );
        assert_eq!(
            bus.read_word(scsi_pb + PB_RESULT_OFFSET as u32) as i16,
            -7872,
            "SCSIAction should mirror scsiPBLengthError into scsiResult"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SCSIAction should preserve StackSpace on PB length errors"
        );
        assert_eq!(
            bus.read_byte(scsi_pb + PB_EXISTS_OFFSET as u32),
            0xFF,
            "SCSIGetVirtualIDInfo should leave scsiExists untouched on PB length errors"
        );
    }

    #[test]
    fn scsiaction_scsigetvirtualidinfo_rejects_non_nil_completion_with_request_invalid() {
        // Inside Macintosh: Devices (1994), pp. 4-49 to 4-50 and 4-21:
        // SCSIGetVirtualIDInfo is synchronous, so scsiCompletion must be nil.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        const PB_SIZE: u32 = 40;
        const PB_RESULT_OFFSET: usize = 10;
        const PB_COMPLETION_OFFSET: usize = 16;

        let scsi_pb = bus.alloc(PB_SIZE);

        for i in 0..PB_SIZE as usize {
            bus.write_byte(scsi_pb + i as u32, 0);
        }
        bus.write_word(scsi_pb + 6, PB_SIZE as u16);
        bus.write_byte(scsi_pb + 8, 0x80);
        bus.write_long(scsi_pb + PB_COMPLETION_OFFSET as u32, 0x0000_1234);
        bus.write_word(scsi_pb + PB_RESULT_OFFSET as u32, 0x3FFF);

        cpu.write_reg(Register::A0, scsi_pb);
        cpu.write_reg(Register::D0, 0x0000_0001);

        let result = dispatcher.dispatch_memory(false, 0x89, &mut cpu, &mut bus);
        assert!(result.is_some(), "SCSIAtomic should be handled");
        assert!(result.unwrap().is_ok(), "SCSIAtomic should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -7870,
            "SCSIAtomic should return scsiRequestInvalid for a non-nil completion"
        );
        assert_eq!(
            bus.read_word(scsi_pb + PB_RESULT_OFFSET as u32) as i16,
            -7870,
            "SCSIAction should mirror scsiRequestInvalid into scsiResult"
        );
    }

    #[test]
    fn scsiaction_scsigetvirtualidinfo_rejects_nil_parameter_block_with_request_invalid() {
        // Inside Macintosh: Devices (1994), pp. 4-38 to 4-39 and p. 4-90:
        // SCSIAction takes a pointer to a SCSI Manager parameter block, so
        // a NIL scsiPB is an invalid request.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        let sp_before = cpu.read_reg(Register::A7);

        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::D0, 0x0000_0001);

        let result = dispatcher.dispatch_memory(false, 0x89, &mut cpu, &mut bus);
        assert!(result.is_some(), "SCSIAtomic should be handled");
        assert!(result.unwrap().is_ok(), "SCSIAtomic should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -7870,
            "SCSIAtomic should return scsiRequestInvalid for a NIL parameter block"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SCSIAction should preserve StackSpace on a NIL parameter block"
        );
    }

    #[test]
    fn pmgrop_returns_noerr_and_preserves_stack_pointer_in_noop_path() {
        // Inside Macintosh: Devices (1994), Power Manager chapter.
        // PMgrOp is the no-op Power Manager dispatcher on systems with no
        // hardware power management. The HLE path should consume no Pascal
        // arguments, return noErr in D0, and leave A7 untouched.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);

        cpu.write_reg(Register::D0, 0);
        let result = dispatcher.dispatch_memory(false, 0x85, &mut cpu, &mut bus);
        assert!(result.is_some(), "PMgrOp should be handled");
        assert!(result.unwrap().is_ok(), "PMgrOp should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "PMgrOp should return noErr");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "PMgrOp should preserve the caller stack pointer"
        );
    }

    fn assert_no_hardware_trap_returns_noerr_and_preserves_stack(trap_num: u16, trap_name: &str) {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xA5A5_5A5A);

        cpu.write_reg(Register::D0, 0xFFFF_FFFF);
        let result = dispatcher.dispatch_memory(false, trap_num, &mut cpu, &mut bus);
        assert!(result.is_some(), "{trap_name} should be handled");
        assert!(result.unwrap().is_ok(), "{trap_name} should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "{trap_name} should return noErr");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "{trap_name} should preserve the caller stack pointer"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xA5A5_5A5A,
            "{trap_name} should not consume or rewrite stack arguments"
        );
    }

    #[test]
    fn iopinfoaccess_returns_noerr_and_preserves_stack_pointer() {
        // The generic target has no IOP hardware, so the HLE path is the
        // same no-hardware compatibility return used by IOPMoveData.
        assert_no_hardware_trap_returns_noerr_and_preserves_stack(0x86, "IOPInfoAccess");
    }

    #[test]
    fn iopmsgrequest_returns_noerr_and_preserves_stack_pointer() {
        assert_no_hardware_trap_returns_noerr_and_preserves_stack(0x87, "IOPMsgRequest");
    }

    #[test]
    fn egretdispatch_returns_noerr_and_preserves_stack_pointer() {
        assert_no_hardware_trap_returns_noerr_and_preserves_stack(0x92, "EgretDispatch");
    }

    #[test]
    fn hsetrbit_sets_resource_flag_for_valid_handle() {
        // Inside Macintosh: Memory (1992), pp. 2-49 to 2-50:
        // HSetRBit sets a handle's resource flag and returns noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let data_ptr = bus.alloc(16);
        let handle = bus.alloc(4);
        bus.write_long(handle, data_ptr);
        let sp_before = cpu.read_reg(Register::A7);

        cpu.write_reg(Register::A0, handle);
        let result = dispatcher.dispatch_memory(false, 0x67, &mut cpu, &mut bus);
        assert!(result.is_some(), "HSetRBit should be handled");
        assert!(result.unwrap().is_ok(), "HSetRBit should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HSetRBit should return noErr for a valid handle"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "HSetRBit uses register calling convention and should preserve A7"
        );
        assert_eq!(
            dispatcher
                .handle_state_bits
                .get(&handle)
                .copied()
                .unwrap_or(0)
                & 0x20,
            0x20,
            "HSetRBit should set the resource bit in tracked handle state"
        );
    }

    #[test]
    fn hsetrbit_nil_handle_returns_nilhandleerr_in_d0() {
        // Inside Macintosh: Memory (1992), pp. 2-49 to 2-50:
        // nilHandleErr (-109) is returned for a NIL master pointer.
        let (mut dispatcher, mut cpu, mut _bus) = setup();
        cpu.write_reg(Register::A0, 0);

        let result = dispatcher.dispatch_memory(false, 0x67, &mut cpu, &mut _bus);
        assert!(result.is_some(), "HSetRBit should be handled");
        assert!(result.unwrap().is_ok(), "HSetRBit should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "HSetRBit should return nilHandleErr for a NIL handle"
        );
    }

    #[test]
    fn hclrrbit_clears_resource_flag_for_valid_handle() {
        // Inside Macintosh: Memory (1992), pp. 2-50 to 2-51:
        // HClrRBit clears a handle's resource flag and returns noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let data_ptr = bus.alloc(16);
        let handle = bus.alloc(4);
        bus.write_long(handle, data_ptr);
        dispatcher.handle_state_bits.insert(handle, 0x20);
        let sp_before = cpu.read_reg(Register::A7);

        cpu.write_reg(Register::A0, handle);
        let result = dispatcher.dispatch_memory(false, 0x68, &mut cpu, &mut bus);
        assert!(result.is_some(), "HClrRBit should be handled");
        assert!(result.unwrap().is_ok(), "HClrRBit should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HClrRBit should return noErr for a valid handle"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "HClrRBit uses register calling convention and should preserve A7"
        );
        assert_eq!(
            dispatcher
                .handle_state_bits
                .get(&handle)
                .copied()
                .unwrap_or(0)
                & 0x20,
            0,
            "HClrRBit should clear the resource bit in tracked handle state"
        );
    }

    #[test]
    fn hclrrbit_nil_handle_returns_nilhandleerr_in_d0() {
        // Inside Macintosh: Memory (1992), pp. 2-50 to 2-51:
        // nilHandleErr (-109) is returned for a NIL master pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0);

        let result = dispatcher.dispatch_memory(false, 0x68, &mut cpu, &mut bus);
        assert!(result.is_some(), "HClrRBit should be handled");
        assert!(result.unwrap().is_ok(), "HClrRBit should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "HClrRBit should return nilHandleErr for a NIL handle"
        );
    }

    #[test]
    fn hsetrbit_then_hgetstate_round_trips_resource_bit() {
        // Pins the documented HSetRBit ↔ HGetState round-trip contract
        // witnessed by a067_a068_hresource_bit_strict
        // (BasiliskII System 7.5.3 ROM). Per IM:Memory 1992 p. 2-43, callers
        // observe handle state ONLY through HGetState ($A069); the master
        // pointer flag byte is not portable across 24/32-bit modes. This
        // test exercises that documented API: after HSetRBit on a freshly
        // allocated handle (whose pre-state is 0x00 per IM:Memory 1992
        // p. 2-27), HGetState must return the byte with bit 5 (0x20) set.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let data_ptr = bus.alloc(16);
        let handle = bus.alloc(4);
        bus.write_long(handle, data_ptr);

        // Pre: HGetState reports clear state.
        cpu.write_reg(Register::A0, handle);
        let pre = dispatcher.dispatch_memory(false, 0x69, &mut cpu, &mut bus);
        assert!(pre.is_some() && pre.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0) & 0x20,
            0,
            "fresh NewHandle should leave the resource bit clear per IM:Memory 1992 p. 2-27"
        );

        // HSetRBit on the handle.
        cpu.write_reg(Register::A0, handle);
        let set = dispatcher.dispatch_memory(false, 0x67, &mut cpu, &mut bus);
        assert!(set.is_some() && set.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HSetRBit on a valid handle should return noErr"
        );

        // Post: HGetState reports the resource bit set.
        cpu.write_reg(Register::A0, handle);
        let post = dispatcher.dispatch_memory(false, 0x69, &mut cpu, &mut bus);
        assert!(post.is_some() && post.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0) & 0x20,
            0x20,
            "HGetState should report the resource bit set after HSetRBit"
        );
    }

    #[test]
    fn hclrrbit_after_hsetrbit_round_trips_resource_bit_to_zero() {
        // Symmetric counterpart to hsetrbit_then_hgetstate_round_trips_resource_bit:
        // pins the HClrRBit ↔ HGetState round-trip from the same fixture
        // (a067_a068_hresource_bit_strict). After HSetRBit then HClrRBit
        // on the same handle, HGetState must report the resource bit
        // cleared (0x00) — per IM:Memory 1992 p. 2-50 "HClrRBit clears
        // the resource flag of a relocatable block."
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let data_ptr = bus.alloc(16);
        let handle = bus.alloc(4);
        bus.write_long(handle, data_ptr);

        cpu.write_reg(Register::A0, handle);
        let set = dispatcher.dispatch_memory(false, 0x67, &mut cpu, &mut bus);
        assert!(set.is_some() && set.unwrap().is_ok());

        cpu.write_reg(Register::A0, handle);
        let mid = dispatcher.dispatch_memory(false, 0x69, &mut cpu, &mut bus);
        assert!(mid.is_some() && mid.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0) & 0x20,
            0x20,
            "precondition: HSetRBit should leave the resource bit set"
        );

        cpu.write_reg(Register::A0, handle);
        let clear = dispatcher.dispatch_memory(false, 0x68, &mut cpu, &mut bus);
        assert!(clear.is_some() && clear.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HClrRBit on a valid handle should return noErr"
        );

        cpu.write_reg(Register::A0, handle);
        let post = dispatcher.dispatch_memory(false, 0x69, &mut cpu, &mut bus);
        assert!(post.is_some() && post.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0) & 0x20,
            0,
            "HGetState should report the resource bit clear after HClrRBit"
        );
    }

    #[test]
    fn setdatetime_updates_time_global_from_d0_seconds_argument() {
        // Inside Macintosh Volume II (1985), pp. II-378 to II-379:
        // _SetDateTime takes secs in D0 and updates the Time global.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let secs = 0x1234_5678u32;
        bus.write_long(0x020C, 0xDEAD_BEEF);
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::D0, secs);

        let result = dispatcher.dispatch_memory(false, 0x3A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetDateTime should be handled");
        assert!(result.unwrap().is_ok(), "SetDateTime should return cleanly");
        assert_eq!(
            bus.read_long(0x020C),
            secs,
            "SetDateTime should copy D0 seconds into low-memory Time ($020C)"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SetDateTime should use register calling convention and preserve A7"
        );
    }

    #[test]
    fn setdatetime_returns_noerr_result_code_in_d0_for_nominal_call() {
        // Inside Macintosh Volume II (1985), p. II-391 register summary:
        // _SetDateTime returns result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0x0102_0304);

        let result = dispatcher.dispatch_memory(false, 0x3A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetDateTime should be handled");
        assert!(result.unwrap().is_ok(), "SetDateTime should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetDateTime nominal path should return noErr in D0"
        );
    }

    #[test]
    fn setdatetime_returns_noerr_regardless_of_secs_input() {
        // Inside Macintosh Volume II (1985), pp. II-378..II-379 + II-391:
        // _SetDateTime takes D0=secs and returns D0=OSErr; both engines
        // return noErr on the nominal write path for any LongInt input.
        // Mirrors B1 of a03a_setdatetime_strict by sweeping multiple
        // secs values and checking the noErr return + A7 preservation.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let secs_inputs = [
            0u32, // 1904-01-01 epoch
            1,
            0x1234_5678,
            0x7FFF_FFFF, // max signed LongInt
            0xFFFF_FFFF, // sentinel high bits
        ];
        for &secs in &secs_inputs {
            let sp_before = cpu.read_reg(Register::A7);
            cpu.write_reg(Register::D0, secs);
            let result = dispatcher.dispatch_memory(false, 0x3A, &mut cpu, &mut bus);
            assert!(result.is_some(), "SetDateTime should be handled");
            assert!(result.unwrap().is_ok(), "SetDateTime should return cleanly");
            assert_eq!(
                cpu.read_reg(Register::D0) & 0xFF,
                0,
                "SetDateTime should return noErr lowbyte for secs=0x{:08X}",
                secs,
            );
            assert_eq!(
                cpu.read_reg(Register::A7),
                sp_before,
                "SetDateTime should preserve A7 (register-only ABI) for secs=0x{:08X}",
                secs,
            );
        }
    }

    #[test]
    fn writeparam_returns_noerr_in_d0_for_nominal_call() {
        // Inside Macintosh Volume II (1985), pp. II-381 to II-382 and p. II-391:
        // _WriteParam returns result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0x01F8); // SysParam
        cpu.write_reg(Register::D0, 0xFFFF_FFFF); // MinusOne

        let result = dispatcher.dispatch_memory(false, 0x38, &mut cpu, &mut bus);
        assert!(result.is_some(), "WriteParam should be handled");
        assert!(result.unwrap().is_ok(), "WriteParam should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "WriteParam nominal path should return noErr in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "WriteParam should use register calling convention and preserve A7"
        );
    }

    #[test]
    fn writeparam_does_not_modify_low_memory_sysparam_copy() {
        // Inside Macintosh Volume II (1985), pp. II-381 to II-382:
        // WriteParam writes the existing low-memory SysParam copy to parameter RAM.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sys_param = 0x01F8u32;
        let mut before = [0u8; 20];
        for (i, slot) in before.iter_mut().enumerate() {
            let value = (i as u8).wrapping_mul(7).wrapping_add(3);
            bus.write_byte(sys_param + i as u32, value);
            *slot = value;
        }
        cpu.write_reg(Register::A0, sys_param);
        cpu.write_reg(Register::D0, 0xFFFF_FFFF);

        let result = dispatcher.dispatch_memory(false, 0x38, &mut cpu, &mut bus);
        assert!(result.is_some(), "WriteParam should be handled");
        assert!(result.unwrap().is_ok(), "WriteParam should return cleanly");
        for (i, expected) in before.iter().enumerate() {
            assert_eq!(
                bus.read_byte(sys_param + i as u32),
                *expected,
                "WriteParam should preserve low-memory SysParam byte {}",
                i
            );
        }
    }

    #[test]
    fn writeparam_five_call_composition_preserves_stack_across_varying_minusone_register_state() {
        // Mirrors band B0 composite of the strict bake
        // a038_writeparam_strict: 5 successive _WriteParam
        // dispatches inside one A7-snapshot sandwich with varying D0 entry
        // values (always logical "MinusOne" but seeded with varying high-byte
        // stale state to stress D0 input handling). Per IM:II II-381 +
        // IM:OSUtils 1994 p. 7-13 the OS-bit FUNCTION consumes no Pascal
        // stack arguments; A7 is unchanged across every call.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sys_param = 0x01F8u32;
        let sentinel = 0xBADC_0DE0u32;
        bus.write_long(sys_param + 16, sentinel); // SP+16 sentinel within SysParam record

        let a7_pre = cpu.read_reg(Register::A7);
        let d0_inputs = [
            0xFFFF_FFFFu32,
            0xFFFF_FFFEu32,
            0xFFFF_0000u32,
            0xFFFF_FFFFu32,
            0xFFFF_FF00u32,
        ];
        for d0_in in d0_inputs.iter().copied() {
            cpu.write_reg(Register::A0, sys_param);
            cpu.write_reg(Register::D0, d0_in);
            let result = dispatcher.dispatch_memory(false, 0x38, &mut cpu, &mut bus);
            assert!(result.is_some(), "WriteParam should be handled");
            assert!(result.unwrap().is_ok(), "WriteParam should return cleanly");
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "WriteParam nominal path should return noErr in D0 across varying MinusOne high-byte state"
            );
        }
        assert_eq!(
            cpu.read_reg(Register::A7),
            a7_pre,
            "Five WriteParam calls must net zero A7 delta (register-only OS-bit ABI)"
        );
        assert_eq!(
            bus.read_long(sys_param + 16),
            sentinel,
            "SysParam sentinel preserved across all five WriteParam calls"
        );
    }

    #[test]
    fn initutil_returns_noerr_in_d0_for_nominal_call() {
        // Inside Macintosh Volume II (1985), pp. II-380 to II-381 and p. II-391:
        // _InitUtil exits with result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::D0, 0xFFFF_FFFF);

        let result = dispatcher.dispatch_memory(false, 0x3F, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitUtil should be handled");
        assert!(result.unwrap().is_ok(), "InitUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "InitUtil nominal path should return noErr in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InitUtil takes no stack arguments and should preserve A7"
        );
    }

    #[test]
    fn initutil_sets_spvalid_byte_to_a8_on_success() {
        // Inside Macintosh Volume II (1985), pp. II-380 to II-381:
        // InitUtil initializes low-memory parameter RAM state from the clock chip.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        bus.write_byte(0x01F8, 0x00);

        let result = dispatcher.dispatch_memory(false, 0x3F, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitUtil should be handled");
        assert!(result.unwrap().is_ok(), "InitUtil should return cleanly");
        assert_eq!(
            bus.read_byte(0x01F8),
            0xA8,
            "InitUtil nominal path should mark SPValid ($01F8) as valid ($A8)"
        );
    }

    #[test]
    fn initutil_rewrites_spvalid_when_pre_poisoned_to_invalid() {
        // Mirrors band B2 of the strict bake
        // a03f_initutil_strict: pre-poisons SPValid
        // ($01F8) with $5A (canonical "invalid" per IM:II II-380 — any
        // byte other than $A8 means parameter RAM has not been validated
        // since the last reset), dispatches _InitUtil, and verifies that
        // (a) D0 returns noErr (0), (b) SPValid was overwritten to $A8.
        // Pinning the rewrite-from-invalid path defeats no-op stubs that
        // would leave SPValid at its incoming value.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_byte(0x01F8, 0x5A);
        cpu.write_reg(Register::D0, 0xDEAD_BEEF);

        let result = dispatcher.dispatch_memory(false, 0x3F, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitUtil should be handled");
        assert!(result.unwrap().is_ok(), "InitUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) & 0xFF,
            0,
            "InitUtil must return noErr (0) in D0 lowbyte after rewriting invalid SPValid"
        );
        assert_eq!(
            bus.read_byte(0x01F8),
            0xA8,
            "InitUtil must overwrite a pre-poisoned $5A SPValid with $A8 (valid stamp)"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InitUtil takes no stack arguments and must preserve A7"
        );
    }

    #[test]
    fn initutil_register_only_calling_convention_preserves_stack_pointer() {
        // Mirrors band B3 of the strict bake: repeated register-only
        // calls should not consume a stack frame or move A7.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);

        for _ in 0..5 {
            let result = dispatcher.dispatch_memory(false, 0x3F, &mut cpu, &mut bus);
            assert!(result.is_some(), "InitUtil should be handled");
            assert!(result.unwrap().is_ok(), "InitUtil should return cleanly");
            assert_eq!(
                cpu.read_reg(Register::D0) & 0xFF,
                0,
                "InitUtil should return noErr in D0 lowbyte on each call"
            );
            assert_eq!(
                cpu.read_reg(Register::A7),
                sp_before,
                "InitUtil must preserve A7 across repeated register-only calls"
            );
        }
    }

    #[test]
    fn initzone_uses_a0_parameter_block_and_returns_noerr_in_d0() {
        // Inside Macintosh: Memory (1992), pp. 2-86 to 2-87:
        // InitZone takes a parameter-block pointer in A0 and returns
        // the result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let param_block = bus.alloc(14);
        bus.write_long(param_block, 0x0030_0000); // startPtr
        bus.write_long(param_block + 4, 0x0038_0000); // limitPtr
        bus.write_word(param_block + 8, 4); // cMoreMasters
        bus.write_long(param_block + 10, 0); // pGrowZone
        cpu.write_reg(Register::A0, param_block);
        cpu.write_reg(Register::D0, 0xFACE_B00C);

        let result = dispatcher.dispatch_memory(false, 0x19, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitZone should be handled");
        assert!(result.unwrap().is_ok(), "InitZone should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "InitZone nominal path should return noErr in D0"
        );
    }

    #[test]
    fn initzone_uses_register_calling_convention_without_stack_arguments() {
        // Inside Macintosh: Memory (1992), pp. 2-86 to 2-87:
        // InitZone uses A0 for its parameter block and does not document
        // a Pascal stack argument frame.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let param_block = bus.alloc(14);
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, param_block);

        let result = dispatcher.dispatch_memory(false, 0x19, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitZone should be handled");
        assert!(result.unwrap().is_ok(), "InitZone should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InitZone should preserve A7 in its register calling convention"
        );
    }

    #[test]
    fn initzone_initializes_zone_header_and_makes_startptr_current_zone() {
        // Inside Macintosh Volume II (1985), p. II-29:
        // InitZone creates a heap zone at startPtr..limitPtr, initializes
        // its visible header fields, and makes startPtr the current zone.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let param_block = bus.alloc(14);
        let start = 0x0030_0000;
        let limit = 0x0030_0400;
        let more_masters: u16 = 4;
        let grow_zone = 0x0012_3456;
        bus.write_long(param_block, start);
        bus.write_long(param_block + 4, limit);
        bus.write_word(param_block + 8, more_masters);
        bus.write_long(param_block + 10, grow_zone);
        bus.write_long(0x0118, 0x00AA_BBCC);
        cpu.write_reg(Register::A0, param_block);

        let result = dispatcher.dispatch_memory(false, 0x19, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitZone should be handled");
        assert!(result.unwrap().is_ok(), "InitZone should return cleanly");
        assert_eq!(bus.read_long(start), limit, "bkLim should equal limitPtr");
        assert_eq!(
            bus.read_long(start + 12),
            limit - start - (72 + (4 * more_masters as u32)),
            "zcbFree should match the documented initial free-byte formula"
        );
        assert_eq!(
            bus.read_long(start + 16),
            grow_zone,
            "gzProc should reflect pGrowZone from the parameter block"
        );
        assert_eq!(
            bus.read_word(start + 20),
            more_masters,
            "moreMast should reflect cMoreMasters from the parameter block"
        );
        assert_eq!(
            bus.read_long(0x0118),
            start,
            "InitZone should make startPtr the current zone via TheZone"
        );
    }

    #[test]
    fn initapplzone_returns_noerr_result_code_in_d0() {
        // Inside Macintosh: Memory (1992), pp. 2-87 to 2-88:
        // InitApplZone returns a result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0xDEAD_BEEF);

        let result = dispatcher.dispatch_memory(false, 0x2C, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitApplZone should be handled");
        assert!(
            result.unwrap().is_ok(),
            "InitApplZone should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "InitApplZone nominal path should return noErr in D0"
        );
    }

    #[test]
    fn initapplzone_takes_no_arguments_and_preserves_stack_pointer() {
        // Inside Macintosh Volume II (1985), p. II-28:
        // InitApplZone is a no-argument procedure with D0 result code.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);

        let result = dispatcher.dispatch_memory(false, 0x2C, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitApplZone should be handled");
        assert!(
            result.unwrap().is_ok(),
            "InitApplZone should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InitApplZone should preserve A7"
        );
    }

    #[test]
    fn initapplzone_reinitializes_application_zone_and_makes_it_current() {
        // Inside Macintosh Volume II (1985), p. II-28:
        // InitApplZone initializes the application heap zone, clears its
        // grow-zone function, and makes ApplZone the current zone.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let appl_zone = 0x0020_0000;
        let appl_limit = 0x0028_0000;
        bus.write_long(0x02AA, appl_zone); // ApplZone
        bus.write_long(0x0130, appl_limit); // ApplLimit
        bus.write_long(0x0118, 0x00AA_BBCC); // TheZone
        bus.write_long(appl_zone + 16, 0xDEAD_BEEF); // gzProc

        let result = dispatcher.dispatch_memory(false, 0x2C, &mut cpu, &mut bus);
        assert!(result.is_some(), "InitApplZone should be handled");
        assert!(
            result.unwrap().is_ok(),
            "InitApplZone should return cleanly"
        );
        assert_eq!(
            bus.read_long(0x0118),
            appl_zone,
            "InitApplZone should make ApplZone the current zone"
        );
        assert_eq!(
            bus.read_long(appl_zone + 16),
            0,
            "InitApplZone should clear the application zone grow-zone pointer"
        );
        assert_eq!(
            bus.read_word(appl_zone + 20),
            64,
            "InitApplZone should restore the application zone moreMast increment"
        );
    }

    #[test]
    fn setapplbase_uses_a0_startptr_and_returns_noerr_in_d0() {
        // Inside Macintosh: Memory (1992), pp. 2-88 to 2-89:
        // SetApplBase takes startPtr in A0 and returns result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x0040_0000);
        cpu.write_reg(Register::D0, 0x1234_5678);

        let result = dispatcher.dispatch_memory(false, 0x57, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetApplBase should be handled");
        assert!(result.unwrap().is_ok(), "SetApplBase should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetApplBase nominal path should return noErr in D0"
        );
    }

    #[test]
    fn setapplbase_uses_register_calling_convention_without_stack_arguments() {
        // Inside Macintosh Volume II (1985), p. II-32 summary:
        // SetApplBase receives startPtr in A0 and should not pop stack args.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0x0040_0000);

        let result = dispatcher.dispatch_memory(false, 0x57, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetApplBase should be handled");
        assert!(result.unwrap().is_ok(), "SetApplBase should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SetApplBase should preserve A7"
        );
    }

    #[test]
    fn setapplbase_returns_noerr_regardless_of_startptr_value() {
        // Inside Macintosh Volume II (1985), pp. II-28 to II-29:
        // SetApplBase returns noErr on the nominal path. Systemless HLE
        // does not model a relocatable application zone, so the trap
        // is a no-op that writes D0 = noErr regardless of startPtr.
        // This mirrors B1 of the a057_setapplbase_strict bake, which
        // dispatches the trap with startPtr echoing the current
        // ApplZone low-memory pointer, but verifies that any other
        // startPtr value (NIL, sentinel, or arbitrary address) also
        // produces D0 = 0 in the HLE.
        let cases: [u32; 5] = [
            0x0000_0000, // NIL — "use default" per IM:II II-28
            0x0040_0000, // arbitrary 4MB address (matches the existing test)
            0xDEAD_BEEF, // sentinel (untouched by HLE)
            0x0000_0001, // tiny pointer
            0x7FFF_FFFE, // near-max signed pointer
        ];
        for (i, startptr) in cases.iter().enumerate() {
            let (mut dispatcher, mut cpu, mut bus) = setup();
            let sp_before = cpu.read_reg(Register::A7);
            cpu.write_reg(Register::A0, *startptr);
            cpu.write_reg(Register::D0, 0xCAFE_BABE);

            let result = dispatcher.dispatch_memory(false, 0x57, &mut cpu, &mut bus);
            assert!(result.is_some(), "SetApplBase[{i}] should be handled");
            assert!(
                result.unwrap().is_ok(),
                "SetApplBase[{i}] should return cleanly"
            );
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "SetApplBase[{i}] (startPtr=0x{startptr:08X}) should return noErr in D0"
            );
            assert_eq!(
                cpu.read_reg(Register::A7),
                sp_before,
                "SetApplBase[{i}] should preserve A7"
            );
        }
    }

    #[test]
    fn translate24to32_preserves_full_input_in_32bit_mode() {
        // BasiliskII System 7.5.3's default 32-bit-addressing path
        // returns the full input unchanged for tagged values.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0xAB12_3456);

        let result = dispatcher.dispatch_memory(false, 0x91, &mut cpu, &mut bus);
        assert!(result.is_some(), "Translate24To32 should be handled");
        assert!(
            result.unwrap().is_ok(),
            "Translate24To32 should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0xAB12_3456,
            "Translate24To32 should preserve the full tagged input in 32-bit mode"
        );
    }

    #[test]
    fn translate24to32_uses_d0_register_calling_convention_and_preserves_a7() {
        // Inside Macintosh: Memory (1992), p. 4-28:
        // Translate24To32 takes input in D0 and returns output in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::D0, 0x0012_3456);

        let result = dispatcher.dispatch_memory(false, 0x91, &mut cpu, &mut bus);
        assert!(result.is_some(), "Translate24To32 should be handled");
        assert!(
            result.unwrap().is_ok(),
            "Translate24To32 should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0x0012_3456,
            "Translate24To32 should return the same value for a 32-bit-clean address"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "Translate24To32 should preserve A7 in register calling convention"
        );
    }

    #[test]
    fn vinstall_consumes_a0_taskptr_and_returns_oserr_in_d0() {
        // Inside Macintosh: Processes (1994), pp. 4-24 to 4-25:
        // VInstall takes task pointer in A0 and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_long(task_ptr, 0xDEAD_BEEF);
        bus.write_word(task_ptr + 4, 1);
        bus.write_long(task_ptr + 6, 0x1234_5678);
        bus.write_word(task_ptr + 10, 2);
        bus.write_word(task_ptr + 12, 1);
        cpu.write_reg(Register::A0, task_ptr);

        let result = dispatcher.dispatch_memory(false, 0x33, &mut cpu, &mut bus);
        assert!(result.is_some(), "VInstall should be handled");
        assert!(result.unwrap().is_ok(), "VInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "VInstall should return noErr"
        );
        assert_eq!(
            bus.read_long(task_ptr),
            0,
            "single-task queue link should terminate at NIL"
        );
    }

    #[test]
    fn vinstall_invalid_qtype_returns_vtyperr() {
        // Inside Macintosh: Processes (1994), p. 4-25:
        // VInstall returns vTypErr (-2) for invalid qType.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 0);
        cpu.write_reg(Register::A0, task_ptr);

        let result = dispatcher.dispatch_memory(false, 0x33, &mut cpu, &mut bus);
        assert!(result.is_some(), "VInstall should be handled");
        assert!(result.unwrap().is_ok(), "VInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -2,
            "VInstall should return vTypErr for invalid qType"
        );
    }

    #[test]
    fn vremove_consumes_a0_taskptr_and_returns_oserr_in_d0() {
        // Inside Macintosh: Processes (1994), pp. 4-25 to 4-26:
        // VRemove takes task pointer in A0 and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        bus.write_long(task_ptr + 6, 0x1234_5678);
        bus.write_word(task_ptr + 10, 2);
        bus.write_word(task_ptr + 12, 1);

        cpu.write_reg(Register::A0, task_ptr);
        let install = dispatcher.dispatch_memory(false, 0x33, &mut cpu, &mut bus);
        assert!(install.is_some());
        assert!(install.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::D0), 0);

        cpu.write_reg(Register::A0, task_ptr);
        let remove = dispatcher.dispatch_memory(false, 0x34, &mut cpu, &mut bus);
        assert!(remove.is_some(), "VRemove should be handled");
        assert!(remove.unwrap().is_ok(), "VRemove should return cleanly");
        assert_eq!(cpu.read_reg(Register::D0), 0, "VRemove should return noErr");
        assert_eq!(
            bus.read_long(task_ptr),
            0,
            "removed task should have qLink reset to NIL"
        );
    }

    #[test]
    fn vremove_task_not_in_queue_returns_qerr() {
        // Inside Macintosh: Processes (1994), p. 4-26:
        // VRemove returns qErr (-1) when the task isn't in the queue.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        cpu.write_reg(Register::A0, task_ptr);

        let result = dispatcher.dispatch_memory(false, 0x34, &mut cpu, &mut bus);
        assert!(result.is_some(), "VRemove should be handled");
        assert!(result.unwrap().is_ok(), "VRemove should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -1,
            "VRemove should return qErr for non-queued task"
        );
    }

    #[test]
    fn vinstall_then_vremove_roundtrip_returns_noerr_on_both_and_qerr_on_second_remove() {
        // Mirrors B1+B2+B4 of the a033_a034_vinstall_vremove_strict bake:
        // VInstall(valid) → noErr; immediate VRemove → noErr; second VRemove
        // of the same now-empty slot → qErr. Per IM:Processes 1994 p. 4-26
        // a second remove of an already-removed task hits the queue-not-found
        // path and returns qErr=-1.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        bus.write_long(task_ptr + 6, 0x0040_1000);
        bus.write_word(task_ptr + 10, 0x7FFF);
        bus.write_word(task_ptr + 12, 0);

        cpu.write_reg(Register::A0, task_ptr);
        let install = dispatcher.dispatch_memory(false, 0x33, &mut cpu, &mut bus);
        assert!(install.is_some());
        assert!(install.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "VInstall should return noErr"
        );

        cpu.write_reg(Register::A0, task_ptr);
        let remove1 = dispatcher.dispatch_memory(false, 0x34, &mut cpu, &mut bus);
        assert!(remove1.is_some());
        assert!(remove1.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "first VRemove should return noErr"
        );

        cpu.write_reg(Register::A0, task_ptr);
        let remove2 = dispatcher.dispatch_memory(false, 0x34, &mut cpu, &mut bus);
        assert!(remove2.is_some());
        assert!(remove2.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -1,
            "second VRemove should return qErr (task no longer in queue)"
        );
    }

    #[test]
    fn slotvinstall_consumes_a0_taskptr_d0_slot_and_returns_oserr_in_d0() {
        // Inside Macintosh: Processes (1994), pp. 4-22 to 4-23:
        // SlotVInstall takes task pointer in A0, slot in D0, and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        bus.write_long(task_ptr + 6, 0x1234_5678);
        bus.write_word(task_ptr + 10, 2);
        bus.write_word(task_ptr + 12, 1);
        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, 3);

        let result = dispatcher.dispatch_memory(false, 0x6F, &mut cpu, &mut bus);
        assert!(result.is_some(), "SlotVInstall should be handled");
        assert!(
            result.unwrap().is_ok(),
            "SlotVInstall should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SlotVInstall should return noErr"
        );
        assert_eq!(
            bus.read_long(task_ptr),
            0,
            "single-task queue link should terminate at NIL"
        );
    }

    #[test]
    fn slotvinstall_negative_one_slot_returns_noerr() {
        // Inside Macintosh: Processes (1994), p. 4-23:
        // BasiliskII accepts slot = -1 for SlotVInstall and returns noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, (-1i16) as u16 as u32);

        let result = dispatcher.dispatch_memory(false, 0x6F, &mut cpu, &mut bus);
        assert!(result.is_some(), "SlotVInstall should be handled");
        assert!(
            result.unwrap().is_ok(),
            "SlotVInstall should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SlotVInstall should return noErr for slot = -1"
        );
        assert_eq!(
            bus.read_long(task_ptr),
            0,
            "SlotVInstall should still install the task record"
        );
    }

    #[test]
    fn slotvremove_consumes_a0_taskptr_d0_slot_and_returns_oserr_in_d0() {
        // Inside Macintosh: Processes (1994), pp. 4-23 to 4-24:
        // SlotVRemove takes task pointer in A0, slot in D0, and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        bus.write_long(task_ptr + 6, 0x1234_5678);
        bus.write_word(task_ptr + 10, 2);
        bus.write_word(task_ptr + 12, 1);

        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, 2);
        let install = dispatcher.dispatch_memory(false, 0x6F, &mut cpu, &mut bus);
        assert!(install.is_some());
        assert!(install.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::D0), 0);

        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, 2);
        let remove = dispatcher.dispatch_memory(false, 0x70, &mut cpu, &mut bus);
        assert!(remove.is_some(), "SlotVRemove should be handled");
        assert!(remove.unwrap().is_ok(), "SlotVRemove should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SlotVRemove should return noErr"
        );
    }

    #[test]
    fn slotvremove_task_not_in_queue_returns_qerr() {
        // Inside Macintosh: Processes (1994), p. 4-24:
        // SlotVRemove returns qErr (-1) when the task isn't in the queue.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = bus.alloc(14);
        bus.write_word(task_ptr + 4, 1);
        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, 4);

        let result = dispatcher.dispatch_memory(false, 0x70, &mut cpu, &mut bus);
        assert!(result.is_some(), "SlotVRemove should be handled");
        assert!(result.unwrap().is_ok(), "SlotVRemove should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -1,
            "SlotVRemove should return qErr for non-queued task"
        );
    }

    #[test]
    fn test_hpurge() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x49, &mut cpu, &mut bus);
        assert!(result.is_some(), "HPurge ($A049) should be handled");
        assert!(result.unwrap().is_ok(), "HPurge should succeed");
    }

    #[test]
    fn movehhi_unlocked_handle_returns_noerr_and_preserves_master_pointer() {
        // Inside Macintosh Volume II (1985), p. II-44: MoveHHi moves the
        // relocatable block toward the top of the current heap zone and
        // reports success as noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let data_ptr = bus.alloc(32);
        let handle = bus.alloc(4);
        bus.write_long(handle, data_ptr);
        cpu.write_reg(Register::A0, handle);

        let result = dispatcher.dispatch_memory(false, 0x64, &mut cpu, &mut bus);
        assert!(result.is_some(), "MoveHHi should be handled");
        assert!(result.unwrap().is_ok(), "MoveHHi should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "MoveHHi should return noErr");
        assert_eq!(
            bus.read_long(handle),
            data_ptr,
            "MoveHHi should keep the master pointer valid for the same handle"
        );
    }

    #[test]
    fn test_get_handle_size() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // First allocate a handle of size 256
        cpu.write_reg(Register::D0, 256);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        let handle = cpu.read_reg(Register::A0);
        // Now get its size
        cpu.write_reg(Register::A0, handle);
        let result = dispatcher.dispatch_memory(false, 0x25, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetHandleSize should be handled");
        assert!(result.unwrap().is_ok(), "GetHandleSize should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            256,
            "GetHandleSize should return 256 in D0"
        );
    }

    #[test]
    fn test_get_handle_size_updates_ccr_from_low_word_of_d0() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let ptr = bus.alloc(0x1_0000);
        let handle = bus.alloc(4);
        bus.write_long(handle, ptr);
        cpu.write_reg(Register::A0, handle);
        cpu.ccr = 0x10;

        let result = dispatcher.dispatch_memory(false, 0x25, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetHandleSize should be handled");
        assert!(result.unwrap().is_ok(), "GetHandleSize should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0x1_0000);
        assert_eq!(
            cpu.ccr, 0x14,
            "GetHandleSize should emulate trap-dispatcher TST.W D0 and preserve X"
        );
    }

    #[test]
    fn test_dispose_handle_sets_zero_flag_via_dispatcher_ccr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let ptr = bus.alloc(8);
        let handle = bus.alloc(4);
        bus.write_long(handle, ptr);
        cpu.write_reg(Register::A0, handle);
        cpu.ccr = 0x18;

        let result = dispatcher.dispatch_memory(false, 0x23, &mut cpu, &mut bus);
        assert!(result.is_some(), "DisposeHandle should be handled");
        assert!(result.unwrap().is_ok(), "DisposeHandle should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0);
        assert_eq!(
            cpu.ccr, 0x14,
            "DisposeHandle should emulate trap-dispatcher TST.W D0 and preserve X"
        );
    }

    #[test]
    fn test_flush_code_cache() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0xBD, &mut cpu, &mut bus);
        assert!(result.is_some(), "FlushCodeCache should be handled");
        assert!(
            result.unwrap().is_ok(),
            "FlushCodeCache should succeed (no-op)"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "FlushCodeCache should return noErr in D0"
        );
    }

    #[test]
    fn hwpriv_swapinstructioncache_selector_0000_returns_previous_state_boolean() {
        // Inside Macintosh: Memory (1992), p. 4-29:
        // SwapInstructionCache uses _HWPriv selector $0000 and returns
        // the previous instruction-cache state as a Boolean, while
        // installing the requested new state.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);
        cpu.write_reg(Register::A0, 0); // request FALSE
        cpu.write_reg(Register::D0, 0); // selector $0000

        let result = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(result.is_some(), "HWPriv should be handled");
        assert!(
            result.unwrap().is_ok(),
            "HWPriv selector $0000 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "SwapInstructionCache should return previous state Boolean (TRUE) in A0"
        );
        assert!(
            !dispatcher.instruction_cache_enabled,
            "SwapInstructionCache(FALSE) should install the requested disabled state"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_HWPriv selector calls use register ABI and should not pop stack arguments"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xDEAD_BEEF,
            "stack top should remain untouched for register-dispatched _HWPriv calls"
        );
    }

    #[test]
    fn hwpriv_swapinstructioncache_second_call_returns_false_after_prior_disable() {
        // The second SwapInstructionCache call should observe the state
        // installed by the first one.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0); // disable
        cpu.write_reg(Register::D0, 0);
        let first = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(
            first.is_some(),
            "first SwapInstructionCache should be handled"
        );
        assert!(
            first.unwrap().is_ok(),
            "first SwapInstructionCache should return"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "first SwapInstructionCache(FALSE) should report previous TRUE state in A0"
        );

        cpu.write_reg(Register::A0, 1); // re-enable
        cpu.write_reg(Register::D0, 0);
        let second = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(
            second.is_some(),
            "second SwapInstructionCache should be handled"
        );
        assert!(
            second.unwrap().is_ok(),
            "second SwapInstructionCache should return"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "second SwapInstructionCache(TRUE) should report prior FALSE state in A0"
        );
        assert!(
            dispatcher.instruction_cache_enabled,
            "second SwapInstructionCache(TRUE) should restore the enabled state"
        );
    }

    #[test]
    fn hwpriv_swapdatacache_selector_0002_returns_previous_state_boolean() {
        // Inside Macintosh: Memory (1992), p. 4-30:
        // SwapDataCache uses _HWPriv selector $0002 and returns
        // the previous data-cache state as a Boolean, while installing
        // the requested new state.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xCAFE_F00D);
        cpu.write_reg(Register::A0, 0); // request FALSE
        cpu.write_reg(Register::D0, 2); // selector $0002

        let result = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(result.is_some(), "HWPriv should be handled");
        assert!(
            result.unwrap().is_ok(),
            "HWPriv selector $0002 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "SwapDataCache should return previous state Boolean (TRUE) in A0"
        );
        assert!(
            !dispatcher.data_cache_enabled,
            "SwapDataCache(FALSE) should install the requested disabled state"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_HWPriv selector calls use register ABI and should not pop stack arguments"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xCAFE_F00D,
            "stack top should remain untouched for register-dispatched _HWPriv calls"
        );
    }

    #[test]
    fn hwpriv_swapdatacache_second_call_returns_false_after_prior_disable() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0); // disable
        cpu.write_reg(Register::D0, 2);
        let first = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(first.is_some(), "first SwapDataCache should be handled");
        assert!(first.unwrap().is_ok(), "first SwapDataCache should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "first SwapDataCache(FALSE) should report previous TRUE state in A0"
        );

        cpu.write_reg(Register::A0, 1); // re-enable
        cpu.write_reg(Register::D0, 2);
        let second = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(second.is_some(), "second SwapDataCache should be handled");
        assert!(
            second.unwrap().is_ok(),
            "second SwapDataCache should return"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "second SwapDataCache(TRUE) should report prior FALSE state in A0"
        );
        assert!(
            dispatcher.data_cache_enabled,
            "second SwapDataCache(TRUE) should restore the enabled state"
        );
    }

    #[test]
    fn hwpriv_flushcodecacherange_selector_0009_uses_a0_a1_and_returns_result_code() {
        // Inside Macintosh: Memory (1992), pp. 4-32 to 4-33:
        // FlushCodeCacheRange uses _HWPriv selector $0009 with
        // A0=address, A1=count, and returns result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xFACE_C0DE);
        cpu.write_reg(Register::A0, 0x0012_3400);
        cpu.write_reg(Register::A1, 0x0000_0400);
        cpu.write_reg(Register::D0, 9); // selector $0009

        let result = dispatcher.dispatch_memory(false, 0x98, &mut cpu, &mut bus);
        assert!(result.is_some(), "HWPriv should be handled");
        assert!(
            result.unwrap().is_ok(),
            "HWPriv selector $0009 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "FlushCodeCacheRange should return noErr in D0 on nominal HLE path"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x0012_3400,
            "FlushCodeCacheRange should read address from A0 without clobbering it"
        );
        assert_eq!(
            cpu.read_reg(Register::A1),
            0x0000_0400,
            "FlushCodeCacheRange should read byte count from A1 without clobbering it"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "FlushCodeCacheRange should not consume a Pascal stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xFACE_C0DE,
            "stack top should remain untouched by register ABI call"
        );
    }

    #[test]
    fn flushcodecache_is_parameterless_and_preserves_stack_pointer() {
        // Inside Macintosh: Memory (1992), p. 4-31:
        // FlushCodeCache is PROCEDURE FlushCodeCache; with no arguments.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xBEEF_1357);

        let result = dispatcher.dispatch_memory(false, 0xBD, &mut cpu, &mut bus);
        assert!(result.is_some(), "FlushCodeCache should be handled");
        assert!(
            result.unwrap().is_ok(),
            "FlushCodeCache should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "FlushCodeCache should not pop a stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xBEEF_1357,
            "FlushCodeCache should leave the caller stack untouched"
        );
    }

    #[test]
    fn test_get_trap_address() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0x0044);
        let result = dispatcher.dispatch_memory(false, 0x46, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetTrapAddress should be handled");
        assert!(result.unwrap().is_ok(), "GetTrapAddress should succeed");
        let addr = cpu.read_reg(Register::A0);
        assert_eq!(
            addr,
            0x00F00000 | 0x0044,
            "GetTrapAddress should return 0x00F00000 | trap_num in A0"
        );
    }

    #[test]
    fn test_get_trap_address_docking_dispatch_aliases_unimplemented_vector() {
        let (mut dispatcher, mut cpu, mut bus) = setup();

        cpu.write_reg(Register::D0, 0xAA57);
        let result = dispatcher.dispatch_memory(false, 0x46, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "GetTrapAddress should handle DockingDispatch"
        );
        assert!(result.unwrap().is_ok(), "GetTrapAddress should succeed");
        let docking_addr = cpu.read_reg(Register::A0);

        cpu.write_reg(Register::D0, 0xA89F);
        let result = dispatcher.dispatch_memory(false, 0x46, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "GetTrapAddress should handle Unimplemented"
        );
        assert!(result.unwrap().is_ok(), "GetTrapAddress should succeed");
        let unimplemented_addr = cpu.read_reg(Register::A0);

        assert_eq!(
            docking_addr, unimplemented_addr,
            "DockingDispatch should alias the _Unimplemented trampoline on the generic target"
        );
    }

    #[test]
    fn phantom_gettooltrapaddress_returns_native_table_entry_and_preserves_stack() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x1357_BEEF);
        dispatcher.native_trap_table.insert(0xA89F, 0x00F0_2468);

        cpu.write_reg(Register::D0, 0xA89F);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "phantom GetToolTrapAddress should be handled"
        );
        assert!(
            result.unwrap().is_ok(),
            "phantom GetToolTrapAddress should succeed"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x00F0_2468,
            "native trap-table entries should take precedence"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "phantom GetToolTrapAddress should preserve A7"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x1357_BEEF,
            "phantom GetToolTrapAddress should leave caller stack memory untouched"
        );
    }

    #[test]
    fn test_get_tool_trap_address_docking_dispatch_aliases_unimplemented_probe() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x0BAD_F00D);

        cpu.write_reg(Register::D0, 0x257);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "GetToolTrapAddress should handle DockingDispatch"
        );
        assert!(
            result.unwrap().is_ok(),
            "GetToolTrapAddress should succeed"
        );
        let docking_addr = cpu.read_reg(Register::A0);

        cpu.write_reg(Register::D0, 0x09F);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "GetToolTrapAddress should handle Unimplemented"
        );
        assert!(result.unwrap().is_ok(), "GetToolTrapAddress should succeed");
        let unimplemented_addr = cpu.read_reg(Register::A0);

        assert_eq!(
            docking_addr, unimplemented_addr,
            "DockingDispatch should alias the _Unimplemented probe sentinel on the generic target"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "phantom GetToolTrapAddress should preserve A7"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x0BAD_F00D,
            "phantom GetToolTrapAddress should leave caller stack memory untouched"
        );
    }

    #[test]
    fn phantom_gettooltrapaddress_creates_stable_trampoline_for_tool_trap_word() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xCAFE_BABE);

        cpu.write_reg(Register::D0, 0xA89F);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "phantom GetToolTrapAddress should handle tool-trap words"
        );
        assert!(
            result.unwrap().is_ok(),
            "phantom GetToolTrapAddress should succeed"
        );
        let first_addr = cpu.read_reg(Register::A0);
        assert_ne!(first_addr, 0, "tool-trap trampoline address should be nonzero");

        cpu.write_reg(Register::D0, 0xA89F);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "phantom GetToolTrapAddress should handle repeated tool-trap words"
        );
        assert!(
            result.unwrap().is_ok(),
            "phantom GetToolTrapAddress should succeed on repeated lookup"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            first_addr,
            "tool-trap trampoline lookup should be stable"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "phantom GetToolTrapAddress should preserve A7"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xCAFE_BABE,
            "phantom GetToolTrapAddress should leave caller stack memory untouched"
        );
    }

    #[test]
    fn test_block_move() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x300000u32;
        let dst = 0x310000u32;
        let data: [u8; 8] = [0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE];
        for (i, &b) in data.iter().enumerate() {
            bus.write_byte(src + i as u32, b);
        }
        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, dst);
        cpu.write_reg(Register::D0, data.len() as u32);
        let result = dispatcher.dispatch_memory(false, 0x2E, &mut cpu, &mut bus);
        assert!(result.is_some(), "BlockMove should be handled");
        assert!(result.unwrap().is_ok(), "BlockMove should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "BlockMove should set D0 to 0"
        );
        for (i, &b) in data.iter().enumerate() {
            assert_eq!(
                bus.read_byte(dst + i as u32),
                b,
                "BlockMove should copy byte {} correctly (expected 0x{:02X})",
                i,
                b
            );
        }
    }

    #[test]
    fn test_block_move_overlapping_ranges() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let base = 0x300000u32;
        let data: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
        for (i, &b) in data.iter().enumerate() {
            bus.write_byte(base + i as u32, b);
        }

        cpu.write_reg(Register::A0, base);
        cpu.write_reg(Register::A1, base + 2);
        cpu.write_reg(Register::D0, 6);

        let result = dispatcher.dispatch_memory(false, 0x2E, &mut cpu, &mut bus);
        assert!(result.is_some(), "BlockMove should be handled");
        assert!(result.unwrap().is_ok(), "BlockMove should succeed");

        let expected: [u8; 8] = [0, 1, 0, 1, 2, 3, 4, 5];
        for (i, &b) in expected.iter().enumerate() {
            assert_eq!(
                bus.read_byte(base + i as u32),
                b,
                "BlockMove should behave like memmove for overlapping ranges"
            );
        }
    }

    #[test]
    fn test_set_trap_address() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // Set a native trap handler
        cpu.write_reg(Register::D0, 0x01FF);
        cpu.write_reg(Register::A0, 0x00400000); // handler address
        let result = dispatcher.dispatch_memory(false, 0x47, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetTrapAddress should be handled");
        assert!(result.unwrap().is_ok(), "SetTrapAddress should succeed");
        // Now GetTrapAddress should return the installed handler
        cpu.write_reg(Register::D0, 0x01FF);
        let result = dispatcher.dispatch_memory(false, 0x46, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x00400000,
            "GetTrapAddress should return the handler set by SetTrapAddress"
        );
    }

    #[test]
    fn test_strip_address() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0x55, &mut cpu, &mut bus);
        assert!(result.is_some(), "StripAddress should be handled");
        assert!(
            result.unwrap().is_ok(),
            "StripAddress should succeed (no-op)"
        );
    }

    #[test]
    fn test_purge_space() {
        // PurgeSpace returns the free_heap_estimate value (clamped
        // to [24MB, 64MB]) in BOTH A0 and D0. With dispatcher-
        // default HEAP_END/APPL_LIMIT (typically uninitialized
        // = 0), the saturating_sub yields 0 → clamps up to the
        // 24MB floor. Pin both registers receive the same value
        // so the "no fragmentation, total == contiguous" HLE
        // invariant holds.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0x62, &mut cpu, &mut bus);
        assert!(result.is_some(), "PurgeSpace should be handled");
        assert!(result.unwrap().is_ok(), "PurgeSpace should succeed");
        let a0 = cpu.read_reg(Register::A0);
        let d0 = cpu.read_reg(Register::D0);
        assert_eq!(a0, 24 * 1024 * 1024,
            "PurgeSpace must return free_heap_estimate floor (24MB) in A0 with default low-mem state");
        assert_eq!(d0, 24 * 1024 * 1024,
            "PurgeSpace must return free_heap_estimate floor (24MB) in D0 with default low-mem state");
        assert_eq!(
            a0, d0,
            "PurgeSpace must return same value in A0 (total) and D0 (contiguous) — \
             no fragmentation in Systemless's flat allocator"
        );
    }

    #[test]
    fn test_sys_environs_0x90() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let buf = 0x300000u32;
        cpu.write_reg(Register::A0, buf);
        cpu.write_reg(Register::D0, 2); // version
        let result = dispatcher.dispatch_memory(false, 0x90, &mut cpu, &mut bus);
        assert!(result.is_some(), "SysEnvirons (0x90) should be handled");
        assert!(result.unwrap().is_ok(), "SysEnvirons (0x90) should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SysEnvirons should set D0 to 0 (noErr)"
        );
        assert_eq!(bus.read_word(buf), 2, "environsVersion should be 2");
        assert_eq!(
            bus.read_word(buf + 2),
            crate::machine_profile::ORACLE_MACHINE_PROFILE.gestalt_machine_type,
            "machineType should match the oracle machine profile"
        );
        assert_eq!(
            bus.read_word(buf + 4),
            crate::machine_profile::ORACLE_MACHINE_PROFILE.system_version_bcd,
            "systemVersion should match the oracle machine profile"
        );
        assert_eq!(bus.read_word(buf + 6), 5, "processor should be 5 (68040)");
        assert_eq!(
            bus.read_byte(buf + 8),
            1,
            "hasFPU should be 1 (68040 has integrated FPU)"
        );
        assert_eq!(bus.read_byte(buf + 9), 1, "hasColorQD should be 1");
    }

    #[test]
    fn test_flush_code_cache_0xbd() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0xBD, &mut cpu, &mut bus);
        assert!(result.is_some(), "FlushCodeCache ($A0BD) should be handled");
        assert!(
            result.unwrap().is_ok(),
            "FlushCodeCache should succeed (no-op)"
        );
    }

    #[test]
    fn internalwait_routes_gettimeout_and_settimeout_selector_paths() {
        // Inside Macintosh Volume V (1986), p. V-356 and
        // Inside Macintosh: Operating System Utilities (1994), p. 7-13:
        // GetTimeout/SetTimeout are selector-driven wrappers over _InternalWait.
        for selector in [0u16, 1u16] {
            let (mut dispatcher, mut cpu, mut bus) = setup();
            let sp_before = cpu.read_reg(Register::A7);
            bus.write_word(sp_before, selector);
            bus.write_long(sp_before + 4, 0xACED_C0DE);
            cpu.write_reg(Register::A0, selector as u32);

            let result = dispatcher.dispatch_memory(false, 0x7F, &mut cpu, &mut bus);
            assert!(result.is_some(), "InternalWait should be handled");
            assert!(
                result.unwrap().is_ok(),
                "InternalWait should return cleanly"
            );
            assert_eq!(
                cpu.read_reg(Register::A7),
                sp_before,
                "InternalWait no-op path should not pop selector bytes"
            );
            assert_eq!(
                bus.read_word(sp_before),
                selector,
                "InternalWait should leave caller-provided selector storage intact"
            );
        }
    }

    #[test]
    fn internalwait_stub_preserves_stack_pointer_in_noop_path() {
        // Inside Macintosh Volume V (1986), p. V-356:
        // Start Manager timeout entry points are wrappers over _InternalWait.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xC0DE_CAFE);
        cpu.write_reg(Register::A1, 0x00AB_CDEF);
        cpu.write_reg(Register::D1, 0x1357_9BDF);

        let result = dispatcher.dispatch_memory(false, 0x7F, &mut cpu, &mut bus);
        assert!(result.is_some(), "InternalWait should be handled");
        assert!(
            result.unwrap().is_ok(),
            "InternalWait should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InternalWait no-op path should preserve stack pointer"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xC0DE_CAFE,
            "InternalWait should not mutate caller stack contents"
        );
        assert_eq!(
            cpu.read_reg(Register::A1),
            0x00AB_CDEF,
            "InternalWait no-op path should preserve A1"
        );
        assert_eq!(
            cpu.read_reg(Register::D1),
            0x1357_9BDF,
            "InternalWait no-op path should preserve D1"
        );
    }

    #[test]
    fn internalwait_five_call_composition_preserves_stack_across_alternating_selectors() {
        // Mirrors B2 of a07f_internalwait_strict: five
        // successive _InternalWait dispatches with alternating A0 selectors
        // ($0000/$0001) and varying D0 count inputs (0/1/15/20/31) preserve
        // A7 in aggregate, with no per-call drift. Per IM:Operating_System_
        // Utils 1994 pp. 9-27 to 9-28 the trap consumes no Pascal stack
        // arguments regardless of selector or D0 input.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);

        let selectors: [u32; 5] = [0x0000, 0x0001, 0x0000, 0x0001, 0x0001];
        let counts: [u32; 5] = [0, 1, 15, 20, 31];
        for (selector, count) in selectors.iter().zip(counts.iter()) {
            cpu.write_reg(Register::A0, *selector);
            cpu.write_reg(Register::D0, *count);
            let result = dispatcher.dispatch_memory(false, 0x7F, &mut cpu, &mut bus);
            assert!(result.is_some(), "InternalWait should be handled");
            assert!(
                result.unwrap().is_ok(),
                "InternalWait should return cleanly"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "InternalWait five-call composition should preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xDEAD_BEEF,
            "InternalWait should not mutate caller stack contents across composition"
        );
    }

    #[test]
    fn dtinstall_uses_a0_dttaskptr_register_calling_convention() {
        // Inside Macintosh Volume V (1986), p. V-467 and
        // Inside Macintosh: Processes (1994), pp. 6-12 to 6-13:
        // _DTInstall uses A0 for dtTaskPtr and D0 for result.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let dt_task_ptr = bus.alloc(24);
        bus.write_long(dt_task_ptr, 0);
        bus.write_word(dt_task_ptr + 4, super::DT_QTYPE);
        bus.write_word(dt_task_ptr + 6, 0);
        bus.write_long(dt_task_ptr + 8, 0x1234_5678);
        bus.write_long(dt_task_ptr + 12, 0);
        bus.write_long(dt_task_ptr + 16, 0);
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xFACE_B00C);
        cpu.write_reg(Register::A0, dt_task_ptr);
        cpu.write_reg(Register::D0, 0xFFFF_FFFE);

        let result = dispatcher.dispatch_memory(false, 0x82, &mut cpu, &mut bus);
        assert!(result.is_some(), "DTInstall should be handled");
        assert!(result.unwrap().is_ok(), "DTInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A0),
            dt_task_ptr,
            "DTInstall should preserve A0 task pointer"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "DTInstall should not consume a Pascal stack frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xFACE_B00C,
            "DTInstall should leave caller stack contents untouched"
        );
    }

    #[test]
    fn dtinstall_valid_record_returns_noerr_in_d0() {
        // Inside Macintosh Volume V (1986), p. V-467:
        // DTInstall returns noErr for nominal installs.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let dt_task_ptr = bus.alloc(24);
        bus.write_long(dt_task_ptr, 0);
        bus.write_word(dt_task_ptr + 4, super::DT_QTYPE);
        bus.write_word(dt_task_ptr + 6, 0);
        bus.write_long(dt_task_ptr + 8, 0x1234_5678);
        bus.write_long(dt_task_ptr + 12, 0);
        bus.write_long(dt_task_ptr + 16, 0);
        cpu.write_reg(Register::A0, dt_task_ptr);
        cpu.write_reg(Register::D0, 0xDEAD_BEEF);

        let result = dispatcher.dispatch_memory(false, 0x82, &mut cpu, &mut bus);
        assert!(result.is_some(), "DTInstall should be handled");
        assert!(result.unwrap().is_ok(), "DTInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DTInstall should return noErr in D0 for a valid record"
        );
    }

    #[test]
    fn dtinstall_invalid_qtype_returns_vtyperr_and_preserves_stack_pointer() {
        // Inside Macintosh Volume V (1986), p. V-467; and
        // Inside Macintosh: Processes (1994), pp. 6-12 to 6-13:
        // DTInstall returns vTypErr (-2) when qType is not ORD(dtQType).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let dt_task_ptr = bus.alloc(24);
        bus.write_long(dt_task_ptr, 0);
        bus.write_word(dt_task_ptr + 4, 0);
        bus.write_word(dt_task_ptr + 6, 0);
        bus.write_long(dt_task_ptr + 8, 0x1234_5678);
        bus.write_long(dt_task_ptr + 12, 0);
        bus.write_long(dt_task_ptr + 16, 0);
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xABCD_0123);
        cpu.write_reg(Register::A0, dt_task_ptr);
        cpu.write_reg(Register::D0, 0xDEAD_BEEF);

        let result = dispatcher.dispatch_memory(false, 0x82, &mut cpu, &mut bus);
        assert!(result.is_some(), "DTInstall should be handled");
        assert!(result.unwrap().is_ok(), "DTInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0) as i16,
            -2,
            "DTInstall should return vTypErr for invalid qType"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "DTInstall should preserve A7 on invalid qType"
        );
    }

    #[test]
    fn maxapplzone_returns_noerr_and_preserves_appllimit_in_hle() {
        // Inside Macintosh Volume II (1985), p. II-30: MaxApplZone expands
        // the app heap up to ApplLimit and reports noErr on success.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let appl_limit = 0x00A0_0000u32;
        bus.write_long(crate::memory::globals::addr::HEAP_END, appl_limit);
        bus.write_long(crate::memory::globals::addr::APPL_LIMIT, appl_limit);
        cpu.write_reg(Register::D0, 0xFFFF_FFEE);

        let result = dispatcher.dispatch_memory(false, 0x63, &mut cpu, &mut bus);
        assert!(result.is_some(), "MaxApplZone should be handled");
        assert!(
            result.unwrap().is_ok(),
            "MaxApplZone should succeed on nominal call"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "MaxApplZone should return noErr in D0 for assembly callers"
        );
        assert_eq!(
            bus.read_long(crate::memory::globals::addr::APPL_LIMIT),
            appl_limit,
            "MaxApplZone should not rewrite ApplLimit itself"
        );
    }

    #[test]
    fn maxapplzone_updates_heapend_to_applimit_when_room_is_available() {
        // Inside Macintosh Volume II, II-30 and Memory 1992, 2-27 / 2-74..2-75:
        // MaxApplZone expands the application heap up to ApplLimit.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let heap_end = 0x00A0_0000u32;
        let appl_limit = heap_end + 0x1000;
        bus.write_long(crate::memory::globals::addr::HEAP_END, heap_end);
        bus.write_long(crate::memory::globals::addr::APPL_LIMIT, appl_limit);

        let result = dispatcher.dispatch_memory(false, 0x63, &mut cpu, &mut bus);
        assert!(result.is_some(), "MaxApplZone should be handled");
        assert!(
            result.unwrap().is_ok(),
            "MaxApplZone should succeed on nominal call"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "MaxApplZone should return noErr in D0 for assembly callers"
        );
        assert_eq!(
            bus.read_long(crate::memory::globals::addr::HEAP_END),
            appl_limit,
            "MaxApplZone should advance HeapEnd to the current ApplLimit"
        );
        assert_eq!(
            bus.read_long(crate::memory::globals::addr::APPL_LIMIT),
            appl_limit,
            "MaxApplZone should not rewrite ApplLimit itself"
        );
    }

    #[test]
    fn resrvmem_uses_d0_cbneeded_and_returns_noerr() {
        // Inside Macintosh Volume II (1985), p. II-39: ResrvMem takes
        // cbNeeded in D0 and returns an OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0x0001_0000);

        let result = dispatcher.dispatch_memory(false, 0x40, &mut cpu, &mut bus);
        assert!(result.is_some(), "ResrvMem should be handled");
        assert!(result.unwrap().is_ok(), "ResrvMem should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "ResrvMem should return noErr in D0 on nominal calls"
        );
    }

    #[test]
    fn moremasters_returns_noerr_and_followup_newhandle_succeeds() {
        // Inside Macintosh Volume II (1985), p. II-31: MoreMasters allocates
        // another master-pointer block and reports noErr on success.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0xFACE_F00D);

        let more_masters = dispatcher.dispatch_memory(false, 0x36, &mut cpu, &mut bus);
        assert!(more_masters.is_some(), "MoreMasters should be handled");
        assert!(
            more_masters.unwrap().is_ok(),
            "MoreMasters should succeed on nominal call"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "MoreMasters should return noErr in D0 for assembly callers"
        );

        cpu.write_reg(Register::D0, 64);
        let new_handle = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(
            new_handle.unwrap().is_ok(),
            "NewHandle should still succeed"
        );
        assert_ne!(
            cpu.read_reg(Register::A0),
            0,
            "MoreMasters no-op path should not block subsequent handle allocation"
        );
    }

    #[test]
    fn sleepqinstall_variant_consumes_sleepqrecptr_argument() {
        // SleepQInstall is PROCEDURE SleepQInstall(qRecPtr: SleepQRecPtr),
        // so it consumes one 4-byte pointer argument from stack.
        // Inside Macintosh: Devices (1994), p. 6-33.
        // Trap word mapping: SleepQInstall = $A28A (IM:VI 1991 Appendix C, p. C-3).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let q_rec_ptr = bus.alloc(12);
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, q_rec_ptr);
        dispatcher.current_trap_word = 0xA28A;

        let result = dispatcher.dispatch_memory(false, 0x8A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SleepQInstall should be handled");
        assert!(
            result.unwrap().is_ok(),
            "SleepQInstall should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before.wrapping_add(4),
            "SleepQInstall should pop one SleepQRecPtr argument (4 bytes)"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SleepQInstall no-op path should report noErr in D0"
        );
    }

    #[test]
    fn sleepqremove_variant_consumes_sleepqrecptr_argument() {
        // SleepQRemove is PROCEDURE SleepQRemove(qRecPtr: SleepQRecPtr),
        // so it consumes one 4-byte pointer argument from stack.
        // Inside Macintosh: Devices (1994), p. 6-33.
        // Trap word mapping: SleepQRemove = $A48A (IM:VI 1991 Appendix C, p. C-3).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let q_rec_ptr = bus.alloc(12);
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, q_rec_ptr);
        dispatcher.current_trap_word = 0xA48A;

        let result = dispatcher.dispatch_memory(false, 0x8A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SleepQRemove should be handled");
        assert!(
            result.unwrap().is_ok(),
            "SleepQRemove should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before.wrapping_add(4),
            "SleepQRemove should pop one SleepQRecPtr argument (4 bytes)"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SleepQRemove no-op path should report noErr in D0"
        );
    }

    #[test]
    fn sleepq_family_trap_leaves_stack_untouched() {
        // The family trap word ($A08A) is the shell that dispatches to the
        // SleepQInstall/$A28A and SleepQRemove/$A48A variants.
        // The shell itself should not consume a Pascal argument frame.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x1357_9BDF);
        dispatcher.current_trap_word = 0xA08A;

        let result = dispatcher.dispatch_memory(false, 0x8A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SleepQ family trap should be handled");
        assert!(
            result.unwrap().is_ok(),
            "SleepQ family trap should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SleepQ family shell should not pop a Pascal frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x1357_9BDF,
            "SleepQ family shell should leave the stack top untouched"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SleepQ family shell should report noErr in D0"
        );
    }

    #[test]
    fn commtoolboxdispatch_countditl_returns_dialog_item_count_and_preserves_stack_pointer() {
        // Inside Macintosh Volume VI (1991), Appendix C table C-3 (p. C-4):
        // _CommToolboxDispatch ($A08B) dispatches CountDITL via selector
        // $0403. The MPW C frame observed in the strict fixture places
        // the 4-byte result slot at SP+0..3, the selector word at SP+4..5,
        // and the DialogPtr argument at SP+6..9.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08B;
        let dialog_ptr = bus.alloc(170);
        let items = vec![
            crate::trap::dispatch::DialogItem {
                item_type: 4,
                rect: (10, 10, 20, 20),
                text: "One".to_string(),
                resource_id: 0,
                proc_ptr: 0,
                sel_start: 0,
                sel_end: 0,
            },
            crate::trap::dispatch::DialogItem {
                item_type: 8,
                rect: (20, 10, 30, 20),
                text: "Two".to_string(),
                resource_id: 0,
                proc_ptr: 0,
                sel_start: 0,
                sel_end: 0,
            },
            crate::trap::dispatch::DialogItem {
                item_type: 16,
                rect: (30, 10, 40, 20),
                text: "Three".to_string(),
                resource_id: 0,
                proc_ptr: 0,
                sel_start: 0,
                sel_end: 0,
            },
        ];
        dispatcher.dialog_items.insert(dialog_ptr, items);
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xCAFE_BABE);
        bus.write_word(sp_before + 4, 0x0403);
        bus.write_long(sp_before + 6, dialog_ptr);
        bus.write_word(sp_before + 10, 0x9BDF);

        let result = dispatcher.dispatch_memory(false, 0x8B, &mut cpu, &mut bus);
        assert!(result.is_some(), "CommToolboxDispatch should be handled");
        assert!(
            result.unwrap().is_ok(),
            "CommToolboxDispatch should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "CountDITL should leave the caller stack pointer unchanged"
        );
        assert_eq!(
            bus.read_word(sp_before + 4),
            0x0403,
            "CountDITL should not overwrite the selector word on the caller stack"
        );
        assert_eq!(
            bus.read_long(sp_before + 6),
            dialog_ptr,
            "CountDITL should not overwrite the dialog pointer slot on the caller stack"
        );
        assert_eq!(
            bus.read_word(sp_before + 10),
            0x9BDF,
            "CountDITL should not overwrite the following stack word"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            3,
            "CountDITL should report the three dialog items we installed"
        );
    }

    #[test]
    fn commtoolboxdispatch_countditl_preserves_non_d0_registers() {
        // Inside Macintosh Volume VI (1991), Appendix C table C-3 (p. C-4):
        // CountDITL is one selector behind _CommToolboxDispatch. The MPW
        // C frame places the 4-byte result slot at SP+0..3, selector at
        // SP+4..5, and the DialogPtr argument at SP+6..9.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08B;
        let dialog_ptr = bus.alloc(170);
        dispatcher.dialog_items.insert(
            dialog_ptr,
            vec![crate::trap::dispatch::DialogItem {
                item_type: 4,
                rect: (10, 10, 20, 20),
                text: "One".to_string(),
                resource_id: 0,
                proc_ptr: 0,
                sel_start: 0,
                sel_end: 0,
            }],
        );
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);
        bus.write_word(sp_before + 4, 0x0403);
        bus.write_long(sp_before + 6, dialog_ptr);
        cpu.write_reg(Register::A0, 0x00AB_C000);
        cpu.write_reg(Register::A1, 0x00AB_C100);
        cpu.write_reg(Register::D1, 0x5AA5_0F0F);

        let result = dispatcher.dispatch_memory(false, 0x8B, &mut cpu, &mut bus);
        assert!(result.is_some(), "CommToolboxDispatch should be handled");
        assert!(
            result.unwrap().is_ok(),
            "CommToolboxDispatch should return cleanly"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x00AB_C000,
            "CommToolboxDispatch stub should preserve A0"
        );
        assert_eq!(
            cpu.read_reg(Register::A1),
            0x00AB_C100,
            "CountDITL should preserve A1"
        );
        assert_eq!(
            cpu.read_reg(Register::D1),
            0x5AA5_0F0F,
            "CountDITL should preserve D1"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "CountDITL should preserve the caller stack pointer"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            1,
            "CountDITL should mirror the result into D0 for CCR update"
        );
    }

    #[test]
    fn commtoolboxdispatch_selector_0403_returns_expected_counts_for_one_and_three_item_dialogs() {
        // Inside Macintosh Volume VI (1991), Appendix C table C-3 (p. C-4):
        // _CommToolboxDispatch ($A08B) dispatches CountDITL via selector
        // $0403. The MPW frame used by the strict fixture places the
        // 4-byte result slot at SP+0..3, selector at SP+4..5, and the
        // DialogPtr argument at SP+6..9. This test mirrors the strict
        // fixture by checking both a one-item dialog and the existing
        // three-item dialog.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08B;

        let one_dialog_ptr = bus.alloc(170);
        dispatcher.dialog_items.insert(
            one_dialog_ptr,
            vec![crate::trap::dispatch::DialogItem {
                item_type: 4,
                rect: (10, 10, 20, 20),
                text: "OK".to_string(),
                resource_id: 0,
                proc_ptr: 0,
                sel_start: 0,
                sel_end: 0,
            }],
        );

        let three_dialog_ptr = bus.alloc(170);
        dispatcher.dialog_items.insert(
            three_dialog_ptr,
            vec![
                crate::trap::dispatch::DialogItem {
                    item_type: 4,
                    rect: (10, 10, 20, 20),
                    text: "One".to_string(),
                    resource_id: 0,
                    proc_ptr: 0,
                    sel_start: 0,
                    sel_end: 0,
                },
                crate::trap::dispatch::DialogItem {
                    item_type: 8,
                    rect: (20, 10, 30, 20),
                    text: "Two".to_string(),
                    resource_id: 0,
                    proc_ptr: 0,
                    sel_start: 0,
                    sel_end: 0,
                },
                crate::trap::dispatch::DialogItem {
                    item_type: 16,
                    rect: (30, 10, 40, 20),
                    text: "Three".to_string(),
                    resource_id: 0,
                    proc_ptr: 0,
                    sel_start: 0,
                    sel_end: 0,
                },
            ],
        );

        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);
        bus.write_word(sp_before + 4, 0x0403);
        bus.write_long(sp_before + 6, one_dialog_ptr);
        let one_result = dispatcher.dispatch_memory(false, 0x8B, &mut cpu, &mut bus);
        assert!(
            one_result.is_some(),
            "CommToolboxDispatch should be handled for a one-item dialog"
        );
        assert!(
            one_result.unwrap().is_ok(),
            "CommToolboxDispatch should return cleanly for a one-item dialog"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            1,
            "CommToolboxDispatch should report one item for the one-item dialog"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "CommToolboxDispatch should preserve the caller stack pointer for the one-item dialog"
        );

        cpu.write_reg(Register::A7, sp_before);
        bus.write_long(sp_before, 0xDEAD_BEEF);
        bus.write_word(sp_before + 4, 0x0403);
        bus.write_long(sp_before + 6, three_dialog_ptr);
        let three_result = dispatcher.dispatch_memory(false, 0x8B, &mut cpu, &mut bus);
        assert!(
            three_result.is_some(),
            "CommToolboxDispatch should be handled for a three-item dialog"
        );
        assert!(
            three_result.unwrap().is_ok(),
            "CommToolboxDispatch should return cleanly for a three-item dialog"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            3,
            "CommToolboxDispatch should report three items for the three-item dialog"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "CommToolboxDispatch should preserve the caller stack pointer for the three-item dialog"
        );
    }

    #[test]
    fn debugutil_debuggergetmax_returns_max_selector_and_preserves_stack_pointer() {
        // Inside Macintosh Volume VI (1991), p. 28-30 and Appendix C table C-3
        // (p. C-4): _DebugUtil is selector-dispatched in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x2468_ACF0);
        cpu.write_reg(Register::D0, 0x0000); // DebuggerGetMax selector

        let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugUtil should be handled");
        assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "DebugUtil should not consume a stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x2468_ACF0,
            "stack top should remain untouched for DebugUtil selector dispatch"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            8,
            "DebugUtil selector $0000 should return the highest documented selector"
        );
    }

    #[test]
    fn debugutil_other_selectors_preserve_non_d0_registers() {
        // Inside Macintosh Volume VI (1991), pp. 28-30..28-31 and Appendix C
        // table C-3 (p. C-4): debugger helper routines share _DebugUtil.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        cpu.write_reg(Register::A0, 0x0012_3000);
        cpu.write_reg(Register::A1, 0x0012_3F00);
        cpu.write_reg(Register::D1, 0x1234_5678);
        cpu.write_reg(Register::D0, 0x0006); // DebuggerLockMemory selector

        let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugUtil should be handled");
        assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x0012_3000,
            "DebugUtil selector $0006 should preserve A0"
        );
        assert_eq!(
            cpu.read_reg(Register::A1),
            0x0012_3F00,
            "DebugUtil selector $0006 should preserve A1"
        );
        assert_eq!(
            cpu.read_reg(Register::D1),
            0x1234_5678,
            "DebugUtil selector $0006 should preserve D1"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DebugUtil selector $0006 should rewrite only D0 to noErr"
        );
    }

    #[test]
    fn debugutil_debuggerpoll_preserves_stack_sentinel_and_returns_noerr() {
        // Selector $0003 (DebuggerPoll) is part of the documented
        // DebugUtil table in Inside Macintosh Volume VI 1991,
        // Appendix C table C-3 (p. C-4).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x1357_9BDF);
        cpu.write_reg(Register::D0, 0x0003);
        cpu.write_reg(Register::A0, 0x00FE_DCBA);
        cpu.write_reg(Register::A1, 0x00AB_CDEF);

        let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugUtil should be handled");
        assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "DebugUtil selector $0003 should not consume a stack frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x1357_9BDF,
            "DebugUtil selector $0003 should leave the stack sentinel untouched"
        );
        assert_eq!(cpu.read_reg(Register::A0), 0x00FE_DCBA);
        assert_eq!(cpu.read_reg(Register::A1), 0x00AB_CDEF);
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DebugUtil selector $0003 should return noErr"
        );
    }

    #[test]
    fn debugutil_debuggerpoll_updates_dispatcher_ccr_for_noerr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        cpu.set_ccr(0x10);
        cpu.write_reg(Register::D0, 0x0003);

        let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugUtil should be handled");
        assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DebugUtil selector $0003 should return noErr"
        );
        assert_eq!(
            cpu.get_ccr(),
            0x14,
            "DebugUtil selector $0003 should mirror noErr into CCR without disturbing X"
        );
    }

    #[test]
    fn debugutil_debuggergetmax_preserves_non_d0_registers() {
        // Selector $0000 should use the same register-only ABI and
        // leave the scratch registers alone while returning 8 in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        cpu.write_reg(Register::A0, 0x00AA_5500);
        cpu.write_reg(Register::A1, 0x00BB_6600);
        cpu.write_reg(Register::D1, 0x1234_5678);
        cpu.write_reg(Register::D0, 0x0000);

        let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugUtil should be handled");
        assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        assert_eq!(cpu.read_reg(Register::A0), 0x00AA_5500);
        assert_eq!(cpu.read_reg(Register::A1), 0x00BB_6600);
        assert_eq!(cpu.read_reg(Register::D1), 0x1234_5678);
        assert_eq!(cpu.read_reg(Register::D0), 8);
    }

    #[test]
    fn debugutil_five_call_composition_preserves_stack_across_documented_selectors() {
        // Mirrors B2 of the a08d_debugutil_strict bake: 5 successive
        // _DebugUtil dispatches with varying D0 selector inputs spanning
        // the documented IM:VI 1991 Appendix C table C-3 (p. C-4) range
        // ($0000 DebuggerGetMax / $0001 DebuggerEnter / $0003 DebuggerPoll
        // / $0005 PageFaultFatal / $0008 EnterSupervisorMode) preserve A7
        // in aggregate AND leave the SP+0 sentinel untouched.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);

        let selectors: [u32; 5] = [0x0000, 0x0001, 0x0003, 0x0005, 0x0008];
        for selector in selectors {
            cpu.write_reg(Register::D0, selector);
            let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
            assert!(result.is_some(), "DebugUtil should be handled");
            assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
        }
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "5-call DebugUtil composition should preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xDEAD_BEEF,
            "SP+0 sentinel should survive 5-call DebugUtil composition"
        );
    }

    #[test]
    fn debugutil_debuggerpoll_five_call_composition_preserves_stack_across_repeated_selector_three_calls() {
        // Mirrors B4 of the a08d_debugutil_strict bake: five successive
        // DebuggerPoll calls preserve A7 in aggregate and continue to
        // return noErr across the repeated selector-3 path.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08D;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xCAFE_BABE);

        for _ in 0..5 {
            cpu.write_reg(Register::D0, 0x0003);
            let result = dispatcher.dispatch_memory(false, 0x8D, &mut cpu, &mut bus);
            assert!(result.is_some(), "DebugUtil should be handled");
            assert!(result.unwrap().is_ok(), "DebugUtil should return cleanly");
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "DebugUtil selector $0003 should return noErr"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "five DebuggerPoll calls should preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xCAFE_BABE,
            "five DebuggerPoll calls should leave the stack sentinel untouched"
        );
    }

    #[test]
    fn deferuserfn_uses_register_calling_convention_without_stack_arguments() {
        // Inside Macintosh Volume VI (1991), p. 28-30; Inside Macintosh:
        // Memory (1992), p. 3-33: DeferUserFn uses D0(argument)/A0(function)
        // registers and returns result in D0. This test exercises the safe
        // fallback path for a non-callable placeholder pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08F;
        let sp_before = cpu.read_reg(Register::A7);
        let pc_before = 0x00BA_D000;
        bus.write_long(sp_before, 0xBADC_0DE0);
        cpu.write_reg(Register::A0, 0x00C0_FFEE);
        cpu.write_reg(Register::D0, 0x0012_3400);
        cpu.write_reg(Register::PC, pc_before);

        let result = dispatcher.dispatch_memory(false, 0x8F, &mut cpu, &mut bus);
        assert!(result.is_some(), "DeferUserFn should be handled");
        assert!(result.unwrap().is_ok(), "DeferUserFn should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "DeferUserFn should not pop a Pascal stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xBADC_0DE0,
            "stack top should remain untouched by DeferUserFn register ABI"
        );
        assert_eq!(
            cpu.read_reg(Register::PC),
            pc_before,
            "non-callable DeferUserFn fallback should not install a trampoline"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DeferUserFn stub should return noErr in D0"
        );
    }

    #[test]
    fn deferuserfn_nominal_stub_returns_noerr() {
        // Inside Macintosh Volume VI (1991), p. 28-30: DeferUserFn returns an
        // OSErr in D0. This is the safe non-callable-pointer fallback.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08F;
        cpu.write_reg(Register::A0, 0x00D0_0000);
        cpu.write_reg(Register::D0, 0x00E0_0000);

        let result = dispatcher.dispatch_memory(false, 0x8F, &mut cpu, &mut bus);
        assert!(result.is_some(), "DeferUserFn should be handled");
        assert!(result.unwrap().is_ok(), "DeferUserFn should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "DeferUserFn stub should report noErr for nominal calls"
        );
    }

    #[test]
    fn deferuserfn_callable_pointer_installs_trampoline_and_returns_noerr() {
        // Valid callable-proc path: the trap should inject a trampoline,
        // pass the argument in A0, and return noErr in D0 before the
        // trampoline executes. The actual callback run is covered by the
        // BasiliskII strict fixture.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08F;

        let pc_after_trap = 0x00BA_D100;
        let sp_before = cpu.read_reg(Register::A7);
        let user_fn = bus.alloc(8);
        bus.write_word(user_fn, 0x4E56); // LINK A6,#0 — looks like a real proc
        bus.write_word(user_fn + 2, 0x0000);
        bus.write_word(user_fn + 4, 0x4E75); // RTS

        cpu.write_reg(Register::PC, pc_after_trap);
        cpu.write_reg(Register::A0, user_fn);
        cpu.write_reg(Register::D0, 0x00DE_ADBE);

        let result = dispatcher.dispatch_memory(false, 0x8F, &mut cpu, &mut bus);
        assert!(result.is_some(), "DeferUserFn should be handled");
        assert!(result.unwrap().is_ok(), "DeferUserFn should return cleanly");

        let tramp = dispatcher.defer_user_fn_trampoline;
        assert_ne!(tramp, 0, "DeferUserFn should allocate a trampoline");
        assert_eq!(cpu.read_reg(Register::PC), tramp, "trampoline PC should be installed");
        assert_eq!(cpu.read_reg(Register::A7), sp_before - 4, "DeferUserFn should push a return address for the trampoline");
        assert_eq!(bus.read_long(sp_before - 4), pc_after_trap, "trampoline should resume at the post-trap PC");
        assert_eq!(cpu.read_reg(Register::D0), 0, "DeferUserFn should return noErr in D0");
        assert_eq!(bus.read_word(tramp), 0x48E7, "trampoline should save scratch registers");
        assert_eq!(bus.read_word(tramp + 2), 0xF0F0, "trampoline should save D0-D3/A0-A3");
        assert_eq!(bus.read_word(tramp + 4), 0x207C, "trampoline should load the argument into A0");
        assert_eq!(bus.read_long(tramp + 6), 0x00DE_ADBE, "trampoline should patch the argument literal");
        assert_eq!(bus.read_word(tramp + 10), 0x4EB9, "trampoline should JSR to the user function");
        assert_eq!(bus.read_long(tramp + 12), user_fn, "trampoline should patch the callback address");
        assert_eq!(bus.read_word(tramp + 16), 0x4CDF, "trampoline should restore scratch registers");
        assert_eq!(bus.read_word(tramp + 18), 0x0F0F, "trampoline should restore D0-D3/A0-A3");
        assert_eq!(bus.read_word(tramp + 20), 0x7000, "trampoline should clear D0 to noErr");
        assert_eq!(bus.read_word(tramp + 22), 0x4E75, "trampoline should RTS back to the caller");
    }

    #[test]
    fn deferuserfn_five_call_composition_preserves_stack_across_varying_args() {
        // Mirrors a08f_deferuserfn_strict B2: 5 successive _DeferUserFn
        // dispatches with varying (A0=userFunction, D0=argument) inputs
        // span the IM:Memory 1992 p. 3-33 register convention. Per-call
        // pop-discipline errors accumulate; the 5-call composition
        // catches drift even when a single call's discipline is correct.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08F;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xBADC_0DE0);

        // Five (userFunction, argument) tuples spanning small/large
        // pointer values and zero-vs-nonzero arguments.
        let inputs = [
            (0x0040_0000u32, 0x0000_0000u32),
            (0x00C0_0000u32, 0x0000_0001u32),
            (0x0050_8000u32, 0xDEAD_BEEFu32),
            (0x00B0_C000u32, 0x0000_FFFFu32),
            (0x0080_0000u32, 0xCAFE_BABEu32),
        ];
        for (a0, d0) in inputs.iter().copied() {
            cpu.write_reg(Register::A0, a0);
            cpu.write_reg(Register::D0, d0);
            let r = dispatcher.dispatch_memory(false, 0x8F, &mut cpu, &mut bus);
            assert!(r.is_some(), "DeferUserFn should be handled");
            assert!(r.unwrap().is_ok(), "DeferUserFn should return cleanly");
        }
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "5-call DeferUserFn composition should preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xBADC_0DE0,
            "SP+0 sentinel should survive 5-call DeferUserFn composition"
        );
    }

    #[test]
    fn deferuserfn_three_call_composition_preserves_stack_across_varying_args() {
        // Mirrors the strict fixture's repeated-call witness: three
        // successive DeferUserFn dispatches with varying A0/D0 inputs
        // should still preserve the Pascal stack discipline.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        dispatcher.current_trap_word = 0xA08F;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xBADC_0DE0);

        let user_fn = bus.alloc(8);
        bus.write_word(user_fn, 0x4E56); // LINK A6,#0 — looks like a real proc
        bus.write_word(user_fn + 2, 0x0000);
        bus.write_word(user_fn + 4, 0x4E75); // RTS

        let inputs = [
            (0x0040_0000u32, 0x0000_0000u32),
            (0x00C0_0000u32, 0x0000_0001u32),
            (0x0050_8000u32, 0xDEAD_BEEFu32),
        ];
        for (a0, d0) in inputs.iter().copied() {
            cpu.write_reg(Register::A0, a0);
            cpu.write_reg(Register::D0, d0);
            let r = dispatcher.dispatch_memory(false, 0x8F, &mut cpu, &mut bus);
            assert!(r.is_some(), "DeferUserFn should be handled");
            assert!(r.unwrap().is_ok(), "DeferUserFn should return cleanly");
        }
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "3-call DeferUserFn composition should preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xBADC_0DE0,
            "SP+0 sentinel should survive 3-call DeferUserFn composition"
        );
    }

    #[test]
    fn nminstall_returns_noerr_for_nominal_notification_request() {
        // Inside Macintosh Volume VI (1991), p. 24-10:
        // NMInstall returns noErr for valid notification requests.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let nm_rec = bus.alloc(32);
        bus.write_word(nm_rec + 4, 8); // qType = ORD(nmType)
        cpu.write_reg(Register::A0, nm_rec);

        let result = dispatcher.dispatch_memory(false, 0x5E, &mut cpu, &mut bus);
        assert!(result.is_some(), "NMInstall should be handled");
        assert!(result.unwrap().is_ok(), "NMInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NMInstall should return noErr in D0 for nominal input"
        );
    }

    #[test]
    fn nminstall_uses_a0_nmrecptr_register_calling_convention() {
        // Inside Macintosh Volume VI (1991), p. 24-10:
        // NMInstall takes NMRecPtr in A0 and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let nm_rec = bus.alloc(32);
        bus.write_word(nm_rec + 4, 8); // qType = ORD(nmType)
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xFEED_FACE);
        cpu.write_reg(Register::A0, nm_rec);

        let result = dispatcher.dispatch_memory(false, 0x5E, &mut cpu, &mut bus);
        assert!(result.is_some(), "NMInstall should be handled");
        assert!(result.unwrap().is_ok(), "NMInstall should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "NMInstall should not consume a Pascal stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xFEED_FACE,
            "stack top should remain untouched by register calling convention"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NMInstall should return noErr"
        );
    }

    #[test]
    fn nmremove_returns_noerr_for_nominal_notification_request() {
        // Inside Macintosh Volume VI (1991), p. 24-11:
        // NMRemove returns noErr for a successful request removal.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let nm_rec = bus.alloc(32);
        bus.write_word(nm_rec + 4, 8); // qType = ORD(nmType)
        cpu.write_reg(Register::A0, nm_rec);

        let result = dispatcher.dispatch_memory(false, 0x5F, &mut cpu, &mut bus);
        assert!(result.is_some(), "NMRemove should be handled");
        assert!(result.unwrap().is_ok(), "NMRemove should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NMRemove should return noErr in D0 for nominal input"
        );
    }

    #[test]
    fn nmremove_uses_a0_nmrecptr_register_calling_convention() {
        // Inside Macintosh Volume VI (1991), p. 24-11:
        // NMRemove takes NMRecPtr in A0 and returns OSErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let nm_rec = bus.alloc(32);
        bus.write_word(nm_rec + 4, 8); // qType = ORD(nmType)
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xC0DE_CAFE);
        cpu.write_reg(Register::A0, nm_rec);

        let result = dispatcher.dispatch_memory(false, 0x5F, &mut cpu, &mut bus);
        assert!(result.is_some(), "NMRemove should be handled");
        assert!(result.unwrap().is_ok(), "NMRemove should return cleanly");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "NMRemove should not consume a Pascal stack argument frame"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xC0DE_CAFE,
            "stack top should remain untouched by register calling convention"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "NMRemove should return noErr"
        );
    }

    #[test]
    fn lowertext_variant_converts_ascii_and_macroman_uppercase_to_lowercase() {
        // Inside Macintosh Volume VI (1991), p. 14-62: LowerText localizes
        // lowercase conversion for len bytes at A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let input = [b'A', 0x83, b'Z', b'!', 0x84, 0x8E];
        let ptr = bus.alloc(input.len() as u32);
        bus.write_bytes(ptr, &input);

        dispatcher.current_trap_word = 0xA056;
        cpu.write_reg(Register::A0, ptr);
        cpu.write_reg(Register::D0, 5);
        let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);

        assert!(result.is_some(), "LowerText variant should be handled");
        assert!(result.unwrap().is_ok(), "LowerText should return");
        assert_eq!(
            bus.read_bytes(ptr, input.len()),
            vec![b'a', 0x8E, b'z', b'!', 0x96, 0x8E],
            "LowerText should lowercase only the requested len bytes"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LowerText should return noErr in D0"
        );
    }

    #[test]
    fn uppertext_variant_converts_ascii_and_macroman_lowercase_to_uppercase() {
        // Inside Macintosh Volume VI (1991), p. 14-63: UpperText localizes
        // uppercase conversion for len bytes at A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let input = [b'a', 0x8E, b'z', b'?', 0x96, 0x8A];
        let ptr = bus.alloc(input.len() as u32);
        bus.write_bytes(ptr, &input);

        dispatcher.current_trap_word = 0xA456;
        cpu.write_reg(Register::A0, ptr);
        cpu.write_reg(Register::D0, 5);
        let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);

        assert!(result.is_some(), "UpperText variant should be handled");
        assert!(result.unwrap().is_ok(), "UpperText should return");
        assert_eq!(
            bus.read_bytes(ptr, input.len()),
            vec![b'A', 0x83, b'Z', b'?', 0x84, 0x8A],
            "UpperText should uppercase only the requested len bytes"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UpperText should return noErr in D0"
        );
    }

    #[test]
    fn striptext_variant_strips_diacriticals_without_case_fold() {
        // Inside Macintosh Volume VI (1991), p. 14-63: StripText removes
        // diacritical marks without forcing uppercase.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let input = [0x8E, 0x83, 0x96, 0x84, b'Q', 0x9A];
        let ptr = bus.alloc(input.len() as u32);
        bus.write_bytes(ptr, &input);

        dispatcher.current_trap_word = 0xA256;
        cpu.write_reg(Register::A0, ptr);
        cpu.write_reg(Register::D0, 5);
        let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);

        assert!(result.is_some(), "StripText variant should be handled");
        assert!(result.unwrap().is_ok(), "StripText should return");
        assert_eq!(
            bus.read_bytes(ptr, input.len()),
            vec![b'e', b'E', b'n', b'N', b'Q', 0x9A],
            "StripText should strip marks while preserving letter case"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "StripText should return noErr in D0"
        );
    }

    #[test]
    fn stripuppertext_variant_strips_diacriticals_and_uppercases() {
        // Inside Macintosh Volume VI (1991), p. 14-63: StripUpperText strips
        // diacritical marks and uppercases text for len bytes at A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let input = [0x8E, 0x8A, b'x', 0x96, 0xCF, b'?'];
        let ptr = bus.alloc(input.len() as u32);
        bus.write_bytes(ptr, &input);

        dispatcher.current_trap_word = 0xA656;
        cpu.write_reg(Register::A0, ptr);
        cpu.write_reg(Register::D0, 5);
        let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);

        assert!(result.is_some(), "StripUpperText variant should be handled");
        assert!(result.unwrap().is_ok(), "StripUpperText should return");
        assert_eq!(
            bus.read_bytes(ptr, input.len()),
            vec![b'E', b'A', b'X', b'N', b'O', b'?'],
            "StripUpperText should strip marks and uppercase requested bytes"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "StripUpperText should return noErr in D0"
        );
    }

    #[test]
    fn lowertext_family_variants_return_noerr_in_d0_for_nominal_calls() {
        // Inside Macintosh Volume VI (1991), p. 14-63: LowerText-family
        // result codes include noErr and resNotFound; nominal calls return noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        for trap_word in [0xA056u16, 0xA256, 0xA456, 0xA656] {
            let ptr = bus.alloc(3);
            bus.write_bytes(ptr, b"Ae?");
            dispatcher.current_trap_word = trap_word;
            cpu.write_reg(Register::A0, ptr);
            cpu.write_reg(Register::D0, 3);
            let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);
            assert!(
                result.is_some(),
                "LowerText-family variant ${trap_word:04X} should be handled"
            );
            assert!(
                result.unwrap().is_ok(),
                "LowerText-family variant ${trap_word:04X} should return"
            );
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "LowerText-family variant ${trap_word:04X} should return noErr in D0"
            );
        }
    }

    #[test]
    fn lowertext_family_returns_noerr_in_d0_for_each_trap_word_variant() {
        // Pins the catalog row assertion
        // `A056:text_conversion_variants_return_noerr_in_d0_for_nominal_calls`.
        // The strict bake fixture a056_text_conversion_variants_strict
        // exercises the same four variants on the same input bytes
        // {0x41, 0x61, 0x83, 0x8E} but witnesses the buffer outputs only —
        // MPW Universal Headers declare the family as void-returning, so
        // C-side fixtures cannot sample D0 without inline asm. This test
        // pins D0=0 (noErr) on Systemless for each $A056/$A256/$A456/$A656
        // dispatch over the same input, completing the round-trip contract
        // alongside the bake's golden assertions.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        for trap_word in [0xA056u16, 0xA256, 0xA456, 0xA656] {
            let ptr = bus.alloc(4);
            bus.write_bytes(ptr, &[0x41, 0x61, 0x83, 0x8E]);
            dispatcher.current_trap_word = trap_word;
            cpu.write_reg(Register::A0, ptr);
            cpu.write_reg(Register::D0, 4);
            let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);
            assert!(
                result.is_some(),
                "LowerText-family variant ${trap_word:04X} dispatch must be handled"
            );
            assert!(
                result.unwrap().is_ok(),
                "LowerText-family variant ${trap_word:04X} dispatch must return Ok"
            );
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "LowerText-family variant ${trap_word:04X} must return noErr in D0 per IM:VI 14-63"
            );
        }
    }

    #[test]
    fn lowertext_family_variants_match_strict_bake_input_byte_sequences() {
        // Cross-reference for the strict bake's golden assertions.
        // Input: {0x41 'A', 0x61 'a', 0x83 'É', 0x8E 'é'} — 4 bytes per
        // fixture a056_text_conversion_variants_strict.
        //
        // Documented outputs per IM:VI 14-62..14-63 and IM:IV IV-235:
        //   $A056 LowerText      → {0x61, 0x61, 0x8E, 0x8E}  "aa\x8E\x8E"
        //   $A456 UpperText      → {0x41, 0x41, 0x83, 0x83}  "AA\x83\x83"
        //   $A256 StripText      → {0x41, 0x61, 0x45, 0x65}  "AaEe"
        //   $A656 StripUpperText → {0x41, 0x41, 0x45, 0x45}  "AAEE"
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let cases: &[(u16, [u8; 4])] = &[
            (0xA056, [0x61, 0x61, 0x8E, 0x8E]),
            (0xA456, [0x41, 0x41, 0x83, 0x83]),
            (0xA256, [0x41, 0x61, 0x45, 0x65]),
            (0xA656, [0x41, 0x41, 0x45, 0x45]),
        ];
        for &(trap_word, expected) in cases {
            let ptr = bus.alloc(4);
            bus.write_bytes(ptr, &[0x41, 0x61, 0x83, 0x8E]);
            dispatcher.current_trap_word = trap_word;
            cpu.write_reg(Register::A0, ptr);
            cpu.write_reg(Register::D0, 4);
            let result = dispatcher.dispatch_memory(false, 0x56, &mut cpu, &mut bus);
            assert!(
                result.is_some(),
                "Variant ${trap_word:04X} dispatch must be handled"
            );
            assert!(
                result.unwrap().is_ok(),
                "Variant ${trap_word:04X} dispatch must return Ok"
            );
            assert_eq!(
                bus.read_bytes(ptr, 4),
                expected.to_vec(),
                "Variant ${trap_word:04X} must produce documented byte sequence"
            );
        }
    }

    #[test]
    fn setvideodefault_roundtrips_defvideorec_through_getvideodefault() {
        // Inside Macintosh Volume V (1986), pp. V-354..V-355:
        // SetVideoDefault consumes DefVideoRec {sdSlot, sdSResource}, and
        // GetVideoDefault returns the stored default video record.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let set_pb = bus.alloc(2);
        bus.write_byte(set_pb, 0x0E);
        bus.write_byte(set_pb + 1, 0x2A);

        cpu.write_reg(Register::A0, set_pb);
        let set_result = dispatcher.dispatch_memory(false, 0x81, &mut cpu, &mut bus);
        assert!(set_result.is_some(), "SetVideoDefault should be handled");
        assert!(
            set_result.unwrap().is_ok(),
            "SetVideoDefault should succeed"
        );

        let get_pb = bus.alloc(2);
        cpu.write_reg(Register::A0, get_pb);
        let get_result = dispatcher.dispatch_memory(false, 0x80, &mut cpu, &mut bus);
        assert!(get_result.is_some(), "GetVideoDefault should be handled");
        assert!(
            get_result.unwrap().is_ok(),
            "GetVideoDefault should succeed"
        );
        assert_eq!(
            bus.read_byte(get_pb),
            0x0E,
            "GetVideoDefault should return sdSlot written by SetVideoDefault"
        );
        assert_eq!(
            bus.read_byte(get_pb + 1),
            0x2A,
            "GetVideoDefault should return sdSResource written by SetVideoDefault"
        );
    }

    #[test]
    fn getvideodefault_writes_two_bytes_and_preserves_following_memory() {
        // Inside Macintosh Volume V (1986), p. V-354: DefVideoRec is two bytes
        // (sdSlot, sdSResource), so GetVideoDefault should write exactly that
        // record at A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = bus.alloc(4);
        bus.write_byte(pb, 0xAA);
        bus.write_byte(pb + 1, 0xBB);
        bus.write_byte(pb + 2, 0xC3);
        bus.write_byte(pb + 3, 0xD4);

        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x80, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetVideoDefault should be handled");
        assert!(result.unwrap().is_ok(), "GetVideoDefault should succeed");
        assert_eq!(
            bus.read_byte(pb),
            0,
            "Default sdSlot should be 0 when no explicit video default is set"
        );
        assert_eq!(
            bus.read_byte(pb + 1),
            0,
            "Default sdSResource should be 0 when no explicit video default is set"
        );
        assert_eq!(
            bus.read_byte(pb + 2),
            0xC3,
            "GetVideoDefault must not overwrite bytes beyond DefVideoRec"
        );
        assert_eq!(
            bus.read_byte(pb + 3),
            0xD4,
            "GetVideoDefault must preserve trailing bytes in caller memory"
        );
    }

    #[test]
    fn setosdefault_roundtrips_sdostype_and_getosdefault_reports_reserved_zero() {
        // Inside Macintosh Volume V (1986), p. V-355: SetOSDefault specifies
        // sdOSType; sdReserved is reserved and should be 0 when read back via
        // GetOSDefault.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let set_pb = bus.alloc(2);
        bus.write_byte(set_pb, 0x7F);
        bus.write_byte(set_pb + 1, 0x05);

        cpu.write_reg(Register::A0, set_pb);
        let set_result = dispatcher.dispatch_memory(false, 0x83, &mut cpu, &mut bus);
        assert!(set_result.is_some(), "SetOSDefault should be handled");
        assert!(set_result.unwrap().is_ok(), "SetOSDefault should succeed");

        let get_pb = bus.alloc(2);
        cpu.write_reg(Register::A0, get_pb);
        let get_result = dispatcher.dispatch_memory(false, 0x84, &mut cpu, &mut bus);
        assert!(get_result.is_some(), "GetOSDefault should be handled");
        assert!(get_result.unwrap().is_ok(), "GetOSDefault should succeed");
        assert_eq!(
            bus.read_byte(get_pb),
            0,
            "GetOSDefault should report sdReserved as 0"
        );
        assert_eq!(
            bus.read_byte(get_pb + 1),
            0x05,
            "GetOSDefault should return sdOSType written by SetOSDefault"
        );
    }

    #[test]
    fn setosdefault_preserves_caller_defosrec_input_bytes_read_only_a0() {
        // Inside Macintosh Volume V (1986), p. V-355: SetOSDefault's parameter
        // block direction arrows (`→` in both rows of the trap-macro summary)
        // document sdReserved + sdOSType as INPUTs supplied by the caller; the
        // trap copies them into the in-session default record without writing
        // back to the caller's buffer. Mirrors B1 of a083_setosdefault_strict.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = bus.alloc(4);
        bus.write_byte(pb, 0x00);
        bus.write_byte(pb + 1, 0x02);
        bus.write_byte(pb + 2, 0xCC);
        bus.write_byte(pb + 3, 0xCC);

        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x83, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetOSDefault should be handled");
        assert!(result.unwrap().is_ok(), "SetOSDefault should succeed");

        assert_eq!(
            bus.read_byte(pb),
            0x00,
            "SetOSDefault must not modify caller's sdReserved input byte"
        );
        assert_eq!(
            bus.read_byte(pb + 1),
            0x02,
            "SetOSDefault must not modify caller's sdOSType input byte"
        );
        assert_eq!(
            bus.read_byte(pb + 2),
            0xCC,
            "SetOSDefault must not clobber memory past DefOSRec at byte +2"
        );
        assert_eq!(
            bus.read_byte(pb + 3),
            0xCC,
            "SetOSDefault must not clobber memory past DefOSRec at byte +3"
        );
    }

    #[test]
    fn getosdefault_writes_two_bytes_and_preserves_following_memory() {
        // Inside Macintosh Volume V (1986), p. V-355: DefOSRec is two bytes
        // (sdReserved, sdOSType), and Macintosh OS is represented by
        // sdOSType=1.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = bus.alloc(4);
        bus.write_byte(pb, 0xAA);
        bus.write_byte(pb + 1, 0xBB);
        bus.write_byte(pb + 2, 0xC3);
        bus.write_byte(pb + 3, 0xD4);

        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x84, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetOSDefault should be handled");
        assert!(result.unwrap().is_ok(), "GetOSDefault should succeed");
        assert_eq!(
            bus.read_byte(pb),
            0,
            "GetOSDefault should return sdReserved as 0"
        );
        assert_eq!(
            bus.read_byte(pb + 1),
            1,
            "GetOSDefault should default sdOSType to Macintosh OS (1)"
        );
        assert_eq!(
            bus.read_byte(pb + 2),
            0xC3,
            "GetOSDefault must not overwrite bytes beyond DefOSRec"
        );
        assert_eq!(
            bus.read_byte(pb + 3),
            0xD4,
            "GetOSDefault must preserve trailing bytes in caller memory"
        );
    }

    #[test]
    fn test_free_mem() {
        // FreeMem returns `free_heap_estimate` clamped to [24MB, 64MB].
        // setup() leaves HEAP_END/APPL_LIMIT at 0 so the floor (24MB) wins.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0x1C, &mut cpu, &mut bus);
        assert!(result.is_some(), "FreeMem should be handled");
        assert!(result.unwrap().is_ok(), "FreeMem should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            24 * 1024 * 1024,
            "FreeMem should return 24MB clamp floor in D0"
        );
    }

    #[test]
    fn test_max_mem() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0x1D, &mut cpu, &mut bus);
        assert!(result.is_some(), "MaxMem should be handled");
        assert!(result.unwrap().is_ok(), "MaxMem should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            24 * 1024 * 1024,
            "MaxMem should return 24MB clamp floor in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            24 * 1024 * 1024,
            "MaxMem should return 24MB clamp floor in A0"
        );
    }

    #[test]
    fn test_compact_mem() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 1024); // requested size
        let result = dispatcher.dispatch_memory(false, 0x4C, &mut cpu, &mut bus);
        assert!(result.is_some(), "CompactMem should be handled");
        assert!(result.unwrap().is_ok(), "CompactMem should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            24 * 1024 * 1024,
            "CompactMem should return 24MB clamp floor in D0"
        );
    }

    #[test]
    fn test_set_handle_size() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // First create a handle of size 128
        cpu.write_reg(Register::D0, 128);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        let handle = cpu.read_reg(Register::A0);
        let old_ptr = bus.read_long(handle);
        // Write some data into the block
        bus.write_long(old_ptr, 0xDEADBEEF);
        bus.write_long(old_ptr + 4, 0xCAFEBABE);
        // Resize to 2048
        cpu.write_reg(Register::A0, handle);
        cpu.write_reg(Register::D0, 2048);
        let result = dispatcher.dispatch_memory(false, 0x24, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetHandleSize should be handled");
        assert!(result.unwrap().is_ok(), "SetHandleSize should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetHandleSize should set D0 to 0 (noErr)"
        );
        // Handle should now point to new block with old data preserved
        let new_ptr = bus.read_long(handle);
        assert_eq!(
            bus.read_long(new_ptr),
            0xDEADBEEF,
            "Data should be preserved after resize"
        );
        assert_eq!(
            bus.read_long(new_ptr + 4),
            0xCAFEBABE,
            "Data should be preserved after resize"
        );
        // New block should be tracked with new size
        let new_size = bus.get_alloc_size(new_ptr).unwrap_or(0);
        assert_eq!(new_size, 2048, "New block should be 2048 bytes");
    }

    #[test]
    fn test_reallocate_handle() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // First create a handle via NewHandle
        cpu.write_reg(Register::D0, 128);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok(), "NewHandle (setup) should succeed");
        let handle = cpu.read_reg(Register::A0);
        let old_ptr = bus.read_long(handle);

        // Now reallocate it with a new size
        cpu.write_reg(Register::A0, handle);
        cpu.write_reg(Register::D0, 2048);
        let result = dispatcher.dispatch_memory(false, 0x27, &mut cpu, &mut bus);
        assert!(result.is_some(), "ReallocateHandle should be handled");
        assert!(result.unwrap().is_ok(), "ReallocateHandle should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "ReallocateHandle should set D0 to 0"
        );
        let new_ptr = bus.read_long(handle);
        assert!(
            new_ptr >= 0x200000,
            "ReallocateHandle should update handle to a valid pointer, got ${:08X}",
            new_ptr
        );
        assert_ne!(
            new_ptr, old_ptr,
            "ReallocateHandle should allocate a new block (different from old ptr)"
        );
    }

    #[test]
    fn test_recover_handle() {
        // Per IM:V V-579, RecoverHandle searches the master pointer
        // table and returns the EXISTING handle that owns the given
        // ptr. Allocate a real handle, then verify RecoverHandle on
        // its data ptr returns that same handle.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        cpu.write_reg(Register::D0, 100);
        let _ = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus); // NewHandle
        let original_handle = cpu.read_reg(Register::A0);
        let data_ptr = bus.read_long(original_handle);

        cpu.write_reg(Register::A0, data_ptr);
        let result = dispatcher.dispatch_memory(false, 0x28, &mut cpu, &mut bus);
        assert!(result.is_some(), "RecoverHandle should be handled");
        assert!(result.unwrap().is_ok(), "RecoverHandle should succeed");
        assert_eq!(
            cpu.read_reg(Register::A0),
            original_handle,
            "RecoverHandle must return the existing handle, not a fresh copy"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "RecoverHandle should set D0 to 0"
        );
    }

    #[test]
    fn test_dispose_then_recover_returns_stale_handle() {
        // On real Mac OS, DisposeHandle frees the master pointer slot but
        // does NOT zero it. RecoverHandle scans all slots (including freed
        // ones), so it still finds the stale data address and returns the
        // freed handle rather than nil. IM:V V-579.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 100);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let handle = cpu.read_reg(Register::A0);
        let data_ptr = bus.read_long(handle);
        cpu.write_reg(Register::A0, handle);
        dispatcher
            .dispatch_memory(false, 0x23, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        cpu.write_reg(Register::A0, data_ptr);
        dispatcher
            .dispatch_memory(false, 0x28, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_ne!(
            cpu.read_reg(Register::A0),
            0,
            "RecoverHandle after DisposeHandle must return stale freed handle (not nil), per IM:V V-579 scan-all-slots behavior"
        );
    }

    #[test]
    fn test_get_ptr_size() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // First allocate a pointer of size 512
        cpu.write_reg(Register::D0, 512);
        let result = dispatcher.dispatch_memory(false, 0x1E, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        let ptr = cpu.read_reg(Register::A0);
        // Now get its size
        cpu.write_reg(Register::A0, ptr);
        let result = dispatcher.dispatch_memory(false, 0x21, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetPtrSize should be handled");
        assert!(result.unwrap().is_ok(), "GetPtrSize should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            512,
            "GetPtrSize should return 512 in D0"
        );
    }

    // SetPtrSize must keep the pointer stable per IM:Memory 1992 p.2-44
    // ("SetPtrSize doesn't move the pointer").
    #[test]
    fn test_set_ptr_size_shrink_preserves_pointer() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // NewPtr(256)
        cpu.write_reg(Register::D0, 256);
        dispatcher
            .dispatch_memory(false, 0x1E, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let original_ptr = cpu.read_reg(Register::A0);
        assert_ne!(original_ptr, 0);
        // SetPtrSize(128)
        cpu.write_reg(Register::A0, original_ptr);
        cpu.write_reg(Register::D0, 128);
        dispatcher
            .dispatch_memory(false, 0x20, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::D0) as i32, 0, "noErr expected");
        assert_eq!(
            cpu.read_reg(Register::A0),
            original_ptr,
            "SetPtrSize must not move the pointer (IM:Memory 1992 p.2-44)"
        );
        // GetPtrSize should now read 128 at the ORIGINAL pointer.
        cpu.write_reg(Register::A0, original_ptr);
        dispatcher
            .dispatch_memory(false, 0x21, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(
            cpu.read_reg(Register::D0),
            128,
            "GetPtrSize on the original pointer must reflect the new logical size"
        );
    }

    // Attempting to grow a Ptr beyond its aligned capacity returns
    // memFullErr rather than silently moving the pointer. This matches
    // IM:Memory 1992's "SetPtrSize doesn't move the pointer" contract.
    #[test]
    fn test_set_ptr_size_grow_beyond_capacity_returns_memfullerr() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 128);
        dispatcher
            .dispatch_memory(false, 0x1E, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let ptr = cpu.read_reg(Register::A0);
        cpu.write_reg(Register::A0, ptr);
        cpu.write_reg(Register::D0, 4096); // way beyond aligned 128
        dispatcher
            .dispatch_memory(false, 0x20, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -108,
            "SetPtrSize beyond aligned capacity must return memFullErr (-108)"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            ptr,
            "SetPtrSize on failure must leave A0 untouched"
        );
    }

    #[test]
    fn test_ins_time() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000); // TMTask pointer
        let result = dispatcher.dispatch_memory(false, 0x58, &mut cpu, &mut bus);
        assert!(result.is_some(), "InsTime should be handled");
        assert!(result.unwrap().is_ok(), "InsTime should succeed (no-op)");
    }

    #[test]
    fn test_rmv_time() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x59, &mut cpu, &mut bus);
        assert!(result.is_some(), "RmvTime should be handled");
        assert!(result.unwrap().is_ok(), "RmvTime should succeed (no-op)");
    }

    #[test]
    fn test_prime_time() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000); // TMTask pointer
        cpu.write_reg(Register::D0, 1000); // delay
        let result = dispatcher.dispatch_memory(false, 0x5A, &mut cpu, &mut bus);
        assert!(result.is_some(), "PrimeTime should be handled");
        assert!(result.unwrap().is_ok(), "PrimeTime should succeed (no-op)");
    }

    #[test]
    fn test_prime_time_rounds_up_to_tick_boundary() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let task_ptr = 0x200000;

        bus.write_long(0x016A, 100);
        cpu.write_reg(Register::A0, task_ptr);
        let result = dispatcher.dispatch_memory(false, 0x58, &mut cpu, &mut bus);
        assert!(result.is_some(), "InsTime should be handled");
        assert!(result.unwrap().is_ok(), "InsTime should succeed");

        cpu.write_reg(Register::A0, task_ptr);
        cpu.write_reg(Register::D0, 33);
        let result = dispatcher.dispatch_memory(false, 0x5A, &mut cpu, &mut bus);
        assert!(result.is_some(), "PrimeTime should be handled");
        assert!(result.unwrap().is_ok(), "PrimeTime should succeed");

        let task = dispatcher
            .timer_tasks
            .iter()
            .find(|task| task.task_ptr == task_ptr)
            .expect("timer task should be queued");
        assert!(task.active, "PrimeTime should activate the task");
        assert_eq!(
            task.fire_at_tick, 102,
            "33 ms should round up to two 60 Hz ticks from TickCount 100"
        );
    }

    #[test]
    fn test_control_set_mode_uses_vdpginfo_pointer() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = 0x300000u32;
        let vdpg_info = 0x310000u32;

        dispatcher.screen_mode.0 = 0x01F80000;
        bus.write_word(pb + 26, 2); // csCode = cscSetMode
        bus.write_long(pb + 28, vdpg_info); // csParam = VDPgInfoPtr

        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x04, &mut cpu, &mut bus);
        assert!(result.is_some(), "PBControl should be handled");
        assert!(result.unwrap().is_ok(), "PBControl should succeed");

        assert_eq!(
            bus.read_word(vdpg_info + 6),
            0,
            "SetMode should return page 0 through the pointed VDPgInfo"
        );
        assert_eq!(
            bus.read_long(vdpg_info + 8),
            0x01F80000,
            "SetMode should return the framebuffer base through the pointed VDPgInfo"
        );
        assert_eq!(
            bus.read_long(pb + 36),
            0,
            "SetMode should not scribble past the param block by treating VDPgInfo as inline"
        );
    }

    #[test]
    fn test_microseconds() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // setup() already sets TickCount at $016A to 100
        let ticks = 100u64;
        // 1 tick = 16,625 µs (1/60.15 Hz; Guide to Macintosh Family Hardware 2nd Ed., p. 6-798)
        let expected_usecs = ticks * 16_625;
        let result = dispatcher.dispatch_memory(false, 0x93, &mut cpu, &mut bus);
        assert!(result.is_some(), "Microseconds should be handled");
        assert!(result.unwrap().is_ok(), "Microseconds should succeed");
        // D0 = low 32 bits, A0 = high 32 bits (executor emustubs.cpp convention,
        // retained for Executor-style register-reader callers)
        let d0 = cpu.read_reg(Register::D0) as u64;
        let a0 = cpu.read_reg(Register::A0) as u64;
        let actual_usecs = (a0 << 32) | d0;
        assert_eq!(
            actual_usecs, expected_usecs,
            "Microseconds should return ticks*16625 = {} in D0(lo):A0(hi), got {}",
            expected_usecs, actual_usecs
        );
    }

    #[test]
    fn microseconds_does_not_speculatively_write_through_a0_on_entry() {
        // The MPW Universal Headers `Timer.h` declares Microseconds as
        // FOURWORDINLINE($A193, $225F, $22C8, $2280). The trap itself
        // returns the count in registers (D0 = lo, A0 = hi); the
        // caller-side inline glue ($225F MOVEA.L (A7)+, A1; $22C8
        // MOVE.L A0, (A1)+; $2280 MOVE.L D0, (A1)) then writes the
        // 64-bit result through the caller's UnsignedWide pointer.
        //
        // Under that FOURWORDINLINE pattern, register A0 on entry to
        // the trap is uninitialised scratch — the buffer pointer is
        // still on the stack and won't be moved into A1 until *after*
        // the trap returns. The HLE must NOT speculatively write
        // through whatever value A0 happens to hold, because that
        // would corrupt unrelated guest memory in the common case.
        // Verify the HLE leaves the byte under A0 alone.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let unrelated = 0x322000u32;
        // Pre-fill the "unrelated" memory at the address that A0
        // happens to point to; a buggy HLE that speculatively writes
        // through A0 would clobber this sentinel.
        bus.write_long(unrelated, 0x11223344u32);
        bus.write_long(unrelated + 4, 0x55667788u32);
        cpu.write_reg(Register::A0, unrelated);

        let result = dispatcher.dispatch_memory(false, 0x93, &mut cpu, &mut bus);
        assert!(result.is_some(), "Microseconds should be handled");
        assert!(result.unwrap().is_ok(), "Microseconds should succeed");

        assert_eq!(
            bus.read_long(unrelated),
            0x11223344u32,
            "Microseconds must not write through whatever value A0 held on entry"
        );
        assert_eq!(
            bus.read_long(unrelated + 4),
            0x55667788u32,
            "Microseconds must not write past whatever value A0 held on entry"
        );
    }

    #[test]
    fn readxpram_zero_fills_requested_count_and_returns_noerr() {
        // Inside Macintosh Volume V (1986), p. V-519: ReadXPRam uses D0
        // high-word count and A0 destination pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let dest = 0x322000u32;
        bus.write_bytes(dest, &[0xAA, 0xBB, 0xCC, 0xDD, 0xEE]);
        cpu.write_reg(Register::D0, (4u32 << 16) | 0x0012u32);
        cpu.write_reg(Register::A0, dest);

        let result = dispatcher.dispatch_memory(false, 0x51, &mut cpu, &mut bus);
        assert!(result.is_some(), "ReadXPRam should be handled");
        assert!(result.unwrap().is_ok(), "ReadXPRam should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "ReadXPRam should return noErr"
        );
        assert_eq!(bus.read_bytes(dest, 4), vec![0, 0, 0, 0]);
        assert_eq!(
            bus.read_byte(dest + 4),
            0xEE,
            "ReadXPRam should zero exactly count bytes"
        );
    }

    #[test]
    fn readxpram_uses_d0_count_offset_and_a0_destptr_register_calling_convention() {
        // Inside Macintosh Volume V (1986), p. V-519: ReadXPRam register
        // calling convention does not consume stack arguments.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let dest = 0x322040u32;
        bus.write_bytes(dest, &[0x11, 0x22, 0x33, 0x44]);
        cpu.write_reg(Register::D0, (3u32 << 16) | 0x00FFu32);
        cpu.write_reg(Register::A0, dest);

        let result = dispatcher.dispatch_memory(false, 0x51, &mut cpu, &mut bus);
        assert!(result.is_some(), "ReadXPRam should be handled");
        assert!(result.unwrap().is_ok(), "ReadXPRam should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "ReadXPRam should preserve A7 in register-calling convention"
        );
        assert_eq!(bus.read_bytes(dest, 3), vec![0, 0, 0]);
        assert_eq!(bus.read_byte(dest + 3), 0x44);
    }

    #[test]
    fn readxpram_five_call_composition_preserves_stack_across_varying_count_offset() {
        // Mirrors band B2 of the a051_a052_xpram_strict bake fixture: 5
        // successive _ReadXPRam dispatches with varying D0 packed
        // (count << 16) | offset values must each preserve A7. Per
        // IM:V V-519 the register-only ABI takes A0 + D0 inputs and
        // returns OSErr in D0; no Pascal stack frame is consumed.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let dest = 0x322200u32;
        let sp_before = cpu.read_reg(Register::A7);

        let cases: [(u32, u32); 5] = [
            ((1u32 << 16) | 0x0014, dest),     // count=1 offset=20 (start of XPRAM)
            ((4u32 << 16) | 0x0080, dest + 8), // count=4 offset=128
            ((8u32 << 16) | 0x00FF, dest + 16), // count=8 offset=255 (last byte)
            ((2u32 << 16) | 0x0000, dest + 32), // count=2 offset=0 (SysParam start)
            ((16u32 << 16) | 0x004B, dest + 48), // count=16 offset=75
        ];

        for (d0, a0) in cases.iter() {
            cpu.write_reg(Register::D0, *d0);
            cpu.write_reg(Register::A0, *a0);
            let result = dispatcher.dispatch_memory(false, 0x51, &mut cpu, &mut bus);
            assert!(result.is_some(), "ReadXPRam should be handled");
            assert!(result.unwrap().is_ok(), "ReadXPRam should return");
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "ReadXPRam should return noErr regardless of count/offset"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "5 successive ReadXPRam calls must preserve A7 in aggregate"
        );
    }

    #[test]
    fn writexpram_noop_returns_noerr_in_hle_without_persistent_xpram() {
        // Inside Macintosh Volume V (1986), p. V-519: WriteXPRam uses D0
        // count/offset + A0 source pointer. HLE returns noErr without
        // persistent XPRAM storage.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x322080u32;
        bus.write_bytes(src, &[0x9A, 0xBC, 0xDE, 0xF0]);
        cpu.write_reg(Register::D0, (4u32 << 16) | 0x0042u32);
        cpu.write_reg(Register::A0, src);

        let result = dispatcher.dispatch_memory(false, 0x52, &mut cpu, &mut bus);
        assert!(result.is_some(), "WriteXPRam should be handled");
        assert!(result.unwrap().is_ok(), "WriteXPRam should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "WriteXPRam should return noErr"
        );
        assert_eq!(
            bus.read_bytes(src, 4),
            vec![0x9A, 0xBC, 0xDE, 0xF0],
            "WriteXPRam should not mutate caller source bytes"
        );
    }

    #[test]
    fn writexpram_uses_d0_count_offset_and_a0_srcptr_register_calling_convention() {
        // Inside Macintosh Volume V (1986), p. V-519: WriteXPRam register
        // convention should preserve A7.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let src = 0x3220C0u32;
        bus.write_bytes(src, &[0x01, 0x23, 0x45]);
        cpu.write_reg(Register::D0, (3u32 << 16) | 0x0001u32);
        cpu.write_reg(Register::A0, src);

        let result = dispatcher.dispatch_memory(false, 0x52, &mut cpu, &mut bus);
        assert!(result.is_some(), "WriteXPRam should be handled");
        assert!(result.unwrap().is_ok(), "WriteXPRam should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "WriteXPRam should not consume stack arguments"
        );
    }

    #[test]
    fn writexpram_five_call_composition_preserves_stack_and_source_across_varying_count_offset() {
        // Mirrors band B4 of the a051_a052_xpram_strict bake fixture:
        // 5 successive _WriteXPRam dispatches with varying D0 packed
        // (count << 16) | offset values must each preserve A7 AND
        // leave the caller's source bytes untouched. Per IM:V V-519
        // the register-only ABI treats A0 as a READ-ONLY source
        // pointer (the trap propagates the bytes OUT to the clock
        // chip) — the low-memory source buffer is the authoritative
        // input, never overwritten by the trap.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x322300u32;
        let sentinel: [u8; 16] = [
            0x4B, 0x58, 0x44, 0x50, 0x01, 0x02, 0x03, 0x04, 0xAA, 0xBB, 0xCC, 0xDD, 0x10, 0x20,
            0x30, 0x40,
        ];
        bus.write_bytes(src, &sentinel);
        let sp_before = cpu.read_reg(Register::A7);

        let cases: [u32; 5] = [
            (1u32 << 16) | 0x0014,  // count=1 offset=20
            (4u32 << 16) | 0x0080,  // count=4 offset=128
            (8u32 << 16) | 0x00FF,  // count=8 offset=255
            (2u32 << 16) | 0x0000,  // count=2 offset=0
            (16u32 << 16) | 0x004B, // count=16 offset=75
        ];

        for d0 in cases.iter() {
            cpu.write_reg(Register::D0, *d0);
            cpu.write_reg(Register::A0, src);
            let result = dispatcher.dispatch_memory(false, 0x52, &mut cpu, &mut bus);
            assert!(result.is_some(), "WriteXPRam should be handled");
            assert!(result.unwrap().is_ok(), "WriteXPRam should return");
            assert_eq!(
                cpu.read_reg(Register::D0),
                0,
                "WriteXPRam should return noErr regardless of count/offset"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "5 successive WriteXPRam calls must preserve A7 in aggregate"
        );
        assert_eq!(
            bus.read_bytes(src, 16),
            sentinel.to_vec(),
            "5 successive WriteXPRam calls must leave the caller's source buffer untouched"
        );
    }

    #[test]
    fn getdefaultstartup_fills_4_byte_defstartrec_through_a0() {
        // Inside Macintosh Volume V (1986), p. V-529: GetDefaultStartup
        // writes a DefStartRec through A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let ptr = 0x322100u32;
        bus.write_long(ptr, 0xDEAD_BEEF);
        cpu.write_reg(Register::A0, ptr);

        let result = dispatcher.dispatch_memory(false, 0x7D, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetDefaultStartup should be handled");
        assert!(result.unwrap().is_ok(), "GetDefaultStartup should return");
        assert_eq!(
            bus.read_long(ptr),
            0,
            "GetDefaultStartup should return the initial in-session DefStartRec in HLE"
        );
    }

    #[test]
    fn getdefaultstartup_uses_a0_parameter_block_without_stack_arguments() {
        // Inside Macintosh Volume V (1986), p. V-529: GetDefaultStartup
        // takes A0 parameter block input.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0);

        let result = dispatcher.dispatch_memory(false, 0x7D, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetDefaultStartup should be handled");
        assert!(result.unwrap().is_ok(), "GetDefaultStartup should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "GetDefaultStartup should preserve A7"
        );
    }

    #[test]
    fn setdefaultstartup_updates_getdefaultstartup_and_preserves_stack_pointer() {
        // Inside Macintosh Volume V (1986), p. V-529: SetDefaultStartup
        // consumes a DefStartRec from A0 and GetDefaultStartup should
        // return the same in-session bytes afterward.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let set_ptr = 0x322140u32;
        let get_ptr = 0x322180u32;
        bus.write_long(set_ptr, 0xA1B2_C3D4);
        bus.write_long(get_ptr, 0xDEAD_BEEF);
        cpu.write_reg(Register::A0, set_ptr);
        cpu.write_reg(Register::D0, 0x1357_9BDF);

        let result = dispatcher.dispatch_memory(false, 0x7E, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetDefaultStartup should be handled");
        assert!(result.unwrap().is_ok(), "SetDefaultStartup should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SetDefaultStartup should preserve A7"
        );
        assert_eq!(
            bus.read_long(set_ptr),
            0xA1B2_C3D4,
            "SetDefaultStartup should not mutate the caller DefStartRec"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0x1357_9BDF,
            "SetDefaultStartup should not clobber D0 in the PROCEDURE path"
        );

        cpu.write_reg(Register::A0, get_ptr);
        let result = dispatcher.dispatch_memory(false, 0x7D, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetDefaultStartup should be handled after SetDefaultStartup");
        assert!(
            result.unwrap().is_ok(),
            "GetDefaultStartup should return after SetDefaultStartup"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "GetDefaultStartup should preserve A7"
        );
        assert_eq!(
            bus.read_long(get_ptr),
            0xA1B2_C3D4,
            "GetDefaultStartup should return the record stored by SetDefaultStartup"
        );
    }

    #[test]
    fn test_hnopurge() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x4A, &mut cpu, &mut bus);
        assert!(result.is_some(), "HNoPurge ($A04A) should be handled");
        assert!(result.unwrap().is_ok(), "HNoPurge should succeed (no-op)");
    }

    #[test]
    fn test_hget_state() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        let result = dispatcher.dispatch_memory(false, 0x69, &mut cpu, &mut bus);
        assert!(result.is_some(), "HGetState should be handled");
        assert!(result.unwrap().is_ok(), "HGetState should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HGetState should return 0 in D0"
        );
    }

    #[test]
    fn test_hset_state() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0x200000);
        cpu.write_reg(Register::D0, 0x40); // some state byte
        let result = dispatcher.dispatch_memory(false, 0x6A, &mut cpu, &mut bus);
        assert!(result.is_some(), "HSetState should be handled");
        assert!(result.unwrap().is_ok(), "HSetState should succeed (no-op)");
    }

    #[test]
    fn test_memorydispatch_unlockmemory_returns_notlockederr_for_unlocked_range() {
        // Inside Macintosh: Memory (1992), 3-30: UnlockMemory returns
        // notLockedErr (-623) when the specified range is not locked.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 3); // UnlockMemory selector
        cpu.write_reg(Register::A0, 0x0020_0123);
        cpu.write_reg(Register::A1, 0x180);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(result.is_some(), "MemoryDispatch should handle selector 3");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 3 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-623i32) as u32,
            "UnlockMemory should return notLockedErr (-623) for unlocked pages"
        );
    }

    #[test]
    fn test_memorydispatch_unholdmemory_returns_nothelderr_for_never_held_range() {
        // Inside Macintosh: Memory (1992), 3-25 to 3-27: UnholdMemory
        // returns notHeldErr (-621) when the requested pages were never held.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 1); // UnholdMemory selector
        cpu.write_reg(Register::A0, 0x0020_0456);
        cpu.write_reg(Register::A1, 0x200);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 1");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 1 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-621i32) as u32,
            "UnholdMemory should return notHeldErr (-621) for never-held pages"
        );
        assert_eq!(
            sp_pre, sp_post,
            "UnholdMemory should preserve the caller's stack pointer for never-held pages"
        );
    }

    #[test]
    fn test_memorydispatch_holdmemory_round_trip_releases_idempotently() {
        // Inside Macintosh: Memory (1992), 3-25 to 3-27: HoldMemory
        // rounds the range to whole pages, and UnholdMemory remains
        // noErr on a range that has already been held and released.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let base = bus.alloc(0x3000);
        let hold_start = base + 0x11;
        let hold_count = 0x180u32;

        cpu.write_reg(Register::D0, 0); // HoldMemory selector
        cpu.write_reg(Register::A0, hold_start);
        cpu.write_reg(Register::A1, hold_count);
        let sp_pre = cpu.read_reg(Register::A7);
        let hold_once = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            hold_once.is_some(),
            "MemoryDispatch should handle selector 0"
        );
        assert!(hold_once.unwrap().is_ok(), "HoldMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HoldMemory should return noErr on a live logical-RAM range"
        );

        cpu.write_reg(Register::D0, 0); // HoldMemory selector again
        cpu.write_reg(Register::A0, hold_start);
        cpu.write_reg(Register::A1, hold_count);
        let hold_twice = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            hold_twice.is_some(),
            "MemoryDispatch should handle selector 0"
        );
        assert!(
            hold_twice.unwrap().is_ok(),
            "HoldMemory should return on repeat"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HoldMemory should remain idempotent on the same page span"
        );

        cpu.write_reg(Register::D0, 1); // UnholdMemory selector
        cpu.write_reg(Register::A0, hold_start);
        cpu.write_reg(Register::A1, hold_count);
        let unhold_once = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unhold_once.is_some(),
            "MemoryDispatch should handle selector 1"
        );
        assert!(unhold_once.unwrap().is_ok(), "UnholdMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnholdMemory should return noErr after releasing one hold"
        );

        cpu.write_reg(Register::D0, 1); // UnholdMemory selector again
        cpu.write_reg(Register::A0, hold_start);
        cpu.write_reg(Register::A1, hold_count);
        let unhold_twice = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unhold_twice.is_some(),
            "MemoryDispatch should handle selector 1"
        );
        assert!(
            unhold_twice.unwrap().is_ok(),
            "UnholdMemory should return on second release"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnholdMemory should return noErr while the second hold is still tracked"
        );

        cpu.write_reg(Register::D0, 1); // UnholdMemory selector a third time
        cpu.write_reg(Register::A0, hold_start);
        cpu.write_reg(Register::A1, hold_count);
        let unhold_third = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unhold_third.is_some(),
            "MemoryDispatch should handle selector 1"
        );
        assert!(unhold_third.unwrap().is_ok(), "UnholdMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnholdMemory should remain noErr after the last tracked hold is released"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "HoldMemory/UnholdMemory should preserve the caller's stack pointer"
        );
    }

    #[test]
    fn test_memorydispatch_holdmemory_invalid_range_returns_noerr_and_preserves_stack() {
        // Inside Macintosh: Memory (1992), 3-26: HoldMemory returns
        // noErr on the BasiliskII-observed invalid-range path.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x1000;
        cpu.write_reg(Register::D0, 0); // HoldMemory selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0x200);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 0");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 0 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HoldMemory should return noErr for BasiliskII invalid-range behavior"
        );
        assert_eq!(
            sp_pre, sp_post,
            "HoldMemory should preserve the caller's stack pointer for invalid ranges"
        );
    }

    #[test]
    fn test_memorydispatch_unholdmemory_invalid_range_returns_noerr_and_preserves_stack() {
        // Inside Macintosh: Memory (1992), 3-27: UnholdMemory returns
        // noErr on the BasiliskII-observed invalid-range path.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x0800;
        cpu.write_reg(Register::D0, 1); // UnholdMemory selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0x300);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 1");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 1 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnholdMemory should return noErr for BasiliskII invalid-range behavior"
        );
        assert_eq!(
            sp_pre, sp_post,
            "UnholdMemory should preserve the caller's stack pointer for invalid ranges"
        );
    }

    #[test]
    fn test_memorydispatch_lockmemory_invalid_range_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-28 and 3-29: LockMemory and
        // LockMemoryContiguous return paramErr (-50) for invalid ranges.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x0400;
        cpu.write_reg(Register::D0, 2); // LockMemory selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0x500);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 2");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 2 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "LockMemory should return paramErr (-50) for non-RAM ranges"
        );
        assert_eq!(
            sp_pre, sp_post,
            "LockMemory should preserve the caller's stack pointer for invalid ranges"
        );
    }

    #[test]
    fn test_memorydispatch_lockmemorycontiguous_invalid_range_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-29: LockMemoryContiguous returns
        // paramErr (-50) for an invalid parameter list.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x1400;
        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0x280);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 4");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 4 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "LockMemoryContiguous should return paramErr (-50) for non-RAM ranges"
        );
        assert_eq!(
            sp_pre, sp_post,
            "LockMemoryContiguous should preserve the caller's stack pointer for invalid ranges"
        );
    }

    #[test]
    fn test_memorydispatch_lockmemorycontiguous_zero_length_invalid_range_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-29: LockMemoryContiguous returns
        // paramErr (-50) for an invalid parameter list. Zero-length ranges
        // still need a plausible logical-RAM start address.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x2000;
        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(result.is_some(), "MemoryDispatch should handle selector 4");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 4 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "LockMemoryContiguous should return paramErr (-50) for a zero-length range outside logical RAM"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "LockMemoryContiguous should not consume a Pascal stack frame"
        );
    }

    #[test]
    fn test_memorydispatch_unlockmemory_invalid_range_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-30: UnlockMemory returns
        // paramErr (-50) for an invalid parameter list.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let invalid_start = bus.ram_size() + 0x2000;
        cpu.write_reg(Register::D0, 3); // UnlockMemory selector
        cpu.write_reg(Register::A0, invalid_start);
        cpu.write_reg(Register::A1, 0x180);
        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 3");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 3 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "UnlockMemory should return paramErr (-50) for non-RAM ranges"
        );
        assert_eq!(
            sp_pre, sp_post,
            "UnlockMemory should preserve the caller's stack pointer for invalid ranges"
        );
    }

    #[test]
    fn test_memorydispatch_unlockmemory_reverses_lockmemorycontiguous_on_page_rounded_range() {
        // Inside Macintosh: Memory (1992), 3-29 to 3-30: LockMemoryContiguous
        // and UnlockMemory round ranges to page boundaries, and UnlockMemory
        // undoes both LockMemory and LockMemoryContiguous.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let block_start = bus.alloc(0x3000);
        let rounded_page = (block_start + 0x0FFF) & !0x0FFF;
        let lock_start = rounded_page + 0x10;
        let lock_count = 0x20u32;
        let unlock_start = rounded_page + 0x80;
        let unlock_count = 0x30u32;

        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, lock_start);
        cpu.write_reg(Register::A1, lock_count);
        let lock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            lock_result.is_some(),
            "MemoryDispatch should handle selector 4"
        );
        assert!(
            lock_result.unwrap().is_ok(),
            "LockMemoryContiguous should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LockMemoryContiguous should return noErr"
        );

        cpu.write_reg(Register::D0, 3); // UnlockMemory selector
        cpu.write_reg(Register::A0, unlock_start);
        cpu.write_reg(Register::A1, unlock_count);
        let unlock_once = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unlock_once.is_some(),
            "MemoryDispatch should handle selector 3"
        );
        assert!(unlock_once.unwrap().is_ok(), "UnlockMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnlockMemory should return noErr when undoing LockMemoryContiguous for the rounded page"
        );

        cpu.write_reg(Register::D0, 3); // UnlockMemory selector again
        cpu.write_reg(Register::A0, unlock_start);
        cpu.write_reg(Register::A1, unlock_count);
        let unlock_twice = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unlock_twice.is_some(),
            "MemoryDispatch should handle selector 3"
        );
        assert!(
            unlock_twice.unwrap().is_ok(),
            "UnlockMemory should return on second attempt"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-623i32) as u32,
            "UnlockMemory should return notLockedErr (-623) after the prior unlock released the rounded page"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_requires_locked_range() {
        // Inside Macintosh: Memory (1992), 3-32: GetPhysical requires the
        // logical range to be locked and returns notLockedErr (-623) if not.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.alloc(512);
        let logical_count = 128u32;
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);
        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 1); // request one entry
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(result.is_some(), "MemoryDispatch should handle selector 5");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 5 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-623i32) as u32,
            "GetPhysical should return notLockedErr (-623) for unlocked ranges"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "GetPhysical should return translated-entry count 0 on lock failure"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_invalid_logical_range_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-32: GetPhysical returns
        // paramErr (-50) when asked to translate non-logical-RAM addresses.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.ram_size() + 0x4000;
        let logical_count = 256u32;
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);
        bus.write_long(table + 8, 0x1111_1111);
        bus.write_long(table + 12, 0x2222_2222);

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 1);
        let sp_before = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_after = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 5");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 5 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "GetPhysical should return paramErr (-50) for non-RAM logical ranges"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "GetPhysical should return translated-entry count 0 on paramErr"
        );
        assert_eq!(
            sp_before, sp_after,
            "GetPhysical should preserve the caller's stack pointer on paramErr"
        );
        assert_eq!(
            bus.read_long(table + 8),
            0x1111_1111,
            "GetPhysical should preserve translation entries on paramErr"
        );
        assert_eq!(
            bus.read_long(table + 12),
            0x2222_2222,
            "GetPhysical should preserve translation entries on paramErr"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_null_table_returns_paramerr() {
        // Inside Macintosh: Memory (1992), 3-32: GetPhysical returns paramErr
        // for an invalid parameter list (NIL translation-table pointer).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::A1, 1);
        let sp_before = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_after = cpu.read_reg(Register::A7);
        assert!(result.is_some(), "MemoryDispatch should handle selector 5");
        assert!(
            result.unwrap().is_ok(),
            "MemoryDispatch selector 5 should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "GetPhysical should return paramErr (-50) for NIL translation table"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "GetPhysical should return translated-entry count 0 for NIL translation table"
        );
        assert_eq!(
            sp_before, sp_after,
            "GetPhysical should preserve the caller's stack pointer for NIL translation table"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_fills_identity_mapping_when_locked() {
        // Inside Macintosh: Memory (1992), 3-31 to 3-32: on success,
        // GetPhysical writes translation entries and returns entry count.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.alloc(1024) + 37; // force non-page-aligned start
        let logical_count = 700u32;
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);

        cpu.write_reg(Register::D0, 2); // LockMemory selector
        cpu.write_reg(Register::A0, logical_start);
        cpu.write_reg(Register::A1, logical_count);
        let lock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            lock_result.is_some(),
            "MemoryDispatch should handle selector 2"
        );
        assert!(lock_result.unwrap().is_ok(), "LockMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LockMemory should return noErr before GetPhysical"
        );

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 1);
        let get_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            get_result.is_some(),
            "MemoryDispatch should handle selector 5"
        );
        assert!(get_result.unwrap().is_ok(), "GetPhysical should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "GetPhysical should return noErr on locked range"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "GetPhysical should report one translated physical entry"
        );
        assert_eq!(
            bus.read_long(table + 8),
            logical_start,
            "GetPhysical should emit identity physical start in entry[0]"
        );
        assert_eq!(
            bus.read_long(table + 12),
            logical_count,
            "GetPhysical should emit identity physical count in entry[0]"
        );
        assert_eq!(
            bus.read_long(table),
            logical_start,
            "GetPhysical should leave the logical start unchanged when the range fits in one physical entry"
        );
        assert_eq!(
            bus.read_long(table + 4),
            logical_count,
            "GetPhysical should leave the logical count unchanged when the range fits in one physical entry"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_entrycount_zero_returns_paramerr_and_required_entries() {
        // BasiliskII returns paramErr (-50) and the required translated-entry
        // count for a locked non-empty range queried with physicalEntryCount=0,
        // while preserving the caller's stack pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.alloc(4096) + 99;
        let logical_count = 1536u32;
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);
        bus.write_long(table + 8, 0x1111_2222);
        bus.write_long(table + 12, 0x3333_4444);

        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, logical_start);
        cpu.write_reg(Register::A1, logical_count);
        let lock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            lock_result.is_some(),
            "MemoryDispatch should handle selector 4"
        );
        assert!(
            lock_result.unwrap().is_ok(),
            "LockMemoryContiguous should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LockMemoryContiguous should return noErr"
        );

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 0); // ask only for required entry count
        let sp_pre = cpu.read_reg(Register::A7);
        let get_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(
            get_result.is_some(),
            "MemoryDispatch should handle selector 5"
        );
        assert!(get_result.unwrap().is_ok(), "GetPhysical should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "GetPhysical should return paramErr (-50) for entrycount=0 query"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            1,
            "GetPhysical should report one required translated entry for entrycount=0 query"
        );
        assert_eq!(
            sp_pre, sp_post,
            "GetPhysical should preserve the caller's stack pointer for entrycount=0 query"
        );
        assert_eq!(
            bus.read_long(table + 8),
            0x1111_2222,
            "GetPhysical(entrycount=0) should preserve physical entry address"
        );
        assert_eq!(
            bus.read_long(table + 12),
            0x3333_4444,
            "GetPhysical(entrycount=0) should preserve physical entry count"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_entrycount_zero_on_locked_multpage_range_returns_two_and_preserves_table(
    ) {
        // Inside Macintosh: Memory (1992), 3-31: a zero-count GetPhysical
        // query reports the number of physical entries required for the
        // entire logical range and leaves the table untouched.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.alloc(8192) + 99;
        let logical_count = 5000u32;
        assert_eq!(
            super::vm_required_physical_entries(logical_start, logical_count),
            2,
            "zero-count GetPhysical should compute two required physical entries for the locked multi-page witness range"
        );
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);
        bus.write_long(table + 8, 0x5555_AAAA);
        bus.write_long(table + 12, 0x7777_BBBB);

        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, logical_start);
        cpu.write_reg(Register::A1, logical_count);
        let lock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            lock_result.is_some(),
            "MemoryDispatch should handle selector 4"
        );
        assert!(
            lock_result.unwrap().is_ok(),
            "LockMemoryContiguous should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LockMemoryContiguous should return noErr"
        );

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 0); // ask only for required entry count
        let get_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            get_result.is_some(),
            "MemoryDispatch should handle selector 5"
        );
        assert!(get_result.unwrap().is_ok(), "GetPhysical should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "GetPhysical should return paramErr (-50) for entrycount=0 query"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            2,
            "GetPhysical should report two required physical entries for this locked multi-page logical range"
        );
        assert_eq!(
            bus.read_long(table + 8),
            0x5555_AAAA,
            "GetPhysical(entrycount=0) should preserve physical entry address"
        );
        assert_eq!(
            bus.read_long(table + 12),
            0x7777_BBBB,
            "GetPhysical(entrycount=0) should preserve physical entry count"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_entrycount_zero_on_empty_range_returns_paramerr_and_preserves_table(
    ) {
        // BasiliskII returns paramErr for an empty logical range queried
        // with physicalEntryCount=0 and leaves the table/A0 shape intact.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        bus.write_long(table, 0x0010_0000);
        bus.write_long(table + 4, 0);
        bus.write_long(table + 8, 0xAAAA_BBBB);
        bus.write_long(table + 12, 0xCCCC_DDDD);

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 0); // ask only for required entry count
        let get_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            get_result.is_some(),
            "MemoryDispatch should handle selector 5"
        );
        assert!(get_result.unwrap().is_ok(), "GetPhysical should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-50i32) as u32,
            "GetPhysical should return paramErr (-50) for empty-range entrycount=0 query"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            table,
            "GetPhysical(empty range) should preserve the A0 table pointer on return"
        );
        assert_eq!(
            bus.read_long(table + 8),
            0xAAAA_BBBB,
            "GetPhysical(empty range) should preserve physical entry address"
        );
        assert_eq!(
            bus.read_long(table + 12),
            0xCCCC_DDDD,
            "GetPhysical(empty range) should preserve physical entry count"
        );
    }

    #[test]
    fn test_memorydispatch_getphysical_entrycount_zero_on_unlocked_range_returns_notlockederr() {
        // The logical range must stay locked while GetPhysical reports the
        // required physical-entry count, and the zero-count query still
        // preserves the caller's stack frame.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let table = bus.alloc(16);
        let logical_start = bus.alloc(4096) + 55;
        let logical_count = 1792u32;
        bus.write_long(table, logical_start);
        bus.write_long(table + 4, logical_count);
        bus.write_long(table + 8, 0x4444_5555);
        bus.write_long(table + 12, 0x6666_7777);

        cpu.write_reg(Register::D0, 4); // LockMemoryContiguous selector
        cpu.write_reg(Register::A0, logical_start);
        cpu.write_reg(Register::A1, logical_count);
        let lock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            lock_result.is_some(),
            "MemoryDispatch should handle selector 4"
        );
        assert!(
            lock_result.unwrap().is_ok(),
            "LockMemoryContiguous should return"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "LockMemoryContiguous should return noErr"
        );

        cpu.write_reg(Register::D0, 3); // UnlockMemory selector
        cpu.write_reg(Register::A0, logical_start);
        cpu.write_reg(Register::A1, logical_count);
        let unlock_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        assert!(
            unlock_result.is_some(),
            "MemoryDispatch should handle selector 3"
        );
        assert!(unlock_result.unwrap().is_ok(), "UnlockMemory should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "UnlockMemory should return noErr after releasing the range"
        );

        cpu.write_reg(Register::D0, 5); // GetPhysical selector
        cpu.write_reg(Register::A0, table);
        cpu.write_reg(Register::A1, 0); // ask only for required entry count
        let sp_pre = cpu.read_reg(Register::A7);
        let get_result = dispatcher.dispatch_memory(false, 0x5C, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);
        assert!(
            get_result.is_some(),
            "MemoryDispatch should handle selector 5"
        );
        assert!(get_result.unwrap().is_ok(), "GetPhysical should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            (-623i32) as u32,
            "GetPhysical should return notLockedErr (-623) for unlocked entrycount=0 query"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "GetPhysical should report zero translated entries for unlocked entrycount=0 query"
        );
        assert_eq!(
            sp_pre, sp_post,
            "GetPhysical should preserve the caller's stack pointer for unlocked entrycount=0 query"
        );
        assert_eq!(
            bus.read_long(table + 8),
            0x4444_5555,
            "GetPhysical(entrycount=0) should preserve physical entry address after unlock"
        );
        assert_eq!(
            bus.read_long(table + 12),
            0x6666_7777,
            "GetPhysical(entrycount=0) should preserve physical entry count after unlock"
        );
    }

    #[test]
    fn countadbs_returns_number_of_connected_adb_devices_in_d0() {
        // Inside Macintosh Volume V (1986), p. V-372; Inside Macintosh:
        // Devices (1994), p. 5-42: CountADBs returns the number of ADB
        // devices by counting ADB device-table entries.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0x77, &mut cpu, &mut bus);
        assert!(result.is_some(), "CountADBs should be handled");
        assert!(result.unwrap().is_ok(), "CountADBs should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            2,
            "HLE CountADBs should report keyboard+mouse device count"
        );
    }

    #[test]
    fn countadbs_takes_no_arguments_and_reports_no_error_codes() {
        // Inside Macintosh Volume V (1986), p. V-372; Inside Macintosh:
        // Devices (1994), p. 5-42: CountADBs has no arguments and no
        // separate error-code contract.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x77, &mut cpu, &mut bus);
        assert!(result.is_some(), "CountADBs should be handled");
        assert!(result.unwrap().is_ok(), "CountADBs should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "CountADBs should not consume stack parameters"
        );
        assert!(
            (cpu.read_reg(Register::D0) as i32) >= 0,
            "CountADBs should return only a nonnegative device-count result in D0"
        );
    }

    #[test]
    fn getindadb_valid_index_returns_positive_adb_address() {
        // Inside Macintosh Volume V (1986), p. V-373; Inside Macintosh:
        // Devices (1994), p. 5-43: valid entry indexes return the current
        // ADB address as a positive function result.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::D0, 1);
        let first = dispatcher.dispatch_memory(false, 0x78, &mut cpu, &mut bus);
        assert!(first.is_some(), "GetIndADB should be handled");
        assert!(first.unwrap().is_ok(), "GetIndADB(index=1) should return");
        assert!(
            (cpu.read_reg(Register::D0) as i32) > 0,
            "GetIndADB(index=1) should return a positive address"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            2,
            "HLE GetIndADB index 1 should map to keyboard ADB address 2"
        );

        cpu.write_reg(Register::D0, 2);
        let second = dispatcher.dispatch_memory(false, 0x78, &mut cpu, &mut bus);
        assert!(second.is_some(), "GetIndADB should be handled");
        assert!(second.unwrap().is_ok(), "GetIndADB(index=2) should return");
        assert!(
            (cpu.read_reg(Register::D0) as i32) > 0,
            "GetIndADB(index=2) should return a positive address"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            3,
            "HLE GetIndADB index 2 should map to mouse ADB address 3"
        );
    }

    #[test]
    fn getindadb_out_of_range_index_returns_negative_result() {
        // Inside Macintosh: Devices (1994), p. 5-43 (and IM:V V-373):
        // if GetIndADB cannot find the indexed entry, it returns a
        // negative function result.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320000u32;
        for i in 0..10u32 {
            bus.write_byte(info + i, 0xA5);
        }

        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 0);
        let result = dispatcher.dispatch_memory(false, 0x78, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetIndADB should be handled");
        assert!(result.unwrap().is_ok(), "GetIndADB should return");
        assert!(
            (cpu.read_reg(Register::D0) as i32) < 0,
            "Out-of-range GetIndADB index should return a negative result"
        );
    }

    #[test]
    fn getindadb_writes_adbdatablock_for_valid_index() {
        // Inside Macintosh Volume V (1986), p. V-373; Inside Macintosh:
        // Devices (1994), p. 5-43: info receives an ADBDataBlock for the
        // selected entry.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320100u32;
        for i in 0..10u32 {
            bus.write_byte(info + i, 0xCC);
        }

        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 1);
        let result = dispatcher.dispatch_memory(false, 0x78, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetIndADB should be handled");
        assert!(result.unwrap().is_ok(), "GetIndADB should return");
        assert_eq!(
            bus.read_byte(info),
            0,
            "GetIndADB should write devType field in info block"
        );
        assert_eq!(
            bus.read_byte(info + 1),
            2,
            "GetIndADB should write origADBAddr for keyboard entry"
        );
        assert_eq!(
            bus.read_long(info + 2),
            0,
            "GetIndADB should write dbServiceRtPtr field in info block"
        );
        assert_eq!(
            bus.read_long(info + 6),
            0,
            "GetIndADB should write dbDataAreaAddr field in info block"
        );
    }

    #[test]
    fn getindadb_preserves_caller_memory_beyond_adbdatablock() {
        // Per IM:V V-373: the ADBDataBlock is documented as 10 bytes
        // (devType + origADBAddr + dbServiceRtPtr + dbDataAreaAddr).
        // Pin that the HLE write loop does not clobber caller memory
        // beyond the 10-byte window; mirrors the trailing-sentinel
        // conjunct of B3 in a078_getindadb_strict.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320180u32;
        for i in 0..12u32 {
            bus.write_byte(info + i, 0xFF);
        }

        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 1);
        let result = dispatcher.dispatch_memory(false, 0x78, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetIndADB should be handled");
        assert!(result.unwrap().is_ok(), "GetIndADB should return");
        assert_ne!(
            bus.read_byte(info),
            0xFF,
            "GetIndADB should overwrite the sentinel at offset 0"
        );
        assert_eq!(
            bus.read_byte(info + 10),
            0xFF,
            "GetIndADB must not clobber caller memory at offset 10"
        );
        assert_eq!(
            bus.read_byte(info + 11),
            0xFF,
            "GetIndADB must not clobber caller memory at offset 11"
        );
    }

    #[test]
    fn getadbinfo_returns_noerr_for_nominal_address() {
        // Inside Macintosh Volume V (1986), p. V-369: GetADBInfo returns
        // an OSErr result code in D0; noErr indicates successful completion.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320200u32;
        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 2); // keyboard ADB address

        let result = dispatcher.dispatch_memory(false, 0x79, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetADBInfo should be handled");
        assert!(result.unwrap().is_ok(), "GetADBInfo should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "GetADBInfo nominal path should return noErr in D0"
        );
    }

    #[test]
    fn getadbinfo_writes_adbdatablock_fields_through_a0_parameter_block() {
        // Inside Macintosh Volume V (1986), p. V-369: A0 points to an
        // ADBDataBlock parameter block that GetADBInfo writes on success.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320240u32;
        for i in 0..12u32 {
            bus.write_byte(info + i, 0xCC);
        }

        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 3); // mouse ADB address
        let result = dispatcher.dispatch_memory(false, 0x79, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetADBInfo should be handled");
        assert!(result.unwrap().is_ok(), "GetADBInfo should return");
        assert_eq!(
            bus.read_byte(info),
            0,
            "device handler byte should be written"
        );
        assert_eq!(
            bus.read_byte(info + 1),
            0,
            "original-address byte should be written"
        );
        assert_eq!(
            bus.read_long(info + 2),
            0,
            "service-routine pointer field should be written"
        );
        assert_eq!(
            bus.read_long(info + 6),
            0,
            "data-area pointer field should be written"
        );
    }

    #[test]
    fn getadbinfo_preserves_stack_pointer_for_nominal_address() {
        // Inside Macintosh Volume V (1986), p. V-369: GetADBInfo uses
        // a register-only OS trap calling convention and should not
        // consume a Pascal argument frame.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320280u32;
        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 2); // keyboard ADB address
        let sp_before = cpu.read_reg(Register::A7);

        let result = dispatcher.dispatch_memory(false, 0x79, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetADBInfo should be handled");
        assert!(result.unwrap().is_ok(), "GetADBInfo should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "GetADBInfo should preserve A7"
        );
    }

    #[test]
    fn setadbinfo_returns_noerr_for_nominal_address() {
        // Inside Macintosh Volume V (1986), p. V-369: SetADBInfo returns
        // an OSErr result code in D0; noErr indicates successful completion.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let info = 0x320280u32;
        bus.write_long(info, 0x00AA_5500);
        bus.write_long(info + 4, 0x00CC_7700);
        cpu.write_reg(Register::A0, info);
        cpu.write_reg(Register::D0, 2);

        let result = dispatcher.dispatch_memory(false, 0x7A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetADBInfo should be handled");
        assert!(result.unwrap().is_ok(), "SetADBInfo should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetADBInfo nominal path should return noErr in D0"
        );
    }

    #[test]
    fn setadbinfo_uses_a0_parameter_block_and_d0_address_register_calling_convention() {
        // Inside Macintosh Volume V (1986), p. V-369: SetADBInfo takes
        // A0=ADBSetInfoBlock pointer and D0=ADB address on entry.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::D0, 0x0F);

        let result = dispatcher.dispatch_memory(false, 0x7A, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetADBInfo should be handled");
        assert!(result.unwrap().is_ok(), "SetADBInfo should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SetADBInfo should not consume stack arguments"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetADBInfo should return noErr in D0 on nominal calls"
        );
    }

    #[test]
    fn adbreinit_has_no_parameters_and_preserves_stack_pointer() {
        // Inside Macintosh Volume V (1986), p. V-367: ADBReInit has no
        // parameters.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xDEAD_BEEF);

        let result = dispatcher.dispatch_memory(false, 0x7B, &mut cpu, &mut bus);
        assert!(result.is_some(), "ADBReInit should be handled");
        assert!(result.unwrap().is_ok(), "ADBReInit should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "ADBReInit should preserve A7 because it takes no stack arguments"
        );
    }

    #[test]
    fn adbop_returns_noerr_when_command_queue_accepts_request() {
        // Inside Macintosh Volume V (1986), p. V-368: ADBOp returns
        // noErr when the command is accepted.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = 0x3202C0u32;
        cpu.write_reg(Register::A0, pb);
        cpu.write_reg(Register::D0, 0x08); // command byte

        let result = dispatcher.dispatch_memory(false, 0x7C, &mut cpu, &mut bus);
        assert!(result.is_some(), "ADBOp should be handled");
        assert!(result.unwrap().is_ok(), "ADBOp should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "ADBOp nominal path should return noErr in D0"
        );
    }

    #[test]
    fn adbop_uses_a0_parameter_block_and_d0_commandnum_without_stack_arguments() {
        // Inside Macintosh Volume V (1986), p. V-368: ADBOp uses
        // A0=parameter-block pointer and D0=commandNum on entry.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::D0, 0x0C); // Flush command byte shape

        let result = dispatcher.dispatch_memory(false, 0x7C, &mut cpu, &mut bus);
        assert!(result.is_some(), "ADBOp should be handled");
        assert!(result.unwrap().is_ok(), "ADBOp should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "ADBOp should not consume stack arguments"
        );
    }

    #[test]
    fn adbop_repeated_calls_balance_stack_no_drift() {
        // Mirrors B3 of a07c_adbop_strict: 8
        // successive ADBOp dispatches with varied commandNum bytes
        // (Flush + Talk-register-0..2 + Listen-register-0..3) and
        // varied ADB device addresses (1..8) preserve A7 in aggregate.
        // Per IM:V V-368, ADBOp uses only A0+D0 inputs and returns its
        // result in D0; no per-call pop discipline error can
        // accumulate across the composition.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let pb = 0x3202C0u32;
        let commands: [u32; 8] = [
            0x11, // device 1 Flush
            0x2C, // device 2 Talk r0
            0x3D, // device 3 Talk r1
            0x4E, // device 4 Talk r2
            0x58, // device 5 Listen r0
            0x69, // device 6 Listen r1
            0x7A, // device 7 Listen r2
            0x8B, // device 8 Listen r3
        ];
        for command in commands.iter() {
            cpu.write_reg(Register::A0, pb);
            cpu.write_reg(Register::D0, *command);
            let result = dispatcher.dispatch_memory(false, 0x7C, &mut cpu, &mut bus);
            assert!(result.is_some(), "ADBOp should be handled");
            assert!(result.unwrap().is_ok(), "ADBOp should return");
        }
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "8 successive ADBOp calls should preserve A7 in aggregate"
        );
    }

    #[test]
    fn control_writes_ioresult_and_returns_noerr_in_d0() {
        // IM:Devices 1994 p. 1-77: _Control returns the OSErr result in D0
        // and uses CntrlParam.ioResult in the parameter block.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = 0x300000u32;
        // Write a non-zero value at ioResult (pb+16) to verify it gets cleared
        bus.write_word(pb + 16, 0xFFFF);
        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x04, &mut cpu, &mut bus);
        assert!(result.is_some(), "_Control should be handled");
        assert!(result.unwrap().is_ok(), "_Control should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "_Control should set D0 to 0");
        assert_eq!(
            bus.read_word(pb + 16),
            0,
            "_Control should set ioResult at pb+16 to 0"
        );
    }

    #[test]
    fn control_nil_paramblock_returns_noerr_and_preserves_stack() {
        // IM:Devices 1994 p. 1-77 (assembly): _Control takes the param block
        // in A0 and only D0 is defined as affected on return.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0);
        let result = dispatcher.dispatch_memory(false, 0x04, &mut cpu, &mut bus);
        assert!(result.is_some(), "_Control should be handled");
        assert!(result.unwrap().is_ok(), "_Control should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "_Control with NIL param block should still return noErr in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_Control should not consume stack arguments in the A0-param-block calling convention"
        );
    }

    #[test]
    fn status_writes_ioresult_and_returns_noerr_in_d0() {
        // IM:Devices 1994 p. 1-80: _Status returns result in D0 and reports
        // driver status through CntrlParam (including ioResult).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let pb = 0x300000u32;
        // Write a non-zero value at ioResult (pb+16) to verify it gets cleared
        bus.write_word(pb + 16, 0xFFFF);
        cpu.write_reg(Register::A0, pb);
        let result = dispatcher.dispatch_memory(false, 0x05, &mut cpu, &mut bus);
        assert!(result.is_some(), "_Status should be handled");
        assert!(result.unwrap().is_ok(), "_Status should succeed");
        assert_eq!(cpu.read_reg(Register::D0), 0, "_Status should set D0 to 0");
        assert_eq!(
            bus.read_word(pb + 16),
            0,
            "_Status should set ioResult at pb+16 to 0"
        );
    }

    #[test]
    fn status_nil_paramblock_returns_noerr_and_preserves_stack() {
        // IM:Devices 1994 p. 1-80 (assembly): _Status uses A0 for the
        // parameter block and returns the result in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::A0, 0);
        let result = dispatcher.dispatch_memory(false, 0x05, &mut cpu, &mut bus);
        assert!(result.is_some(), "_Status should be handled");
        assert!(result.unwrap().is_ok(), "_Status should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "_Status with NIL param block should still return noErr in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_Status should not consume stack arguments in the A0-param-block calling convention"
        );
    }

    #[test]
    fn pbstatus_writes_same_oserr_to_d0_and_ioresult_preserving_stack() {
        // Mirrors B1 + B2 of a005_pbstatus_strict:
        // pre-poisons pb.ioResult at pb+16 with 0x3FFF (neither noErr nor
        // any documented OSErr), dispatches _Status with a clearly-bogus
        // ioRefNum 9999, witnesses that the trap overwrote the sentinel
        // AND that D0 == ioResult (per Device Manager dispatcher
        // convention IM:II 1985 p. II-114) AND that A7 is preserved
        // across the call (register-only OS-bit FUNCTION calling
        // convention per IM:Devices 1994 p. 1-80).
        let (mut dispatcher, mut cpu, mut bus) = setup();

        let pb = 0x300300u32;
        cpu.write_reg(Register::A0, pb);
        bus.write_word(pb + 16, 0x3FFFu16); // pre-poison ioResult
        bus.write_word(pb + 24, 9999u16); // bogus ioRefNum

        let sp_pre = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(false, 0x05, &mut cpu, &mut bus);
        let sp_post = cpu.read_reg(Register::A7);

        assert!(result.is_some(), "_Status should be handled");
        assert!(result.unwrap().is_ok(), "_Status should succeed");

        let d0 = cpu.read_reg(Register::D0) as i16;
        let io_result = bus.read_word(pb + 16) as i16;
        assert_ne!(
            io_result, 0x3FFFi16,
            "ioResult sentinel must be overwritten"
        );
        assert_eq!(d0, io_result, "D0 == ioResult per dispatcher convention");
        assert_eq!(
            d0,
            (-21i16),
            "bogus ioRefNum should collapse to badUnitErr on the HLE path"
        );
        assert_eq!(sp_pre, sp_post, "A7 preserved (register-only ABI)");
    }

    #[test]
    fn setapplimit_updates_appllimit_when_limit_is_not_below_heap_extent() {
        // Inside Macintosh: Memory (1992), pp. 2-84..2-85:
        // SetApplLimit sets the current application heap limit to zoneLimit.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let heap_end = 0x0030_0000u32;
        let appl_limit_before = 0x0038_0000u32;
        let requested_limit = 0x003C_0000u32;
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(0x0114, heap_end); // HEAP_END
        bus.write_long(0x0130, appl_limit_before); // APPL_LIMIT

        cpu.write_reg(Register::A0, requested_limit);
        let result = dispatcher.dispatch_memory(false, 0x2D, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetApplLimit should be handled");
        assert!(result.unwrap().is_ok(), "SetApplLimit should return");
        assert_eq!(
            bus.read_long(0x0130),
            requested_limit,
            "SetApplLimit should store zoneLimit in ApplLimit when zoneLimit is not below current heap extent"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetApplLimit should return noErr in D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "SetApplLimit uses A0 parameter passing and should not consume stack arguments"
        );
    }

    #[test]
    fn setapplimit_below_heap_extent_does_not_cut_back_appllimit() {
        // Inside Macintosh: Memory (1992), p. 2-85:
        // if the zone already extends beyond zoneLimit, no cut-back occurs.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let heap_end = 0x0038_0000u32;
        let appl_limit_before = 0x0038_0000u32;
        let requested_limit = 0x0030_0000u32;
        bus.write_long(0x0114, heap_end); // HEAP_END
        bus.write_long(0x0130, appl_limit_before); // APPL_LIMIT

        cpu.write_reg(Register::A0, requested_limit);
        let result = dispatcher.dispatch_memory(false, 0x2D, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetApplLimit should be handled");
        assert!(result.unwrap().is_ok(), "SetApplLimit should return");
        assert_eq!(
            bus.read_long(0x0130),
            appl_limit_before,
            "SetApplLimit must not reduce ApplLimit when heap already extends beyond requested limit"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetApplLimit should still return noErr when lower limit is ignored"
        );
    }

    #[test]
    fn setapplimit_below_heap_extent_leaves_heapend_and_appllimit_unchanged() {
        // Mirrors the regression fixture's lower-limit branch: a
        // requested limit below HeapEnd must leave both HeapEnd and
        // ApplLimit unchanged while still returning noErr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let heap_end = 0x0038_0000u32;
        let appl_limit_before = 0x003C_0000u32;
        let requested_limit = heap_end - 0x1000;
        bus.write_long(0x0114, heap_end); // HEAP_END
        bus.write_long(0x0130, appl_limit_before); // APPL_LIMIT

        cpu.write_reg(Register::A0, requested_limit);
        let result = dispatcher.dispatch_memory(false, 0x2D, &mut cpu, &mut bus);
        assert!(result.is_some(), "SetApplLimit should be handled");
        assert!(result.unwrap().is_ok(), "SetApplLimit should return");
        assert_eq!(
            bus.read_long(0x0130),
            appl_limit_before,
            "SetApplLimit must not reduce ApplLimit when the requested limit is below HeapEnd"
        );
        assert_eq!(
            bus.read_long(0x0114),
            heap_end,
            "SetApplLimit should not rewrite HeapEnd"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetApplLimit should return noErr when the lower-limit path is taken"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            TEST_SP,
            "SetApplLimit should preserve A7"
        );
    }

    #[test]
    fn setzone_writes_thezone_and_getzone_roundtrips() {
        // Inside Macintosh: Memory (1992), pp. 2-80..2-81:
        // SetZone makes hz current; GetZone returns the current zone.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let new_zone = 0x0BAD_F00Du32;
        bus.write_long(0x0118, 0x00AA_BBCC);

        cpu.write_reg(Register::A0, new_zone);
        let set_result = dispatcher.dispatch_memory(false, 0x1B, &mut cpu, &mut bus);
        assert!(set_result.is_some(), "SetZone should be handled");
        assert!(set_result.unwrap().is_ok(), "SetZone should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "SetZone should return noErr in D0"
        );
        assert_eq!(
            bus.read_long(0x0118),
            new_zone,
            "SetZone should write TheZone low-memory global ($0118)"
        );

        let get_result = dispatcher.dispatch_memory(false, 0x1A, &mut cpu, &mut bus);
        assert!(get_result.is_some(), "GetZone should be handled");
        assert!(get_result.unwrap().is_ok(), "GetZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            new_zone,
            "GetZone should return the zone selected by SetZone"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "GetZone should return noErr in D0"
        );
    }

    #[test]
    fn setzone_roundtrip_with_saved_original_restores_thezone() {
        // Inside Macintosh: Memory (1992), pp. 2-80..2-81:
        // GetZone reads TheZone; SetZone writes A0 to TheZone.
        // Mirrors the a01b_setzone_strict bake's save/test/restore
        // pattern: save the original TheZone via GetZone, switch to a
        // different zone via SetZone, witness both the TheZone write
        // and the GetZone roundtrip on the new value, then restore
        // the original via SetZone and confirm GetZone observes it.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let original_zone = 0x00AA_BBCCu32;
        let new_zone = 0x0BAD_F00Du32;
        bus.write_long(0x0118, original_zone);

        // Save original via GetZone.
        let get_orig = dispatcher.dispatch_memory(false, 0x1A, &mut cpu, &mut bus);
        assert!(get_orig.is_some(), "GetZone should be handled");
        assert!(get_orig.unwrap().is_ok(), "GetZone should return");
        let saved_zone = cpu.read_reg(Register::A0);
        assert_eq!(
            saved_zone, original_zone,
            "GetZone should return the original TheZone before any switch"
        );

        // SetZone(new_zone) — writes TheZone.
        cpu.write_reg(Register::A0, new_zone);
        let set_new = dispatcher.dispatch_memory(false, 0x1B, &mut cpu, &mut bus);
        assert!(set_new.is_some(), "SetZone should be handled");
        assert!(set_new.unwrap().is_ok(), "SetZone should return");
        assert_eq!(
            bus.read_long(0x0118),
            new_zone,
            "SetZone should write the new zone pointer into TheZone ($0118)"
        );

        // GetZone after SetZone(new_zone) returns new_zone.
        let get_new = dispatcher.dispatch_memory(false, 0x1A, &mut cpu, &mut bus);
        assert!(get_new.is_some(), "GetZone should be handled");
        assert!(get_new.unwrap().is_ok(), "GetZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            new_zone,
            "GetZone should return the zone selected by SetZone (roundtrip)"
        );

        // Restore: SetZone(saved_zone).
        cpu.write_reg(Register::A0, saved_zone);
        let set_back = dispatcher.dispatch_memory(false, 0x1B, &mut cpu, &mut bus);
        assert!(set_back.is_some(), "SetZone should be handled");
        assert!(set_back.unwrap().is_ok(), "SetZone should return");
        assert_eq!(
            bus.read_long(0x0118),
            original_zone,
            "SetZone should restore the original TheZone value"
        );

        // GetZone after restore returns the original.
        let get_restored = dispatcher.dispatch_memory(false, 0x1A, &mut cpu, &mut bus);
        assert!(get_restored.is_some(), "GetZone should be handled");
        assert!(get_restored.unwrap().is_ok(), "GetZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            original_zone,
            "GetZone after restore should return the original TheZone"
        );
    }

    #[test]
    fn setgrowzone_register_only_calling_convention_preserves_stack() {
        // Mirrors B1 + B2 of a04b_setgrowzone_strict.
        //
        // Per IM:Memory 1992 p. 2-56 SetGrowZone is an OS-bit PROCEDURE
        // with a register-only ABI (A0 input, D0 result, no Pascal
        // stack frame). The test pins:
        //   - Single SetGrowZone(NIL) preserves A7 and returns D0=noErr
        //   - 5-call composition mixing NIL → synthetic ProcPtr → NIL →
        //     synthetic ProcPtr → NIL preserves A7 cumulatively
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_pre = cpu.read_reg(Register::A7);

        // Single-call: SetGrowZone(NIL)
        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::D0, 0xDEAD_BEEF);
        let single = dispatcher.dispatch_memory(false, 0x4B, &mut cpu, &mut bus);
        assert!(single.is_some(), "SetGrowZone should be handled");
        assert!(single.unwrap().is_ok(), "SetGrowZone should succeed");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "A7 preserved across single SetGrowZone(NIL) call"
        );
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            0,
            "SetGrowZone returns noErr in D0"
        );

        // 5-call composition: NIL → synthetic ProcPtr → NIL → ...
        let inputs = [0u32, 0x0040_0000, 0, 0x0040_0040, 0];
        for &a0 in &inputs {
            cpu.write_reg(Register::A0, a0);
            cpu.write_reg(Register::D0, 0xCAFE_F00D);
            let r = dispatcher.dispatch_memory(false, 0x4B, &mut cpu, &mut bus);
            assert!(r.is_some(), "SetGrowZone should be handled");
            assert!(
                r.unwrap().is_ok(),
                "SetGrowZone should succeed for A0=${a0:08X}"
            );
            assert_eq!(
                cpu.read_reg(Register::D0) as i32,
                0,
                "SetGrowZone returns noErr in D0 on each call"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "A7 preserved across 5-call composition with mixed inputs"
        );
    }

    #[test]
    fn purgemem_register_only_calling_convention_preserves_stack() {
        // Mirrors B1 + B2 of a04d_purgemem_strict.
        //
        // Per IM:Memory 1992 p. 2-73 PurgeMem is an OS-bit PROCEDURE
        // with a register-only ABI (D0 = cbNeeded input, D0 = result
        // code output, no Pascal stack frame). The test pins:
        //   - Single PurgeMem(0) preserves A7 and returns D0=noErr
        //   - 5-call composition cycling cbNeeded values
        //     0 -> 256 -> 0 -> 1024 -> 0 preserves A7 cumulatively
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_pre = cpu.read_reg(Register::A7);

        // Single-call: PurgeMem(0)
        cpu.write_reg(Register::D0, 0);
        let single = dispatcher.dispatch_memory(false, 0x4D, &mut cpu, &mut bus);
        assert!(single.is_some(), "PurgeMem should be handled");
        assert!(single.unwrap().is_ok(), "PurgeMem should succeed");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "A7 preserved across single PurgeMem(0) call"
        );
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            0,
            "PurgeMem returns noErr in D0"
        );

        // 5-call composition: cbNeeded = 0 -> 256 -> 0 -> 1024 -> 0
        let inputs = [0u32, 256, 0, 1024, 0];
        for &d0 in &inputs {
            cpu.write_reg(Register::D0, d0);
            let r = dispatcher.dispatch_memory(false, 0x4D, &mut cpu, &mut bus);
            assert!(r.is_some(), "PurgeMem should be handled");
            assert!(
                r.unwrap().is_ok(),
                "PurgeMem should succeed for D0=${d0:08X}"
            );
            assert_eq!(
                cpu.read_reg(Register::D0) as i32,
                0,
                "PurgeMem returns noErr in D0 on each call"
            );
        }

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_pre,
            "A7 preserved across 5-call composition with mixed cbNeeded inputs"
        );
    }

    #[test]
    fn getzone_returns_thezone_pointer_and_noerr() {
        // Inside Macintosh: Memory (1992), p. 2-80:
        // GetZone returns TheZone in A0 and a result code in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let zone = 0x1234_5678u32;
        bus.write_long(0x0118, zone);

        let result = dispatcher.dispatch_memory(false, 0x1A, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetZone should be handled");
        assert!(result.unwrap().is_ok(), "GetZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            zone,
            "GetZone should return TheZone in A0"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "GetZone should return noErr in D0"
        );
    }

    #[test]
    fn handlezone_valid_handle_returns_current_zone_pointer() {
        // Inside Macintosh: Memory (1992), pp. 2-82..2-83:
        // HandleZone returns zone pointer for relocatable block handles.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let zone = 0x2001_1000u32;
        bus.write_long(0x0118, zone);

        cpu.write_reg(Register::D0, 4);
        let new_handle = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(new_handle.is_some(), "NewHandle should be handled");
        assert!(new_handle.unwrap().is_ok(), "NewHandle should return");
        let handle = cpu.read_reg(Register::A0);
        assert_ne!(handle, 0, "NewHandle should allocate a non-NIL handle");

        cpu.write_reg(Register::A0, handle);
        let result = dispatcher.dispatch_memory(false, 0x26, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandleZone should be handled");
        assert!(result.unwrap().is_ok(), "HandleZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            zone,
            "HandleZone should return current zone pointer in A0"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HandleZone should return noErr for a valid handle"
        );
    }

    #[test]
    fn handlezone_empty_handle_returns_zone_pointer() {
        // Inside Macintosh: Memory (1992), p. 2-82 important note:
        // empty handles still return a zone pointer (master-pointer zone).
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let zone = 0x2002_2000u32;
        bus.write_long(0x0118, zone);

        let empty_result = dispatcher.dispatch_memory(false, 0x66, &mut cpu, &mut bus);
        assert!(empty_result.is_some(), "NewEmptyHandle should be handled");
        assert!(
            empty_result.unwrap().is_ok(),
            "NewEmptyHandle should return"
        );
        let empty_handle = cpu.read_reg(Register::A0);
        assert_ne!(empty_handle, 0, "NewEmptyHandle should return a handle");
        assert_eq!(
            bus.read_long(empty_handle),
            0,
            "NewEmptyHandle should initialize master pointer to NIL"
        );

        cpu.write_reg(Register::A0, empty_handle);
        let result = dispatcher.dispatch_memory(false, 0x26, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandleZone should be handled");
        assert!(result.unwrap().is_ok(), "HandleZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            zone,
            "HandleZone(empty-handle) should return a zone pointer"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HandleZone(empty-handle) should return noErr"
        );
    }

    #[test]
    fn handlezone_nil_handle_returns_noerr_in_d0() {
        // BasiliskII-observed divergence from Inside Macintosh: Memory
        // (1992), p. 2-83: NIL handles return noErr in D0.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0);
        let result = dispatcher.dispatch_memory(false, 0x26, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandleZone should be handled");
        assert!(result.unwrap().is_ok(), "HandleZone should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            0,
            "HandleZone(NIL) should return noErr (BasiliskII divergence)"
        );
    }

    #[test]
    fn handlezone_disposed_handle_returns_memwzerr() {
        // Inside Macintosh: Memory (1992), p. 2-83:
        // memWZErr (-111) indicates attempt to operate on a free block.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 4);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.is_some(), "NewHandle should be handled");
        assert!(result.unwrap().is_ok(), "NewHandle should return");
        let handle = cpu.read_reg(Register::A0);
        assert_ne!(handle, 0, "NewHandle should allocate a handle");

        cpu.write_reg(Register::A0, handle);
        let dispose = dispatcher.dispatch_memory(false, 0x23, &mut cpu, &mut bus);
        assert!(dispose.is_some(), "DisposeHandle should be handled");
        assert!(dispose.unwrap().is_ok(), "DisposeHandle should return");
        assert_eq!(
            bus.get_alloc_size(handle),
            None,
            "DisposeHandle should free the master-pointer slot"
        );

        cpu.write_reg(Register::A0, handle);
        let result = dispatcher.dispatch_memory(false, 0x26, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandleZone should be handled");
        assert!(result.unwrap().is_ok(), "HandleZone should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -111,
            "HandleZone(disposed handle) should return memWZErr (-111)"
        );
    }

    #[test]
    fn ptrzone_valid_pointer_returns_current_zone_pointer() {
        // Inside Macintosh: Memory (1992), p. 2-83:
        // PtrZone returns the zone containing a nonrelocatable block pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let zone = 0x2003_3000u32;
        bus.write_long(0x0118, zone);

        cpu.write_reg(Register::D0, 8);
        let ptr_result = dispatcher.dispatch_memory(false, 0x1E, &mut cpu, &mut bus);
        assert!(ptr_result.is_some(), "NewPtr should be handled");
        assert!(ptr_result.unwrap().is_ok(), "NewPtr should return");
        let ptr = cpu.read_reg(Register::A0);
        assert_ne!(ptr, 0, "NewPtr should return a non-NIL pointer");

        cpu.write_reg(Register::A0, ptr);
        let result = dispatcher.dispatch_memory(false, 0x48, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrZone should be handled");
        assert!(result.unwrap().is_ok(), "PtrZone should return");
        assert_eq!(
            cpu.read_reg(Register::A0),
            zone,
            "PtrZone should return current zone pointer in A0"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "PtrZone should return noErr for a valid pointer"
        );
    }

    #[test]
    fn ptrzone_nil_pointer_returns_memwzerr() {
        // Inside Macintosh: Memory (1992), p. 2-83:
        // PtrZone returns memWZErr for free/invalid pointer blocks.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0);
        let result = dispatcher.dispatch_memory(false, 0x48, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrZone should be handled");
        assert!(result.unwrap().is_ok(), "PtrZone should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -111,
            "PtrZone(NIL) should return memWZErr (-111)"
        );
    }

    // ==================== Toolbox Traps (is_tool=true) ====================

    #[test]
    fn debugger_trap_is_parameterless_and_preserves_stack_pointer() {
        // Inside Macintosh: Processes (1994), p. 7-9 and Inside Macintosh:
        // Memory (1992), p. 3-23 describe _Debugger as a trap-driven debugger
        // entry point; Systemless models it as a parameterless call frame.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        let result = dispatcher.dispatch_memory(true, 0x3FF, &mut cpu, &mut bus);
        assert!(result.is_some(), "Debugger should be handled");
        assert!(result.unwrap().is_ok(), "Debugger should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_Debugger should preserve A7 (no stack arguments)"
        );
    }

    #[test]
    fn debugger_without_installed_debugger_returns_to_caller() {
        // On a stock System 7/BasiliskII setup without MacsBug installed,
        // _Debugger returns immediately to the caller.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 0x1234_5678);
        cpu.write_reg(Register::A0, 0x00AA_5500);
        let result = dispatcher.dispatch_memory(true, 0x3FF, &mut cpu, &mut bus);
        assert!(result.is_some(), "Debugger should be handled");
        assert!(result.unwrap().is_ok(), "Debugger should return to caller");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0x1234_5678,
            "_Debugger no-op path should preserve D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x00AA_5500,
            "_Debugger no-op path should preserve A0"
        );
    }

    #[test]
    fn debugstr_trap_is_parameterless_and_preserves_stack_pointer() {
        // Inside Macintosh: Processes (1994), p. 7-9 and Inside Macintosh:
        // Memory (1992), p. 3-23 describe the debugger-entry trap entry
        // point. Systemless's no-debugger HLE path should return without
        // consuming stack space or perturbing scratch registers.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        cpu.write_reg(Register::D0, 0x1234_5678);
        cpu.write_reg(Register::A0, 0x00AA_5500);

        let result = dispatcher.dispatch_memory(true, 0x3FF, &mut cpu, &mut bus);
        assert!(result.is_some(), "DebugStr should be handled");
        assert!(result.unwrap().is_ok(), "DebugStr should return");
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "_DebugStr should preserve A7 (no stack arguments)"
        );
        assert_eq!(
            cpu.read_reg(Register::D0),
            0x1234_5678,
            "_DebugStr no-op path should preserve D0"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0x00AA_5500,
            "_DebugStr no-op path should preserve A0"
        );
    }

    #[test]
    fn test_get_tool_trap_address_tool() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0xAA55_AA55);

        cpu.write_reg(Register::D0, 0x0234);
        let result = dispatcher.dispatch_memory(true, 0x346, &mut cpu, &mut bus);
        assert!(
            result.is_some(),
            "GetToolTrapAddress (tool) should be handled"
        );
        assert!(
            result.unwrap().is_ok(),
            "GetToolTrapAddress (tool) should succeed"
        );
        let addr = cpu.read_reg(Register::A0);
        assert_eq!(
            addr,
            0xCAFE0000 + 0x0234,
            "GetToolTrapAddress (tool) should return 0xCAFE0000 + (trap & 0x3FF) in A0"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "GetToolTrapAddress (tool) should preserve A7"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0xAA55_AA55,
            "GetToolTrapAddress (tool) should leave caller stack memory untouched"
        );
    }

    #[test]
    fn gettooltrapaddress_trap_word_variant_returns_callable_trampoline() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let sp_before = cpu.read_reg(Register::A7);
        bus.write_long(sp_before, 0x1234_5678);

        // Simulate the real trap-instruction variant ($A746) so
        // dispatch_memory(false, 0x46, ..) takes the A746 branch.
        dispatcher.current_trap_word = 0xA746;
        cpu.write_reg(Register::D0, 0x00EC); // CopyBits tool-trap number

        let result = dispatcher.dispatch_memory(false, 0x46, &mut cpu, &mut bus);
        assert!(result.is_some(), "GetToolTrapAddress variant should be handled");
        assert!(
            result.unwrap().is_ok(),
            "GetToolTrapAddress variant should succeed"
        );

        let addr = cpu.read_reg(Register::A0);
        assert_ne!(addr, 0, "tool-trap trampoline address should be nonzero");
        assert!(
            !(0xCAFE0000..=0xCAFE03FF).contains(&addr),
            "A746 variant must return a callable trampoline, not a CAFE fake-ptr"
        );
        assert_eq!(
            bus.read_word(addr),
            0xACEC,
            "trampoline must encode auto-pop canonical trap word for CopyBits"
        );
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before,
            "GetToolTrapAddress variant should preserve A7"
        );
        assert_eq!(
            bus.read_long(sp_before),
            0x1234_5678,
            "GetToolTrapAddress variant should leave caller stack memory untouched"
        );
    }

    #[test]
    fn test_hand_to_hand() {
        // Inside Macintosh: Memory (1992), p. 2-62:
        // HandToHand returns a new handle to copied data in A0/theHndl.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        // Create a source handle with data
        cpu.write_reg(Register::D0, 8);
        let result = dispatcher.dispatch_memory(false, 0x22, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        let src_handle = cpu.read_reg(Register::A0);
        let src_ptr = bus.read_long(src_handle);
        bus.write_long(src_ptr, 0xDEADBEEF);
        bus.write_long(src_ptr + 4, 0xCAFEBABE);
        // Call HandToHand (0x1E1)
        cpu.write_reg(Register::A0, src_handle);
        let result = dispatcher.dispatch_memory(true, 0x1E1, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandToHand should be handled");
        assert!(result.unwrap().is_ok(), "HandToHand should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HandToHand should return noErr"
        );
        let new_handle = cpu.read_reg(Register::A0);
        assert_ne!(
            new_handle, src_handle,
            "HandToHand should return a different handle"
        );
        let new_ptr = bus.read_long(new_handle);
        assert_ne!(
            new_ptr, src_ptr,
            "HandToHand should allocate new data block"
        );
        assert_eq!(
            bus.read_long(new_ptr),
            0xDEADBEEF,
            "HandToHand should copy data"
        );
        assert_eq!(
            bus.read_long(new_ptr + 4),
            0xCAFEBABE,
            "HandToHand should copy data"
        );
    }

    #[test]
    fn test_hand_to_hand_nil_handle_returns_nilhandleerr() {
        // Inside Macintosh: Memory (1992), p. 2-63:
        // nilHandleErr (-109) for NIL master pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::A0, 0);
        let result = dispatcher.dispatch_memory(true, 0x1E1, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandToHand should be handled");
        assert!(result.unwrap().is_ok(), "HandToHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "HandToHand should return nilHandleErr (-109) for NIL handle"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "HandToHand should leave A0 as NIL on nilHandleErr"
        );
    }

    #[test]
    fn test_ptr_to_hand() {
        // Inside Macintosh: Memory (1992), p. 2-60:
        // PtrToHand returns a newly created handle whose bytes match srcPtr.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x300000u32;
        let data: [u8; 6] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
        for (i, &b) in data.iter().enumerate() {
            bus.write_byte(src + i as u32, b);
        }
        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::D0, data.len() as u32);
        let result = dispatcher.dispatch_memory(true, 0x1E3, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrToHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrToHand should succeed");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "PtrToHand should set D0 to 0 (noErr)"
        );
        let handle = cpu.read_reg(Register::A0);
        assert!(
            handle >= 0x200000,
            "PtrToHand should return a valid handle in A0, got ${:08X}",
            handle
        );
        let ptr = bus.read_long(handle);
        assert!(
            ptr >= 0x200000,
            "PtrToHand handle should point to a valid pointer, got ${:08X}",
            ptr
        );
        for (i, &b) in data.iter().enumerate() {
            assert_eq!(
                bus.read_byte(ptr + i as u32),
                b,
                "PtrToHand should copy byte {} correctly (expected 0x{:02X})",
                i,
                b
            );
        }
    }

    #[test]
    fn test_ptr_to_xhand_copies_bytes_and_returns_destination_handle() {
        // Inside Macintosh: Memory (1992), pp. 2-61..2-62:
        // PtrToXHand copies into an existing handle and returns dstHndl in A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        let src = 0x310000u32;
        let src_data: [u8; 4] = [0x41, 0x42, 0x43, 0x44];
        for (i, &b) in src_data.iter().enumerate() {
            bus.write_byte(src + i as u32, b);
        }

        cpu.write_reg(Register::D0, 3);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let dst_handle = cpu.read_reg(Register::A0);

        let dst_ptr_before = bus.read_long(dst_handle);
        for i in 0..3 {
            bus.write_byte(dst_ptr_before + i as u32, 0x7A);
        }

        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, dst_handle);
        cpu.write_reg(Register::D0, src_data.len() as u32);
        let result = dispatcher.dispatch_memory(true, 0x1E2, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrToXHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrToXHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "PtrToXHand should return noErr"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            dst_handle,
            "PtrToXHand should return destination handle in A0"
        );

        let dst_ptr_after = bus.read_long(dst_handle);
        assert_eq!(
            bus.get_alloc_size(dst_ptr_after),
            Some(src_data.len() as u32),
            "PtrToXHand should update the handle's logical size to the requested byte count"
        );
        for (i, &b) in src_data.iter().enumerate() {
            assert_eq!(
                bus.read_byte(dst_ptr_after + i as u32),
                b,
                "PtrToXHand should copy source byte {}",
                i
            );
        }
    }

    #[test]
    fn test_ptr_to_xhand_same_bucket_shrink_updates_logical_size() {
        // Inside Macintosh: Memory (1992), p. 2-61:
        // PtrToXHand makes dstHndl a handle to a copy of size bytes
        // beginning at srcPtr, even when the new logical size stays in
        // the same aligned heap bucket.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x320000u32;
        bus.write_byte(src, 0x5A);

        cpu.write_reg(Register::D0, 4);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let dst_handle = cpu.read_reg(Register::A0);
        let dst_ptr_before = bus.read_long(dst_handle);
        for i in 0..4 {
            bus.write_byte(dst_ptr_before + i as u32, 0x71 + i as u8);
        }

        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, dst_handle);
        cpu.write_reg(Register::D0, 1);
        let result = dispatcher.dispatch_memory(true, 0x1E2, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrToXHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrToXHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "PtrToXHand should return noErr"
        );

        let dst_ptr_after = bus.read_long(dst_handle);
        assert_eq!(
            bus.get_alloc_size(dst_ptr_after),
            Some(1),
            "PtrToXHand should shrink the handle's logical size inside the same aligned bucket"
        );
        assert_eq!(
            bus.read_byte(dst_ptr_after),
            0x5A,
            "PtrToXHand should preserve copied byte 0 when shrinking the destination"
        );
    }

    #[test]
    fn test_ptr_to_xhand_nil_destination_returns_nilhandleerr() {
        // Inside Macintosh: Memory (1992), p. 2-62:
        // nilHandleErr (-109) for NIL destination handle.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x320000u32;
        bus.write_byte(src, 0x55);
        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, 0);
        cpu.write_reg(Register::D0, 1);
        let result = dispatcher.dispatch_memory(true, 0x1E2, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrToXHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrToXHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "PtrToXHand should return nilHandleErr (-109) for NIL destination"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "PtrToXHand should return NIL destination handle in A0"
        );
    }

    #[test]
    fn test_hand_and_hand_appends_source_to_destination_and_returns_destination_handle() {
        // Inside Macintosh: Memory (1992), pp. 2-64..2-65:
        // HandAndHand appends aHndl to bHndl, leaves aHndl unchanged, returns bHndl in A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        cpu.write_reg(Register::D0, 2);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let src_handle = cpu.read_reg(Register::A0);
        let src_ptr = bus.read_long(src_handle);
        bus.write_byte(src_ptr, b'A');
        bus.write_byte(src_ptr + 1, b'B');

        cpu.write_reg(Register::D0, 2);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let dst_handle = cpu.read_reg(Register::A0);
        let dst_ptr = bus.read_long(dst_handle);
        bus.write_byte(dst_ptr, b'C');
        bus.write_byte(dst_ptr + 1, b'D');

        cpu.write_reg(Register::A0, src_handle);
        cpu.write_reg(Register::A1, dst_handle);
        let result = dispatcher.dispatch_memory(true, 0x1E4, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandAndHand should be handled");
        assert!(result.unwrap().is_ok(), "HandAndHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "HandAndHand should return noErr"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            dst_handle,
            "HandAndHand should return destination handle in A0"
        );

        let new_dst_ptr = bus.read_long(dst_handle);
        assert_eq!(bus.get_alloc_size(new_dst_ptr), Some(4));
        assert_eq!(bus.read_byte(new_dst_ptr), b'C');
        assert_eq!(bus.read_byte(new_dst_ptr + 1), b'D');
        assert_eq!(bus.read_byte(new_dst_ptr + 2), b'A');
        assert_eq!(bus.read_byte(new_dst_ptr + 3), b'B');

        assert_eq!(
            bus.read_byte(src_ptr),
            b'A',
            "HandAndHand should leave source handle contents unchanged"
        );
        assert_eq!(
            bus.read_byte(src_ptr + 1),
            b'B',
            "HandAndHand should leave source handle contents unchanged"
        );
    }

    #[test]
    fn test_hand_and_hand_nil_source_returns_nilhandleerr() {
        // Inside Macintosh: Memory (1992), p. 2-65:
        // nilHandleErr (-109) for NIL master pointer.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        cpu.write_reg(Register::D0, 1);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let dst_handle = cpu.read_reg(Register::A0);

        cpu.write_reg(Register::A0, 0);
        cpu.write_reg(Register::A1, dst_handle);
        let result = dispatcher.dispatch_memory(true, 0x1E4, &mut cpu, &mut bus);
        assert!(result.is_some(), "HandAndHand should be handled");
        assert!(result.unwrap().is_ok(), "HandAndHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "HandAndHand should return nilHandleErr (-109) when source handle is NIL"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            dst_handle,
            "HandAndHand should still return destination handle in A0"
        );
    }

    #[test]
    fn test_ptr_and_hand_appends_pointer_data_and_returns_destination_handle() {
        // Inside Macintosh: Memory (1992), pp. 2-65..2-66:
        // PtrAndHand appends bytes from pntr to hndl and returns hndl in A0.
        let (mut dispatcher, mut cpu, mut bus) = setup();

        cpu.write_reg(Register::D0, 3);
        dispatcher
            .dispatch_memory(false, 0x22, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let dst_handle = cpu.read_reg(Register::A0);
        let dst_ptr = bus.read_long(dst_handle);
        bus.write_byte(dst_ptr, b'H');
        bus.write_byte(dst_ptr + 1, b'E');
        bus.write_byte(dst_ptr + 2, b'L');

        let src = 0x330000u32;
        bus.write_byte(src, b'L');
        bus.write_byte(src + 1, b'O');

        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, dst_handle);
        cpu.write_reg(Register::D0, 2);
        let result = dispatcher.dispatch_memory(true, 0x1EF, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrAndHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrAndHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0),
            0,
            "PtrAndHand should return noErr"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            dst_handle,
            "PtrAndHand should return destination handle in A0"
        );

        let new_dst_ptr = bus.read_long(dst_handle);
        assert_eq!(bus.get_alloc_size(new_dst_ptr), Some(5));
        assert_eq!(bus.read_byte(new_dst_ptr), b'H');
        assert_eq!(bus.read_byte(new_dst_ptr + 1), b'E');
        assert_eq!(bus.read_byte(new_dst_ptr + 2), b'L');
        assert_eq!(bus.read_byte(new_dst_ptr + 3), b'L');
        assert_eq!(bus.read_byte(new_dst_ptr + 4), b'O');
    }

    #[test]
    fn test_ptr_and_hand_nil_destination_returns_nilhandleerr() {
        // Inside Macintosh: Memory (1992), p. 2-66:
        // nilHandleErr (-109) for NIL destination handle.
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let src = 0x340000u32;
        bus.write_byte(src, 0xAA);
        cpu.write_reg(Register::A0, src);
        cpu.write_reg(Register::A1, 0);
        cpu.write_reg(Register::D0, 1);
        let result = dispatcher.dispatch_memory(true, 0x1EF, &mut cpu, &mut bus);
        assert!(result.is_some(), "PtrAndHand should be handled");
        assert!(result.unwrap().is_ok(), "PtrAndHand should return");
        assert_eq!(
            cpu.read_reg(Register::D0) as i32,
            -109,
            "PtrAndHand should return nilHandleErr (-109) for NIL destination"
        );
        assert_eq!(
            cpu.read_reg(Register::A0),
            0,
            "PtrAndHand should return NIL destination handle in A0"
        );
    }

    // ==================== Unhandled trap returns None ====================

    #[test]
    fn test_unhandled_trap_returns_none() {
        let (mut dispatcher, mut cpu, mut bus) = setup();
        let result = dispatcher.dispatch_memory(false, 0xFFFF, &mut cpu, &mut bus);
        assert!(result.is_none(), "Unhandled trap should return None");
    }
}