rigless 0.2.2

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The static description of a system on chip, and the [`Bus`] that gives its addresses meaning.
//!
//! The description is what `rigless svd generate` emits from the vendor's SVD: a [`Cpu`], every
//! [`Peripheral`] instance at its address, and one [`RegisterSpec`] table per layout, with a
//! [`Layout`] enum naming each table's registers. A hand-written memory map of [`Region`]s
//! completes it. [`Bus::builder`] assembles all of that with the SoC's corrections, reset values,
//! write rules and field shapes, and the fields a model declares, checks it once, and produces a
//! [`Bus`].
//!
//! **A bus owns no models.** It decodes an address to a slot, holds each slot's [`RegisterFile`],
//! and carries the event queue and the interrupt changes. The models are fields of the MCU that
//! has them, and [`crate::mcu::Mcu`] is what joins the two: it hands the bus and the model in one
//! slot to the runtime, borrowed apart, so a model is reached by a field and never by a name.
//!
//! Nothing here knows which processor family the SoC belongs to: addresses and values are
//! 64-bit, and a [`Cpu`] is a name, an FPU flag, and an interrupt count.
//!
//! A model raises its interrupt by position in its instance's table, `context.raise(UPDATE)` with
//! `const UPDATE: usize = 0`, because a layout is shared by every instance built on it and only the
//! instance knows its number. The bus resolves the position and reports the change as the
//! instance's name, the number, and the level. A position the table doesn't list is a bug in the
//! model and panics with the instance's name.
//!
//! # Joining one instance to another
//!
//! A model may not reach another model. It would be a second borrow of the bus inside a call, and
//! the order of the effects would stop being the description's. Five mechanisms join them instead,
//! and a part that needs none of them declares none.
//!
//! **A gate** is a bit of one instance that another answers behind. Where the vendor says a
//! peripheral whose clock is off doesn't answer its registers, that's one line of the part's
//! description:
//!
//! ```
//! # use rigless::soc::{Access, Bus, Clock, Cpu, Endian, FieldSpec, Gate, Peripheral, ReadAction, Region, RegisterSpec, Width, WriteModify};
//! # const fn flag(name: &'static str, bit: u8) -> FieldSpec {
//! #     FieldSpec { name, bit, width: 1, access: Access::ReadWrite, read: ReadAction::None, write: WriteModify::None }
//! # }
//! # static ENABLES: [RegisterSpec; 1] = [RegisterSpec { name: "ENR", offset: 0, width: Width::W32,
//! #     reset: 0, access: Access::ReadWrite, read: ReadAction::None, write: WriteModify::None,
//! #     fields: &[flag("SERIALEN", 0)] }];
//! # static DATA: [RegisterSpec; 1] = [RegisterSpec { name: "DR", offset: 0, width: Width::W32, reset: 0,
//! #     access: Access::ReadWrite, read: ReadAction::None, write: WriteModify::None, fields: &[] }];
//! # static DMAEN: FieldSpec = flag("DMAEN", 1);
//! # static CPU: Cpu = Cpu::new("a-core", true, 8, Endian::Little);
//! # static MEMORY: [Region; 1] = [Region::ram("sram", 0x2000_0000, 1 << 16)];
//! # fn instances() -> [Peripheral; 3] { [
//! #     Peripheral { name: "CLOCKS", base: 0x4000_0000, size: 0x400, interrupts: &[], registers: &ENABLES },
//! #     Peripheral { name: "SERIAL", base: 0x4000_0400, size: 0x400, interrupts: &[1], registers: &DATA },
//! #     Peripheral { name: "DMA", base: 0x4000_0800, size: 0x400, interrupts: &[2], registers: &DATA },
//! # ] }
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let bus = Bus::builder(CPU, &MEMORY, instances())
//!     // Every access to SERIAL is refused while CLOCKS.ENR.SERIALEN is clear.
//!     .gate("SERIAL", Gate::by("CLOCKS", "ENR", "SERIALEN"))
//!     // The same over named registers and in one direction: reads still answer.
//!     .gate_writes("SERIAL", &["DR"], Gate::by("CLOCKS", "ENR", "SERIALEN"))
//!     // A field the vendor's file omits, which a model declares and a gate may then name.
//!     .declare("CLOCKS", "ENR", &DMAEN)
//!     // DMA reads every request any instance drives.
//!     .reads_requests("DMA")
//!     // SERIAL runs on the first clock output of CLOCKS.
//!     .clocked_by("SERIAL", Clock::output("CLOCKS", 0))
//!     // DMA hears every interrupt and drives the core's lines, as an interrupt matrix would.
//!     .routes_interrupts("DMA")
//!     .build()?;
//! # let _ = bus;
//! # Ok(())
//! # }
//! ```
//!
//! The bit is named rather than numbered, so its position comes from the generated table. A gate is
//! read where its bit lies and never through a second gate, so gates can't cycle. An access a gate
//! refuses is [`Fault::Gated`] from [`crate::mcu::Operate::read`] and [`crate::mcu::Operate::write`]. A
//! [`crate::session::Session`] turns that into the zero the firmware sees, and lists the address in
//! [`crate::session::Session::refused`].
//!
//! **A reset line** is a bit of one instance that holds another in reset while it stands, as a part's
//! clock controller has one for each peripheral, declared with [`Builder::reset_by`]. Each write that
//! leaves the bit set puts the instance back as a system reset of it alone would: its registers at
//! their reset values, its model's [`crate::device::Device::reset`], its events dropped and its
//! interrupts lowered.
//!
//! **A request line** is a level one instance drives and another reads, the same shape as an
//! interrupt on another wire. `context.request(n, level)` drives the instance's `n`th output in its
//! own numbering, the way [`crate::device::DeviceContext::interrupt`] takes a position. Every
//! instance `reads_requests` named sees it as a [`crate::device::RequestChange`] carrying the
//! driver's name and that number. **A request no reader was named for is dropped and nothing
//! reports it**, so a part whose controller isn't a reader sees none of them.
//!
//! The runtime carries no wiring table of its own, on purpose: what a driver's number means is the
//! reader's to decide. So wiring one instance to another is three things the models own rather than
//! one the crate provides. The driver publishes a constant per output,
//! `pub const RECEIVE_REQUEST: usize = 0` beside its `const GLOBAL: usize = 0`. The reader declares
//! whatever shape its own wiring wants and is handed one at construction. The part writes the table
//! out and names the reader with `reads_requests`. A DMA controller's table of which request lands
//! on which of its channels is one such shape.
//!
//! **A clock** is a rate one instance drives and another runs on: what a clock tree feeds a
//! peripheral that counts. `context.clock(n, hz)` drives the instance's `n`th clock output in its
//! own numbering. `clocked_by(instance, Clock::output(source, n))` says which one an instance runs
//! on, so that instance alone is told at [`crate::device::Device::on_clock`], and only of that
//! output. A rate isn't a level. The reader keeps time against it, so it re-bases at the instant of
//! the change rather than reinterpreting what it had already counted, and an event it placed at the
//! old rate is placed again. A model built with a rate and never wired to a clock keeps the rate it
//! was built with. That's what a test putting one model on a bus of its own gets.
//!
//! **A requested access** is a model asking the runtime to make a bus or memory access on its
//! behalf. `context.read_from(address, width, token)` and
//! `context.write_to(address, width, value, token)` take effect after the call returns, through the
//! same path a firmware's access takes. The answer comes back to
//! [`crate::device::Device::on_access`] carrying the model's own `token`, or to
//! [`crate::device::Device::on_refused`] where the bus wouldn't make it. An access that lies wholly
//! inside one of the part's [`Region`]s reaches the emulator's memory. One that runs past a region's
//! end goes to the bus.
//!
//! **A programmed region** is memory the firmware can't write directly, like flash, that a model of
//! the part programs: its flash interface. [`Region::programmed_by`] names the instance, and the bus
//! refuses a name the part doesn't have, or RAM with one. A store the firmware makes into the region
//! at its own address reaches that model at [`crate::device::Device::write_region`], which says
//! whether it takes it. One it doesn't take is refused, as a store where nothing answers is. The model changes the region only by asking,
//! with `context.program(address, width, value, token)`, which lands whatever the firmware may write
//! there and is answered as a requested access is. A snapshot keeps the region as it keeps RAM.
//!
//! **An interrupt controller on the part's side** is an instance that hears every interrupt the
//! others raise, in place of the core, and drives the core's lines itself: an interrupt matrix the
//! firmware programs, or a distributor the part places in front of the core.
//! `routes_interrupts(instance)` names it, which a part does once. Its model hears each change at
//! [`crate::device::Device::on_interrupt`] and drives a line with
//! [`crate::device::DeviceContext::drive_line`]. A part that names none has the direct line: an
//! interrupt drives the core's line of its own number, and one past the core's lines is reported
//! as unrouted.
//!
//! **Call [`crate::mcu::Operate::settle`] after every access and every event.**
//! [`crate::mcu::Operate::read`], [`crate::mcu::Operate::write`] and [`crate::mcu::Operate::advance_to`] only
//! queue what the models asked for. Settling is what carries it out, and a harness that forgets it
//! drives a controller that never moves a byte and says nothing. [`crate::session::Session`] does
//! it for a run, so only a test driving an [`crate::mcu::Mcu`] itself has to.
//!
//! A settle serves clock changes first, then request changes, then interrupt changes to a
//! controller, then answers, then the accesses themselves, each at the instant of the access or
//! event that set it off. A DMA controller is the
//! worked example of three of the four mechanisms at once: it reads requests, is gated by a clock
//! enable, and asks for every access it makes.

#[cfg(feature = "stm32f427")]
pub mod stm32f427;
#[cfg(feature = "stm32h743")]
pub mod stm32h743;

use std::fmt;
use std::num::{NonZeroU32, NonZeroU64};

use crate::device::{
    Answer, ClockChange, DeviceContext, Effects, InterruptChange, LineChange, PendingAccess,
    RegisterFile, RequestChange, ResetCause, Told,
};
use crate::emulator::AccessKind;
use crate::snapshot::store;
use crate::time::{EventId, VirtualNanos};

/// The processor core as the SVD describes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cpu {
    /// The core name as the vendor spells it.
    pub name: &'static str,
    /// Whether the core has a floating-point unit.
    pub fpu: bool,
    /// Number of external interrupt lines the interrupt controller has.
    pub interrupt_lines: u16,
    /// The order the core keeps a value's bytes in memory.
    pub endian: Endian,
}

impl Cpu {
    /// The core the vendor calls `name`, with a floating-point unit when `fpu`, an interrupt
    /// controller of `interrupt_lines` lines, and its data kept `endian`.
    #[must_use]
    pub const fn new(name: &'static str, fpu: bool, interrupt_lines: u16, endian: Endian) -> Self {
        Self {
            name,
            fpu,
            interrupt_lines,
            endian,
        }
    }
}

/// The order of a value's bytes in memory.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Endian {
    /// The least significant byte at the lowest address.
    #[default]
    Little,
    /// The most significant byte at the lowest address.
    Big,
}

