vj 0.2.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
//! Task S7 (`docs/superpowers/plans/2026-09-26-wave-A2-slice.md`; ledger
//! CG-125): `vj run <file.sv>` -- the end-to-end pipeline. Elaborate
//! -> STATE layout/instance -> discover processes -> CFG/liveness/segments
//! -> codegen -> JIT (via `vj_codegen::pipeline::CompiledPipeline::
//! get_process_fn`, CG-125's own API -- backed by the production
//! `orc::JitBackend` ORC v2 JIT as of Task 24's review fix r1, no longer
//! the legacy `jit::Jit`/`ExecutionEngine`) -> register with a real
//! `sched::Engine` -> run -> drain `$display` output.
//!
//! **Superseded scope deviation (Task S7 era):** an earlier version of this
//! module bypassed `netlist::elaborate` entirely and supported exactly one
//! top-level module with no sub-instances, on the grounds that Task S7's own
//! ledger id (CG-125) and its own single-module fixture didn't exercise
//! anything else. Task F3
//! (`docs/superpowers/plans/2026-09-27-wave-A2-slice-finish.md`; ledger
//! CG-125's hierarchy half, NL-035's runtime half) removes that narrowing:
//! `run_design` now calls the real `netlist::elaborate` and walks its
//! `registration_order()`, allocating one `StateEngine` instance (sharing one
//! `StateLayout` per distinct dedup `TemplateKey`, per S5's own dedup) and
//! discovering/lowering that instance's own processes against that
//! instance's own signal slots, for every elaborated instance in the design
//! -- not just its single top module. Each instance port connection is
//! realized as a synthetic continuous assignment (LRM 23.3.3): a small
//! native `CompiledProcess` ([`PortWireProcess`] below), registered with
//! static sensitivity on its source cell, that copies the source's value to
//! the destination through the canonical `commit_blocking_write` path
//! whenever the source changes -- giving the LRM's delta ordering (a
//! clocked child output reaches the parent one delta after its own NBA
//! commit) for free, since it goes through the exact same
//! `SchedulerOps`/`SensitivityTable` machinery every other process in this
//! pipeline does. **Deliberately still out of this task's scope (documented,
//! not silently smoothed over), each a named `LoweringError`, not a panic or
//! a silent drop:** a port connection whose parent-scope side is anything
//! other than a plain identifier (a binary expression, a part-select, a
//! constant); an unconnected port (LRM's implicit `Z` is not represented);
//! an `inout`/`ref`-direction port; and a connection whose two sides have
//! different bit widths (no implicit extension/truncation).
//!
//! **`SimHandle`-reachability wiring (the one genuinely new cross-cutting
//! decision this task makes, flagged as open by both
//! `vj-codegen::process_lower::declare_rt_finish`'s and
//! `vj-sim::sched::kernel_adapter`'s own doc comments):** the frozen
//! `ProcessFn` ABI carries no scheduler-ops parameter, and `SimHandle`
//! reaches only STATE, so a compiled kernel's `nba_enqueue`/`sv_rt_finish`
//! calls have no way to reach the real `SchedulerOps` this run's `Engine`
//! constructs internally per resume. This task closes that gap with the
//! minimal, additive hook `vj-sim::sched::kernel_adapter::
//! with_scheduler_ops`/`real_nba_enqueue`/`real_sv_rt_finish` add (a
//! thread-local, save-and-restored for exactly one raw kernel call's
//! duration) -- bound into this run's JIT module below via
//! `Jit::add_global_mapping`, the same binding mechanism every accessor-ABI
//! stub in this workspace's own tests already uses. `sv_rt_display`/
//! `sv_rt_write`'s real bodies (`vj_runtime::display_sink`) need no such
//! bridge: their own ABI shape carries no `SimHandle` at all (see that
//! module's own doc comment for why this run instead reads back a
//! thread-local output buffer after the engine finishes).
pub use crate::timing_options::{SdfMtm, TimingOptions};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::io::Write;
use std::path::Path;
use vj_sim::symid::SymbolUid;

use sv_lang::kinds::{ExpressionKind, SymbolKind};
use sv_lang::{ArgumentDirection, Expression, SemNode, Statement, Symbol};
use vj_sim::symid::SymbolId;

use vj_codegen::error::LoweringError;
use vj_codegen::module::{
    DiscoveredProcess, SliceProcKind, build_comb_sensitivity_index, discover_called_subroutines,
    discover_called_subroutines_inlined, discover_cont_assigns, discover_processes_dispatching,
    discover_variable_initializers,
};
use vj_codegen::pipeline::{
    ContAssignLoweringSpec, RealBindings, SubroutineLoweringSpec, build_pipeline,
};
use vj_codegen::process_lower::{
    SignalSlot, SignalSlotClass, build_lowering_plan, to_state_edge_kind,
};
use vj_codegen::select::{RefActualError, ref_actual_window};

use vj_runtime::display_sink::{real_sv_rt_display, real_sv_rt_write, take_output};
use vj_runtime::file_io_sink::{
    real_sv_rt_fclose, real_sv_rt_fdisplay, real_sv_rt_feof, real_sv_rt_fflush,
    real_sv_rt_fmonitor, real_sv_rt_fopen, real_sv_rt_fopen_mcd, real_sv_rt_fseek,
    real_sv_rt_fstrobe, real_sv_rt_fwrite, real_sv_rt_system, reset_mcd_table_for_new_run,
};
use vj_runtime::plusargs_sink::{
    real_sv_rt_plusargs_test, real_sv_rt_plusargs_value, set_plusargs_for_run,
};
use vj_runtime::random::{sv_rt_dist, sv_rt_random_reseed, sv_rt_urandom_reseed};
use vj_runtime::random_sink::{
    real_sv_rt_random, real_sv_rt_urandom, real_sv_rt_urandom_range, reset_seed_for_new_run,
};

use crate::primitives::loc_of;
pub use crate::sources::SourceSet;
use vj_abi::{SimHandle, SlotId};
use vj_sim::netlist::{self, ElabError, InstanceId, NetlistView, TemplateKey};
use vj_sim::process::cfg::{ProcessLoopKind, lower_to_segments};
use vj_sim::process::liveness::{FrameLayout, compute_liveness};
use vj_sim::sched::{
    CompiledKernelProcess, DeferredIoCallback, Engine, IoSink, ProcessKind, SchedTime,
    SchedulerControl, StaticSensitivity, real_nba_enqueue, real_sv_rt_disable_fork,
    real_sv_rt_finish, real_sv_rt_time, real_sv_set_mem_word, real_sv_set_scalar, real_sv_set_wide,
};
use vj_sim::state::{
    AliasWindow, EdgeKind as StateEdgeKind, FourStateValue, StateCellId, StateEngine,
    TemplateRegistry, build_template_layout, cell_for_slot, set_foreign_slots_windowed,
};

/// Every failure mode `run_design` can hit -- each a named variant with a
/// `Display` impl; `main` prints it to stderr and exits non-zero, never
/// panics.
#[derive(Debug)]
pub enum RunError {
    Compile(sv_lang::Error),
    /// The source has errors (slang's rendered diagnostics).
    Diagnostics(String),
    Lowering(LoweringError),
    Jit(String),
    Io(std::io::Error),
    /// Task 4 (A2-part2; ledger CG-127, RT-003): `vj build-aot`'s own
    /// failure mode, wrapping `vj_codegen::error::CodegenError`
    /// (object emission / linking / the post-link `dlsym` probe) --
    /// distinct from `RunError::Jit`, which is `run_design`'s own JIT-path
    /// error and shares nothing with the AOT backend.
    Codegen(vj_codegen::error::CodegenError),
    /// A `$sdf_annotate` call could not annotate at all (unreadable or malformed SDF file, a
    /// scope that names no instance, a malformed option; LRM 32.9). The run was finished at
    /// the failing call -- never carried on with stale delays -- and fails with this.
    SdfAnnotate(String),
    /// A VPI library could not be loaded (`vpi::loader`).
    Vpi(String),
    /// The scheduler's delta-loop guard tripped: a zero-delay loop that never
    /// lets time advance (SC-080/DT-050). A named runtime error, never a panic.
    Livelock(String),
    /// `vj build-aot` met a construct whose behaviour lives in the host
    /// process or in state the design image cannot serialize, so it refuses
    /// the design by name rather than building a `.so` that would run it
    /// differently from `vj run`.
    AotRefused {
        /// The construct family (`hierarchy`, `dpi`, `covergroup`, ...).
        feature: String,
        reason: String,
        /// `file:line` of the construct.
        at: String,
    },
}

impl fmt::Display for RunError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RunError::Compile(e) => write!(f, "compile error: {e}"),
            RunError::Diagnostics(text) => write!(f, "the design has errors:\n{text}"),
            RunError::Lowering(e) => write!(f, "lowering error: {e}"),
            RunError::Jit(msg) => write!(f, "JIT error: {msg}"),
            RunError::Io(e) => write!(f, "I/O error: {e}"),
            RunError::Codegen(e) => write!(f, "codegen error: {e}"),
            RunError::SdfAnnotate(msg) => write!(f, "$sdf_annotate failed: {msg}"),
            RunError::Vpi(msg) => write!(f, "VPI error: {msg}"),
            RunError::Livelock(msg) => write!(f, "simulation livelock: {msg}"),
            RunError::AotRefused {
                feature,
                reason,
                at,
            } => write!(f, "AOT-REFUSED({feature}): {reason} at {at}"),
        }
    }
}

impl std::error::Error for RunError {}

/// A no-op [`IoSink`]: this pipeline's `$display`/`$finish` delivery
/// (`vj_runtime::display_sink`, `SchedulerOps::request_finish`) never
/// routes through `defer_io`, but `Engine::new` still requires a real
/// `Box<dyn IoSink>` (STATE/SCHED's own dependency-injection contract) --
/// see this file's module doc comment for why `$display`'s real sink is
/// deliberately NOT this one.
struct NullIoSink;
impl IoSink for NullIoSink {
    fn enqueue(&self, _at: SchedTime, _region: vj_abi::Region, _seq: u64, _cb: DeferredIoCallback) {
    }
}

/// Converts `vj-sim::process::cfg`/`liveness`'s own (frontend-free, per
/// D4) `LoweringError` into this crate's `vj-codegen`-facing one --
/// distinct types (`vj-codegen::error::LoweringError` carries a
/// `hierarchical_path()`-derived `at`; the process-track's own type is a bare
/// message, since it must build with `--no-default-features`, i.e. with no
/// `sv_lang::Symbol` to cite), reconciled here at the one call site that
/// needs both rather than either type gaining a dependency on the other.
pub(crate) fn sim_lowering_to_run_error(
    e: vj_sim::process::cfg::LoweringError,
    path: &Path,
) -> RunError {
    RunError::Lowering(LoweringError::unsupported(
        &e.to_string(),
        path.display().to_string().as_str(),
    ))
}

/// Mirrors `vj-codegen::module::SliceProcKind` -> `vj-sim::sched::
/// ProcessKind` (a cross-crate mapping neither track's own file owns, so it
/// lives here, at the one call site that needs both).
fn scheduler_process_kind(kind: SliceProcKind) -> ProcessKind {
    match kind {
        SliceProcKind::Initial => ProcessKind::Initial,
        SliceProcKind::Always => ProcessKind::Always,
        SliceProcKind::AlwaysComb => ProcessKind::AlwaysComb,
        SliceProcKind::AlwaysLatch => ProcessKind::AlwaysLatch,
        SliceProcKind::AlwaysFF => ProcessKind::AlwaysFF,
        SliceProcKind::Final => ProcessKind::Final,
        // Never registered with the scheduler (`vj_exec::verif` runs its
        // action blocks from region callbacks); a one-shot like `Initial`.
        SliceProcKind::StaticAssertion => ProcessKind::Initial,
    }
}

/// `Initial`/`AlwaysComb`/`AlwaysLatch`/`Final` -> a one-shot CFG (no
/// loop-back: none of these has a head timing control to loop back to --
/// `AlwaysComb`/`AlwaysLatch` are re-triggered externally, by the static
/// sensitivity `register_process` installs for them below, never by an
/// internal loop); `Always`/`AlwaysFF` -> a looping one
/// (`process::cfg::ProcessLoopKind`'s own doc comment: "a caller that
/// already has a `SliceProcKind` ... maps it down to this coarser 2-value
/// distinction itself").
pub(crate) fn loop_kind_of(kind: SliceProcKind) -> ProcessLoopKind {
    match kind {
        SliceProcKind::Initial
        | SliceProcKind::AlwaysComb
        | SliceProcKind::AlwaysLatch
        | SliceProcKind::Final
        | SliceProcKind::StaticAssertion => ProcessLoopKind::OneShot,
        SliceProcKind::Always | SliceProcKind::AlwaysFF => ProcessLoopKind::Looping,
    }
}

/// The [`StaticSensitivity`] data `discover_processes` computed for one
/// process, threaded from the discovery loop (which has the live
/// `Symbol<'d>`s to convert an `AlwaysFF` reset's `sv_lang::EdgeKind` via
/// [`to_state_edge_kind`] while they're still in scope) through to the
/// final registration loop (which has the `SimHandle`/signal-slot map a
/// `SymbolId` needs to resolve into a real [`StateCellId`]). Empty
/// `read_set` and `reset: None` for `Initial`/`Always`/`AlwaysFF`-without-
/// reset/`Final` -- `register_process` keeps getting `None` for those,
/// unchanged from before this task.
#[derive(Debug, Clone, Default)]
/// What a `disable` can name in a process (16.14.6.4), see `run_design`.
struct DisableScope {
    /// The process's index among the instance's discovered processes.
    process: usize,
    /// Its outermost named block.
    block: Option<vj_sim::process::cfg::PeerBlock>,
    /// Its other named blocks, which another process's `disable` may name too
    /// (LRM 9.6.2).
    nested: Vec<vj_sim::process::cfg::PeerBlock>,
    /// The dotted path of every named block of the process
    /// (`vj_sim::process::cfg::named_block_paths`).
    paths: Vec<String>,
    /// The plan indices of the procedural assertions queued from it.
    keys: Vec<usize>,
    /// The labels of those assertions, with their plan index.
    labels: Vec<(String, usize)>,
}

struct KernelSensitivitySpec {
    /// `AlwaysComb`/`AlwaysLatch` only: the whole-procedure read set
    /// (CG-079), each entry becoming a `(cell, None)` "any change" edge.
    read_set: Vec<SymbolId>,
    /// The constant bit windows of the `read_set` symbols the body reads only
    /// through constant selects (LRM 9.2.2.2.1); empty for every other kind.
    windows: HashMap<SymbolId, Vec<(u32, u32)>>,
    /// `AlwaysFF` with an async reset only (CG-079's other half): the
    /// reset signal and its already-converted `vj_sim::state::EdgeKind`.
    reset: Option<(SymbolId, StateEdgeKind)>,
}

/// Per-cell constant read windows `(lo, hi)` of an `always_comb` (LRM 9.2.2.2.1).
type ReadWindows = Vec<(StateCellId, Vec<(u32, u32)>)>;

/// Builds the real [`StaticSensitivity`] `register_process` needs for one
/// kernel from its [`KernelSensitivitySpec`], resolving each `SymbolId`
/// through `signals` (that instance's own `SymbolId -> SignalSlot` map,
/// exactly as [`register_port_wire`] above already resolves a port's own
/// slot) into a real [`StateCellId`] via `cell_for_slot` -- the same
/// resolution path every other cell reference in this pipeline goes
/// through, never a second, hand-rolled one. Returns `None` when `spec` is
/// empty (every kind but `AlwaysComb`/`AlwaysLatch`/a reset-bearing
/// `AlwaysFF`), preserving today's behavior for those kinds exactly.
fn build_static_sensitivity(
    spec: &KernelSensitivitySpec,
    signals: &HashMap<SymbolId, SignalSlot>,
    sim_handle: SimHandle,
    path: &Path,
) -> Result<Option<(StaticSensitivity, ReadWindows)>, RunError> {
    let resolve = |id: &SymbolId| -> Result<StateCellId, RunError> {
        let slot = *signals.get(id).ok_or_else(|| {
            RunError::Lowering(LoweringError::unsupported(
                &format!(
                    "static-sensitivity entry `{id}` has no resolved signal slot in its own \
                     module"
                ),
                path.display().to_string().as_str(),
            ))
        })?;
        Ok(cell_for_slot(sim_handle, SlotId(slot.slot)))
    };

    let mut edges = Vec::with_capacity(spec.read_set.len() + usize::from(spec.reset.is_some()));
    for id in &spec.read_set {
        edges.push((resolve(id)?, None));
    }
    if let Some((id, edge)) = &spec.reset {
        edges.push((resolve(id)?, Some(*edge)));
    }
    let narrowed = spec
        .read_set
        .iter()
        .filter_map(|id| Some((id, spec.windows.get(id)?)))
        .map(|(id, w)| Ok((resolve(id)?, w.clone())))
        .collect::<Result<Vec<_>, RunError>>()?;
    if edges.is_empty() {
        Ok(None)
    } else {
        Ok(Some((StaticSensitivity { edges }, narrowed)))
    }
}

/// The `frame_word_count` [`CompiledKernelProcess::new`] needs to size its
/// owned frame buffer.
fn total_frame_words(frame: &FrameLayout) -> u32 {
    frame.total_words()
}

/// Builds the `(SymbolId -> SignalSlot)` map every process's
/// `ProcessLoweringPlan` needs to resolve an external (module-level) signal
/// reference to its accessor-ABI `SlotId`/width/signedness.
///
/// **Documented duplication (the same tension `vj-codegen::module`'s own
/// doc comment names for `netlist::template.rs`):** this walk must assign
/// slot indices in EXACTLY the same order `state::layout::
/// build_template_layout` does (its own filter: `Variable`/`Net`/`Port`
/// members only, skipping a `Port` with an internal symbol and skipping a
/// null port) -- there is no existing API that hands back a per-symbol slot
/// index alongside a built `StateLayout`, so this function mirrors that
/// filter by hand rather than inventing a shared helper mid-task (which
/// would mean touching `state::layout.rs`, a file this task's own Files list
/// does not name). A future wave reconciling this belongs to whichever track
/// owns `state::layout.rs`.
///
/// R-run Task 13 (ST-009/AB-050/CG-163/ST-024/ST-114): a member's
/// `SignalSlot` now also carries its [`SignalSlotClass`] -- `Inline`
/// (`width <= 64`), `Wide` (`64 < width <= 128`, codegen's own
/// `WIDE_THRESHOLD`), or `Memory { num_rows }` for a fixed-size unpacked
/// array. A `Memory` member's `width` is the per-ROW element's bit width,
/// never the bare `ty.bit_width()` of the unpacked-array `Type` itself
/// (which is `0` -- a non-integral shape -- and was the historical
/// `accessor.rs:207` `debug_assert!` panic trigger this task fixes): the
/// `is_unpacked_array()`/`element_type()`/`fixed_unpacked_array_range()`
/// derivation below deliberately mirrors `vj_sim::state::layout::
/// build_template_layout`'s own `SlotClass::Memory` branch exactly (same
/// predicate order, same `is_integral()` row-element gate), so this map's
/// slot shapes never disagree with the real `StateLayout` a `Memory`-class
/// accessor call is resolved against.
pub(crate) fn signal_slots_of<'d>(
    body: &Symbol<'d>,
) -> Result<HashMap<SymbolId, SignalSlot>, RunError> {
    vj_codegen::module::signal_slots_of(body).map_err(RunError::Lowering)
}

/// Diagnostics slang downgrades to warnings although the LRM makes them
/// errors (each cited at its `CODES` row): a name declared twice in one scope
/// (23.2 `Redefinition`, 6.5 "redeclare"), a variable with more than one
/// continuous assignment (6.5 `MultipleContAssigns`) and a variable written
/// both continuously and procedurally (6.5 `MixedVarAssigns`). The last two
/// come from slang's driver analysis, which runs only when this finds nothing
/// earlier; of its errors only the `uwire` one is promoted (the others have
/// their own, better-worded checks later): a `uwire` with two drivers, 6.6.2.
/// A source buffer that declares a `checker` is exempt from the driver
/// diagnostics: slang models a checker's output arguments as continuous
/// assignments, so a checker instantiated in a procedural loop reads as
/// several continuous drivers of one variable (17.3), which is legal.
/// Returns the rendered text of the offenders (as `error:` lines), or `None`.
fn lrm_errors_slang_only_warns(design: &sv_lang::Design) -> Option<String> {
    const CODES: [&str; 9] = [
        "Redefinition",
        "MultipleContAssigns",
        "MixedVarAssigns",
        // 3.13 a: one definition per name in the definitions name space.
        "DuplicateDefinition",
        // 23.10.2.2: a by-name override names a parameter of the instantiated module.
        "ParameterDoesNotExist",
        // 11.4.12: unsized constant numbers are not allowed in concatenations.
        "UnsizedInConcat",
        // 5.7.1: a digit sequence does not start with an underscore.
        "DigitsLeadingUnderscore",
        // 23.2.2.1: a non-ANSI port redeclared with a different data type.
        "RedefinitionDifferentType",
        // 11.5.1: a select applies to a vector or an array, a scalar has no bits to select.
        "CannotIndexScalar",
    ];
    let render = |items: &[sv_lang::Diagnostic], analysis: bool| -> Vec<String> {
        items
            .iter()
            .filter(|d| {
                CODES.contains(&d.code_name())
                    || (analysis && d.is_error() && d.message.contains("'uwire'"))
            })
            .filter(|d| d.source.as_deref().is_none_or(|s| !s.contains("checker")))
            .filter(|d| !is_block_label_redefinition(d) || generate_label_conflict(design, d))
            .filter(|d| !is_constraint_redefinition(d))
            .map(|d| format!("{}:{}:{}: error: {}", d.file, d.line, d.column, d.message))
            .collect()
    };
    let mut found = render(design.diagnostics().items(), false);
    if found.is_empty()
        && let Ok(analysis) = design.analyze(sv_lang::AnalysisFlags::NONE, 1)
    {
        found = render(analysis.diagnostics().items(), true);
    }
    (!found.is_empty()).then(|| found.join("\n") + "\n")
}

/// True when the `Redefinition` of a `begin : name` label (see
/// [`is_block_label_redefinition`]) clashes with a *generate* block of that
/// name in the same design element. 23.9: an identifier declares one item in
/// a scope, "for generate blocks ... regardless of whether the generate block
/// is instantiated", so a generate block named like a variable, a procedural
/// block or another generate block is an error even though two procedural
/// blocks sharing a label (accepted by every tool) are not. The diagnostic
/// does not say what the other declaration is, so this reads the syntax: some
/// `GenerateBlock` of that label sits in the module, interface or program
/// that holds the diagnostic.
fn generate_label_conflict(design: &sv_lang::Design, d: &sv_lang::Diagnostic) -> bool {
    use sv_lang::kinds::SyntaxKind;
    let (Some(src), Some(name)) = (d.source.as_deref(), d.message.split('\'').nth(1)) else {
        return false;
    };
    let label_of = |block: &sv_lang::Node<'_>| -> Option<String> {
        block
            .children()
            .find(|c| c.kind() == SyntaxKind::NamedBlockClause)
            .map(|c| c.text().trim().trim_start_matches(':').trim().to_owned())
    };
    design.syntax_trees().iter().any(|tree| {
        // The tree's text can differ from the buffer by a trailing newline.
        let text = tree.text();
        if !(src.starts_with(text.as_str()) || text.starts_with(&*src)) {
            return false;
        }
        let nodes: Vec<_> = tree.root().descendants().collect();
        let holder = nodes
            .iter()
            .filter(|n| {
                matches!(
                    n.kind(),
                    SyntaxKind::ModuleDeclaration
                        | SyntaxKind::InterfaceDeclaration
                        | SyntaxKind::ProgramDeclaration
                ) && n.byte_range().contains(&d.byte_offset)
            })
            .min_by_key(|n| n.byte_range().len());
        let Some(holder) = holder else {
            return false;
        };
        let range = holder.byte_range();
        nodes.iter().any(|n| {
            n.kind() == SyntaxKind::GenerateBlock
                && range.contains(&n.byte_range().start)
                && label_of(n).as_deref() == Some(name)
        })
    })
}

/// True for a `Redefinition` on a `constraint` declaration line: those are
/// reported by name, with their LRM 18.5.1 reason, by the constraint checks
/// (`constraint_decls`, the class constraint-block collection) instead.
fn is_constraint_redefinition(d: &sv_lang::Diagnostic) -> bool {
    d.code_name() == "Redefinition"
        && d.source.as_deref().is_some_and(|s| {
            s.get(..d.byte_offset).is_some_and(|before| {
                before
                    .rsplit('\n')
                    .next()
                    .is_some_and(|line| line.contains("constraint"))
            })
        })
}

/// True for a `Redefinition` of a `begin : name` / `fork : name` label.
/// Same-named blocks in separate processes are common and slang (and every
/// other tool) accepts them, so they stay warnings; a declaration's name is
/// never directly preceded by a colon.
fn is_block_label_redefinition(d: &sv_lang::Diagnostic) -> bool {
    d.code_name() == "Redefinition"
        && d.source.as_deref().is_some_and(|s| {
            s.get(..d.byte_offset)
                .is_some_and(|before| before.trim_end().ends_with(':'))
        })
}

/// The system task and function names slang reported as unknown
/// (`UnknownSystemName`), each once, in order.
fn unknown_system_names(design: &sv_lang::Design) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    for d in design.diagnostics().items() {
        if d.code_name() != "UnknownSystemName" {
            continue;
        }
        let name = d
            .message
            .split('\'')
            .nth(1)
            .map_or_else(|| d.message.clone(), str::to_owned);
        if !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// Converts one elaboration failure into this crate's own `RunError`
/// (mirrors [`sim_lowering_to_run_error`]'s reconciliation for the
/// process-track's own `LoweringError` -- `netlist::ElabError` is a third,
/// distinct error type, so it gets the same one-call-site treatment).
pub(crate) fn elab_to_run_error(e: ElabError, path: &Path) -> RunError {
    RunError::Lowering(LoweringError::unsupported(
        &e.to_string(),
        path.display().to_string().as_str(),
    ))
}

/// `netlist.instance_symbol(id).instance_body()`, with the same
/// `LoweringError`-on-`None` discipline every other fallible `Symbol`
/// accessor in this module already applies -- factored out since Task F3's
/// hierarchy walk below needs it at several call sites, never duplicating
/// the error-construction inline.
pub(crate) fn instance_body_of<'d>(
    nl: &netlist::Netlist<'d>,
    id: InstanceId,
    path: &Path,
) -> Result<Symbol<'d>, RunError> {
    nl.instance_symbol(id).instance_body().ok_or_else(|| {
        RunError::Lowering(LoweringError::unsupported(
            "instance has no instance_body()",
            path.display().to_string().as_str(),
        ))
    })
}

/// The variable or net a value name refers to: a modport port (`b.data`
/// through a `bus_if.dst b` port) names the interface instance's own
/// member; anything else that is not a variable or net (a parameter, an
/// enum value, ...) is `None`.
fn value_target<'d>(sym: Symbol<'d>) -> Option<Symbol<'d>> {
    let sym = if sym.kind() == SymbolKind::ModportPort {
        sym.modport_port_internal_symbol()?
    } else {
        sym
    };
    // A clocking block (its event counter) or clock variable (its sample)
    // reached through a virtual interface has its own slot too.
    // A static task's formal argument is a state slot of its instance, like
    // its static locals: another instance calling the task (through an
    // interface) binds and reads it there.
    (matches!(
        sym.kind(),
        SymbolKind::Net | SymbolKind::Variable | SymbolKind::ClockVar | SymbolKind::ClockingBlock
    ) || (sym.kind() == SymbolKind::FormalArgument
        && vj_sim::netlist::is_static_procedural_var(&sym)))
    .then_some(sym)
}

/// For an output clock variable `cv` with an edge output skew (its own, or
/// its clocking block's default): the symbol of its clocking event's signal.
fn edge_skew_clock<'d>(cv: &Symbol<'d>) -> Option<Symbol<'d>> {
    let cb = cv.parent()?;
    let mut skew = cv.clock_var_output_skew();
    if !skew.has_value() {
        skew = cb.clocking_block_default_output_skew();
    }
    if matches!(skew.edge, sv_lang::EdgeKind::None) {
        return None;
    }
    let ev = cb.clocking_block_event()?.as_timing_control()?;
    vj_sim::sva::sampled::clock_event_of(ev)
        .ok()?
        .signal
        .referenced_symbol()
}

