i8051-disassembler 0.25.0

An i8051 disassembler, useful for structured disassembly.
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
use std::collections::BTreeMap;
use std::ops::RangeBounds;
use std::range::Range;
use std::sync::OnceLock;

mod weak;
mod xrefs;

pub use weak::{AutoDisassembleError, AutoDisassembleResult};
use weak::{CodeSource, Weak};
use xrefs::Xrefs;

use crate::address::{AddressRange, AddressSpace, AddressValue, PhysicalAddr, Xref, XrefType};
use crate::commands::{
    AutoDisassemble, Command, DisassembleRange, MapBytes, MarkData, MarkUnknown, OverrideOperand,
    SetComment, SetConstantBytes, SetFunction, SetLabel, boxed,
};
use crate::db::{
    Equivalent, EquivalentAt, EquivalentKind, EquivalentRange, Error, ErrorKind, Function,
    OperandOverride, SpaceUsage,
};
use crate::labels::{ImplicitLabels, LabelCollector, LabelKind, Labels};
use crate::pattern::BytePattern;
use crate::platform::{
    ControlFlow, DecodedInsn, PlatformRef, branch_target, branch_target_operand_index,
    xrefs_from_instruction,
};
use crate::render::Line;

#[derive(Debug, Clone)]
pub enum ByteRange {
    Mapped(String, usize, Vec<u8>),
    Constant(AddressValue, u8),
}

impl ByteRange {
    pub fn len(&self) -> AddressValue {
        match self {
            ByteRange::Mapped(_, _, data) => data.len() as AddressValue,
            ByteRange::Constant(size, _) => *size,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A basic block in a routine's control-flow graph: a maximal straight-line run
/// of instructions `[start, end)` with the starts of its successor blocks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Block {
    pub start: AddressValue,
    pub end: AddressValue,
    pub successors: Vec<AddressValue>,
}

/// A referenced control-flow target that is not a clean instruction start.
/// Either the decode has not reached it (`misaligned` false), or it lands
/// inside an already-decoded instruction (`misaligned` true, a decode error
/// upstream).
#[derive(Debug, Clone, Copy)]
pub(crate) struct ControlTarget {
    pub target: AddressValue,
    pub kind: XrefType,
    pub from: AddressValue,
    pub misaligned: bool,
}

/// A decoded run whose successor is not code: execution leaves known code.
#[derive(Debug, Clone, Copy)]
pub(crate) struct FlowLeak {
    pub from: AddressValue,
    pub to: AddressValue,
    pub kind: LeakKind,
}

/// Where a [`FlowLeak`] lands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeakKind {
    /// Into mapped bytes carrying no equivalent yet.
    IntoUndefined,
    /// Into bytes typed as data.
    IntoData,
    /// Past the end of mapped bytes.
    OffEnd,
}

/// One instruction from a scratch decode (see [`Region::scratch_decode`]).
#[derive(Debug, Clone)]
pub struct ScratchInsn {
    pub addr: AddressValue,
    pub text: String,
    pub bytes: Vec<u8>,
    /// The branch/call target, if the instruction has one.
    pub target: Option<AddressValue>,
    /// Whether `target` points at a mapped byte. A target beyond the loaded
    /// image is strong evidence the bytes are not really code.
    pub target_mapped: bool,
    /// Whether `target` lands inside an existing instruction rather than at its
    /// start. Also strong evidence the bytes are not really code.
    pub target_misaligned: bool,
    /// Whether `target` lands inside another instruction of this same decode (a
    /// self-misalignment suggests this is not code).
    pub target_self_misaligned: bool,
}

/// The result of decoding bytes as code without committing them: a look before
/// leaping to a real disassemble.
#[derive(Debug, Clone, Default)]
pub struct ScratchDecode {
    pub lines: Vec<ScratchInsn>,
    /// Flow ended at a return or unconditional jump (a clean block end).
    pub terminates: bool,
    /// Decoding stopped early because an opcode ran past the mapped bytes.
    pub ran_out: bool,
    /// How many decoded targets point outside the loaded image.
    pub out_of_range_targets: usize,
    /// How many decoded targets land inside an existing instruction.
    pub misaligned_targets: usize,
    /// How many decoded targets land inside another instruction of this same
    /// decode.
    pub self_misaligned_targets: usize,
}

/// Flag every target that lands inside another instruction of the same decode,
/// and total them into [`ScratchDecode::self_misaligned_targets`].
///
/// Run after the decode completes, because a target may point forward at an
/// instruction not yet decoded when its branch was read.
fn mark_self_misaligned(decode: &mut ScratchDecode) {
    let starts: std::collections::BTreeSet<AddressValue> =
        decode.lines.iter().map(|insn| insn.addr).collect();
    let (Some(first), Some(last)) = (decode.lines.first(), decode.lines.last()) else {
        return;
    };
    let span = first.addr..last.addr.saturating_add(last.bytes.len() as AddressValue);

    let mut count = 0;
    for insn in &mut decode.lines {
        let Some(target) = insn.target else { continue };
        if span.contains(&target) && !starts.contains(&target) {
            insn.target_self_misaligned = true;
            count += 1;
        }
    }
    decode.self_misaligned_targets = count;
}

/// What an instruction's ambiguous operand resolves to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperandType {
    /// An address in this space.
    Pointer(AddressSpace),
    /// A number, e.g.: a count, a mask, a register being cleared.
    Value,
}

/// How a label behaves beyond its text.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LabelAttrs {
    /// A working guess, left on the naming worklist.
    pub provisional: bool,
    /// Scoped to the enclosing routine, so its name need only be unique there.
    pub local: bool,
}

/// The nearest scope-delimiting label at or before `offset`.
fn scope_in(
    globals: &std::collections::BTreeSet<AddressValue>,
    offset: AddressValue,
) -> Option<AddressValue> {
    globals.range(..=offset).next_back().copied()
}

pub struct Region {
    space: AddressSpace,
    /// The driver that decodes this region's bytes. `None` until a CPU is set,
    /// in which case nothing decodes.
    platform: Option<PlatformRef>,
    byte_ranges: BTreeMap<AddressValue, ByteRange>,
    equivalents: BTreeMap<AddressValue, EquivalentRange>,
    labels: BTreeMap<AddressValue, String>,
    /// Addresses whose label is a working guess.
    draft_labels: std::collections::BTreeSet<AddressValue>,
    /// Addresses whose label is scoped to the routine containing it. Its name
    /// only has to be unique within that routine, so the same `.loop` may name
    /// a loop in every routine that has one.
    local_labels: std::collections::BTreeSet<AddressValue>,
    /// What an instruction's ambiguous operand turned out to mean, keyed by the
    /// instruction.
    operand_types: BTreeMap<AddressValue, OperandType>,
    /// Platform addresses we've chosen to disable (w/ a reason).
    disabled_platform_addresses: BTreeMap<AddressValue, String>,
    /// How many address lines the board actually decodes for this space, `None`
    /// means every line is decoded.
    address_bits: Option<u8>,
    comments: BTreeMap<AddressValue, String>,
    functions: BTreeMap<AddressValue, Function>,
    /// Operand overrides, keyed by `(instruction address, operand index)`.
    overrides: BTreeMap<(AddressValue, u8), OperandOverride>,
    /// The derived auto-disassembly layer (roots + their code). Reads overlay
    /// `equivalents` over `weak.code()`. Never serialized.
    weak: Weak,
    /// Reverse cross-reference index, derived from the code. Cleared on every
    /// code change and rebuilt on the next read. Never serialized.
    xrefs: OnceLock<Xrefs>,
}

impl Region {
    pub fn new(space: AddressSpace, platform: Option<PlatformRef>) -> Self {
        Self {
            space,
            platform,
            byte_ranges: BTreeMap::new(),
            equivalents: BTreeMap::new(),
            labels: BTreeMap::new(),
            address_bits: None,
            disabled_platform_addresses: BTreeMap::new(),
            operand_types: BTreeMap::new(),
            draft_labels: std::collections::BTreeSet::new(),
            local_labels: std::collections::BTreeSet::new(),
            comments: BTreeMap::new(),
            functions: BTreeMap::new(),
            overrides: BTreeMap::new(),
            weak: Weak::default(),
            xrefs: OnceLock::new(),
        }
    }

    /// Swap the decoding driver and re-derive, since decode results change.
    pub(crate) fn set_platform(&mut self, platform: Option<PlatformRef>) {
        self.platform = platform;
        self.refresh_weak();
        self.invalidate_xrefs();
    }

    /// Record what the ambiguous operand of the instruction at `offset` names.
    pub fn set_operand_type(
        &mut self,
        offset: AddressValue,
        kind: OperandType,
    ) -> Option<OperandType> {
        self.operand_types.insert(offset, kind)
    }

    /// Forget the decision for the instruction at `offset`.
    pub fn clear_operand_type(&mut self, offset: AddressValue) -> Option<OperandType> {
        self.operand_types.remove(&offset)
    }

    pub fn operand_type(&self, offset: AddressValue) -> Option<OperandType> {
        self.operand_types.get(&offset).copied()
    }