/// One peripheral instance at its address.
///
/// Instances the SVD derives from a sibling share that sibling's table, so every instance of one
/// kind points at one generated `REGISTERS`. An SoC module corrects an instance the vendor's file
/// got wrong with struct update syntax: `Peripheral { interrupts: &[87], ..generated::AN_INSTANCE }`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Peripheral {
    /// The instance name as the vendor spells it, such as `SERIAL`.
    pub name: &'static str,
    /// Absolute address of the first register.
    pub base: u64,
    /// Bytes the instance occupies on the bus.
    pub size: u64,
    /// Interrupt lines the instance raises, ascending.
    pub interrupts: &'static [u16],
    /// The register table, each row where its layout's index names it. The bus finds a row by
    /// offset whatever order the rows are in.
    pub registers: &'static [RegisterSpec],
}

impl Peripheral {
    /// Whether the address falls inside the instance.
    pub const fn contains(&self, address: u64) -> bool {
        address >= self.base && address < self.base + self.size
    }
}

/// One register of a table: where it is, what it holds after reset, and how the bus may treat it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegisterSpec {
    /// The register name as the vendor spells it.
    pub name: &'static str,
    /// Offset from the instance base.
    pub offset: u32,
    /// Width on the bus.
    pub width: Width,
    /// Value after reset.
    pub reset: u64,
    /// Which directions the bus allows.
    pub access: Access,
    /// What a read does to the register.
    pub read: ReadAction,
    /// What arithmetic a write performs before the value lands.
    pub write: WriteModify,
    /// The bit fields, ordered by position.
    pub fields: &'static [FieldSpec],
}

impl RegisterSpec {
    /// One past the last byte of the register, as an offset from the instance base.
    pub const fn end(&self) -> u32 {
        self.offset + self.width.bytes()
    }
}

/// One bit field of a register.
///
/// The generator emits one constant per field, so a model reads a bit by name:
/// `ctrl::EN.is_set(value)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldSpec {
    /// The field name as the vendor spells it.
    pub name: &'static str,
    /// Position of the least significant bit.
    pub bit: u8,
    /// Width in bits.
    pub width: u8,
    /// Which directions the bus allows, taken from the register unless the SVD says otherwise.
    pub access: Access,
    /// What a read does to the field, taken from the register unless the SVD says otherwise.
    pub read: ReadAction,
    /// What arithmetic a write performs, taken from the register unless the SVD says otherwise.
    pub write: WriteModify,
}

impl FieldSpec {
    /// The bits the field occupies within the register.
    pub const fn mask(&self) -> u64 {
        if self.width >= Width::W64.bits() {
            u64::MAX
        } else {
            ((1u64 << self.width) - 1) << self.bit
        }
    }

    /// The field's value within a register value.
    pub const fn get(&self, register_value: u64) -> u64 {
        (register_value & self.mask()) >> self.bit
    }

    /// The register value with this field replaced.
    pub const fn set(&self, register_value: u64, field_value: u64) -> u64 {
        (register_value & !self.mask()) | ((field_value << self.bit) & self.mask())
    }

    /// Whether any bit of the field is set in the register value.
    pub const fn is_set(&self, register_value: u64) -> bool {
        register_value & self.mask() != 0
    }
}

/// Width of a register, or of a bus access, in bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Width {
    /// Eight bits.
    W8,
    /// Sixteen bits.
    W16,
    /// Thirty-two bits.
    W32,
    /// Sixty-four bits.
    W64,
}

impl Width {
    /// The width in bits.
    pub const fn bits(self) -> u8 {
        match self {
            Self::W8 => 8,
            Self::W16 => 16,
            Self::W32 => 32,
            Self::W64 => 64,
        }
    }

    /// The width in bytes.
    pub const fn bytes(self) -> u32 {
        self.bits() as u32 / 8
    }

    /// A mask of the bits a value of this width holds.
    pub const fn mask(self) -> u64 {
        match self {
            Self::W64 => u64::MAX,
            narrower => (1u64 << narrower.bits()) - 1,
        }
    }
}

/// Which directions the bus allows, as the CMSIS-SVD `access` element names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Access {
    /// Reads return the value and writes are ignored.
    ReadOnly,
    /// Writes land and reads return zero.
    WriteOnly,
    /// Both directions.
    ReadWrite,
    /// Only the first write after reset lands, and reads return zero.
    WriteOnce,
    /// Only the first write after reset lands, and reads return the value.
    ReadWriteOnce,
}

impl Access {
    /// Whether the bus may read the value.
    pub const fn is_readable(self) -> bool {
        !matches!(self, Self::WriteOnly | Self::WriteOnce)
    }

    /// Whether the bus may write the value, at least once.
    pub const fn is_writable(self) -> bool {
        !matches!(self, Self::ReadOnly)
    }

    /// Whether only the first write after reset lands.
    pub const fn is_write_once(self) -> bool {
        matches!(self, Self::WriteOnce | Self::ReadWriteOnce)
    }
}

/// What a read does to a register, as the CMSIS-SVD `readAction` element names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadAction {
    /// Nothing.
    None,
    /// The register clears.
    Clear,
    /// The register sets.
    Set,
    /// The register changes in a way only the model knows.
    Modify,
    /// Another register changes.
    ModifyExternal,
}

impl ReadAction {
    /// The value the register holds after a read of `value`, within `mask`.
    pub const fn apply(self, value: u64, mask: u64) -> u64 {
        match self {
            Self::Clear => value & !mask,
            Self::Set => value | mask,
            Self::None | Self::Modify | Self::ModifyExternal => value,
        }
    }
}

/// What arithmetic a write performs before the value lands, as the CMSIS-SVD `modifiedWriteValues` element names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteModify {
    /// The written value lands.
    None,
    /// Written ones clear their bits.
    OneToClear,
    /// Written ones set their bits.
    OneToSet,
    /// Written ones toggle their bits.
    OneToToggle,
    /// Written zeros clear their bits.
    ZeroToClear,
    /// Written zeros set their bits.
    ZeroToSet,
    /// Written zeros toggle their bits.
    ZeroToToggle,
    /// Any write clears the register.
    Clear,
    /// Any write sets the register.
    Set,
    /// Any write changes the register in a way only the model knows.
    Modify,
}

impl WriteModify {
    /// The value that lands when `written` arrives over `old`.
    pub const fn apply(self, old: u64, written: u64) -> u64 {
        match self {
            Self::None => written,
            Self::OneToClear => old & !written,
            Self::OneToSet => old | written,
            Self::OneToToggle => old ^ written,
            Self::ZeroToClear => old & written,
            Self::ZeroToSet => old | !written,
            Self::ZeroToToggle => old ^ !written,
            Self::Clear => 0,
            Self::Set => u64::MAX,
            Self::Modify => old,
        }
    }

    /// The written value that leaves `old` unchanged, for the lanes a narrow access doesn't touch.
    pub const fn neutral(self, old: u64) -> u64 {
        match self {
            Self::OneToClear | Self::OneToSet | Self::OneToToggle => 0,
            Self::ZeroToClear | Self::ZeroToSet | Self::ZeroToToggle => u64::MAX,
            Self::None | Self::Clear | Self::Set | Self::Modify => old,
        }
    }
}

/// A register table's names as a type, so a model matches on registers instead of strings.
///
/// The generator emits one enum implementing this per table. A variant's index is its row in
/// [`Layout::REGISTERS`].
pub trait Layout: Copy + fmt::Debug {
    /// The table this layout names.
    const REGISTERS: &'static [RegisterSpec];

    /// The register at this row of the table.
    fn from_index(index: usize) -> Option<Self>;

    /// This register's row in the table.
    fn index(self) -> usize;

    /// This register's row of the table.
    fn spec(self) -> &'static RegisterSpec {
        &Self::REGISTERS[self.index()]
    }

    /// The field of this register whose least significant bit is `bit`, if it has one.
    fn field_at(self, bit: u32) -> Option<&'static FieldSpec> {
        self.spec()
            .fields
            .iter()
            .find(|field| u32::from(field.bit) == bit)
    }
}

/// What a memory region holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegionKind {
    /// Code and constant data, loaded from the firmware image.
    Flash,
    /// Read-write memory.
    Ram,
    /// Vendor read-only data such as the unique device ID.
    System,
}

impl RegionKind {
    /// Whether the firmware can write the region. The emulator maps every other kind read-only, and
    /// a snapshot saves only these, since what the image put in the rest never changes.
    #[must_use]
    pub const fn is_writable(self) -> bool {
        matches!(self, Self::Ram)
    }
}

/// One memory region of the SoC.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Region {
    /// The region name, such as `sram`.
    pub name: &'static str,
    /// Absolute address of the first byte.
    pub base: u64,
    /// Size in bytes.
    pub size: u64,
    /// What the region holds.
    pub kind: RegionKind,
    /// The blocks the region erases in, in the order they sit in it from its base, or none for one
    /// block the size of the region. A debugger loading flash erases whole blocks.
    pub blocks: &'static [EraseBlocks],
    /// What every byte of the region reads once it's erased, and so wherever no image fills it.
    pub erased: u8,
    /// The instance whose model programs the region, a flash region's flash interface, or none. A
    /// store the firmware makes into the region reaches that model, and a snapshot keeps the region
    /// as it keeps one the firmware writes. RAM has none.
    pub programmer: Option<&'static str>,
}

/// A run of erase blocks of one size, in the order they sit in a flash region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EraseBlocks {
    /// The bytes of each block.
    pub size: NonZeroU64,
    /// How many blocks of that size there are in a row.
    pub count: NonZeroU32,
}

impl Region {
    /// A flash region.
    pub const fn flash(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::Flash,
            blocks: &[],
            erased: 0,
            programmer: None,
        }
    }

    /// A RAM region.
    pub const fn ram(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::Ram,
            blocks: &[],
            erased: 0,
            programmer: None,
        }
    }

    /// This region, erased in `blocks`, which add up to its size.
    #[must_use]
    pub const fn erased_in(self, blocks: &'static [EraseBlocks]) -> Self {
        Self { blocks, ..self }
    }

    /// This region, reading `value` in every byte once it's erased, where it would read 0.
    #[must_use]
    pub const fn erased_to(self, value: u8) -> Self {
        Self {
            erased: value,
            ..self
        }
    }

    /// This region, programmed by the model of `instance`. See [`Region::programmer`].
    #[must_use]
    pub const fn programmed_by(self, instance: &'static str) -> Self {
        Self {
            programmer: Some(instance),
            ..self
        }
    }

    /// Whether this region holds `address`.
    #[must_use]
    pub const fn contains(&self, address: u64) -> bool {
        address >= self.base && address - self.base < self.size
    }

    /// A system memory region.
    pub const fn system(name: &'static str, base: u64, size: u64) -> Self {
        Self {
            name,
            base,
            size,
            kind: RegionKind::System,
            blocks: &[],
            erased: 0,
            programmer: None,
        }
    }
}

/// A range of addresses outside the part's register tables where a board puts a chip, such as a
/// display on a bank of an external memory interface.
///
/// The part's module defines where its windows are, and when each one answers as a [`Gate`] on one
/// of the part's enable bits. [`Bus::add_window`] adds one to a built bus. Accesses reach the chip
/// through [`crate::mcu::Mcu::split`] like any model, with an offset into the window instead of a
/// register.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Window {
    /// What the window is called, such as the chip select that picks it.
    pub name: &'static str,
    /// Absolute address of its first byte.
    pub base: u64,
    /// Bytes it spans.
    pub size: NonZeroU64,
    /// Interrupt lines a chip in it raises, ascending.
    pub interrupts: &'static [u16],
    /// The bit that has to be set for the window to answer, if one does.
    pub gate: Option<Gate>,
}