/// Every symbol a value name (`x`, `b.valid`, `top.u.r`) anywhere under
/// `roots` refers to -- and, transitively, under the bodies of the user
/// subroutines they call (an interface task's body reads and writes its
/// interface's variables) -- first appearance first.
pub(crate) fn referenced_values<'d>(roots: Vec<SemNode<'d>>) -> Vec<Symbol<'d>> {
    let mut out = Vec::new();
    let mut seen = HashSet::new();
    let mut called = HashSet::new();
    let mut stack = roots;
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression() {
            if vj_sim::symid::is_value_name(e.kind())
                && let Some(sym) = e.referenced_symbol()
                && seen.insert(sym.uid())
            {
                // A clock variable named through an interface port
                // (`port.cb.q <= v`, LRM 14.16 / 25.5.5) drives the signal of
                // another instance, which this process must also carry.
                if sym.kind() == SymbolKind::ClockVar {
                    let driven = sym.initializer().and_then(|i| i.referenced_symbol());
                    let clock = edge_skew_clock(&sym);
                    // Its clocking block's event counter: a `##N` cycle
                    // delay in an intra-assignment drive (`b.cb.q <= ##1 v`,
                    // LRM 14.11, 25.9.1) counts that block's events.
                    let block = sym
                        .parent()
                        .filter(|p| p.kind() == SymbolKind::ClockingBlock);
                    for s in driven.into_iter().chain(clock).chain(block) {
                        if seen.insert(s.uid()) {
                            out.push(s);
                        }
                    }
                }
                // A modport port with an expression (`.x(r[3:0])`, LRM 25.5.4)
                // reads and writes the interface signals that expression names.
                if sym.kind() == SymbolKind::ModportPort
                    && let Some(x) = sym.modport_port_explicit_connection()
                {
                    stack.push(x.as_sem_node());
                }
                out.push(sym);
            }
            // Another instance's clocking block named in an event control
            // (`@(bus.cb)`).
            if e.kind() == ExpressionKind::ArbitrarySymbol
                && let Some(sym) = e.referenced_symbol()
                && matches!(sym.kind(), SymbolKind::ClockingBlock | SymbolKind::ClockVar)
                && seen.insert(sym.uid())
            {
                out.push(sym);
            }
            // `vif.m`: every candidate instance's `m` (see
            // `vj_codegen::vif`).
            for sym in vj_sim::netlist::vif::member_targets(&e)
                .into_iter()
                .flatten()
                .flatten()
            {
                // A clock variable also names the signal it drives.
                let driven = (sym.kind() == SymbolKind::ClockVar)
                    .then(|| sym.initializer().and_then(|i| i.referenced_symbol()))
                    .flatten();
                // An edge output skew (`output negedge q`, LRM 14.4) drives
                // at an edge of the clocking event's signal, which the
                // process then waits on.
                let clock = (sym.kind() == SymbolKind::ClockVar)
                    .then(|| edge_skew_clock(&sym))
                    .flatten();
                // Its clocking block's event counter: `##N` in a drive
                // through the virtual interface, or a drive without skew
                // that matures at the next clocking event (LRM 14.16, 25.9.1).
                let block = (sym.kind() == SymbolKind::ClockVar)
                    .then(|| {
                        sym.parent()
                            .filter(|p| p.kind() == SymbolKind::ClockingBlock)
                    })
                    .flatten();
                for s in std::iter::once(sym).chain(driven).chain(clock).chain(block) {
                    if seen.insert(s.uid()) {
                        out.push(s);
                    }
                }
            }
            if e.kind() == ExpressionKind::Call && e.is_system_call() != Some(true) {
                // The callee itself, for `foreign_references` to find a call
                // into another instance (LRM 23.6).
                if let Some(callee) = e.call_subroutine()
                    && seen.insert(callee.uid())
                {
                    out.push(callee);
                }
                // Through a virtual interface: every candidate instance's
                // own subroutine (see `vj_codegen::vif`).
                let callees: Vec<Symbol<'d>> = match vj_sim::netlist::vif::call_targets(&e) {
                    Some((_, targets)) => targets.into_iter().flatten().collect(),
                    // An interface `extern` method: every module-side
                    // implementation (LRM 25.7).
                    None => vj_sim::netlist::itf::call_callees(&e),
                };
                for callee in callees {
                    if called.insert(callee.uid())
                        && let Some(body) = vj_sim::process::cfg::proc_body(&callee)
                    {
                        stack.push(body.as_sem_node());
                        // The call binds every static formal and local,
                        // whether or not the body names it.
                        for m in callee.members() {
                            if matches!(m.kind(), SymbolKind::FormalArgument | SymbolKind::Variable)
                                && seen.insert(m.uid())
                            {
                                // A local's initializer (`int x = f();`) runs
                                // with the call and can reach more state.
                                stack.extend(m.initializer().map(|i| i.as_sem_node()));
                                out.push(m);
                            }
                        }
                    }
                }
            }
        }
        stack.extend(vj_sim::process::cfg::live_children(&n));
    }
    out
}

/// Whether the code in `roots` (and the plain subroutines it calls) creates a
/// class object (`new`, LRM 8.7) or calls a class method. Constructors and
/// virtual methods run overrides and callees the static walk of
/// [`referenced_values`] cannot follow, so such code may reach any package
/// variable (UVM: `uvm_sequence`'s constructor reads `build_ph`).
fn reaches_class_code(roots: Vec<SemNode<'_>>) -> bool {
    let mut called = HashSet::new();
    let mut stack = roots;
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression() {
            if e.kind() == ExpressionKind::NewClass {
                return true;
            }
            if e.kind() == ExpressionKind::Call
                && e.is_system_call() != Some(true)
                && let Some(callee) = e.call_subroutine()
            {
                if callee
                    .parent()
                    .is_some_and(|p| p.kind() == SymbolKind::ClassType)
                {
                    return true;
                }
                if called.insert(callee.uid())
                    && let Some(body) = vj_sim::process::cfg::proc_body(&callee)
                {
                    stack.push(body.as_sem_node());
                }
            }
        }
        stack.extend(vj_sim::process::cfg::live_children(&n));
    }
    false
}

/// The package whose state holds the static local or formal `var` of a
/// package subroutine (LRM 6.21), if it is one.
fn package_of_static<'d>(var: &Symbol<'d>) -> Option<Symbol<'d>> {
    if !vj_sim::netlist::is_static_procedural_var(var) {
        return None;
    }
    let mut cur = var.parent();
    while let Some(p) = cur {
        if matches!(p.kind(), SymbolKind::Package | SymbolKind::CompilationUnit) {
            return Some(p);
        }
        cur = p.parent();
    }
    None
}

/// A signal of another instance reached from this one: the symbol the code
/// names it by, the variable/net itself, its instance, and its slot there.
/// A `ref` port bound to a select of a variable also names the window of the
/// target's storage (`AliasWindow`) the signal is.
type ForeignRef<'d> = (
    Symbol<'d>,
    Symbol<'d>,
    InstanceId,
    SignalSlot,
    Option<AliasWindow>,
);

/// The signals of OTHER instances that `body`'s processes, continuous
/// assigns and variable/net initializers reach -- an interface member
/// through an interface port or modport, an interface task's variables, a
/// hierarchical reference, a package variable -- as `(referenced symbol, target instance,
/// target's own slot)`. Signals of `own` itself, locals, and constants are
/// not included.
fn foreign_references<'d>(
    body: &Symbol<'d>,
    own: InstanceId,
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    body_id_to_instance: &HashMap<SymbolId, InstanceId>,
    ref_aliases: &RefAliases,
    trees: &[sv_lang::SyntaxTree],
) -> (Vec<ForeignRef<'d>>, bool) {
    let mut roots = Vec::new();
    roots.extend(crate::clocking::enclosing_global_clock_for_assertions(
        body, trees,
    ));
    for m in vj_sim::netlist::module_items(body) {
        let kind = m.kind();
        if kind == SymbolKind::ProceduralBlock {
            roots.extend(vj_sim::process::cfg::proc_body(&m).map(|b| b.as_sem_node()));
            // `@$global_clock` with the global clocking in an enclosing
            // instance (LRM 14.14): its event signals are foreign here.
            roots.extend(crate::clocking::enclosing_global_clock_event(&m, trees));
        } else if kind == SymbolKind::ContinuousAssign {
            roots.extend(m.continuous_assign_assignment().map(|e| e.as_sem_node()));
        } else if matches!(kind, SymbolKind::Net | SymbolKind::Variable) {
            roots.extend(m.initializer().map(|e| e.as_sem_node()));
        }
    }
    let class_code = reaches_class_code(roots.clone());
    let mut syms = referenced_values(roots);
    // LRM 16.15: a nested module declaration inherits the `default disable iff`
    // of the module it is declared in, whose signals are then foreign to this
    // instance (own-instance signals drop out below).
    if let Some(tree) = trees.iter().find(|t| body.syntax(t).is_some()) {
        syms.extend(vj_codegen::assertion::default_disable_signals(body, tree));
    }
    let refs = foreign_references_of_symbols(
        syms,
        own,
        instance_signals,
        body_id_to_instance,
        ref_aliases,
    );
    (refs, class_code)
}

/// The signals of OTHER state instances that the expressions `roots` read
/// or write, as for [`foreign_references`]. Split out so a package's variable
/// initializers (which are not an instance body's items) share it.
fn foreign_references_of_roots<'d>(
    roots: Vec<SemNode<'d>>,
    own: InstanceId,
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    body_id_to_instance: &HashMap<SymbolId, InstanceId>,
    ref_aliases: &RefAliases,
) -> Vec<ForeignRef<'d>> {
    foreign_references_of_symbols(
        referenced_values(roots),
        own,
        instance_signals,
        body_id_to_instance,
        ref_aliases,
    )
}

/// [`foreign_references_of_roots`] over the already-collected `syms`
/// ([`referenced_values`]'s output).
fn foreign_references_of_symbols<'d>(
    syms: Vec<Symbol<'d>>,
    own: InstanceId,
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    body_id_to_instance: &HashMap<SymbolId, InstanceId>,
    ref_aliases: &RefAliases,
) -> Vec<ForeignRef<'d>> {
    let mut out = Vec::new();
    for sym in syms {
        // A hierarchical call into another instance (LRM 23.6) whose
        // subroutine needs its instance's handle: the caller gets a foreign
        // slot onto any one signal of that instance, registered under the
        // callee's symbol, from which codegen derives the callee's handle
        // (`sv_rt_slot_owner`). It is typed as a one-row memory so it reaches
        // `LowerCtx::mem_signals`; nothing ever reads or writes it.
        if sym.kind() == SymbolKind::Subroutine {
            // A package subroutine that forces/assigns a package variable runs
            // in the package's own state (LRM 10.6): the same registration,
            // with the package's state instance as the owner.
            let scope = vj_sim::netlist::enclosing_instance_body(&sym).or_else(|| {
                vj_codegen::func::subroutine_forces(&sym)
                    .then(|| vj_sim::netlist::enclosing_package(&sym))
                    .flatten()
            });
            if let Some(owner) = scope.and_then(|b| body_id_to_instance.get(&b.uid()).copied())
                && owner != own
                && vj_codegen::func::subroutine_needs_handle(&sym)
                && let Some(&slot) = instance_signals[&owner]
                    .values()
                    .filter(|s| !matches!(s.class, SignalSlotClass::Memory { .. }))
                    .min_by_key(|s| s.slot)
            {
                let slot = SignalSlot {
                    class: SignalSlotClass::Memory {
                        num_rows: 1,
                        lower_index: 0,
                    },
                    ..slot
                };
                out.push((sym, sym, owner, slot, None));
            }
            continue;
        }
        let Some(target) = value_target(sym) else {
            continue;
        };
        // A package variable's owner is its package's own state instance.
        let Some(owner) = target
            .parent()
            .and_then(|scope| {
                if matches!(
                    scope.kind(),
                    SymbolKind::Package | SymbolKind::CompilationUnit
                ) {
                    Some(scope)
                } else {
                    scope
                        .containing_instance()
                        .or_else(|| package_of_static(&target))
                }
            })
            .and_then(|b| body_id_to_instance.get(&b.uid()).copied())
        else {
            continue;
        };
        // A `ref` port variable is its actual: whoever names it (the child
        // by its own name, the parent as `u.r`) reaches the actual's cell.
        if let Some(&(storage_owner, slot, window)) = ref_aliases.get(&(owner, target.uid())) {
            out.push((sym, target, storage_owner, slot, window));
            continue;
        }
        if owner == own {
            // A modport port naming this instance's own variable (the
            // interface's process calling an exported task that reaches it
            // through `a.targets`): the port is one more name for the cell.
            if sym.kind() == SymbolKind::ModportPort
                && let Some(&slot) = instance_signals[&owner].get(&target.uid())
            {
                out.push((sym, target, owner, slot, None));
            }
            continue;
        }
        if let Some(&slot) = instance_signals[&owner].get(&target.uid()) {
            out.push((sym, target, owner, slot, None));
        }
    }
    out
}

/// The storage every `ref` port variable aliases (LRM 1800-2023 23.3.3.2):
/// `(instance, port variable)` to the instance and slot of the variable it is
/// ultimately connected to, found through any chain of `ref` ports.
///
/// A `ref` port bound to a select of a variable additionally carries the
/// [`AliasWindow`] of the target's storage it names; its slot then has the
/// port's own shape (width, signedness, class) over the target's slot number.
type RefAliases = HashMap<(InstanceId, SymbolId), (InstanceId, SignalSlot, Option<AliasWindow>)>;

/// Resolves every `ref` port of every instance to the cell it shares, through
/// any chain of `ref` ports (an actual may itself be a `ref` port, whatever
/// the instances' registration order). Must run on `instance_signals` as built
/// by `signal_slots_of`, before any foreign slot is added: an actual then still
/// names its own instance's slot.
fn ref_port_aliases<'d>(
    elaborated: &netlist::Netlist<'d>,
    registration_order: &[InstanceId],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    body_id_to_instance: &HashMap<SymbolId, InstanceId>,
) -> Result<RefAliases, RunError> {
    type Pending<'d> =
        HashMap<(InstanceId, SymbolId), (InstanceId, SymbolId, Symbol<'d>, Option<AliasWindow>)>;
    let mut pending: Pending<'d> = HashMap::new();
    for &id in registration_order {
        let child = elaborated.instance_symbol(id);
        for conn in child.instance_port_connections() {
            let port = conn.port();
            if port.kind() == SymbolKind::InterfacePort
                || port.port_direction() != ArgumentDirection::Ref
            {
                continue;
            }
            let member = port.port_internal_symbol().unwrap_or(port);
            let unsupported = |why: &str| {
                RunError::Lowering(LoweringError::unsupported_at(
                    &format!("ref port `{}`: {why}", port.hierarchical_path()),
                    &port,
                ))
            };
            // 23.3.3.2: "This kind of port cannot be left unconnected."
            let expr = conn
                .expression()
                .ok_or_else(|| unsupported("a ref port is connected to no variable (23.3.3.2)"))?;
            // A select actual (an element of an unpacked array, a member of
            // an unpacked struct) is a window of the variable's storage.
            let (root_expr, window) = ref_actual_window(expr).map_err(|e| match e {
                RefActualError::NonConstant => unsupported(
                    "the actual indexes an unpacked array with a non-constant expression; \
                     a ref port is bound once, at elaboration, so a select actual must \
                     name one fixed element. IEEE 1800-2023 23.3.3.2 says only that \
                     references to a ref port are hierarchical references to the connected \
                     variable, and 13.5.2 (pass by reference, which fixes the element when \
                     the call starts) covers subroutine arguments, not ports; the LRM \
                     does not say when the index is evaluated for a port (once at \
                     elaboration, or at every use as a moving alias), so no clause makes \
                     it unambiguous",
                ),
                RefActualError::Packed => unsupported(
                    "the actual is a select of a packed value; a ref actual must be a \
                     variable or a member/element of an unpacked struct or array \
                     (IEEE 1800-2023 13.5.2, 23.3.3.2)",
                ),
                RefActualError::Unsupported(why) => unsupported(&format!(
                    "the actual is {why}; not implemented for a ref port (IEEE 1800-2023 \
                     23.3.3.2)"
                )),
            })?;
            let window = window
                .map(|w| {
                    let (Ok(lo), Ok(width)) = (u32::try_from(w.lo), u32::try_from(w.width)) else {
                        return Err(unsupported("the selected window is too wide"));
                    };
                    Ok(AliasWindow {
                        row: w.row,
                        lo,
                        width,
                    })
                })
                .transpose()?;
            let actual = root_expr
                .referenced_symbol()
                .and_then(value_target)
                .ok_or_else(|| unsupported("the actual is not a variable"))?;
            let owner = actual
                .parent()
                .and_then(|scope| {
                    if matches!(
                        scope.kind(),
                        SymbolKind::Package | SymbolKind::CompilationUnit
                    ) {
                        Some(scope)
                    } else {
                        scope.containing_instance()
                    }
                })
                .and_then(|b| body_id_to_instance.get(&b.uid()).copied())
                .ok_or_else(|| unsupported("the actual's storage is not in an instance"))?;
            pending.insert((id, member.uid()), (owner, actual.uid(), port, window));
        }
    }
    // An actual may itself be a `ref` port (of the parent, or of a sibling
    // named hierarchically): follow the chain to the storage that is not.
    let mut aliases = RefAliases::new();
    for (key, (first_owner, first_actual, port, first_window)) in &pending {
        let (mut owner, mut actual) = (*first_owner, first_actual.clone());
        let mut window = *first_window;
        let mut hops = 0usize;
        while let Some((next_owner, next_actual, _, base)) = pending.get(&(owner, actual.clone())) {
            (owner, actual) = (*next_owner, next_actual.clone());
            // `window` selects within the port just followed, which is itself
            // the window `base` of the next target.
            window = match (*base, window) {
                (None, w) => w,
                (b, None) => b,
                (Some(b), Some(w)) if w.row.is_none() => Some(AliasWindow {
                    row: b.row,
                    lo: b.lo + w.lo,
                    width: w.width,
                }),
                (Some(_), Some(_)) => {
                    return Err(RunError::Lowering(LoweringError::unsupported_at(
                        &format!(
                            "ref port `{}`: an element of an array reached through another \
                             windowed ref port (IEEE 1800-2023 23.3.3.2)",
                            port.hierarchical_path()
                        ),
                        port,
                    )));
                }
            };
            hops += 1;
            if hops > pending.len() {
                return Err(RunError::Lowering(LoweringError::unsupported_at(
                    &format!(
                        "ref port `{}`: a cycle of ref port connections",
                        port.hierarchical_path()
                    ),
                    port,
                )));
            }
        }
        let slot = instance_signals[&owner]
            .get(&actual)
            .copied()
            .ok_or_else(|| {
                RunError::Lowering(LoweringError::unsupported_at(
                    &format!(
                        "ref port `{}`: the actual has no storage slot",
                        port.hierarchical_path()
                    ),
                    port,
                ))
            })?;
        // A window has the shape of the port that names it (its type and
        // signedness), over the target's slot.
        let slot = match window {
            None => slot,
            Some(w) => {
                if !matches!(slot.class, SignalSlotClass::Memory { .. })
                    && vj_codegen::huge::is_huge_width(slot.width)
                {
                    return Err(RunError::Lowering(LoweringError::unsupported_at(
                        &format!(
                            "ref port `{}`: a select of a variable wider than the wide-value \
                             threshold (IEEE 1800-2023 6.9.1)",
                            port.hierarchical_path()
                        ),
                        port,
                    )));
                }
                let shape = instance_signals[&key.0]
                    .get(&key.1)
                    .copied()
                    .unwrap_or(slot);
                SignalSlot {
                    slot: slot.slot,
                    width: w.width,
                    signed: shape.signed,
                    class: if w.width > 64 {
                        SignalSlotClass::Wide
                    } else {
                        SignalSlotClass::Inline
                    },
                }
            }
        };
        aliases.insert(key.clone(), (owner, slot, window));
    }
    Ok(aliases)
}

/// `--x-initial zero` (non-LRM): uninitialized 4-state variables and
/// memories start at 0 instead of X, as under a 2-state simulator.
static X_INITIAL_ZERO: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Sets the `--x-initial zero` option for later runs in this process.
pub fn set_x_initial_zero(on: bool) {
    X_INITIAL_ZERO.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// `--seed N`: the base state of the run's random generators (`None` keeps
/// `process_rng::DEFAULT_SEED`).
static SEED: std::sync::Mutex<Option<u64>> = std::sync::Mutex::new(None);

/// Sets the `--seed` option for later runs in this process.
pub fn set_seed(seed: Option<u64>) {
    *SEED.lock().unwrap_or_else(|e| e.into_inner()) = seed;
}

/// The seed given with `--seed`, if any.
pub fn seed() -> Option<u64> {
    *SEED.lock().unwrap_or_else(|e| e.into_inner())
}

/// Whether the port connection `expr` (to `port`) is wired natively
/// (`register_port_wire*`): a plain name, or a chain of constant bit-/part-
/// selects of a plain non-array name, with no implicit width conversion.
/// Anything else -- an expression, a width conversion, an array element --
/// is compiled as a continuous assignment in the parent
/// ([`compiled_port_connections`]).
fn native_port_connection<'d>(expr: Expression<'d>, _port: &Symbol<'d>) -> bool {
    // An integral expression's width (`None` for an unpacked array, a
    // struct, a type-less expression: those connect whole, unconverted).
    let width = |x: Expression<'d>| {
        x.expr_type()
            .filter(|t| t.is_integral())
            .map(|t| vj_codegen::types::TypeWidth::value_width(&t))
    };
    let e = if expr.kind() == ExpressionKind::Assignment {
        // An output: `parent_lvalue = <port value>`, where slang wraps the
        // port value in a conversion when the widths differ (23.3.3.7).
        let (Some(l), Some(r)) = (expr.left(), expr.right()) else {
            return false;
        };
        let mut inner = r;
        while inner.kind() == ExpressionKind::Conversion {
            match inner.operand() {
                Some(o) => inner = o,
                None => return false,
            }
        }
        if width(l) != width(inner) {
            return false;
        }
        l
    } else {
        expr
    };
    // A name of a variable or net (not a parameter or an enum constant,
    // which is compiled like any other constant expression).
    let names_signal = |x: Expression<'d>| {
        x.kind() == ExpressionKind::NamedValue
            && x.referenced_symbol().is_some_and(|s| {
                // A package or compilation-unit variable lives outside the
                // parent instance's own signals, so it is read through a
                // continuous assignment, not wired natively (LRM 23.3.3).
                matches!(s.kind(), SymbolKind::Variable | SymbolKind::Net)
                    && !s.parent().is_some_and(|p| {
                        matches!(p.kind(), SymbolKind::Package | SymbolKind::CompilationUnit)
                    })
            })
    };
    match e.kind() {
        ExpressionKind::NamedValue => names_signal(e),
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect => {
            let Some(base) = select_base(e).filter(|b| names_signal(*b)) else {
                return false;
            };
            let Some(base_ty) = base.expr_type().filter(|t| !t.is_unpacked_array()) else {
                return false;
            };
            let base_width = vj_codegen::types::TypeWidth::value_width(&base_ty);
            vj_codegen::select::constant_window(e, base_width)
                .is_ok_and(|(_, w)| Some(w) == width(e))
        }
        _ => false,
    }
}

/// The input ports a clocking event is traced through
/// ([`crate::clocking::PortSources`]): an input port connected as a whole to a
/// variable of its parent, of equal width, whose connection is a native wire
/// (not a net resolved in the bank, not an inout, not `ref`).
fn clock_port_sources(
    elaborated: &netlist::Netlist<'_>,
    order: &[InstanceId],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    resolution: &crate::nets::Resolution,
) -> crate::clocking::PortSources {
    let mut out = crate::clocking::PortSources::new();
    for &id in order {
        let Some(parent) = elaborated.instance(id).parent else {
            continue;
        };
        let (Some(child_signals), Some(parent_signals)) =
            (instance_signals.get(&id), instance_signals.get(&parent))
        else {
            continue;
        };
        for conn in elaborated.instance_symbol(id).instance_port_connections() {
            let port = conn.port();
            if port.kind() == SymbolKind::InterfacePort
                || port.port_direction() != ArgumentDirection::In
                || resolution.inout_ports.contains(&(id, port.uid()))
            {
                continue;
            }
            let Some(expr) = conn.expression() else {
                continue;
            };
            if expr.kind() != ExpressionKind::NamedValue || !native_port_connection(expr, &port) {
                continue;
            }
            let Some(src) = expr.referenced_symbol().filter(|s| {
                s.kind() == SymbolKind::Variable || out.contains_key(&(parent, s.uid()))
            }) else {
                continue;
            };
            let member = port.port_internal_symbol().unwrap_or(port);
            let (Some(&cs), Some(&ps)) = (
                child_signals.get(&member.uid()),
                parent_signals.get(&src.uid()),
            ) else {
                continue;
            };
            if cs.width != ps.width
                || matches!(cs.class, SignalSlotClass::Memory { .. })
                || matches!(ps.class, SignalSlotClass::Memory { .. })
            {
                continue;
            }
            out.insert((id, member.uid()), (parent, src.uid(), ps.slot));
        }
    }
    out
}

/// The value at the bottom of a chain of element/part-selects (`e` itself
/// when it is not a select).
fn select_base(mut e: Expression<'_>) -> Option<Expression<'_>> {
    while matches!(
        e.kind(),
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
    ) {
        e = e.select_value()?;
    }
    Some(e)
}

/// `inst`'s input and output port connections that are compiled as a
/// continuous assignment in its parent: `(port, connection expression)`.
/// An input's expression is the value (`child_port = expr`); an output's is
/// slang's implicit `parent_lvalue = <port value>` assignment.
fn compiled_port_connections<'d>(inst: &Symbol<'d>) -> Vec<(Symbol<'d>, Expression<'d>)> {
    inst.instance_port_connections()
        .filter_map(|conn| {
            let port = conn.port();
            if port.kind() == SymbolKind::InterfacePort
                || !matches!(
                    port.port_direction(),
                    ArgumentDirection::In | ArgumentDirection::Out
                )
            {
                return None;
            }
            let expr = conn.expression()?;
            if crate::nets::connects_interconnect(&port, expr) {
                return None;
            }
            (!native_port_connection(expr, &port)).then_some((port, expr))
        })
        .collect()
}

/// A planner slot's class as the image names it.
pub(crate) fn place_class(class: SignalSlotClass) -> vj_sim::image::PlaceClass {
    use vj_sim::image::PlaceClass;
    match class {
        SignalSlotClass::Inline => PlaceClass::Inline,
        SignalSlotClass::Wide => PlaceClass::Wide,
        SignalSlotClass::Memory { num_rows, .. } => PlaceClass::Memory { rows: num_rows },
    }
}

/// One signal of one instance as a native process addresses it.
fn place_of(instance: InstanceId, slot: SignalSlot) -> vj_sim::image::PlaceImage {
    vj_sim::image::PlaceImage {
        instance,
        slot: slot.slot,
        width: slot.width,
        class: place_class(slot.class),
    }
}

/// The pipeline: reads `path`, elaborates it (walking the FULL instance
/// hierarchy via `netlist::elaborate`, not just its single top module),
/// allocates one `StateEngine` instance per elaborated instance, lowers
/// every discovered process (of every instance) into one shared LLVM
/// module, JITs it, wires every instance port connection as a synthetic
/// continuous-assignment process, registers every compiled kernel and every
/// port-wire process with a real `sched::Engine`, runs to completion, and
/// writes every `$display`/`$write` line to `stdout`. Returns the `$finish`
/// exit code (or `0` if the run completed without ever calling `$finish`).
pub fn run_design(path: &Path, stdout: &mut dyn Write) -> Result<i32, RunError> {
    run_design_with_plusargs(path, &[], stdout)
}

/// [`run_design`], plus RT-077's own literal wiring: `plusargs` is this
/// run's raw, `+`-prefixed argv tokens (e.g. `["+SEED=5", "+FOO=bar"]`),
/// handed to `vj_runtime::plusargs_sink::set_plusargs_for_run` BEFORE
/// this run's `sched::Engine` ever resumes a process, exactly the
/// "`runtime::init` before simulation starts" ordering RT-077's own
/// acceptance text names (`plusargs_sink`'s own module doc has the full
/// deviation note on why this crate's actual entry point is named
/// `set_plusargs_for_run`, not a bare `runtime::init`, since no such
/// function exists anywhere in this crate). `run_design` itself is this
/// function with an empty `plusargs` slice -- a NEW, additive function
/// rather than a breaking signature change to `run_design`, so every
/// existing caller (this crate's own `main.rs`, and the many `run_design`
/// call sites across this workspace's own test suites) keeps compiling
/// unchanged.
///
/// Overwrites (never merges) this OS thread's whole plusarg store on every
/// call, including with an empty slice -- the same "reset at the start of
/// every run" discipline `reset_seed_for_new_run`/`reset_mcd_table_for_new_run`
/// below already establish, so a SECOND `run_design`/`run_design_with_plusargs`
/// call on the same OS thread (this workspace's own test binaries routinely
/// do this) never silently inherits a prior call's plusargs.
pub fn run_design_with_plusargs(
    path: &Path,
    plusargs: &[String],
    stdout: &mut dyn Write,
) -> Result<i32, RunError> {
    run_design_with_options(path, plusargs, TimingOptions::default(), stdout)
}

/// [`run_design_with_plusargs`], plus the run-wide [`TimingOptions`] (the "simulators may
/// provide an option" clauses of LRM clause 31, e.g. 31.8's per-bit expansion of vector
/// timing checks). `TimingOptions::default()` is the LRM's default behaviour, which is what
/// every function above runs with.
pub fn run_design_with_options(
    path: &Path,
    plusargs: &[String],
    timing: TimingOptions,
    stdout: &mut dyn Write,
) -> Result<i32, RunError> {
    run_sources_with_options(&SourceSet::single(path), plusargs, timing, stdout)
}

/// [`run_design_with_options`] for several source files elaborated together,
/// with the include directories, macros and top modules of `sources`
/// ([`SourceSet`]). Errors that name "the" source file name the first one.
pub fn run_sources_with_options(
    sources: &SourceSet,
    plusargs: &[String],
    timing: TimingOptions,
    stdout: &mut dyn Write,
) -> Result<i32, RunError> {
    run_sources_core(sources, plusargs, timing, stdout, None)
}

/// Where `vj build-aot` has the shared planner put its result.
struct AotRequest<'a> {
    /// The object file the lowered module is written to.
    out_obj: &'a Path,
    /// `build-aot --exe`: also emit a real `main` calling `vj_aot_main`
    /// into the same object, so [`crate::aot::build_aot_exe`] can link it as
    /// a standalone executable instead of a `.so`.
    with_main: bool,
    /// The design image the planner assembled (set on success).
    image: &'a mut Option<vj_sim::image::DesignImage>,
}

/// Plans `sources` and lowers them to an AOT object at `out_obj`, returning the
/// [`DesignImage`](vj_sim::image::DesignImage) embedded in it. This is the
/// SAME planner [`run_sources_with_options`] runs (it stops where the JIT
/// would bind the module), so the two modes cannot plan a design differently.
///
/// A design the image cannot carry is refused by name
/// ([`RunError::AotRefused`]).
pub fn build_aot_object(
    sources: &SourceSet,
    timing: TimingOptions,
    out_obj: &Path,
) -> Result<vj_sim::image::DesignImage, RunError> {
    build_aot_object_with(sources, timing, false, out_obj)
}

/// [`build_aot_object`] with `with_main` (`build-aot --exe`): the object also
/// gets a real C `main` forwarding to `vj_aot_main`, so it can be linked
/// as a standalone executable instead of a `.so` (`crate::aot::build_aot_exe`).
pub fn build_aot_object_with(
    sources: &SourceSet,
    timing: TimingOptions,
    with_main: bool,
    out_obj: &Path,
) -> Result<vj_sim::image::DesignImage, RunError> {
    let mut image = None;
    run_sources_core(
        sources,
        &[],
        timing,
        &mut std::io::sink(),
        Some(AotRequest {
            out_obj,
            with_main,
            image: &mut image,
        }),
    )?;
    image.ok_or_else(|| {
        RunError::Jit("build-aot: the planner finished without producing a design image".into())
    })
}