    /// Every disambiguated operand, in address order.
    pub fn operand_types(&self) -> impl Iterator<Item = (AddressValue, OperandType)> + '_ {
        self.operand_types.iter().map(|(&addr, &kind)| (addr, kind))
    }

    /// Targets reached only by inferred pointer references, as
    /// `(target, how many, the earliest source)`.
    pub(crate) fn inferred_pointer_candidates(&self) -> Vec<(PhysicalAddr, usize, AddressValue)> {
        let mut out = Vec::new();
        for (target, edges) in self.xref_index().targets() {
            let sources: Vec<AddressValue> = edges
                .iter()
                .filter(|e| {
                    e.kind == XrefType::Pointer
                        && e.certainty == crate::platform::Certainty::Inferred
                })
                .map(|e| e.from)
                .collect();
            let Some(&first) = sources.iter().min() else {
                continue;
            };
            out.push((*target, sources.len(), first));
        }
        out.sort_unstable_by_key(|(t, _, _)| (t.offset, t.space));
        out
    }

    /// The instructions that produce an inferred pointer to `target`.
    pub(crate) fn pointer_sources(&self, target: &PhysicalAddr) -> Vec<AddressValue> {
        self.xref_index()
            .to(target)
            .iter()
            .filter(|e| {
                e.kind == XrefType::Pointer && e.certainty == crate::platform::Certainty::Inferred
            })
            .map(|e| e.from)
            .collect()
    }

    /// Record that a platform address is disabled. Returns the previous reason,
    /// if it was already disabled.
    pub fn disable_platform_address(
        &mut self,
        offset: AddressValue,
        reason: String,
    ) -> Option<String> {
        self.disabled_platform_addresses.insert(offset, reason)
    }

    /// Restore the platform's claim about `offset`, returning the reason it had.
    pub fn enable_platform_address(&mut self, offset: AddressValue) -> Option<String> {
        self.disabled_platform_addresses.remove(&offset)
    }

    pub fn platform_address_disabled(&self, offset: AddressValue) -> bool {
        self.disabled_platform_addresses.contains_key(&offset)
    }

    /// Every disabled address with its reason, in address order.
    pub fn disabled_platform_addresses(&self) -> impl Iterator<Item = (AddressValue, &str)> + '_ {
        self.disabled_platform_addresses
            .iter()
            .map(|(&addr, reason)| (addr, reason.as_str()))
    }

    /// Narrow this space to the address lines the board decodes. `None` restores
    /// the full width. Returns the previous setting.
    pub fn set_address_bits(&mut self, bits: Option<u8>) -> Option<u8> {
        let previous = self.address_bits;
        self.address_bits = bits;
        self.invalidate_xrefs();
        previous
    }

    pub fn address_bits(&self) -> Option<u8> {
        self.address_bits
    }

    /// The byte an address actually reaches after `set_address_bits` is applied.
    pub fn effective(&self, offset: AddressValue) -> AddressValue {
        match self.address_bits {
            Some(bits) if (bits as u32) < AddressValue::BITS => offset & ((1u32 << bits) - 1),
            _ => offset,
        }
    }

    /// Set or clear the override at `(addr, index)`, returning the prior value.
    pub fn set_operand_override(
        &mut self,
        addr: AddressValue,
        index: u8,
        value: Option<OperandOverride>,
    ) -> Option<OperandOverride> {
        match value {
            Some(value) => self.overrides.insert((addr, index), value),
            None => self.overrides.remove(&(addr, index)),
        }
    }

    /// Operand overrides for the instruction at `addr`, as a positional vec.
    fn operand_overrides_at(&self, addr: AddressValue) -> Vec<Option<OperandOverride>> {
        let mut out = Vec::new();
        for (&(_, index), value) in self.overrides.range((addr, 0)..=(addr, u8::MAX)) {
            let index = index as usize;
            if out.len() <= index {
                out.resize(index + 1, None);
            }
            out[index] = Some(value.clone());
        }
        out
    }

    /// Lift the weak layer out to derive against `self` (which supplies the
    /// bytes and barriers via [`CodeSource`]), then put it back. The take avoids
    /// borrowing `self` mutably and immutably at once.
    fn with_weak<R>(&mut self, f: impl FnOnce(&mut Weak, &Self) -> R) -> R {
        let mut weak = std::mem::take(&mut self.weak);
        let result = f(&mut weak, self);
        self.weak = weak;
        result
    }

    fn refresh_weak(&mut self) {
        self.with_weak(|weak, src| weak.refresh(src));
    }

    /// Drop the cached xref index. Cheap: the rebuild is deferred to the next
    /// read, so a bulk load pays for one rebuild, not one per command.
    fn invalidate_xrefs(&mut self) {
        self.xrefs.take();
    }

    /// The reverse xref index, built on demand and cached until the next code
    /// change. Reads `self` (bytes, equivalents, weak) to derive the edges.
    fn xref_index(&self) -> &Xrefs {
        self.xrefs.get_or_init(|| Xrefs::build(self))
    }

    /// Auto-disassemble from `start`, recording it as a root (so the export is
    /// one `auto_disassemble` command). Returns the traversal diagnostics.
    pub fn auto_disassemble(&mut self, start: AddressValue) -> AutoDisassembleResult {
        let result = self.with_weak(|weak, src| weak.extend(src, start));
        self.invalidate_xrefs();
        result
    }

    pub fn add_auto_root(&mut self, start: AddressValue) {
        let _ = self.auto_disassemble(start);
    }

    /// Removing a root re-derives weak, so code reachable only through it drops.
    pub fn remove_auto_root(&mut self, start: AddressValue) -> bool {
        let removed = self.weak.remove_root(start);
        if removed {
            self.refresh_weak();
            self.invalidate_xrefs();
        }
        removed
    }

    pub fn is_auto_root(&self, start: AddressValue) -> bool {
        self.weak.contains_root(start)
    }

    fn is_code_start(&self, offset: AddressValue) -> bool {
        matches!(
            self.equivalents.get(&offset).map(|r| r.equivalent.kind()),
            Some(EquivalentKind::Code)
        ) || self.weak.code().contains_key(&offset)
    }

    /// If `addr` is a pure thunk, its forwarding target. A pure thunk is a code
    /// instruction whose entire body is one unconditional jump.
    fn thunk_target(&self, addr: AddressValue) -> Option<AddressValue> {
        if !self.is_code_start(addr) {
            return None;
        }
        match self.decode_at(addr)?.control_flow() {
            ControlFlow::Jump { target } => Some(target),
            _ => None,
        }
    }

    /// Follow pure jump thunks from `addr` to the ultimate target. Returns
    /// `addr` unchanged when it is not a thunk, and treats a jump cycle as not
    /// a thunk at all. The hop cap bounds degenerate chains.
    pub(crate) fn resolve_thunks(&self, addr: AddressValue) -> AddressValue {
        const MAX_HOPS: usize = 16;
        let mut seen = [addr; MAX_HOPS];
        let mut current = addr;
        for hops in 1..MAX_HOPS {
            let Some(next) = self.thunk_target(current) else {
                break;
            };
            if seen[..hops].contains(&next) {
                return addr;
            }
            seen[hops] = next;
            current = next;
        }
        current
    }

    /// The control-flow graph of the routine rooted at `entry`: maximal
    /// straight-line blocks split at branch targets and terminators. Calls fall
    /// through, except a call to a `noreturn` function, which ends its block.
    /// Derived on demand from the xref index and the linear code.
    pub(crate) fn basic_blocks(&self, entry: AddressValue) -> Vec<Block> {
        let index = self.xref_index();
        // Only control-flow edges make a leader. A data reference to a code
        // address (a table read, say) does not split a block.
        let is_leader = |addr: AddressValue| {
            index
                .to(&PhysicalAddr {
                    space: self.space,
                    offset: addr,
                })
                .iter()
                .any(|e| matches!(e.kind, XrefType::Call | XrefType::Jump))
        };
        let mut blocks: BTreeMap<AddressValue, Block> = BTreeMap::new();
        let mut worklist = vec![entry];
        while let Some(start) = worklist.pop() {
            if blocks.contains_key(&start) || !self.is_code_start(start) {
                continue;
            }
            let mut addr = start;
            let (end, successors) = loop {
                let Some(insn) = self.decode_at(addr) else {
                    break (addr, vec![]);
                };
                let next = addr + insn.len() as AddressValue;
                // `Some` ends the block with those successors. `None` extends it.
                let ended = match insn.control_flow() {
                    ControlFlow::Jump { target } => Some(vec![target]),
                    ControlFlow::Choice {
                        fall_through,
                        branch_target,
                    } => Some(vec![fall_through, branch_target]),
                    ControlFlow::Diverge => Some(vec![]),
                    ControlFlow::Call { target, return_pc } => {
                        if self.functions.get(&target).is_some_and(|f| f.noreturn) {
                            Some(vec![])
                        } else if is_leader(return_pc) {
                            Some(vec![return_pc])
                        } else {
                            None
                        }
                    }
                    ControlFlow::Continue { next } => is_leader(next).then(|| vec![next]),
                };
                match ended {
                    Some(successors) => break (next, successors),
                    None => addr = next,
                }
            };
            for &succ in &successors {
                worklist.push(succ);
            }
            blocks.insert(
                start,
                Block {
                    start,
                    end,
                    successors,
                },
            );
        }
        blocks.into_values().collect()
    }

    /// Every code instruction start across both layers, deduplicated.
    fn code_offsets(&self) -> Vec<AddressValue> {
        let mut offsets: Vec<AddressValue> = self
            .equivalents
            .iter()
            .filter(|(_, range)| matches!(range.equivalent, Equivalent::Code))
            .map(|(&offset, _)| offset)
            .collect();
        for &offset in self.weak.code().keys() {
            if !self.equivalents.contains_key(&offset) {
                offsets.push(offset);
            }
        }
        offsets
    }

    /// Nearest strong or weak start at/after `after`. Bounds undefined runs.
    fn next_equivalent_boundary(&self, after: AddressValue) -> Option<AddressValue> {
        let next_strong = self.equivalents.range(after..).next().map(|(&k, _)| k);
        let next_weak = self.weak.code().range(after..).next().map(|(&k, _)| k);
        [next_strong, next_weak].into_iter().flatten().min()
    }

    pub fn set_bytes(
        &mut self,
        file: &str,
        file_offset: usize,
        offset: AddressValue,
        bytes: &[u8],
    ) {
        self.map_bytes(file, file_offset, offset, bytes);
    }

    pub fn map_bytes(
        &mut self,
        file: &str,
        file_offset: usize,
        offset: AddressValue,
        bytes: &[u8],
    ) {
        if !bytes.is_empty() {
            self.unmap_bytes(offset, bytes.len() as AddressValue);
        }
        self.byte_ranges.insert(
            offset,
            ByteRange::Mapped(file.to_string(), file_offset, bytes.to_vec()),
        );
        self.refresh_weak();
        self.invalidate_xrefs();
    }

    pub fn set_constant(&mut self, offset: AddressValue, size: AddressValue, value: u8) {
        if size == 0 {
            return;
        }
        self.unmap_bytes(offset, size);
        self.byte_ranges
            .insert(offset, ByteRange::Constant(size, value));
        self.refresh_weak();
        self.invalidate_xrefs();
    }

    pub fn find_bytes(&self, pattern: &BytePattern) -> impl Iterator<Item = Range<AddressValue>> {
        self.find_bytes_in(pattern, ..)
    }

    /// Find bytes in a specific range (`..` searches the whole region).
    ///
    /// Cross-byte-range matches and constant-byte-range matches do not
    /// currently work.
    pub fn find_bytes_in(
        &self,
        pattern: &BytePattern,
        range: impl RangeBounds<AddressValue>,
    ) -> impl Iterator<Item = Range<AddressValue>> {
        let range = AddressRange::from(range);
        let end_inclusive = range.end.saturating_sub(1);
        self.byte_ranges
            .iter()
            .filter_map(move |(addr, byte_range)| match byte_range {
                ByteRange::Mapped(_, _, data) => {
                    if ranges_overlap_inclusive(
                        range.start,
                        end_inclusive,
                        *addr,
                        *addr + data.len() as AddressValue,
                    ) {
                        let data_start = range.start.saturating_sub(*addr) as usize;
                        let data_end = end_inclusive
                            .saturating_sub(*addr)
                            .min((data.len() - 1) as AddressValue)
                            as usize;
                        Some(
                            pattern
                                .find_all(&data[data_start..=data_end])
                                .map(move |range| {
                                    Range::from(
                                        range
                                            .start
                                            .saturating_add(data_start)
                                            .saturating_add(*addr as usize)
                                            ..range
                                                .end
                                                .saturating_add(data_start)
                                                .saturating_add(*addr as usize),
                                    )
                                }),
                        )
                    } else {
                        None
                    }
                }
                ByteRange::Constant(..) => None,
            })
            .flatten()
            .map(|range| Range::from(range.start as AddressValue..range.end as AddressValue))
    }

    pub(crate) fn snapshot_byte_ranges(
        &self,
        offset: AddressValue,
        size: AddressValue,
    ) -> Vec<(AddressValue, ByteRange)> {
        if size == 0 {
            return Vec::new();
        }
        let end = offset.saturating_add(size);
        self.byte_ranges
            .iter()
            .filter(|(start, range)| range.len() > offset && **start < end)
            .map(|(start, range)| (*start as AddressValue, range.clone()))
            .collect()
    }

    pub fn unmap_bytes(&mut self, offset: AddressValue, size: AddressValue) {
        if size == 0 {
            return;
        }
        let end = offset.saturating_add(size);
        let mut kept = BTreeMap::new();

        for (&start, range) in &self.byte_ranges {
            match range {
                ByteRange::Mapped(file, file_offset, data) => {
                    let range_end = start.saturating_add(data.len() as AddressValue);
                    if range_end <= offset || start >= end {
                        kept.insert(start, range.clone());
                        continue;
                    }
                    if start < offset {
                        let keep_len = offset - start;
                        kept.insert(
                            start,
                            ByteRange::Mapped(
                                file.clone(),
                                *file_offset,
                                data[..keep_len as usize].to_vec(),
                            ),
                        );
                    }
                    if range_end > end {
                        let skip = end.saturating_sub(start);
                        kept.insert(
                            end,
                            ByteRange::Mapped(
                                file.clone(),
                                file_offset.saturating_add(skip as usize),
                                data[skip as _..].to_vec(),
                            ),
                        );
                    }
                }
                ByteRange::Constant(count, value) => {
                    let range_end = start.saturating_add(*count);
                    if range_end <= offset || start >= end {
                        kept.insert(start, range.clone());
                        continue;
                    }
                    if start < offset {
                        kept.insert(start, ByteRange::Constant(offset - start, *value));
                    }
                    if range_end > end {
                        kept.insert(end, ByteRange::Constant(range_end - end, *value));
                    }
                }
            }
        }

        self.byte_ranges = kept;
        self.refresh_weak();
        self.invalidate_xrefs();
    }

    pub fn set_equivalent(
        &mut self,
        offset: AddressValue,
        equivalent: Equivalent,
    ) -> Result<&EquivalentRange, Error> {
        if self.has_equivalent(offset) {
            let (start, end, existing) = match self.get_equivalent(offset) {
                EquivalentAt::Defined { start, range } => {
                    (start, range.end, range.equivalent.kind())
                }
                EquivalentAt::Undefined(range) => (range.start, range.end, EquivalentKind::Unknown),
            };
            let requested_end = self
                .equivalent_span(offset, &equivalent)
                .map(|span| offset.saturating_add(span))
                .unwrap_or(offset.saturating_add(1));
            return Err(crate::db::already_classified(
                (self.space, offset).into(),
                existing,
                start,
                end,
                requested_end,
            ));
        }

        let span = self.equivalent_span(offset, &equivalent)?;
        self.validate_equivalent_bounds(offset, span)?;
        self.validate_no_equivalent_overlap(offset, span)?;

        // Only a barrier landing on already-derived code forces a re-derive (a
        // chop). A code island, or a barrier over undefined bytes, leaves weak as-is.
        let kind = equivalent.kind();
        let chops_weak = kind != EquivalentKind::Code && self.weak.overlaps(offset, span);
        self.equivalents.insert(
            offset,
            EquivalentRange {
                end: offset.saturating_add(span),
                equivalent,
            },
        );
        if chops_weak {
            self.refresh_weak();
            self.invalidate_xrefs();
        } else if kind == EquivalentKind::Code {
            // A strong code island adds a new instruction source.
            self.invalidate_xrefs();
        }
        Ok(&self.equivalents[&offset])
    }

    pub fn clear_equivalents(&mut self, offset: AddressValue, size: AddressValue) {
        if size == 0 {
            return;
        }
        let end = offset.saturating_add(size);
        self.equivalents
            .retain(|&start, range| range.end <= offset || start >= end);
        self.refresh_weak();
        self.invalidate_xrefs();
    }

    /// Linear-sweep `[start, end)` as strong code. Errors (mutating nothing) on
    /// a byte that doesn't decode or a strong overlap. The final instruction may
    /// run past `end`. Returns the actual end.
    pub(crate) fn disassemble_linear(
        &mut self,
        start: AddressValue,
        end: AddressValue,
    ) -> Result<AddressValue, Error> {
        // Validate up front so the inserts below can't fail, then re-derive weak once.
        let mut addr = start;
        let mut spans = Vec::new();
        while addr < end {
            let insn = self
                .decode_at(addr)
                .ok_or_else(|| Error::from(ErrorKind::InvalidEquivalent))?;
            let insn_end = addr.saturating_add(insn.len() as AddressValue);
            let overlaps = self.snapshot_equivalents(addr, insn_end - addr);
            if let Some((at, range)) = overlaps.first() {
                return Err(ErrorKind::Overlap {
                    at: self.space.dsl_addr(*at),
                    marked: crate::db::marked_word(range.equivalent.kind()).to_string(),
                }
                .into());
            }
            spans.push((addr, insn_end));
            addr = insn_end;
        }
        for (offset, insn_end) in spans {
            self.equivalents.insert(
                offset,
                EquivalentRange {
                    end: insn_end,
                    equivalent: Equivalent::Code,
                },
            );
        }
        self.refresh_weak();
        self.invalidate_xrefs();
        Ok(addr)
    }

    pub fn snapshot_equivalents(
        &self,
        offset: AddressValue,
        size: AddressValue,
    ) -> Vec<(AddressValue, EquivalentRange)> {
        if size == 0 {
            return Vec::new();
        }
        let end = offset.saturating_add(size);
        self.equivalents
            .iter()
            .filter(|(start, range)| ranges_overlap(**start, range.end, offset, end))
            .map(|(&start, range)| (start, range.clone()))
            .collect()
    }

    /// Whether a *strong* equivalent covers `offset`. Strong-only: a barrier may
    /// overwrite weak code, which then re-derives.
    pub fn has_equivalent(&self, offset: AddressValue) -> bool {
        lookup_in(&self.equivalents, offset).is_some()
    }

    pub fn get_equivalent_kind(&self, offset: AddressValue) -> Option<EquivalentKind> {
        match self.equivalent_at(offset) {
            EquivalentAt::Defined { range, .. } => Some(range.equivalent.kind()),
            EquivalentAt::Undefined(_) => None,
        }
    }

    pub fn get_equivalent(&self, offset: AddressValue) -> EquivalentAt<'_> {
        self.equivalent_at(offset)
    }

    fn equivalent_at(&self, offset: AddressValue) -> EquivalentAt<'_> {
        // Strong (data / unknown / code islands) overlays weak (derived code).
        match lookup_in(&self.equivalents, offset).or_else(|| lookup_in(self.weak.code(), offset)) {
            Some((start, range)) => EquivalentAt::Defined { start, range },
            None => EquivalentAt::Undefined(self.undefined_range_at(offset)),
        }
    }

    fn undefined_range_at(&self, offset: AddressValue) -> Range<AddressValue> {
        let after = offset.saturating_add(1);
        let next_eq = self.next_equivalent_boundary(after);
        let next_lbl = self.labels.range(after..).next().map(|(&k, _)| k);
        let next_cmt = self.comments.range(after..).next().map(|(&k, _)| k);
        let end = [Some(self.end()), next_eq, next_lbl, next_cmt]
            .into_iter()
            .flatten()
            .min()
            .unwrap_or(self.end());
        (offset..end).into()
    }

    /// Name `offset`.
    pub fn set_label(&mut self, offset: AddressValue, label: &str, attrs: LabelAttrs) {
        self.labels.insert(offset, label.to_string());
        if attrs.provisional {
            self.draft_labels.insert(offset);
        } else {
            self.draft_labels.remove(&offset);
        }
        if attrs.local {
            self.local_labels.insert(offset);
        } else {
            self.local_labels.remove(&offset);
        }
    }

    /// Whether the label at `offset` is scoped to its enclosing routine.
    pub fn is_local_label(&self, offset: AddressValue) -> bool {
        self.local_labels.contains(&offset)
    }

    /// The nearest non-local label at or before `offset`.
    pub fn scope_of(&self, offset: AddressValue) -> Option<AddressValue> {
        self.labels
            .range(..=offset)
            .rev()
            .map(|(&at, _)| at)
            .find(|at| !self.local_labels.contains(at))
    }

    /// Whether every reference to the local at `offset` comes from inside its
    /// own scope.
    fn local_is_self_contained(
        &self,
        offset: AddressValue,
        globals: &std::collections::BTreeSet<AddressValue>,
    ) -> bool {
        let scope = scope_in(globals, offset);
        let target = PhysicalAddr {
            space: self.space,
            offset,
        };
        self.xref_index()
            .to(&target)
            .iter()
            .all(|edge| scope_in(globals, edge.from) == scope)
    }

    /// The name to emit for each labelled address as *assembly*.
    pub(crate) fn export_names(&self, implicit: &Labels) -> BTreeMap<AddressValue, String> {
        let globals: std::collections::BTreeSet<AddressValue> = self
            .labels
            .keys()
            .copied()
            .filter(|at| !self.local_labels.contains(at))
            .chain(implicit.keys().copied())
            .collect();

        let mut out = BTreeMap::new();
        let mut per_scope: BTreeMap<Option<AddressValue>, usize> = BTreeMap::new();
        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
        for (&offset, name) in &self.labels {
            if self.local_labels.contains(&offset) && self.local_is_self_contained(offset, &globals)
            {
                let n = per_scope.entry(scope_in(&globals, offset)).or_insert(0);
                *n += 1;
                out.insert(offset, format!("{n}$"));
            } else {
                let count = seen.entry(name.clone()).or_insert(0);
                *count += 1;
                let unique = if *count > 1 {
                    format!("{name}_{}", *count - 1)
                } else {
                    name.clone()
                };
                out.insert(offset, unique);
            }
        }
        out
    }

    /// Addresses reached only by pointer references and still unnamed, as
    /// `(offset, how many, earliest source, every reference inferred)`.
    pub(crate) fn unnamed_pointer_targets(&self) -> Vec<(AddressValue, usize, AddressValue, bool)> {
        let mut out = Vec::new();
        for (target, edges) in self.xref_index().targets() {
            if target.space != self.space {
                continue;
            }
            let offset = target.offset;
            let pointers: Vec<&crate::region::xrefs::Edge> = edges
                .iter()
                .filter(|e| e.kind == XrefType::Pointer)
                .collect();
            if pointers.is_empty()
                || self.get_label(offset).is_some()
                || self.read_byte(offset).is_none()
                // A pointer into decoded code is a code reference; the naming
                // worklist already covers those.
                || matches!(self.get_equivalent_kind(offset), Some(EquivalentKind::Code))
            {
                continue;
            }
            let first = pointers.iter().map(|e| e.from).min().unwrap_or(offset);
            let inferred = pointers
                .iter()
                .all(|e| e.certainty == crate::platform::Certainty::Inferred);
            out.push((offset, pointers.len(), first, inferred));
        }
        out.sort_unstable();
        out
    }

    /// The extent of the instruction decoded at `offset`, if one starts there.
    pub fn instruction_range(&self, offset: AddressValue) -> Option<(AddressValue, AddressValue)> {
        match self.get_equivalent(offset) {
            EquivalentAt::Defined { range, .. } if matches!(range.equivalent, Equivalent::Code) => {
                Some((offset, range.end))
            }
            _ => None,
        }
    }

    /// The instruction `offset` falls inside, if it is not at its start.
    pub fn covering_instruction(
        &self,
        offset: AddressValue,
    ) -> Option<(AddressValue, AddressValue)> {
        match self.get_equivalent(offset) {
            EquivalentAt::Defined { start, range }
                if matches!(range.equivalent, Equivalent::Code) && start != offset =>
            {
                Some((start, range.end))
            }
            _ => None,
        }
    }

    /// Narrowest address width covering every mapped byte.
    pub fn covering_address_bits(&self) -> u8 {
        let end = self.end();
        let mut bits = 1u8;
        while bits < 32 && (1u64 << bits) < u64::from(end) {
            bits += 1;
        }
        bits
    }

    /// Unmapped stretches sitting between mapped bytes that should arguably be
    /// mapper or filled.
    pub fn mapping_gaps(&self) -> Vec<(AddressValue, AddressValue)> {
        let mut gaps = Vec::new();
        let mut previous_end: Option<AddressValue> = None;
        for (&start, range) in &self.byte_ranges {
            if let Some(end) = previous_end
                && start > end
            {
                gaps.push((end, start));
            }
            previous_end = Some(start + range.len());
        }
        gaps
    }

    /// Whether `offset` has a mapped byte.
    pub fn has_byte(&self, offset: AddressValue) -> bool {
        self.read_byte(offset).is_some()
    }

    /// Whether the label at `offset` is a working guess rather than finalized.
    pub fn is_draft_label(&self, offset: AddressValue) -> bool {
        self.draft_labels.contains(&offset)
    }

    pub fn clear_label(&mut self, offset: AddressValue) {
        self.labels.remove(&offset);
        self.draft_labels.remove(&offset);
        self.local_labels.remove(&offset);
    }

    pub fn get_label(&self, offset: AddressValue) -> Option<&str> {
        self.labels
            .get(&(offset as AddressValue))
            .map(String::as_str)
    }

    pub fn set_comment(&mut self, offset: AddressValue, comment: &str) {
        self.comments
            .insert(offset as AddressValue, comment.to_string());
    }

    pub fn clear_comment(&mut self, offset: AddressValue) {
        self.comments.remove(&(offset as AddressValue));
    }

    pub fn get_comment(&self, offset: AddressValue) -> Option<&str> {
        self.comments
            .get(&(offset as AddressValue))
            .map(String::as_str)
    }

    pub fn set_function(&mut self, function: Function) {
        self.functions
            .insert(function.addr.offset as AddressValue, function);
    }

    pub fn get_function(&self, offset: AddressValue) -> Option<&Function> {
        self.functions.get(&(offset as AddressValue))
    }

    /// Every label in this region, in ascending address order.
    pub fn labels(&self) -> impl Iterator<Item = (AddressValue, &str)> {
        self.labels
            .iter()
            .map(|(&addr, name)| (addr, name.as_str()))
    }

    /// Every function in this region, in ascending address order.
    pub fn functions(&self) -> impl Iterator<Item = (AddressValue, &Function)> {
        self.functions.iter().map(|(&addr, func)| (addr, func))
    }

    pub fn clear_function(&mut self, offset: AddressValue) {
        self.functions.remove(&(offset as AddressValue));
    }

    /// Remove every label in `range`, returning the removed `(address, label)`
    /// pairs (for undo).
    pub fn clear_labels_in(
        &mut self,
        range: impl RangeBounds<AddressValue>,
    ) -> Vec<(AddressValue, String)> {
        let keys: Vec<AddressValue> = self.labels.range(range).map(|(&k, _)| k).collect();
        keys.into_iter()
            .filter_map(|k| {
                self.draft_labels.remove(&k);
                self.local_labels.remove(&k);
                self.labels.remove(&k).map(|v| (k, v))
            })
            .collect()
    }

    /// Remove every comment in `range`, returning the removed pairs.
    pub fn clear_comments_in(
        &mut self,
        range: impl RangeBounds<AddressValue>,
    ) -> Vec<(AddressValue, String)> {
        let keys: Vec<AddressValue> = self.comments.range(range).map(|(&k, _)| k).collect();
        keys.into_iter()
            .filter_map(|k| self.comments.remove(&k).map(|v| (k, v)))
            .collect()
    }

    /// Remove every function in `range`, returning the removed `(address,
    /// function)` pairs.
    pub fn clear_functions_in(
        &mut self,
        range: impl RangeBounds<AddressValue>,
    ) -> Vec<(AddressValue, Function)> {
        let keys: Vec<AddressValue> = self.functions.range(range).map(|(&k, _)| k).collect();
        keys.into_iter()
            .filter_map(|k| self.functions.remove(&k).map(|v| (k, v)))
            .collect()
    }

    pub fn byte_at(&self, offset: AddressValue) -> Option<u8> {
        self.read_byte(offset)
    }

    pub fn read_u16_le(&self, offset: AddressValue) -> Option<u16> {
        let low = self.read_byte(offset)?;
        let high = self.read_byte(offset.saturating_add(1))?;
        Some((low as u16) | ((high as u16) << 8))
    }

    pub fn read_u16_be(&self, offset: AddressValue) -> Option<u16> {
        let high = self.read_byte(offset)?;
        let low = self.read_byte(offset.saturating_add(1))?;
        Some((high as u16) | ((low as u16) << 8))
    }

    pub fn bytes_at(&self, offset: AddressValue, size: AddressValue) -> Vec<u8> {
        (0..size)
            .filter_map(|i| self.read_byte(offset + i))
            .collect()
    }

    /// Count mapped bytes classified as code, data, or undefined (no equivalent).
    pub fn space_usage(&self) -> SpaceUsage {
        let mut usage = SpaceUsage::default();
        for (&start, range) in &self.equivalents {
            let span = range.end.saturating_sub(start);
            match &range.equivalent {
                Equivalent::Code => usage.code += span,
                Equivalent::Data(_, _) => usage.data += span,
                Equivalent::Unknown(_) => {} // counts as undefined, via subtraction below
            }
        }
        // Weak code, minus strong islands already counted.
        for (&start, range) in self.weak.code() {
            if !self.equivalents.contains_key(&start) {
                usage.code += range.end.saturating_sub(start);
            }
        }

        let mapped: AddressValue = self.byte_ranges.values().map(ByteRange::len).sum();

        usage.undefined = mapped.saturating_sub(usage.code).saturating_sub(usage.data);

        usage
    }

    /// Byte counts for the completeness assessment, deriving `undefined` from
    /// the actual undefined spans (so it is correct regardless of where mapped
    /// ranges are based).
    pub(crate) fn coverage(&self) -> SpaceUsage {
        let mut usage = SpaceUsage::default();
        for (&start, range) in &self.equivalents {
            let span = range.end.saturating_sub(start);
            match &range.equivalent {
                Equivalent::Code => usage.code += span,
                Equivalent::Data(_, _) => usage.data += span,
                Equivalent::Unknown(_) => {}
            }
        }
        for (&start, range) in self.weak.code() {
            if !self.equivalents.contains_key(&start) {
                usage.code += range.end.saturating_sub(start);
            }
        }
        usage.undefined = self.undefined_spans().iter().map(|(a, b)| b - a).sum();
        usage
    }

    /// Half-open `[start, end)` spans of mapped bytes carrying no equivalent
    /// (rendered raw). Adjacent spans across byte-range boundaries coalesce.
    pub(crate) fn undefined_spans(&self) -> Vec<(AddressValue, AddressValue)> {
        let mut spans: Vec<(AddressValue, AddressValue)> = Vec::new();
        for (&start, byte_range) in &self.byte_ranges {
            let range_end = start.saturating_add(byte_range.len());
            let mut addr = start;
            while addr < range_end {
                match self.get_equivalent(addr) {
                    EquivalentAt::Undefined(run) => {
                        let end = run.end.min(range_end);
                        match spans.last_mut() {
                            Some(last) if last.1 == addr => last.1 = end,
                            _ => spans.push((addr, end)),
                        }
                        addr = end.max(addr.saturating_add(1));
                    }
                    EquivalentAt::Defined { range, .. } => {
                        addr = range.end.min(range_end).max(addr.saturating_add(1));
                    }
                }
            }
        }
        spans
    }

    /// Control-flow targets (calls/jumps) that are not clean instruction starts.
    pub(crate) fn unresolved_control_targets(&self) -> Vec<ControlTarget> {
        let index = self.xref_index();
        let mut out = Vec::new();
        for (target, edges) in index.targets() {
            if target.space != self.space || self.is_code_start(target.offset) {
                continue;
            }
            let edge = edges
                .iter()
                .find(|e| e.kind == XrefType::Call)
                .or_else(|| edges.iter().find(|e| e.kind == XrefType::Jump));
            let Some(edge) = edge else {
                continue;
            };
            let misaligned = matches!(
                self.get_equivalent_kind(target.offset),
                Some(EquivalentKind::Code)
            );
            out.push(ControlTarget {
                target: target.offset,
                kind: edge.kind,
                from: edge.from,
                misaligned,
            });
        }
        out
    }

    /// Decoded runs whose successor is not code (execution leaves known code).
    pub(crate) fn flow_leaks(&self) -> Vec<FlowLeak> {
        let mut leaks = Vec::new();
        for offset in self.code_offsets() {
            let Some(insn) = self.decode_at(offset) else {
                continue;
            };
            let successor = match insn.control_flow() {
                ControlFlow::Continue { next } => Some(next),
                ControlFlow::Choice { fall_through, .. } => Some(fall_through),
                ControlFlow::Call { return_pc, .. } => Some(return_pc),
                ControlFlow::Jump { .. } | ControlFlow::Diverge => None,
            };
            let Some(to) = successor else {
                continue;
            };
            if self.is_code_start(to) {
                continue;
            }
            let kind = if self.read_byte(to).is_none() {
                LeakKind::OffEnd
            } else if matches!(self.get_equivalent_kind(to), Some(EquivalentKind::Data)) {
                LeakKind::IntoData
            } else {
                LeakKind::IntoUndefined
            };
            leaks.push(FlowLeak {
                from: offset,
                to,
                kind,
            });
        }
        leaks
    }

    /// Decode bytes as code from `start` to `end` in a linear fashion without
    /// committing anything, ignoring control flow. Detects if a run is code
    /// before disassembling it (out-of-range targets flags likely garbage).
    pub(crate) fn scratch_decode_linear(
        &self,
        start: AddressValue,
        end: AddressValue,
    ) -> ScratchDecode {
        let mut result = ScratchDecode::default();
        let mut addr = start;
        while addr < end {
            let Some(insn) = self.decode_at(addr) else {
                result.ran_out = true;
                break;
            };
            let target = branch_target(&insn).map(|t| self.effective(t));
            let target_mapped = target.is_none_or(|t| self.read_byte(t).is_some());
            let target_misaligned = target.is_some_and(|t| {
                matches!(self.get_equivalent_kind(t), Some(EquivalentKind::Code))
                    && !self.is_code_start(t)
            });
            if !target_mapped {
                result.out_of_range_targets += 1;
            }
            if target_misaligned {
                result.misaligned_targets += 1;
            }
            result.lines.push(ScratchInsn {
                addr,
                text: insn.as_string().to_string(),
                bytes: insn.bytes().to_vec(),
                target,
                target_mapped,
                target_misaligned,
                target_self_misaligned: false,
            });
            addr = addr.saturating_add(insn.len() as AddressValue);
        }
        mark_self_misaligned(&mut result);
        result
    }

    /// Decode bytes as code from `start` without committing anything, following
    /// fall-through up to `max_lines` instructions and stopping at the first
    /// return or unconditional jump. Lets a caller judge whether a run is code
    /// before disassembling it (out-of-range targets flag likely garbage).
    pub(crate) fn scratch_decode(&self, start: AddressValue, max_lines: usize) -> ScratchDecode {
        let mut result = ScratchDecode::default();
        let mut addr = start;
        for _ in 0..max_lines {
            let Some(insn) = self.decode_at(addr) else {
                result.ran_out = true;
                break;
            };
            let target = branch_target(&insn).map(|t| self.effective(t));
            let target_mapped = target.is_none_or(|t| self.read_byte(t).is_some());
            // Misaligned only makes sense for a mapped target already decoded as
            // code.
            let target_misaligned = target.is_some_and(|t| {
                matches!(self.get_equivalent_kind(t), Some(EquivalentKind::Code))
                    && !self.is_code_start(t)
            });
            if !target_mapped {
                result.out_of_range_targets += 1;
            }
            if target_misaligned {
                result.misaligned_targets += 1;
            }
            result.lines.push(ScratchInsn {
                addr,
                text: insn.as_string().to_string(),
                bytes: insn.bytes().to_vec(),
                target,
                target_mapped,
                target_misaligned,
                target_self_misaligned: false,
            });
            addr = match insn.control_flow() {
                ControlFlow::Continue { next } => next,
                ControlFlow::Choice { fall_through, .. } => fall_through,
                ControlFlow::Call { return_pc, .. } => return_pc,
                ControlFlow::Jump { .. } | ControlFlow::Diverge => {
                    result.terminates = true;
                    break;
                }
            };
        }
        mark_self_misaligned(&mut result);
        result
    }

    /// The rendered mnemonic of the instruction at `offset`, if one decodes
    /// there. Used to give a caller enough context to name a routine.
    pub(crate) fn instruction_text(&self, offset: AddressValue) -> Option<String> {
        self.decode_at(offset)
            .map(|insn| insn.as_string().trim().to_string())
    }

    /// Referenced code targets in this region carrying only an auto-generated
    /// name (`sub_`/`loc_`), the provisional labels an assessment flags for
    /// naming. Mirrors [`collect_refs`](Region::collect_refs).
    pub(crate) fn provisional_labels(&self) -> Vec<(AddressValue, LabelKind)> {
        let index = self.xref_index();
        let mut out = Vec::new();
        for (target, edges) in index.targets() {
            let finalized =
                self.get_label(target.offset).is_some() && !self.is_draft_label(target.offset);
            if target.space != self.space || finalized {
                continue;
            }
            let kind = if edges.iter().any(|e| e.kind == XrefType::Call) {
                LabelKind::Sub
            } else if edges.iter().any(|e| e.kind == XrefType::Jump) {
                LabelKind::Loc
            } else {
                continue;
            };
            out.push((target.offset, kind));
        }
        out
    }

    /// Named routines in this region: code entries that carry a real
    /// (non-provisional) label and are either called or marked as functions.
    pub(crate) fn named_routines(&self) -> Vec<(AddressValue, String)> {
        let index = self.xref_index();
        let mut out: Vec<(AddressValue, String)> = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for (target, edges) in index.targets() {
            if target.space != self.space {
                continue;
            }
            let Some(name) = self.get_label(target.offset) else {
                continue;
            };
            if edges.iter().any(|e| e.kind == XrefType::Call) && seen.insert(target.offset) {
                out.push((target.offset, name.to_string()));
            }
        }
        for (offset, _func) in self.functions() {
            if let Some(name) = self.get_label(offset)
                && seen.insert(offset)
            {
                out.push((offset, name.to_string()));
            }
        }
        out.sort_by_key(|(offset, _)| *offset);
        out
    }

    pub(crate) fn render(
        &self,
        space: AddressSpace,
        implicit_labels: &ImplicitLabels,
    ) -> Vec<Line> {
        self.render_named(space, implicit_labels, None)
    }

    /// `render`, but emitting `names` in place of each address's stored label.
    pub(crate) fn render_named(
        &self,
        space: AddressSpace,
        implicit_labels: &ImplicitLabels,
        names: Option<&BTreeMap<AddressValue, String>>,
    ) -> Vec<Line> {
        let mut lines = Vec::new();
        let start = self.start();
        let end = self.end();
        if start >= end {
            return lines;
        }

        let default_labels = Labels::default();
        let labels = implicit_labels.get(&space).unwrap_or(&default_labels);

        let mut addr = start;
        let mut need_org = true;
        while addr < end {
            if need_org {
                lines.push(Line::Org { addr });
                lines.push(Line::Blank);
                need_org = false;
            }

            if let Some(function) = self.get_function(addr) {
                lines.push(Line::Function {
                    addr,
                    name: function.name.clone(),
                    signature: function.signature.clone(),
                    length: function.length,
                    noreturn: function.noreturn,
                });
            }
            if let Some(comment) = self.get_comment(addr) {
                lines.push(Line::Comment {
                    addr,
                    text: comment.to_string(),
                });
            }
            let exported = names.and_then(|m| m.get(&addr)).map(String::as_str);
            if let Some(label) = exported.or_else(|| self.get_label(addr)) {
                lines.push(Line::Label {
                    addr,
                    name: label.to_string(),
                });
            } else if let Some(label) = labels.get(&addr) {
                lines.push(Line::Label {
                    addr,
                    name: label.to_string(),
                });
            }

            match self.get_equivalent(addr) {
                EquivalentAt::Defined { start: _, range } => match &range.equivalent {
                    Equivalent::Code => {
                        let insn = self
                            .decode_at(addr)
                            .expect("validated code equivalent must decode");
                        let overrides = self.operand_overrides_at(addr);
                        let text = self.format_instruction(addr, &insn, &overrides, labels, names);
                        lines.push(Line::Instruction {
                            addr,
                            direct: insn.direct_addr(),
                            text,
                            bytes: insn.bytes().to_vec(),
                            target: branch_target(&insn),
                        });
                        addr = range.end;
                    }
                    Equivalent::Data(data_type, size) => {
                        // Swallowing a label undefines its references.
                        let end = self
                            .next_annotation(addr, labels)
                            .map_or(range.end, |next| range.end.min(next));
                        let size = end.saturating_sub(addr).min(*size).max(1);
                        let bytes = self.bytes_at(addr, size);
                        lines.push(Line::Data {
                            addr,
                            data_type: data_type.clone(),
                            bytes,
                        });
                        addr = addr.saturating_add(size);
                    }
                    Equivalent::Unknown(_) => {
                        let span = self.raw_span(addr, labels);
                        let bytes = self.bytes_at(addr, span);
                        lines.push(Line::Raw { addr, bytes });
                        addr += span;
                    }
                },
                EquivalentAt::Undefined(undefined) => {
                    let span = self.raw_span(addr, labels);
                    if span == 0 {
                        if let Some((&next_mapped, _)) =
                            self.byte_ranges.range(addr.saturating_add(1)..).next()
                            && next_mapped < undefined.end
                        {
                            addr = next_mapped;
                            need_org = true;
                            continue;
                        }
                        addr += 1;
                        continue;
                    }
                    let bytes = self.bytes_at(addr, span);
                    lines.push(Line::Raw { addr, bytes });
                    addr += span;
                }
            }
        }

        lines
    }

    pub(crate) fn to_commands(&self, space: AddressSpace) -> Vec<Box<dyn Command>> {
        let mut commands = Vec::new();
        for (&offset, range) in &self.byte_ranges {
            match range {
                ByteRange::Mapped(file, file_offset, data) => {
                    commands.push(boxed(MapBytes::new(
                        (space, offset),
                        file.clone(),
                        *file_offset,
                        data.len() as AddressValue,
                    )));
                }
                ByteRange::Constant(size, value) => {
                    commands.push(boxed(SetConstantBytes::new(
                        (space, offset..offset + *size),
                        *value,
                    )));
                }
            }
        }

        // Barriers must precede the roots so they're in place when reload re-derives.
        for (&offset, equivalent_range) in &self.equivalents {
            match &equivalent_range.equivalent {
                Equivalent::Data(data_type, _) => {
                    commands.push(boxed(MarkData::new(
                        (space, offset..equivalent_range.end),
                        data_type.clone(),
                    )));
                }
                Equivalent::Unknown(_) => {
                    commands.push(boxed(MarkUnknown::new((
                        space,
                        offset..equivalent_range.end,
                    ))));
                }
                Equivalent::Code => {}
            }
        }

        for root in self.weak.roots() {
            commands.push(boxed(AutoDisassemble::new((space, root))));
        }

        // Manual code islands (strong code no root covers), coalesced into one
        // `disassemble_range` per contiguous run.
        let mut run: Option<(AddressValue, AddressValue)> = None;
        for (&offset, equivalent_range) in &self.equivalents {
            let island = matches!(equivalent_range.equivalent, Equivalent::Code)
                && !self.weak.code().contains_key(&offset);
            match (run, island) {
                (Some((start, end)), true) if end == offset => {
                    run = Some((start, equivalent_range.end));
                }
                (Some((start, end)), _) => {
                    commands.push(boxed(DisassembleRange::new((space, start..end), true)));
                    run = island.then_some((offset, equivalent_range.end));
                }
                (None, true) => run = Some((offset, equivalent_range.end)),
                (None, false) => {}
            }
        }
        if let Some((start, end)) = run {
            commands.push(boxed(DisassembleRange::new((space, start..end), true)));
        }

        for (&(offset, index), value) in &self.overrides {
            commands.push(boxed(OverrideOperand::new(
                (space, offset),
                index,
                Some(value.clone()),
            )));
        }

        for (&offset, label) in &self.labels {
            commands.push(boxed(SetLabel::new(
                (space, offset),
                label.clone(),
                self.draft_labels.contains(&offset),
                self.local_labels.contains(&offset),
            )));
        }
        for (&offset, comment) in &self.comments {
            commands.push(boxed(SetComment::new((space, offset), comment.clone())));
        }
        for (&offset, function) in &self.functions {
            commands.push(boxed(SetFunction::new((space, offset), function.clone())));
        }
        commands
    }

    pub(crate) fn xrefs_to(&self, target: &PhysicalAddr) -> Vec<Xref> {
        self.xref_index()
            .to(target)
            .iter()
            .map(|edge| Xref {
                from: PhysicalAddr {
                    space: self.space,
                    offset: edge.from,
                },
                to: *target,
                xref_type: edge.kind,
                certainty: edge.certainty,
            })
            .collect()
    }

    pub(crate) fn xrefs_from(&self, source: &PhysicalAddr) -> Vec<Xref> {
        let offset = source.offset;
        if !self.is_code_start(offset) {
            return Vec::new();
        }
        let Some(instruction) = self.decode_at(offset) else {
            return Vec::new();
        };
        xrefs_from_instruction(&instruction, *source)
    }

    /// Feed implicit code labels from the xref index: every code target with an
    /// inbound call (`sub_`) or jump (`loc_`) that lacks an explicit name.
    pub(crate) fn collect_refs(&self, refs: &mut LabelCollector) {
        let index = self.xref_index();
        for (target, edges) in index.targets() {
            // Implicit code labels only apply to targets in this region's own
            // (code) space, data references into other spaces are not labelled.
            let finalized =
                self.get_label(target.offset).is_some() && !self.is_draft_label(target.offset);
            if target.space != self.space || finalized {
                continue;
            }
            let kind = if edges.iter().any(|e| e.kind == XrefType::Call) {
                LabelKind::Sub
            } else if edges.iter().any(|e| e.kind == XrefType::Jump) {
                LabelKind::Loc
            } else {
                continue;
            };
            refs.collect(*target, kind);
        }
    }

    fn start(&self) -> AddressValue {
        [
            self.byte_ranges.keys().copied().next(),
            self.equivalents.keys().copied().next(),
            self.labels.keys().copied().next(),
            self.comments.keys().copied().next(),
        ]
        .into_iter()
        .flatten()
        .min()
        .unwrap_or(0) as AddressValue
    }

    /// Upper bound (exclusive) of mapped bytes and equivalents.
    fn end(&self) -> AddressValue {
        [
            self.byte_ranges
                .iter()
                .next_back()
                .map(|(&start, range)| start + range.len()),
            self.equivalents
                .iter()
                .next_back()
                .map(|(&start, range)| start + range.end),
            self.labels.keys().next_back().copied(),
            self.comments.keys().next_back().copied(),
            self.functions.keys().next_back().copied(),
        ]
        .into_iter()
        .flatten()
        .max()
        .map(|addr| addr + 1)
        .unwrap_or(0)
    }

    fn read_byte(&self, offset: AddressValue) -> Option<u8> {
        let (&start, range) = self.byte_ranges.range(..=offset).next_back()?;
        match range {
            ByteRange::Mapped(_, _, data) => data.get((offset - start) as usize).copied(),
            ByteRange::Constant(size, value) if offset - start < *size => Some(*value),
            ByteRange::Constant(_, _) => None,
        }
    }

    fn decode_at(&self, address: AddressValue) -> Option<DecodedInsn> {
        // No CPU means nothing decodes.
        let platform = self.platform.as_ref()?;
        let max = platform.max_insn_len();
        let mut available = Vec::with_capacity(max);

        for i in 0..max as AddressValue {
            if let Some(b) = self.read_byte(address + i) {
                available.push(b);
            } else {
                break;
            }
        }
        if available.is_empty() {
            return None;
        }

        let ins = platform.decode(address, &available);
        if ins.len() > available.len() {
            return None;
        }

        Some(ins)
    }

    pub(crate) fn equivalent_span(
        &self,
        offset: AddressValue,
        equivalent: &Equivalent,
    ) -> Result<AddressValue, Error> {
        match equivalent {
            Equivalent::Code => self
                .decode_at(offset)
                .map(|insn| insn.len() as AddressValue)
                .ok_or_else(|| Error::from(ErrorKind::InvalidEquivalent)),
            Equivalent::Data(_, size) => Ok(*size),
            Equivalent::Unknown(size) => Ok(*size),
        }
    }

    fn validate_equivalent_bounds(
        &self,
        offset: AddressValue,
        span: AddressValue,
    ) -> Result<(), Error> {
        for i in 0..span {
            if self.read_byte(offset + i).is_none() {
                return Err(crate::db::nothing_mapped(self.space, offset + i));
            }
        }
        Ok(())
    }

    fn validate_no_equivalent_overlap(
        &self,
        offset: AddressValue,
        span: AddressValue,
    ) -> Result<(), Error> {
        let end = offset.saturating_add(span);
        if let Some((&other_start, other)) = self.equivalents.range(..end).next_back()
            && other.end > offset
        {
            return Err(ErrorKind::Overlap {
                at: self.space.dsl_addr(other_start),
                marked: crate::db::marked_word(other.equivalent.kind()).to_string(),
            }
            .into());
        }
        Ok(())
    }

    /// Nearest address after `addr` needing its own line.
    fn next_annotation(
        &self,
        addr: AddressValue,
        implicit_labels: &Labels,
    ) -> Option<AddressValue> {
        let after = addr.saturating_add(1);
        [
            self.labels.range(after..).next().map(|(&k, _)| k),
            self.comments.range(after..).next().map(|(&k, _)| k),
            self.functions.range(after..).next().map(|(&k, _)| k),
            implicit_labels.range(after..).next().map(|(&k, _)| k),
        ]
        .into_iter()
        .flatten()
        .min()
    }

    /// The length of the coalesced raw region at `addr`.
    fn raw_span(&self, addr: AddressValue, implicit_labels: &Labels) -> AddressValue {
        let boundary = self
            .next_annotation(addr, implicit_labels)
            .map_or(self.end(), |next| self.end().min(next));

        let mut cur = addr;
        while cur < boundary {
            match self.get_equivalent(cur) {
                EquivalentAt::Defined { range, .. } => match &range.equivalent {
                    Equivalent::Unknown(_) => cur = range.end.min(boundary),
                    Equivalent::Code | Equivalent::Data(..) => break,
                },
                EquivalentAt::Undefined(undefined) => {
                    let limit = boundary.min(undefined.end);
                    let mut end = cur;
                    while end < limit && self.read_byte(end).is_some() {
                        end += 1;
                    }
                    if end == cur {
                        break; // an unmapped byte at the run's edge
                    }
                    cur = end;
                    if cur < undefined.end {
                        break; // stopped short on an unmapped hole
                    }
                }
            }
        }
        cur - addr
    }

    fn format_instruction(
        &self,
        _addr: AddressValue,
        insn: &DecodedInsn,
        overrides: &[Option<OperandOverride>],
        implicit_labels: &Labels,
        names: Option<&BTreeMap<AddressValue, String>>,
    ) -> String {
        let decoded = insn.as_string();
        let mut merged = overrides.to_vec();

        if let (Some(target), Some(idx)) = (branch_target(insn), branch_target_operand_index(insn))
        {
            while merged.len() <= idx {
                merged.push(None);
            }
            if merged[idx].is_none() {
                let label = names
                    .and_then(|m| m.get(&target))
                    .map(String::as_str)
                    .or_else(|| self.get_label(target))
                    .or_else(|| implicit_labels.get(&target).map(String::as_str));
                if let Some(label) = label {
                    merged[idx] = Some(OperandOverride::Label(label.to_string()));
                }
            }
        }

        // Does this operand have a better name?
        let decided = self.operand_type(_addr);
        for data_ref in &insn.data_refs {
            let Some(idx) = data_ref.operand.map(usize::from) else {
                continue;
            };
            if data_ref.space != self.space {
                continue;
            }
            if data_ref.certainty == crate::platform::Certainty::Inferred
                && !matches!(decided, Some(OperandType::Pointer(space)) if space == self.space)
            {
                continue;
            }
            while merged.len() <= idx {
                merged.push(None);
            }
            if merged[idx].is_some() {
                continue;
            }
            if let Some(label) = names
                .and_then(|m| m.get(&data_ref.offset))
                .map(String::as_str)
                .or_else(|| self.get_label(data_ref.offset))
                .or_else(|| implicit_labels.get(&data_ref.offset).map(String::as_str))
            {
                let text = match data_ref.kind {
                    XrefType::Pointer => format!("#{label}"),
                    _ => label.to_string(),
                };
                merged[idx] = Some(OperandOverride::Label(text));
            }
        }

        let text = if merged.iter().all(|o| o.is_none()) {
            decoded.to_string()
        } else {
            apply_operand_overrides(decoded, &merged)
        };
        sdas_indent_instruction(&text)
    }
}