impl Window {
    /// The `size` bytes from `base`, answering always and raising nothing.
    #[must_use]
    pub const fn new(name: &'static str, base: u64, size: NonZeroU64) -> Self {
        Self {
            name,
            base,
            size,
            interrupts: &[],
            gate: None,
        }
    }

    /// This window, answering only while `gate`'s bit is set. While the bit is clear, accesses are
    /// refused the same way a gated instance refuses them.
    #[must_use]
    pub const fn gated(self, gate: Gate) -> Self {
        Self {
            gate: Some(gate),
            ..self
        }
    }

    /// This window, with a chip in it raising `interrupts`.
    #[must_use]
    pub const fn raising(self, interrupts: &'static [u16]) -> Self {
        Self { interrupts, ..self }
    }
}

/// The register table of a window, which is empty. A chip in a window decodes the offset itself.
pub(crate) static NO_REGISTERS: [RegisterSpec; 0] = [];

/// What a refusal names as the register of a window.
const WINDOW: &str = "window";

/// Why an SoC description doesn't hold together.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Two memory regions share addresses.
    #[error("memory regions {lower} and {upper} overlap")]
    OverlappingRegions {
        /// The region with the lower base.
        lower: &'static str,
        /// The region that starts inside it.
        upper: &'static str,
    },
    /// A region names a programmer the part doesn't have.
    #[error("memory region {region} is programmed by {instance}, which the part doesn't have")]
    NoProgrammer {
        /// The region.
        region: &'static str,
        /// The instance it names.
        instance: &'static str,
    },
    /// A RAM region names a programmer. The firmware writes RAM itself, so nothing programs it.
    #[error(
        "memory region {region} is RAM, which the firmware writes itself, so nothing programs it"
    )]
    ProgrammedRam {
        /// The region.
        region: &'static str,
    },
    /// A region's erase blocks don't add up to its size.
    #[error("the erase blocks of memory region {region} don't add up to its size")]
    EraseBlocksMismatch {
        /// The region.
        region: &'static str,
    },
    /// Two peripheral instances share addresses.
    #[error("peripheral instances {lower} and {upper} overlap")]
    OverlappingInstances {
        /// The instance with the lower base.
        lower: &'static str,
        /// The instance that starts inside it.
        upper: &'static str,
    },
    /// An instance raises an interrupt line the CPU doesn't have.
    #[error("{instance} raises interrupt {line} but the CPU has {lines} lines")]
    InterruptOutOfRange {
        /// The instance.
        instance: &'static str,
        /// The interrupt line.
        line: u16,
        /// Lines the CPU has.
        lines: u16,
    },
    /// A binding or correction names an instance the SoC doesn't have.
    #[error("{instance} is not an instance of this SoC")]
    UnknownInstance {
        /// The name given.
        instance: &'static str,
    },
    /// A block correction that would make an instance's block smaller than the description's.
    #[error(
        "{instance}'s block can only grow, and {size:#x} bytes is smaller than the description's"
    )]
    ShrunkBlock {
        /// The instance.
        instance: &'static str,
        /// The size asked for.
        size: u64,
    },
    /// The description names two instances that route interrupts, and a part has one.
    #[error("{first} and {second} both route interrupts, and a part has one controller that does")]
    RoutedTwice {
        /// The first instance named.
        first: &'static str,
        /// The second.
        second: &'static str,
    },
    /// The description names an instance to route interrupts that the MCU has no model for, so
    /// nothing would hear them.
    #[error("{instance} routes interrupts, and the part has no model for it to hear them")]
    UnheardRouter {
        /// The instance.
        instance: &'static str,
    },
    /// A region names a programmer that the MCU has no model for, so nothing would hear the
    /// firmware's stores to it.
    #[error("{instance} programs memory, and the part has no model for it to hear the stores")]
    UnheardProgrammer {
        /// The instance.
        instance: &'static str,
    },
    /// The description runs one instance on two clocks, and an instance runs on one.
    #[error("{instance} is clocked twice, and an instance runs on one clock")]
    ClockedTwice {
        /// The instance named twice.
        instance: &'static str,
    },
    /// A correction, a declaration or a gate names a register the instance doesn't have.
    #[error("{instance} has no register {register}")]
    UnknownRegister {
        /// The instance.
        instance: &'static str,
        /// The name given.
        register: &'static str,
    },
    /// A gate names a field the register doesn't declare, in the tables or by a model, or a
    /// correction names one the tables don't carry.
    #[error("{instance}.{register} has no field {field}")]
    UnknownField {
        /// The instance.
        instance: &'static str,
        /// The register.
        register: &'static str,
        /// The name given.
        field: &'static str,
    },
    /// A corrected or declared field runs past its register.
    #[error("{instance}.{register}.{field} does not fit its register")]
    FieldOutOfRange {
        /// The instance.
        instance: &'static str,
        /// The register.
        register: &'static str,
        /// The field corrected.
        field: &'static str,
    },
    /// A corrected reset value has bits beyond the register's width.
    #[error("reset value {value:#x} does not fit {instance}.{register}")]
    ResetTooWide {
        /// The instance.
        instance: &'static str,
        /// The register.
        register: &'static str,
        /// The value given.
        value: u64,
    },
    /// A device written for one register layout was bound to an instance of another.
    #[error("{instance} does not have the register layout the device was written for")]
    LayoutMismatch {
        /// The instance.
        instance: &'static str,
    },
    /// Two devices were bound to one instance.
    #[error("{instance} is bound twice")]
    BoundTwice {
        /// The instance.
        instance: &'static str,
    },
    /// A region or a window added to a built bus shares addresses with a region, an instance or a
    /// window already there.
    #[error("{added} overlaps {by}")]
    Overlapping {
        /// What was added.
        added: &'static str,
        /// What was there first.
        by: &'static str,
    },
    /// A region or a window added to a built bus has the name of one already there.
    #[error("{added} is already the name of a region, an instance or a window")]
    NamedTwice {
        /// What was added.
        added: &'static str,
    },
    /// A bus asked to keep what a board added to another isn't fresh from the same description.
    #[error(
        "a bus keeps what a board added to another only when it's fresh from the same description"
    )]
    OtherDescription,
    /// A region or a window added to a built bus runs past the last address.
    #[error("{added} runs past the last address")]
    PastTheEnd {
        /// What was added.
        added: &'static str,
    },
}

/// Why a bus access couldn't complete.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum Fault {
    /// No register covers the address.
    #[error("no register at {address:#x}")]
    Unmapped {
        /// The address accessed.
        address: u64,
    },
    /// A gate the part declares is shut, so the instance doesn't answer.
    #[error("{instance}.{register} is gated by {}.{}.{}", by.instance, by.register, by.field)]
    Gated {
        /// The instance that didn't answer.
        instance: &'static str,
        /// The register reached.
        register: &'static str,
        /// The bit that would have opened it.
        by: Gate,
    },
    /// The access runs past the end of the register that covers the address.
    #[error("a {}-bit access at {address:#x} runs past its register", width.bits())]
    Misaligned {
        /// The address accessed.
        address: u64,
        /// The width of the access.
        width: Width,
    },
}

impl Fault {
    /// Whether this is the part saying no, a gate it declares being shut, which is the model answering
    /// as the silicon does rather than a gap in the models.
    #[must_use]
    pub fn is_shut_gate(&self) -> bool {
        matches!(self, Self::Gated { .. })
    }
}

/// A field of a register the vendor's file leaves out, which the part declares so the bus can find it.
struct Declaration {
    instance: &'static str,
    register: &'static str,
    field: &'static FieldSpec,
}

/// Adds `declaration`'s field to its register in the [`RegisterFile`], failing on a field that runs past
/// the register's width.
fn declare_field(slots: &mut [Slot], declaration: &Declaration) -> Result<(), Error> {
    let slot = slot_named_mut(slots, declaration.instance)?;
    let row = row_named(
        slot.peripheral.registers,
        declaration.instance,
        declaration.register,
    )?;
    let past = u32::from(declaration.field.bit) + u32::from(declaration.field.width);
    if past > u32::from(slot.peripheral.registers[row].width.bits()) {
        return Err(Error::FieldOutOfRange {
            instance: declaration.instance,
            register: declaration.register,
            field: declaration.field.name,
        });
    }
    slot.registers.declare_field(row, declaration.field);
    Ok(())
}

/// The row of `table` named `register`, failing on a name the table doesn't carry.
fn row_named(
    table: &'static [RegisterSpec],
    instance: &'static str,
    register: &'static str,
) -> Result<usize, Error> {
    table
        .iter()
        .position(|candidate| candidate.name == register)
        .ok_or(Error::UnknownRegister { instance, register })
}

/// Replaces one field of one register of `instance` with `correction.corrected`, in the [`RegisterFile`]
/// rather than in [`Peripheral::registers`]: that table is what [`crate::device::Device::layout`]
/// compares itself to, so a model's own layout stays the vendor's shape and only what the register file
/// applies, reads and writes through, learns the correction. [`Builder::reset`] and [`Builder::write_modify`]
/// take the same path for the same reason.
fn correct_field(slots: &mut [Slot], correction: &FieldCorrection) -> Result<(), Error> {
    let slot = slot_named_mut(slots, correction.instance)?;
    let row = row_named(
        slot.peripheral.registers,
        correction.instance,
        correction.register,
    )?;
    let register = &slot.peripheral.registers[row];
    let past = u32::from(correction.corrected.bit) + u32::from(correction.corrected.width);
    if past > u32::from(register.width.bits()) {
        return Err(Error::FieldOutOfRange {
            instance: correction.instance,
            register: correction.register,
            field: correction.field,
        });
    }
    if !register
        .fields
        .iter()
        .any(|field| field.name == correction.field)
    {
        return Err(Error::UnknownField {
            instance: correction.instance,
            register: correction.register,
            field: correction.field,
        });
    }
    slot.registers
        .correct_field(row, correction.field, correction.corrected);
    Ok(())
}

/// Where the instance a description names sits, failing on a name nothing carries.
fn slot_named(slots: &[Slot], instance: &'static str) -> Result<usize, Error> {
    slots
        .iter()
        .position(|slot| slot.peripheral.name == instance)
        .ok_or(Error::UnknownInstance { instance })
}

/// The slot, row and mask of the bit `bit` names, from the tables or a model's own declaration,
/// failing on a name nothing carries.
fn resolve_bit(
    slots: &[Slot],
    declarations: &[Declaration],
    bit: Gate,
) -> Result<(usize, usize, u64), Error> {
    let slot = slot_named(slots, bit.instance)?;
    let row = row_named(slots[slot].peripheral.registers, bit.instance, bit.register)?;
    let mask = slots[slot]
        .registers
        .fields(row)
        .iter()
        .find(|field| field.name == bit.field)
        .or_else(|| {
            declarations
                .iter()
                .find(|declared| {
                    declared.instance == bit.instance
                        && declared.register == bit.register
                        && declared.field.name == bit.field
                })
                .map(|declared| declared.field)
        })
        .map(FieldSpec::mask)
        .ok_or(Error::UnknownField {
            instance: bit.instance,
            register: bit.register,
            field: bit.field,
        })?;
    Ok((slot, row, mask))
}