/// [`run_sources_with_options`], or -- with `aot` -- the planning half of
/// `vj build-aot`.
fn run_sources_core(
    sources: &SourceSet,
    plusargs: &[String],
    timing: TimingOptions,
    stdout: &mut dyn Write,
    aot: Option<AotRequest<'_>>,
) -> Result<i32, RunError> {
    let path = sources.label();
    set_plusargs_for_run(plusargs.to_vec());
    // B-runtime Task 6 (RT-078/RT-082): reset `$random`/`$urandom`/
    // `$urandom_range`'s thread-local seed to its fixed default at the START
    // of every run -- `vj_runtime::random_sink::reset_seed_for_new_run`'s
    // own doc comment explains why this is load-bearing, not defensive: this
    // function's own callers (this crate's tests included) routinely call
    // `run_design` more than once on the same OS thread to compare two runs,
    // and without this reset the second call would silently continue the
    // first call's own PRNG stream instead of starting the identical,
    // reproducible one RT-082 requires.
    reset_seed_for_new_run();
    if let Some(n) = seed() {
        vj_sim::sched::process_rng::set_base_seed(n);
    }
    // B-runtime Task 7 (RT-050): the same "reset at the start of every run"
    // discipline as `reset_seed_for_new_run` above, for the identical reason
    // -- `vj_runtime::file_io_sink::reset_mcd_table_for_new_run`'s own
    // doc comment.
    reset_mcd_table_for_new_run();
    crate::dpi::reset_for_new_run();
    vj_sim::sched::reset_cells_for_new_run();
    vj_runtime::severity::reset_error_count();

    // VPI libraries load first, before the sources are even read: their
    // startup routines register system tasks and callbacks (IEEE 1800-2023
    // 36.9), which `sources::compile` declares to slang as the design calls them.
    crate::vpi::api::begin_run(plusargs);
    let vpi_libraries = crate::vpi::loader::take_pending_libraries();
    if !vpi_libraries.is_empty() {
        crate::nets::track_strengths();
    }
    // `build-aot` loads them too: the system tasks they register decide how
    // the design lowers (`vpi_systf::set_registered`), and the image records
    // that set so `run-aot` can check the libraries it loads register the same.
    crate::vpi::loader::load(&vpi_libraries).map_err(|e| RunError::Vpi(e.to_string()))?;
    // Threads, frames and statement callbacks (`vpi::dynobj`): the probes and
    // the scheduler's thread hook exist only for a run that loaded a VPI
    // library, so every other design runs exactly the code it always did.
    // (Both are per-thread settings, so each run states them afresh.) An AOT
    // build never reaches here with a library (refused above), so this
    // always disables them for it.
    vj_codegen::vpi_dyn::set_enabled(!vpi_libraries.is_empty());
    // Statement-coverage probes (LRM 40.2.1 a): `--coverage` at run or build time.
    vj_codegen::stmtcov::set_enabled(vj_runtime::codecov::enabled());
    vj_sim::sched::set_thread_hook(
        (!vpi_libraries.is_empty()).then_some(crate::vpi::dynobj::thread_hook as _),
    );
    // The assertion runner's own VPI bridge (`vj_exec::verif`'s own
    // doc comment): installed under the identical "only when a VPI library
    // loaded" rule.
    vj_exec::verif::set_vpi_hooks(
        (!vpi_libraries.is_empty()).then(|| Box::new(crate::vpi::sim::Hooks) as _),
    );

    let (mut design, systf_codegen) = {
        let mut compiled = crate::sources::compile(sources)?;
        // A system task or function slang does not know (it only warns): a
        // VPI library may register it now (38.36.3 `cbUnresolvedSystf`), and
        // the design is compiled again with it; otherwise it is an error.
        let unknown = unknown_system_names(&compiled.0);
        if !unknown.is_empty() && crate::vpi::callbacks::resolve_unresolved_systfs(&unknown) {
            compiled = crate::sources::compile(sources)?;
        }
        let unknown = unknown_system_names(&compiled.0);
        if !unknown.is_empty() {
            return Err(RunError::Diagnostics(format!(
                "the design calls system tasks or functions that are neither built in nor \
                 registered by a VPI library: {}\n{}",
                unknown.join(", "),
                compiled.0.diagnostics().rendered()
            )));
        }
        compiled
    };
    // Run-time messages name locations as slang does (`include`, `line`).
    vj_sim::process::cfg::set_source_session(Some(design.session().clone()));
    // A design with errors elaborates to placeholders (e.g. an
    // `UninstantiatedDef`) that would otherwise surface as an unrelated
    // lowering error.
    if design.diagnostics().has_errors() {
        return Err(RunError::Diagnostics(design.diagnostics().to_string()));
    }
    if let Some(text) = lrm_errors_slang_only_warns(&design) {
        return Err(RunError::Diagnostics(text));
    }
    // LRM 20.10.1: an elaboration `$warning` / `$info` only prints its
    // message (an `$error` / `$fatal` already aborted above).
    for d in design.diagnostics().items() {
        let (tag, task) = if d.message.starts_with("$warning encountered") {
            ("WARNING", "$warning encountered")
        } else if d.message.starts_with("$info encountered") {
            ("INFO", "$info encountered")
        } else {
            continue;
        };
        let text = d.message[task.len()..].trim_start_matches(':').trim_start();
        let file = std::fs::canonicalize(&d.file)
            .map_or_else(|_| d.file.clone(), |p| p.display().to_string());
        let _ = writeln!(stdout, "{tag}: {file}:{}: {text}", d.line);
    }
    // An out-of-line `extern` method body slang bound only after its
    // diagnostics were collected (25.7): an error there is not in them.
    if let Some((path, _)) = vj_sim::netlist::itf::invalid_impl_bodies(&design)
        .into_iter()
        .next()
    {
        return Err(RunError::Diagnostics(format!(
            "error: the body of the exported interface method `{path}` does not elaborate: \
             it names something its modport does not expose, or otherwise misuses the \
             interface (IEEE 1800-2023 25.7, 25.5)\n"
        )));
    }
    crate::constraint_decls::check_single_external_blocks(&design.syntax_trees())
        .map_err(RunError::Diagnostics)?;
    // 29.3 (a UDP table has an entry) and 23.2.2.1 (a redeclared port keeps its range).
    crate::decl_checks::check_udp_tables(&design.syntax_trees()).map_err(RunError::Diagnostics)?;
    crate::decl_checks::check_nonansi_port_ranges(&design.syntax_trees())
        .map_err(RunError::Diagnostics)?;
    // 35.4/35.5.4: the deprecated "DPI" version string warns; mixing versions is an error.
    for w in crate::decl_checks::check_dpi_spec_strings(&design.syntax_trees())
        .map_err(RunError::Diagnostics)?
    {
        eprint!("{w}");
    }
    // 11.12: a let is defined before it is used (slang accepts the call form).
    vj_codegen::let_order::check_let_definition_order(&design.syntax_trees())
        .map_err(RunError::Diagnostics)?;
    // DPI-C: the export trampolines first (user libraries link against
    // them), then the user libraries themselves.
    let export_names: Vec<String> = design.dpi_exports().map(|e| e.c_identifier()).collect();
    let dpi_libraries = crate::dpi::take_pending_libraries();
    // (`build-aot` loads no library: the refusals are raised by the hook below.)
    if aot.is_none() {
        crate::dpi::load_export_trampolines(&export_names).map_err(RunError::Jit)?;
        if !dpi_libraries.is_empty() {
            crate::dpi::load_svdpi_support().map_err(RunError::Jit)?;
        }
        crate::dpi::load_libraries(&dpi_libraries).map_err(RunError::Jit)?;
    }

    // Task 2 (CG-079/CG-080/PR-084): computed exactly ONCE, over the WHOLE
    // design, and strictly BEFORE `design.eval_session()` below --
    // `build_comb_sensitivity_index`'s own doc comment explains why this
    // call order is load-bearing, not stylistic (`EvalSession`'s lifetime
    // keeps `design` exclusively borrowed for the rest of this function
    // once it exists, and `Design::analyze` needs its own, separate borrow
    // of `design` that cannot coexist with that).
    let comb_sensitivity = build_comb_sensitivity_index(&design).map_err(RunError::Lowering)?;

    // The VPI object model, from `&design` (so before the evaluation session
    // borrows it exclusively): available from `cbEndOfCompile` onwards.
    let vpi_model = crate::vpi::build::build_model(&mut design, &path.to_string_lossy())
        .map_err(|e| RunError::Vpi(e.to_string()))?;
    crate::vpi::state::install_model(vpi_model);

    let eval = design.eval_session();
    let elaborated = netlist::elaborate(&eval).map_err(|e| elab_to_run_error(e, path))?;

    // Every module no other module instantiates is a top-level instance
    // (LRM 1800-2023 23.3.1); all of them are simulated.
    // A design with no module at all (only packages, classes, interfaces,
    // `define/`include material, ...) is legal and has nothing to simulate:
    // `run` finishes cleanly at time 0, as every other simulator does.
    // `build-aot` still refuses it by name, `AOT-REFUSED(no-top-module)`, as
    // there is no design image to carry.
    if elaborated.top.is_empty() && aot.is_none() {
        return Ok(0);
    }
    if elaborated.top.is_empty() {
        return Err(RunError::AotRefused {
            feature: "no-top-module".to_owned(),
            reason: "design has no top-level module instance".to_owned(),
            at: format!("{}:1", path.display()),
        });
    }
    let registration_order = elaborated.registration_order();

    // A virtual class task that can suspend is inlined, so a call through a
    // base handle dispatches over the classes an object can be
    // (`process::cfg::VirtualTasks`): the same discovery, and the same dense
    // template ids, as the class sub-pass below. Telling `super.m()` (not
    // virtual) from a bare `m()` needs the design's syntax.
    let (virtual_tasks, class_uids) = {
        let mut tys = netlist::collect_new_class_types(&eval);
        let ancestors: Vec<sv_lang::Type<'_>> =
            tys.iter().flat_map(|t| netlist::base_chain(*t)).collect();
        tys.extend(ancestors);
        let ids = netlist::assign_class_template_ids(&tys);
        let mut seen = HashSet::new();
        let classes: Vec<(u32, sv_lang::Type<'_>)> = tys
            .iter()
            .zip(ids.iter())
            .filter(|(_, id)| seen.insert(id.0))
            .map(|(ty, id)| (id.0, *ty))
            .collect();
        let class_uids: Vec<(u32, String)> = {
            use vj_sim::symid::SymbolUid as _;
            classes
                .iter()
                .map(|(id, ty)| (*id, format!("{:?}", ty.as_symbol().uid())))
                .collect()
        };
        (
            std::rc::Rc::new(vj_sim::process::cfg::VirtualTasks::new(classes)),
            class_uids,
        )
    };
    vj_sim::process::cfg::set_suspending_virtuals(&virtual_tasks);
    vj_sim::process::cfg::set_explicit_super_detector(Some(
        vj_codegen::classes::call_is_explicit_super,
    ));
    let _super_syntax = vj_codegen::classes::DesignSyntaxScope::enter(eval.design());

    // --- STATE (layout half): register one `StateLayout` per distinct
    // dedup `TemplateKey` -- two elaborated instances sharing a `TemplateKey`
    // (S5's own dedup) share one layout, built once from whichever of them
    // is encountered first in `registration_order`. ------------------------
    let templates = TemplateRegistry::new();
    let mut registered_templates: HashSet<TemplateKey> = HashSet::new();
    for &id in &registration_order {
        let key = *elaborated.dedup_key(elaborated.instance(id).template);
        if registered_templates.insert(key) {
            let body = instance_body_of(&elaborated, id, path)?;
            let layout = build_template_layout(&body).map_err(|e| {
                RunError::Lowering(LoweringError::unsupported(
                    &format!("state layout error: {e:?}"),
                    path.display().to_string().as_str(),
                ))
            })?;
            // SAFETY: `templates` is a local, single-owned registry with no
            // live `layout_of` borrow held across this call, and no
            // concurrent caller (this function's whole STATE/JIT setup runs
            // single-threaded).
            unsafe {
                templates.register(key, layout);
            }
        }
    }
    // A package's variables live in a state instance of their own (a
    // package is not part of the instance hierarchy), reached like another
    // instance's signals (foreign slots). Keyed by ids and template keys
    // counting down from `u32::MAX`, clear of the elaborated instances'.
    let mut packages: Vec<(InstanceId, TemplateKey, Symbol<'_>)> = Vec::new();
    // A `$unit` (compilation-unit) scope's variables are state the same way
    // (LRM 3.12.1): `bit failed;` outside any module, read and written by all.
    let compilation = eval
        .design()
        .packages()
        .chain(eval.design().compilation_units());
    for pkg in compilation {
        if !vj_sim::netlist::state_items(&pkg)
            .iter()
            .any(|m| m.kind() == SymbolKind::Variable)
        {
            continue;
        }
        let n = u32::MAX - packages.len() as u32;
        let key = TemplateKey {
            definition: n,
            params_hash: 0,
        };
        let layout = build_template_layout(&pkg).map_err(|e| {
            RunError::Lowering(LoweringError::unsupported_at(
                &format!("package state layout error: {e:?}"),
                &pkg,
            ))
        })?;
        // SAFETY: as for the instance templates just above.
        unsafe {
            templates.register(key, layout);
        }
        packages.push((InstanceId(n), key, pkg));
    }

    // --- Codegen: discover + lower every process of every instance into one
    // shared plan list, then hand the whole batch to
    // `vj-codegen::pipeline::build_pipeline` -- the one place in this
    // tree allowed to touch `inkwell` (AB-024; see `pipeline.rs`'s own doc
    // comment) -- to build, JIT, and bind it. Each instance's own processes
    // are discovered and lowered against THAT instance's own signal slots
    // (`signal_slots_of`, keyed by that instance's own, undeduped
    // `vj_sim::symid::SymbolId`s -- never the canonical/deduped body's), which is
    // exactly what gives two instances of one module their own independent
    // state (S5's dedup collapses `Template`s, never the per-instance
    // `Symbol` walk this function performs). -------------------------------
    let instance_ids_by_path: HashMap<String, u32> = registration_order
        .iter()
        .map(|&o| (elaborated.instance_symbol(o).hierarchical_path(), o.0))
        .collect();
    // LRM 25.7.4: `disable b.t;` / `disable m1.a.t;` of an interface `extern`
    // task, per requester instance, as the scope tag of the activations it
    // ends -> the `<requester id>/<path>` keys that reach them.
    let ext_aliases: std::sync::Arc<HashMap<String, Vec<String>>> = {
        let mut m: HashMap<String, Vec<String>> = HashMap::new();
        let labels = vj_sim::process::cfg::dotted_disable_labels();
        for &r in &registration_order {
            let sym = elaborated.instance_symbol(r);
            for label in &labels {
                let path: Vec<String> = label.split('.').map(str::to_string).collect();
                if let Some(tag) = vj_sim::netlist::itf::extern_disable_tag(&sym, &path) {
                    m.entry(tag).or_default().push(format!("{}/{label}", r.0));
                }
            }
        }
        std::sync::Arc::new(m)
    };
    // `(requester instance id, dotted path)` of every `disable u1.blk;`.
    let mut instance_path_disables: Vec<(u32, String)> = Vec::new();
    // `<instance path>.<name>` of every named block that never suspends: a
    // `disable` of one from another process is a no-op (9.6.2, nothing can be
    // inside it), so it is accepted without a scope.
    let mut inert_blocks: HashSet<String> = HashSet::new();
    let mut plans = Vec::new();
    let mut kernel_meta: Vec<(u32, ProcessKind, InstanceId, KernelSensitivitySpec, bool)> =
        Vec::new();
    // Each kernel's `ProcessCfg::disable_scopes` (indexed like `kernel_meta`):
    // `(resume pc, label, exit pc)`.
    let mut branch_scope_labels: HashSet<String> = HashSet::new();
    let mut kernel_disable_scopes: Vec<std::sync::Arc<[(u32, String, u32)]>> = Vec::new();
    // Each kernel's `(instance body, process symbol)`, which VPI's thread
    // objects (`vpi::dynobj`) find the process object by.
    let mut kernel_dyn: Vec<(SymbolId, SymbolId)> = Vec::new();
    // The kernels (indexed like `kernel_meta`) and continuous assignments
    // (indexed like `cont_assign_specs`) that run in the Reactive region: a
    // checker's procedures, continuous assignments and output formal
    // connections (LRM 17.7.3, 17.3).
    let mut reactive_kernels: std::collections::HashSet<usize> = std::collections::HashSet::new();
    let mut program_initial_kernels: std::collections::HashSet<usize> =
        std::collections::HashSet::new();
    let mut reactive_cont_assigns: std::collections::HashSet<usize> =
        std::collections::HashSet::new();
    // Task 2 (NL-034, `docs/superpowers/plans/2026-09-27-run-wiring.md`):
    // every module-level continuous `assign`, across every elaborated
    // instance, mirrors `plans`/`kernel_meta` above but has no `Segment`s/
    // `FrameLayout` of its own (see `vj_codegen::process_lower::
    // lower_cont_assign_kernel_fn`'s own doc comment for why it is a
    // distinct kind of lowering input, not a `ProcessLoweringPlan`).
    // `cont_assign_meta` is index-aligned with `cont_assign_specs` (and,
    // later, with `build_pipeline`'s own returned continuous-assign kernel
    // names) exactly the way `kernel_meta` is index-aligned with `plans`.
    let mut cont_assign_specs: Vec<ContAssignLoweringSpec> = Vec::new();
    let mut cont_assign_meta: Vec<(InstanceId, Vec<SymbolId>)> = Vec::new();
    // R-run Task 10 (`docs/superpowers/plans/2026-09-27-run-wiring.md`;
    // CG-061 reused, CG-042 untouched), review fix (r1): every ordinary
    // (non-DPI) `function`/`task` actually CALLED, transitively, from some
    // discovered process's own body or some continuous assign's own RHS,
    // across the whole design -- mirrors `plans`/`cont_assign_specs` above,
    // but is filled in AFTER the per-instance loop below finishes (not
    // alongside it), from `call_roots`, which that loop DOES populate
    // (every discovered process's body / continuous-assign RHS, as
    // `SemNode`s) -- see `module::discover_called_subroutines`'s own doc
    // comment for why reachability, not blanket per-instance-body
    // enumeration, is what this task's own scope calls for: a design
    // containing an unused, unsupported-shaped function/task must still
    // run, exactly as it did before this task existed.
    // `build_pipeline`'s own subroutine pre-pass dedups by mangled name, so
    // two instances of the same (unparameterized) module contributing the
    // "same" subroutine here is fine -- never a double-lowering, never a
    // collision.
    let mut subroutine_specs: Vec<SubroutineLoweringSpec> = Vec::new();
    let mut call_roots: Vec<SemNode> = Vec::new();
    // Every instance's own signals, then (a second pass, once every
    // instance's are known) the signals of other instances it reaches: each
    // gets a foreign slot, `own + k` (`set_foreign_slots`, registered once
    // the instances exist), under the symbol its code names it by -- so a
    // process reads, writes, waits on and schedules NBAs to `b.valid`
    // exactly as it does its own signals.
    let mut instance_signals: HashMap<InstanceId, HashMap<SymbolId, SignalSlot>> = HashMap::new();
    let mut body_id_to_instance: HashMap<SymbolId, InstanceId> = HashMap::new();
    for &id in &registration_order {
        let body = instance_body_of(&elaborated, id, path)?;
        body_id_to_instance.insert(body.uid(), id);
        instance_signals.insert(id, signal_slots_of(&body)?);
    }
    for (id, _, pkg) in &packages {
        body_id_to_instance.insert(pkg.uid(), *id);
        instance_signals.insert(*id, signal_slots_of(pkg)?);
    }
    let syntax_trees = eval.design().syntax_trees();
    // Resolved nets (`crate::nets`): found over the instances' own signals,
    // before any foreign slot is added. Their drivers' contribution cells
    // live in one synthetic "bank" instance.
    let mut infos = Vec::new();
    for &id in &registration_order {
        infos.push((
            id,
            instance_body_of(&elaborated, id, path)?,
            elaborated.instance_symbol(id),
            elaborated.instance(id).parent,
        ));
    }
    // The nets declared with a user-defined nettype (LRM 6.6.7).
    let user_nets =
        crate::usernets::user_net_types(&eval, &infos, &instance_signals, &syntax_trees)
            .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "nettype")))?;
    let bodies: Vec<(InstanceId, Symbol<'_>)> =
        infos.iter().map(|(id, body, _, _)| (*id, *body)).collect();
    // Specify-block module-path retiming (`docs/superpowers/plans/
    // 2026-10-03-sdf.md` Task 4a): discovery + delay attachment
    // (`crate::specify::discover`) runs BEFORE `crate::primitives::plan`
    // now (Task 9) -- it has no dependency on `resolution`/`bank_id` at all,
    // so moving it earlier changes nothing it computes, and lets
    // `specify_dests` below reach `primitives::plan`.
    let mut timing_model = crate::specify::discover_with(&eval, &bodies, path, &timing)?;
    // Negative timing checks (LRM 31.9.1): solve the delay of every signal a negative limit
    // delays, and raise the module paths that start at one, BEFORE any path is planned.
    let iface_terminals: HashMap<InstanceId, HashMap<SymbolId, (InstanceId, SignalSlot)>> = bodies
        .iter()
        .map(|(id, body)| {
            (
                *id,
                crate::specify::modport_terminals(body, &instance_signals, &body_id_to_instance),
            )
        })
        .collect();
    let timing_scope = crate::timingcheck::Scope {
        own: &instance_signals,
        iface: &iface_terminals,
    };
    let mut delay_table =
        crate::timingcheck::negative_timing(&mut timing_model, &timing_scope, &timing)
            .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "timing check")))?;
    // Task 9 (LRM 30.6): every `(instance, destination)` any module path
    // targets -- every `PathEntry` is already desugared to exactly one
    // output by `discover` (Task 3's own doc comment), so `outputs[0]` is
    // always present. `primitives::plan` consults this to defer to
    // `crate::specify::plan` for a destination's own delay line instead of
    // building a second, independently-committing one (`primitives::
    // Plans::natural`'s own doc comment).
    let specify_dests: std::collections::HashSet<(InstanceId, vj_sim::symid::SymbolId)> =
        timing_model
            .paths
            .iter()
            .map(|p| (p.instance, p.outputs[0].0.clone()))
            .collect();
    let mut resolution = crate::nets::analyze(
        &infos,
        &instance_signals,
        &syntax_trees,
        &user_nets,
        &specify_dests,
    )
    .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "net")))?;
    let bank_id = InstanceId(u32::MAX - (1 << 20));
    let port_sources = clock_port_sources(
        &elaborated,
        &registration_order,
        &instance_signals,
        &resolution,
    );
    // Primitives and delayed continuous drivers (`crate::primitives`),
    // whose staging cells also live in the bank.
    let mut prim_plans = crate::primitives::plan(
        &eval,
        &bodies,
        &instance_signals,
        &syntax_trees,
        &mut resolution,
        bank_id,
        &specify_dests,
    )
    .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "primitive")))?;
    // `trireg` charge decay times (LRM 28.16.2), for the net resolvers.
    let trireg_decays = crate::primitives::trireg_decays(&eval, &bodies)
        .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "trireg")))?;
    let trireg_charges = crate::primitives::trireg_charges(&eval, &bodies);
    // Planning net/variable-destination retimers against the SAME
    // resolution/bank the primitives above just populated -- a sibling
    // call, same shapes, same call site. `&prim_plans.natural` (Task 9)
    // hands this call every destination's own competing distributed delay
    // (if any) to fold into `RetimerPlan::natural`.
    let mut specify_plans = crate::specify::plan(
        &bodies,
        &instance_signals,
        &mut resolution,
        bank_id,
        &timing_model,
        &prim_plans.natural,
        &body_id_to_instance,
        &prim_plans.specify_staging,
        &if timing_model.paths.is_empty() {
            Default::default()
        } else {
            crate::nets::driven_windows(&infos, &instance_signals, &syntax_trees)
        },
    )
    .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "specify path")))?;
    // System timing checks (sdf T15 onward): one native process per check. A check that reads
    // an implicit delayed signal (LRM 31.9.1) allocates its copy in the bank.
    let timing_check_plans = crate::timingcheck::plan(
        &timing_model,
        &timing_scope,
        &timing,
        &mut delay_table,
        &mut resolution,
        bank_id,
    )
    .map_err(|m| RunError::Lowering(LoweringError::unsupported(&m, "timing check")))?;
    for warning in &delay_table.warnings {
        eprintln!("{warning}");
    }
    // `$sdf_annotate` (LRM 32) raises an annotated path delay to the same negative-timing floor
    // the model's own delays got.
    let floors: Vec<u64> = timing_model
        .paths
        .iter()
        .map(|p| {
            p.inputs
                .first()
                .map_or(0, |i| delay_table.delay_of(p.instance, &i.0))
                .max(0) as u64
        })
        .collect();
    specify_plans.apply_floors(&floors);
    // SD-C / T29 (LRM 32.4.4): a design that calls `$sdf_annotate` builds every packed port
    // connection wire delay-capable (`crate::interconnect`); the one process that commits their
    // delayed transitions sleeps on a kick cell of its own in the bank.
    // A VPI library can annotate interconnect delays (`vpi_put_delays`) too.
    let sdf_wires =
        crate::primitives::calls_sdf_annotate(&syntax_trees) || !vpi_libraries.is_empty();
    let sdf_kick = sdf_wires.then(|| {
        let slot = resolution.bank_widths.len() as u32;
        resolution.bank_widths.push(32);
        crate::primitives::bank_slot(slot, 32)
    });
    let interconnect_table = crate::interconnect::new_table();
    let bank_key = TemplateKey {
        definition: u32::MAX - (1 << 20),
        params_hash: 1,
    };
    // The resolver processes below run against the bank even when no net has
    // a contribution cell (a `tri0`/`supply1` net nothing drives still
    // resolves to its pull value).
    let needs_bank = !resolution.bank_widths.is_empty()
        || !resolution.groups.is_empty()
        || !resolution.networks.is_empty();
    if needs_bank {
        // A driver of an unpacked-array net has one contribution MEMORY (a row
        // per element); a user-nettype driver's rows start at the data type's
        // default value, not `z` (6.7.3).
        let n = resolution.bank_widths.len();
        let mut mem_rows = vec![0u32; n];
        let mut fills: Vec<Vec<sv_lang::Bit>> = vec![Vec::new(); n];
        for (&slot, t) in &resolution.bank_mem {
            if let SignalSlotClass::Memory { num_rows, .. } = t.class {
                mem_rows[slot as usize] = num_rows;
            }
        }
        for g in &resolution.groups {
            let Some(t) = g.user else { continue };
            for (&(slot, _), row) in g.drivers.iter().zip(&g.driver_rows) {
                if row.is_some() {
                    fills[slot as usize] = user_nets.types[t].init.clone();
                }
            }
        }
        // A specify path's staging cell starts `x`, not `z` (LRM 30.5.1: the
        // path destination is `x` until its first transition): a driver that
        // settles to `z` at start is then a real `x -> z` change the retimer
        // sees, and a driver that never ran stays `x`.
        for r in &specify_plans.retimers {
            if r.staging.inst == bank_id.0 {
                fills[r.staging.slot.slot as usize] =
                    vec![sv_lang::Bit::X; r.staging.slot.width as usize];
            }
        }
        // SAFETY: as for the instance templates above.
        unsafe {
            templates.register(
                bank_key,
                vj_sim::state::synthetic_z_layout_rows(&resolution.bank_widths, &mem_rows, &fills),
            );
        }
    }
    // Each resolved driver whose code runs in an instance (a continuous
    // assign, or a port connection compiled into the parent) reaches its
    // contribution cell through a foreign slot of that instance.
    // A delayed continuous assignment writes its staging cell instead.
    let mut kernel_slots = resolution.contrib.clone();
    kernel_slots.extend(prim_plans.staged.iter().map(|(k, s)| (k.clone(), *s)));
    kernel_slots.extend(
        prim_plans
            .hidden
            .iter()
            .enumerate()
            .map(|(n, h)| (crate::nets::DriverKey::Hidden(h.inst, n as u32), h.cell)),
    );
    // `primitives::plan`'s own `specify_dests` check (Task 9) guarantees
    // this never collides: a destination `specify_plans.staged` redirects
    // is always in `specify_dests`, so `primitives::plan` deferred to it
    // rather than ALSO inserting into `prim_plans.staged` -- a last, cheap,
    // independent check anyway, so a future change that weakens that
    // guarantee fails LOUDLY here rather than silently losing one
    // subsystem's redirect to `HashMap::extend`'s own last-write-wins
    // behavior.
    for key in specify_plans.staged.keys() {
        if prim_plans.staged.contains_key(key) {
            return Err(RunError::Lowering(LoweringError::unsupported(
                &format!(
                    "internal: a continuous assignment's own staging slot ({key:?}) was \
                     claimed by BOTH `primitives::plan` and `specify::plan` -- `primitives::\
                     plan`'s own `specify_dests` deferral (LRM 30.6, Task 9) should make this \
                     unreachable"
                ),
                "specify path",
            )));
        }
    }
    kernel_slots.extend(specify_plans.staged.iter().map(|(k, s)| (k.clone(), *s)));
    let mut contrib_by_inst: HashMap<InstanceId, Vec<(crate::nets::DriverKey, u32)>> =
        HashMap::new();
    for (key, &slot) in &kernel_slots {
        let owner = match key {
            crate::nets::DriverKey::Assign(inst, _, _)
            | crate::nets::DriverKey::Hidden(inst, _) => Some(*inst),
            crate::nets::DriverKey::Port(child, port, _) => {
                let inst = elaborated.instance_symbol(*child);
                let compiled = compiled_port_connections(&inst)
                    .iter()
                    .any(|(p, _)| p.uid() == *port);
                if compiled {
                    elaborated.instance(*child).parent
                } else {
                    None
                }
            }
            // A primitive writes its cells natively.
            crate::nets::DriverKey::Prim(..) | crate::nets::DriverKey::PrimElem(..) => None,
            // A module path's own retimer writes its cells natively too
            // (`docs/superpowers/plans/2026-10-03-sdf.md` Task 4a) -- see
            // `DriverKey::SpecifyPath`'s own doc comment.
            crate::nets::DriverKey::SpecifyPath(..) => None,
            // Task 4b: a specify-path VARIABLE destination's real driver is
            // the nonblocking-assignment STATEMENT itself, which runs in
            // the SAME instance that declares it (never compiled as a
            // separate per-driver function the way a continuous assign is)
            // -- so, exactly like `DriverKey::Assign`, its foreign staging
            // slot is added to THAT instance's own `contrib_by_inst` entry,
            // consulted below (`specify_dest_redirect`) when lowering that
            // instance's processes.
            crate::nets::DriverKey::ProcVar(inst, _) => Some(*inst),
        };
        if let Some(owner) = owner {
            contrib_by_inst
                .entry(owner)
                .or_default()
                .push((key.clone(), slot));
        }
    }
    // A bank slot's description: a plain cell, or (a driver of an
    // unpacked-array net) a memory shaped like that net.
    let bank_slot_of = |slot: u32| match resolution.bank_mem.get(&slot) {
        Some(net_slot) => SignalSlot { slot, ..*net_slot },
        None => crate::primitives::bank_slot(slot, resolution.bank_widths[slot as usize]),
    };
    // A resolved driver's foreign slot in the instance its code runs in.
    let mut driver_slot: HashMap<crate::nets::DriverKey, SignalSlot> = HashMap::new();
    let mut instance_refs: HashMap<InstanceId, Vec<ForeignRef<'_>>> = HashMap::new();
    let ref_aliases = ref_port_aliases(
        &elaborated,
        &registration_order,
        &instance_signals,
        &body_id_to_instance,
    )?;
    let mut class_refs: Option<Vec<Symbol<'_>>> = None;
    for &id in &registration_order {
        let body = instance_body_of(&elaborated, id, path)?;
        let (mut refs, class_code) = foreign_references(
            &body,
            id,
            &instance_signals,
            &body_id_to_instance,
            &ref_aliases,
            &syntax_trees,
        );
        // Constructors and class methods run code (overrides, virtual calls)
        // the static walk cannot follow, which may read any package variable
        // (UVM's `uvm_sequence::new` reads `build_ph`): give the instance a
        // foreign slot for each. Designs with no class code pay nothing.
        if class_code {
            // A class method's `vif.m` (LRM 25.9) names the member of every
            // candidate instance of the interface: each is a signal this
            // instance's processes reach through the method, wherever the
            // call dispatches (UVM drivers/monitors hold `virtual` ifs).
            let class_syms = class_refs.get_or_insert_with(|| {
                let bodies = netlist::class_method_symbols(&eval)
                    .into_iter()
                    .filter_map(|m| vj_sim::process::cfg::proc_body(&m))
                    .map(|b| b.as_sem_node())
                    .collect();
                referenced_values(bodies)
            });
            refs.extend(foreign_references_of_symbols(
                class_syms.clone(),
                id,
                &instance_signals,
                &body_id_to_instance,
                &ref_aliases,
            ));
            for (pid, _, pkg) in &packages {
                for v in vj_sim::netlist::state_items(pkg) {
                    if v.kind() == SymbolKind::Variable
                        && let Some(&slot) = instance_signals[pid].get(&v.uid())
                    {
                        refs.push((v, v, *pid, slot, None));
                    }
                }
            }
        }
        instance_refs.entry(id).or_default().extend(refs);
        // Every `ref` port variable of this instance names its actual's cell,
        // whether or not its code ever mentions the port (a waveform dump, a
        // VPI handle and a hierarchical name still reach it).
        for body_port in vj_sim::netlist::module_items(&body) {
            if let Some(&(owner, slot, window)) = ref_aliases.get(&(id, body_port.uid())) {
                instance_refs
                    .entry(id)
                    .or_default()
                    .push((body_port, body_port, owner, slot, window));
            }
        }
        // A port connection compiled as a continuous assignment in the
        // parent (`compiled_port_connections`) reaches the child's port
        // variable from the parent.
        if let Some(parent) = elaborated.instance(id).parent {
            for (port, expr) in compiled_port_connections(&elaborated.instance_symbol(id)) {
                // The connection expression is in the parent's scope and may
                // name a package or compilation-unit variable (LRM 23.3.3).
                let refs = foreign_references_of_roots(
                    vec![expr.as_sem_node()],
                    parent,
                    &instance_signals,
                    &body_id_to_instance,
                    &ref_aliases,
                );
                instance_refs.entry(parent).or_default().extend(refs);
                let member = port.port_internal_symbol().unwrap_or(port);
                if let Some(&slot) = instance_signals[&id].get(&member.uid()) {
                    instance_refs
                        .entry(parent)
                        .or_default()
                        .push((member, member, id, slot, None));
                }
            }
        }
    }
    // A package variable's initializer may read another package's variable
    // (`integer y = x;` with `x` imported from `P1`, LRM 26.3): the package's
    // state instance reaches it through a foreign slot like any instance.
    for (pid, _, pkg) in &packages {
        let roots = discover_variable_initializers(pkg)
            .into_iter()
            .map(|v| v.assign_expr.as_sem_node())
            .collect();
        let refs = foreign_references_of_roots(
            roots,
            *pid,
            &instance_signals,
            &body_id_to_instance,
            &ref_aliases,
        );
        instance_refs.entry(*pid).or_default().extend(refs);
    }
    // A class's dynamic static initializer (`static bit r = reg();`) runs in
    // its owner's state instance (below, where its kernel is built) and may
    // reach, through the subroutines it calls, variables of other packages
    // (UVM's `build_ph`): those need foreign slots in that instance too.
    for cls in netlist::classes_with_dynamic_static_init(&eval) {
        let Some(&first) = registration_order.first() else {
            break;
        };
        let owner = std::iter::successors(cls.parent(), |s| s.parent())
            .find_map(|anc| packages.iter().find(|(_, _, p)| p.uid() == anc.uid()))
            .map_or(first, |(pid, _, _)| *pid);
        let roots = netlist::classify_members(cls)
            .map(|m| m.statics)
            .unwrap_or_default()
            .iter()
            .filter_map(|s| s.initializer())
            .map(|e| e.as_sem_node())
            .collect();
        let mut refs = foreign_references_of_roots(
            roots,
            owner,
            &instance_signals,
            &body_id_to_instance,
            &ref_aliases,
        );
        // What the initializer reaches through constructors (`new`), virtual
        // methods and other calls the walk above cannot follow statically is
        // any package variable (UVM: `uvm_callbacks::get()` ... `build_ph`),
        // so every other package's variables are visible to the kernel.
        for (pid, _, pkg) in &packages {
            if *pid == owner {
                continue;
            }
            for v in vj_sim::netlist::state_items(pkg) {
                if v.kind() == SymbolKind::Variable
                    && let Some(&slot) = instance_signals[pid].get(&v.uid())
                {
                    refs.push((v, v, *pid, slot, None));
                }
            }
        }
        instance_refs.entry(owner).or_default().extend(refs);
    }
    type ForeignTarget = (InstanceId, u32, Option<AliasWindow>);
    let mut instance_foreign: HashMap<InstanceId, (u32, Vec<ForeignTarget>)> = HashMap::new();
    let foreign_owners: Vec<(InstanceId, TemplateKey)> = registration_order
        .iter()
        .map(|&id| (id, *elaborated.dedup_key(elaborated.instance(id).template)))
        .chain(packages.iter().map(|(id, key, _)| (*id, *key)))
        .collect();
    // Group mode (`event_plan::group_mode`): event ids are tagged with the pool
    // they belong to, so every pool-mode instance reaches every pool-mode
    // instance's pool (its own included) under `peer_key(tag - 1)`.
    let event_peers: Vec<(InstanceId, SignalSlot)> = if vj_sim::state::event_plan::group_mode() {
        registration_order
            .iter()
            .filter_map(|&id| {
                instance_signals
                    .get(&id)?
                    .get(&vj_sim::state::event_pool::pool_key())
                    .map(|&p| (id, p))
            })
            .collect()
    } else {
        Vec::new()
    };
    for (id, key) in foreign_owners {
        let own = templates
            .layout_of(&key)
            .expect("every instance's template layout was registered above")
            .slots
            .len() as u32;
        let refs = instance_refs.remove(&id).unwrap_or_default();
        let mut contribs = contrib_by_inst.remove(&id).unwrap_or_default();
        let pooled_peer = event_peers.iter().any(|&(p, _)| p == id);
        if refs.is_empty() && contribs.is_empty() && !pooled_peer {
            continue;
        }
        let mut targets: Vec<ForeignTarget> = Vec::new();
        contribs.sort_by_key(|(_, slot)| *slot);
        for (key, slot) in contribs {
            targets.push((bank_id, slot, None));
            driver_slot.insert(
                key,
                SignalSlot {
                    slot: own + targets.len() as u32 - 1,
                    ..bank_slot_of(slot)
                },
            );
        }
        let mut added = Vec::new();
        for (sym, target, owner, slot, window) in refs {
            if owner == id && window.is_none() {
                // The instance's own cell (a parent naming `u.r` whose
                // actual lives in the parent itself): no second slot number
                // for one cell.
                added.push((sym.uid(), slot));
                added.push((target.uid(), slot));
                continue;
            }
            let k = match targets
                .iter()
                .position(|&t| t == (owner, slot.slot, window))
            {
                Some(k) => k,
                None => {
                    targets.push((owner, slot.slot, window));
                    targets.len() - 1
                }
            };
            let foreign = SignalSlot {
                slot: own + k as u32,
                ..slot
            };
            added.push((sym.uid(), foreign));
            added.push((target.uid(), foreign));
            // A static event of an instance that keeps its events in a pool
            // (`state::event_pool`): this instance reaches the owner's pool
            // memory too, as the event's row range and as the pool (whose
            // handle cells decide which object the event names), so a
            // hierarchical `-> s.ev`, `@(s.ev)` or `s.ev.triggered` acts on
            // the pool row (LRM 1800-2023 15.5, 23.6).
            if owner != id {
                for key in [
                    vj_sim::state::event_pool::static_key(&target.uid()),
                    vj_sim::state::event_pool::pool_of_key(&target.uid()),
                ] {
                    let Some(&pool_slot) = instance_signals[&owner].get(&key) else {
                        continue;
                    };
                    let k = match targets
                        .iter()
                        .position(|&t| t == (owner, pool_slot.slot, None))
                    {
                        Some(k) => k,
                        None => {
                            targets.push((owner, pool_slot.slot, None));
                            targets.len() - 1
                        }
                    };
                    added.push((
                        key,
                        SignalSlot {
                            slot: own + k as u32,
                            ..pool_slot
                        },
                    ));
                }
            }
        }
        if pooled_peer {
            for (j, &(owner, pool_slot)) in event_peers.iter().enumerate() {
                let key = vj_sim::state::event_pool::peer_key(j as u32);
                if owner == id {
                    added.push((key, pool_slot));
                    continue;
                }
                let k = match targets
                    .iter()
                    .position(|&t| t == (owner, pool_slot.slot, None))
                {
                    Some(k) => k,
                    None => {
                        targets.push((owner, pool_slot.slot, None));
                        targets.len() - 1
                    }
                };
                added.push((
                    key,
                    SignalSlot {
                        slot: own + k as u32,
                        ..pool_slot
                    },
                ));
            }
        }
        instance_signals
            .get_mut(&id)
            .expect("filled above")
            .extend(added);
        instance_foreign.insert(id, (own, targets));
    }
    // Task 4b (`docs/superpowers/plans/2026-10-03-sdf.md`): every specify-
    // path VARIABLE destination's own foreign staging slot (`DriverKey::
    // ProcVar`, just resolved above into `driver_slot` the SAME way a
    // redirected continuous assign's `DriverKey::Assign` entry is -- already
    // a ready-to-use foreign-index `SignalSlot`, never re-derived here),
    // grouped by the instance whose process writes it -- handed to EVERY
    // process of that instance below. Safe to hand to a process that never
    // references the destination at all: `LowerCtx::specify_dest`'s only
    // two consumers (`select::resolve_lvalue`'s `RootMode::Signal` branch
    // and `lower_nonblocking_assignment`'s fast-path exclusion) both key off
    // the WRITE's own lvalue symbol, never iterate this table blindly.
    let mut specify_dest_redirect: HashMap<InstanceId, HashMap<SymbolId, SignalSlot>> =
        HashMap::new();
    for (key, slot) in &driver_slot {
        if let crate::nets::DriverKey::ProcVar(inst, sym) = key {
            specify_dest_redirect
                .entry(*inst)
                .or_default()
                .insert(sym.clone(), *slot);
        }
    }
    let mut next_kernel_idx: usize = 0;
    let mut next_cont_assign_idx: usize = 0;
    let mut cov_roots: HashMap<InstanceId, Vec<SemNode<'_>>> = HashMap::new();
    for &id in &registration_order {
        let body = instance_body_of(&elaborated, id, path)?;
        let processes: Vec<DiscoveredProcess<'_>> =
            discover_processes_dispatching(&body, &comb_sensitivity, Some(&virtual_tasks))
                .map_err(RunError::Lowering)?;
        let signals = instance_signals[&id].clone();
        let procedural_checkers = vj_sim::netlist::procedural_checkers(&body);
        // What `##N` counts (`crate::clocking`).
        let default_clocking = crate::clocking::default_clocking(&body, &syntax_trees);

        // 16.14.6: the plan index of the host of each procedural assertion this
        // instance's processes reach (`discover_processes` lists a host right
        // after the process it is nested in), for the queueing processes.
        let nested_assertions: HashMap<String, usize> = processes
            .iter()
            .enumerate()
            .filter_map(|(j, p)| {
                let h = p.assertion.filter(|h| h.procedural)?;
                Some((h.queue_key(&p.sym), next_kernel_idx + j))
            })
            .collect();

        // 16.14.6.4: what a `disable` may name in this instance -- for every
        // process (not a plan hosting an assertion) its outermost named block
        // with the assertions queued from it, and the labels of those
        // assertions.
        let scopes: Vec<Option<DisableScope>> = processes
            .iter()
            .enumerate()
            .map(|(j, p)| {
                if p.assertion.is_some() {
                    return None;
                }
                let root = vj_sim::process::cfg::proc_body(&p.sym)?;
                let queued: Vec<(usize, Statement<'_>)> = processes
                    .iter()
                    .enumerate()
                    .filter_map(|(k, h)| {
                        let h = h.assertion.filter(|h| h.procedural)?;
                        (processes[k].sym == p.sym).then_some((next_kernel_idx + k, h.stmt))
                    })
                    .collect();
                let labels = vj_sim::process::cfg::assertion_labels(&root)
                    .into_iter()
                    .filter_map(|(label, stmt)| {
                        let at = stmt.source_range().start;
                        let (key, _) = queued.iter().find(|(_, h)| h.source_range().start == at)?;
                        Some((label, *key))
                    })
                    .collect();
                Some(DisableScope {
                    process: j,
                    block: vj_sim::process::cfg::peer_block(&root),
                    nested: vj_sim::process::cfg::nested_peer_blocks(&root),
                    paths: vj_sim::process::cfg::named_block_paths(&root),
                    // The process's own key too: its outermost scope's `disable`
                    // flushes its deferred assertion queue (16.4.4).
                    keys: queued
                        .iter()
                        .map(|(k, _)| *k)
                        .chain(std::iter::once(
                            (next_kernel_idx + j)
                                | vj_sim::sched::proc_assert::PROCESS_KEY_FLAG as usize,
                        ))
                        .collect(),
                    labels,
                })
            })
            .collect();
        {
            let inst_path = elaborated.instance_symbol(id).hierarchical_path();
            for s in scopes.iter().flatten() {
                for b in s.block.iter().chain(&s.nested).filter(|b| !b.can_suspend) {
                    inert_blocks.insert(format!("{inst_path}.{}", b.name));
                }
            }
        }

        for (j, proc) in processes.iter().enumerate() {
            let root = match proc.assertion.filter(|h| h.procedural) {
                Some(h) => h.stmt,
                None => vj_sim::process::cfg::proc_body(&proc.sym).ok_or_else(|| {
                    RunError::Lowering(LoweringError::unsupported_at(
                        "procedural block has no body statement",
                        &proc.sym,
                    ))
                })?,
            };
            // R-run Task 10 review fix (r1): this process's own body is one
            // of `discover_called_subroutines`' own reachability roots
            // (collected here, resolved once after the whole per-instance
            // loop below finishes -- see `call_roots`'s own doc comment).
            call_roots.push(root.as_sem_node());
            // Where this instance's covergroups are constructed.
            cov_roots.entry(id).or_default().push(root.as_sem_node());
            // 17.3: the deferred assertions of the procedural checker
            // instances this process instantiates run in it.
            if proc.assertion.is_none() {
                for pc in procedural_checkers.iter().filter(|c| c.block == proc.sym) {
                    for block in vj_sim::netlist::module_items(&pc.instance) {
                        if let Some(d) = vj_codegen::module::static_deferred_assertion_of(&block) {
                            call_roots.push(d.as_sem_node());
                        }
                    }
                }
            }
            // `force`/`assign` (`vj_codegen::force`): writes must then
            // re-read their target, and a forced expression that reads
            // signals gets a continuous driver of its own.
            if vj_codegen::force::contains_force(root.as_sem_node()) {
                vj_codegen::force::note_design_forces();
            }
            for (site, assign) in vj_codegen::force::force_drivers(root.as_sem_node()) {
                let read_set = assign
                    .right()
                    .map(vj_codegen::module::cont_assign_read_set)
                    .unwrap_or_default();
                cont_assign_specs.push(ContAssignLoweringSpec {
                    fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                    fn_sym: proc.sym,
                    assign_expr: assign,
                    net_target: None,
                    signals: signals.clone(),
                    read_signals: HashMap::new(),
                    force_site: Some(site),
                    port_source: None,
                    var_init: false,
                    hidden_target: None,
                });
                cont_assign_meta.push((id, read_set));
                next_cont_assign_idx += 1;
            }
            // 16.17: the plan hosting an `expect` for the assertion engine holds
            // it as a leaf; the process that blocks on it is another plan.
            let hosts_expect = proc
                .assertion
                .is_some_and(|h| h.stmt.assertion_kind() == Some(sv_lang::AssertionKind::Expect));
            // A name two blocks of the instance share (in different scopes)
            // cannot be told apart by name: it is not a peer (the `disable`
            // is then a named lowering error) -- unless every holder is a
            // fork branch, which the runtime scan ends all at once (9.6.2).
            let mut name_uses: HashMap<&str, usize> = HashMap::new();
            let mut non_branch: HashSet<&str> = HashSet::new();
            for s in scopes.iter().flatten() {
                for b in s.block.iter().chain(&s.nested) {
                    *name_uses.entry(b.name.as_str()).or_default() += 1;
                    if !b.fork_branch {
                        non_branch.insert(b.name.as_str());
                    }
                }
            }
            let peers: Vec<vj_sim::process::cfg::PeerBlock> = scopes
                .iter()
                .flatten()
                .filter(|s| s.process != j)
                .flat_map(|s| s.block.iter().chain(&s.nested))
                .filter(|b| {
                    name_uses[b.name.as_str()] == 1 || !non_branch.contains(b.name.as_str())
                })
                .cloned()
                .collect();
            let checker_clock = crate::clocking::checker_inferred_clock(&proc.sym, &syntax_trees)
                .map_err(|msg| {
                RunError::Lowering(LoweringError::unsupported_at(&msg, &proc.sym))
            })?;
            let cfg = if hosts_expect {
                vj_sim::process::cfg::build_cfg_hosted_assertion(&root, default_clocking)
            } else {
                vj_sim::process::cfg::build_cfg_scoped_with_virtuals(
                    &root,
                    loop_kind_of(proc.kind),
                    default_clocking,
                    &peers,
                    checker_clock,
                    crate::clocking::global_clock_event(&proc.sym, &syntax_trees).map_err(
                        |msg| RunError::Lowering(LoweringError::unsupported_at(&msg, &proc.sym)),
                    )?,
                    Some(virtual_tasks.clone()),
                )
            }
            .map_err(|e| sim_lowering_to_run_error(e, path))?;
            // PR-085: `fork ... join`/`join_any`/`join_none` run for real --
            // each branch is its own compiled kernel, minted as a child
            // process by its parent (`CompiledKernelProcess::mint_fork_child`).
            let frame = compute_liveness(&cfg).map_err(|e| sim_lowering_to_run_error(e, path))?;
            let frame_words = total_frame_words(&frame);
            let segments = lower_to_segments(&cfg, &frame);
            // A bound `ref` formal of an inlined task names its actual's
            // storage (LRM 13.5.2, `ProcessCfg::ref_bindings`).
            let mut proc_signals = signals.clone();
            for (formal, actual) in &cfg.ref_bindings {
                let slot = signals.get(&actual.uid()).cloned().ok_or_else(|| {
                    RunError::Lowering(LoweringError::unsupported_at(
                        &format!(
                            "`ref` argument `{}` is bound to `{}`, which is not storage of this \
                             instance",
                            formal.name(),
                            actual.name()
                        ),
                        &proc.sym,
                    ))
                })?;
                proc_signals.insert(formal.uid(), slot);
            }
            let mut plan = build_lowering_plan(
                format!("vj_proc_{next_kernel_idx}"),
                proc.sym,
                segments,
                frame,
                proc_signals,
            );
            // Review fix (Task 9, CG-101 r2): `id` is this outer loop's own
            // real elaborated `InstanceId` (the current `registration_order`
            // entry) -- every process discovered from this instance's body
            // shares it, which is exactly what `pipeline::
            // side_tables_for_plans` groups by to derive
            // `canonical_process_id` (see `ProcessLoweringPlan::
            // owning_instance`'s own doc comment).
            plan.owning_instance = id;
            plan.disable_broadcast = cfg.disable_broadcast.clone();
            // LRM 9.6.2 `disable u1.blk;` from another instance: each scope is
            // also registered under the instance-path keys
            // `<requester instance id>/<path>` and `/<absolute path>`, so the
            // runtime finds a block of a descendant instance from the
            // requester's id (`drain_pending_disable_scope`).
            for (label, _) in cfg
                .disable_broadcast
                .iter()
                .cloned()
                .chain(cfg.branch_disable_broadcast())
            {
                if label.contains('.') {
                    instance_path_disables.push((id.0, label.clone()));
                }
            }
            let own_path = elaborated.instance_symbol(id).hierarchical_path();
            let ancestors: Vec<(u32, String)> = {
                let segs: Vec<&str> = own_path.split('.').collect();
                (1..segs.len())
                    .filter_map(|k| {
                        let anc = segs[..k].join(".");
                        let aid = instance_ids_by_path.get(&anc)?;
                        Some((*aid, segs[k..].join(".")))
                    })
                    .collect()
            };
            let scope_keys = std::sync::Arc::new(vj_codegen::process_lower::DisableScopeKeys {
                instance: id.0,
                own_path: own_path.clone(),
                ancestors,
                ext_aliases: ext_aliases.clone(),
            });
            let mut scope_rows: Vec<(u32, String, u32)> = cfg
                .disable_scopes
                .iter()
                .flat_map(|(resume, label, exit)| scope_keys.expand(resume.0, label, exit.0))
                .collect();
            // LRM 9.6.2 `disable s.outer.inner;` (a descendant instance's fork
            // branch `inner`, reached through an enclosing named block `outer`
            // of its process): ownership rows `outer.inner` that no resume
            // point ever matches (`u32::MAX`), so only
            // `drain_pending_disable_scope` finds the owning process by key
            // and ends the branch by its name.
            // `disable g[0].bk;` (a block of a process inside generate block
            // `g[0]`): every scope row also under the generate-qualified label.
            let proc_path = proc.sym.hierarchical_path();
            if let Some(gen_path) = proc_path
                .strip_prefix(own_path.as_str())
                .and_then(|r| r.strip_prefix('.'))
                .filter(|g| !g.is_empty())
            {
                let rows: Vec<(u32, String, u32)> = cfg
                    .disable_scopes
                    .iter()
                    .map(|(r, l, e)| (r.0, l.clone(), e.0))
                    .collect();
                for (resume, label, exit) in rows {
                    scope_rows.extend(scope_keys.expand(
                        resume,
                        &format!("{gen_path}.{label}"),
                        exit,
                    ));
                }
            }
            if let Some(own) = &scopes[j] {
                let mut enclosing: Vec<String> = own
                    .block
                    .iter()
                    .chain(&own.nested)
                    .map(|b| b.name.clone())
                    .collect();
                // `outer.mid.inner`: the outermost block then one nested block.
                if let Some(o) = &own.block {
                    enclosing.extend(own.nested.iter().map(|n| format!("{}.{}", o.name, n.name)));
                }
                let labels = cfg.branch_disable_labels();
                for l in &labels {
                    for e in &enclosing {
                        scope_rows.extend(scope_keys.expand(u32::MAX, &format!("{e}.{l}"), 0));
                    }
                }
                // `disable s.a.b.c.inner;`: a branch block at any depth is named
                // by its full path from the outermost block (9.6.2).
                for p in &own.paths {
                    if p.rsplit('.')
                        .next()
                        .is_some_and(|leaf| labels.iter().any(|l| l == leaf))
                    {
                        scope_rows.extend(scope_keys.expand(u32::MAX, p, 0));
                    }
                }
            }
            kernel_disable_scopes.push(scope_rows.into());
            branch_scope_labels.extend(cfg.branch_disable_labels().into_iter().flat_map(|l| {
                scope_keys
                    .expand(0, &l, 0)
                    .into_iter()
                    .map(|(_, k, _)| k)
                    .collect::<Vec<_>>()
            }));
            plan.disable_scope_keys = Some(scope_keys);
            plan.hosted_assertion = proc.assertion;
            // 17.4: a checker procedure that reads `$inferred_disable` reads the
            // `default disable iff` signal of its instantiation (an `always_ff`
            // its sampled value, 17.5: `checker_ff_sampled_signals`).
            let mut read_set = proc.read_set.clone();
            if proc.assertion.is_none() {
                plan.inferred_disable =
                    vj_codegen::module::procedure_inferred_disable(&proc.sym, &syntax_trees)
                        .map_err(RunError::Lowering)?
                        .map(|state| state.map(|(sym, negate)| (sym.uid(), negate)));
                if let Some(Some((id, _))) = &plan.inferred_disable
                    && matches!(
                        proc.kind,
                        SliceProcKind::AlwaysComb | SliceProcKind::AlwaysLatch
                    )
                    && !read_set.contains(id)
                {
                    read_set.push(id.clone());
                }
            }
            if proc.assertion.is_none() {
                plan.nested_assertions = nested_assertions.clone();
            }
            if let Some(own) = &scopes[j] {
                // The other processes' blocks first: the process's own names
                // (inner scope) win a clash.
                for other in scopes.iter().flatten().filter(|s| s.process != j) {
                    if let Some(block) = &other.block {
                        plan.disable_keys
                            .insert(block.name.clone(), other.keys.clone());
                    }
                    // A nested block has no assertion queue of its own to
                    // clear (16.14.6.4 names the outermost scope).
                    for block in &other.nested {
                        plan.disable_keys.entry(block.name.clone()).or_default();
                    }
                }
                if let Some(block) = &own.block {
                    plan.disable_keys
                        .insert(block.name.clone(), own.keys.clone());
                }
                for (label, key) in &own.labels {
                    plan.disable_keys.insert(label.clone(), vec![*key]);
                }
            }
            // Task 4b: this instance's own specify-path variable-
            // destination redirect table (empty for every instance with no
            // such destination -- the overwhelmingly common case, and
            // `LowerCtx::specify_dest`'s doc comment is the real "default
            // means unaffected" guarantee this relies on).
            plan.specify_dest_redirect =
                specify_dest_redirect.get(&id).cloned().unwrap_or_default();
            let reads_inferred_disable = plan.inferred_disable.is_some();
            plans.push(plan);
            // Task 2 (CG-079): converted eagerly, here, while `proc.reset`'s
            // `Symbol<'d>` is still in scope for `to_state_edge_kind`'s own
            // error citation -- the final registration loop below only has
            // owned `SymbolId`s to work with (see `KernelSensitivitySpec`'s
            // own doc comment).
            let reset = proc
                .reset
                .map(|(sym, edge)| -> Result<_, RunError> {
                    let converted = to_state_edge_kind(edge, &sym).map_err(RunError::Lowering)?;
                    Ok((sym.uid(), converted))
                })
                .transpose()?;
            // LRM 9.2.2.2.1: a signal the body reads only through constant
            // selects is sensitive to those bits (the longest static prefix),
            // not the whole variable. Not narrowed when the process also reads
            // through paths the walk cannot see (nested assertions, the
            // inferred `disable iff` signal).
            let windows = if matches!(
                proc.kind,
                SliceProcKind::AlwaysComb | SliceProcKind::AlwaysLatch
            ) && proc.assertion.is_none()
                && nested_assertions.is_empty()
                && !reads_inferred_disable
            {
                vj_codegen::process_lower::comb_read_windows(&root, &signals)
            } else {
                HashMap::new()
            };
            let sensitivity_spec = KernelSensitivitySpec {
                read_set,
                windows,
                reset,
            };
            kernel_meta.push((
                frame_words,
                scheduler_process_kind(proc.kind),
                id,
                sensitivity_spec,
                vj_codegen::module::has_implicit_event_head(&proc.sym),
            ));
            kernel_dyn.push((body.uid(), proc.sym.uid()));
            if vj_sim::netlist::is_in_checker(&proc.sym)
                || vj_sim::netlist::is_in_program(&proc.sym)
            {
                reactive_kernels.insert(next_kernel_idx);
                if vj_sim::netlist::is_in_program(&proc.sym)
                    && matches!(proc.kind, SliceProcKind::Initial)
                {
                    program_initial_kernels.insert(next_kernel_idx);
                }
            }
            next_kernel_idx += 1;
        }

        // Task 2 (NL-034): every plain `assign` in this instance's own
        // body, resolved against this SAME instance's own `signals` map
        // (never the deduped `Template`'s `SymbolKey` numbering -- this
        // mirrors `discover_processes`'s own per-instance re-derivation
        // above, exactly the "consume `sv_lang` directly, per instance"
        // shape CG-079's own read-set already established, rather than
        // routing through `netlist::Netlist`'s `ContAssignTemplate`, which
        // is keyed by the DEDUPED `Template`'s own `SymbolKey` numbering,
        // not this loop's per-instance, undeduped `SymbolId`s).
        let cont_assigns = discover_cont_assigns(&body).map_err(RunError::Lowering)?;
        // A variable's non-constant initializer runs as a one-shot kernel,
        // ahead of this instance's continuous assigns (which may read it).
        let var_inits = discover_variable_initializers(&body);
        for (ca, var_init) in var_inits
            .iter()
            .map(|v| (v, true))
            .chain(cont_assigns.iter().map(|c| (c, false)))
        {
            // A resolved net this assign drives: its contribution cell.
            let mut signals = signals.clone();
            let roots: Vec<Symbol<'_>> = match ca.net_target {
                Some(net) => vec![net],
                None => ca
                    .assign_expr
                    .left()
                    .map(crate::nets::lvalue_roots)
                    .unwrap_or_default(),
            };
            let mut read_signals: HashMap<SymbolId, SignalSlot> = HashMap::new();
            for root in roots {
                let key = crate::nets::DriverKey::Assign(id, ca.sym.uid(), root.uid());
                if let Some(&slot) = driver_slot.get(&key) {
                    // The right-hand side still reads the net's resolved cell.
                    if let Some(&own) = signals.get(&root.uid()) {
                        read_signals.insert(root.uid(), own);
                    }
                    signals.insert(root.uid(), slot);
                }
            }
            // R-run Task 10 review fix (r1): a continuous assign's own RHS
            // is `discover_called_subroutines`' other kind of reachability
            // root (see `call_roots`'s own doc comment above).
            call_roots.push(ca.assign_expr.as_sem_node());
            cont_assign_specs.push(ContAssignLoweringSpec {
                fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                fn_sym: ca.sym,
                assign_expr: ca.assign_expr,
                net_target: ca.net_target,
                signals: signals.clone(),
                read_signals,
                force_site: None,
                port_source: None,
                var_init,
                hidden_target: None,
            });
            cont_assign_meta.push((id, ca.read_set.clone()));
            if vj_sim::netlist::is_in_checker(&ca.sym) || vj_sim::netlist::is_in_program(&ca.sym) {
                reactive_cont_assigns.insert(next_cont_assign_idx);
            }
            next_cont_assign_idx += 1;
        }

        // Each primitive input terminal expression of this instance (LRM
        // 28.3): a kernel storing its value into the terminal's hidden cell.
        for (n, h) in prim_plans.hidden.iter().enumerate() {
            if h.inst != id {
                continue;
            }
            let slot = driver_slot[&crate::nets::DriverKey::Hidden(id, n as u32)];
            call_roots.push(h.expr.as_sem_node());
            cont_assign_specs.push(ContAssignLoweringSpec {
                fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                fn_sym: h.prim,
                assign_expr: h.expr,
                net_target: None,
                signals: signals.clone(),
                read_signals: HashMap::new(),
                force_site: None,
                port_source: None,
                var_init: false,
                hidden_target: Some(SignalSlot {
                    signed: false,
                    ..slot
                }),
            });
            cont_assign_meta.push((id, vj_codegen::module::cont_assign_read_set(h.expr)));
            next_cont_assign_idx += 1;
        }

        // Each checker instance's connected output formals (LRM 17.3): the
        // checker's items run in this instance (`module_items`), so the
        // formal and its actual are both slots here, and the connection is
        // slang's `actual = <formal>` assignment -- an output port's shape.
        for checker in vj_sim::netlist::checker_instances(&body) {
            for out in vj_sim::netlist::checker_outputs(&checker) {
                let Some(assign) = out.assign else {
                    continue;
                };
                call_roots.push(assign.as_sem_node());
                let mut out_signals = signals.clone();
                for root in assign
                    .left()
                    .map(crate::nets::lvalue_roots)
                    .unwrap_or_default()
                {
                    let key = crate::nets::DriverKey::Assign(id, out.formal.uid(), root.uid());
                    if let Some(&slot) = driver_slot.get(&key) {
                        out_signals.insert(root.uid(), slot);
                    }
                }
                cont_assign_specs.push(ContAssignLoweringSpec {
                    fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                    fn_sym: out.formal,
                    assign_expr: assign,
                    net_target: None,
                    signals: out_signals,
                    read_signals: HashMap::new(),
                    force_site: None,
                    port_source: Some(out.formal),
                    var_init: false,
                    hidden_target: None,
                });
                cont_assign_meta.push((id, vec![out.formal.uid()]));
                // 17.3: "as if there were continuous assignments, executed in
                // the Reactive region".
                reactive_cont_assigns.insert(next_cont_assign_idx);
                next_cont_assign_idx += 1;
            }
        }

        // This instance's port connections that are not wired natively,
        // each a continuous assignment in the PARENT (its expression is in
        // the parent's scope; the port's variable is a foreign slot there).
        if let Some(parent) = elaborated.instance(id).parent {
            let inst = elaborated.instance_symbol(id);
            for (port, expr) in compiled_port_connections(&inst) {
                call_roots.push(expr.as_sem_node());
                let member = port.port_internal_symbol().unwrap_or(port);
                let input = port.port_direction() == ArgumentDirection::In;
                // A resolved net the connection drives: its contribution.
                let mut port_signals = instance_signals[&parent].clone();
                let targets: Vec<Symbol<'_>> = if input {
                    vec![member]
                } else {
                    expr.left()
                        .map(crate::nets::lvalue_roots)
                        .unwrap_or_default()
                };
                for t in targets {
                    let key = crate::nets::DriverKey::Port(id, port.uid(), t.uid());
                    if let Some(&slot) = driver_slot.get(&key) {
                        port_signals.insert(t.uid(), slot);
                    }
                }
                let read_set = if input {
                    vj_codegen::module::cont_assign_read_set(expr)
                } else {
                    vec![member.uid()]
                };
                cont_assign_specs.push(ContAssignLoweringSpec {
                    fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                    fn_sym: port,
                    assign_expr: expr,
                    net_target: input.then_some(member),
                    signals: port_signals,
                    read_signals: HashMap::new(),
                    force_site: None,
                    port_source: (!input).then_some(member),
                    var_init: false,
                    hidden_target: None,
                });
                cont_assign_meta.push((parent, read_set));
                next_cont_assign_idx += 1;
            }
        }
    }

    // A package variable's non-constant initializer (`C bar = new;`,
    // `int k = f();`; LRM 26.2, 6.8) is a one-shot time-zero kernel in the
    // package's own state instance, like a module variable's above.
    for (pid, _, pkg) in &packages {
        for v in discover_variable_initializers(pkg) {
            call_roots.push(v.assign_expr.as_sem_node());
            cont_assign_specs.push(ContAssignLoweringSpec {
                fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                fn_sym: v.sym,
                assign_expr: v.assign_expr,
                net_target: v.net_target,
                signals: instance_signals[pid].clone(),
                read_signals: HashMap::new(),
                force_site: None,
                port_source: None,
                var_init: true,
                hidden_target: None,
            });
            cont_assign_meta.push((*pid, Vec::new()));
            next_cont_assign_idx += 1;
        }
    }

    // A class's static property initialized by a non-constant expression
    // (`static bit m__initialized = reg();`, LRM 6.21 / 8.9) runs once at time
    // zero whether or not anything reads it (UVM registers every
    // `uvm_*_utils` type this way): one time-zero kernel per such class
    // specialization the design names, in the state instance of the package
    // that declares it (or of the first instance, for a `$unit` class).
    for cls in netlist::classes_with_dynamic_static_init(&eval) {
        let Some(&first) = registration_order.first() else {
            break;
        };
        let owner = std::iter::successors(cls.parent(), |s| s.parent())
            .find_map(|anc| packages.iter().find(|(_, _, p)| p.uid() == anc.uid()))
            .map_or(first, |(pid, _, _)| *pid);
        // The kernel materializes the whole singleton, so every static's
        // initializer is a reachability root for called subroutines.
        let statics = netlist::classify_members(cls)
            .map(|m| m.statics)
            .unwrap_or_default();
        for init in statics.iter().filter_map(|s| s.initializer()) {
            call_roots.push(init.as_sem_node());
        }
        let Some((prop, init)) = statics.iter().find_map(|s| {
            s.initializer()
                .filter(|e| e.constant_value().is_none())
                .map(|e| (*s, e))
        }) else {
            continue;
        };
        cont_assign_specs.push(ContAssignLoweringSpec {
            fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
            fn_sym: prop,
            assign_expr: init,
            net_target: Some(prop),
            signals: instance_signals[&owner].clone(),
            read_signals: HashMap::new(),
            force_site: None,
            port_source: None,
            var_init: true,
            hidden_target: None,
        });
        cont_assign_meta.push((owner, Vec::new()));
        next_cont_assign_idx += 1;
    }

    // R-run Task 10 review fix (r1): resolved ONCE, over every root
    // `call_roots` collected across every elaborated instance above --
    // never per-instance-body enumeration (see `module::
    // discover_called_subroutines`'s own doc comment for why: a
    // never-called function/task, of any shape, must stay untouched by
    // this pipeline, exactly as it was before R-run Task 10 existed). No
    // per-subroutine signal map needed (a subroutine's own args/locals are
    // its own LLVM `alloca`s, never `signals`-mapped external state),
    // unlike `processes`/`cont_assigns` above.
    // Covergroups (`crate::covergroups`): compiled per instance; a kernel
    // may call a function, so its expressions are reachability roots too.
    let cov_packages: Vec<_> = eval.design().packages().collect();
    let cov_units: Vec<_> = eval.design().compilation_units().collect();
    let mut cov_plan = crate::covergroups::plan(
        &bodies,
        &cov_packages,
        &cov_units,
        &instance_signals,
        &cov_roots,
        &syntax_trees,
    )
    .map_err(RunError::Lowering)?;
    // The clocking blocks' `iff` gates ride in `specs` after the covergroups'
    // (`covergroups::image` pairs specs with extracts and stops at the latter).
    cov_plan.specs.extend(
        crate::clocking::gate_specs(&bodies, &instance_signals, &syntax_trees)
            .map_err(RunError::Lowering)?,
    );
    for spec in &cov_plan.specs {
        call_roots.extend(spec.kernels.iter().map(|k| k.expr.as_sem_node()));
        call_roots.extend(spec.gates.iter().map(|g| g.as_sem_node()));
    }
    let (mut called, inlined) =
        discover_called_subroutines_inlined(call_roots.clone(), &mut HashSet::new());
    // LRM 10.6.2: a `force`/`assign` inside a called function or task whose
    // right-hand side reads signals gets the same continuous driver a process
    // body's does (`vj_codegen::force::force_drivers`), in the instance
    // owning the subroutine: the driver re-forces the target while that
    // statement's force is in effect, whichever process ran the call.
    let mut force_added = false;
    for sub in called.iter().map(|c| c.sym).chain(inlined.iter().copied()) {
        let Some(body) = vj_sim::process::cfg::proc_body(&sub) else {
            continue;
        };
        if vj_codegen::force::contains_force(body.as_sem_node()) {
            vj_codegen::force::note_design_forces();
        }
        let Some(&id) = vj_sim::netlist::enclosing_instance_body(&sub)
            .or_else(|| vj_sim::netlist::enclosing_package(&sub))
            .and_then(|b| body_id_to_instance.get(&b.uid()))
        else {
            continue;
        };
        for (site, assign) in vj_codegen::force::force_drivers(body.as_sem_node()) {
            let read_set = assign
                .right()
                .map(vj_codegen::module::cont_assign_read_set)
                .unwrap_or_default();
            if let Some(r) = assign.right() {
                call_roots.push(r.as_sem_node());
                force_added = true;
            }
            cont_assign_specs.push(ContAssignLoweringSpec {
                fn_name: format!("vj_cont_assign_{next_cont_assign_idx}"),
                fn_sym: sub,
                assign_expr: assign,
                net_target: None,
                signals: instance_signals[&id].clone(),
                read_signals: HashMap::new(),
                force_site: Some(site),
                port_source: None,
                var_init: false,
                hidden_target: None,
            });
            cont_assign_meta.push((id, read_set));
            next_cont_assign_idx += 1;
        }
    }
    if force_added {
        called = discover_called_subroutines(call_roots);
    }
    for sub in called {
        subroutine_specs.push(SubroutineLoweringSpec {
            sym: sub.sym,
            nettype_resolver: false,
        });
    }
    // Each user-defined nettype's resolution function, called by the
    // simulator's net resolver (`UserNetResolver`) through a wrapper.
    for t in &user_nets.types {
        if let Some(f) = t.func {
            subroutine_specs.push(SubroutineLoweringSpec {
                sym: f,
                nettype_resolver: true,
            });
        }
    }

    let bindings = RealBindings {
        get_scalar: Some(vj_sim::state::real_sv_get_scalar as *const () as usize),
        set_scalar: Some(real_sv_set_scalar as *const () as usize),
        get_wide: Some(vj_sim::state::real_sv_get_wide as *const () as usize),
        set_wide: Some(real_sv_set_wide as *const () as usize),
        get_mem_word: Some(vj_sim::state::real_sv_get_mem_word as *const () as usize),
        set_mem_word: Some(real_sv_set_mem_word as *const () as usize),
        nba_enqueue: Some(real_nba_enqueue as *const () as usize),
        display: Some(real_sv_rt_display as *const () as usize),
        write: Some(real_sv_rt_write as *const () as usize),
        finish: Some(real_sv_rt_finish as *const () as usize),
        disable_fork: Some(real_sv_rt_disable_fork as *const () as usize),
        disable_fork_block: Some(
            vj_sim::sched::real_sv_rt_disable_fork_block as *const () as usize,
        ),
        disable_named: Some(vj_sim::sched::real_sv_rt_disable_named as *const () as usize),
        nba_masked: Some(vj_sim::sched::real_sv_rt_nba_masked as *const () as usize),
        nba_pulse: Some(vj_sim::sched::real_sv_rt_nba_pulse as *const () as usize),
        reactive_drive: Some(vj_sim::sched::real_sv_rt_reactive_drive as *const () as usize),
        nba_coll: Some(vj_sim::sched::real_sv_rt_nba_coll as *const () as usize),
        set_delay: Some(vj_sim::sched::real_sv_rt_set_delay as *const () as usize),
        fired_term: Some(vj_sim::sched::real_sv_rt_fired_term as *const () as usize),
        fired_mask: Some(vj_sim::sched::real_sv_rt_fired_mask as *const () as usize),
        proc_assert: Some(vj_sim::sched::proc_assert::real_sv_rt_proc_assert as *const () as usize),
        assert_input: Some(
            vj_sim::sched::proc_assert::real_sv_rt_assert_input as *const () as usize,
        ),
        proc_assert_disable: Some(
            vj_sim::sched::proc_assert::real_sv_rt_proc_assert_disable as *const () as usize,
        ),
        slot_owner: Some(vj_sim::state::real_sv_rt_slot_owner as *const () as usize),
        inline_ptrs: Some(vj_sim::state::real_sv_rt_inline_ptrs as *const () as usize),
        aborted: Some(vj_sim::sched::real_sv_rt_aborted as *const () as usize),
        cell_alloc: Some(vj_sim::sched::real_sv_rt_cell_alloc as *const () as usize),
        cell_store: Some(vj_sim::sched::real_sv_rt_cell_store as *const () as usize),
        edge_snapshot: Some(vj_sim::sched::real_sv_rt_edge_snapshot as *const () as usize),
        edge_check: Some(vj_sim::sched::real_sv_rt_edge_check as *const () as usize),
        edge_load: Some(vj_sim::sched::real_sv_rt_edge_load as *const () as usize),
        set_fired_term: Some(vj_sim::sched::real_sv_rt_set_fired_term as *const () as usize),
        deferred_begin: Some(
            vj_runtime::display_sink::real_sv_rt_deferred_begin as *const () as usize,
        ),
        deferred_end: Some(vj_runtime::display_sink::real_sv_rt_deferred_end as *const () as usize),
        deferred_call: Some(
            vj_runtime::display_sink::real_sv_rt_deferred_call as *const () as usize,
        ),
        assert_ctl: Some(
            vj_sim::sched::assert_control::real_sv_rt_assert_ctl as *const () as usize,
        ),
        fscan: Some(vj_runtime::file_io_sink::real_sv_rt_fscan as *const () as usize),
        sscan: Some(vj_runtime::file_io_sink::real_sv_rt_sscan as *const () as usize),
        fgets: Some(vj_runtime::file_io_sink::real_sv_rt_fgets as *const () as usize),
        fgetc: Some(vj_runtime::file_io_sink::real_sv_rt_fgetc as *const () as usize),
        ungetc: Some(vj_runtime::file_io_sink::real_sv_rt_ungetc as *const () as usize),
        ftell: Some(vj_runtime::file_io_sink::real_sv_rt_ftell as *const () as usize),
        ferror: Some(vj_runtime::file_io_sink::real_sv_rt_ferror as *const () as usize),
        force: Some(vj_sim::sched::real_sv_rt_force as *const () as usize),
        release: Some(vj_sim::sched::real_sv_rt_release as *const () as usize),
        force_active: Some(vj_sim::sched::real_sv_rt_force_active as *const () as usize),
        force_row: Some(vj_sim::sched::real_sv_rt_force_row as *const () as usize),
        readmem_rows: Some(vj_runtime::readmem::sv_rt_readmem_rows as *const () as usize),
        strobe_postponed: Some(vj_sim::sched::real_sv_rt_strobe as *const () as usize),
        monitor_start: Some(vj_sim::sched::real_sv_rt_monitor as *const () as usize),
        monitor_enable: Some(vj_sim::sched::real_sv_rt_monitor_enable as *const () as usize),
        time: Some(real_sv_rt_time as *const () as usize),
        // B-runtime Task 4 (RT-070/RT-162): `$dumpfile`/`$dumpflush`'s real
        // production bodies -- `RuntimeHost`-free (this crate's own
        // `dump_control` module doc explains why), so binding them here
        // carries none of the "no RuntimeHost installed" abort risk the
        // other five `$dump*` tasks would.
        dumpfile: Some(crate::dump::sv_rt_dump_file as *const () as usize),
        dumpflush: Some(crate::dump::sv_rt_dump_flush as *const () as usize),
        dump_vars: Some(crate::dump::sv_rt_dump_vars as *const () as usize),
        dump_ctl: Some(crate::dump::sv_rt_dump_ctl as *const () as usize),
        dump_ports: Some(crate::dump::sv_rt_dump_ports as *const () as usize),
        timeformat: Some(vj_runtime::timefmt::sv_rt_timeformat as *const () as usize),
        real_math: Some(vj_runtime::real_math::sv_rt_real_math as *const () as usize),
        dpi_set_scope: Some(crate::dpi::sv_rt_dpi_set_scope as *const () as usize),
        dpi_sync: Some(crate::dpi::sv_rt_dpi_sync as *const () as usize),
        dpi_export_handle: Some(crate::dpi::sv_rt_dpi_export_handle as *const () as usize),
        dpi_export_variant: Some(crate::dpi::sv_rt_dpi_export_variant as *const () as usize),
        str_intern: Some(vj_runtime::strings_rt::sv_rt_str_intern as *const () as usize),
        str_op: Some(vj_runtime::strings_rt::sv_rt_str_op as *const () as usize),
        coll: Some(vj_runtime::collections_rt::sv_rt_coll as *const () as usize),
        // Classes plan Task 5: the object heap's own multiplexed ABI
        // entry point (`RealBindings::obj`'s own doc comment explains why
        // this explicit binding is load-bearing, not cosmetic, for this
        // symbol specifically).
        obj: Some(vj_runtime::objects_rt::sv_rt_obj as *const () as usize),
        process_class: Some(vj_runtime::process_class::sv_rt_process as *const () as usize),
        weakref: Some(vj_runtime::weakref::sv_rt_weakref as *const () as usize),
        semaphore: Some(vj_runtime::semaphore_rt::sv_rt_semaphore as *const () as usize),
        stoch_q: Some(vj_runtime::stoch_queue::sv_rt_stoch_q as *const () as usize),
        net_drivers: Some(vj_sim::sched::real_sv_rt_net_drivers as *const () as usize),
        mailbox: Some(vj_runtime::mailbox_rt::sv_rt_mailbox as *const () as usize),
        wide: Some(vj_runtime::wide_rt::sv_rt_wide as *const () as usize),
        huge: Some(vj_sim::sched::real_sv_rt_huge as *const () as usize),
        str_cstr: Some(vj_runtime::strings_rt::sv_rt_str_cstr as *const () as usize),
        str_to_real: Some(vj_runtime::strings_rt::sv_rt_str_to_real as *const () as usize),
        str_from_real: Some(vj_runtime::strings_rt::sv_rt_str_from_real as *const () as usize),
        str_sformatf: Some(vj_runtime::strings_rt::sv_rt_str_sformatf as *const () as usize),
        // B-runtime Task 6 (RT-078..RT-082): `$random`/`$urandom`/
        // `$urandom_range`'s real, `RuntimeHost`-free production sink --
        // `vj_runtime::random_sink`'s own module doc explains why this
        // carries none of the "no `RuntimeHost` installed" abort risk the
        // `ProcessRuntimeState`-based tasks would.
        random: Some(real_sv_rt_random as *const () as usize),
        urandom: Some(real_sv_rt_urandom as *const () as usize),
        urandom_range: Some(real_sv_rt_urandom_range as *const () as usize),
        // Review fix r2 (blocking finding, RT-078/079): `$random(seed)`/
        // `$urandom(seed)`'s explicit-seed reseed form -- bound directly to
        // `vj_runtime::random`'s pure algorithm (no `RuntimeHost`/
        // ambient-state sink needed; see `RealBindings::random_reseed`'s own
        // doc comment for why).
        random_reseed: Some(sv_rt_random_reseed as *const () as usize),
        urandom_reseed: Some(sv_rt_urandom_reseed as *const () as usize),
        dist: Some(sv_rt_dist as *const () as usize),
        // B-runtime Task 7 (RT-050/051/052/053): `$fopen`/`$fclose`/
        // `$fflush`'s real, `RuntimeHost`-free production sink --
        // `vj_runtime::file_io_sink`'s own module doc explains why this
        // carries none of the "no `RuntimeHost` installed" abort risk the
        // `ProcessRuntimeState`-based tasks would.
        fopen: Some(real_sv_rt_fopen as *const () as usize),
        fopen_mcd: Some(real_sv_rt_fopen_mcd as *const () as usize),
        system: Some(real_sv_rt_system as *const () as usize),
        fclose: Some(real_sv_rt_fclose as *const () as usize),
        fflush: Some(real_sv_rt_fflush as *const () as usize),
        // B-runtime Task 8 (RT-022/RT-049/RT-054/RT-055/RT-056/RT-057):
        // `$fwrite`/`$fdisplay`/`$fmonitor`/`$fstrobe`'s real,
        // `RuntimeHost`-free production sink -- `vj_runtime::
        // file_io_sink`'s own module doc explains why this carries none of
        // the "no `RuntimeHost` installed" abort risk the
        // `ProcessRuntimeState`-based tasks would.
        fwrite: Some(real_sv_rt_fwrite as *const () as usize),
        fdisplay: Some(real_sv_rt_fdisplay as *const () as usize),
        fmonitor: Some(real_sv_rt_fmonitor as *const () as usize),
        fstrobe: Some(real_sv_rt_fstrobe as *const () as usize),
        // B-runtime Task 9 (RT-061/RT-063): `$fseek`/`$feof`'s real,
        // `RuntimeHost`-free production sink -- see `vj_runtime::
        // file_io::read`'s own module doc for why these two are the only
        // read-side calls this task binds all the way through the real
        // pipeline.
        fseek: Some(real_sv_rt_fseek as *const () as usize),
        feof: Some(real_sv_rt_feof as *const () as usize),
        // B-runtime Task 11 (RT-074/RT-075/RT-076/RT-077): `$test$plusargs`/
        // `$value$plusargs`'s real, `RuntimeHost`-free production sink --
        // `vj_runtime::plusargs_sink`'s own module doc explains why
        // this carries none of the "no `RuntimeHost` installed" abort risk
        // the `ProcessRuntimeState`-based tasks would.
        plusargs_test: Some(real_sv_rt_plusargs_test as *const () as usize),
        plusargs_value: Some(real_sv_rt_plusargs_value as *const () as usize),
        // SD-B / T25: `$sdf_annotate`'s real body -- `vj_runtime::
        // sdf_annotate::sv_rt_sdf_annotate`, which hands the call to the
        // applier `run_design` installs (`crate::sdf_apply::Installed`) for this run.
        sdf_annotate: Some(vj_runtime::sdf_annotate::sv_rt_sdf_annotate as *const () as usize),
        cov: Some(vj_runtime::covergroup_rt::sv_rt_cov as *const () as usize),
        vpi_systf: Some(crate::vpi::systf::sv_rt_vpi_systf as *const () as usize),
        vpi_dyn: Some(crate::vpi::dynobj::sv_rt_vpi_dyn as *const () as usize),
        // SD-C / T28: a compiled specparam read asks for the SDF LABEL-annotated value.
        specparam_value: Some(vj_runtime::specparam::sv_rt_specparam_value as *const () as usize),
    };
    // Classes plan Task 5: every class template reachable from a `new()`
    // site anywhere in the design (`netlist::collect_new_class_types`/
    // `assign_class_template_ids` -- Task 2's own whole-design discovery/
    // dedup, run here exactly once), paired with its representative
    // `Symbol`, index-aligned by `ClassTemplateId`'s own dense numbering --
    // `build_pipeline`'s new class sub-pass registers each one's
    // `ObjectLayout` with the object heap and lowers its methods/
    // constructor into the SAME shared module every other kernel below
    // lowers into, before any of them (so a forward `new()`/method-call
    // reference always resolves).
    //
    // Classes plan Task 6 deviation: `collect_new_class_types` alone finds
    // only a type some `new(...)` expression NAMES -- a base class that is
    // merely `extends`ed, never itself `new()`'d anywhere (the overwhelming
    // common case: nothing in a real design ever writes `new base_class()`
    // once every object is created through its most-derived type), is
    // therefore never discovered on its own, yet `super.new(...)` chaining
    // (`classes::chain_to_base`/the recursive `is_super_class` path) needs
    // THAT base class's own `ObjectLayout` registered and its own
    // methods/constructor lowered into this SAME module just as much as any
    // directly-`new()`'d class's. `netlist::base_chain(ty)` already gives
    // every ancestor of a discovered `ty`, root first, so extending the
    // discovered set with each one's own chain -- before dedup -- closes
    // this without a second discovery mechanism: `assign_class_template_ids`'s
    // existing hash-then-verify dedup collapses an ancestor reachable from
    // more than one derived leaf (or already directly `new()`'d elsewhere)
    // to the one `ClassTemplateId` it already would have gotten.
    let mut class_types = netlist::collect_new_class_types(&eval);
    let ancestor_types: Vec<sv_lang::Type<'_>> = class_types
        .iter()
        .flat_map(|ty| netlist::base_chain(*ty))
        .collect();
    class_types.extend(ancestor_types);
    let class_ids = netlist::assign_class_template_ids(&class_types);
    let mut classes_by_id: std::collections::HashMap<u32, sv_lang::Symbol<'_>> =
        std::collections::HashMap::new();
    for (ty, id) in class_types.iter().zip(class_ids.iter()) {
        classes_by_id.entry(id.0).or_insert_with(|| ty.as_symbol());
    }
    let mut classes: Vec<(vj_sim::netlist::ClassTemplateId, sv_lang::Symbol<'_>)> = classes_by_id
        .into_iter()
        .map(|(raw, sym)| (vj_sim::netlist::ClassTemplateId(raw), sym))
        .collect();
    classes.sort_by_key(|(id, _)| id.0);
    // The object heap's per-template registry (`vj_sim::objects::
    // registry`, read by every `release`/`copy`/`is_a` through a C-ABI entry
    // that has no design handle) is process-wide and keyed by THIS design's
    // dense `ClassTemplateId`s. Two designs with classes running at once in
    // one process (this workspace's test binaries run many in parallel
    // threads) would overwrite each other's entries for the same id, so
    // `new obj` would stop retaining a nested handle and free it early. A
    // design with classes therefore holds this guard for its whole run; a
    // design without any is unaffected.
    static CLASS_DESIGN_RUN: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _class_design_run =
        (!classes.is_empty()).then(|| CLASS_DESIGN_RUN.lock().unwrap_or_else(|e| e.into_inner()));

    // Task F3 (NL-035's runtime half): every non-top instance's own port
    // connections, each realized as a synthetic continuous assignment (see
    // `vj_exec::wires`). `child_sym.instance_port_connections()` (called
    // on the CHILD's own `Instance`-kind symbol, per `sv-lang`'s own API)
    // yields, for every one of the child template's own ports, the formal
    // `Port` symbol (in the child's own body) paired with the connection
    // expression bound at the instantiation site (in the PARENT's own scope)
    // -- exactly NL-035's "each instance port's driving expression ... at the
    // parent scope" framing.
    //
    // Planned here as DATA (`WireImage`, with the interconnect graph's
    // `WireInfo` alongside for the JIT): the JIT and an AOT `.so` build the
    // same processes from it, in this order.
    let mut planned_wires: Vec<(
        vj_sim::image::WireImage,
        Option<crate::interconnect::WireInfo>,
    )> = Vec::new();
    for &id in &registration_order {
        let Some(parent_id) = elaborated.instance(id).parent else {
            // A top-level instance has no parent scope to wire its own ports
            // against -- nothing to do.
            continue;
        };
        let child_sym = elaborated.instance_symbol(id);
        let child_signals = &instance_signals[&id];
        let parent_signals = &instance_signals[&parent_id];

        for conn in child_sym.instance_port_connections() {
            let port_sym = conn.port();
            // An interface port has no storage to wire: the child reaches
            // the connected instance's members through foreign slots.
            if port_sym.kind() == SymbolKind::InterfacePort {
                continue;
            }
            // A `ref` port is not wired either: the port variable IS the
            // actual's cell (`ref_port_aliases`, LRM 23.3.3.3).
            // A null (empty) port, `module m(a,);`, has no internal
            // expression and so no storage: nothing to wire (LRM 23.2.2.1).
            if port_sym.port_is_null_port() {
                continue;
            }
            if port_sym.port_direction() == ArgumentDirection::Ref {
                continue;
            }
            // Deviation, found via real sv-lang=0.1.9 output (mirrors
            // `signal_slots_of`'s own identical handling, applied here so
            // the two lookups never disagree on which symbol owns a given
            // port's storage): an ANSI port backed by an implicit
            // net/variable elaborates into TWO sibling members with the
            // same name -- the `Port` boundary-descriptor symbol itself and
            // its separate internal `Net`/`Variable` symbol
            // (`port_internal_symbol()`). The internal symbol, when present,
            // is what actually holds storage (and therefore a
            // `SignalSlot`); the bare `Port` symbol itself never does.
            let member_sym = port_sym.port_internal_symbol().unwrap_or(port_sym);
            let child_slot = *child_signals.get(&member_sym.uid()).ok_or_else(|| {
                RunError::Lowering(LoweringError::unsupported_at(
                    "instance port has no resolved signal slot in its own module",
                    &port_sym,
                ))
            })?;

            // An inout port joining two nets is resolved as one group
            // (`crate::nets`), not wired.
            if resolution.inout_ports.contains(&(id, port_sym.uid())) {
                continue;
            }
            // An unconnected port has no driver: an input net floats
            // (`z`), an input variable keeps its own value.
            let Some(expr) = conn.expression() else {
                continue;
            };
            if !native_port_connection(expr, &port_sym)
                && matches!(
                    port_sym.port_direction(),
                    ArgumentDirection::In | ArgumentDirection::Out
                )
            {
                // Compiled as a continuous assignment in the parent.
                continue;
            }
            // Deviation, found via real sv-lang=0.1.9 output: an INPUT
            // port's connection expression IS the plain rvalue expression
            // directly (`ExpressionKind::NamedValue` for a bare identifier).
            // An OUTPUT port's connection expression is instead wrapped in
            // an implicit `ExpressionKind::Assignment` node (LRM 23.3.3's own
            // "port value assigned to the external net" as a real
            // assignment, LHS = the parent-scope lvalue) -- `Expression::
            // left()` unwraps to that lvalue. Applied unconditionally: an
            // input port's own rvalue expression is never itself
            // `Assignment`-kind, so this unwrap is a no-op for that case.
            let ident_expr = if expr.kind() == ExpressionKind::Assignment {
                expr.left().ok_or_else(|| {
                    RunError::Lowering(LoweringError::unsupported_at(
                        "output port's implicit connection assignment has no lvalue",
                        &port_sym,
                    ))
                })?
            } else {
                expr
            };
            // sv-lang wraps ANY width-mismatched port connection expression
            // in an implicit `ExpressionKind::Conversion` node. Unwrapping it
            // here lets the width checks below actually fire with a clear,
            // named width-mismatch error. This never applies the conversion
            // itself -- a genuine width mismatch is still rejected below.
            let ident_expr = if ident_expr.kind() == ExpressionKind::Conversion {
                ident_expr.operand().unwrap_or(ident_expr)
            } else {
                ident_expr
            };
            // A plain identifier resolves the WHOLE parent-scope signal; a
            // chain of constant bit-/part-selects (`a[g*4 +: 4]`, `y[l]` of a
            // multi-dimensional packed array, `m[l][3:0]`) a constant
            // SUB-RANGE of one (`native_port_connection` admitted only
            // those). Everything else stays a named `LoweringError`.
            let parent_base_expr = match select_base(ident_expr) {
                Some(b) if b.kind() == ExpressionKind::NamedValue => b,
                _ => {
                    return Err(RunError::Lowering(LoweringError::unsupported_at(
                        &format!(
                            "instance port connected to a non-identifier expression \
                             ({:?}) -- this slice only realizes a plain identifier \
                             connection, or a constant bit-select/part-select connection \
                             (e.g. a genvar-indexed `a[g*4 +: 4]`), as a synthetic \
                             continuous assignment",
                            ident_expr.kind()
                        ),
                        &port_sym,
                    )));
                }
            };
            let parent_ref_sym = parent_base_expr.referenced_symbol().ok_or_else(|| {
                RunError::Lowering(LoweringError::unsupported_at(
                    "unresolved name in instance port connection expression",
                    &port_sym,
                ))
            })?;
            let parent_slot = *parent_signals.get(&parent_ref_sym.uid()).ok_or_else(|| {
                RunError::Lowering(LoweringError::unsupported_at(
                    "instance port connection expression names a non-local signal in the \
                     parent scope",
                    &port_sym,
                ))
            })?;
            let bit_range: Option<(u32, u32)> = match ident_expr.kind() {
                ExpressionKind::ElementSelect | ExpressionKind::RangeSelect => {
                    // A bit-select/part-select connection to (or from) an
                    // unpacked-array (`SignalSlotClass::Memory`) port or
                    // parent signal is out of this slice's native bit-range
                    // scope.
                    if matches!(parent_slot.class, SignalSlotClass::Memory { .. })
                        || matches!(child_slot.class, SignalSlotClass::Memory { .. })
                    {
                        return Err(RunError::Lowering(LoweringError::unsupported_at(
                            "bit-select/part-select instance port connection to an \
                             unpacked-array (Memory-class) signal is out of this slice's scope",
                            &port_sym,
                        )));
                    }
                    Some(
                        vj_codegen::select::constant_window(ident_expr, parent_slot.width)
                            .map_err(|why| {
                                RunError::Lowering(LoweringError::unsupported_at(
                                    &format!("instance port connection select: {why}"),
                                    &port_sym,
                                ))
                            })?,
                    )
                }
                _ => None,
            };

            // A resolved net the connection drives (`crate::nets`): its
            // contribution cell, in the bank, instead.
            let bank_cell = |key: crate::nets::DriverKey| {
                resolution
                    .slot(&key)
                    .map(|slot| (bank_id, bank_slot_of(slot)))
            };
            // SD-C / T29: the signals the wire joins as the SDF annotator names them (before
            // the bank substitution below), for the interconnect table.
            let (child_logical, parent_logical) = (child_slot, parent_slot);
            let child_bank = (port_sym.port_direction() == ArgumentDirection::In)
                .then(|| {
                    bank_cell(crate::nets::DriverKey::Port(
                        id,
                        port_sym.uid(),
                        member_sym.uid(),
                    ))
                })
                .flatten();
            let parent_bank = (port_sym.port_direction() == ArgumentDirection::Out)
                .then(|| {
                    bank_cell(crate::nets::DriverKey::Port(
                        id,
                        port_sym.uid(),
                        parent_ref_sym.uid(),
                    ))
                })
                .flatten();
            let (child_inst, child_slot) = child_bank.unwrap_or((id, child_slot));
            let (parent_inst, parent_slot) = parent_bank.unwrap_or((parent_id, parent_slot));
            // A wire an interconnect delay can annotate: a design that calls `$sdf_annotate`,
            // and a packed (not unpacked-array) signal.
            let wire_info = (sdf_wires
                && !matches!(child_slot.class, SignalSlotClass::Memory { .. })
                && !matches!(parent_slot.class, SignalSlotClass::Memory { .. }))
            .then(|| {
                let into_port = port_sym.port_direction() == ArgumentDirection::In;
                let (lo, _) = bit_range.unwrap_or((0, 0));
                let child_node = (id, child_logical.slot);
                let parent_node = (parent_id, parent_logical.slot);
                let child_actual = loc_of(child_inst, child_slot);
                let parent_actual = loc_of(parent_inst, parent_slot);
                if into_port {
                    crate::interconnect::WireInfo {
                        meta: crate::interconnect::Meta {
                            src_node: parent_node,
                            dst_node: child_node,
                            port_node: child_node,
                            into_port,
                            src_lo: lo,
                            dst_lo: 0,
                            width: child_logical.width,
                            dst_banked: child_bank.is_some(),
                        },
                        src: parent_actual,
                        dst: child_actual,
                    }
                } else {
                    crate::interconnect::WireInfo {
                        meta: crate::interconnect::Meta {
                            src_node: child_node,
                            dst_node: parent_node,
                            port_node: child_node,
                            into_port,
                            src_lo: 0,
                            dst_lo: lo,
                            width: child_logical.width,
                            dst_banked: parent_bank.is_some(),
                        },
                        src: child_actual,
                        dst: parent_actual,
                    }
                }
            });
            let child_place = place_of(child_inst, child_slot);
            let parent_place = place_of(parent_inst, parent_slot);
            let into_port = match port_sym.port_direction() {
                ArgumentDirection::In => true,
                ArgumentDirection::Out => false,
                ArgumentDirection::InOut | ArgumentDirection::Ref => {
                    return Err(RunError::Lowering(LoweringError::unsupported_at(
                        "inout/ref-direction instance port (not implemented in this slice)",
                        &port_sym,
                    )));
                }
            };
            let dir = if into_port { "input" } else { "output" };
            // A non-simple port (`module m(a[7:4], a[3:0]);`, LRM 23.2.2.1) binds
            // the connection to a constant sub-range of its internal signal.
            let child_window: Option<(u32, u32)> = match port_sym
                .port_internal_expr()
                .filter(|e| {
                    matches!(
                        e.kind(),
                        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect
                    )
                })
                .filter(|_| !matches!(child_slot.class, SignalSlotClass::Memory { .. }))
            {
                Some(e) => Some(
                    vj_codegen::select::constant_window(e, child_slot.width).map_err(|why| {
                        RunError::Lowering(LoweringError::unsupported_at(
                            &format!("instance port internal select: {why}"),
                            &port_sym,
                        ))
                    })?,
                ),
                None => None,
            };
            let parent_w = bit_range.map_or(parent_slot.width, |(_, w)| w);
            let child_w = child_window.map_or(child_slot.width, |(_, w)| w);
            if parent_w != child_w {
                return Err(RunError::Lowering(LoweringError::unsupported_at(
                    &format!(
                        "{dir} port connection width mismatch (this slice does not \
                         implement implicit extension/truncation)"
                    ),
                    &port_sym,
                )));
            }
            let (parent_range, child_range) = (bit_range, child_window);
            let ranged = parent_range.is_some() || child_range.is_some();
            let wire = if into_port {
                vj_sim::image::WireImage {
                    src: parent_place,
                    src_range: parent_range,
                    dst: child_place,
                    dst_range: child_range,
                    ranged,
                }
            } else {
                vj_sim::image::WireImage {
                    src: child_place,
                    src_range: child_range,
                    dst: parent_place,
                    dst_range: parent_range,
                    ranged,
                }
            };
            planned_wires.push((wire, wire_info));
        }
    }
    // A group whose drivers or nets are rows of an unpacked-array net, or
    // whose nettype is user-defined, has no counterpart in
    // `vj_sim::image::{DriverImage, GroupImage}` yet (cell slots only),
    // or (a user nettype with a resolution function) needs a JIT-compiled
    // function pointer with no serializable form at all: such a group's
    // resolver is native (`NetResolver`/`UserNetResolver`/`UserSwitchResolver`
    // below), registered directly with the JIT `Engine`, never through the
    // design image -- so the image carries them (`native_nets`).
    let group_is_native =
        |g: &crate::nets::Group| g.user.is_some() || !g.rows.is_empty() || !g.cells.is_empty();
    let native_groups: Vec<bool> = resolution.groups.iter().map(group_is_native).collect();
    let network_is_native =
        |net: &crate::nets::Network| net.groups.iter().any(|&gi| native_groups[gi]);
    // The image's group indices, once native groups are left out.
    let mut group_remap: Vec<Option<u32>> = Vec::with_capacity(resolution.groups.len());
    let mut next_group = 0u32;
    for &native in &native_groups {
        if native {
            group_remap.push(None);
        } else {
            group_remap.push(Some(next_group));
            next_group += 1;
        }
    }
    // The resolved net groups and switch networks, as data
    // (`vj_exec::nets` builds the resolvers from them) -- every group
    // `group_is_native` does not claim.
    let shows_strength = crate::nets::shows_strength(&syntax_trees);
    let port_views = if crate::nets::uses_dumpports(&syntax_trees) {
        dump_port_views(
            &elaborated,
            &registration_order,
            &resolution,
            &native_groups,
        )
    } else {
        PortViews::default()
    };
    let planned_groups: Vec<vj_sim::image::GroupImage> = resolution
        .groups
        .iter()
        .enumerate()
        .filter(|(_, g)| !group_is_native(g))
        .map(|(gi, g)| vj_sim::image::GroupImage {
            kind: g.kind,
            width: g.width,
            nets: g
                .nets
                .iter()
                .map(|(inst, sym)| (*inst, instance_signals[inst][sym].slot))
                .collect(),
            drivers: g
                .drivers
                .iter()
                .map(|&(slot, strength)| vj_sim::image::DriverImage {
                    slot,
                    strength,
                    ambiguous: resolution.ambiguous.get(&slot).copied(),
                    src: resolution.strength_src.get(&slot).copied(),
                })
                .collect(),
            strength_tick: resolution.strength_ticks.get(&gi).copied(),
            sides: port_views.sides.get(&gi).cloned().unwrap_or_default(),
            charge: g
                .nets
                .iter()
                .find_map(|n| trireg_charges.get(n).copied())
                .unwrap_or(4),
            switched: g.switched,
            decay: (g.kind == vj_sim::state::NetKind::TriReg)
                .then(|| g.nets.iter().find_map(|n| trireg_decays.get(n).copied()))
                .flatten(),
            // A design that prints `%v` keeps the group's strengths under
            // each net's key.
            strength_keys: if shows_strength || crate::nets::tracks_strengths() {
                g.nets
                    .iter()
                    .map(|(_, sym)| vj_runtime::fmt::strength_key(&sym.key_string()))
                    .collect()
            } else {
                Vec::new()
            },
        })
        .collect();
    let planned_networks: Vec<vj_sim::image::NetworkImage> = resolution
        .networks
        .iter()
        .filter(|net| !network_is_native(net))
        .map(|net| {
            // Switch ends as indices into this network's own groups.
            let local = |gi: usize| {
                net.groups
                    .iter()
                    .position(|&x| x == gi)
                    .expect("in network") as u32
            };
            vj_sim::image::NetworkImage {
                groups: net
                    .groups
                    .iter()
                    .map(|&g| {
                        group_remap[g].expect(
                            "a non-native network (checked above) only names non-native groups",
                        )
                    })
                    .collect(),
                switches: net
                    .switches
                    .iter()
                    .map(|s| vj_sim::image::SwitchImage {
                        a: (local(s.a.0), s.a.1),
                        b: (local(s.b.0), s.b.1),
                        conducts: match s.conducts {
                            crate::nets::Conducts::Always => vj_sim::image::ConductsImage::Always,
                            crate::nets::Conducts::When(c, on) => {
                                vj_sim::image::ConductsImage::When(
                                    match c {
                                        crate::nets::Control::Bit(inst, slot, bit) => {
                                            vj_sim::image::ControlImage::Bit {
                                                instance: inst,
                                                slot: slot.slot,
                                                width: slot.width,
                                                bit,
                                            }
                                        }
                                        crate::nets::Control::Const(v) => {
                                            vj_sim::image::ControlImage::Const(v)
                                        }
                                        crate::nets::Control::Bank(cell) => {
                                            vj_sim::image::ControlImage::Bit {
                                                instance: bank_id,
                                                slot: cell,
                                                width: 1,
                                                bit: 0,
                                            }
                                        }
                                    },
                                    on,
                                )
                            }
                        },
                        resistive: s.resistive,
                    })
                    .collect(),
            }
        })
        .collect();

    // The resolvers `group_is_native` claimed, as data (`vj_exec::usernets`
    // builds them for both `vj run` and a built `.so`): in the order they
    // register -- the switch networks over native groups, then the groups.
    let native_nets = {
        use vj_exec::usernets as un;
        let mut types: Vec<un::UserType> = Vec::new();
        let mut type_of: HashMap<usize, u32> = HashMap::new();
        let mut type_index = |t: usize| -> Result<u32, RunError> {
            if let Some(&i) = type_of.get(&t) {
                return Ok(i);
            }
            let ty = &user_nets.types[t];
            let func = match &ty.func {
                Some(f) => {
                    Some(vj_codegen::nettype::resolver_symbol(f).map_err(RunError::Lowering)?)
                }
                None => None,
            };
            types.push(un::UserType {
                func,
                default: vj_sim::state::packed_words(&ty.init),
            });
            let i = (types.len() - 1) as u32;
            type_of.insert(t, i);
            Ok(i)
        };
        // Where a group's resolved value goes: its nets, its elements of
        // unpacked-array nets, and the bank cells of the interconnect elements
        // a primitive terminal reads.
        let targets_of = |g: &crate::nets::Group| -> Vec<un::Target> {
            let mut v: Vec<un::Target> = g
                .nets
                .iter()
                .map(|(inst, sym)| un::Target::Cell {
                    instance: inst.0,
                    slot: instance_signals[inst][sym].slot,
                })
                .collect();
            v.extend(g.rows.iter().map(|(net, row)| un::Target::Row {
                instance: net.0.0,
                slot: instance_signals[&net.0][&net.1].slot,
                row: *row,
            }));
            v.extend(g.cells.iter().map(|&s| un::Target::Cell {
                instance: bank_id.0,
                slot: s,
            }));
            v
        };
        // A group's drivers' contributions.
        let contribs_of = |g: &crate::nets::Group| -> Vec<un::Contrib> {
            g.drivers
                .iter()
                .zip(&g.driver_rows)
                .map(|(&(slot, _), row)| match row {
                    Some(r) => un::Contrib::Row(slot, *r),
                    None => un::Contrib::Cell(slot),
                })
                .collect()
        };
        // A native group as data; `user` is its nettype's index, if any.
        let native_group = |g: &crate::nets::Group, user: Option<u32>| -> un::NativeGroup {
            un::NativeGroup {
                user,
                kind: g.kind,
                width: g.width,
                drivers: contribs_of(g)
                    .into_iter()
                    .zip(&g.drivers)
                    .map(|(contrib, &(slot, strength))| un::NativeDriver {
                        contrib,
                        strength,
                        ambiguous: if user.is_some() {
                            None
                        } else {
                            resolution.ambiguous.get(&slot).copied()
                        },
                    })
                    .collect(),
                targets: targets_of(g),
                strength_keys: if shows_strength || crate::nets::tracks_strengths() {
                    // A net keeps its record under its own key, an element
                    // of an unpacked-array net under its row's.
                    g.nets
                        .iter()
                        .map(|(_, sym)| sym.key_string())
                        .chain(
                            g.rows
                                .iter()
                                .map(|(net, row)| format!("{}[{row}]", net.1.key_string())),
                        )
                        .map(|k| vj_runtime::fmt::strength_key(&k))
                        .collect()
                } else {
                    Vec::new()
                },
            }
        };
        let mut plain_networks = Vec::new();
        let mut networks = Vec::new();
        // Switch networks over a native group. Only a user-defined nettype's
        // switch network (LRM 28.8) is exercised today (`nets::analyze` has no
        // fixture joining a plain unpacked-array net's elements through a
        // switch); a future one would need a row-aware twin of
        // `vj_exec::nets`'s own `SwitchResolver`.
        for net in resolution
            .networks
            .iter()
            .filter(|net| network_is_native(net))
        {
            let local = |gi: usize| {
                net.groups
                    .iter()
                    .position(|&x| x == gi)
                    .expect("in network") as u32
            };
            let conducts_of = |c: crate::nets::Conducts| match c {
                crate::nets::Conducts::Always => un::NativeConducts::Always,
                crate::nets::Conducts::When(crate::nets::Control::Bit(inst, slot, bit), on) => {
                    un::NativeConducts::Bit {
                        instance: inst.0,
                        slot: slot.slot,
                        width: slot.width,
                        bit,
                        on,
                    }
                }
                crate::nets::Conducts::When(crate::nets::Control::Const(value), on) => {
                    un::NativeConducts::Const { value, on }
                }
                crate::nets::Conducts::When(crate::nets::Control::Bank(cell), on) => {
                    un::NativeConducts::Bit {
                        instance: bank_id.0,
                        slot: cell,
                        width: 1,
                        bit: 0,
                        on,
                    }
                }
            };
            let Some(t) = resolution.groups[net.groups[0]].user else {
                // Built-in nettypes joined through switches, with elements
                // of unpacked-array nets among them (LRM 28.7): resolved per
                // bit with strength reduction.
                if net
                    .groups
                    .iter()
                    .any(|&gi| resolution.groups[gi].kind == vj_sim::state::NetKind::TriReg)
                {
                    return Err(RunError::Lowering(LoweringError::unsupported(
                        "a switch network joining a `trireg` net and an element of an \
                         unpacked-array net (LRM 28.16.2)",
                        "net",
                    )));
                }
                plain_networks.push(un::NativePlainNetwork {
                    groups: net
                        .groups
                        .iter()
                        .map(|&gi| native_group(&resolution.groups[gi], None))
                        .collect(),
                    switches: net
                        .switches
                        .iter()
                        .map(|s| un::NativePlainSwitch {
                            a: local(s.a.0),
                            a_bit: s.a.1,
                            b: local(s.b.0),
                            b_bit: s.b.1,
                            conducts: conducts_of(s.conducts),
                            resistive: s.resistive,
                        })
                        .collect(),
                });
                continue;
            };
            networks.push(un::NativeNetwork {
                user: type_index(t)?,
                width: resolution.groups[net.groups[0]].width,
                groups: net
                    .groups
                    .iter()
                    .map(|&gi| {
                        let g = &resolution.groups[gi];
                        (contribs_of(g), targets_of(g))
                    })
                    .collect(),
                switches: net
                    .switches
                    .iter()
                    .map(|s| un::NativeSwitch {
                        a: local(s.a.0),
                        b: local(s.b.0),
                        conducts: match s.conducts {
                            crate::nets::Conducts::Always => un::NativeConducts::Always,
                            crate::nets::Conducts::When(
                                crate::nets::Control::Bit(inst, slot, bit),
                                on,
                            ) => un::NativeConducts::Bit {
                                instance: inst.0,
                                slot: slot.slot,
                                width: slot.width,
                                bit,
                                on,
                            },
                            crate::nets::Conducts::When(crate::nets::Control::Const(value), on) => {
                                un::NativeConducts::Const { value, on }
                            }
                            crate::nets::Conducts::When(crate::nets::Control::Bank(cell), on) => {
                                un::NativeConducts::Bit {
                                    instance: bank_id.0,
                                    slot: cell,
                                    width: 1,
                                    bit: 0,
                                    on,
                                }
                            }
                        },
                    })
                    .collect(),
            });
        }
        let mut groups = Vec::new();
        for g in resolution
            .groups
            .iter()
            .filter(|g| !g.switched && group_is_native(g))
        {
            let user = match g.user {
                Some(t) => Some(type_index(t)?),
                None => {
                    // A plain (non-user) native group: its drivers or nets are
                    // rows of an unpacked-array net, or a bank cell an
                    // interconnect element's primitive terminal reads.
                    // `nets::analyze` rejects an unpacked array of `trireg`
                    // nets (28.16.2), so no native group is ever a `trireg` --
                    // the resolver has no charge-holding logic to run for one.
                    if g.kind == vj_sim::state::NetKind::TriReg {
                        return Err(RunError::Lowering(LoweringError::unsupported(
                            "a `trireg` group resolved per element -- this should have been \
                             rejected when the design's nets were analyzed",
                            "net",
                        )));
                    }
                    None
                }
            };
            groups.push(native_group(g, user));
        }
        un::NativeNets {
            types,
            networks,
            plain_networks,
            groups,
        }
    };

    // Waveform dumping's signal list (LRM 1800-2023 21.7): every variable/net
    // of every instance, planned here so a run and a built image agree on it.
    let dump_signals = dump_signal_images(
        &elaborated,
        &registration_order,
        &instance_signals,
        &eval.design().syntax_trees(),
        &port_views,
    );

    // FSMs named by the 40.4 pragmas (LRM 40.2.1 c): read when a build-aot
    // image is made or `--coverage` collects; otherwise nothing is read.
    let fsms = if aot.is_some() || vj_runtime::codecov::enabled() {
        fsm_images(sources, &elaborated, &registration_order, &instance_signals)
    } else {
        Vec::new()
    };

    // `vj build-aot` stops here: everything above is the planner `vj run`
    // runs too, and what follows binds the lowered module to a JIT and builds
    // the engine in this process, which a `.so` does not have. The image below
    // carries what the runner needs in their place.
    if let Some(request) = aot {
        use crate::aot_image::{Locator, codegen_refusal, not_supported, refused, runtime_refusal};
        use vj_sim::image::{
            DesignImage, ForeignImage, InstanceImage, InstanceKind, KernelImage, KernelRole,
            TemplateImage, XWindow,
        };
        let locate = Locator::new(&syntax_trees, sources);
        let first_body = instance_body_of(&elaborated, registration_order[0], path)?;
        let design_at = locate.symbol(&first_body);

        // --- Refusals, in a fixed order: the first one that applies is reported.
        // The registered VPI system tasks lower to `sv_rt_vpi_systf` calls whose
        // sites the image carries (`vpi` section, written at the end of the
        // lowering below).
        let vpi_registered = systf_codegen.clone();
        vj_codegen::vpi_systf::set_registered(systf_codegen);

        // --- The image: what the planner knows, besides the machine code.
        let mut base = DesignImage::empty(vj_abi::VJ_ABI_VERSION);
        base.x_initial_zero = X_INITIAL_ZERO.load(std::sync::atomic::Ordering::Relaxed);
        base.tick_exp = vj_codegen::timescale::design_tick_exp(
            &elaborated.instance_symbol(registration_order[0]),
        );
        // M5: the run-wide timing options this build used (LRM 30.7/31.8/
        // 31.9.4/32's own "simulators may provide an option" clauses) are
        // baked into the planned pulse widths and `TOOL_CONTROL` selection
        // above already; recording them here too lets `vj run-aot`
        // refuse a disagreeing flag by name instead of silently running
        // with the build's choice under a different one's name.
        base.timing.options = timing.to_image();
        let layout_of = |key: &TemplateKey| {
            templates
                .layout_of(key)
                .expect("every template was registered above")
                .clone()
        };
        let mut seen_templates: HashSet<TemplateKey> = HashSet::new();
        for &id in &registration_order {
            let key = *elaborated.dedup_key(elaborated.instance(id).template);
            if seen_templates.insert(key) {
                base.templates.push(TemplateImage {
                    key,
                    layout: layout_of(&key),
                });
            }
            base.instances.push(InstanceImage {
                id,
                template: key,
                kind: InstanceKind::Elaborated,
                path: elaborated.instance_symbol(id).hierarchical_path(),
            });
        }
        for (id, key, _) in &packages {
            base.templates.push(TemplateImage {
                key: *key,
                layout: layout_of(key),
            });
            base.instances.push(InstanceImage {
                id: *id,
                template: *key,
                kind: InstanceKind::Package,
                path: String::new(),
            });
        }
        // The driver bank: the contribution cells of the resolved nets.
        if needs_bank {
            base.templates.push(TemplateImage {
                key: bank_key,
                layout: layout_of(&bank_key),
            });
            base.instances.push(InstanceImage {
                id: bank_id,
                template: bank_key,
                kind: InstanceKind::Bank,
                path: String::new(),
            });
        }
        base.wires = planned_wires.iter().map(|(w, _)| *w).collect();
        base.groups = planned_groups.clone();
        let timing_plan = vj_exec::timing::TimingPlan {
            prims: prim_plans.prims.clone(),
            lines: prim_plans.lines.clone(),
            device_init: prim_plans.device_init.clone(),
            specify: specify_plans.spec(),
            checks: timing_check_plans.spec(),
            sdf: Default::default(),
            interconnect: vj_exec::timing::interconnect::InterconnectPlan {
                kick: sdf_kick.map(|slot| loc_of(bank_id, slot)),
                wires: planned_wires.iter().map(|(_, info)| *info).collect(),
                style: timing.default_pulse_style(),
                showcancelled: timing.default_showcancelled(),
            },
        };
        if !timing_plan.is_empty() {
            base.timing.plan = vj_exec::timing::encode(&timing_plan);
        }
        base.networks = planned_networks.clone();
        for id in registration_order
            .iter()
            .copied()
            .chain(packages.iter().map(|(id, _, _)| *id))
        {
            if let Some((own, targets)) = instance_foreign.get(&id) {
                base.foreign.push(ForeignImage {
                    instance: id,
                    own_slots: *own,
                    targets: targets.clone(),
                });
            }
        }
        let mut x_windows = crate::nets::driven_windows(&infos, &instance_signals, &syntax_trees);
        // A net of a user-defined nettype starts at its data type's default
        // value (LRM 6.7.3), as does each driver's contribution cell: the
        // same initialization `vj run` commits below, as windows.
        for (net, &t) in &user_nets.by_net {
            x_windows.remove(net);
            let slot = &instance_signals[&net.0][&net.1];
            if matches!(slot.class, SignalSlotClass::Memory { .. }) {
                continue;
            }
            base.x_windows.push(XWindow {
                instance: net.0,
                slot: slot.slot,
                value: vj_sim::state::bits_to_four_state(&user_nets.types[t].init),
            });
        }
        for g in resolution.groups.iter().filter(|g| g.user.is_some()) {
            let value =
                vj_sim::state::bits_to_four_state(&user_nets.types[g.user.unwrap_or(0)].init);
            for (&(slot, _), row) in g.drivers.iter().zip(&g.driver_rows) {
                if row.is_some() {
                    continue;
                }
                base.x_windows.push(XWindow {
                    instance: bank_id,
                    slot,
                    value: value.clone(),
                });
            }
        }
        for &id in &registration_order {
            let body = instance_body_of(&elaborated, id, path)?;
            for uid in crate::nets::trireg_nets(&body, &syntax_trees) {
                x_windows.entry((id, uid)).or_default().push(None);
            }
        }
        for ((id, uid), windows) in &x_windows {
            let Some(slot) = instance_signals.get(id).and_then(|s| s.get(uid)) else {
                continue;
            };
            let value = match slot.class {
                SignalSlotClass::Memory { num_rows, .. } => x_memory_value(slot, num_rows, windows),
                _ => x_window_value(slot, windows),
            };
            base.x_windows.push(XWindow {
                instance: *id,
                slot: slot.slot,
                value,
            });
        }
        // (A hash map's order is not part of the design.)
        base.x_windows.sort_by_key(|w| (w.instance.0, w.slot));
        base.x_windows.dedup_by_key(|w| (w.instance.0, w.slot));

        // --- Lowering, then the kernel table.
        let stash: std::cell::RefCell<Option<RunError>> = std::cell::RefCell::new(None);
        let slot_of = |id: InstanceId, sym: &SymbolId| -> Result<u32, LoweringError> {
            instance_signals
                .get(&id)
                .and_then(|s| s.get(sym))
                .map(|s| s.slot)
                .ok_or_else(|| {
                    LoweringError::unsupported(
                        &format!(
                            "static-sensitivity entry `{sym}` has no resolved signal slot in its \
                             own module"
                        ),
                        "build-aot",
                    )
                })
        };
        vj_codegen::systask::clear_sdf_sites();
        let result = vj_codegen::pipeline::compile_design_to_object(
            &plans,
            &cont_assign_specs,
            &subroutine_specs,
            &classes,
            &cov_plan.specs,
            eval.design(),
            base,
            |image, parts| {
                // What the lowered module calls reveals the constructs whose
                // behaviour lives in the host process.
                let refusal = parts
                    .declared_runtime
                    .iter()
                    .find_map(|s| runtime_refusal(s));
                if let Some((feature, what)) = refusal {
                    *stash.borrow_mut() =
                        Some(refused(feature, &not_supported(what), design_at.clone()));
                    return Err(LoweringError::unsupported(what, "build-aot"));
                }
                // An assertion's kernel runs only its action blocks, resumed by
                // the assertion engine: the registrar never registers it
                // (`AssertionSpec::end_cell`: a watcher's process still runs).
                let engine_owned: HashSet<usize> = parts
                    .assertions
                    .iter()
                    .filter(|a| a.end_cell.is_none())
                    .map(|a| a.plan_index)
                    .collect();
                for (i, (frame_words, kind, id, spec, level)) in kernel_meta.iter().enumerate() {
                    let symbol = image.intern(&parts.names[i]);
                    image.kernels.push(KernelImage {
                        symbol,
                        frame_words: *frame_words,
                        kind: *kind,
                        instance: *id,
                        role: KernelRole::Process,
                        level_head: *level,
                        reactive: reactive_kernels.contains(&i),
                        program_initial: program_initial_kernels.contains(&i),
                        registered: !engine_owned.contains(&i),
                        read_set: spec
                            .read_set
                            .iter()
                            .map(|s| slot_of(*id, s))
                            .collect::<Result<_, _>>()?,
                        read_windows: {
                            let mut out = Vec::new();
                            for s in &spec.read_set {
                                for (lsb, width) in spec.windows.get(s).into_iter().flatten() {
                                    out.push((slot_of(*id, s)?, *lsb, *width));
                                }
                            }
                            out
                        },
                        reset: spec
                            .reset
                            .as_ref()
                            .map(|(s, edge)| slot_of(*id, s).map(|slot| (slot, *edge)))
                            .transpose()?,
                        disable_scopes: kernel_disable_scopes[i].to_vec(),
                    });
                }
                for (i, (id, read_set)) in cont_assign_meta.iter().enumerate() {
                    let symbol = image.intern(&parts.cont_assign_names[i]);
                    image.kernels.push(KernelImage {
                        symbol,
                        frame_words: 0,
                        kind: ProcessKind::AlwaysComb,
                        instance: *id,
                        role: if cont_assign_specs[i].var_init {
                            KernelRole::VarInit
                        } else {
                            KernelRole::ContAssign
                        },
                        level_head: false,
                        reactive: reactive_cont_assigns.contains(&i),
                        program_initial: false,
                        registered: true,
                        read_set: read_set
                            .iter()
                            .map(|s| slot_of(*id, s))
                            .collect::<Result<_, _>>()?,
                        read_windows: Vec::new(),
                        reset: None,
                        disable_scopes: Vec::new(),
                    });
                }
                // Assertion engines, checker free variables and the sampled
                // value history: the same description `vj run` runs.
                let body_infos: Vec<_> = bodies
                    .iter()
                    .map(|(id, body)| crate::verif_image::BodyInfo {
                        instance: *id,
                        body,
                        signals: &instance_signals[id],
                        port_sources: &port_sources,
                    })
                    .collect();
                let kernel = |plan_index: usize| {
                    kernel_meta
                        .get(plan_index)
                        .map(
                            |(frame_words, _, id, _, _)| crate::verif_image::KernelInfo {
                                name: parts.names[plan_index].as_str(),
                                frame_words: *frame_words,
                                instance: *id,
                            },
                        )
                };
                let verif = crate::verif_image::build(
                    &parts.assertions,
                    kernel,
                    &body_infos,
                    &syntax_trees,
                    &cov_plan,
                    |n| image.intern(n),
                )?;
                image.verif = verif;
                // A string's id, and a constant collection's handle, are baked
                // into the machine code and the cells' initial values: the
                // runner makes the same ids before anything else runs.
                image.strings = vj_sim::strings::snapshot();
                // Lowering registered each class's handle fields, ancestors
                // and `rand` properties with this process's object heap; the
                // runner registers the same ones from the image.
                let class_ids: Vec<_> = classes.iter().map(|(id, _)| *id).collect();
                image.classes = vj_sim::objects::template_snapshot(&class_ids);
                // The native resolvers (user-defined nettypes, unpacked-array
                // nets) and the symbols of their resolution functions.
                for t in &native_nets.types {
                    if let Some(f) = &t.func {
                        image.intern(f);
                    }
                }
                image.native_nets = vj_exec::usernets::encode(&native_nets);
                // The solver's programs and the `randomize()` call sites' specs
                // (their ids are baked into the machine code), registered the
                // same way by the runner (LRM 18.6).
                image.randomize = vj_sim::constraints::registry::snapshot(&class_ids);
                image.dump_signals = dump_signals.clone();
                image.fsms = fsms.clone();
                // DPI-C: the C functions the imports call (checked when the
                // design is loaded) and, per export, the dispatcher the
                // runner's trampoline is pointed at.
                let mut imports = parts.dpi_c_symbols.clone();
                imports.sort();
                imports.dedup();
                let mut exports: Vec<(String, u32)> = parts
                    .dpi_exports
                    .iter()
                    .map(|(c_name, thunk)| (c_name.clone(), image.intern(thunk)))
                    .collect();
                exports.sort();
                let mut variants = parts.dpi_export_variants.clone();
                variants.sort();
                image.dpi = vj_sim::image::DpiImage {
                    imports,
                    exports,
                    variants,
                    task_fibers: !parts.export_tasks.is_empty(),
                };
                match vj_sim::collections::frozen_snapshot() {
                    Ok(collections) => image.collections = collections,
                    Err(why) => {
                        *stash.borrow_mut() = Some(refused(
                            "collection",
                            &not_supported(&why),
                            design_at.clone(),
                        ));
                        return Err(LoweringError::unsupported(&why, "build-aot"));
                    }
                }
                // `$sdf_annotate` calls with literal arguments are resolved now, by the
                // annotator `vj run` runs, on a copy of the design's timing cells.
                let sites = vj_codegen::systask::take_sdf_sites();
                if !sites.is_empty() {
                    let mut plan = timing_plan.clone();
                    let live = vj_exec::timing::TimingLive::new(&plan);
                    // The port connection wires `PORT`, `NETDELAY` and `INTERCONNECT` annotate:
                    // the graph alone, which records the annotations for the image to replay.
                    let wire_graph = std::sync::Arc::new(std::sync::Mutex::new(
                        vj_exec::timing::interconnect::Table::recording(
                            plan.interconnect
                                .wires
                                .iter()
                                .flatten()
                                .map(|w| w.meta)
                                .collect(),
                        ),
                    ));
                    let annotator = crate::sdf_apply::Annotator::new(
                        timing_model.paths.clone(),
                        crate::sdf_apply::instance_table(&infos, &instance_signals),
                        crate::sdf_apply::condition_specparams(&timing_model),
                        std::sync::Arc::clone(&live.paths),
                        crate::primitives::device_cells(&prim_plans.device, &live),
                        image.tick_exp,
                    )
                    .with_primitives(crate::primitives::prim_cells(&prim_plans.by_path, &live))
                    .with_checks(
                        timing_model.timing_checks.clone(),
                        std::sync::Arc::clone(&live.checks),
                    )
                    .with_options(&timing)
                    .with_labels(crate::sdf_labels::collect(&eval, &bodies, &timing_model))
                    .with_interconnect(std::sync::Arc::clone(&wire_graph))
                    .capturing_logs();
                    match crate::aot_sdf::resolve(
                        &sites,
                        &live,
                        &wire_graph,
                        timing_model.timing_checks.len(),
                        annotator,
                    ) {
                        Ok(sdf) => {
                            plan.sdf = sdf;
                            image.timing.plan = vj_exec::timing::encode(&plan);
                        }
                        Err((feature, why)) => {
                            *stash.borrow_mut() =
                                Some(refused(feature, &not_supported(&why), design_at.clone()));
                            return Err(LoweringError::unsupported(&why, "build-aot"));
                        }
                    }
                }
                // Statement-coverage sites (LRM 40.2.1 a), known once every
                // kernel is lowered.
                image.stmt_cov =
                    vj_codegen::stmtcov::enabled().then(vj_codegen::stmtcov::take_sites);
                // VPI: the object model and every build-time fact the runner
                // cannot recompute without a frontend (`vpi::boot`), only when
                // a library was loaded (the statement probes exist only then).
                if !vpi_libraries.is_empty() {
                    let mut boot = crate::vpi::boot::VpiBoot {
                        registered: vpi_registered.clone(),
                        sites: vj_codegen::vpi_systf::take_sites(),
                        fork_origins: vj_codegen::vpi_dyn::take_fork_origins()
                            .into_iter()
                            .collect(),
                        stmt_sites: vj_codegen::vpi_dyn::take_stmt_sites(),
                        disable_sites: vj_codegen::vpi_dyn::take_disable_sites(),
                        frame_sites: vj_codegen::vpi_dyn::take_frame_sites(),
                        class_uids: class_uids.clone(),
                        static_keys: vj_sim::objects::static_singleton_key_pairs(),
                        kernel_dyn: kernel_dyn.clone(),
                        ..Default::default()
                    };
                    fill_vpi_planner_facts(
                        &mut boot,
                        &timing_model,
                        &body_id_to_instance,
                        &instance_signals,
                        image.tick_exp,
                    );
                    let model = crate::vpi::state::model().ok_or_else(|| {
                        LoweringError::unsupported("the VPI model was not built", "build-aot")
                    })?;
                    image.vpi = crate::vpi::boot::encode_image(&model, &boot);
                }
                Ok(())
            },
            request.with_main,
            request.out_obj,
        );
        return match result {
            Ok(image) => {
                *request.image = Some(image);
                Ok(0)
            }
            Err(e) => {
                if let Some(r) = stash.take() {
                    return Err(r);
                }
                if let vj_codegen::error::CodegenError::Lowering(le) = &e
                    && let Some((feature, what)) = codegen_refusal(&le.message)
                {
                    return Err(refused(feature, &not_supported(what), design_at));
                }
                Err(RunError::Codegen(e))
            }
        };
    }

    // `eval.design()` also serves B-runtime Task 15 (RT-007): `build_pipeline`
    // enumerates the design's `export "DPI-C"` declarations from it.
    let vpi_registered = systf_codegen.clone();
    vj_codegen::vpi_systf::set_registered(systf_codegen);
    let (pipeline, kernel_names, cont_assign_kernel_names) = build_pipeline(
        &plans,
        &cont_assign_specs,
        &subroutine_specs,
        &classes,
        &cov_plan.specs,
        eval.design(),
        bindings,
    )
    .map_err(RunError::Lowering)?;
    // Each call site of a registered system task/function, with its
    // `compiletf` run once now (36.4: before the simulation starts).
    // The build-time facts VPI needs (`vpi::boot`); an AOT image carries the same
    // struct, so both runs wire VPI through the same two calls.
    let mut vpi_boot = crate::vpi::boot::VpiBoot {
        registered: vpi_registered,
        sites: vj_codegen::vpi_systf::take_sites(),
        fork_origins: vj_codegen::vpi_dyn::take_fork_origins()
            .into_iter()
            .collect(),
        stmt_sites: vj_codegen::vpi_dyn::take_stmt_sites(),
        disable_sites: vj_codegen::vpi_dyn::take_disable_sites(),
        frame_sites: vj_codegen::vpi_dyn::take_frame_sites(),
        class_uids,
        static_keys: vj_sim::objects::static_singleton_key_pairs(),
        kernel_dyn: std::mem::take(&mut kernel_dyn),
        ..Default::default()
    };
    vpi_boot.install_static();
    crate::dpi::set_export_targets(&pipeline.dpi_export_thunks().map_err(RunError::Lowering)?)
        .map_err(RunError::Jit)?;
    for (c_name, scope, variant) in pipeline.dpi_export_variants() {
        crate::dpi::register_export_variant(c_name, scope, *variant);
    }
    #[allow(clippy::type_complexity)]
    let kernel_names: Vec<(
        String,
        u32,
        ProcessKind,
        InstanceId,
        KernelSensitivitySpec,
        bool,
    )> = kernel_names
        .into_iter()
        .zip(kernel_meta)
        .map(|(name, (frame_words, kind, id, spec, level))| {
            (name, frame_words, kind, id, spec, level)
        })
        .collect();
    // Task 2 (NL-034): index-aligned with `cont_assign_specs`/
    // `cont_assign_meta` above, mirroring `kernel_names`' own zip just above.
    let cont_assign_kernel_names: Vec<(String, InstanceId, Vec<SymbolId>, bool)> =
        cont_assign_kernel_names
            .into_iter()
            .zip(cont_assign_meta)
            .zip(cont_assign_specs.iter().map(|s| s.var_init))
            .map(|((name, (id, read_set)), var_init)| (name, id, read_set, var_init))
            .collect();

    // LRM 9.6.2: an instance-path disable must name a block of a process that
    // can suspend (only those carry a disable scope) or a task; a fork branch,
    // a block that cannot suspend or an unresolved name stays loud.
    if !instance_path_disables.is_empty() {
        let known: HashSet<&str> = kernel_disable_scopes
            .iter()
            .flat_map(|s| s.iter().map(|(_, l, _)| l.as_str()))
            .chain(branch_scope_labels.iter().map(String::as_str))
            .collect();
        for (requester, label) in &instance_path_disables {
            let requester_path = instance_ids_by_path
                .iter()
                .find_map(|(p, i)| (i == requester).then_some(p));
            let inert = inert_blocks.contains(label)
                || requester_path.is_some_and(|rp| inert_blocks.contains(&format!("{rp}.{label}")));
            // `disable u1.t;` of a task no activation of which can be in
            // progress (it never suspends): nothing is inside it, so it is a
            // no-op (9.6.2), like an inert block. The prefix must name an
            // instance, relative to the requester or absolute.
            let inert = inert
                || label.rsplit_once('.').is_some_and(|(prefix, leaf)| {
                    vj_sim::process::cfg::is_task_name(leaf)
                        && (instance_ids_by_path.contains_key(prefix)
                            || requester_path.is_some_and(|rp| {
                                instance_ids_by_path.contains_key(&format!("{rp}.{prefix}"))
                            }))
                });
            if !known.contains(format!("{requester}/{label}").as_str())
                && !known.contains(format!("/{label}").as_str())
                && !inert
            {
                return Err(RunError::Lowering(LoweringError::unsupported(
                    &format!(
                        "disable of `{label}` (an instance-path target is supported only for a \
                         named block of a process or fork branch that can suspend, or a task; IEEE 1800-2023 9.6.2)"
                    ),
                    path.display().to_string().as_str(),
                )));
            }
        }
    }

    // --- STATE (instance half): allocate one `StateEngine` instance per
    // elaborated instance (identical definitions share one layout/template,
    // per the dedup pass above; each `allocate_instance` call still mints a
    // fresh, disjoint arena range and a fresh `InstanceId`, which is what
    // gives two instances of one module their own independent storage). ----
    let mut state_engine = StateEngine::new(templates);
    // Nothing in a run drains STATE's value-change log (observers read STATE
    // directly), so it would hold every change of the run (ST-124).
    state_engine.set_change_log(false);
    let mut instance_sim_handle: HashMap<InstanceId, SimHandle> = HashMap::new();
    for &id in &registration_order {
        let key = *elaborated.dedup_key(elaborated.instance(id).template);
        let instance_handle = state_engine.allocate_instance(key).expect(
            "every distinct dedup TemplateKey reachable via registration_order was \
             registered into `templates` by the loop above before any allocate_instance call",
        );
        let handle = instance_handle.into_sim_handle();
        // Every instance is a DPI scope (`svGetScopeFromName`).
        crate::dpi::register_scope(
            &elaborated.instance_symbol(id).hierarchical_path(),
            handle.0 as usize,
        );
        instance_sim_handle.insert(id, handle);
    }
    for (id, key, _) in &packages {
        let handle = state_engine
            .allocate_instance(*key)
            .expect("every package template was registered above")
            .into_sim_handle();
        instance_sim_handle.insert(*id, handle);
    }
    if needs_bank {
        let handle = state_engine
            .allocate_instance(bank_key)
            .expect("the driver bank template was registered above")
            .into_sim_handle();
        instance_sim_handle.insert(bank_id, handle);
    }

    // Foreign slots (see `instance_foreign`), now that every instance has
    // its handle -- before any kernel runs.
    for (&id, (own, targets)) in &instance_foreign {
        let targets: Vec<(SimHandle, SlotId, Option<AliasWindow>)> = targets
            .iter()
            .map(|&(owner, slot, window)| (instance_sim_handle[&owner], SlotId(slot), window))
            .collect();
        let registered_own =
            set_foreign_slots_windowed(&mut state_engine, instance_sim_handle[&id], &targets);
        assert_eq!(
            registered_own, *own,
            "an instance's own slot count is its template layout's"
        );
    }

    // Task S8 fix (XC-001, `docs/superpowers/plans/2026-09-26-wave-A2-slice.md`):
    // `allocate_instance` only *records* each slot's `CellReset` policy
    // (`instance.rs`'s own doc comment: "populated in exact lockstep with
    // ... alloc_cell") -- it never blits that policy into the arena itself.
    // A freshly allocated instance's raw words are therefore whatever
    // `Arena::alloc_inline_words`/`alloc_wide_words` zero-initialized them
    // to (val=0/unk=0, i.e. a well-known `0`), not the honest 4-state X an
    // uninitialized `logic` must read as before its first driven write
    // (LRM 1800-2023 §6.8) -- `StateEngine::reset_to_initial` is the one
    // call that actually re-blits `CellReset::AllX`/`Initial(_)` over the
    // arena. Without it, `run_design` silently diverged from Icarus on
    // exactly the construct XC-001 names (a register read before it is
    // ever written): reproduced by this task's own `counter.sv` fixture
    // (`crates/vj-harness/tests/slice_vs_iverilog.rs`), whose first
    // `$display` line read back `"0000"` instead of the correct `"xxxx"`
    // before this call was added -- recorded failure, not a hypothetical.
    // Called exactly once, here, after every instance has been allocated
    // (`reset_to_initial` itself walks the WHOLE engine's `cells`/
    // `cell_reset` tables, not one instance's own slice of them), per Task
    // F3's own plan text ("keep that for every instance you allocate").
    state_engine.reset_to_initial_with(X_INITIAL_ZERO.load(std::sync::atomic::Ordering::Relaxed));
    // A net starts at Z (`state::layout`); the bits a driver drives start at
    // X instead -- the driver's value is unknown until it first runs (a
    // delayed `assign #2` leaves its net X until then) -- and so does a whole
    // `trireg`, whose initial charge is unknown (LRM 6.6.4.1).
    let mut x_windows = crate::nets::driven_windows(&infos, &instance_signals, &syntax_trees);
    // A net of a user-defined nettype starts at its data type's default value
    // (LRM 6.7.3: `x` for 4-state integral types, 0 for a `real`), as does
    // each driver's contribution cell (not `z`: a real has no such value).
    for (net, &t) in &user_nets.by_net {
        x_windows.remove(net);
        let slot = &instance_signals[&net.0][&net.1];
        // An array of such nets is a memory whose rows already start at the
        // element type's default value (the layout's reset image).
        if matches!(slot.class, SignalSlotClass::Memory { .. }) {
            continue;
        }
        let value = vj_sim::state::bits_to_four_state(&user_nets.types[t].init);
        let cell =
            vj_sim::state::cell_for_slot(instance_sim_handle[&net.0], vj_abi::SlotId(slot.slot));
        state_engine.commit_write(cell, value, &mut ());
    }
    for g in resolution.groups.iter().filter(|g| g.user.is_some()) {
        let value = vj_sim::state::bits_to_four_state(&user_nets.types[g.user.unwrap_or(0)].init);
        for (&(slot, _), row) in g.drivers.iter().zip(&g.driver_rows) {
            // A contribution memory's rows start at the default already (the
            // bank layout's reset image).
            if row.is_some() {
                continue;
            }
            let cell =
                vj_sim::state::cell_for_slot(instance_sim_handle[&bank_id], vj_abi::SlotId(slot));
            state_engine.commit_write(cell, value.clone(), &mut ());
        }
    }
    for &id in &registration_order {
        let body = instance_body_of(&elaborated, id, path)?;
        for uid in crate::nets::trireg_nets(&body, &syntax_trees) {
            x_windows.entry((id, uid)).or_default().push(None);
        }
    }
    for ((id, uid), windows) in &x_windows {
        let Some(slot) = instance_signals.get(id).and_then(|s| s.get(uid)) else {
            continue;
        };
        // (`driven_windows` and `trireg_nets` list nets only.)
        if let SignalSlotClass::Memory { num_rows, .. } = slot.class {
            // An unpacked array of nets: the layout starts every row X, a net
            // starts Z (LRM 6.6.1) with the driven bits X, window by window
            // in the flat `row * width + bit` image (`nets::memory_window`).
            let value = x_memory_value(slot, num_rows, windows);
            let cell =
                vj_sim::state::cell_for_slot(instance_sim_handle[id], vj_abi::SlotId(slot.slot));
            state_engine.commit_write(cell, value, &mut ());
            continue;
        }
        let value = x_window_value(slot, windows);
        let cell = vj_sim::state::cell_for_slot(instance_sim_handle[id], vj_abi::SlotId(slot.slot));
        state_engine.commit_write(cell, value, &mut ());
    }

    // --- SCHED: register every compiled process, then every instance's own
    // port-connection processes, then run to completion. -------------------
    let mut engine = Engine::new(Box::new(state_engine), Box::new(NullIoSink));

    // The scheduler tick: the design's finest time precision
    // (`vj_codegen::timescale`), which `%t` defaults to.
    let tick_exp = registration_order
        .first()
        .map(|&id| vj_codegen::timescale::design_tick_exp(&elaborated.instance_symbol(id)))
        .unwrap_or(0);
    vj_runtime::timefmt::set_design_tick_exp(tick_exp);

    // VPI (`crate::vpi::sim`): its objects reach their STATE now that the
    // instances exist, and a run with a VPI library gets the engine's
    // scheduling hooks for its callbacks and writes.
    // The planned timing processes as data (`vj_exec::timing`), and the live cells they
    // share with the annotator: the same plan an AOT image carries.
    let timing_plan = vj_exec::timing::TimingPlan {
        prims: std::mem::take(&mut prim_plans.prims),
        lines: std::mem::take(&mut prim_plans.lines),
        device_init: std::mem::take(&mut prim_plans.device_init),
        specify: specify_plans.spec(),
        checks: timing_check_plans.spec(),
        sdf: Default::default(),
        interconnect: Default::default(),
    };
    let timing_live = vj_exec::timing::TimingLive::new(&timing_plan);
    let sdf_live = std::sync::Arc::clone(&timing_live.paths);
    let sdf_check_live = std::sync::Arc::clone(&timing_live.checks);
    // Module paths reach the live delays `$sdf_annotate` also writes.
    fill_vpi_planner_facts(
        &mut vpi_boot,
        &timing_model,
        &body_id_to_instance,
        &instance_signals,
        tick_exp,
    );
    // Interconnect paths, delay devices and delay terms (37.37, 37.45) read and write the
    // interconnect delay table through the wires' nodes.
    vpi_boot.attach_runtime(
        |id| instance_sim_handle.get(&id).copied(),
        &sdf_live,
        &sdf_check_live,
        &interconnect_table,
    );
    if !vpi_libraries.is_empty() {
        engine.set_host(Box::new(crate::vpi::sim::VpiHost));
        vj_sim::sched::record_force_events(true);
    }
    // The planned timing processes as data (`vj_exec::timing`), and the live cells they
    // share with the annotator: the same plan an AOT image carries.
    // `$sdf_annotate` (LRM 32): the runtime call reaches this design's annotator through the
    // thread's installed applier, which the guard removes when this run ends.
    let _sdf_applier = crate::sdf_apply::Installed::new(
        crate::sdf_apply::Annotator::new(
            timing_model.paths.clone(),
            crate::sdf_apply::instance_table(&infos, &instance_signals),
            crate::sdf_apply::condition_specparams(&timing_model),
            sdf_live,
            crate::primitives::device_cells(&prim_plans.device, &timing_live),
            tick_exp,
        )
        .with_primitives(crate::primitives::prim_cells(
            &prim_plans.by_path,
            &timing_live,
        ))
        .with_checks(timing_model.timing_checks.clone(), sdf_check_live)
        .with_options(&timing)
        .with_labels(crate::sdf_labels::collect(&eval, &bodies, &timing_model))
        .with_interconnect(std::sync::Arc::clone(&interconnect_table)),
    );
    // Static concurrent assertions, checker free variables and the sampled
    // value functions' history: the same verification image `vj build-aot`
    // serializes, built over this session's functions and run by the same
    // `vj_exec::verif` code. Each assertion's kernel runs only its action
    // blocks, so it is never registered below.
    let mut scratch = crate::verif_image::ScratchSymbols::default();
    let verif_image = {
        let body_infos: Vec<_> = bodies
            .iter()
            .map(|(id, body)| crate::verif_image::BodyInfo {
                instance: *id,
                body,
                signals: &instance_signals[id],
                port_sources: &port_sources,
            })
            .collect();
        crate::verif_image::build(
            pipeline.assertions(),
            |plan_index| {
                kernel_names
                    .get(plan_index)
                    .map(
                        |(name, frame_words, _, id, _, _)| crate::verif_image::KernelInfo {
                            name,
                            frame_words: *frame_words,
                            instance: *id,
                        },
                    )
            },
            &body_infos,
            &syntax_trees,
            &cov_plan,
            |name| scratch.intern(name),
        )
        .map_err(RunError::Lowering)?
    };
    let assertion_plans: HashSet<usize> = pipeline
        .assertions()
        .iter()
        .filter(|a| a.end_cell.is_none())
        .map(|a| a.plan_index)
        .collect();
    let verif = vj_exec::verif::Verif::build(
        &verif_image,
        &scratch.names,
        &crate::verif_image::PipelineResolver(&pipeline),
        &instance_sim_handle,
        &pipeline.fork_table(),
        &pipeline.wait_table(),
    )
    .map_err(|e| RunError::Jit(e.to_string()))?;
    verif.set_fork_kernels(&pipeline.fork_kernels().map_err(RunError::Lowering)?);
    verif.start(&engine);

    // Waveform dumping (`$dumpvars` & co., `crate::dump`): every variable/
    // net of every instance (memories and events are not dumped), sampled
    // at the end of each timestep.
    {
        // The signals were listed before the AOT split, so a built image and
        // this run name the same ones; the dump's timescale is the scheduler
        // tick.
        let table = crate::dump::table_from_image(&dump_signals, &instance_sim_handle);
        let (text, exp10) = crate::dump::timescale(tick_exp);
        crate::dump::install(table, text, exp10);
    }
    // Code coverage (`--coverage`): installed only when asked for.
    let code_cov = vj_runtime::codecov::enabled();
    if code_cov {
        vj_runtime::codecov::install(&dump_signals, &fsms, &instance_sim_handle);
    }
    let fork_table = pipeline.fork_table();
    let fork_kernels = pipeline.fork_kernels().map_err(RunError::Lowering)?;
    let wait_table = pipeline.wait_table();
    // Registration order is dispatch order within a time step: every
    // continuous process (primitives and delay lines, continuous assigns,
    // port connections, clocking samplers, net resolvers) comes before the
    // procedural ones (below). So at time 0 a continuous assignment settles
    // from the declaration initializers before an edge-triggered `always`
    // starts waiting -- as Icarus orders them -- while a write an `initial`
    // makes still wakes it; and a delayed update due at the same time as a
    // process's wake-up, scheduled earlier, goes first. The exception is an
    // `always @*`: it is registered first, so it is already waiting when
    // those time-zero updates change its inputs from X, and runs on them.
    let register_procedural = |engine: &mut Engine, level_heads: bool| -> Result<(), RunError> {
        for (plan_index, (name, frame_words, kind, id, spec, level)) in
            kernel_names.iter().enumerate()
        {
            if assertion_plans.contains(&plan_index) || *level != level_heads {
                continue;
            }
            let sim_handle = instance_sim_handle[id];
            let kernel = pipeline.get_process_fn(name).ok_or_else(|| {
                RunError::Jit(format!(
                    "get_process_fn: JIT did not produce a callable pointer for `{name}`"
                ))
            })?;
            let proc = CompiledKernelProcess::new(kernel, *frame_words, sim_handle)
                .with_fork_table(fork_table.clone())
                .with_fork_kernels(fork_kernels.clone())
                .with_wait_table(wait_table.clone())
                .with_instance_slot_mapping()
                .with_disable_scopes(id.0, kernel_disable_scopes[plan_index].clone());
            let proc = if pipeline.export_tasks().is_empty() {
                proc
            } else {
                proc.with_task_fibers()
            };
            // Real static sensitivity for `AlwaysComb`/`AlwaysLatch` (the
            // whole-procedure read set) and an `AlwaysFF`'s async reset;
            // `None` for every other kind.
            let (sensitivity, narrowed) =
                match build_static_sensitivity(spec, &instance_signals[id], sim_handle, path)? {
                    Some((s, n)) => (Some(s), n),
                    None => (None, Vec::new()),
                };
            // LRM 18.14.1: seed the process from its instance's
            // initialization RNG, so its random stream is a function of where
            // it sits in the design, not of how many processes the rest of
            // the design registered.
            engine.set_registration_scope(Some(id.0));
            let pid = if reactive_kernels.contains(&plan_index) {
                let pid = engine.register_reactive_process(Box::new(proc), *kind, sensitivity, 0);
                if program_initial_kernels.contains(&plan_index) {
                    engine.mark_program_initial(pid);
                }
                pid
            } else {
                engine.register_procedure(Box::new(proc), *kind, sensitivity, 0)
            };
            for (cell, windows) in &narrowed {
                engine.narrow_static_sensitivity(pid, *cell, windows);
            }
            vj_sim::sched::proc_assert::register_process(plan_index as i64, pid);
            if !vpi_libraries.is_empty() {
                let (body, sym) = vpi_boot.kernel_dyn[plan_index].clone();
                crate::vpi::dynobj::note_root(pid, body, sym);
            }
            engine.set_registration_scope(None);
        }
        Ok(())
    };
    register_procedural(&mut engine, true)?;
    vj_exec::timing::register_all(
        &timing_plan,
        &timing_live,
        &instance_sim_handle,
        &mut engine,
    );

    // Task 2 (NL-034): every module-level continuous `assign`'s compiled
    // kernel, registered exactly like an `always_comb` kernel above --
    // `ProcessKind::AlwaysComb` (a level-sensitive process dispatched once
    // at registration and re-dispatched on every source change, exactly a
    // continuous assignment's own LRM semantics), static sensitivity built
    // from the RHS's own whole-expression read-set (`build_static_sensitivity`
    // reused unchanged -- a continuous assign never has an `AlwaysFF` reset,
    // so `KernelSensitivitySpec::reset` is always `None` here), zero frame
    // words (a continuous assign's kernel declares no frame-local of its
    // own -- see `lower_cont_assign_kernel_fn`'s own doc comment).
    for (ca_index, (name, id, read_set, var_init)) in cont_assign_kernel_names.iter().enumerate() {
        let sim_handle = instance_sim_handle[id];
        let kernel = pipeline.get_process_fn(name).ok_or_else(|| {
            RunError::Jit(format!(
                "get_process_fn: JIT did not produce a callable pointer for `{name}`"
            ))
        })?;
        let proc = CompiledKernelProcess::new(kernel, 0, sim_handle).with_instance_slot_mapping();
        let spec = KernelSensitivitySpec {
            read_set: read_set.clone(),
            windows: HashMap::new(),
            reset: None,
        };
        let sensitivity =
            build_static_sensitivity(&spec, &instance_signals[id], sim_handle, path)?.map(|s| s.0);
        // A variable initializer has no active thread: its process draws from
        // its instance's initialization RNG (LRM 18.14.1), so an object it
        // creates is seeded from that.
        if *var_init {
            engine.set_registration_scope(Some(id.0));
            engine.set_registration_static_initializer(true);
        }
        if reactive_cont_assigns.contains(&ca_index) {
            engine.register_reactive_process(
                Box::new(proc),
                ProcessKind::AlwaysComb,
                sensitivity,
                0,
            );
        } else {
            engine.register_process(Box::new(proc), ProcessKind::AlwaysComb, sensitivity, 0);
        }
        if *var_init {
            engine.set_registration_scope(None);
            engine.set_registration_static_initializer(false);
        }
    }

    // Every port wire (planned above as data, shared with an AOT `.so`), built by
    // `vj-exec` and registered at once, in plan order: plain, or (for a design that
    // calls `$sdf_annotate`) delay-capable (`crate::interconnect`).
    let mut wire_specs: Vec<crate::interconnect::WireSpec> = Vec::new();
    for (wire, info) in planned_wires {
        let (plain, src_cell) = vj_exec::wires::build_wire(&instance_sim_handle, &wire)
            .map_err(|e| RunError::Lowering(LoweringError::unsupported(&e.0, "port wire")))?;
        wire_specs.push(crate::interconnect::WireSpec {
            plain,
            src_cell,
            info,
        });
    }
    crate::interconnect::register(
        wire_specs,
        sdf_kick.map(|slot| loc_of(bank_id, slot)),
        &instance_sim_handle,
        &mut engine,
        &interconnect_table,
    );
    // LRM 30.7.4: the global pulse style / showcancelled options also govern the interconnect
    // delay lines (they have no declarations of their own, so the options are all there is).
    interconnect_table
        .lock()
        .unwrap()
        .set_pulse(timing.default_pulse_style(), timing.default_showcancelled());

    // The samplers (`vj_exec::verif::Verif::register_samplers`): each
    // covergroup with a clocking event, then each clocking block, woken by its
    // event. (The covergroups' tables were registered with the runtime when
    // `Verif` was built.)
    verif
        .register_samplers(&mut engine)
        .map_err(|e| RunError::Jit(e.to_string()))?;
    // Sampled value functions' history, then the assertions' rows, then the
    // dump (the dump never shows hidden cells, so that order is only for
    // clarity).
    engine.set_timestep_end_hook(Box::new(move |now| {
        verif.end_of_step();
        if code_cov {
            vj_runtime::codecov::sample();
        }
        crate::dump::sample(now.ticks)
    }));

    // One resolver process per resolved net group, switch networks first
    // (`vj_exec::nets`): it folds the group's contribution cells and writes
    // every net of it. Covers every group `group_is_native` did not claim
    // above (plain cell nets of a built-in nettype) -- for both `vj run`
    // and `vj run-aot`.
    vj_exec::nets::register_group_resolvers(
        &planned_groups,
        &planned_networks,
        needs_bank.then_some(bank_id),
        &instance_sim_handle,
        &mut engine,
    )
    .map_err(|e| RunError::Lowering(LoweringError::unsupported(&e.0, "net resolver")))?;

    // The native resolvers `group_is_native` claimed above (a user-defined
    // nettype's group, a group whose drivers or nets are rows of an
    // unpacked-array net): the same `vj_exec::usernets` code a built `.so`
    // runs, over the plan built above.
    {
        let symbols: Vec<String> = native_nets
            .types
            .iter()
            .filter_map(|t| t.func.clone())
            .collect();
        vj_exec::usernets::register(
            &native_nets,
            &symbols,
            &crate::verif_image::PipelineResolver(&pipeline),
            needs_bank.then_some(bank_id),
            &instance_sim_handle,
            &mut engine,
        )
        .map_err(|e| RunError::Lowering(LoweringError::unsupported(&e.0, "net resolver")))?;
    }

    // The procedural processes (see the registration-order note above).
    register_procedural(&mut engine, false)?;

    // Every kernel is lowered now: the statement sites the probes number.
    if code_cov {
        vj_runtime::codecov::set_stmt_sites(
            vj_codegen::stmtcov::enabled().then(vj_codegen::stmtcov::take_sites),
        );
    }

    // One timestep per `run_until` call, writing each timestep's output as
    // soon as it exists: `$display` accumulates in a thread-local buffer,
    // so a single `run_until(None)` showed nothing until the whole run
    // ended -- and a long run killed by a timeout lost all of it.
    //
    // A DPI call (`sv_rt_dpi_sync`) writes pending output mid-timestep, so
    // it interleaves correctly with the C code's own; it reaches `stdout`
    // through `dpi_out`, the only way `stdout` is used while it is set.
    // Deferred assertion reports mature into the same output.
    vj_sim::sched::set_deferred_writer(vj_runtime::display_sink::write_deferred);
    vj_sim::sched::set_violation_writer(vj_runtime::display_sink::write_deferred);
    let dpi_out = crate::dpi::OutputGuard::set(stdout);
    // The simulation lifecycle callbacks (IEEE 1800-2023 38.36): the design
    // is compiled and elaborated, nothing has run yet.
    crate::vpi::callbacks::deliver_lifecycle(crate::vpi::consts::CB_END_OF_COMPILE, 0);
    crate::vpi::state::set_phase(crate::vpi::state::Phase::Run);
    crate::vpi::callbacks::deliver_lifecycle(crate::vpi::consts::CB_START_OF_SIMULATION, 0);
    // The assertion system is initialized (39.4.1); from now on its control
    // changes reach the VPI assertion callbacks.
    if crate::vpi::sim::active() {
        crate::vpi::sim::enable_control_events(true);
        crate::vpi::sim::deliver_assertion_sys_callbacks(true);
    }
    // `vpi_control(vpiFinish)` from a start-of-simulation callback ends the
    // run before any design code executes; from later code, at the end of the
    // current time step (a `$finish` in the design takes precedence).
    let code = if let Some(code) = crate::vpi::state::take_finish_request() {
        code
    } else {
        loop {
            let next = SchedTime {
                ticks: engine.now().ticks + 1,
            };
            let result = engine.run_until(Some(next));
            // Between time steps no process is running: reclaim objects only
            // a reference cycle keeps alive (LRM 8.29), once enough have
            // been allocated to be worth a heap walk.
            if _class_design_run.is_some() {
                vj_sim::objects::maybe_collect_cycles();
            }
            let pending = take_output();
            if !pending.is_empty() {
                dpi_out.write(&pending).map_err(RunError::Io)?;
            }
            let requested = crate::vpi::state::take_finish_request();
            match result {
                vj_sim::sched::RunResult::Finished { code } => break code,
                vj_sim::sched::RunResult::Completed => break requested.unwrap_or(0),
                vj_sim::sched::RunResult::Deadline => {
                    if let Some(code) = requested {
                        break code;
                    }
                }
                vj_sim::sched::RunResult::Livelock(msg) => {
                    return Err(RunError::Livelock(msg));
                }
            }
        }
    };

    // Review fix (r2, blocking finding 1): `run_until` only drains the
    // 5-region timestep loop -- `final` blocks (`ProcessKind::Final`) are
    // deliberately routed outside that loop (see `sched::finals`'s own doc
    // comment) and are run in one dedicated post-simulation pass. Without
    // this call, `final` blocks are accepted at discovery/registration time
    // but their bodies never execute: no error, exit code 0, and any
    // `$display` inside a `final` block silently never reaches stdout,
    // unlike real `iverilog`/`vvp` on the same source. Must happen before
    // `take_output()` so the final pass's own IO is captured too.
    engine.run_finals();
    crate::vpi::callbacks::deliver_lifecycle(
        crate::vpi::consts::CB_END_OF_SIMULATION,
        engine.now().ticks,
    );

    // Flush and close the waveform dump (`crate::dump`) before returning.
    crate::dump::finish(engine.now().ticks);
    if vj_runtime::codecov::enabled() {
        vj_runtime::codecov::uninstall();
    }
    // The coverage report (`+vj_coverage_report`) and database (19.9).
    if let Some(report) = vj_exec::covergroups::finish(plusargs) {
        dpi_out.write(&take_output()).map_err(RunError::Io)?;
        dpi_out.write(report.as_bytes()).map_err(RunError::Io)?;
    }

    dpi_out.write(&take_output()).map_err(RunError::Io)?;
    drop(dpi_out);
    // `VJ_OBJECT_STATS=1`: the object heap's state at the end of the run
    // (what reference counting and the cycle collector left alive).
    if std::env::var("VJ_OBJECT_STATS").is_ok_and(|v| v == "1") {
        eprintln!(
            "vj: objects live={} collected={}",
            vj_sim::objects::live_count(),
            vj_sim::objects::collected_count()
        );
        eprintln!("vj: collections live={}", vj_sim::collections::live_count());
    }

    // Every `sim_handle` above's `InstanceHandle` was intentionally leaked
    // into a raw pointer (the established, documented pattern this
    // workspace's own STATE tests already use: "the handle's lifetime is
    // the simulation run's" -- `InstanceHandle::into_sim_handle`'s own doc
    // comment). This process is about to exit (or, in a test, every
    // handle's underlying `Arena`/`TemplateRegistry` allocations are kept
    // alive by `state_engine`'s -- now moved into `engine` -- own `Rc`
    // clones for the process's whole remaining lifetime), so no reclaim is
    // attempted here, matching every other real caller of this API in this
    // tree.

    // A `$sdf_annotate` that could not annotate finished the run at its call (the runtime
    // asked the scheduler, as `$fatal` does); the run's own output above is already written,
    // and the run fails rather than exiting as if the delays had been annotated.
    if let Some(msg) = vj_runtime::sdf_annotate::take_failure() {
        return Err(RunError::SdfAnnotate(msg));
    }

    Ok(vj_runtime::severity::error_exit_code(
        crate::vpi::state::strict_exit_code(code),
    ))
}