impl CodeSource for Region {
    fn decode(&self, addr: AddressValue) -> Option<DecodedInsn> {
        self.decode_at(addr)
    }

    fn barrier_in(&self, addr: AddressValue, len: AddressValue) -> Option<EquivalentKind> {
        let end = addr.saturating_add(len);
        // Strong equivalents don't overlap, so scanning back from `end` until one
        // ends at/before `addr` covers every entry touching the range.
        for (_, range) in self.equivalents.range(..end).rev() {
            if range.end <= addr {
                break;
            }
            let kind = range.equivalent.kind();
            if kind != EquivalentKind::Code {
                return Some(kind);
            }
        }
        None
    }
}

fn sdas_indent_instruction(text: &str) -> String {
    if let Some((mnemonic, operands)) = text.split_once(' ') {
        format!("    {mnemonic:<8}{operands}")
    } else {
        format!("    {text}")
    }
}

fn split_instruction(decoded: &str) -> (&str, Vec<&str>) {
    let (mnemonic, rest) = decoded.split_once(' ').unwrap_or((decoded, ""));
    let operands = if rest.is_empty() {
        Vec::new()
    } else {
        rest.split(',').map(str::trim).collect()
    };
    (mnemonic, operands)
}

fn apply_operand_overrides(decoded: &str, overrides: &[Option<OperandOverride>]) -> String {
    if overrides.is_empty() {
        return decoded.to_string();
    }
    let (mnemonic, operands) = split_instruction(decoded);
    let mut out = mnemonic.to_string();
    let operand_count = operands.len().max(overrides.len());
    for idx in 0..operand_count {
        if idx > 0 {
            out.push(',');
        } else {
            out.push(' ');
        }
        match overrides.get(idx).and_then(|o| o.as_ref()) {
            Some(OperandOverride::Label(label)) => out.push_str(label),
            Some(OperandOverride::LabelOffset { label, offset }) => {
                if *offset >= 0 {
                    out.push_str(&format!("{label}+{offset}"));
                } else {
                    out.push_str(&format!("{label}{offset}"));
                }
            }
            Some(OperandOverride::Text(text)) => out.push_str(text),
            None => {
                if let Some(default) = operands.get(idx) {
                    out.push_str(default);
                }
            }
        }
    }
    out
}