/// Every declared reset line as the bus tests it, failing on a name nothing carries.
fn resolve_reset_lines(
    slots: &[Slot],
    declarations: &[Declaration],
    lines: &[(&'static str, Gate)],
) -> Result<Box<[ResolvedReset]>, Error> {
    lines
        .iter()
        .map(|&(instance, bit)| {
            let (by_slot, by_row, mask) = resolve_bit(slots, declarations, bit)?;
            Ok(ResolvedReset {
                by_slot,
                by_row,
                mask,
                held: slot_named(slots, instance)?,
            })
        })
        .collect()
}

/// A reset line as the bus tests it: a bit of one slot that holds another in reset while it stands,
/// resolved once when the part is built.
#[derive(Debug, Clone, Copy)]
struct ResolvedReset {
    by_slot: usize,
    by_row: usize,
    mask: u64,
    held: usize,
}

/// Turns a declared gate into the slot it belongs to and the slot, row and mask the bus tests against,
/// failing on a name nothing carries.
fn resolve_gate(
    slots: &[Slot],
    declarations: &[Declaration],
    spec: &GateSpec,
) -> Result<(usize, ResolvedGate), Error> {
    let gate = spec.gate;
    let (by_slot, by_row, mask) = resolve_bit(slots, declarations, gate)?;
    let gated = slot_named(slots, spec.instance)?;
    let rows = spec
        .registers
        .iter()
        .map(|name| row_named(slots[gated].peripheral.registers, spec.instance, name))
        .collect::<Result<Vec<usize>, Error>>()?;
    Ok((
        gated,
        ResolvedGate {
            by_slot,
            by_row,
            mask,
            writes_only: spec.writes_only,
            rows: rows.into_boxed_slice(),
            gate,
        },
    ))
}

/// One peripheral instance on the bus: where it answers, and what it holds. The model that gives it
/// behavior is a field of the MCU, not a box in here.
pub struct Slot {
    peripheral: Peripheral,
    registers: RegisterFile,
    /// What has to be true elsewhere for this instance to answer. Usually none.
    gates: Box<[ResolvedGate]>,
    /// Whether this is a [`Window`], which decodes offsets instead of using a register table.
    window: bool,
}

/// A gate as the bus checks it: a bit of another slot, resolved once when the part is built.
#[derive(Debug, Clone)]
struct ResolvedGate {
    by_slot: usize,
    by_row: usize,
    mask: u64,
    writes_only: bool,
    /// The rows it covers. Empty covers every row of the instance.
    rows: Box<[usize]>,
    gate: Gate,
}

impl ResolvedGate {
    fn covers(&self, row: usize, writing: bool) -> bool {
        (writing || !self.writes_only) && (self.rows.is_empty() || self.rows.contains(&row))
    }
}

/// A bit of an instance: the one that opens a gate, or the one that holds another instance in reset.
/// It's named as a field of a register.
///
/// Naming the field rather than a bit means the position comes from the tables, or from a model's
/// own declaration where the vendor's file omits it, and there's no number to mistype.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Gate {
    /// The instance holding the bit.
    pub instance: &'static str,
    /// The register holding it.
    pub register: &'static str,
    /// The field, as the manual names it.
    pub field: &'static str,
}

impl Gate {
    /// The bit `field` of `register` of `instance`.
    #[must_use]
    pub const fn by(instance: &'static str, register: &'static str, field: &'static str) -> Self {
        Self {
            instance,
            register,
            field,
        }
    }
}

/// The clock an instance runs on: one clock output of another instance, in that instance's own numbering.
///
/// The output is numbered rather than named because it's the driver's own, the way an interrupt
/// position and a request output are. The driver publishes a constant per output beside them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Clock {
    /// The instance driving it.
    pub instance: &'static str,
    /// Which of that instance's clock outputs.
    pub output: usize,
}

impl Clock {
    /// Output `output` of `instance`.
    #[must_use]
    pub const fn output(instance: &'static str, output: usize) -> Self {
        Self { instance, output }
    }
}

/// A clock as the bus delivers it: which slot runs on which output of which slot, resolved once.
#[derive(Debug, Clone, Copy)]
struct ResolvedClock {
    source: usize,
    output: usize,
    sink: usize,
}

store!(Slot {
    values: [],
    parts: [registers],
    built: [peripheral, gates, window],
});

impl Slot {
    /// The instance this slot answers for.
    #[must_use]
    pub fn peripheral(&self) -> &Peripheral {
        &self.peripheral
    }

    /// Whether this is a [`Window`] a board added.
    pub(crate) fn is_window(&self) -> bool {
        self.window
    }

    /// What this instance holds.
    #[must_use]
    pub fn registers(&self) -> &RegisterFile {
        &self.registers
    }

    /// What this instance holds, for the model that owns it.
    pub fn registers_mut(&mut self) -> &mut RegisterFile {
        &mut self.registers
    }
}

impl fmt::Debug for Slot {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Slot")
            .field("peripheral", &self.peripheral.name)
            .field("registers", &self.registers)
            .field("gates", &self.gates)
            .field("window", &self.window)
            .finish()
    }
}