/// The value a net's `slot` starts with once the bits `windows` list (`None`: the
/// whole net) are known to be driven: X where a driver will write, Z elsewhere
/// (a net starts at Z, but the bits a driver drives start at X: its value is
/// unknown until it first runs). Shared by `vj run` and `vj build-aot`
/// (which stores the value in the design image) so the two cannot disagree.
/// [`x_window_value`] for an unpacked array of nets: `num_rows` rows of
/// `slot.width` bits, `windows` in the flat `row * width + bit` image.
fn x_memory_value(
    slot: &SignalSlot,
    num_rows: u32,
    windows: &[Option<(u32, u32)>],
) -> FourStateValue {
    let (mut aval, mut bval) = (Vec::new(), Vec::new());
    for r in 0..num_rows {
        let base = r * slot.width;
        let row: Vec<Option<(u32, u32)>> = windows
            .iter()
            .filter_map(|w| match w {
                None => Some(None),
                Some((lo, width)) => {
                    let (s, e) = (*lo.max(&base), (lo + width).min(base + slot.width));
                    (s < e).then(|| Some((s - base, e - s)))
                }
            })
            .collect();
        let v = x_window_value(
            &SignalSlot {
                class: SignalSlotClass::Wide,
                ..*slot
            },
            &row,
        );
        if let FourStateValue::Wide { aval: a, bval: b } = v {
            aval.extend(a);
            bval.extend(b);
        }
    }
    FourStateValue::Wide { aval, bval }
}