/// Find the entry covering `offset` in one equivalent layer: an exact start, or
/// a preceding range that still contains it.
fn lookup_in(
    map: &BTreeMap<AddressValue, EquivalentRange>,
    offset: AddressValue,
) -> Option<(AddressValue, &EquivalentRange)> {
    if let Some(range) = map.get(&offset) {
        return Some((offset, range));
    }
    match map.range(..=offset).next_back() {
        Some((&start, range)) if offset < range.end => Some((start, range)),
        _ => None,
    }
}

/// A and B are inclusive start, exclusive end.
fn ranges_overlap(
    a_start: AddressValue,
    a_end: AddressValue,
    b_start: AddressValue,
    b_end: AddressValue,
) -> bool {
    a_start < b_end && b_start < a_end
}

/// A and B are inclusive start, inclusive end.
fn ranges_overlap_inclusive(
    a_start: AddressValue,
    a_end: AddressValue,
    b_start: AddressValue,
    b_end: AddressValue,
) -> bool {
    a_start <= b_end && b_start <= a_end
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::{DataType, Equivalent, OperandOverride, SpaceUsage};
    use crate::platform::i8051::{CODE, platform};

    #[test]
    fn overlap_names_space_kind() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x22]);
        region.set_equivalent(0, Equivalent::Code).unwrap();
        let err = region
            .disassemble_linear(0, 2)
            .expect_err("second instruction overlaps code at 0");
        assert!(matches!(
            &err.what,
            ErrorKind::Overlap { at, marked } if at == "CODE:0x0" && marked == "code"
        ));
    }

    #[test]
    fn overlapping_equivalents_are_rejected() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes(
            "test.bin",
            0,
            0,
            &[0x02, 0x00, 0x10, 0x74, 0x01, 0x00, 0x00, 0x00],
        );
        region.set_equivalent(0, Equivalent::Code).unwrap();
        assert!(matches!(
            region.set_equivalent(1, Equivalent::Code),
            Err(e) if matches!(&e.what, ErrorKind::AlreadyClassified { at, .. } if at == "CODE:0x1")
        ));
        region.set_equivalent(6, Equivalent::Code).unwrap();
        assert!(matches!(
            region.set_equivalent(4, Equivalent::Data(DataType::Byte, 3)),
            Err(e) if matches!(&e.what, ErrorKind::Overlap { at, marked } if at == "CODE:0x6" && marked == "code")
        ));
    }

    #[test]
    fn unmap_splits_straddling_range() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4, 5]);
        region.unmap_bytes(1, 2);
        assert_eq!(region.bytes_at(0, 5), vec![1, 4, 5]);
    }

    #[test]
    fn decode_without_zero_bytes() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0x100, &[0x74, 0x42]);
        let insn = region.decode_at(0x100).unwrap();
        assert_eq!(insn.len(), 2);
        assert_eq!(insn.as_string(), "MOV A,#0x42");
    }

    #[test]
    fn decode_requires_full_length() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x02, 0x00]);
        assert!(
            region.decode_at(0).is_none(),
            "Expected None, got {:?}",
            region.decode_at(0).unwrap().as_string()
        );
    }

    #[test]
    fn branch_uses_implicit_label() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x12, 0x01, 0x6D, 0x02, 0x03, 0x04]);
        region.set_equivalent(0, Equivalent::Code).unwrap();
        region.set_equivalent(3, Equivalent::Code).unwrap();

        let mut collector = LabelCollector::default();
        region.collect_refs(&mut collector);
        let implicit_labels = collector.into_implicit_labels();

        let lines = region.render(CODE, &implicit_labels);
        let insn = lines
            .iter()
            .find_map(|line| match line {
                Line::Instruction { addr: 0, text, .. } => Some(text.clone()),
                _ => None,
            })
            .unwrap();
        assert!(insn.contains("LCALL"), "{insn}");
        // A call target is named `sub_`, not `loc_`.
        assert!(insn.contains("sub_016D"), "{insn}");
        assert!(!insn.contains("#0x016D"), "{insn}");
    }

    #[test]
    fn xref_index_reflects_chop() {
        let mut region = Region::new(CODE, Some(platform()));
        // LJMP 0x0006 / NOP x4. Auto-disassembly flows through the jump.
        region.set_bytes("t.bin", 0, 0, &[0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00]);
        region.add_auto_root(0);

        let target = PhysicalAddr {
            space: CODE,
            offset: 6,
        };
        let before = region.xrefs_to(&target);
        assert_eq!(before.len(), 1);
        assert_eq!(before[0].from.offset, 0);
        assert_eq!(before[0].xref_type, XrefType::Jump);

        // A barrier over the LJMP chops the derived code, so its edge drops.
        region.set_equivalent(0, Equivalent::Unknown(3)).unwrap();
        assert!(region.xrefs_to(&target).is_empty());
    }

    #[test]
    fn blocks_split_at_targets() {
        let mut region = Region::new(CODE, Some(platform()));
        // 0: JZ 0x03 / 2: NOP / 3: RET
        region.set_bytes("t.bin", 0, 0, &[0x60, 0x01, 0x00, 0x22]);
        region.add_auto_root(0);

        let blocks = region.basic_blocks(0);
        let starts: Vec<_> = blocks.iter().map(|b| b.start).collect();
        assert_eq!(starts, vec![0, 2, 3]);
        // The JZ block falls through to 2 and branches to 3.
        assert_eq!(blocks[0].end, 2);
        assert_eq!(blocks[0].successors, vec![2, 3]);
        // The NOP block ends where the branch target (a leader) begins.
        assert_eq!(blocks[1].successors, vec![3]);
    }

    #[test]
    fn thunk_render_stays_faithful() {
        let mut region = Region::new(CODE, Some(platform()));
        // 0: LCALL 0x0003 / 3: LJMP 0x0006 (a pure thunk) / 6: RET
        region.set_bytes("t.bin", 0, 0, &[0x12, 0x00, 0x03, 0x02, 0x00, 0x06, 0x22]);
        region.add_auto_root(0);

        // Resolution follows the lone jump at 3 through to 6. 6 is not a thunk.
        assert_eq!(region.resolve_thunks(3), 6);
        assert_eq!(region.resolve_thunks(6), 6);

        // Rendering stays faithful to the bytes: the LCALL shows the stub it
        // actually targets (sub_0003), so the text reassembles to the ROM.
        let mut collector = LabelCollector::default();
        region.collect_refs(&mut collector);
        let implicit = collector.into_implicit_labels();
        let call = region
            .render(CODE, &implicit)
            .into_iter()
            .find_map(|l| match l {
                Line::Instruction { addr: 0, text, .. } => Some(text),
                _ => None,
            })
            .unwrap();
        assert!(call.contains("0003"), "{call}");
        assert!(!call.contains("0006"), "{call}");
    }

    #[test]
    fn override_preserves_operands() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0xB5, 0x20, 0x10]);
        region.set_label(0x13, "target", crate::region::LabelAttrs::default());
        region.set_equivalent(0, Equivalent::Code).unwrap();
        region.set_operand_override(0, 2, Some(OperandOverride::Label("target".into())));
        let implicit_labels = ImplicitLabels::default();
        let lines = region.render(CODE, &implicit_labels);
        let insn = lines
            .iter()
            .find_map(|line| match line {
                Line::Instruction { text, .. } => Some(text.clone()),
                _ => None,
            })
            .unwrap();
        assert!(insn.contains("0x20,target"));
    }

    #[test]
    fn adjacent_unknown_barriers_coalesce() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4, 5, 6]);
        // Undefine the range in three small adjacent chunks.
        region.set_equivalent(0, Equivalent::Unknown(2)).unwrap();
        region.set_equivalent(2, Equivalent::Unknown(2)).unwrap();
        region.set_equivalent(4, Equivalent::Unknown(2)).unwrap();
        let raws: Vec<_> = region
            .render(CODE, &ImplicitLabels::default())
            .into_iter()
            .filter_map(|line| match line {
                Line::Raw { addr, bytes } => Some((addr, bytes.len())),
                _ => None,
            })
            .collect();
        assert_eq!(raws, vec![(0, 6)], "adjacent barriers render together");
    }

    #[test]
    fn label_splits_raw_run() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4]);
        region.set_equivalent(0, Equivalent::Unknown(2)).unwrap();
        region.set_equivalent(2, Equivalent::Unknown(2)).unwrap();
        region.set_label(2, "mid", crate::region::LabelAttrs::default());
        let raws: Vec<_> = region
            .render(CODE, &ImplicitLabels::default())
            .into_iter()
            .filter_map(|line| match line {
                Line::Raw { addr, bytes } => Some((addr, bytes.len())),
                _ => None,
            })
            .collect();
        assert_eq!(raws, vec![(0, 2), (2, 2)], "label breaks the run");
    }

    #[test]
    fn render_emits_org() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[1, 2, 3]);
        region.set_bytes("test.bin", 3, 0x10, &[4, 5]);
        let implicit_labels = ImplicitLabels::default();
        let lines = region.render(CODE, &implicit_labels);
        let orgs: Vec<_> = lines
            .iter()
            .filter_map(|line| match line {
                Line::Org { addr } => Some(*addr),
                _ => None,
            })
            .collect();
        assert_eq!(orgs, vec![0, 0x10]);
    }

    #[test]
    fn usage_counts_each_kind() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes(
            "test.bin",
            0,
            0,
            &[0x02, 0x00, 0x10, 0x74, 0x01, 0xFF, 0xFF],
        );
        region.set_equivalent(0, Equivalent::Code).unwrap();
        region.set_equivalent(3, Equivalent::Code).unwrap();
        region
            .set_equivalent(5, Equivalent::Data(DataType::Word, 2))
            .unwrap();

        assert_eq!(
            region.space_usage(),
            SpaceUsage {
                code: 5,
                data: 2,
                undefined: 0,
            }
        );

        region.clear_equivalents(5, 2);
        assert_eq!(
            region.space_usage(),
            SpaceUsage {
                code: 5,
                data: 0,
                undefined: 2,
            }
        );
    }

    #[test]
    fn usage_counts_nonzero_base() {
        // A byte range based at a nonzero offset must still count in full.
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0x1000, &[0xAA, 0xBB, 0xCC, 0xDD]);

        let usage = region.space_usage();
        assert_eq!(usage.undefined, 4);
        assert_eq!(usage.code, 0);
        assert_eq!(usage.data, 0);
        // The completeness `coverage()` derives `undefined` from the spans and
        // must agree.
        assert_eq!(region.coverage().undefined, 4);
    }

    use crate::commands::{MapBytes, boxed};
    use crate::db::Db;

    struct Env(&'static [u8]);
    impl crate::commands::Environment for Env {
        fn load_file_bytes(
            &self,
            _f: &str,
            offset: usize,
            size: AddressValue,
        ) -> Result<Vec<u8>, std::io::Error> {
            Ok(self.0[offset..offset + size as usize].to_vec())
        }
    }

    fn peek(image: &'static [u8]) -> ScratchDecode {
        let env = Env(image);
        let mut db = Db::with_platform(crate::platform::i8051::platform());
        db.apply(
            boxed(MapBytes::new((CODE, 0), "img", 0usize, image.len() as u32)),
            Some(&env),
        )
        .unwrap();
        db.peek_linear(CODE, 0, image.len() as AddressValue)
    }

    /// One signature of data decoded as code: a branch landing partway through
    /// a neighbour.
    #[test]
    fn branch_into_neighbour_counted() {
        // 0: SJMP 0x03 — lands inside the instruction at 0x02.
        // 2: SJMP 0x04 — lands on a real boundary.
        // 4: NOP, 5: RET.
        let decode = peek(&[0x80, 0x01, 0x80, 0x00, 0x00, 0x22]);

        assert_eq!(decode.self_misaligned_targets, 1);
        assert!(decode.lines[0].target_self_misaligned, "0x00 -> 0x03");
        assert!(
            !decode.lines[1].target_self_misaligned,
            "0x02 -> 0x04 is aligned"
        );
    }

    /// Real code branches to boundaries.
    #[test]
    fn boundary_branches_clean() {
        // 0: SJMP 0x02, 2: NOP, 3: NOP, 4: NOP, 5: RET.
        let decode = peek(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x22]);

        assert_eq!(decode.self_misaligned_targets, 0);
        assert_eq!(decode.out_of_range_targets, 0);
        assert!(decode.lines.iter().all(|l| !l.target_self_misaligned));
    }

    /// A target beyond the image counts into `out_of_range_targets`.
    #[test]
    fn outside_target_not_misaligned() {
        // LJMP 0x4321 — far outside a six-byte image.
        let decode = peek(&[0x02, 0x43, 0x21, 0x00, 0x00, 0x22]);

        assert_eq!(decode.out_of_range_targets, 1);
        assert_eq!(decode.self_misaligned_targets, 0);
    }

    /// The linear decode covers the whole range.
    #[test]
    fn linear_ignores_return() {
        let image: &[u8] = &[0x22, 0x00, 0x00, 0x22];
        let env = Env(image);
        let mut db = Db::with_platform(crate::platform::i8051::platform());
        db.apply(
            boxed(MapBytes::new((CODE, 0), "img", 0usize, 4u32)),
            Some(&env),
        )
        .unwrap();

        assert_eq!(db.peek(CODE, 0, 16).lines.len(), 1, "flow stops at the RET");
        assert_eq!(
            db.peek_linear(CODE, 0, 4).lines.len(),
            4,
            "linear keeps going"
        );
    }

    /// The same local name in two routines must survive into valid assembly,
    /// and a global name used twice must be made unique rather than emitted.
    #[test]
    fn locals_repeat_globals_unique() {
        struct Img;
        impl crate::commands::Environment for Img {
            fn load_file_bytes(
                &self,
                _f: &str,
                offset: usize,
                size: AddressValue,
            ) -> Result<Vec<u8>, std::io::Error> {
                // main: MOV R0,#5 / DJNZ R0,-2 / RET; other: the same shape.
                const IMAGE: [u8; 10] =
                    [0x78, 0x05, 0xD8, 0xFE, 0x22, 0x78, 0x03, 0xD8, 0xFE, 0x22];
                Ok(IMAGE[offset..offset + size as usize].to_vec())
            }
        }
        use crate::commands::{AutoDisassemble, MapBytes, SetLabel};
        use crate::db::Db;

        let mut db = Db::with_platform(platform());
        db.apply(
            boxed(MapBytes::new((CODE, 0), "img", 0usize, 10u32)),
            Some(&Img),
        )
        .unwrap();
        for entry in [0u32, 5] {
            db.apply(boxed(AutoDisassemble::new((CODE, entry))), Some(&Img))
                .unwrap();
        }
        db.apply(
            boxed(SetLabel::new(
                (CODE, 0u32),
                "main".to_string(),
                false,
                false,
            )),
            None,
        )
        .unwrap();
        db.apply(
            boxed(SetLabel::new(
                (CODE, 5u32),
                "other".to_string(),
                false,
                false,
            )),
            None,
        )
        .unwrap();
        // One name, two routines — legal only because each is scoped to its own.
        for at in [2u32, 7] {
            db.apply(
                boxed(SetLabel::new((CODE, at), ".loop".to_string(), false, true)),
                None,
            )
            .unwrap();
        }

        let asm = db.to_sdas();
        assert!(
            asm.contains("1$:"),
            "locals export as ASxxxx locals:\n{asm}"
        );
        assert!(!asm.contains(".loop:"), "not a local to sdas:\n{asm}");
        // Each scope restarts numbering, so both routines get their own `1$`.
        assert_eq!(asm.matches("1$:").count(), 2, "one local per scope:\n{asm}");
        // References must follow the definitions, or the output assembles wrong.
        assert_eq!(asm.matches("DJNZ").count(), 2, "{asm}");
        assert!(
            !asm.contains("DJNZ    R0,.loop"),
            "reference not rewritten:\n{asm}"
        );
    }

    /// A global name reused at two addresses is disambiguated, since emitting
    /// it twice would be a duplicate symbol.
    #[test]
    fn repeated_global_made_unique() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x00, 0x22]);
        region.set_label(0, "handler", LabelAttrs::default());
        region.set_label(2, "handler", LabelAttrs::default());

        let names = region.export_names(&Labels::default());
        assert_eq!(names.get(&0).map(String::as_str), Some("handler"));
        assert_eq!(names.get(&2).map(String::as_str), Some("handler_1"));
    }

    #[test]
    fn cross_scope_local_named() {
        struct Img;
        impl crate::commands::Environment for Img {
            fn load_file_bytes(
                &self,
                _f: &str,
                offset: usize,
                size: AddressValue,
            ) -> Result<Vec<u8>, std::io::Error> {
                // main: MOV R0,#5 / NOP / RET; other: MOV R0,#3 / SJMP 0x2 / RET.
                // The SJMP reaches back into main's body, across `other`'s label.
                const IMAGE: [u8; 9] = [0x78, 0x05, 0x00, 0x22, 0x78, 0x03, 0x80, 0xFA, 0x22];
                Ok(IMAGE[offset..offset + size as usize].to_vec())
            }
        }
        use crate::commands::{AutoDisassemble, MapBytes, SetLabel};
        use crate::db::Db;

        let mut db = Db::with_platform(platform());
        db.apply(
            boxed(MapBytes::new((CODE, 0), "img", 0usize, 9u32)),
            Some(&Img),
        )
        .unwrap();
        for entry in [0u32, 4] {
            db.apply(boxed(AutoDisassemble::new((CODE, entry))), Some(&Img))
                .unwrap();
        }
        db.apply(
            boxed(SetLabel::new(
                (CODE, 0u32),
                "main".to_string(),
                false,
                false,
            )),
            None,
        )
        .unwrap();
        db.apply(
            boxed(SetLabel::new(
                (CODE, 4u32),
                "other".to_string(),
                false,
                false,
            )),
            None,
        )
        .unwrap();
        db.apply(
            boxed(SetLabel::new(
                (CODE, 2u32),
                "inner".to_string(),
                false,
                true,
            )),
            None,
        )
        .unwrap();

        let region = db.region(CODE).unwrap();
        assert!(region.is_local_label(2));
        assert_eq!(region.scope_of(2), Some(0), "its routine is `main`");

        let asm = db.to_sdas();
        assert!(
            asm.contains("inner:"),
            "the local falls back to its name:\n{asm}"
        );
        assert!(!asm.contains("1$:"), "it cannot be an ASxxxx local:\n{asm}");
        assert!(
            asm.contains("SJMP    inner"),
            "the reference matches:\n{asm}"
        );
    }

    /// A swallowed label undefines every reference to it.
    #[test]
    fn data_run_stops_early() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x11, 0x22, 0x33, 0x44]);
        region
            .set_equivalent(0, Equivalent::Data(DataType::Byte, 4))
            .unwrap();
        region.set_label(2, "table_hi", LabelAttrs::default());

        let lines = region.render(CODE, &ImplicitLabels::default());
        let labelled: Vec<AddressValue> = lines
            .iter()
            .filter_map(|l| match l {
                Line::Label { addr, .. } => Some(*addr),
                _ => None,
            })
            .collect();
        assert_eq!(
            labelled,
            vec![2],
            "the label must survive the run: {lines:#?}"
        );

        // The run splits rather than losing bytes.
        let data: Vec<(AddressValue, usize)> = lines
            .iter()
            .filter_map(|l| match l {
                Line::Data { addr, bytes, .. } => Some((*addr, bytes.len())),
                _ => None,
            })
            .collect();
        assert_eq!(data, vec![(0, 2), (2, 2)], "{lines:#?}");
    }

    #[test]
    fn clearing_label_clears_attributes() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x00, 0x22]);

        region.set_label(
            0,
            "guess",
            LabelAttrs {
                provisional: true,
                local: true,
            },
        );
        assert!(region.is_draft_label(0) && region.is_local_label(0));

        region.clear_label(0);
        assert!(!region.is_draft_label(0), "draft flag outlived the label");
        assert!(!region.is_local_label(0), "local flag outlived the label");

        // A plain name set afterwards must be plain.
        region.set_label(0, "settled", LabelAttrs::default());
        assert!(!region.is_draft_label(0) && !region.is_local_label(0));

        // The range form has to do the same.
        region.set_label(
            2,
            "spot",
            LabelAttrs {
                provisional: true,
                local: true,
            },
        );
        region.clear_labels_in(2..3);
        assert!(!region.is_draft_label(2) && !region.is_local_label(2));
    }

    #[test]
    fn peek_reports_self_misaligned() {
        struct Img;
        impl crate::commands::Environment for Img {
            fn load_file_bytes(
                &self,
                _f: &str,
                offset: usize,
                size: AddressValue,
            ) -> Result<Vec<u8>, std::io::Error> {
                // JNZ 0x3 falls through to the MOV at 0x2, and its target
                // lands inside that instruction.
                const BYTES: [u8; 5] = [0x70, 0x01, 0x74, 0x00, 0x22];
                Ok(BYTES[offset..offset + size as usize].to_vec())
            }
        }
        use crate::commands::MapBytes;
        use crate::db::Db;

        let mut db = Db::with_platform(platform());
        db.apply(
            boxed(MapBytes::new((CODE, 0), "img", 0usize, 5u32)),
            Some(&Img),
        )
        .unwrap();

        assert_eq!(db.peek(CODE, 0, 16).self_misaligned_targets, 1);
    }

    #[test]
    fn retyping_says_clearing_cost() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x00; 0x40]);
        region
            .set_equivalent(0, Equivalent::Data(DataType::Byte, 0x40))
            .unwrap();

        let err = region
            .set_equivalent(0x10, Equivalent::Data(DataType::Byte, 4))
            .expect_err("those bytes already carry a classification");
        assert!(matches!(
            &err.what,
            ErrorKind::AlreadyClassified { marked, cleared: 0x40, asked: 0x4, .. }
                if marked == "data"
        ));
        // The clear, and how to put back what was not being retyped.
        let text = err.to_string();
        assert!(text.contains("clear_equivalents"), "{text}");
        assert!(
            text.contains("mark_data(range=CODE:0x0..0x10"),
            "restore before: {text}"
        );
        assert!(
            text.contains("mark_data(range=CODE:0x14..0x40"),
            "restore after: {text}"
        );
    }

    #[test]
    fn unmapped_address_names_space() {
        let mut region = Region::new(CODE, Some(platform()));
        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00]);

        let err = region
            .set_equivalent(0, Equivalent::Data(DataType::Byte, 8))
            .expect_err("the run runs past the mapped bytes");
        assert!(matches!(
            &err.what,
            ErrorKind::NothingMapped { at } if at == "CODE:0x2"
        ));
    }
}