/// Each instance `blocks` names, given the block size it names, which may only grow.
fn grow_blocks(
    peripherals: &mut [Peripheral],
    blocks: &[(&'static str, u64)],
) -> Result<(), Error> {
    for &(instance, size) in blocks {
        let peripheral = peripherals
            .iter_mut()
            .find(|peripheral| peripheral.name == instance)
            .ok_or(Error::UnknownInstance { instance })?;
        if size < peripheral.size {
            return Err(Error::ShrunkBlock { instance, size });
        }
        peripheral.size = size;
    }
    Ok(())
}

/// A named span of addresses, for the overlap checks of the bus, of the aliases a session opens
/// with, and of the images a run places.
#[derive(Clone, Copy)]
pub(crate) struct Extent<T = &'static str> {
    pub(crate) name: T,
    pub(crate) base: u64,
    pub(crate) size: u64,
}

impl<T> Extent<T> {
    const fn end(&self) -> u64 {
        self.base.saturating_add(self.size)
    }

    /// Whether the two share an address. A span of no bytes has none to share.
    pub(crate) const fn overlaps<U>(&self, other: &Extent<U>) -> bool {
        self.size != 0 && other.size != 0 && self.base < other.end() && other.base < self.end()
    }
}

/// Assembles a bus from its description and the SoC's corrections, checking everything once in [`Builder::build`].
#[must_use = "a builder does nothing until built"]
pub struct Builder {
    cpu: Cpu,
    memory: &'static [Region],
    peripherals: Vec<Peripheral>,
    reset_corrections: Vec<ResetCorrection>,
    write_corrections: Vec<WriteCorrection>,
    field_corrections: Vec<FieldCorrection>,
    gates: Vec<GateSpec>,
    sinks: Vec<&'static str>,
    routers: Vec<&'static str>,
    clocks: Vec<(&'static str, Clock)>,
    declarations: Vec<Declaration>,
    undefined_reads_zero: bool,
    blocks: Vec<(&'static str, u64)>,
    reset_lines: Vec<(&'static str, Gate)>,
}

struct GateSpec {
    instance: &'static str,
    registers: &'static [&'static str],
    writes_only: bool,
    gate: Gate,
}

struct ResetCorrection {
    instance: &'static str,
    register: &'static str,
    value: u64,
}

struct WriteCorrection {
    instance: &'static str,
    register: &'static str,
    rule: WriteModify,
}

struct FieldCorrection {
    instance: &'static str,
    register: &'static str,
    field: &'static str,
    corrected: FieldSpec,
}

impl fmt::Debug for Builder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Builder")
            .field("cpu", &self.cpu)
            .field("reset_corrections", &self.reset_corrections.len())
            .field("write_corrections", &self.write_corrections.len())
            .finish_non_exhaustive()
    }
}

impl Builder {
    /// Overrides a reset value where the SVD disagrees with the vendor's documentation of the SoC.
    pub fn reset(mut self, instance: &'static str, register: &'static str, value: u64) -> Self {
        self.reset_corrections.push(ResetCorrection {
            instance,
            register,
            value,
        });
        self
    }

    /// Declares a field of a register the vendor's file leaves out. The register file then applies
    /// its access and write rules, [`RegisterFile::fields`] lists it, and a gate can name it.
    ///
    /// A generated table is the vendor's file transcribed and stays that way, so a field the vendor omits
    /// is the model's own.
    pub fn declare(
        mut self,
        instance: &'static str,
        register: &'static str,
        field: &'static FieldSpec,
    ) -> Self {
        self.declarations.push(Declaration {
            instance,
            register,
            field,
        });
        self
    }

    /// Gates every access to `instance` on a bit of another instance.
    ///
    /// A peripheral whose clock is off doesn't answer its registers, and which bit says so is the
    /// part's to know. So the part's binding is where a gate is declared and where the manual is
    /// cited. An access the gate refuses is refused the way the bus refuses any other: it answers
    /// zero, the write is dropped, and it's reported.
    pub fn gate(mut self, instance: &'static str, gate: Gate) -> Self {
        self.gates.push(GateSpec {
            instance,
            registers: &[],
            writes_only: false,
            gate,
        });
        self
    }

    /// Gates writes to named registers of `instance` on a bit of another instance.
    ///
    /// See [`Builder::gate`].
    pub fn gate_writes(
        mut self,
        instance: &'static str,
        registers: &'static [&'static str],
        gate: Gate,
    ) -> Self {
        self.gates.push(GateSpec {
            instance,
            registers,
            writes_only: true,
            gate,
        });
        self
    }

    /// Drops every gate the description declared, for a bus built to hold one model rather than a part.
    ///
    /// A gate is another instance's bit, and a bus with one model on it doesn't carry the instance
    /// holding it in any meaningful state. [`crate::mcu::Single`] and [`crate::mcu::Bare`] build
    /// through this so that a model under the microscope answers. That's what a test asking about
    /// that model alone means by putting it on a bus.
    pub(crate) fn ungated(mut self) -> Self {
        self.gates.clear();
        self.reset_lines.clear();
        self
    }

    /// Holds `instance` in reset while the bit `by` names stands, the way a part's clock controller
    /// resets a peripheral through a bit of its own. At each write that leaves the bit standing, the
    /// instance's registers go back to their reset values, its model is put back, its events are
    /// dropped and its interrupts lowered, as at a system reset of the instance alone. A firmware
    /// pulses the bit, and the instance comes out of it as it came out of the part's reset.
    pub fn reset_by(mut self, instance: &'static str, by: Gate) -> Self {
        self.reset_lines.push((instance, by));
        self
    }

    /// Sends every request any instance drives to `instance` as well.
    ///
    /// A controller knows its own wiring, so it recognizes the requests meant for it and ignores the rest.
    /// Sinks see a change in the order they were named here.
    pub fn reads_requests(mut self, instance: &'static str) -> Self {
        self.sinks.push(instance);
        self
    }

    /// Sends every interrupt any instance raises to `instance` in place of the core, for an
    /// interrupt controller on the part's side, which drives the core's lines itself. A part with
    /// none has each interrupt drive the core's line of its own number. A part names one at most,
    /// and a second is refused at build.
    pub fn routes_interrupts(mut self, instance: &'static str) -> Self {
        self.routers.push(instance);
        self
    }

    /// Runs `instance` on `clock`, an output of another instance: a change of that output's rate reaches
    /// `instance` at [`crate::device::Device::on_clock`], and no other output does.
    ///
    /// An instance runs on one clock. Naming a second replaces nothing and is refused at build.
    pub fn clocked_by(mut self, instance: &'static str, clock: Clock) -> Self {
        self.clocks.push((instance, clock));
        self
    }

    /// Overrides the write rule of a register and of every field in it where the SVD disagrees with the
    /// vendor's documentation of the SoC, a status register whose flags clear on a written zero for one.
    pub fn write_modify(
        mut self,
        instance: &'static str,
        register: &'static str,
        rule: WriteModify,
    ) -> Self {
        self.write_corrections.push(WriteCorrection {
            instance,
            register,
            rule,
        });
        self
    }

    /// Corrects a field's shape where the SVD disagrees with the vendor's documentation of the SoC, the
    /// way [`Builder::reset`] corrects a register's reset value: `corrected` replaces the named field
    /// whole, so a struct update over the table's own constant keeps what the SVD got right and
    /// restates only what it did not.
    pub fn field(
        mut self,
        instance: &'static str,
        register: &'static str,
        field: &'static str,
        corrected: FieldSpec,
    ) -> Self {
        self.field_corrections.push(FieldCorrection {
            instance,
            register,
            field,
            corrected,
        });
        self
    }

    /// Gives `instance` a block of `size` bytes where the description gives it a smaller one: what a
    /// part has whose manual places registers past the end the description does. Space the block
    /// gains holds no register, so on a part whose undefined space reads zero it answers that way.
    pub fn grow_block(mut self, instance: &'static str, size: u64) -> Self {
        self.blocks.push((instance, size));
        self
    }

    /// Has the part answer an access to space inside an instance's block that no register covers
    /// with zero, and drop a write there, rather than take a fault: what a part does whose manual
    /// says undefined space in a peripheral reads zero. A firmware that reaches such space is told
    /// to the session, once for each instance.
    pub fn undefined_reads_zero(mut self) -> Self {
        self.undefined_reads_zero = true;
        self
    }

    /// Checks the description and produces the bus, naming what is at fault otherwise.
    ///
    /// A description with no gates declared builds as it is. A gate is something a part declares
    /// between two of its instances, and a bus of your own with none needs nothing more than this.
    pub fn build(mut self) -> Result<Bus, Error> {
        grow_blocks(&mut self.peripherals, &self.blocks)?;
        let regions = self.memory.iter().map(|region| Extent {
            name: region.name,
            base: region.base,
            size: region.size,
        });
        if let Some((lower, upper)) = first_overlap(regions) {
            return Err(Error::OverlappingRegions { lower, upper });
        }
        check_erase_blocks(self.memory)?;
        let spans = self.peripherals.iter().map(|peripheral| Extent {
            name: peripheral.name,
            base: peripheral.base,
            size: peripheral.size,
        });
        if let Some((lower, upper)) = first_overlap(spans) {
            return Err(Error::OverlappingInstances { lower, upper });
        }
        check_interrupts(&self.peripherals, self.cpu.interrupt_lines)?;

        let mut slots: Vec<Slot> = self
            .peripherals
            .into_iter()
            .map(|peripheral| Slot {
                gates: Box::default(),
                peripheral,
                registers: RegisterFile::new(peripheral.registers),
                window: false,
            })
            .collect();
        slots.sort_by_key(|slot| slot.peripheral.base);
        check_programmers(self.memory, &slots)?;

        for correction in self.reset_corrections {
            let instance = slot_named_mut(&mut slots, correction.instance)?;
            let row = row_named(
                instance.peripheral.registers,
                correction.instance,
                correction.register,
            )?;
            let register = &instance.peripheral.registers[row];
            if correction.value & !register.width.mask() != 0 {
                return Err(Error::ResetTooWide {
                    instance: correction.instance,
                    register: correction.register,
                    value: correction.value,
                });
            }
            instance.registers.correct_reset(row, correction.value);
        }

        for correction in self.write_corrections {
            let instance = slot_named_mut(&mut slots, correction.instance)?;
            let row = row_named(
                instance.peripheral.registers,
                correction.instance,
                correction.register,
            )?;
            instance.registers.correct_write(row, correction.rule);
        }

        for correction in &self.field_corrections {
            correct_field(&mut slots, correction)?;
        }

        for declaration in &self.declarations {
            declare_field(&mut slots, declaration)?;
        }

        let sinks = self
            .sinks
            .iter()
            .map(|name| slot_named(&slots, name))
            .collect::<Result<Vec<usize>, Error>>()?;
        let router = router(&slots, &self.routers)?;

        let mut clocks = Vec::with_capacity(self.clocks.len());
        for (instance, clock) in &self.clocks {
            let sink = slot_named(&slots, instance)?;
            if clocks
                .iter()
                .any(|wired: &ResolvedClock| wired.sink == sink)
            {
                return Err(Error::ClockedTwice { instance });
            }
            clocks.push(ResolvedClock {
                source: slot_named(&slots, clock.instance)?,
                output: clock.output,
                sink,
            });
        }

        for spec in self.gates {
            let (gated, resolved) = resolve_gate(&slots, &self.declarations, &spec)?;
            let mut gates = std::mem::take(&mut slots[gated].gates).into_vec();
            gates.push(resolved);
            slots[gated].gates = gates.into_boxed_slice();
        }

        let reset_lines = resolve_reset_lines(&slots, &self.declarations, &self.reset_lines)?;
        let drives_resets = (0..slots.len())
            .map(|index| reset_lines.iter().any(|line| line.by_slot == index))
            .collect();
        let spans = slots
            .iter()
            .enumerate()
            .map(|(index, slot)| (slot.peripheral.base, slot.peripheral.size, index))
            .collect();
        Ok(Bus {
            cpu: self.cpu,
            memory: self.memory.to_vec(),
            described: self.memory.len(),
            spans,
            slots,
            effects: Effects::default(),
            sinks,
            router,
            clocks,
            undefined_reads_zero: self.undefined_reads_zero,
            reset_lines,
            drives_resets,
        })
    }
}