/// The planner facts of [`crate::vpi::boot::VpiBoot`] that do not come from
/// the codegen's site tables: module path / timing check keys, the body ->
/// instance map and the slots of the signals a model object names. Shared by
/// `vj run` and `vj build-aot` so both fill the struct identically.
fn fill_vpi_planner_facts(
    boot: &mut crate::vpi::boot::VpiBoot,
    timing_model: &vj_sim::netlist::specify::TimingModel,
    body_id_to_instance: &HashMap<SymbolId, InstanceId>,
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    tick_exp: i32,
) {
    boot.path_keys = timing_model
        .paths
        .iter()
        .map(|e| (e.instance, e.path_uid.clone()))
        .collect();
    boot.check_keys = timing_model
        .timing_checks
        .iter()
        .map(|e| (e.instance, e.check_uid.clone()))
        .collect();
    boot.bodies = body_id_to_instance
        .iter()
        .map(|(b, i)| (b.clone(), *i))
        .collect();
    boot.signals = {
        // Only the signals some model object names (`vpi::boot::used_signals`).
        let used = crate::vpi::state::model()
            .map(|m| crate::vpi::boot::used_signals(&m))
            .unwrap_or_default();
        used.iter()
            .filter_map(|(body, sym)| {
                let id = *body_id_to_instance.get(body)?;
                let slot = *instance_signals.get(&id)?.get(sym)?;
                Some((id, sym.clone(), slot))
            })
            .collect()
    };
    boot.tick_exp = tick_exp;
    boot.canonicalize();
}