/// The slot of the one instance `named` routes interrupts, if it names one.
fn router(slots: &[Slot], named: &[&'static str]) -> Result<Option<usize>, Error> {
    match *named {
        [] => Ok(None),
        [instance] => slot_named(slots, instance).map(Some),
        [first, second, ..] => Err(Error::RoutedTwice { first, second }),
    }
}

fn slot_named_mut<'a>(slots: &'a mut [Slot], name: &'static str) -> Result<&'a mut Slot, Error> {
    let index = slot_named(slots, name)?;
    Ok(&mut slots[index])
}

/// The first two spans that share an address, by ascending base: the lower and the one that
/// starts inside it.
pub(crate) fn first_overlap<T: Copy>(spans: impl Iterator<Item = Extent<T>>) -> Option<(T, T)> {
    // A span of no bytes overlaps nothing, and left in it would part two neighbors that do.
    let mut sorted: Vec<Extent<T>> = spans.filter(|span| span.size != 0).collect();
    sorted.sort_by_key(|span| span.base);
    sorted
        .windows(2)
        .find(|pair| pair[0].overlaps(&pair[1]))
        .map(|pair| (pair[0].name, pair[1].name))
}

/// Refuses a region whose erase blocks don't add up to its size.
fn check_erase_blocks(memory: &[Region]) -> Result<(), Error> {
    let covered = |region: &Region| {
        region.blocks.iter().try_fold(0_u64, |covered, blocks| {
            blocks
                .size
                .get()
                .checked_mul(u64::from(blocks.count.get()))
                .and_then(|bytes| covered.checked_add(bytes))
        })
    };
    match memory
        .iter()
        .find(|region| !region.blocks.is_empty() && covered(region) != Some(region.size))
    {
        Some(region) => Err(Error::EraseBlocksMismatch {
            region: region.name,
        }),
        None => Ok(()),
    }
}

/// Refuses a region whose programmer the part doesn't have, and RAM with a programmer.
fn check_programmers(memory: &[Region], slots: &[Slot]) -> Result<(), Error> {
    for region in memory {
        let Some(instance) = region.programmer else {
            continue;
        };
        if region.kind.is_writable() {
            return Err(Error::ProgrammedRam {
                region: region.name,
            });
        }
        if slot_named(slots, instance).is_err() {
            return Err(Error::NoProgrammer {
                region: region.name,
                instance,
            });
        }
    }
    Ok(())
}

fn check_interrupts(peripherals: &[Peripheral], lines: u16) -> Result<(), Error> {
    for peripheral in peripherals {
        if let Some(&line) = peripheral.interrupts.iter().find(|&&line| line >= lines) {
            return Err(Error::InterruptOutOfRange {
                instance: peripheral.name,
                line,
                lines,
            });
        }
    }
    Ok(())
}

/// A checked bus: the CPU, the memory map, and every peripheral instance with its register file.
///
/// It answers where an address lands and what that register holds. It doesn't answer what the
/// peripheral *does*. That's the model, which is a field of the MCU built on this bus.
#[derive(Debug)]
pub struct Bus {
    cpu: Cpu,
    memory: Vec<Region>,
    /// How many entries of `memory` came from the description. A board added the rest.
    described: usize,
    /// The instances of the description, in address order, then each window a board added.
    slots: Vec<Slot>,
    /// Each slot's first address, its size and its index, by ascending address, where finding the
    /// slot an address lands in reads only these.
    spans: Vec<(u64, u64, usize)>,
    effects: Effects,
    /// The slots that read every request, in the order the description named them.
    sinks: Vec<usize>,
    /// The slot that hears every interrupt in place of the core, if the description named one.
    router: Option<usize>,
    /// Which slot runs on which clock output of which slot, in the order the description named them.
    clocks: Vec<ResolvedClock>,
    /// Whether an access to space inside an instance's block that no register covers reads zero and
    /// drops a write, as the description says the part does, rather than taking a fault.
    undefined_reads_zero: bool,
    /// The bits of one slot that hold another in reset, as the description declared them.
    reset_lines: Box<[ResolvedReset]>,
    /// Whether a bit of the slot at each index holds another in reset, so a write to any other
    /// looks at no reset line.
    drives_resets: Box<[bool]>,
}

/// How many events one instant may carry before the runtime calls it a model that can't move time
/// on. Several models legitimately schedule at one instant, but none of them needs a thousand.
pub(crate) const SAME_INSTANT_LIMIT: u32 = 1_000;

/// How many steps one settle may take before the runtime calls it a model that never finishes.
///
/// A settle carries out what the models asked for, and each answer may produce another ask. The
/// largest legitimate run of them is one block move: the 65535 items a sixteen-bit counter holds,
/// four bytes each at the widest, moved a byte at a time at the narrowest on the other side.
/// That's 65535 accesses on one port and four times as many on the other, and each access is two
/// steps here, itself and its answer. Twice that leaves room for the other models the same settle
/// reaches and still catches one answering its own answer.
// ceiling: one sixteen-bit block move per settle; upgrade when a wider counter moves more
pub(crate) const SETTLE_LIMIT: u32 = 2 * 2 * (65_535 + 4 * 65_535);

store!(Bus {
    values: [effects],
    parts: [slots],
    built: [
        cpu,
        memory,
        described,
        spans,
        sinks,
        router,
        clocks,
        undefined_reads_zero,
        reset_lines,
        drives_resets
    ],
});

impl Bus {
    /// Starts assembling a bus from its CPU, memory map, and peripheral instances.
    pub fn builder(
        cpu: Cpu,
        memory: &'static [Region],
        peripherals: impl IntoIterator<Item = Peripheral>,
    ) -> Builder {
        Builder {
            cpu,
            memory,
            peripherals: peripherals.into_iter().collect(),
            reset_corrections: Vec::new(),
            write_corrections: Vec::new(),
            field_corrections: Vec::new(),
            gates: Vec::new(),
            sinks: Vec::new(),
            routers: Vec::new(),
            clocks: Vec::new(),
            declarations: Vec::new(),
            undefined_reads_zero: false,
            blocks: Vec::new(),
            reset_lines: Vec::new(),
        }
    }

    /// Every slot, in address order. The index is what [`crate::mcu::Mcu::split`] dispatches on.
    #[must_use]
    pub fn slots(&self) -> &[Slot] {
        &self.slots
    }

    /// The part as a system reset leaves it: every register at its reset value and nothing scheduled,
    /// driven, or waiting for an answer.
    pub fn reset(&mut self) {
        for slot in &mut self.slots {
            slot.registers.reset();
        }
        let mut events = std::mem::take(&mut self.effects.events);
        events.clear();
        self.effects = Effects {
            events,
            ..Effects::default()
        };
    }

    /// The slot index of the instance called `name`, which an MCU resolves once at construction so
    /// that nothing after it looks a peripheral up by string.
    #[must_use]
    pub fn slot_of(&self, name: &str) -> Option<usize> {
        self.slots
            .iter()
            .position(|slot| slot.peripheral.name == name)
    }

    /// The slot an address falls in, or `None` where no instance covers it.
    ///
    /// The same search an access decodes with, for a caller that wants to know which instance an address
    /// belongs to without making the access.
    #[must_use]
    pub fn slot_at(&self, address: u64) -> Option<usize> {
        let candidates = self.spans.partition_point(|&(base, ..)| base <= address);
        let (base, size, index) = self.spans[candidates.checked_sub(1)?];
        (address - base < size).then_some(index)
    }

    /// The CPU.
    pub fn cpu(&self) -> Cpu {
        self.cpu
    }

    /// The memory regions, the description's and then each one a board added.
    pub fn memory(&self) -> &[Region] {
        &self.memory
    }

    /// Adds a region of memory a board fits outside the part, like RAM or flash on its external
    /// memory interface. The emulator maps it as it maps the part's own, an image can be placed in
    /// it, and a model's requested access reaches it.
    ///
    /// Fails when the region shares a name or an address with a region, an instance or a window
    /// already there, runs past the last address, its erase blocks don't add up to its size, or it
    /// names a programmer the part doesn't have or is RAM with one.
    pub fn add_region(&mut self, region: Region) -> Result<(), Error> {
        self.check_added(Extent {
            name: region.name,
            base: region.base,
            size: region.size,
        })?;
        check_erase_blocks(&[region])?;
        check_programmers(&[region], &self.slots)?;
        self.memory.push(region);
        Ok(())
    }

    /// Adds a window for a board's chip and returns its slot. The slot comes after every existing
    /// slot, so no slot a part already resolved moves. Fails like [`Bus::add_region`], and also
    /// when the gate or an interrupt names something the bus doesn't have.
    pub fn add_window(&mut self, window: Window) -> Result<usize, Error> {
        let peripheral = Peripheral {
            name: window.name,
            base: window.base,
            size: window.size.get(),
            interrupts: window.interrupts,
            registers: &NO_REGISTERS,
        };
        self.check_added(Extent {
            name: window.name,
            base: window.base,
            size: window.size.get(),
        })?;
        check_interrupts(&[peripheral], self.cpu.interrupt_lines)?;
        let index = self.slots.len();
        self.slots.push(Slot {
            peripheral,
            registers: RegisterFile::new(&NO_REGISTERS),
            gates: Box::default(),
            window: true,
        });
        if let Some(gate) = window.gate {
            let spec = GateSpec {
                instance: window.name,
                registers: &[],
                writes_only: false,
                gate,
            };
            match resolve_gate(&self.slots, &[], &spec) {
                Ok((_, resolved)) => self.slots[index].gates = Box::new([resolved]),
                Err(error) => {
                    self.slots.pop();
                    return Err(error);
                }
            }
        }
        let at = self.spans.partition_point(|&(base, ..)| base < window.base);
        self.spans
            .insert(at, (window.base, window.size.get(), index));
        Ok(index)
    }

    /// Copies the regions and windows a board added to `from` onto this bus, with each window in
    /// the same slot, and goes on numbering events from where `from` stood, so an id a chip kept
    /// from before is never a new event's. A part that rebuilds its bus on reset uses this to keep
    /// them.
    ///
    /// Fails, with nothing copied, unless `self` is fresh from the same description as `from`: the
    /// same CPU, regions and instances, and nothing added yet. Otherwise a window would land on
    /// another slot than the one its chip answers for.
    pub fn keep_added(&mut self, from: &Bus) -> Result<(), Error> {
        fn described(bus: &Bus) -> (Cpu, &[Region], Vec<Peripheral>) {
            let instances = bus.slots.iter().filter(|slot| !slot.window);
            (
                bus.cpu,
                &bus.memory[..bus.described],
                instances.map(|slot| slot.peripheral).collect(),
            )
        }
        let fresh =
            self.memory.len() == self.described && self.slots.iter().all(|slot| !slot.window);
        if !fresh || described(self) != described(from) {
            return Err(Error::OtherDescription);
        }
        self.memory
            .extend_from_slice(&from.memory[from.described..]);
        for slot in from.slots.iter().filter(|slot| slot.window) {
            self.slots.push(Slot {
                peripheral: slot.peripheral,
                registers: RegisterFile::new(slot.peripheral.registers),
                gates: slot.gates.clone(),
                window: true,
            });
        }
        self.spans.clone_from(&from.spans);
        self.effects.events.continue_from(&from.effects.events);
        Ok(())
    }

    /// Refuses an added span with a name already taken, one past the last address, and one over a
    /// region, an instance or a window.
    fn check_added(&self, added: Extent) -> Result<(), Error> {
        let regions = self.memory.iter().map(|region| Extent {
            name: region.name,
            base: region.base,
            size: region.size,
        });
        let instances = self.slots.iter().map(|slot| Extent {
            name: slot.peripheral.name,
            base: slot.peripheral.base,
            size: slot.peripheral.size,
        });
        let mut held = regions.chain(instances);
        if held.clone().any(|held| held.name == added.name) {
            return Err(Error::NamedTwice { added: added.name });
        }
        if added.base.checked_add(added.size).is_none() {
            return Err(Error::PastTheEnd { added: added.name });
        }
        match held.find(|held| held.overlaps(&added)) {
            Some(held) => Err(Error::Overlapping {
                added: added.name,
                by: held.name,
            }),
            None => Ok(()),
        }
    }

    /// Every peripheral instance, by ascending base address.
    pub fn peripherals(&self) -> impl Iterator<Item = &Peripheral> {
        self.slots.iter().map(|slot| &slot.peripheral)
    }

    /// The instance with this name.
    #[must_use]
    pub fn peripheral(&self, name: &str) -> Option<&Peripheral> {
        self.slot_of(name).map(|slot| &self.slots[slot].peripheral)
    }

    /// The register file of the instance with this name.
    #[must_use]
    pub fn registers(&self, name: &str) -> Option<&RegisterFile> {
        self.slot_of(name).map(|slot| &self.slots[slot].registers)
    }

    /// The registers of the instance at `slot` and a context for its model at `at`, as an access hands
    /// them over, for an input the bus doesn't carry: a level on a pin, a sample, a word from a chip.
    /// A part's `drive_` method is this with its model's field named beside it. What the model does
    /// with the context, an event, an interrupt or a request, settles when the run resumes from the
    /// stop the input was handed over at, so the firmware sees it at that same stop.
    ///
    /// # Panics
    ///
    /// If `slot` is past the end of [`Bus::slots`].
    pub fn drive(
        &mut self,
        at: VirtualNanos,
        slot: usize,
    ) -> (&mut RegisterFile, DeviceContext<'_>) {
        let (slot, context) = self.call(at, slot);
        (slot.registers_mut(), context)
    }

    /// The slot at `index`, for the MCU that owns its model. A part's setter that changes what its
    /// registers hold with no instant to schedule from, like a supply that sets a status bit, writes
    /// through it. One that schedules or raises goes through [`Bus::drive`].
    ///
    /// # Panics
    ///
    /// If `index` is past the end of [`Bus::slots`].
    pub fn slot_mut(&mut self, index: usize) -> &mut Slot {
        &mut self.slots[index]
    }

    /// The slot whose block `address` falls in where no register covers it, on a part whose
    /// undefined space reads zero, or `None` where the address is covered, outside every block, or
    /// the part takes a fault there. It's asked only once an access has come back unmapped, which an
    /// access in a window never does.
    pub(crate) fn undefined_at(&self, address: u64) -> Option<usize> {
        if !self.undefined_reads_zero {
            return None;
        }
        let index = self.slot_at(address)?;
        let slot = &self.slots[index];
        let offset = u32::try_from(address - slot.peripheral.base).ok()?;
        slot.registers
            .row_covering(offset, |_| true)
            .is_none()
            .then_some(index)
    }

    /// Where an access lands, or the fault it takes.
    pub(crate) fn locate(
        &self,
        address: u64,
        width: Width,
        kind: AccessKind,
    ) -> Result<Located, Fault> {
        self.land::<true>(address, width, kind)
    }

    /// Where an access lands whatever its gate says, or the fault it takes: what a debugger's peek
    /// reaches, since a register file holds its values with its gate shut.
    pub(crate) fn locate_ungated(
        &self,
        address: u64,
        width: Width,
        kind: AccessKind,
    ) -> Result<Located, Fault> {
        self.land::<false>(address, width, kind)
    }

    // Both of the above as one body, so the firmware's path compiles to the instructions it did
    // before a debugger's peek needed the other, `row_covering` inlined in it. Had `locate` called
    // `locate_ungated` and then tested the gate, every access the firmware made gained a call.
    fn land<const GATED: bool>(
        &self,
        address: u64,
        width: Width,
        kind: AccessKind,
    ) -> Result<Located, Fault> {
        let allows: fn(Access) -> bool = match kind {
            AccessKind::Read => Access::is_readable,
            AccessKind::Write => Access::is_writable,
        };
        let index = self.slot_at(address).ok_or(Fault::Unmapped { address })?;
        let slot = &self.slots[index];
        if slot.window {
            let offset = address - slot.peripheral.base;
            if offset + u64::from(width.bytes()) > slot.peripheral.size {
                return Err(Fault::Misaligned { address, width });
            }
            if GATED && let Some(shut) = slot.gates.iter().find(|gate| !self.gate_is_open(gate)) {
                return Err(Fault::Gated {
                    instance: slot.peripheral.name,
                    register: WINDOW,
                    by: shut.gate,
                });
            }
            return Ok(Located {
                slot: index,
                row: 0,
                lane: Lane { shift: 0 },
                window: Some(offset),
            });
        }
        let offset = u32::try_from(address - slot.peripheral.base)
            .map_err(|_too_far| Fault::Unmapped { address })?;
        let row = slot
            .registers
            .row_covering(offset, allows)
            .ok_or(Fault::Unmapped { address })?;
        let register = &slot.peripheral.registers[row];
        let byte_in_register = offset - register.offset;
        if byte_in_register + width.bytes() > register.width.bytes() {
            return Err(Fault::Misaligned { address, width });
        }
        // The gate is tested last, after the address has been resolved to a register of this
        // instance. That way an address the instance doesn't carry is still reported as the gap in
        // the map it is, rather than as the instance declining to answer.
        if GATED
            && let Some(shut) = slot.gates.iter().find(|gate| {
                gate.covers(row, kind == AccessKind::Write) && !self.gate_is_open(gate)
            })
        {
            return Err(Fault::Gated {
                instance: slot.peripheral.name,
                register: register.name,
                by: shut.gate,
            });
        }
        // ceiling: a range the architecture keeps little-endian whatever the part's order takes the
        // part's lane here; upgrade when a big-endian part models a register there that takes
        // narrow accesses.
        Ok(Located {
            slot: index,
            row,
            lane: Lane {
                shift: lane_shift(
                    self.cpu.endian,
                    register.width.bytes(),
                    byte_in_register,
                    width,
                ),
            },
            window: None,
        })
    }

    /// Whether the bit a gate names stands.
    ///
    /// The bit is read where it lies, whatever gates the instance holding it. A gate isn't
    /// evaluated through another. That avoids a cycle, since two instances can each hold the bit
    /// that opens the other. It's also the truer reading, since an enable keeps its value when the
    /// thing it enables is off.
    fn gate_is_open(&self, gate: &ResolvedGate) -> bool {
        self.slots[gate.by_slot].registers.get_row(gate.by_row) & gate.mask != 0
    }

    /// The slots a bit of the slot `by` holds in reset now, in the order the description declared
    /// them.
    pub(crate) fn held_in_reset_by(&self, by: usize) -> Vec<usize> {
        if !self.drives_resets[by] {
            return Vec::new();
        }
        self.reset_lines
            .iter()
            .filter(|line| {
                line.by_slot == by && self.slots[by].registers.get_row(line.by_row) & line.mask != 0
            })
            .map(|line| line.held)
            .collect()
    }

    /// Puts the slot at `index` back as a system reset leaves it, alone: every register at its reset
    /// value and nothing of its own scheduled. Its model and its lines are the caller's.
    pub(crate) fn reset_slot(&mut self, index: usize) {
        self.slots[index].registers.reset();
        self.effects.events.forget(index);
    }

    /// The slot at `index` with a context for the model that owns it, borrowed apart.
    pub(crate) fn call(
        &mut self,
        at: VirtualNanos,
        index: usize,
    ) -> (&mut Slot, DeviceContext<'_>) {
        let Self { slots, effects, .. } = self;
        let slot = &mut slots[index];
        let context = DeviceContext::new(at, index, slot.peripheral, effects);
        (slot, context)
    }

    /// The next event due by `now`, as its id, the slot that scheduled it, and its instant.
    pub(crate) fn pop_due(&mut self, now: VirtualNanos) -> Option<(EventId, usize, VirtualNanos)> {
        self.effects.events.pop_due(now)
    }

    /// The instant of the earliest pending event, which is when the emulator next needs to stop.
    #[must_use]
    pub fn next_event(&self) -> Option<VirtualNanos> {
        self.effects.events.next_at()
    }

    /// Takes the interrupt levels the models set since the last drain, in the order they set them.
    pub fn drain_interrupts(&mut self) -> impl Iterator<Item = InterruptChange> + '_ {
        self.effects
            .interrupts
            .drain(..)
            .map(|(_at, change)| change)
    }

    /// The slot that hears every interrupt in place of the core, if the description named one.
    pub(crate) fn router(&self) -> Option<usize> {
        self.router
    }

    /// The oldest interrupt change the router hasn't heard yet, with the instant it was set at.
    pub(crate) fn next_interrupt_change(&mut self) -> Option<(VirtualNanos, InterruptChange)> {
        self.effects.interrupts.pop_front()
    }

    /// Takes what an interrupt controller on the part drove onto the core's lines since the last
    /// drain, in the order it drove them.
    pub fn drain_lines(&mut self) -> impl Iterator<Item = LineChange> + '_ {
        self.effects.lines.drain(..)
    }

    /// Takes what the models told since the last drain, in the order they told it.
    pub fn drain_told(&mut self) -> impl Iterator<Item = Told> + '_ {
        self.effects.told.drain(..)
    }

    /// Marks `address` as answered from undefined space, for whoever made the access to take.
    pub(crate) fn answered_undefined(&mut self, address: u64) {
        self.effects.undefined = Some(address);
    }

    /// Takes the address the last access reached in undefined space, if it reached one since the last
    /// take.
    pub(crate) fn take_undefined(&mut self) -> Option<u64> {
        self.effects.undefined.take()
    }

    /// The slots that read every request, in the order the description named them.
    pub(crate) fn sinks(&self) -> &[usize] {
        &self.sinks
    }

    /// The oldest request change no sink has seen yet, with the instant it was driven at.
    pub(crate) fn next_request_change(&mut self) -> Option<(VirtualNanos, RequestChange)> {
        self.effects.requests.pop_front()
    }

    /// Takes the request levels the models set since the last drain, in the order they set them.
    pub fn drain_requests(&mut self) -> impl Iterator<Item = RequestChange> + '_ {
        self.effects.requests.drain(..).map(|(_at, change)| change)
    }

    /// The oldest clock change no reader has seen yet, with the instant it was driven at.
    pub(crate) fn next_clock_change(&mut self) -> Option<(VirtualNanos, ClockChange)> {
        self.effects.clocks.pop_front()
    }

    /// The slots that run on `change`'s output, in the order the description named them.
    pub(crate) fn readers_of(&self, change: ClockChange) -> impl Iterator<Item = usize> + '_ {
        let source = self.slot_of(change.instance);
        self.clocks
            .iter()
            .filter(move |wired| Some(wired.source) == source && wired.output == change.output)
            .map(|wired| wired.sink)
    }

    /// The clock each instance runs on, by name, for a check that every instance keeping time has one.
    pub fn clock_of(&self, instance: &str) -> Option<Clock> {
        let sink = self.slot_of(instance)?;
        self.clocks
            .iter()
            .find(|wired| wired.sink == sink)
            .map(|wired| Clock {
                instance: self.slots[wired.source].peripheral.name,
                output: wired.output,
            })
    }

    /// Takes the clock rates the models drove since the last drain, in the order they drove them.
    pub fn drain_clocks(&mut self) -> impl Iterator<Item = ClockChange> + '_ {
        self.effects.clocks.drain(..).map(|(_at, change)| change)
    }

    /// Whether a model has asked for a system reset during the settle now running, without taking it:
    /// the settle loop stops here rather than carrying out effects a reset is about to discard.
    pub(crate) fn reset_requested(&self) -> bool {
        self.effects.reset.is_some()
    }

    /// Takes the reset a model asked for, if one did.
    pub fn take_reset_request(&mut self) -> Option<ResetCause> {
        self.effects.reset.take()
    }

    /// The oldest access a model asked for and the runtime hasn't made.
    pub(crate) fn next_pending(&mut self) -> Option<PendingAccess> {
        self.effects.accesses.pop_front()
    }

    /// The oldest answer the runtime hasn't handed back to the model that asked.
    pub(crate) fn next_answer(&mut self) -> Option<Answer> {
        self.effects.answers.pop_front()
    }

    /// Puts an answer in the queue for the model that asked, at the instant it asked. `found` is
    /// nothing where the bus refused the access.
    pub(crate) fn answer(&mut self, access: &PendingAccess, found: Option<u64>) {
        self.effects.answers.push_back(Answer {
            at: access.at,
            owner: access.owner,
            token: access.token,
            found,
        });
    }

    /// Which region of memory holds the whole of an access of `width` at `address`, if one does. Any
    /// other access is the peripheral bus's, one that starts in a region and runs past its end among
    /// them: the emulator is only ever handed an access that lies inside memory it lends, never one
    /// crossing into whatever follows a region.
    pub(crate) fn region_holding(&self, address: u64, width: Width) -> Option<&Region> {
        let last = address.checked_add(u64::from(width.bytes()) - 1)?;
        self.memory
            .iter()
            .find(|region| region.contains(address) && region.contains(last))
    }

    /// Drops the programmer of every region `instance` doesn't program, for a bus that holds one
    /// model rather than a part, as [`Builder::ungated`] drops its gates. A store to such a region
    /// is then refused as one where nothing answers.
    pub(crate) fn programmed_only_by(&mut self, instance: &str) {
        for region in &mut self.memory {
            if region.programmer.is_some_and(|named| named != instance) {
                region.programmer = None;
            }
        }
    }

    /// The slot whose model programs the region holding the whole access, where the region names one.
    pub(crate) fn programmer_of(&self, address: u64, width: Width) -> Option<usize> {
        let instance = self.region_holding(address, width)?.programmer?;
        slot_named(&self.slots, instance).ok()
    }
}