fn x_window_value(slot: &SignalSlot, windows: &[Option<(u32, u32)>]) -> FourStateValue {
    let words = slot.width.div_ceil(64).max(1) as usize;
    let mut driven = vec![0u64; words];
    for w in windows {
        let (lo, width) = w.unwrap_or((0, slot.width));
        for b in lo..(lo + width).min(slot.width) {
            driven[(b / 64) as usize] |= 1 << (b % 64);
        }
    }
    let mut all = vec![u64::MAX; words];
    if !slot.width.is_multiple_of(64) {
        all[words - 1] = (1u64 << (slot.width % 64)) - 1;
    }
    // X is (val 0, unk 1) = (aval 1, bval 1); Z is (val 1, unk 1) =
    // (aval 0, bval 1).
    match slot.class {
        SignalSlotClass::Inline => {
            FourStateValue::Narrow(u128::from(all[0] & !driven[0]) | (u128::from(all[0]) << 64))
        }
        _ => FourStateValue::Wide {
            aval: driven.iter().zip(&all).map(|(d, a)| d & a).collect(),
            bval: all.clone(),
        },
    }
}

/// The FSMs the FSM-recognition pragmas (LRM 40.4) of `sources` name, per
/// instance of the module they sit in. A pragma that names a signal or a
/// state parameter the instance does not have is reported and skipped.
fn fsm_images(
    sources: &SourceSet,
    elaborated: &netlist::Netlist<'_>,
    registration_order: &[InstanceId],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
) -> Vec<vj_sim::image::FsmImage> {
    use vj_sim::image::{FsmImage, FsmPartImage};
    let mut defs: HashMap<String, Vec<crate::fsmpragma::FsmDef>> = HashMap::new();
    for path in &sources.files {
        if let Ok(text) = std::fs::read_to_string(path) {
            for (m, v) in
                crate::fsmpragma::extract(&text, &path.to_string_lossy(), &sources.include_dirs)
            {
                defs.entry(m).or_default().extend(v);
            }
        }
    }
    let mut out = Vec::new();
    if defs.is_empty() {
        return out;
    }
    for &id in registration_order {
        let inst = elaborated.instance_symbol(id);
        let Some(body) = inst.instance_body() else {
            continue;
        };
        let Some(def) = inst.instance_definition().map(|d| d.name().to_string()) else {
            continue;
        };
        let Some(fsms) = defs.get(&def) else { continue };
        let signals = &instance_signals[&id];
        let items = vj_sim::netlist::state_items(&body);
        let params: HashMap<String, Option<u64>> = vj_sim::netlist::module_items(&body)
            .iter()
            .filter(|m| m.kind() == SymbolKind::Parameter)
            .map(|m| {
                (
                    m.name().to_string(),
                    m.constant_value()
                        .and_then(|v| v.as_integer().and_then(|i| i.as_u64())),
                )
            })
            .collect();
        'fsm: for f in fsms {
            let mut parts = Vec::new();
            let mut total = 0u32;
            for (sig, range) in &f.parts {
                let found = items.iter().find(|m| {
                    m.name() == sig.as_str()
                        && matches!(m.kind(), SymbolKind::Variable | SymbolKind::Net)
                });
                let slot = found.and_then(|m| signals.get(&m.uid()));
                let Some(slot) = slot.filter(|s| s.class == SignalSlotClass::Inline) else {
                    eprintln!(
                        "warning: FSM `{}` in `{def}`: state signal `{sig}` is not a scalar \
                         variable or net of the module (FSM coverage skipped)",
                        f.name
                    );
                    continue 'fsm;
                };
                let (msb, lsb) = range.unwrap_or((slot.width - 1, 0));
                if msb < lsb || msb >= slot.width {
                    eprintln!(
                        "warning: FSM `{}` in `{def}`: part-select [{msb}:{lsb}] of `{sig}` is \
                         out of range (FSM coverage skipped)",
                        f.name
                    );
                    continue 'fsm;
                }
                total += msb - lsb + 1;
                parts.push(FsmPartImage {
                    slot: slot.slot,
                    msb,
                    lsb,
                });
            }
            if total > 64 {
                eprintln!(
                    "warning: FSM `{}` in `{def}`: a state vector wider than 64 bits is not \
                     supported (FSM coverage skipped)",
                    f.name
                );
                continue;
            }
            let mut states = Vec::new();
            for st in &f.states {
                match params.get(st) {
                    Some(Some(v)) => states.push((st.clone(), *v)),
                    _ => {
                        eprintln!(
                            "warning: FSM `{}` in `{def}`: state `{st}` is not a parameter with \
                             a known value (FSM coverage skipped)",
                            f.name
                        );
                        continue 'fsm;
                    }
                }
            }
            out.push(FsmImage {
                instance: id,
                name: f.name.clone(),
                parts,
                states,
            });
        }
    }
    out
}

/// For an instance's input ports connected to a whole net of the parent of
/// the port's width, the port's internal symbol and that parent net: the
/// child's input net holds only a strong copy, so the port's strengths are
/// the parent net's.
fn input_parent_nets(inst: &sv_lang::Symbol<'_>) -> HashMap<SymbolId, SymbolId> {
    let mut out = HashMap::new();
    for conn in inst.instance_port_connections() {
        let port = conn.port();
        if port.kind() != SymbolKind::Port || port.port_direction() != ArgumentDirection::In {
            continue;
        }
        let Some(expr) = conn.expression() else {
            continue;
        };
        let target = crate::nets::connection_target(expr);
        let member = port.port_internal_symbol().unwrap_or(port);
        if vj_sim::symid::is_value_name(target.kind())
            && let Some(parent_net) = target.referenced_symbol()
            && parent_net.kind() == SymbolKind::Net
            && parent_net.value_type().map(|t| t.bit_width())
                == member.value_type().map(|t| t.bit_width())
        {
            out.insert(member.uid(), parent_net.uid());
        }
    }
    out
}

/// The `$dumpports` fixture/DUT driver split of each dumped port's net
/// (LRM 21.7.4.3.2), planned alongside the resolver groups.
#[derive(Default)]
struct PortViews {
    /// Per resolver group (index into `Resolution::groups`), its port views.
    sides: HashMap<usize, Vec<vj_sim::image::SideSpec>>,
    /// The side key of each port, by `(instance, internal symbol)`.
    side_keys: HashMap<(InstanceId, SymbolId), u64>,
}