/// How far up a register's value an access of `width` lands, in bits, when it starts `byte` bytes
/// into a register `register` bytes wide that it fits inside, on a part that keeps its bytes
/// `endian`. A narrow access takes the bytes it names of the register, and the byte order decides
/// their significance.
pub(crate) const fn lane_shift(endian: Endian, register: u32, byte: u32, width: Width) -> u32 {
    let lane = match endian {
        Endian::Little => byte,
        Endian::Big => register - byte - width.bytes(),
    };
    lane * Width::W8.bits() as u32
}

/// Where one bus access lands: the slot, the register row, and the lane inside the register.
pub(crate) struct Located {
    pub(crate) slot: usize,
    pub(crate) row: usize,
    pub(crate) lane: Lane,
    /// The offset into a window, if the access lands in one.
    pub(crate) window: Option<u64>,
}

pub(crate) struct Lane {
    pub(crate) shift: u32,
}

#[cfg(test)]
mod tests {
    use super::*;

    const ENABLE: FieldSpec = FieldSpec {
        name: "EN",
        bit: 0,
        width: 1,
        access: Access::ReadWrite,
        read: ReadAction::None,
        write: WriteModify::None,
    };

    const fn register(
        name: &'static str,
        offset: u32,
        fields: &'static [FieldSpec],
    ) -> RegisterSpec {
        RegisterSpec {
            name,
            offset,
            width: Width::W32,
            reset: 0,
            access: Access::ReadWrite,
            read: ReadAction::None,
            write: WriteModify::None,
            fields,
        }
    }