/// Plans [`PortViews`]: for every port of every instance whose net a
/// (non-native) resolver group resolves, which of the group's drivers belong
/// to the port's instance (its subtree, but not the port connection driving
/// its own input port, which is the fixture around it) and which to the
/// fixture.
fn dump_port_views(
    elaborated: &netlist::Netlist<'_>,
    registration_order: &[InstanceId],
    resolution: &crate::nets::Resolution,
    native_groups: &[bool],
) -> PortViews {
    let mut group_of: HashMap<(InstanceId, SymbolId), usize> = HashMap::new();
    for (gi, g) in resolution.groups.iter().enumerate() {
        if native_groups[gi] || g.switched {
            continue;
        }
        for n in &g.nets {
            group_of.insert(n.clone(), gi);
        }
    }
    let key_of_slot: HashMap<u32, &crate::nets::DriverKey> =
        resolution.contrib.iter().map(|(k, &s)| (s, k)).collect();
    let in_subtree = |mut x: InstanceId, root: InstanceId| loop {
        if x == root {
            break true;
        }
        match elaborated.instance(x).parent {
            Some(p) => x = p,
            None => break false,
        }
    };
    let mut views = PortViews::default();
    for &id in registration_order {
        let inst = elaborated.instance_symbol(id);
        let Some(body) = inst.instance_body() else {
            continue;
        };
        let parent_nets = input_parent_nets(&inst);
        let ports: Vec<_> = body
            .instance_body_ports()
            .filter(|p| p.kind() == SymbolKind::Port)
            .collect();
        let in_ports: std::collections::HashSet<SymbolId> = ports
            .iter()
            .filter(|p| p.port_direction() == ArgumentDirection::In)
            .map(|p| p.uid())
            .collect();
        for p in &ports {
            let member = p.port_internal_symbol().unwrap_or(*p).uid();
            let net = match (parent_nets.get(&member), elaborated.instance(id).parent) {
                (Some(pn), Some(parent)) => (parent, pn.clone()),
                _ => (id, member.clone()),
            };
            let Some(&gi) = group_of.get(&net) else {
                continue;
            };
            let inside: Vec<bool> = resolution.groups[gi]
                .drivers
                .iter()
                .map(|&(slot, _)| {
                    use crate::nets::DriverKey as K;
                    match key_of_slot.get(&slot) {
                        Some(K::Port(child, port, _)) if *child == id => !in_ports.contains(port),
                        Some(
                            K::Port(i, ..)
                            | K::Assign(i, ..)
                            | K::Prim(i, ..)
                            | K::PrimElem(i, ..)
                            | K::Hidden(i, _)
                            | K::SpecifyPath(i, _)
                            | K::ProcVar(i, _),
                        ) => in_subtree(*i, id),
                        None => false,
                    }
                })
                .collect();
            let key = vj_runtime::fmt::strength_key(&format!(
                "dumpports:{}:{}",
                id.0,
                member.key_string()
            ));
            views.side_keys.insert((id, member), key);
            views
                .sides
                .entry(gi)
                .or_default()
                .push(vj_sim::image::SideSpec { key, inside });
        }
    }
    views
}

/// Every signal `$dumpvars` can select, in design order: each variable/net of
/// every instance (memories, events and collections are not dumped), as the
/// module's own signals then the static variables of its tasks, functions and
/// named blocks (LRM 1800-2023 21.7: only automatic variables are not dumped),
/// each under its scope.
fn dump_signal_images(
    elaborated: &netlist::Netlist<'_>,
    registration_order: &[InstanceId],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    trees: &[sv_lang::SyntaxTree],
    views: &PortViews,
) -> Vec<vj_sim::image::DumpSignalImage> {
    use vj_sim::image::{DumpSignalImage, PortDir, ScopeKind};
    let mut table = Vec::new();
    for &id in registration_order {
        let inst = elaborated.instance_symbol(id);
        let Some(body) = inst.instance_body() else {
            continue;
        };
        // The direction of each port's internal symbol (`$dumpports`).
        let port_dirs: HashMap<SymbolId, PortDir> = body
            .instance_body_ports()
            .filter(|p| p.kind() == SymbolKind::Port)
            .map(|p| {
                let dir = match p.port_direction() {
                    ArgumentDirection::In => PortDir::Input,
                    ArgumentDirection::Out => PortDir::Output,
                    ArgumentDirection::InOut | ArgumentDirection::Ref => PortDir::Inout,
                };
                (p.port_internal_symbol().unwrap_or(p).uid(), dir)
            })
            .collect();
        // The `%v` registry key describing each port's fixture-side strength
        // (`DumpSignalImage::strength_key`): an input port's own net holds a
        // strong copy, so one connected to a whole parent net of its width
        // reads the parent net's record instead.
        let key_of =
            |sym: &sv_lang::Symbol<'_>| vj_runtime::fmt::strength_key(&sym.uid().key_string());
        let input_parent_key: HashMap<SymbolId, u64> = input_parent_nets(&inst)
            .into_iter()
            .map(|(member, net)| (member, vj_runtime::fmt::strength_key(&net.key_string())))
            .collect();
        let inst_path = inst.hierarchical_path();
        let inst_scope: Vec<String> = inst_path.split('.').map(str::to_owned).collect();
        let def_name = inst
            .instance_definition()
            .map(|d| d.name().to_string())
            .unwrap_or_default();
        let signals = &instance_signals[&id];
        for member in vj_sim::netlist::state_items(&body) {
            let kind = member.kind();
            if !matches!(
                kind,
                SymbolKind::Variable | SymbolKind::Net | SymbolKind::FormalArgument
            ) {
                continue;
            }
            let Some(info) = signals.get(&member.uid()) else {
                continue;
            };
            let Some(inner_kinds) = dump_scope_kinds(&member) else {
                continue;
            };
            // Memories and collections (a handle) are not dumped. A scalar
            // `event` is: its cell counts triggers (LRM 21.7.2.2), except in a
            // body with an event pool, whose legacy cell is never written.
            let is_event = member.value_type().is_some_and(|t| t.is_event());
            if matches!(info.class, SignalSlotClass::Memory { .. })
                || member
                    .value_type()
                    .is_some_and(|t| vj_sim::state::storage::is_collection(&t))
                || (is_event && vj_sim::state::event_pool::event_pool(&body).is_some())
            {
                continue;
            }
            // A generate block's item dumps under the block's own scope
            // (`top.st[0].r`), not flattened into the instance's.
            let mut scope = inst_scope.clone();
            let path = member.hierarchical_path();
            if let Some(rest) = path
                .strip_prefix(inst_path.as_str())
                .and_then(|r| r.strip_prefix('.'))
                && let Some((blocks, _)) = rest.rsplit_once('.')
            {
                scope.extend(blocks.split('.').map(str::to_owned));
            }
            let mut scope_kinds = vec![ScopeKind::Module; inst_scope.len()];
            scope_kinds.extend(inner_kinds);
            scope_kinds.resize(scope.len(), ScopeKind::Begin);
            table.push(DumpSignalImage {
                instance: id,
                def_name: def_name.clone(),
                scope,
                scope_kinds,
                name: member.name().to_string(),
                width: info.width,
                var_type: dump_var_type(&member, kind, is_event, trees),
                slot: info.slot,
                wide: info.class == SignalSlotClass::Wide,
                real: member.value_type().is_some_and(|t| t.is_floating()),
                class_handle: member.value_type().is_some_and(|t| t.is_class()),
                port: port_dirs.get(&member.uid()).copied(),
                side_key: views.side_keys.get(&(id, member.uid())).copied(),
                strength_key: port_dirs.contains_key(&member.uid()).then(|| {
                    input_parent_key
                        .get(&member.uid())
                        .copied()
                        .unwrap_or_else(|| key_of(&member))
                }),
            });
        }
    }
    table
}

/// The VCD `$var` type of `member` (LRM 21.7.2.1 `var_type`, 21.7.2.3: a
/// `uwire` is a `wire`).
fn dump_var_type(
    member: &sv_lang::Symbol<'_>,
    kind: SymbolKind,
    is_event: bool,
    trees: &[sv_lang::SyntaxTree],
) -> vj_sim::image::VcdVarType {
    use vj_sim::image::VcdVarType as V;
    if is_event {
        return V::Event;
    }
    if kind == SymbolKind::Net {
        return match crate::nets::net_kind_of(member, trees) {
            vj_sim::state::NetKind::WAnd => V::WAnd,
            vj_sim::state::NetKind::WOr => V::WOr,
            vj_sim::state::NetKind::Tri => V::Tri,
            vj_sim::state::NetKind::TriAnd => V::TriAnd,
            vj_sim::state::NetKind::TriOr => V::TriOr,
            vj_sim::state::NetKind::Tri0 => V::Tri0,
            vj_sim::state::NetKind::Tri1 => V::Tri1,
            vj_sim::state::NetKind::TriReg => V::TriReg,
            vj_sim::state::NetKind::Supply0 => V::Supply0,
            vj_sim::state::NetKind::Supply1 => V::Supply1,
            _ => V::Wire,
        };
    }
    let Some(ty) = member.value_type() else {
        return V::Reg;
    };
    if ty.is_floating() {
        return if ty.floating_kind() == sv_lang::FloatKind::RealTime {
            V::RealTime
        } else {
            V::Real
        };
    }
    // An enum dumps as its base type (LRM 21.7.5, Table 21-11: `integer`
    // for the default `int` base).
    let ty = if ty.is_enum() {
        ty.enum_base().unwrap_or(ty)
    } else {
        ty
    };
    if ty.is_predefined_integer() {
        match ty.predefined_integer_kind() {
            // Table 21-11: `int` maps to `integer`; the other predefined
            // integers (`shortint`, `longint`, `byte`) to `reg`.
            sv_lang::PredefinedIntegerKind::Int | sv_lang::PredefinedIntegerKind::Integer => {
                return V::Integer;
            }
            sv_lang::PredefinedIntegerKind::Time => return V::Time,
            _ => {}
        }
    }
    V::Reg
}

/// The VCD scope types of the scopes between `member`'s instance and
/// `member` (outermost first): `begin` for a generate or named block, `fork`
/// for a named fork, `task`/`function` for a subroutine. `None` for a
/// variable of an unnamed block, which has no name to dump it under.
fn dump_scope_kinds(member: &sv_lang::Symbol<'_>) -> Option<Vec<vj_sim::image::ScopeKind>> {
    use vj_sim::image::ScopeKind;
    let mut kinds = Vec::new();
    let mut cur = member.parent();
    while let Some(p) = cur {
        match p.kind() {
            SymbolKind::InstanceBody => break,
            SymbolKind::GenerateBlock => kinds.push(ScopeKind::Begin),
            SymbolKind::StatementBlock => {
                if p.name().is_empty() {
                    return None;
                }
                kinds.push(match p.statement_block_kind() {
                    Some(sv_lang::StatementBlockKind::Sequential) | None => ScopeKind::Begin,
                    Some(_) => ScopeKind::Fork,
                });
            }
            SymbolKind::Subroutine => kinds.push(
                if p.subroutine_kind() == Some(sv_lang::SubroutineKind::Task) {
                    ScopeKind::Task
                } else {
                    ScopeKind::Function
                },
            ),
            _ => {}
        }
        cur = p.parent();
    }
    kinds.reverse();
    Some(kinds)
}