    static CLOCKS: [RegisterSpec; 1] = [register("ENR", 0x0, &[ENABLE])];
    static PORT: [RegisterSpec; 2] = [register("DR", 0x0, &[]), register("SR", 0x4, &[])];
    static MEMORY: [Region; 1] = [Region::ram("sram", 0x2000_0000, 4 << 10)];

    const fn blocks(size: u64, count: u32) -> EraseBlocks {
        match (NonZeroU64::new(size), NonZeroU32::new(count)) {
            (Some(size), Some(count)) => EraseBlocks { size, count },
            _ => panic!("a block has bytes"),
        }
    }

    static WHOLE: [Region; 2] = [
        Region::flash("flash", 0x0800_0000, 0x1_8000)
            .erased_in(&[blocks(0x4000, 2), blocks(0x1_0000, 1)]),
        Region::flash("plain", 0x0900_0000, 0x1000),
    ];
    static SHORT: [Region; 1] =
        [Region::flash("short", 0x0800_0000, 0x1_8000).erased_in(&[blocks(0x4000, 2)])];
    static OVER: [Region; 1] = [Region::flash("over", 0x0800_0000, 0x1_8000)
        .erased_in(&[blocks(0x4000, 2), blocks(0x1_0000, 2)])];
    static WRAPS: [Region; 1] = [Region::flash("wraps", 0x0800_0000, 0x1_8000)
        .erased_in(&[blocks(u64::MAX, u32::MAX), blocks(0x1_8001, 1)])];

    /// A region's erase blocks add up to its size, or `Bus::build` names the region whose don't,
    /// however far past its size, or round the address space, they reach. A region with none is one
    /// block.
    #[test]
    fn erase_blocks_that_dont_cover_their_region_are_refused() {
        let cpu = Cpu {
            name: "core",
            fpu: false,
            interrupt_lines: 16,
            endian: Endian::Little,
        };
        let build = |memory: &'static [Region]| Bus::builder(cpu, memory, []).build().map(drop);
        assert_eq!(build(&WHOLE), Ok(()));
        for (memory, region) in [(&SHORT, "short"), (&OVER, "over"), (&WRAPS, "wraps")] {
            assert_eq!(build(memory), Err(Error::EraseBlocksMismatch { region }));
        }
    }

    /// The two instances of [`gated`], ungated, through `adjust` before they're built.
    fn adjusted(adjust: impl FnOnce(Builder) -> Builder) -> Result<Bus, Error> {
        let cpu = Cpu {
            name: "core",
            fpu: false,
            interrupt_lines: 16,
            endian: Endian::Little,
        };
        let instance = |name, base, registers: &'static [RegisterSpec]| Peripheral {
            name,
            base,
            size: 0x100,
            interrupts: &[],
            registers,
        };
        adjust(Bus::builder(
            cpu,
            &MEMORY,
            [
                instance("CLOCKS", 0x4000_0000, &CLOCKS),
                instance("PORT", 0x4000_1000, &PORT),
            ],
        ))
        .build()
    }

    #[test]
    fn undefined_space_is_named_only_on_a_part_that_answers_it_and_only_where_no_register_is() {
        let plain = adjusted(|builder| builder).unwrap();
        assert_eq!(plain.undefined_at(0x4000_1008), None, "the default faults");
        let answering = adjusted(Builder::undefined_reads_zero).unwrap();
        assert_eq!(answering.undefined_at(0x4000_1008), Some(1));
        assert_eq!(
            answering.undefined_at(0x4000_1004),
            None,
            "a register is there"
        );
        assert_eq!(
            answering.undefined_at(0x4000_2000),
            None,
            "outside every block"
        );
    }

    #[test]
    fn a_block_grows_where_a_manual_says_and_never_shrinks_or_names_an_instance_it_lacks() {
        let grown =
            adjusted(|builder| builder.undefined_reads_zero().grow_block("PORT", 0x200)).unwrap();
        assert_eq!(
            grown.undefined_at(0x4000_1180),
            Some(1),
            "inside the grown block"
        );
        assert_eq!(
            adjusted(|builder| builder.grow_block("PORT", 0x80)).err(),
            Some(Error::ShrunkBlock {
                instance: "PORT",
                size: 0x80
            })
        );
        assert_eq!(
            adjusted(|builder| builder.grow_block("NOWHERE", 0x200)).err(),
            Some(Error::UnknownInstance {
                instance: "NOWHERE"
            })
        );
        assert!(
            matches!(
                adjusted(|builder| builder.grow_block("CLOCKS", 0x2000)),
                Err(Error::OverlappingInstances { .. })
            ),
            "a grown block is held to the overlap check"
        );
    }

    /// One instance whose every access is gated on another's enable.
    fn gated() -> Bus {
        let cpu = Cpu {
            name: "core",
            fpu: false,
            interrupt_lines: 16,
            endian: Endian::Little,
        };
        let instance = |name, base, registers: &'static [RegisterSpec]| Peripheral {
            name,
            base,
            size: 0x100,
            interrupts: &[],
            registers,
        };
        Bus::builder(
            cpu,
            &MEMORY,
            [
                instance("CLOCKS", 0x4000_0000, &CLOCKS),
                instance("PORT", 0x4000_1000, &PORT),
            ],
        )
        .gate("PORT", Gate::by("CLOCKS", "ENR", "EN"))
        .build()
        .unwrap()
    }

    #[test]
    fn a_reset_line_holds_its_instance_only_while_its_bit_stands_and_puts_it_back_alone() {
        let mut bus =
            adjusted(|builder| builder.reset_by("PORT", Gate::by("CLOCKS", "ENR", "EN"))).unwrap();
        let clocks = bus.slot_of("CLOCKS").unwrap();
        let port = bus.slot_of("PORT").unwrap();
        assert!(bus.held_in_reset_by(clocks).is_empty(), "the bit is clear");
        assert!(
            bus.held_in_reset_by(port).is_empty(),
            "the held instance holds nothing"
        );
        bus.slot_mut(clocks).registers_mut().bus_write(0, 1);
        assert_eq!(bus.held_in_reset_by(clocks), [port]);

        bus.slot_mut(port).registers_mut().bus_write(0, 0xAB);
        bus.effects.events.schedule(VirtualNanos(10), port);
        bus.effects.events.schedule(VirtualNanos(20), clocks);
        bus.reset_slot(port);
        assert_eq!(
            bus.slots()[port].registers().get_row(0),
            0,
            "back to its reset value"
        );
        assert_eq!(
            bus.slots()[clocks].registers().get_row(0),
            1,
            "the other keeps its own"
        );
        assert_eq!(
            bus.pop_due(VirtualNanos(100))
                .map(|(_, slot, at)| (slot, at)),
            Some((clocks, VirtualNanos(20))),
            "only the reset instance's event is gone"
        );
        assert_eq!(bus.pop_due(VirtualNanos(100)), None);

        assert!(matches!(
            adjusted(|builder| builder.reset_by("PORT", Gate::by("CLOCKS", "ENR", "NOPE"))),
            Err(Error::UnknownField { field: "NOPE", .. })
        ));
        assert!(matches!(
            adjusted(|builder| builder.reset_by("NOWHERE", Gate::by("CLOCKS", "ENR", "EN"))),
            Err(Error::UnknownInstance {
                instance: "NOWHERE"
            })
        ));
    }

    #[test]
    fn locate_ungated_finds_what_locate_finds_and_skips_the_gate() {
        let mut bus = gated();
        let landing = |located: Result<Located, Fault>| {
            located.map(|located| (located.slot, located.row, located.lane.shift))
        };
        let status_high_half = (0x4000_1006, Width::W16);
        for kind in [AccessKind::Read, AccessKind::Write] {
            let (address, width) = status_high_half;
            assert!(
                matches!(bus.locate(address, width, kind), Err(Fault::Gated { .. })),
                "{kind:?}"
            );
            assert_eq!(
                landing(bus.locate_ungated(address, width, kind)),
                Ok((1, 1, 16))
            );
        }
        assert_eq!(
            landing(bus.locate_ungated(0x4000_1006, Width::W32, AccessKind::Read)),
            Err(Fault::Misaligned {
                address: 0x4000_1006,
                width: Width::W32
            })
        );
        assert_eq!(
            landing(bus.locate_ungated(0x4000_1008, Width::W32, AccessKind::Read)),
            Err(Fault::Unmapped {
                address: 0x4000_1008
            })
        );
        bus.slot_mut(0).registers_mut().bus_write(0, ENABLE.mask());
        let (address, width) = status_high_half;
        assert_eq!(
            landing(bus.locate(address, width, AccessKind::Read)),
            landing(bus.locate_ungated(address, width, AccessKind::Read)),
            "the gate open"
        );
    }

    /// A rebuilt bus keeps a board's region and window, the window in its slot, only when it's
    /// fresh from the same description as the bus they were added to.
    #[test]
    fn a_bus_keeps_what_was_added_only_fresh_from_the_same_description() {
        static ADDED: Region = Region::ram("added", 0x6000_0000, 0x1000);
        let window = Window::new("display", 0x6400_0000, NonZeroU64::new(0x100).unwrap());
        let mut board = gated();
        board.add_region(ADDED).unwrap();
        let slot = board.add_window(window).unwrap();
        let mut fresh = gated();
        assert_eq!(fresh.keep_added(&board), Ok(()));
        assert_eq!(fresh.memory().last(), Some(&ADDED));
        assert_eq!(fresh.slot_at(window.base), Some(slot));
        assert_eq!(
            fresh.keep_added(&board),
            Err(Error::OtherDescription),
            "no longer fresh"
        );
        let cpu = Cpu::new("core", false, 16, Endian::Little);
        let mut other = Bus::builder(cpu, &MEMORY, []).build().unwrap();
        assert_eq!(other.keep_added(&board), Err(Error::OtherDescription));
        assert_eq!(other.memory(), &MEMORY, "nothing copied");
    }

    /// Two spans overlap when they share an address, whichever is asked about the other, and a
    /// span of no bytes overlaps nothing, even at an address another span holds.
    #[test]
    fn spans_overlap_when_they_share_an_address_either_way_round() {
        let span = |base, size| Extent {
            name: "",
            base,
            size,
        };
        let pairs = [
            (span(0x100, 0x10), span(0x108, 0x10), true),
            (span(0x100, 0x10), span(0x110, 0x10), false),
            (span(0x100, 0x10), span(0x100, 0), false),
            (span(0x100, 0x10), span(0x108, 0), false),
            (span(0x100, 0), span(0x100, 0), false),
            (span(u64::MAX - 1, 8), span(u64::MAX - 1, 1), true),
        ];
        for (first, second, shared) in pairs {
            assert_eq!(first.overlaps(&second), shared, "{:#x}", second.base);
            assert_eq!(second.overlaps(&first), shared, "the other way round");
        }
        let named = |name, base, size| Extent { name, base, size };
        assert_eq!(
            first_overlap(
                [
                    named("long", 0x100, 0x100),
                    named("empty", 0x110, 0),
                    named("inside", 0x120, 0x10),
                ]
                .into_iter()
            ),
            Some(("long", "inside")),
            "an empty span between them hides nothing"
        );
    }
}