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
//! The `vj`-side specify-block/timing-check planning entry point
//! (`docs/superpowers/plans/2026-10-03-sdf.md`, Track A/B) — mirrors
//! `primitives.rs`'s own module-doc shape: specify-block content is planned
//! as native Rust, never lowered to LLVM (the plan's §1.3 decision 1, the
//! exact same reasoning `primitives.rs`'s own top-of-file doc comment gives
//! for gate/UDP instances and delayed continuous assigns).
//!
//! Task 3 wired discovery (`TimingModel::discover`/`seed_specparams`)
//! through this crate's own `RunError`/`Path` error-reporting convention —
//! [`crate::run::elab_to_run_error`], the SAME one-call-site reconciliation
//! `netlist::elaborate`'s own `ElabError` already goes through.
//!
//! **Task 4a** (this task) adds the file's real "planning entry": [`plan`]/
//! [`register`], a sibling pair to `primitives::plan`/`register` at
//! `run.rs`'s own call site, for a module path whose destination is a net
//! (LRM 30.4.2 simple paths, 30.4.5 full/parallel connection — Full and
//! Parallel desugar into the SAME one-input/one-output [`vj_sim::
//! netlist::specify::PathEntry`] shape by the time this file sees them, so
//! neither needs its own code path here) with a 1/2/3-value delay list
//! (30.5's 6/12-value forms are Task 5's own scope — now landed too:
//! `PathDelaySet::from_list` itself (`crates/vj-sim/src/netlist/
//! specify.rs`) takes all five list lengths, so this task's own retimer
//! code below needed zero changes to pick them up, exactly as the plan's
//! own T5 section states). [`discover`] now also ATTACHES each
//! path's own delay list (evaluated + timescale-converted here, since
//! `vj-sim` can depend on neither `sv_lang::EvalSession`'s evaluator
//! nor `vj-codegen::timescale` together — see [`PathEntry::delays`]'s
//! own doc comment) before [`plan`] ever reads it.
//!
//! **The retiming mechanism itself is `primitives.rs`'s own inertial-delay
//! two-process line (its own module doc), reused, not reinvented**: the
//! destination's REAL functional driver (today: exactly one plain
//! continuous assign — see [`plan`]'s own doc comment for why that is this
//! task's own scope boundary) is redirected to a staging cell exactly the
//! way a delayed continuous assignment already is (`primitives::plan`'s own
//! `ca.delay` handling), and [`PathRetimer`] (this file's own "recorder"
//! half, transition-PAIR-indexed via [`PathDelaySet`] instead of
//! `primitives::Delays`' value-indexed table) plus `primitives::Delayer`
//! (REUSED UNCHANGED as the "committer" half; superseded by [`PathCommitter`]
//! in sdf T10, see below) move the value from staging
//! to the real net after the delay the transition calls for. LRM 30.6's
//! own text — "the module path's own declaration never says what value the
//! destination takes" — is exactly why this works: the retimer never
//! independently decides a value, it only re-times whatever the real driver
//! was already going to write. A destination net targeted by more than one
//! real driver remains this task's own explicit, temporary gap — a named,
//! loud `Err` in [`plan`] rather than a guess at the composition — and the
//! SAME reasoning is why a destination net targeted by more than one
//! `PathEntry` at all (LRM 30.5.3's own multi-path delay selection — Task 6's
//! own scope) is also a named `Err` rather than letting whichever `PathEntry`
//! plans last silently win every transition.
//!
//! **Task 9 (LRM 30.6, "mixing module path delays and distributed
//! delays")** closes the one real driver-count-one gap above: a destination
//! whose single real continuous-assign driver ALSO carries its own `#delay`
//! (a distributed delay, `primitives::Delays`). LRM 30.6's own text — "the
//! larger of the two delays... shall be used" — is a per-transition `max`,
//! not a choice of ONE mechanism over the other, so neither delay line can
//! simply win: `primitives::plan` (extended, see its own module doc and
//! [`primitives::Plans::natural`]'s own doc comment) detects that this
//! destination is ALSO a module-path target and, instead of building its own
//! `Recorder`/`Delayer` line that would commit the natural value to the real
//! net on its own schedule (racing [`PathRetimer`]'s own commit whenever the
//! specify delay is the larger one), hands its own computed `Delays` to
//! [`RetimerPlan::natural`] — [`PathRetimer`] reads it on every real
//! transition (`PathRetimer::resume`'s own `.max(self.natural.of(&[to]))`)
//! and the SAME single [`crate::primitives::Delayer`] this file already
//! reuses as its "committer" ends up the destination's ONLY writer, at
//! `max(natural, specify)`, exactly as Figures 30-3/30-4 (reproduced as this
//! task's own probe-corpus fixtures, `specify_mixing_path_longer.sv`/
//! `specify_mixing_distributed_longer.sv`) require. A destination with NO
//! competing distributed delay (the overwhelming common case, every pre-
//! Task-9 fixture) simply never appears in `Plans::natural`, so
//! `RetimerPlan::natural` defaults to `Delays::default()` (all-zero) and
//! `max(natural, specify)` degenerates to `specify` alone — zero behavior
//! change for any design without one.
//!
//! **Task 4b** extends [`plan`] to a module path whose destination is a
//! VARIABLE (LRM 30.4.1's "net OR variable") written by exactly one
//! nonblocking procedural assignment (today: the common sequential-cell
//! shape, `always @(posedge clk) q <= d;`) — the SAME [`RetimerPlan`]/
//! [`PathRetimer`]/`primitives::Delayer` two-process line Task 4a already
//! built, since neither type has ANY net-specific behavior (both read/write
//! bits through a [`crate::primitives::Place`], never a net-only API) —
//! only the WAY the real driver is found and redirected differs, because a
//! variable's driver is a STATEMENT inside a `ProceduralBlock`, not a
//! `ContinuousAssign` module member `vj-codegen` compiles into its own,
//! separate function the way [`plan`]'s net-destination branch redirects.
//! Redirecting a procedural write needs to reach all the way into
//! `vj-codegen`'s lvalue-write lowering instead
//! (`crate::nets::DriverKey::ProcVar`'s own doc comment names the whole
//! wiring path: this task's new driver key → `run.rs`'s
//! `specify_dest_redirect` table → `ProcessLoweringPlan::
//! specify_dest_redirect` → `LowerCtx::specify_dest` → `select::
//! resolve_lvalue`'s `RootMode::Signal` branch /
//! `process_lower::lower_nonblocking_assignment`'s fast-path exclusion).
//! Scope boundary (same discipline as Task 4a's own net-destination one,
//! named loud errors, never a silent narrowing): the destination must be
//! written by EXACTLY ONE nonblocking assignment, of the WHOLE variable (no
//! bit-select/part-select), and NEVER also by a blocking assignment
//! anywhere — a blocking write's commit path (`crate::expr::
//! write_through_store`) is a genuinely separate mechanism this task does
//! not touch, so one reaching a specify-path destination is this task's own
//! explicit, temporary gap, not a silently un-retimed write.
//!
//! **Task 6** (LRM 30.5.3) replaces Task 4a's own former "more than one
//! `PathEntry` targeting one destination bit is a named, not-yet-
//! implemented `Err`" placeholder (review fix r2's own comment on [`plan`],
//! now superseded) with the real thing: [`RetimerPlan`]/[`PathRetimer`] are
//! generalized from carrying exactly one `(input, delays)` pair to a whole
//! `Vec` of them ([`Member`]/[`RetimerMember`]) — one real retiming STAGE
//! (one staging cell, one kick cell, one commit point) per DESTINATION bit,
//! shared by every `PathEntry` that targets it, exactly as LRM 30.5.3's own
//! text frames it ("there may be specify paths to the output from more than
//! one input... the simulator has to decide which specify path to use").
//! `plan`'s own scope boundary (c) above ("targeted by EXACTLY ONE
//! `PathEntry`") no longer exists; a single-`PathEntry` destination is now
//! simply the degenerate `members.len() == 1` case of the SAME code path,
//! not a separate one, so every pre-Task-6 single-path test exercises
//! exactly the same machinery a multi-path one does.
//!
//! [`PathRetimer::resume`] additionally watches each member's own INPUT
//! cell now (never needed before: a single-member group has nothing to
//! compare against), purely to timestamp "this input's own most recent
//! transition" (`RetimerMember::last_change`) — LRM 30.5.3's selection rule
//! itself is still a pure function of the destination's OWN `(from, to)`
//! transition (read off `staging`, exactly as Task 4a/T5 already do) and
//! each candidate member's delay table; the input cells are watched ONLY to
//! know which member(s) are "active" (most-recently-transitioned, ties
//! broken by treating every member tied for the maximum as simultaneously
//! active — LRM's own text: "it is possible for many specify paths to an
//! output to be simultaneously active"), never to decide the destination's
//! VALUE (still never this module's job — see decision 3 above).
//! [`PathRetimer::select_delay`] is this task's one new piece of real
//! logic; see its own doc comment for the one case 30.5.3 leaves genuinely
//! unaddressed (no member has ever recorded a transition at all) and this
//! task's own documented choice for it.
//!
//! **Condition gating (`if (cond) (a=>q)=...;`) was explicitly NOT part of
//! Task 6's own scope** — at that task, `PathEntry` carried no `condition`
//! field, so 30.5.3's "either they have no condition or their conditions
//! are true" clause was satisfied vacuously (every `PathEntry` reaching
//! [`PathRetimer`] was unconditional).
//!
//! **Task 8 (LRM 30.4.4.*, state-dependent paths) adds the real thing.**
//! [`vj_sim::netlist::specify::PathEntry::condition`] now carries a
//! [`vj_sim::netlist::specify::PathCondition`] (`Unconditional` /
//! `If(CondNode)` / `IfNone`). [`CondNode`](vj_sim::netlist::specify::
//! CondNode) is symbolic data (needs no `sv_lang`/live `Design` to
//! evaluate, but DOES need live simulation state -- LRM 30.4.4.1's own
//! operand list is ports/variables/nets, re-read on every check); this
//! file compiles it in TWO stages mirroring every other plan-time/
//! register-time split already in this file: `compile_cond_plan` (plan
//! time, in [`plan`]) resolves every `Signal` leaf to a [`Loc`] against
//! `own`'s own signal-slot table (the SAME table [`Member::input`]'s own
//! resolution already uses) and every `Specparam` leaf to a BAKED
//! [`CondPlan::Const`] (via [`TimingModel::specparam`] — a specparam
//! referenced inside a condition is, as of this task, a plan-time constant,
//! same discipline [`path_delays_of`]'s own delay-list evaluation already
//! uses; a future task wanting `$sdf_annotate` to reach a CONDITION's own
//! specparam operand, not just a path's delay list, would need to extend
//! this — out of this task's own scope and not needed by any of its
//! worked examples); `cond_eval_of` (register time, in [`register`])
//! resolves every `CondPlan::Signal`'s [`Loc`] to a real [`Place`] exactly
//! like every other `Loc` this file resolves at that point. [`CondEval::
//! eval`] is the native, Table-30-1-closed-operator-set interpreter over
//! live [`Bit4`] bit-vectors (LSB-first, mirroring `sv_lang::SVInt::bits`'s
//! own order) that reads those `Place`s fresh on every call — never cached,
//! per decision 3's own "only when a specify path is actually active for
//! it" (a condition's truth can change between any two checks).
//!
//! [`PathRetimer::select_delay`]'s own eligibility filter (already gating
//! on [`PathEdge`] since Task 7) now ALSO gates on [`RetimerMember::
//! condition`] (a [`RuntimeGate`]): `None` (an unconditional member) is
//! always eligible; `Some(RuntimeGate::If(cond))` is eligible exactly when
//! `cond.is_condition_true()` — LRM 30.4.4.1's own LSB-only rule ("If the
//! conditional expression evaluates to x or z, it shall be treated as
//! true... the LSB shall represent the result"), applied to `cond`'s own
//! OUTERMOST result and nowhere else. An `ifnone` member's own [`Member::
//! condition`] is not carried through from its `PathEntry` directly: it is
//! `Some(RuntimeGate::IfNone(siblings))`, `siblings` being every SIBLING
//! member's own already-compiled `If` condition sharing the exact same
//! INPUT terminal (LRM 30.4.4.4: "a default state-dependent path delay
//! when all other conditions for the path are false"; `None` —
//! unconditional-equivalent — when there are no such siblings, per that
//! same subclause's own text), and it is eligible exactly when NONE of
//! those siblings' OWN `is_condition_true()` says true. Deliberately NOT a
//! single pre-combined `NOT(OR(siblings))` boolean synthesized once as a
//! plain [`CondNode`]: that would run every sibling's raw, possibly
//! multi-bit value through [`CondBinaryOp::LogicalOr`]'s ordinary 4-state
//! `||` truthiness (LRM 11.4.6, "any known 1 bit is true") instead of
//! 30.4.4.1's narrower LSB-only rule, and the two disagree whenever a
//! sibling's raw value's LSB differs from "any bit set" (e.g. `sel ==
//! 2'b10`: LSB `0` so `is_condition_true()` says false, but `truthy()`
//! sees the set bit 1 and says true) — see [`RuntimeGate::is_true`]'s own
//! doc comment and this file's own
//! `select_delay_ifnone_gate_uses_each_siblings_own_lsb_rule_not_raw_or_truthiness`
//! test. No new `StaticSensitivity` watches a condition's own referenced signals: a
//! condition only ever changes WHICH DELAY `select_delay` picks for a
//! transition the destination's own real functional driver was already
//! going to make (decision 3, unchanged by this task) — it never gates
//! whether `staging` itself transitions, so the existing `staging`/
//! member-`input` watches are already sufficient (verified live: a
//! condition-only signal change with no accompanying `staging` transition
//! produces no observable effect either in vj or in `iverilog
//! -gspecify`, for every probe-corpus fixture this task adds).
//!
//! **sdf T10 (LRM 30.7, 30.7.1: pulse control)** replaces the one reused
//! `primitives::Delayer` pending slot with this file's own [`PathQueue`]/
//! [`PathCommitter`]: a single slot is exactly full inertial delay (the
//! default, and still what a path with no `PATHPULSE$` gets, since each limit
//! then equals the delay), but filtering a pulse to `x` needs its LEADING edge
//! to stay scheduled until the TRAILING edge shows how wide the pulse was.
//! [`PathRetimer::resume`] hands the queue the selected delay together with
//! that same member's reject/error limit for the transition ([`Selected`] —
//! the limits of the delay that forms the trailing edge decide, per 30.7), and
//! [`PathQueue::schedule`] applies the three width regions. [`discover`]
//! attaches the limits ([`pulse_limits_of`]) AFTER the delays, since
//! `set_path_delays` resets them to the delays. Implementation-defined choices,
//! each documented where it is made: the limit in force is never below the
//! competing distributed delay (30.6); an error limit below the reject limit is
//! raised to it; a negative limit is zero; a tie between equally fast active
//! members takes the first declared member's limits; and a `PATHPULSE$` matching
//! no path is ignored.
//!
//! **sdf T11 (LRM 30.7.4: pulse style, showcancelled)** carries each path's
//! output pulse style and showcancelled mode ([`PathEntry::pulse_style`]/
//! `showcancelled`, attached at discovery from the `pulsestyle_*`/
//! `*showcancelled` declarations) through [`Member`]/[`RetimerMember`]/
//! [`Selected`] to [`PathQueue::schedule`]. On-detect makes the filtered
//! pulse's `x` at detection time, which only the retimer can do (the committer
//! sleeps until the next scheduled transition): `schedule` returns the
//! immediate `x` and [`PathRetimer::resume`] writes it to the destination.
//! Showcancelled turns a negative pulse (trailing edge scheduled at or before
//! the pending leading edge) from a cancellation into an `x`. The
//! `--showcancelled`/`--noshowcancelled`/`--pulse-style` INVOCATION options (sdf
//! T31, [`crate::timing_options`]) OVERRIDE the declarations of their axis (LRM
//! 30.7.4.1/30.7.4.2: "The pulse style invocation options take precedence over
//! pulse style specify block declarations", the same for showcancelled); an
//! absent option leaves the declarations. The `--timing-reject-limit-pct`/
//! `--timing-error-limit-pct` percentages, by contrast, only replace the
//! limit-equals-delay default under a `PATHPULSE$` (30.7.2).

use std::collections::HashMap;
use std::path::Path;

use sv_lang::kinds::{ExpressionKind, SymbolKind};
use sv_lang::{EvalSession, Expression, SemNode, Symbol};
use vj_abi::bit4::Bit4;
use vj_codegen::error::LoweringError;
use vj_codegen::process_lower::SignalSlot;
use vj_sim::netlist::InstanceId;
use vj_sim::netlist::specify::{
    CondNode, PathCondition, PathDelaySet, PathEdge, PathEntry, TimingModel,
};
use vj_sim::symid::{SymbolId, SymbolUid};

use crate::nets::{DriverKey, Resolution};
use crate::primitives::{Delays, Loc, bank_slot, loc_of};
use crate::run::{RunError, elab_to_run_error};
use crate::timing_options::TimingOptions;
#[cfg(test)]
pub(crate) use vj_exec::timing::specify::{CondEval, cond_eval_of};
pub(crate) use vj_exec::timing::specify::{CondPlan, LiveTimes, PathTimes};
use vj_exec::timing::specify::{
    EdgeSel, Gate, Member, PathEdge as ExecEdge, RetimerPlan, SpecifyPlan,
};

/// `(instance, TimingPath symbol)` for every `TimingPath` member of every
/// specify block across `infos` — mirrors `TimingModel::discover`'s OWN
/// identical walk (`vj-sim/src/netlist/specify.rs`), duplicated here
/// only because evaluating a path's own delay list needs `vj-codegen`'s
/// timescale conversion, which `vj-sim` cannot depend on (see this
/// file's own module doc) — this is how `vj` re-locates the SAME
/// symbol `TimingModel::discover` already found, to read its delay list a
/// second time for a different purpose.
pub(crate) fn timing_path_symbols<'d>(
    infos: &[(InstanceId, Symbol<'d>)],
) -> Vec<(InstanceId, Symbol<'d>)> {
    let mut out = Vec::new();
    for &(id, body) in infos {
        for m in vj_sim::netlist::module_items(&body) {
            if m.kind() != SymbolKind::SpecifyBlock {
                continue;
            }
            for inner in m.members() {
                if inner.kind() == SymbolKind::TimingPath {
                    out.push((id, inner));
                }
            }
        }
    }
    out
}

/// `path`'s own `path_delay_value` list (`path.timing_path_delays()`),
/// evaluated and timescale-converted via [`path_delay_values_of`] below,
/// then shaped into a [`PathDelaySet`] (LRM Table 30-2/30-3).
fn path_delays_of(eval: &EvalSession<'_>, path: &Symbol<'_>) -> Result<PathDelaySet, String> {
    let values = path_delay_values_of(eval, path.timing_path_delays(), path)?;
    PathDelaySet::from_list(&values)
}

/// Review fix (r1): `path`'s own `path_delay_value` expressions, evaluated
/// and timescale-converted — a DELIBERATE, NOT-UNCHANGED copy of
/// `primitives::delay_values_of`'s own min:typ:max/constant-evaluation
/// handling, duplicated here (not reused) for one real behavioral
/// difference this task's own clause requires: LRM 1800-2023 30.5.1's own
/// text — "If the path delay expression results in a negative value, it
/// shall be treated as zero" — is textually different from the rule that
/// governs an ordinary `#delay`/distributed delay (9.4.1's own
/// two's-complement-unsigned-time-value rule, a separate, pre-existing
/// question `vj_codegen::timescale::delay_ticks` answers for every OTHER
/// caller and which this function must not disturb). Reusing
/// `delay_values_of` unchanged — this task's own original, now-fixed defect
/// — silently inherited `delay_ticks`'s hard error on any negative value for
/// module path delays too, rejecting a real, LRM-legal design
/// (`specparam NEG = -3; (a => q) = NEG;`) instead of clamping it to zero.
/// So a negative (but finite — NaN is still a real error, no LRM text here
/// says otherwise) evaluated value is clamped to `0.0` BEFORE it ever
/// reaches `delay_ticks`, which then only ever sees a non-negative input
/// for this call site.
fn path_delay_values_of<'d>(
    eval: &EvalSession<'_>,
    exprs: impl Iterator<Item = Expression<'d>>,
    scope: &Symbol<'_>,
) -> Result<Vec<u64>, String> {
    let tick = vj_codegen::timescale::design_tick_exp(scope);
    let mut out = Vec::new();
    for e in exprs {
        // `min:typ:max` takes the typical value (mirrors
        // `primitives::delay_values_of` exactly — this part of the rule is
        // shared, not clause-specific).
        let e = if e.kind() == ExpressionKind::MinTypMax {
            e.children()
                .into_iter()
                .filter_map(|n| n.as_expression())
                .nth(1)
                .ok_or_else(|| "a min:typ:max delay with no typical value".to_string())?
        } else {
            e
        };
        let c = e
            .constant_value()
            .or_else(|| eval.eval_constant(e))
            .ok_or_else(|| "a delay that is not a constant".to_string())?;
        out.push(constant_to_ticks(c, scope, tick)?);
    }
    Ok(out)
}

/// One evaluated delay-shaped constant, as scheduler ticks: the tail of
/// [`path_delay_values_of`], shared with [`pulse_limits_of`] (a `PATHPULSE$`
/// limit is converted by exactly the same rule as the path delay it limits,
/// so there is one evaluator, not two that can diverge).
///
/// LRM 30.5.1: "If the path delay expression results in a negative value, it
/// shall be treated as zero." NaN is not a negative value (and no LRM text
/// asks for a different NaN rule here), so it is left alone and still fails
/// `delay_ticks`'s own NaN check.
fn constant_to_ticks(
    c: sv_lang::ConstantValue,
    scope: &Symbol<'_>,
    tick: i32,
) -> Result<u64, String> {
    let v = match c {
        sv_lang::ConstantValue::Real(f) => f,
        c => c
            .as_i64()
            .ok_or_else(|| "a delay that is not a number".to_string())? as f64,
    };
    let v = if v.is_finite() && v < 0.0 { 0.0 } else { v };
    vj_codegen::timescale::delay_ticks(v, scope, tick).map_err(|e| e.message)
}

/// Seeds and discovers every specify-block construct across `infos`'
/// `(instance, body)` pairs (the SAME per-instance shape `primitives::plan`'s
/// own `insts` parameter already uses) into a fresh [`TimingModel`], then
/// (Task 4a) attaches every discovered [`PathEntry`](vj_sim::netlist::
/// specify::PathEntry)'s own evaluated delay list — or a named
/// [`RunError::Lowering`] at the first discovery OR delay-evaluation
/// failure. `path` is only used to attribute that error (mirrors every
/// other `Result<_, RunError>` plan-time function in this crate).
///
/// [`discover_with`] with no invocation option given (the LRM defaults).
#[cfg(test)]
pub(crate) fn discover<'d>(
    eval: &EvalSession<'d>,
    infos: &[(InstanceId, Symbol<'d>)],
    path: &Path,
) -> Result<TimingModel, RunError> {
    discover_with(eval, infos, path, &TimingOptions::default())
}

/// [`discover`] under the run's pulse invocation options (T31, [`TimingOptions`]): each path's
/// limits default to the options' percentages of its delay (LRM 30.7.2, 32.7), with a design's own
/// `PATHPULSE$` applied on top (SDF annotation > `PATHPULSE$` > option > built-in default for the
/// limits; the SDF level is `$sdf_annotate`'s, later, at run time). The pulse style and
/// showcancelled options go the other way (LRM 30.7.4.1/30.7.4.2: "The pulse style invocation
/// options take precedence over pulse style specify block declarations", and the same for
/// showcancelled): a given option overrides every declaration, an absent one leaves them.
pub(crate) fn discover_with<'d>(
    eval: &EvalSession<'d>,
    infos: &[(InstanceId, Symbol<'d>)],
    path: &Path,
    options: &TimingOptions,
) -> Result<TimingModel, RunError> {
    let mut model = TimingModel::new();
    model.set_pulse_options(options.pulse_style, options.showcancelled);
    model.seed_specparams(infos);
    model
        .discover(eval, infos)
        .map_err(|e| elab_to_run_error(e, path))?;
    for (id, sym) in timing_path_symbols(infos) {
        let delays = path_delays_of(eval, &sym).map_err(|m| {
            RunError::Lowering(LoweringError::unsupported_at(
                &format!("specify path: {m}"),
                &sym,
            ))
        })?;
        model.set_path_delays(id, &sym.uid(), delays);
    }
    // After the delays: `set_path_delays` resets every limit to the delay
    // (the LRM 30.7 default), so the global percentages replace that default and a
    // `PATHPULSE$` is applied on top of both.
    model.apply_pulse_percent(options.reject_pct(), options.error_pct());
    for (id, uid, reject, error) in pulse_limits_of(eval, &model, infos)? {
        model.set_path_pulse_limits(id, &uid, reject, error);
    }
    // sdf T13: every system timing check's limits, in ticks.
    crate::timingcheck::attach_limits(eval, &mut model, infos, path)?;
    Ok(model)
}

/// A path terminal's own signal name, unwrapped exactly like
/// `vj_sim::netlist::specify`'s `resolve_terminal` (a conversion, then a
/// bit-/part-select, around the plain signal reference); `None` for any other
/// shape — a `PATHPULSE$` then simply cannot name that terminal.
fn terminal_name(e: Expression<'_>) -> Option<String> {
    let e = if e.kind() == ExpressionKind::Conversion {
        e.operand().unwrap_or(e)
    } else {
        e
    };
    let e = match e.kind() {
        ExpressionKind::ElementSelect | ExpressionKind::RangeSelect => e.select_value()?,
        _ => e,
    };
    if !vj_sim::symid::is_value_name(e.kind()) {
        return None;
    }
    Some(e.referenced_symbol()?.name().to_string())
}

/// Rejects, loudly, a pulse limit whose value sv-lang has ALREADY truncated to
/// 32 bits before this crate can see it. In sv-lang's default 1800-2017 mode an
/// UNSIZED decimal literal is resized to a 32-bit `int` (1800-2023 5.7.1 no
/// longer truncates, but 0.1.9 has no setter for the language version), so
/// `specparam big = 3000000000` holds -1294967296 and the limit silently wraps
/// to the wrong value (here, clamped to 0). The value alone cannot reveal that,
/// so the literal TOKENS are checked: every integer literal reachable from
/// `root`'s declarator, following identifiers to the specparams/parameters of
/// the same module they name, must not be an unsized decimal above `i32::MAX`.
/// A sized literal (`64'd3000000000`) or a real (`3000000000.0`) is exact and
/// accepted.
fn reject_truncated_literals<'d>(
    root: &Symbol<'d>,
    named: &HashMap<String, Symbol<'d>>,
    trees: &[sv_lang::SyntaxTree],
) -> Result<(), String> {
    use sv_lang::kinds::TokenKind;
    let mut seen = std::collections::HashSet::new();
    let mut work = vec![*root];
    while let Some(sym) = work.pop() {
        if !seen.insert(sym.name().to_string()) {
            continue;
        }
        let Some(node) = trees.iter().find_map(|t| sym.syntax(t)) else {
            continue;
        };
        let mut bad: Option<String> = None;
        let mut refs: Vec<String> = Vec::new();
        // `64'd300`, `'h1F` lex as an `IntegerLiteral` size, an `IntegerBase`,
        // then an `IntegerLiteral` of digits; only a LONE decimal token is an
        // unsized decimal literal (a based literal carries its own width, and
        // slang diagnoses one that overflows it).
        let mut after_base = false;
        node.visit_with_tokens(|c| {
            if let sv_lang::Child::Token(t) = c {
                let based_digits = std::mem::replace(&mut after_base, false);
                match t.kind() {
                    TokenKind::IntegerBase => after_base = true,
                    TokenKind::IntegerLiteral if based_digits => {}
                    TokenKind::IntegerLiteral => {
                        let digits = t.text().replace('_', "");
                        let unsized_decimal = digits.bytes().all(|b| b.is_ascii_digit());
                        if unsized_decimal
                            && digits.parse::<u64>().map_or(true, |v| v > i32::MAX as u64)
                        {
                            bad = Some(t.text().to_string());
                            return sv_lang::Walk::Break;
                        }
                    }
                    TokenKind::Identifier => refs.push(t.text().to_string()),
                    _ => {}
                }
            }
            sv_lang::Walk::Continue
        });
        if let Some(lit) = bad {
            return Err(format!(
                "`{}` uses the unsized decimal literal `{lit}`, which sv-lang truncates to 32 \
                 bits (the value would silently wrap); write it sized, e.g. `64'd{lit}`",
                sym.name()
            ));
        }
        work.extend(refs.iter().filter_map(|r| named.get(r).copied()));
    }
    Ok(())
}

/// `(reject, error)` limits of one `PATHPULSE$` specparam, in ticks (LRM
/// 30.7.1: `specparam PATHPULSE$ = (reject, error)`; a single value is both).
///
/// The first value is the specparam's own constant value (read through the
/// [`TimingModel`], so a later SDF annotation of it is honored). sv-lang 0.1.9
/// has no accessor for the SECOND value of a two-value specparam
/// (`constant_value()` is the first only), so it is read off the declarator's
/// syntax and evaluated in a scratch [`sv_lang::ScriptSession`] in which every
/// plain specparam AND module parameter/localparam (elaborated values) is
/// predeclared — a literal or an expression over those, which is what LRM
/// 6.20.5 allows a specparam to be assigned; anything else (a hierarchical
/// reference, a function call) fails loudly rather than being dropped.
fn pulse_limits_of_specparam(
    model: &TimingModel,
    id: InstanceId,
    sym: &Symbol<'_>,
    plain: &[(String, sv_lang::ConstantValue)],
    named: &HashMap<String, Symbol<'_>>,
    trees: &[sv_lang::SyntaxTree],
) -> Result<(u64, u64), String> {
    reject_truncated_literals(sym, named, trees)?;
    let tick = vj_codegen::timescale::design_tick_exp(sym);
    let first = model
        .specparam(id, &sym.uid())
        .cloned()
        .or_else(|| sym.constant_value())
        .ok_or_else(|| format!("`{}` has no constant value", sym.name()))?;
    let reject = constant_to_ticks(first, sym, tick)?;
    let node = trees
        .iter()
        .find_map(|t| sym.syntax(t))
        .ok_or_else(|| format!("`{}` has no syntax node", sym.name()))?;
    let decl = <sv_lang::nodes::SpecparamDeclaratorSyntax as sv_lang::AstNode>::cast(node)
        .ok_or_else(|| {
            format!(
                "`{}`'s syntax node is `{:?}`, not a specparam declarator",
                sym.name(),
                node.kind()
            )
        })?;
    let Some(second) = decl.value2() else {
        return Ok((reject, reject));
    };
    let mut session = sv_lang::ScriptSession::new().map_err(|e| format!("{e:?}"))?;
    for (name, v) in plain {
        let decl = match v {
            sv_lang::ConstantValue::Real(f) if f.is_finite() => format!("real {name} = {f:?};"),
            // `longint`, not `integer`: a 32-bit predeclaration wraps a value
            // above 2^31 (a `3000000000` error limit became negative, clamped
            // to 0, and silently collapsed onto the reject limit). Written as
            // a sized signed hex literal so every i64 (incl. `i64::MIN`, which
            // has no positive decimal literal) round-trips bit-exactly. A
            // value `as_i64` cannot hold (4-state, or above i64) is skipped,
            // so an expression naming it fails loudly below.
            other => match other.as_i64() {
                Some(n) => format!("longint {name} = 64'sh{:x};", n as u64),
                None => continue,
            },
        };
        session.eval(&decl);
    }
    let value = session
        .eval_expression(sv_lang::AstNode::syntax(&second))
        .ok_or_else(|| {
            format!(
                "the error limit of `{}` is not a constant expression over literals, \
                 specparams and parameters",
                sym.name()
            )
        })?;
    Ok((reject, constant_to_ticks(value, sym, tick)?))
}

/// Every `PATHPULSE$` (LRM 30.7.1) that applies to a module path:
/// `(instance, TimingPath uid, reject, error)`.
///
/// `PATHPULSE$src$dst` names a path by its FIRST input and FIRST output
/// terminal — on a multi-path declaration (`(a, b *> q, r)`) those are the only
/// terminals the LRM lets it name, and one naming any other terminal matches no
/// path and is ignored (never an error: 30.7.1 only says it "shall be
/// ignored"). The path-specific specparam wins over the module-wide
/// `PATHPULSE$`; a path neither names keeps its default limits (its own
/// delays).
fn pulse_limits_of<'d>(
    eval: &EvalSession<'d>,
    model: &TimingModel,
    infos: &[(InstanceId, Symbol<'d>)],
) -> Result<Vec<(InstanceId, SymbolId, u64, u64)>, RunError> {
    let trees = eval.design().syntax_trees();
    let paths = timing_path_symbols(infos);
    let mut out = Vec::new();
    for &(id, body) in infos {
        let mut pulse: HashMap<String, Symbol<'d>> = HashMap::new();
        let mut plain: Vec<(String, sv_lang::ConstantValue)> = Vec::new();
        let mut params: Vec<(String, sv_lang::ConstantValue)> = Vec::new();
        let mut note = |s: Symbol<'d>| {
            let name = s.name().to_string();
            if name.starts_with("PATHPULSE$") {
                pulse.insert(name, s);
            } else if let Some(v) = model.specparam(id, &s.uid()) {
                plain.push((name, v.clone()));
            }
        };
        for m in vj_sim::netlist::module_items(&body) {
            match m.kind() {
                SymbolKind::Specparam => note(m),
                // LRM 6.20.5 (Table 6-11): a specparam "May be assigned
                // specparams and parameters", so the error limit may name a
                // module parameter or localparam. `constant_value()` is the
                // ELABORATED value (instance override and defparam applied),
                // not the declared default.
                SymbolKind::Parameter => {
                    if let Some(v) = m.constant_value() {
                        params.push((m.name().to_string(), v));
                    }
                }
                SymbolKind::SpecifyBlock => {
                    for inner in m.members() {
                        if inner.kind() == SymbolKind::Specparam {
                            note(inner);
                        }
                    }
                }
                _ => {}
            }
        }
        if pulse.is_empty() {
            continue;
        }
        plain.extend(params);
        // Every specparam / parameter by name, for `reject_truncated_literals`
        // to follow an identifier in a limit to its own declarator.
        let mut named: HashMap<String, Symbol<'d>> = HashMap::new();
        for m in vj_sim::netlist::module_items(&body) {
            match m.kind() {
                SymbolKind::Specparam | SymbolKind::Parameter => {
                    named.insert(m.name().to_string(), m);
                }
                SymbolKind::SpecifyBlock => {
                    for inner in m.members() {
                        if inner.kind() == SymbolKind::Specparam {
                            named.insert(inner.name().to_string(), inner);
                        }
                    }
                }
                _ => {}
            }
        }
        for &(pid, path) in &paths {
            if pid != id {
                continue;
            }
            let (Some(src), Some(dst)) = (
                path.timing_path_inputs().next().and_then(terminal_name),
                path.timing_path_outputs().next().and_then(terminal_name),
            ) else {
                continue;
            };
            let Some(sym) = pulse
                .get(&format!("PATHPULSE${src}${dst}"))
                .or_else(|| pulse.get("PATHPULSE$"))
            else {
                continue;
            };
            let (reject, error) = pulse_limits_of_specparam(model, id, sym, &plain, &named, &trees)
                .map_err(|m| {
                    RunError::Lowering(LoweringError::unsupported_at(
                        &format!("specify PATHPULSE$: {m}"),
                        sym,
                    ))
                })?;
            out.push((id, path.uid(), reject, error));
        }
    }
    Ok(out)
}

/// `node`'s own `Loc`/baked-constant resolution against `own` (the SAME
/// per-instance signal-slot table [`Member`]'s own `input` resolution
/// uses) and `model` (for a `Specparam` leaf's CURRENT, pre-SDF value —
/// see this file's own module doc for why this is a one-time bake, not a
/// `TimingModel` reference carried to runtime). A `Signal` leaf naming a
/// symbol with no resolved slot in `own`, or a `Specparam` leaf naming one
/// absent from `model`, is a named `Err` (this condition references a
/// signal/specparam discovery itself could not have produced without one
/// existing, so this is an internal-consistency check, not a real user-
/// facing restriction — mirrors every other "unexpected: discovery already
/// validated this" error elsewhere in this file).
pub(crate) fn compile_cond_plan(
    node: &CondNode,
    own: &HashMap<SymbolId, SignalSlot>,
    instance: InstanceId,
    model: &TimingModel,
) -> Result<CondPlan, String> {
    Ok(match node {
        CondNode::Signal((uid, bits)) => {
            let slot = *own.get(uid).ok_or_else(|| {
                format!(
                    "state-dependent path condition references signal `{uid}`, which has no \
                     resolved signal slot in its own instance (unexpected: discovery already \
                     validated this reference's existence)"
                )
            })?;
            CondPlan::Signal(loc_of(instance, slot), *bits)
        }
        CondNode::Specparam(uid) => {
            let v = model.specparam(instance, uid).ok_or_else(|| {
                format!(
                    "state-dependent path condition references specparam `{uid}`, which has no \
                     value in this design's TimingModel (unexpected: discovery already \
                     validated this reference's existence)"
                )
            })?;
            let int = v.as_integer().ok_or_else(|| {
                format!(
                    "state-dependent path condition's specparam `{uid}` is not an integer \
                     constant (e.g. a real)"
                )
            })?;
            let bits = int.bits();
            if bits.is_empty() && int.bit_width() > 0 {
                return Err(format!(
                    "state-dependent path condition's specparam `{uid}` is too wide to expand \
                     bit-by-bit"
                ));
            }
            CondPlan::Const(bits.iter().map(|&b| bit4_of(b)).collect())
        }
        CondNode::Const(bits) => CondPlan::Const(bits.clone()),
        CondNode::Unary(op, a) => {
            CondPlan::Unary(*op, Box::new(compile_cond_plan(a, own, instance, model)?))
        }
        CondNode::Binary(op, a, b) => CondPlan::Binary(
            *op,
            Box::new(compile_cond_plan(a, own, instance, model)?),
            Box::new(compile_cond_plan(b, own, instance, model)?),
        ),
        CondNode::Ternary(c, t, f) => CondPlan::Ternary(
            Box::new(compile_cond_plan(c, own, instance, model)?),
            Box::new(compile_cond_plan(t, own, instance, model)?),
            Box::new(compile_cond_plan(f, own, instance, model)?),
        ),
        CondNode::Concat(items) => CondPlan::Concat(
            items
                .iter()
                .map(|n| compile_cond_plan(n, own, instance, model))
                .collect::<Result<_, _>>()?,
        ),
        CondNode::Replication(n, item) => {
            CondPlan::Replication(*n, Box::new(compile_cond_plan(item, own, instance, model)?))
        }
    })
}

/// LRM 30.4.4.4's own `ifnone` default rule's own INPUT data: compiles
/// every sibling `CondNode` to a plan-time [`CondPlan`], carried as a
/// GROUP rather than pre-combined into one synthesized boolean (see
/// [`RuntimeGate::is_true`]'s own doc comment for exactly why a
/// pre-combined `NOT(OR(siblings))` disagrees with LRM 30.4.4.1 whenever a
/// sibling's own raw value is multi-bit). `siblings` is every OTHER member
/// of this `ifnone` member's own per-destination group that shares its
/// exact same INPUT terminal and carries an `If` condition (the "all other
/// conditions for the path" 30.4.4.4's own text names — `plan`'s own call
/// site is where "the path" -- same input AND same destination, the
/// destination half already fixed by the per-destination grouping this
/// function's caller iterates inside -- is actually identified). `None`
/// (treated as [`PathCondition::Unconditional`] by every caller) when
/// there are no such siblings, per that same subclause's own text: "If
/// there are no corresponding state-dependent module paths to the ifnone
/// module path, then the ifnone module path shall be treated the same as
/// an unconditional simple module path."
fn compile_ifnone_siblings(
    siblings: &[&CondNode],
    own: &HashMap<SymbolId, SignalSlot>,
    instance: InstanceId,
    model: &TimingModel,
) -> Result<Option<Vec<CondPlan>>, String> {
    if siblings.is_empty() {
        return Ok(None);
    }
    Ok(Some(
        siblings
            .iter()
            .map(|node| compile_cond_plan(node, own, instance, model))
            .collect::<Result<Vec<_>, _>>()?,
    ))
}

/// `b`'s value as [`Bit4`] -- a third small duplicate of `sv_lang::Bit`'s
/// own discriminant-order-equals-`Bit4`'s table (mirrors `vj_sim::
/// netlist::specify::bit4_of`'s own identical copy, and that function's own
/// doc comment's reasoning for why it is a duplicate rather than a shared
/// export: `vj` cannot reach into a sibling CRATE's own private
/// `fn` any more than `state::value`'s copy can be reached from a sibling
/// MODULE).
fn bit4_of(b: sv_lang::Bit) -> Bit4 {
    match b {
        sv_lang::Bit::Zero => Bit4::Zero,
        sv_lang::Bit::One => Bit4::One,
        sv_lang::Bit::X => Bit4::X,
        sv_lang::Bit::Z => Bit4::Z,
    }
}

/// Every net-destination module path's retiming stage, planned by [`plan`].
#[derive(Debug, Default)]
pub(crate) struct Plans {
    pub(crate) retimers: Vec<RetimerPlan>,
    /// The paths' delays and limits at time 0 (see [`PathTimes`]), one per `PathEntry`.
    pub(crate) paths: Vec<PathTimes>,
    /// A redirected real driver's staging slot in the bank, keyed by that
    /// driver's OWN [`DriverKey`] (the continuous assign it already has —
    /// never a `DriverKey::SpecifyPath`, see [`plan`]'s own doc comment):
    /// `run.rs` merges this into its `kernel_slots` map the SAME way it
    /// already merges `primitives::Plans::staged`, so the real driver's
    /// OWN, already-existing lowering (`let key = DriverKey::Assign(...);
    /// if let Some(&slot) = driver_slot.get(&key) { ... }`) picks up the
    /// redirect with ZERO changes to that lowering code.
    pub(crate) staged: HashMap<DriverKey, u32>,
}

impl Plans {
    /// Records each path's negative-timing floor (`floors[i]` for `TimingModel::paths[i]`,
    /// 0 when none) so an annotated delay is raised to it as the model's own was
    /// (`timingcheck::negative_timing`).
    pub(crate) fn apply_floors(&mut self, floors: &[u64]) {
        assert_eq!(
            self.paths.len(),
            floors.len(),
            "one negative-timing floor per module path"
        );
        for (times, &floor) in self.paths.iter_mut().zip(floors) {
            times.floor = floor;
        }
    }
}

/// The executor's copy of a path's edge sensitivity (LRM 30.4.3).
fn exec_edge(edge: PathEdge) -> ExecEdge {
    match edge {
        PathEdge::None => ExecEdge::None,
        PathEdge::Any => ExecEdge::Any,
        PathEdge::Specific(sv_lang::EdgeKind::PosEdge) => ExecEdge::Specific(EdgeSel::Pos),
        PathEdge::Specific(sv_lang::EdgeKind::NegEdge) => ExecEdge::Specific(EdgeSel::Neg),
        PathEdge::Specific(sv_lang::EdgeKind::BothEdges) => ExecEdge::Specific(EdgeSel::Both),
        PathEdge::Specific(sv_lang::EdgeKind::None) => unreachable!(
            "a PathEdge::Specific is never constructed with EdgeKind::None -- \
             PathEdge::from_accessors's own body is the only constructor, and it never does"
        ),
    }
}

impl Plans {
    /// The executor's view of the retimers, for the design image.
    pub(crate) fn spec(&self) -> SpecifyPlan {
        SpecifyPlan {
            retimers: self.retimers.clone(),
            paths: self.paths.clone(),
        }
    }
}

/// The REAL net/variable `SymbolKind` a module path destination `dst_uid`
/// names — never `body.members().find(|s| &s.uid() == dst_uid)` directly:
/// `SymbolId`/`SymbolUid` is a hierarchical PATH (`sv-lang SymbolId is not
/// unique`, this workspace's own standing lesson), and a port-connected
/// signal's PORT symbol and its own INTERNAL net/variable symbol share the
/// exact same path (`"m.q"` for both) — `body.members()`'s own iteration
/// order happens to yield the `Port` symbol first for every fixture this
/// task's own tests construct, so a plain `.find` silently resolves to
/// `SymbolKind::Port`, never the net/variable kind this function actually
/// needs. Mirrors `vj_sim::netlist::specify::port_directions`'s own
/// walk exactly (the SAME `port_internal_symbol()` unwrap, the SAME
/// `internal.uid()` key) — LRM 30.4.1 requires a destination connected to
/// an output/inout port, so it is always reachable this way.
fn destination_signal_kind<'d>(body: &Symbol<'d>, dst_uid: &SymbolId) -> Option<SymbolKind> {
    for m in body.members() {
        if m.kind() != SymbolKind::Port {
            continue;
        }
        let internal = m.port_internal_symbol().unwrap_or(m);
        if &internal.uid() == dst_uid {
            return Some(internal.kind());
        }
    }
    // LRM 25.6: a modport port of an interface port (`ch.q`): the kind of the
    // interface signal it names.
    modport_port_in(body, dst_uid).and_then(|m| m.modport_port_internal_symbol().map(|s| s.kind()))
}

/// LRM 25.6: the interface-port signals of `body` (one entry per signal of the modport an
/// `itf.mp ch` port connects), each as `modport port uid -> (interface instance, slot)`.
pub(crate) fn modport_terminals<'d>(
    body: &Symbol<'d>,
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    body_instances: &HashMap<SymbolId, InstanceId>,
) -> HashMap<SymbolId, (InstanceId, SignalSlot)> {
    let mut out = HashMap::new();
    for m in body.members() {
        let ip = if m.kind() == SymbolKind::Port {
            m.port_internal_symbol().unwrap_or(m)
        } else {
            m
        };
        if ip.kind() != SymbolKind::InterfacePort {
            continue;
        }
        let (_, Some(modport)) = ip.interface_port_connection() else {
            continue;
        };
        for mp in modport.members() {
            if mp.kind() != SymbolKind::ModportPort {
                continue;
            }
            let Some(internal) = mp.modport_port_internal_symbol() else {
                continue;
            };
            let Some(owner) = internal
                .parent()
                .and_then(|p| p.containing_instance())
                .and_then(|b| body_instances.get(&b.uid()).copied())
            else {
                continue;
            };
            if let Some(&slot) = signals.get(&owner).and_then(|m| m.get(&internal.uid())) {
                out.insert(mp.uid(), (owner, slot));
            }
        }
    }
    out
}

/// The `ModportPort` symbol with uid `uid` that some procedural code of `body` names
/// (LRM 25.6: `ch.q` through an `itf.mp ch` port).
fn modport_port_in<'d>(body: &Symbol<'d>, uid: &SymbolId) -> Option<Symbol<'d>> {
    let mut stack: Vec<SemNode<'d>> = Vec::new();
    for m in body.members() {
        if m.kind() == SymbolKind::ProceduralBlock
            && let Some(b) = vj_sim::process::cfg::proc_body(&m)
        {
            stack.push(b.as_sem_node());
        }
    }
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression()
            && vj_sim::symid::is_value_name(e.kind())
            && let Some(sym) = e.referenced_symbol()
            && sym.kind() == SymbolKind::ModportPort
            && &sym.uid() == uid
        {
            return Some(sym);
        }
        stack.extend(vj_sim::process::cfg::live_children(&n));
    }
    None
}

/// Whether `dst_uid` is the internal signal of an `inout` port of `body`
/// (same port walk as [`destination_signal_kind`]).
fn destination_is_inout<'d>(body: &Symbol<'d>, dst_uid: &SymbolId) -> bool {
    body.members().any(|m| {
        m.kind() == SymbolKind::Port
            && &m.port_internal_symbol().unwrap_or(m).uid() == dst_uid
            && m.port_direction() == sv_lang::ArgumentDirection::InOut
    })
}

/// Every assignment expression anywhere in `body`'s `ProceduralBlock`s whose
/// LHS resolves (`crate::nets::lvalue_roots`, the SAME root-finding
/// [`plan`]'s own net-destination branch uses for a continuous assign's
/// target) to include `dst_uid`, as `(the assignment expression, is it
/// nonblocking)` — [`plan`]'s own Task 4b variable-destination branch uses
/// this to validate its own scope boundary (exactly one nonblocking,
/// whole-variable driver; anything else is a named, not-yet-implemented
/// gap, never a silent narrowing). Mirrors `vj::run::
/// referenced_values`'s own generic `SemNode` walk shape.
fn procedural_writes_of<'d>(body: &Symbol<'d>, dst_uid: &SymbolId) -> Vec<(Expression<'d>, bool)> {
    let mut out = Vec::new();
    let mut stack: Vec<SemNode<'d>> = Vec::new();
    for m in body.members() {
        if m.kind() == SymbolKind::ProceduralBlock
            && let Some(b) = vj_sim::process::cfg::proc_body(&m)
        {
            stack.push(b.as_sem_node());
        }
    }
    while let Some(n) = stack.pop() {
        if let Some(e) = n.as_expression()
            && e.kind() == ExpressionKind::Assignment
            && let Some(lhs) = e.left()
            && crate::nets::lvalue_roots(lhs)
                .iter()
                .any(|s| &s.uid() == dst_uid)
        {
            out.push((e, e.is_nonblocking() == Some(true)));
        }
        stack.extend(vj_sim::process::cfg::live_children(&n));
    }
    out
}

/// Plans a retiming stage for every DESTINATION BIT [`model`]'s module
/// paths target, allocating staging and kick cells in the bank (`bank`,
/// whose slot widths are `res.bank_widths`) exactly like `primitives::plan`
/// does — one stage per destination, shared by every
/// [`PathEntry`](vj_sim::netlist::specify::PathEntry) that targets it
/// (LRM 30.5.3, Task 6 — see this file's own module doc for the shape
/// change from Task 4a's original one-`PathEntry`-per-stage code).
///
/// **This task's own explicit scope boundary**: a destination this function
/// retimes must be (a) the WHOLE of a net (no bit-select/part-select — LRM
/// 30.4.1 allows either, but a partial destination needs its own
/// driver-contention design this task does not invent), (b) exactly 1 bit
/// wide (Table 30-2/30-3's own transition model is a SCALAR four-state one;
/// this workspace's own `primitives::Delays::of` vector convention does not
/// carry over to a transition-PAIR table without inventing a new rule this
/// task is not the one to invent — the SAME restriction now also applies to
/// every member's own INPUT terminal, never checked before Task 6 since a
/// single-member group never needed to resolve its own input to a real
/// [`Loc`] at all), and (c) driven by EXACTLY ONE plain continuous assignment
/// (net destination) or ONE nonblocking procedural assignment (variable
/// destination, Task 4b) — regardless of how MANY `PathEntry`s target it (a
/// net/variable with zero or more than one real driver is still this task's
/// own named, loud `Err`, never a silent narrowing). A single real driver
/// that ALSO carries its own distributed delay is no longer rejected here —
/// see the `natural` parameter's own doc comment just below and this file's
/// own module doc for Task 9 (LRM 30.6).
#[allow(clippy::too_many_arguments)]
pub(crate) fn plan<'d>(
    insts: &[(InstanceId, Symbol<'d>)],
    signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    res: &mut Resolution,
    bank: InstanceId,
    model: &TimingModel,
    // Task 9: `(instance, destination symbol) -> its single real
    // continuous-assign driver's own distributed delay`, built by
    // `primitives::plan` (reused unchanged — see its own module doc) for
    // every destination this very `model` targets; `primitives::Plans::
    // natural`'s own doc comment explains why `primitives::plan` exposes
    // this instead of building its own, independently-committing delay line
    // for it. Missing (the overwhelming common case) means "no competing
    // distributed delay" — [`RetimerPlan::natural`] then defaults to
    // `Delays::default()` (all-zero), under which `max(natural, specify)`
    // degenerates to `specify` alone, exactly the pre-Task-9 behavior.
    natural: &HashMap<(InstanceId, SymbolId), Delays>,
    // Instance of each module/interface body (`SymbolId` of the body), to find the interface
    // instance a modport port terminal (LRM 25.6) lives in.
    body_instances: &HashMap<SymbolId, InstanceId>,
    // A destination a primitive drives: the staging slot that gate already
    // writes (`primitives::Plans::specify_staging`).
    prim_staging: &HashMap<(InstanceId, SymbolId), Loc>,
    // The nets some driver drives (`nets::driven_windows`): a path destination net none
    // does has no value to delay (LRM 30.4.1, 30.7: the delay applies to what drives the
    // output), so it plans no retimer.
    driven: &crate::nets::DrivenWindows,
) -> Result<Plans, String> {
    let mut plans = Plans {
        paths: model
            .paths
            .iter()
            .map(|p| PathTimes {
                delays: p.delays,
                reject: p.reject_limit,
                error: p.error_limit,
                floor: 0,
            })
            .collect(),
        ..Plans::default()
    };
    let alloc = |res: &mut Resolution, width: u32| {
        let slot = res.bank_widths.len() as u32;
        res.bank_widths.push(width);
        loc_of(bank, bank_slot(slot, width))
    };
    for &(id, body) in insts {
        let own = &signals[&id];
        let iface = modport_terminals(&body, signals, body_instances);
        let cont_assigns =
            vj_codegen::module::discover_cont_assigns(&body).map_err(|e| e.message)?;

        // Task 6: group every validated `PathEntry` targeting this instance
        // by its own destination symbol — LRM 30.5.3's own text ("there may
        // be specify paths to the output from more than one input... the
        // simulator has to decide which specify path to use") is written
        // generically over "specify paths to the output" regardless of
        // whether they desugared from ONE multi-input declaration
        // (`(a,b=>q)=10;`, 30.4.6) or from several SEPARATE ones
        // (`(a=>q)=10;(b=>q)=20;`), so both land in the SAME group here.
        // `Vec`, not a `HashMap<_, Vec<_>>`, to keep this loop's error
        // ordering identical to pre-Task-6 behavior (the first offending
        // `PathEntry` in discovery order is still the one named in an
        // un-desugared/bit-select `Err`).
        let mut groups: Vec<(SymbolId, Vec<(usize, &PathEntry)>)> = Vec::new();
        for (index, p) in model
            .paths
            .iter()
            .enumerate()
            .filter(|(_, p)| p.instance == id)
        {
            if p.inputs.len() != 1 || p.outputs.len() != 1 {
                return Err(format!(
                    "a module path with {} input(s)/{} output(s) reached `specify::plan` \
                     un-desugared (unexpected: `TimingModel::discover` desugars every multi-\
                     terminal declaration into one-input/one-output entries before this ever \
                     runs)",
                    p.inputs.len(),
                    p.outputs.len()
                ));
            }
            let dst_uid = &p.outputs[0].0;
            if !own.contains_key(dst_uid) && !iface.contains_key(dst_uid) {
                continue;
            }
            match groups.iter_mut().find(|(u, _)| u == dst_uid) {
                Some((_, members)) => members.push((index, p)),
                None => groups.push((dst_uid.clone(), vec![(index, p)])),
            }
        }

        for (dst_uid, group) in groups {
            let (dst_owner, dst_slot) = own
                .get(&dst_uid)
                .map(|&s| (id, s))
                .unwrap_or_else(|| iface[&dst_uid]);
            let width = dst_slot.width;

            // A destination NET nothing drives (no continuous assign, primitive output,
            // net-declaration assignment or port connection) stays `z`: there is no value
            // for the path to delay, so the paths to it are checked (above) and dropped,
            // not refused. An `inout` port is excluded, since its parent's net may drive it.
            if destination_signal_kind(&body, &dst_uid) == Some(SymbolKind::Net)
                && !destination_is_inout(&body, &dst_uid)
                && !driven.contains_key(&(id, dst_uid.clone()))
                && !prim_staging.contains_key(&(id, dst_uid.clone()))
                && !cont_assigns.iter().any(|ca| {
                    ca.net_target.is_some_and(|n| n.uid() == dst_uid)
                        || ca
                            .assign_expr
                            .left()
                            .map(crate::nets::lvalue_roots)
                            .unwrap_or_default()
                            .iter()
                            .any(|r| r.uid() == dst_uid)
                })
            {
                continue;
            }

            // Task 6: resolve every member's own INPUT terminal to its own
            // signal slot — LRM 30.5.3's selection needs each candidate
            // path's input to timestamp "most recently transitioned", never
            // needed before Task 6 (a single-member group has nothing to
            // compare against, so [`PathRetimer`] never had to read an
            // input's own value at all).
            //
            // LRM 30.3/30.4: a terminal may be a vector or a bit-/part-select
            // of one. Table 30-2/30-3's transition model is scalar, so each
            // path is expanded into scalar (source bit, destination bit)
            // pairs, one `Member` per pair, all sharing the path's delays
            // (`Member::path`): a PARALLEL connection (`=>`) pairs bit `i` of
            // the source with bit `i` of the destination and needs equal bit
            // counts (LRM 30.4.2); a FULL connection (`*>`) pairs every
            // source bit with every destination bit (LRM 30.4.3). Each
            // destination bit gets its own retiming stage (`bit_members`).
            let mut bit_members: Vec<Vec<Member>> = vec![Vec::new(); width as usize];
            for &(path_index, p) in &group {
                let (in_uid, in_bits) = &p.inputs[0];
                let (in_owner, in_slot) = own
                    .get(in_uid)
                    .map(|&s| (id, s))
                    .or_else(|| iface.get(in_uid).copied())
                    .ok_or_else(|| {
                        format!(
                            "specify path input `{in_uid}` has no resolved signal slot in its own \
                         instance (unexpected: discovery already validated this terminal's \
                         existence)"
                        )
                    })?;
                let (src_lo, src_w) = in_bits.unwrap_or((0, in_slot.width));
                if src_w == 0 || u64::from(src_lo) + u64::from(src_w) > u64::from(in_slot.width) {
                    return Err(format!(
                        "specify path input `{in_uid}` selects bits {src_lo}+{src_w} of a \
                         {}-bit net (out of range)",
                        in_slot.width
                    ));
                }
                let (dst_lo, dst_w) = p.outputs[0].1.unwrap_or((0, width));
                if dst_w == 0 || u64::from(dst_lo) + u64::from(dst_w) > u64::from(width) {
                    return Err(format!(
                        "specify path destination `{dst_uid}` selects bits {dst_lo}+{dst_w} of a \
                         {width}-bit net (out of range)"
                    ));
                }
                let parallel = p.connection == sv_lang::TimingPathConnectionKind::Parallel;
                if parallel && src_w != dst_w {
                    return Err(format!(
                        "parallel (`=>`) specify path `{in_uid}` ({src_w} bits) to `{dst_uid}` \
                         ({dst_w} bits): LRM 30.4.2 requires the source and destination of a \
                         parallel connection to have the same number of bits"
                    ));
                }
                // Task 8 (LRM 30.4.4.*): this path's own state-dependency,
                // compiled to a plan-time `CondPlan` -- see this file's own
                // module doc. An `IfNone` member's own gate is SYNTHESIZED
                // from its siblings WITHIN THIS SAME destination group that
                // share its exact input and destination terminals and carry
                // an `If` condition -- [`ifnone_gate`]'s own doc comment.
                let condition = match &p.condition {
                    PathCondition::Unconditional => None,
                    PathCondition::If(node) => {
                        Some(Gate::If(compile_cond_plan(node, own, id, model)?))
                    }
                    PathCondition::IfNone => {
                        let siblings: Vec<&CondNode> = group
                            .iter()
                            .filter(|(_, q)| {
                                q.inputs[0] == p.inputs[0] && q.outputs[0] == p.outputs[0]
                            })
                            .filter_map(|(_, q)| match &q.condition {
                                PathCondition::If(node) => Some(node),
                                _ => None,
                            })
                            .collect();
                        compile_ifnone_siblings(&siblings, own, id, model)?.map(Gate::IfNone)
                    }
                };
                for d in 0..dst_w {
                    let srcs = if parallel { d..d + 1 } else { 0..src_w };
                    for s in srcs {
                        bit_members[(dst_lo + d) as usize].push(Member {
                            input: loc_of(in_owner, in_slot),
                            input_lo: src_lo + s,
                            path: path_index,
                            style: p.pulse_style,
                            showcancelled: p.showcancelled,
                            edge: exec_edge(p.edge),
                            condition: condition.clone(),
                        });
                    }
                }
            }
            // A bit no module path reaches has an empty member list: its stage then
            // selects delay 0 (`PathRetimer::select_delay`'s no-candidate floor), so the
            // bit takes its driver's value undelayed (LRM 30.4.6, 30.7: only the bits a
            // path names get a module path delay) -- through the same staging cell, so
            // one driver may serve covered and uncovered bits alike.

            // Task 4b: a VARIABLE destination (LRM 30.4.1's "net or
            // variable") is retimed by redirecting its own single
            // nonblocking-assignment driver, never by the net-specific
            // continuous-assign search below (this function's own module
            // doc explains the whole wiring path). This resolution happens
            // exactly ONCE per destination group (Task 6), regardless of
            // how many `PathEntry`s share it — there is still only one
            // real driver to redirect.
            let dst_kind = destination_signal_kind(&body, &dst_uid);
            if iface.contains_key(&dst_uid) && dst_kind != Some(SymbolKind::Variable) {
                return Err(format!(
                    "specify path destination `{dst_uid}` is a net (or is never written \
                     procedurally) of an interface port (LRM 25.6): only a variable the module \
                     writes is retimed through an interface port"
                ));
            }
            if dst_kind == Some(SymbolKind::Variable) {
                let writes = procedural_writes_of(&body, &dst_uid);
                // LRM 30.4: the path delay belongs to the destination's
                // OUTWARD value, not to whichever statement writes it, so
                // EVERY procedural write to the variable -- blocking or
                // nonblocking, one statement or several, one process or
                // several -- is redirected to the one staging cell below. The
                // staging cell simply holds the last value written, exactly
                // as the variable itself would; the retimer forwards it.
                if writes.is_empty() {
                    return Err(format!(
                        "specify path destination `{dst_uid}` is a variable with no procedural \
                         write the specify retimer could redirect"
                    ));
                }
                for &(write, _) in &writes {
                    let lhs = write.left().ok_or_else(|| {
                        "internal: a procedural assignment resolved with no lvalue".to_string()
                    })?;
                    // A bit-select or part-select write (LRM 10.4.1/11.5) lands in
                    // the same staging cell at the same offset, so only the root
                    // matters; a concatenation lvalue splits one write across
                    // several variables and stays refused.
                    if !matches!(
                        lhs.kind(),
                        ExpressionKind::NamedValue
                            | ExpressionKind::HierarchicalValue
                            | ExpressionKind::ElementSelect
                            | ExpressionKind::RangeSelect
                    ) {
                        return Err(format!(
                            "specify path destination `{dst_uid}`'s procedural driver writes a \
                             concatenation or member lvalue, not a whole variable or a bit/part \
                             select of it (not supported)"
                        ));
                    }
                }

                let staging = alloc(res, width);
                plans
                    .staged
                    .insert(DriverKey::ProcVar(id, dst_uid.clone()), staging.slot.slot);

                let key = DriverKey::SpecifyPath(id, dst_uid.clone());
                let dst = match res.slot(&key) {
                    Some(s) => loc_of(bank, bank_slot(s, dst_slot.width)),
                    None => loc_of(dst_owner, dst_slot),
                };
                for (bit, members) in bit_members.into_iter().enumerate() {
                    let kick = alloc(res, 32);
                    plans.retimers.push(RetimerPlan {
                        staging,
                        staging_lo: bit as u32,
                        dst,
                        dst_lo: bit as u32,
                        width: 1,
                        members,
                        kick,
                        // A variable destination's own driver is never a
                        // `primitives::Plans::natural` key (that map is keyed
                        // only by continuous-assign destinations) — Task 9's
                        // mixing is net-destination-only, matching Figures
                        // 30-3/30-4's own worked examples (this file's own
                        // module doc).
                        natural: Delays::default(),
                    });
                }
                continue;
            }

            // The destination's real functional driver: exactly one plain
            // continuous assign (see this function's own doc comment).
            // Resolved exactly ONCE per destination group (Task 6).
            let mut drivers: Vec<DriverKey> = Vec::new();
            for ca in &cont_assigns {
                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(),
                };
                if roots.iter().any(|r| r.uid() == dst_uid) {
                    drivers.push(DriverKey::Assign(id, ca.sym.uid(), dst_uid.clone()));
                }
            }
            // ... or exactly one primitive, which already writes its own
            // staging slot (`primitives::plan`).
            let prim = prim_staging.get(&(id, dst_uid.clone())).copied();
            let mut inout_driver_slot = None;
            let staging = match (drivers.len(), prim) {
                (0, Some(staging)) => staging,
                (1, None) => {
                    let staging = alloc(res, width);
                    let driver_key = drivers.into_iter().next().expect("one driver");
                    // The assign's own contribution cell, before it is
                    // redirected: an `inout` destination's retimer commits
                    // there (below).
                    inout_driver_slot = res.slot(&driver_key);
                    plans.staged.insert(driver_key, staging.slot.slot);
                    staging
                }
                (n, p) => {
                    return Err(format!(
                        "specify path destination `{dst_uid}` has {n} plain-continuous-assign \
                         driver(s){} — a destination is retimed when it has EXACTLY one \
                         driver, a continuous assign or a primitive (a multi-driver net needs \
                         its own driver-contention design, not yet implemented)",
                        if p.is_some() {
                            " and a primitive driver"
                        } else {
                            ""
                        }
                    ));
                }
            };
            let key = DriverKey::SpecifyPath(id, dst_uid.clone());
            let dst = match res.slot(&key) {
                Some(s) => loc_of(bank, bank_slot(s, dst_slot.width)),
                // An `inout` destination port is joined with the parent's net
                // (LRM 23.3.3.5), so nothing reads the module-local cell the
                // retimer would commit to: the path delay would be silently
                // dropped and the net would never take the driven value.
                None if destination_is_inout(&body, &dst_uid) => {
                    if let Some(s) = inout_driver_slot {
                        loc_of(bank, bank_slot(s, dst_slot.width))
                    } else {
                        return Err(format!(
                            "specify path destination `{dst_uid}` is an `inout` port, which is joined \
                         with the parent's net; retiming a bidirectional port's driver (LRM 30.4) \
                         is not implemented (make the destination an `output` port)"
                        ));
                    }
                }
                None => loc_of(id, dst_slot),
            };
            // Task 9 (LRM 30.6): this destination's own competing
            // distributed delay, if `primitives::plan` found one (this
            // function's own doc comment) — `Delays::default()` (all-zero)
            // when it did not, under which `PathRetimer::resume`'s own
            // `max(natural, specify)` degenerates to `specify` alone.
            let dest_natural = natural
                .get(&(id, dst_uid.clone()))
                .copied()
                .unwrap_or_default();
            for (bit, members) in bit_members.into_iter().enumerate() {
                let kick = alloc(res, 32);
                plans.retimers.push(RetimerPlan {
                    staging,
                    staging_lo: bit as u32,
                    dst,
                    dst_lo: bit as u32,
                    width: 1,
                    members,
                    kick,
                    natural: dest_natural,
                });
            }
        }
    }
    Ok(plans)
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::path::Path;

    use sv_lang::{Compilation, Design, Session, Symbol};
    use vj_abi::bit4::Bit4;
    use vj_codegen::process_lower::{SignalSlot, SignalSlotClass};
    use vj_sim::netlist::InstanceId;
    use vj_sim::symid::SymbolUid;

    use super::{discover, plan};
    use crate::nets::Resolution;

    fn compile(src: &str) -> Design {
        let session = Session::new();
        let mut comp = Compilation::new(&session).expect("compilation created");
        comp.add_source(src).expect("source added");
        comp.compile().expect("design compiled")
    }

    fn top_body(design: &Design) -> Symbol<'_> {
        design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("top instance has a body")
    }

    fn one_bit_slot(slot: u32) -> SignalSlot {
        SignalSlot {
            slot,
            width: 1,
            signed: false,
            class: SignalSlotClass::Inline,
        }
    }

    #[test]
    fn discover_wraps_timing_model_discovery_through_run_error() {
        let mut design = compile(
            "module m(input a, output q);\n  assign q = a;\n  specify\n    (a => q) = 10;\n  \
             endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let model = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(model.paths.len(), 1);
    }

    #[test]
    fn discover_reports_a_direction_violation_as_a_lowering_run_error() {
        let mut design = compile(
            "module m(input b, input q3_in);\n  specify\n    (b => q3_in) = 3;\n  endspecify\n\
             endmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        match discover(&eval, &[(InstanceId(0), body)], Path::new("<test>")) {
            Err(super::RunError::Lowering(_)) => {}
            Err(other) => panic!("expected RunError::Lowering, got {other}"),
            Ok(_) => panic!("a direction violation must surface as a named RunError"),
        }
    }

    #[test]
    fn discover_attaches_the_evaluated_delay_list_to_every_path() {
        let mut design = compile(
            "module m(input a, output q);\n  assign q = a;\n  specify\n    (a => q) = (3, \
             5);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let model = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(model.paths.len(), 1);
        let d = model.paths[0].delays;
        assert_eq!(d.of(vj_abi::bit4::Bit4::Zero, vj_abi::bit4::Bit4::One), 3);
        assert_eq!(d.of(vj_abi::bit4::Bit4::One, vj_abi::bit4::Bit4::Zero), 5);
    }

    /// Task 4b: `discover` already handles an edge-sensitive path whose
    /// destination is a procedurally-written variable with no change at
    /// all (Task 3's own discovery is destination-kind-agnostic) --
    /// `plan`'s own tests below exercise the NEW code this task adds.
    #[test]
    fn discover_resolves_an_edge_sensitive_path_to_a_procedural_reg_destination() {
        let mut design = compile(
            "module m(input clk, input d, output reg q);\n  always @(posedge clk) q <= d;\n  \
             specify\n    (posedge clk => (q +: d)) = (6, 8);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let model = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(model.paths.len(), 1, "{:?}", model.paths);
        assert_eq!(model.paths[0].inputs.len(), 1);
        assert_eq!(model.paths[0].outputs.len(), 1);
        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("reg q")
            .uid();
        assert_eq!(model.paths[0].outputs[0].0, q_uid);
    }

    #[test]
    fn discover_clamps_a_negative_path_delay_to_zero_per_30_5_1() {
        // Review fix (r1): LRM 1800-2023 30.5.1 — "If the path delay
        // expression results in a negative value, it shall be treated as
        // zero" — not an error. Before this fix, `discover` (via
        // `path_delay_values_of`'s predecessor, which reused
        // `primitives::delay_values_of`/`delay_ticks` unchanged) rejected
        // this exact, LRM-legal design with "unsupported: a negative or NaN
        // delay (-3)" instead of running it with delay 0 on every
        // transition.
        let mut design = compile(
            "module m(input a, output q);\n  assign q = a;\n  specify\n    specparam NEG = \
             -3;\n    (a => q) = NEG;\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let model = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(model.paths.len(), 1);
        let d = model.paths[0].delays;
        for (from, to) in [
            (vj_abi::bit4::Bit4::Zero, vj_abi::bit4::Bit4::One),
            (vj_abi::bit4::Bit4::One, vj_abi::bit4::Bit4::Zero),
            (vj_abi::bit4::Bit4::Zero, vj_abi::bit4::Bit4::Z),
        ] {
            assert_eq!(
                d.of(from, to),
                0,
                "{from:?} -> {to:?}: a negative path delay must clamp to 0, not error"
            );
        }
    }

    #[test]
    fn plan_builds_one_retimer_for_a_simple_net_destination_path() {
        let mut design = compile(
            "module m(input a, output q);\n  assign q = a;\n  specify\n    (a => q) = (3, \
             5);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("net q")
            .uid();
        let a_uid = body
            .members()
            .find(|s| s.name() == "a")
            .expect("net a")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid, one_bit_slot(0));
        own.insert(a_uid, one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
        assert_eq!(plans.staged.len(), 1, "the real driver is redirected");
        // Two bank cells allocated (staging + kick).
        assert_eq!(res.bank_widths.len(), 2);
    }

    /// Task 4b's own "unit test for a `DriverKey::ProcVar`-style
    /// resolution": a destination written by exactly one nonblocking
    /// assignment (the common sequential-cell shape) gets exactly one
    /// retimer and exactly one staged (redirected) entry, keyed by
    /// `DriverKey::ProcVar`, not `DriverKey::Assign` (there is no
    /// continuous assign in this fixture at all).
    #[test]
    fn plan_builds_one_retimer_for_a_procedural_variable_destination_path() {
        let mut design = compile(
            "module m(input clk, input d, output reg q);\n  always @(posedge clk) q <= d;\n  \
             specify\n    (posedge clk => (q +: d)) = (6, 8);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("reg q")
            .uid();
        let clk_uid = body
            .members()
            .find(|s| s.name() == "clk")
            .expect("net clk")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid.clone(), one_bit_slot(0));
        own.insert(clk_uid, one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
        assert_eq!(
            plans
                .staged
                .get(&super::DriverKey::ProcVar(InstanceId(0), q_uid)),
            Some(&0),
            "the nonblocking write's own staging slot is keyed by DriverKey::ProcVar"
        );
        // Two bank cells allocated (staging + kick).
        assert_eq!(res.bank_widths.len(), 2);
    }

    /// The destination-writer scan sees through an `Invalid` dead-branch statement (slang 0.1.12
    /// demotes the statically dead `if (S > 1)` arm holding the reversed select `q[7:8-CL]`, whose
    /// blocking write must not count as a driver): only the live nonblocking write is planned.
    #[test]
    fn plan_ignores_a_blocking_write_in_a_statically_dead_arm() {
        let mut design = compile(
            "module m #(parameter S = 1, parameter CL = 0)(input clk, input [7:0] d, output reg \
             [7:0] q);\n  always @(posedge clk) begin\n    if (S > 1) q[7:8-CL] = d;\n    else \
             q <= d;\n  end\n  specify\n    (posedge clk => (q +: d)) = (6, 8);\n  endspecify\n\
             endmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        let uid_of = |n: &str| {
            body.members()
                .find(|s| s.name() == n)
                .expect("signal")
                .uid()
        };
        let mut own = std::collections::HashMap::new();
        own.insert(uid_of("q"), one_bit_slot(0));
        own.insert(uid_of("clk"), one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);
        let mut res = Resolution::default();
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            InstanceId(u32::MAX),
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
    }

    /// A blocking write to a specify-path-destination variable is redirected
    /// to the retimer's staging cell like a nonblocking one (LRM 30.4).
    #[test]
    fn plan_redirects_a_variable_destination_written_by_a_blocking_assignment() {
        let mut design = compile(
            "module m(input clk, input d, output reg q);\n  always @(posedge clk) q = d;\n  \
             specify\n    (posedge clk => (q +: d)) = (6, 8);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("reg q")
            .uid();
        let clk_uid = body
            .members()
            .find(|s| s.name() == "clk")
            .expect("net clk")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid.clone(), one_bit_slot(0));
        own.insert(clk_uid, one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
        assert!(
            plans
                .staged
                .contains_key(&super::DriverKey::ProcVar(InstanceId(0), q_uid)),
            "the blocking write's own staging slot is keyed by DriverKey::ProcVar"
        );
    }

    /// Two nonblocking drivers of one specify-path-destination variable
    /// (one process or two) share ONE staging cell: it holds the last value
    /// written, like the variable itself (LRM 30.4).
    #[test]
    fn plan_redirects_a_variable_destination_written_by_two_nonblocking_statements() {
        let mut design = compile(
            "module m(input clk, input d, input e, output reg q);\n  always @(posedge clk) \
             q <= d;\n  always @(posedge clk) q <= e;\n  specify\n    (posedge clk => (q +: \
             d)) = (6, 8);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("reg q")
            .uid();
        let clk_uid = body
            .members()
            .find(|s| s.name() == "clk")
            .expect("net clk")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid.clone(), one_bit_slot(0));
        own.insert(clk_uid, one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
        assert!(
            plans
                .staged
                .contains_key(&super::DriverKey::ProcVar(InstanceId(0), q_uid)),
            "the two writes' ONE shared staging slot is keyed by DriverKey::ProcVar"
        );
    }

    /// **Task 9** (LRM 30.6, "mixing module path delays and distributed
    /// delays"): a destination's single real continuous-assign driver that
    /// ALSO carries its own `#delay` is no longer rejected — `primitives::
    /// plan` is called here exactly as `run.rs` now calls it (with this
    /// destination in `specify_dests`): it must defer to `specify::plan`
    /// instead of ALSO building its own delay line for the same net (which
    /// would race [`PathRetimer`]'s own commit, this file's own module doc),
    /// and expose the SAME `Delays` it would have used via `Plans::natural`
    /// for this function to fold into [`RetimerPlan::natural`].
    #[test]
    fn plan_mixes_a_module_path_delay_with_a_distributed_delay() {
        let mut design = compile(
            "module m(input a, output q);\n  assign #2 q = a;\n  specify\n    (a => q) = (3, \
             5);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("net q")
            .uid();
        let a_uid = body
            .members()
            .find(|s| s.name() == "a")
            .expect("net a")
            .uid();
        let mut own = HashMap::new();
        own.insert(q_uid.clone(), one_bit_slot(0));
        own.insert(a_uid, one_bit_slot(1));
        let mut signals = HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let trees = eval.design().syntax_trees();
        let specify_dests = std::collections::HashSet::from([(InstanceId(0), q_uid.clone())]);
        let prim_plans = crate::primitives::plan(
            &eval,
            &infos,
            &signals,
            &trees,
            &mut res,
            bank,
            &specify_dests,
        )
        .unwrap_or_else(|e| panic!("primitives::plan failed: {e}"));
        assert!(
            prim_plans.staged.is_empty(),
            "a specify-claimed destination's own `#delay` driver must not ALSO get \
             primitives.rs's own delay line (it would race `PathRetimer`'s own commit): {:?}",
            prim_plans.staged
        );
        let natural = prim_plans
            .natural
            .get(&(InstanceId(0), q_uid.clone()))
            .unwrap_or_else(|| panic!("primitives::plan must expose this destination's own delay"));
        assert_eq!(natural.of(&[Bit4::One]), 2, "the assign's own `#2` delay");
        assert_eq!(
            natural.of(&[Bit4::Zero]),
            2,
            "a single-value delay list: rise == fall"
        );

        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &prim_plans.natural,
            &HashMap::new(),
            &prim_plans.specify_staging,
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "exactly one retimer");
        assert_eq!(
            plans.staged.len(),
            1,
            "specify::plan, not primitives::plan, redirects the real driver"
        );
        assert_eq!(
            plans.retimers[0].natural.of(&[Bit4::One]),
            2,
            "the distributed delay must reach the retimer unchanged"
        );
    }

    /// **Task 6**: two separate `TimingPath` declarations sharing one
    /// destination net now MERGE into one retimer (LRM 30.5.3), replacing
    /// the pre-Task-6 placeholder that rejected this composition (review
    /// fix r2's own "Task 6's own scope" comment, now landed) — one staging
    /// cell, one kick cell (`res.bank_widths.len() == 2`, unchanged from
    /// the single-path case: Task 6 shares ONE retiming stage across
    /// members, never one per `PathEntry`), one retimer, with exactly two
    /// `members`.
    #[test]
    fn plan_merges_two_module_paths_sharing_one_destination_into_one_retimer() {
        let mut design = compile(
            "module m(input a, input b, output q);\n  assign q = a | b;\n  specify\n    (a => \
             q) = 10;\n    (b => q) = 20;\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(model.paths.len(), 2, "two separate TimingPath declarations");

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("net q")
            .uid();
        let a_uid = body
            .members()
            .find(|s| s.name() == "a")
            .expect("net a")
            .uid();
        let b_uid = body
            .members()
            .find(|s| s.name() == "b")
            .expect("net b")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid, one_bit_slot(0));
        own.insert(a_uid, one_bit_slot(1));
        own.insert(b_uid, one_bit_slot(2));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(
            plans.retimers.len(),
            1,
            "one shared retiming stage, not two independent ones"
        );
        assert_eq!(plans.retimers[0].members.len(), 2, "both paths merged in");
        assert_eq!(
            res.bank_widths.len(),
            2,
            "still exactly one staging + one kick cell (shared, not duplicated per path)"
        );
        assert_eq!(
            plans.staged.len(),
            1,
            "the one real driver, redirected once"
        );
    }

    /// The SAME composition as the test above, but one multi-input
    /// declaration (`(a, b => q) = (3, 5);`, 30.4.6) desugars into two
    /// `PathEntry`s sharing one `path_uid` instead of two separate
    /// `TimingPath` symbols -- LRM 30.5.3's own selection rule is written
    /// generically over "specify paths to the output" and does not care
    /// which case it is, so this must merge exactly the same way.
    #[test]
    fn plan_merges_a_fan_in_declaration_targeting_one_destination_too() {
        let mut design = compile(
            "module m(input a, input b, output q);\n  assign q = a | b;\n  specify\n    (a, b \
             *> q) = (3, 5);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(
            model.paths.len(),
            2,
            "one multi-input declaration desugars into two PathEntrys (30.4.6)"
        );

        let q_uid = body
            .members()
            .find(|s| s.name() == "q")
            .expect("net q")
            .uid();
        let a_uid = body
            .members()
            .find(|s| s.name() == "a")
            .expect("net a")
            .uid();
        let b_uid = body
            .members()
            .find(|s| s.name() == "b")
            .expect("net b")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(q_uid, one_bit_slot(0));
        own.insert(a_uid, one_bit_slot(1));
        own.insert(b_uid, one_bit_slot(2));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1, "one shared retiming stage");
        assert_eq!(
            plans.retimers[0].members.len(),
            2,
            "both desugared paths merged in"
        );
    }

    /// **Task 6, LRM 30.5.3 Example 1** (the rise-delay half: "if A
    /// transitioned more recently than B, a delay of 6 will be chosen. But
    /// if B transitioned more recently than A, a delay of 5 will be
    /// chosen. And if... A and B did so simultaneously, then the smallest
    /// of the two rise delays would be chosen, which is... 5.").
    ///
    /// `y`'s own real functional driver (`assign y = trig;`) is
    /// deliberately decoupled from `a`/`b` (LRM 30.5.3's selection is a
    /// function of which specify-path INPUT most recently transitioned,
    /// never of whether the destination's real driver expression actually
    /// reads that input — `PathRetimer::select_delay`'s own doc comment)
    /// so each scenario's `a`/`b` ordering can be set up independently of
    /// when `y` itself is made to transition via `trig`.
    ///
    /// `#N` delays are RELATIVE to the previous statement's own completion
    /// time, not absolute — every absolute checkpoint below is written out
    /// explicitly in a comment to make this unambiguous.
    #[test]
    fn run_design_lrm_30_5_3_example_1_rise_delay_selection() {
        let src = "module dut(input a, input b, input trig, output y);\n  assign y = \
                    trig;\n  specify\n    (a => y) = (6, 9);\n    (b => y) = (5, 11);\n  \
                    endspecify\nendmodule\n\nmodule top;\n  reg a, b, trig;\n  wire y;\n  dut \
                    d(.a(a), .b(b), .trig(trig), .y(y));\n  always @(y) $display(\"t=%0t \
                    y=%b\", $time, y);\n  initial begin\n    a = 0; b = 0; trig = 0;\n    // \
                    t=5: A-recent scenario -- B transitions first, A later.\n    #5 b = 1;\n    \
                    #5 a = 1;\n    #5 trig = 1;\n    // rise, A most recent -> delay 6, commits \
                    at t=15+6=21.\n    #15 trig = 0; a = 0; b = 0;\n    // fall (prev scenario's \
                    tie-break state is irrelevant to a fall from an already-known 1), settle, \
                    then start the B-recent scenario fresh.\n    #10 a = 1;\n    #5 b = 1;\n    \
                    #5 trig = 1;\n    // rise, B most recent -> delay 5, commits at \
                    t(trig=1)+5.\n    #15 trig = 0; a = 0; b = 0;\n    #10;\n    // tie \
                    scenario: a and b transition at the SAME time.\n    begin a = 1; b = 1; \
                    end\n    #5 trig = 1;\n    // rise, tied -> smallest of (6,5) = 5.\n    \
                    #20 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-sdf-t6-example1-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        // Absolute timeline (every `#N` below is relative to the PREVIOUS
        // statement's own completion time, per this test's own doc
        // comment): `a`/`b`/`trig` are `reg`s, so their own very first
        // assignment (`a=0;`/`b=0;`/`trig=0;`, all at t=0) is itself a real
        // `x -> 0` transition on each cell -- `a`'s and `b`'s own
        // `last_change` both start at `Some(0)` from this, and `y`'s own
        // `x -> 0` priming settle (once `trig`'s `x -> 0` reaches `staging`)
        // uses `select_delay(x, 0)` over BOTH members tied at that same
        // t=0 -- `min(x->0 for (6,9), x->0 for (5,11))` = `min(9, 11)` = 9,
        // committing at t=9.
        //
        //   t=0  a=0,b=0,trig=0           (all three cells' own x->0)
        //   t=9  y commits 0              (the x->0 priming settle above)
        //   t=5  b=1  (b's last_change=5)
        //   t=10 a=1  (a's last_change=10, A most recent)
        //   t=15 trig=1 -> rise, A most recent -> delay 6 -> commits t=21
        //   t=30 trig=0,a=0,b=0 (one zero-delay burst: by the time this
        //        process resumes, BOTH a's and b's own commits already
        //        landed, so a and b tie at last_change=30 too)
        //        -> fall, tied -> min(9,11)=9 -> commits t=39
        //   t=40 a=1  (#10 after t=30)
        //   t=45 b=1  (last_change=45, B most recent)
        //   t=50 trig=1 -> rise, B most recent -> delay 5 -> commits t=55
        //   t=65 trig=0,a=0,b=0 (another joint burst, tied again at 65)
        //        -> fall, tied -> min(9,11)=9 -> commits t=74
        //   t=75 a=1,b=1 simultaneously (one `begin...end`, truly tied)
        //   t=80 trig=1 -> rise, tied -> min(6,5)=5 -> commits t=85
        assert_eq!(
            stdout, "t=9 y=0\nt=21 y=1\nt=39 y=0\nt=55 y=1\nt=74 y=0\nt=85 y=1\n",
            "A-recent rise=6, tied fall=min(9,11)=9, B-recent rise=5, tied fall=min(9,11)=9, \
             tied rise=min(6,5)=5 -- LRM 30.5.3 Example 1's own stated selection numbers: {stdout}"
        );
    }

    /// LRM 30.4.4.1 lets a path condition name "bit-/part-selects", and LRM
    /// 11.5.1 defines `[b +: W]` as bits `b..b+W-1` and `[b -: W]` as
    /// `b-W+1..b`. Two conditional paths gate on one of each; the bus value
    /// picks which delay (3 or 7) applies. Hand-derived: s=8'b0001_0000 has
    /// s[4:3]=2'b10 (delay 3) and s[5:4]=2'b01 (no match); s=8'b0011_1000 has
    /// s[4:3]=2'b11 (no match) and s[5:4]=2'b11 (delay 7). The first `y=0`
    /// is the priming settle at the matching delay, 3.
    #[test]
    fn run_design_state_dependent_path_indexed_part_select_conditions() {
        let src = "module dut(input [7:0] s, input a, output y);\n  assign y = a;\n  specify\n    \
                    if (s[3 +: 2] == 2'b10) (a => y) = 3;\n    if (s[5 -: 2] == 2'b11) (a => y) \
                    = 7;\n  endspecify\nendmodule\n\nmodule top;\n  reg [7:0] s; reg a; wire y;\n  \
                    dut d(.s(s), .a(a), .y(y));\n  always @(y) $display(\"t=%0t y=%b\", $time, \
                    y);\n  initial begin\n    s = 8'b0001_0000; a = 0;\n    #50 a = 1;\n    #50 a \
                    = 0;\n    #50 s = 8'b0011_1000;\n    #50 a = 1;\n    #50 a = 0;\n    #50 \
                    $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-specify-indexed-cond-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        assert_eq!(
            stdout, "t=3 y=0\nt=53 y=1\nt=103 y=0\nt=207 y=1\nt=257 y=0\n",
            "`+:` condition selects delay 3, then `-:` condition delay 7: {stdout}"
        );
    }

    /// LRM 30.3 lets a path terminal be a part-select of a vector; LRM 11.5.1
    /// defines `[3 +: 1]` as bit 3 and `[4 -: 1]` as bit 4. `y = a[3] ^ a[4]`
    /// has two paths, `(a[3 +: 1] => y) = 5` and `(a[4 -: 1] => y) = 9`, and
    /// LRM 30.5.3 picks the delay of the most recently transitioned input.
    /// Hand-derived: a=0 primes y=0; a[3] rises at t=10 so y=1 at t=15
    /// (delay 5); a[4] rises at t=30 so y=0 at t=39 (delay 9). A path that
    /// watched the wrong bit would never see either input change.
    #[test]
    fn run_design_path_terminal_indexed_part_select() {
        let src = "module dut(input [4:0] a, output y);\n  assign y = a[3] ^ a[4];\n  specify\n    \
                    (a[3 +: 1] => y) = 5;\n    (a[4 -: 1] => y) = 9;\n  endspecify\nendmodule\n\n\
                    module top;\n  reg [4:0] a; wire y;\n  dut d(.a(a), .y(y));\n  always @(y) \
                    $display(\"t=%0t y=%b\", $time, y);\n  initial begin\n    a = 5'b00000;\n    #10 \
                    a = 5'b01000;\n    #20 a = 5'b11000;\n    #30 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-specify-indexed-term-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        let lines: Vec<&str> = stdout.lines().collect();
        for want in ["t=15 y=1", "t=39 y=0"] {
            assert!(lines.contains(&want), "missing `{want}` in: {stdout}");
        }
    }

    /// Runs `src` and returns `Ok(stdout)` or the run error's text.
    fn run_src_checked(tag: &str, src: &str) -> Result<String, String> {
        let file = std::env::temp_dir().join(format!("vj-{tag}-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let res = crate::run::run_design(&file, &mut out);
        let _ = std::fs::remove_file(&file);
        res.map_err(|e| e.to_string())?;
        Ok(String::from_utf8(out).expect("stdout is valid UTF-8"))
    }

    /// LRM 30.3/30.4.2: `(a[3 +: 2] => y[1:0]) = 5;` is a PARALLEL connection
    /// pairing `a[3]`->`y[0]` and `a[4]`->`y[1]`; `(c => y[0]) = 9;` adds a
    /// second source of `y[0]`. `y = {a[4], a[3] ^ c}`. Hand-derived (LRM
    /// 30.5.3 picks the delay of the most recently changed input): t=0 primes
    /// `00` at t=5 (delay 5 for both bits); a[3] rises at t=10 -> `y[0]`=1 at
    /// t=15; `c` rises at t=30 -> `y[0]`=0, most recent source `c` -> delay 9
    /// -> t=39; a[4] rises at t=50 -> `y[1]` at t=55 (delay 5).
    #[test]
    fn run_design_path_vector_destination_parallel_part_select_source() {
        let src = "module dut(input [4:0] a, input c, output [1:0] y);\n  assign y = {a[4], \
                   a[3] ^ c};\n  specify\n    (a[3 +: 2] => y[1:0]) = 5;\n    (c => y[0]) = \
                   9;\n  endspecify\nendmodule\nmodule top;\n  reg [4:0] a; reg c; wire [1:0] \
                   y;\n  dut d(.a(a), .c(c), .y(y));\n  always @(y) $display(\"t=%0t y=%b\", \
                   $time, y);\n  initial begin\n    a = 0; c = 0;\n    #10 a = 5'b01000;\n    \
                   #20 c = 1;\n    #20 a = 5'b11000;\n    #30 $finish;\n  end\nendmodule\n";
        let stdout = run_src_checked("specify-vec-par", src).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(stdout, "t=5 y=00\nt=15 y=01\nt=39 y=00\nt=55 y=10\n");
    }

    /// LRM 30.4.3: `(a[1:0] *> y) = 3;` is a FULL connection, so `a[1]` is
    /// also a source of `y[0]` (a parallel connection would pair only
    /// `a[0]`->`y[0]`). `y = {a[1], a[0] ^ c}`, plus `(c => y[0]) = 8`.
    /// Hand-derived: priming `00` at t=3; a[1] rises at t=10 -> `y[1]` at 13.
    /// At t=30 `c` rises and `a` clears in one step: `y[1]` falls, `y[0]`
    /// rises; `y[0]`'s most recent sources a[1] and `c` tie, and the tie takes
    /// the smaller delay min(3, 8) = 3 only because the full connection makes
    /// a[1] a source of y[0] (parallel would give 8) -> both at t=33. The same
    /// at t=60 (`c` falls, a[1] rises) -> t=63.
    #[test]
    fn run_design_path_vector_destination_full_connection_pairs_every_bit() {
        let src = "module dut(input [1:0] a, input c, output [1:0] y);\n  assign y = {a[1], \
                   a[0] ^ c};\n  specify\n    (a[1:0] *> y) = 3;\n    (c => y[0]) = 8;\n  \
                   endspecify\nendmodule\nmodule top;\n  reg [1:0] a; reg c; wire [1:0] y;\n  \
                   dut d(.a(a), .c(c), .y(y));\n  always @(y) $display(\"t=%0t y=%b\", $time, \
                   y);\n  initial begin\n    a = 0; c = 0;\n    #10 a = 2'b10;\n    #20 begin c \
                   = 1; a = 2'b00; end\n    #30 begin c = 0; a = 2'b10; end\n    #30 \
                   $finish;\n  end\nendmodule\n";
        let stdout = run_src_checked("specify-vec-full", src).unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(stdout, "t=3 y=00\nt=13 y=10\nt=33 y=01\nt=63 y=10\n");
    }

    /// LRM 30.4.2: a parallel connection needs equal bit counts (slang already refuses it), so
    /// `(a[3:2] => y)` with a 3-bit `y` is refused by name. A destination bit no path reaches
    /// is not an error: it takes its driver's value undelayed (LRM 30.4.6, 30.7).
    #[test]
    fn run_design_path_vector_destination_mismatches_are_refused() {
        let unequal = "module dut(input [3:0] a, output [2:0] y);\n  assign y = a[2:0];\n  \
                       specify\n    (a[3:2] => y) = 5;\n  endspecify\nendmodule\nmodule \
                       top;\n  reg [3:0] a; wire [2:0] y;\n  dut d(.a(a), .y(y));\n  initial \
                       #1 $finish;\nendmodule\n";
        let err = run_src_checked("specify-vec-neq", unequal).expect_err("unequal widths");
        assert!(err.contains("different width than destination"), "{err}");
        let partial = "module dut(input [3:0] a, output [2:0] y);\n  assign y = a[2:0];\n  \
                       specify\n    (a[0] => y[0]) = 5;\n  endspecify\nendmodule\nmodule \
                       top;\n  reg [3:0] a; wire [2:0] y;\n  dut d(.a(a), .y(y));\n  initial \
                       #1 $finish;\nendmodule\n";
        run_src_checked("specify-vec-partial", partial).unwrap_or_else(|e| panic!("{e}"));
    }

    /// **Task 6, LRM 30.5.3 Example 2 — ADAPTED.** The LRM's own example
    /// gates each of five module paths behind `if (MODE < k)`
    /// (state-dependent paths, LRM 30.4.4) — condition evaluation is
    /// explicitly Task 8's own scope, not this one's (`PathEntry` carries
    /// no `condition` field yet; see this file's own module doc). This
    /// task's own scope is the SELECTION mechanism among however many
    /// paths are "active" at once, which the LRM's own `MODE == 2` case
    /// exercises with exactly three active, UNCONDITIONED paths, all from
    /// the SAME input `A` to the SAME output `Y`:
    ///
    /// ```text
    /// if (MODE < 5) (A => Y) = (5, 9);   // MODE==2: active
    /// if (MODE < 4) (A => Y) = (4, 8);   // MODE==2: active
    /// if (MODE < 3) (A => Y) = (6, 5);   // MODE==2: active
    /// if (MODE < 2) (A => Y) = (3, 2);   // MODE==2: NOT active
    /// if (MODE < 1) (A => Y) = (7, 7);   // MODE==2: NOT active
    /// ```
    ///
    /// Reproducing the first three UNCONDITIONALLY (dropping the `if`
    /// guards, since they do not exist yet) is behaviorally identical to
    /// "exactly these three are active, the other two are not" for
    /// SELECTION purposes — the LRM's own stated numbers ("a rise
    /// transition would select a delay of 4... a fall transition would
    /// select a delay of 5") depend only on which THREE delay tables
    /// compete, never on the mechanism (condition vs. omission) that
    /// narrowed the candidate set to those three. All three sharing the
    /// SAME input `A` additionally proves [`PathRetimer::select_delay`]'s
    /// own N-way TIE handling (every member watches the same input cell,
    /// so all three always share one `last_change` timestamp), not just
    /// the two-way, different-input case Example 1 already covers.
    #[test]
    fn run_design_lrm_30_5_3_example_2_adapted_three_way_tie() {
        let src = "module dut(input a, input trig, output y);\n  assign y = trig;\n  \
                    specify\n    (a => y) = (5, 9);\n    (a => y) = (4, 8);\n    (a => y) = \
                    (6, 5);\n  endspecify\nendmodule\n\nmodule top;\n  reg a, trig;\n  wire \
                    y;\n  dut d(.a(a), .trig(trig), .y(y));\n  always @(y) $display(\"t=%0t \
                    y=%b\", $time, y);\n  initial begin\n    a = 0; trig = 0;\n    #5 a = 1;\n    \
                    #5 trig = 1;\n    // rise, all three tied -> smallest of (5,4,6) = 4.\n    \
                    #5 a = 0;\n    #5 trig = 0;\n    // fall, all three tied -> smallest of \
                    (9,8,5) = 5.\n    #20 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-sdf-t6-example2-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        // `a`/`trig` are `reg`s, so `a=0;`/`trig=0;` (both at t=0) are each
        // a real `x -> 0` transition on their own cell -- `a`'s own
        // `last_change` starts at `Some(0)` from this (all three members
        // share input `a`, so all three tie), and `y`'s own `x -> 0`
        // priming settle (once `trig`'s `x -> 0` reaches `staging`) uses
        // `select_delay(x, 0)` over all three tied at that same t=0:
        // `min(x->0 for (5,9), x->0 for (4,8), x->0 for (6,5))` =
        // `min(9, 8, 5)` = 5, committing at t=5.
        //
        //   t=0  a=0,trig=0        (both cells' own x->0)
        //   t=5  y commits 0       (the x->0 priming settle above)
        //   t=5  a=1               (a's last_change=5)
        //   t=10 trig=1 -> rise, three-way tie -> min(5,4,6)=4 -> commits t=14
        //   t=15 a=0               (a's last_change=15)
        //   t=20 trig=0 -> fall, three-way tie -> min(9,8,5)=5 -> commits t=25
        assert_eq!(
            stdout, "t=5 y=0\nt=14 y=1\nt=25 y=0\n",
            "LRM 30.5.3 Example 2's own stated numbers (rise=4, fall=5) among three paths tied \
             on the same input: {stdout}"
        );
    }

    /// Task 4b's own "negative unit test confirming an ordinary
    /// (non-specify-destination) variable write is completely unaffected"
    /// (the plan's own acceptance text) — run through the real
    /// `run_design` pipeline end to end (behavioral proof, not a raw IR
    /// diff: deviation from the plan's own "comparing emitted IR function
    /// body" wording, noted since it proves the SAME guarantee by a
    /// different, equally direct means — an un-redirected write is
    /// OBSERVABLY immediate). `q` and `q2` are written by the SAME
    /// `always @(posedge clk)` statement list (the strongest version of
    /// this test: it proves `LowerCtx::specify_dest`'s redirect is scoped
    /// to `q`'s own lvalue resolution, never leaking to a sibling
    /// statement's write in the SAME process): `q2` (ordinary) becomes `1`
    /// the moment its own nonblocking assignment commits (the NBA region
    /// of the SAME timestep as the clock edge, `t=20`, visible by `t=25`),
    /// while `q` (the specify-path destination) stays `x` until its own
    /// retimed commit lands at `t=26` (visible by `t=27`).
    #[test]
    fn run_design_leaves_an_ordinary_sibling_nonblocking_write_unaffected_end_to_end() {
        let src = "module dut(input clk, input d, output reg q, output reg q2);\n  always \
                    @(posedge clk) begin\n    q <= d;\n    q2 <= d;\n  end\n  specify\n    \
                    (posedge clk => (q +: d)) = (6, 8);\n  endspecify\nendmodule\n\nmodule \
                    top;\n  reg clk, d;\n  wire q, q2;\n  dut u(.clk(clk), .d(d), .q(q), \
                    .q2(q2));\n  initial begin\n    clk = 0;\n    d = 0;\n    #10 d = 1;\n    \
                    #10 clk = 1;\n    #0 $display(\"t=%0t q=%b q2=%b\", $time, q, q2);\n    \
                    #5 $display(\"t=%0t q=%b q2=%b\", $time, q, q2);\n    #2 $display(\"t=%0t \
                    q=%b q2=%b\", $time, q, q2);\n    $finish;\n  end\nendmodule\n";
        let file = std::env::temp_dir().join(format!(
            "vj-sdf-t4b-sibling-write-{}.sv",
            std::process::id()
        ));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        assert_eq!(
            stdout, "t=20 q=x q2=x\nt=25 q=x q2=1\nt=27 q=1 q2=1\n",
            "q2 (ordinary) must commit immediately in the clock edge's own NBA region, while \
             q (the specify-path destination) must stay x until its own retimed commit lands: \
             {stdout}"
        );
    }

    /// Review fix (r1): LRM §30.4.7's own polarity text ("does not affect
    /// the actual propagation of data") says the retimer's TIMING must be
    /// unaffected by polarity -- the acceptance text this task's own plan
    /// entry asks a dedicated test for. Two otherwise-identical fixtures,
    /// differing ONLY in the path operator's polarity (`+*>` vs. `-*>` vs.
    /// no polarity at all, `=>`), run through the real `run_design` pipeline
    /// end to end (not just `discover`/`plan` in isolation -- this proves
    /// `PathRetimer`'s actual scheduled commit times, not merely that the
    /// field round-trips): every one must produce byte-identical `$display`
    /// output, since the only way polarity COULD change scheduled times
    /// would be `PathRetimer::resume`'s delay lookup reading it, which it
    /// never does (`PathRetimer`'s own fields: `src`/`delays`/`prev`/
    /// `shared`/`kick` -- no `polarity`).
    #[test]
    fn path_retimer_never_reads_polarity_in_its_delay_computation() {
        let tb = |path_decl: &str| -> String {
            format!(
                "module dut(input a, output q);\n  assign q = a;\n  specify\n    {path_decl}\n  \
                 endspecify\nendmodule\n\nmodule top;\n  reg a;\n  wire q;\n  dut d(.a(a), \
                 .q(q));\n  initial begin\n    a = 0;\n    #10 $display(\"t=%0t q=%b\", $time, \
                 q);\n    a = 1;\n    #2 $display(\"t=%0t q=%b\", $time, q);\n    #2 \
                 $display(\"t=%0t q=%b\", $time, q);\n    a = 0;\n    #3 $display(\"t=%0t \
                 q=%b\", $time, q);\n    #3 $display(\"t=%0t q=%b\", $time, q);\n    \
                 $finish;\n  end\nendmodule\n"
            )
        };
        let run = |src: &str, tag: &str| -> String {
            static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let file = std::env::temp_dir().join(format!(
                "vj-sdf-t4a-polarity-{}-{tag}-{n}.sv",
                std::process::id()
            ));
            std::fs::write(&file, src).expect("write temp fixture");
            let mut out = Vec::new();
            let code = crate::run::run_design(&file, &mut out)
                .unwrap_or_else(|e| panic!("run_design({tag}) failed: {e}"));
            let _ = std::fs::remove_file(&file);
            assert_eq!(code, 0, "run_design({tag}) exited {code}");
            String::from_utf8(out).expect("stdout is valid UTF-8")
        };

        let no_polarity = run(&tb("(a => q) = (3, 5);"), "none");
        let positive = run(&tb("(a +=> q) = (3, 5);"), "pos");
        let negative = run(&tb("(a -=> q) = (3, 5);"), "neg");

        assert_eq!(
            no_polarity, positive,
            "a `+` polarity path must schedule identically to one with no polarity operator"
        );
        assert_eq!(
            no_polarity, negative,
            "a `-` polarity path must schedule identically to one with no polarity operator"
        );
    }

    // Task 7 (LRM 30.4.3, edge-sensitive paths).

    /// `plan` must copy `PathEntry::edge` into every `Member` it builds --
    /// the one wiring step between Task 3's discovery (already unit-tested
    /// in `vj-sim::netlist::specify`) and `PathRetimer::select_delay`'s
    /// own runtime gating.
    #[test]
    fn plan_copies_the_discovered_edge_spec_into_every_member() {
        let mut design = compile(
            "module m(input clock, in, output out);\n  assign out = in;\n  specify\n    \
             (posedge clock => (out +: in)) = (10, 8);\n  endspecify\nendmodule\n",
        );
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let infos = [(InstanceId(0), body)];
        let model = discover(&eval, &infos, Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));

        let out_uid = body
            .members()
            .find(|s| s.name() == "out")
            .expect("net out")
            .uid();
        let clock_uid = body
            .members()
            .find(|s| s.name() == "clock")
            .expect("net clock")
            .uid();
        let mut own = std::collections::HashMap::new();
        own.insert(out_uid, one_bit_slot(0));
        own.insert(clock_uid, one_bit_slot(1));
        let mut signals = std::collections::HashMap::new();
        signals.insert(InstanceId(0), own);

        let mut res = Resolution::default();
        let bank = InstanceId(u32::MAX);
        let plans = plan(
            &infos,
            &signals,
            &mut res,
            bank,
            &model,
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
        )
        .unwrap_or_else(|e| panic!("plan failed: {e}"));
        assert_eq!(plans.retimers.len(), 1);
        assert_eq!(plans.retimers[0].members.len(), 1);
        assert_eq!(
            plans.retimers[0].members[0].edge,
            vj_exec::timing::specify::PathEdge::Specific(vj_exec::timing::specify::EdgeSel::Pos)
        );
    }

    /// LRM 30.4.3's own text — "This arbitrary data path description does
    /// not affect the actual propagation of data or events through the
    /// model" — the Task 7 sibling of
    /// `path_retimer_never_reads_polarity_in_its_delay_computation` above:
    /// two otherwise-identical fixtures, differing ONLY in the edge-
    /// sensitive suffix's own data-source expression's REFERENCED SIGNAL
    /// NAME (`in` vs. `in2`, a renamed, otherwise-identical port), run
    /// through the real `run_design` pipeline end to end, must produce
    /// byte-identical `$display` output.
    #[test]
    fn edge_source_expr_text_never_affects_scheduled_timing() {
        let tb = |data_name: &str| -> String {
            format!(
                "module dut(input clock, input {data_name}, output out);\n  assign out = \
                 {data_name};\n  specify\n    (posedge clock => (out +: {data_name})) = (10, \
                 8);\n  endspecify\nendmodule\n\nmodule top;\n  reg clock, d;\n  wire out;\n  \
                 dut u(.clock(clock), .{data_name}(d), .out(out));\n  initial begin\n    \
                 clock = 0;\n    d = 0;\n    #10 d = 1;\n    #10 clock = 1;\n    #0 \
                 $display(\"t=%0t out=%b\", $time, out);\n    #9 $display(\"t=%0t out=%b\", \
                 $time, out);\n    #2 $display(\"t=%0t out=%b\", $time, out);\n    \
                 $finish;\n  end\nendmodule\n"
            )
        };
        let run = |src: &str, tag: &str| -> String {
            static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
            let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let file = std::env::temp_dir().join(format!(
                "vj-sdf-t7-edge-source-expr-{}-{tag}-{n}.sv",
                std::process::id()
            ));
            std::fs::write(&file, src).expect("write temp fixture");
            let mut out = Vec::new();
            let code = crate::run::run_design(&file, &mut out)
                .unwrap_or_else(|e| panic!("run_design({tag}) failed: {e}"));
            let _ = std::fs::remove_file(&file);
            assert_eq!(code, 0, "run_design({tag}) exited {code}");
            String::from_utf8(out).expect("stdout is valid UTF-8")
        };

        let named_in = run(&tb("in"), "in");
        let named_in2 = run(&tb("in2"), "in2");
        assert_eq!(
            named_in, named_in2,
            "renaming the edge-sensitive suffix's own data-source expression's referenced \
             signal must not change scheduled timing at all"
        );
    }

    /// The thing this task actually adds over pre-Task-7 behavior:
    /// `PathRetimer::select_delay`'s own edge-eligibility filter (LRM
    /// 30.4.3) EXCLUDES a candidate module path whose own source terminal
    /// did not just transition in the required direction, falling back to
    /// `0`/immediate (this task's own documented floor) rather than
    /// applying its delay table unconditionally. Three destinations
    /// (`outP`/posedge, `outN`/negedge, `outA`/no-identifier-"any
    /// transition") share one `clock`/`in` pair, deliberately decoupled
    /// (`assign outX = in;`, never gated by `clock` at all) so a
    /// transition of the destination and a transition of `clock` are
    /// independent events — exactly the scenario a wrong, pre-Task-7-style
    /// "ignore the edge keyword entirely" implementation cannot
    /// distinguish from this one. The SAME fixture (byte-identical) is also
    /// `crates/vj-harness/tests/fixtures/probe/
    /// specify_edge_sensitive_mismatch.sv`, classified `Verdict::Expected`
    /// in the probe corpus (verified LIVE there that `iverilog -g2012
    /// -gspecify` diverges from the LRM on exactly this point — it ignores
    /// the edge keyword entirely too, applying every path's delay table to
    /// every transition of its own destination regardless of `clock`); this
    /// copy exists so `cargo test -p vj` alone (no harness crate,
    /// no `iverilog` binary) still exercises and would fail on a regression
    /// of this task's own core behavior.
    #[test]
    fn run_design_edge_sensitive_path_gates_on_the_specified_edge() {
        let src = "module dutP(input clock, input in, output out);\n  assign out = in;\n  \
                    specify\n    (posedge clock => (out +: in)) = (10, 8);\n  endspecify\n\
                    endmodule\n\nmodule dutN(input clock, input in, output out);\n  assign out \
                    = in;\n  specify\n    (negedge clock => (out -: in)) = (10, 8);\n  \
                    endspecify\nendmodule\n\nmodule dutA(input clock, input in, output \
                    out);\n  assign out = in;\n  specify\n    (clock => (out : in)) = (10, \
                    8);\n  endspecify\nendmodule\n\nmodule top;\n  reg clock, in;\n  wire outP, \
                    outN, outA;\n  dutP dp(.clock(clock), .in(in), .out(outP));\n  dutN \
                    dn(.clock(clock), .in(in), .out(outN));\n  dutA da(.clock(clock), .in(in), \
                    .out(outA));\n  always @(outP) $display(\"t=%0t outP=%b\", $time, \
                    outP);\n  always @(outN) $display(\"t=%0t outN=%b\", $time, outN);\n  \
                    always @(outA) $display(\"t=%0t outA=%b\", $time, outA);\n  initial \
                    begin\n    clock = 0; in = 0;\n    #20 in = 1;\n    #20 in = 0; clock = \
                    1;\n    #20 in = 1; clock = 0;\n    #20 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-sdf-t7-edge-gate-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        // Absolute timeline (every `#N` is relative to the previous
        // statement's own completion time): `clock`/`in` are `reg`s, so
        // `clock=0;`/`in=0;` (both at t=0) are each a real transition on
        // their own cell -- `clock`'s own `x->0` classifies as `Neg`
        // (`classify_bit4_edge`'s own table), so `outN`/`outA` (which
        // require `Neg`/any) are eligible for it (derived `x->0` delay for
        // the 2-value list `(10,8)` is `max(z->0=8,1->0=8)=8`, due `t=8`)
        // while `outP` (`Pos`) is not eligible (immediate, `t=0`).
        //
        //   t=0   outP=0                 (Pos required, clock's x->0 is Neg -- not eligible, immediate)
        //   t=8   outN=0, outA=0         (Neg/any eligible, derived x->0 delay 8)
        //   t=20  in=1, clock unchanged  -- clock's last_change != 20 for all three -- NONE eligible
        //   t=20  outP=1, outN=1, outA=1 (all three immediate, delay 0)
        //   t=40  in=0, clock=1 (posedge, Pos)
        //         outN: Neg required, mismatch -- immediate, t=40
        //         outP: Pos matches -- fall delay 8 (table.of(1,0)) -- due t=48
        //         outA: any matches  -- fall delay 8 -- due t=48
        //   t=60  in=1, clock=0 (negedge, Neg)
        //         outP: Pos required, mismatch -- immediate, t=60
        //         outN: Neg matches -- rise delay 10 (table.of(0,1)) -- due t=70
        //         outA: any matches -- rise delay 10 -- due t=70
        assert_eq!(
            stdout,
            "t=0 outP=0\nt=8 outN=0\nt=8 outA=0\nt=20 outP=1\nt=20 outN=1\nt=20 outA=1\nt=40 \
             outN=0\nt=48 outP=0\nt=48 outA=0\nt=60 outP=1\nt=70 outN=1\nt=70 outA=1\n",
            "LRM 30.4.3's own edge-gating rule, worked through this fixture's own timeline: \
             {stdout}"
        );
    }

    // ------------------------------------------------------------------
    // Task 8 (LRM 30.4.4.*, state-dependent paths): the native `CondEval`
    // interpreter's own Table 30-1 arithmetic, pinned directly (no
    // `Place`/live design needed -- every leaf here is a `CondEval::Const`).

    fn bits1(b: Bit4) -> Vec<Bit4> {
        vec![b]
    }

    #[test]
    fn eval_unary_logical_not_treats_x_and_z_as_true_per_30_4_4_1() {
        use super::CondEval;
        use vj_sim::netlist::specify::CondUnaryOp;
        // `!0 = 1`, `!1 = 0`, `!x = x`, `!z = x` (LRM 11.4.6's own logical-
        // NOT table over a single-bit operand).
        for (v, want) in [
            (Bit4::Zero, Bit4::One),
            (Bit4::One, Bit4::Zero),
            (Bit4::X, Bit4::X),
            (Bit4::Z, Bit4::X),
        ] {
            let e = CondEval::Unary(CondUnaryOp::LogicalNot, Box::new(CondEval::Const(bits1(v))));
            assert_eq!(e.eval(), bits1(want), "!{v:?}");
        }
    }

    #[test]
    fn eval_binary_logical_and_or_follow_the_4_state_absorbing_element_rule() {
        use super::CondEval;
        use vj_sim::netlist::specify::CondBinaryOp;
        let c = |b: Bit4| CondEval::Const(bits1(b));
        // `0 && x = 0` (absorbing), `1 && x = x`, `1 || x = 1` (absorbing),
        // `0 || x = x`.
        assert_eq!(
            CondEval::Binary(
                CondBinaryOp::LogicalAnd,
                Box::new(c(Bit4::Zero)),
                Box::new(c(Bit4::X))
            )
            .eval(),
            bits1(Bit4::Zero)
        );
        assert_eq!(
            CondEval::Binary(
                CondBinaryOp::LogicalAnd,
                Box::new(c(Bit4::One)),
                Box::new(c(Bit4::X))
            )
            .eval(),
            bits1(Bit4::X)
        );
        assert_eq!(
            CondEval::Binary(
                CondBinaryOp::LogicalOr,
                Box::new(c(Bit4::One)),
                Box::new(c(Bit4::X))
            )
            .eval(),
            bits1(Bit4::One)
        );
        assert_eq!(
            CondEval::Binary(
                CondBinaryOp::LogicalOr,
                Box::new(c(Bit4::Zero)),
                Box::new(c(Bit4::X))
            )
            .eval(),
            bits1(Bit4::X)
        );
    }

    #[test]
    fn eval_binary_equality_is_x_on_any_unknown_bit_else_a_real_bit_comparison() {
        use super::CondEval;
        use vj_sim::netlist::specify::CondBinaryOp;
        // `2'b00 == 2'b00` -> 1; `2'b00 == 2'b01` -> 0; `2'bx0 == 2'b00` ->
        // x (LRM 11.4.6's own `==`/`!=` table: any unknown operand bit
        // forces an `x` result, never a guessed true/false).
        let a = CondEval::Const(vec![Bit4::Zero, Bit4::Zero]);
        let b = CondEval::Const(vec![Bit4::Zero, Bit4::Zero]);
        assert_eq!(
            CondEval::Binary(CondBinaryOp::Equality, Box::new(a), Box::new(b)).eval(),
            bits1(Bit4::One)
        );
        let a = CondEval::Const(vec![Bit4::Zero, Bit4::Zero]);
        let b = CondEval::Const(vec![Bit4::One, Bit4::Zero]);
        assert_eq!(
            CondEval::Binary(CondBinaryOp::Equality, Box::new(a), Box::new(b)).eval(),
            bits1(Bit4::Zero)
        );
        let a = CondEval::Const(vec![Bit4::X, Bit4::Zero]);
        let b = CondEval::Const(vec![Bit4::Zero, Bit4::Zero]);
        assert_eq!(
            CondEval::Binary(CondBinaryOp::Equality, Box::new(a), Box::new(b)).eval(),
            bits1(Bit4::X)
        );
    }

    #[test]
    fn is_condition_true_treats_x_and_z_as_true_and_uses_the_lsb_of_a_vector() {
        use super::CondEval;
        // LRM 30.4.4.1: "If the conditional expression evaluates to x or z,
        // it shall be treated as true. If the conditional expression
        // evaluates to multiple bits, the LSB shall represent the result."
        assert!(CondEval::Const(bits1(Bit4::One)).is_condition_true());
        assert!(!CondEval::Const(bits1(Bit4::Zero)).is_condition_true());
        assert!(CondEval::Const(bits1(Bit4::X)).is_condition_true());
        assert!(CondEval::Const(bits1(Bit4::Z)).is_condition_true());
        // A multi-bit value whose LSB is 0 but whose MSB is 1 -- the LSB
        // rule means this is FALSE, even though an ordinary "any bit set"
        // truthiness check would call it true.
        assert!(!CondEval::Const(vec![Bit4::Zero, Bit4::One]).is_condition_true());
        assert!(CondEval::Const(vec![Bit4::One, Bit4::Zero]).is_condition_true());
    }

    #[test]
    fn eval_concat_is_msb_first_source_order_over_lsb_first_storage() {
        use super::CondEval;
        // `{2'b10, 1'b1}` (3 bits: msb..lsb = 1,0,1) -- `2'b10`'s own
        // LSB-first storage is `[Zero, One]`; `1'b1` is `[One]`. Concatenated
        // (source order `[2'b10, 1'b1]`, MSB-most first), the overall
        // LSB-first result must be `[One, Zero, One]` (bit0=1 from `1'b1`,
        // bit1=0/bit2=1 from `2'b10`).
        let msb_part = CondEval::Const(vec![Bit4::Zero, Bit4::One]);
        let lsb_part = CondEval::Const(vec![Bit4::One]);
        let e = CondEval::Concat(vec![msb_part, lsb_part]);
        assert_eq!(e.eval(), vec![Bit4::One, Bit4::Zero, Bit4::One]);
    }

    #[test]
    fn eval_replication_repeats_the_unit_n_times_lsb_first() {
        use super::CondEval;
        // `{3{1'b1, 1'b0}}` (unit `1,0` MSB-first -> LSB-first `[0,1]`,
        // repeated 3 times): `[0,1,0,1,0,1]`.
        let unit = CondEval::Concat(vec![
            CondEval::Const(bits1(Bit4::One)),
            CondEval::Const(bits1(Bit4::Zero)),
        ]);
        let e = CondEval::Replication(3, Box::new(unit));
        assert_eq!(
            e.eval(),
            vec![
                Bit4::Zero,
                Bit4::One,
                Bit4::Zero,
                Bit4::One,
                Bit4::Zero,
                Bit4::One
            ]
        );
    }

    #[test]
    fn eval_ternary_selects_the_true_or_false_branch_and_merges_on_an_ambiguous_condition() {
        use super::CondEval;
        let t = CondEval::Const(bits1(Bit4::One));
        let f = CondEval::Const(bits1(Bit4::Zero));
        assert_eq!(
            CondEval::Ternary(
                Box::new(CondEval::Const(bits1(Bit4::One))),
                Box::new(t.clone()),
                Box::new(f.clone())
            )
            .eval(),
            bits1(Bit4::One)
        );
        assert_eq!(
            CondEval::Ternary(
                Box::new(CondEval::Const(bits1(Bit4::Zero))),
                Box::new(t.clone()),
                Box::new(f.clone())
            )
            .eval(),
            bits1(Bit4::Zero)
        );
        // An ambiguous (x) condition with agreeing branches must still
        // report that agreed value, not unconditionally `x`.
        assert_eq!(
            CondEval::Ternary(
                Box::new(CondEval::Const(bits1(Bit4::X))),
                Box::new(t.clone()),
                Box::new(t)
            )
            .eval(),
            bits1(Bit4::One)
        );
        // An ambiguous condition with DISAGREEING branches is `x`.
        assert_eq!(
            CondEval::Ternary(
                Box::new(CondEval::Const(bits1(Bit4::X))),
                Box::new(f),
                Box::new(CondEval::Const(bits1(Bit4::One)))
            )
            .eval(),
            bits1(Bit4::X)
        );
    }

    /// [`compile_ifnone_siblings`] + [`RuntimeGate::is_true`] together
    /// (LRM 30.4.4.4: "a default state-dependent path delay when all
    /// other conditions for the path are false"), pinned directly against
    /// the synthesized sibling-GROUP gate -- no `select_delay` tie-break
    /// involved, so this cannot be coincidentally satisfied by a gate that
    /// is wrongly always-eligible (`None`, "unconditional") the way the
    /// end-to-end
    /// `run_design_if_and_ifnone_gate_delay_selection_like_the_lrm_alu_example`
    /// test below can be (see that test's own review history): a sibling
    /// `If` condition being true must make this gate INELIGIBLE, not
    /// merely "not win a smallest-delay tie-break".
    #[test]
    fn ifnone_gate_is_false_whenever_any_sibling_if_condition_is_true() {
        use std::collections::HashMap;

        use super::{TimingModel, compile_ifnone_siblings, cond_eval_of};
        use vj_exec::timing::specify::RuntimeGate;
        use vj_sim::netlist::specify::CondNode;

        let own = HashMap::new();
        let instance = InstanceId(0);
        let model = TimingModel::new();

        // Two sibling `if` conditions (e.g. `if (opcode==2'b01)` and
        // `if (opcode==2'b10)`, LRM 30.4.4.4 Example 1's own ALU), each a
        // single-bit `Const` -- `compile_ifnone_siblings` is purely
        // syntactic over whatever `CondNode`s it is handed, so a `Const`
        // leaf exercises it exactly as faithfully as a real `Signal`
        // leaf, with no `own`/`model` resolution needed at all.
        for (siblings_true, want_eligible, label) in [
            (
                [Bit4::Zero, Bit4::Zero],
                true,
                "every sibling false -> ifnone is the default -> eligible",
            ),
            (
                [Bit4::One, Bit4::Zero],
                false,
                "first sibling true -> ifnone must be excluded",
            ),
            (
                [Bit4::Zero, Bit4::One],
                false,
                "second sibling true -> ifnone must be excluded (ANY \
                 sibling firing excludes it, not just the first)",
            ),
            (
                [Bit4::One, Bit4::One],
                false,
                "both siblings true -> still excluded",
            ),
        ] {
            let siblings: Vec<CondNode> = siblings_true
                .iter()
                .map(|&b| CondNode::Const(vec![b]))
                .collect();
            let refs: Vec<&CondNode> = siblings.iter().collect();
            let compiled = compile_ifnone_siblings(&refs, &own, instance, &model)
                .expect("const-only siblings compile")
                .expect("two `If` siblings -> Some per 30.4.4.4");
            let gate = RuntimeGate::IfNone(
                compiled
                    .iter()
                    .map(|c| cond_eval_of(c, &HashMap::new()))
                    .collect(),
            );
            assert_eq!(
                gate.is_true(),
                want_eligible,
                "{label}: siblings={siblings_true:?}"
            );
        }

        // No siblings at all -> 30.4.4.4's own "treated the same as an
        // unconditional simple module path" rule, synthesized here as
        // `None` (every caller treats `None` as `PathCondition::
        // Unconditional`, per `compile_ifnone_siblings`'s own doc comment)
        // rather than a vacuous always-eligible gate.
        assert!(
            compile_ifnone_siblings(&[], &own, instance, &model)
                .unwrap()
                .is_none()
        );
    }

    /// The actual review finding this test is named for: `ifnone`'s own
    /// gate must exclude a sibling using [`CondEval::is_condition_true`]'s
    /// LSB rule (LRM 30.4.4.1), never ordinary 4-state `||` truthiness
    /// (LRM 11.4.6, "any known 1 bit is true") on that sibling's RAW
    /// value -- the two disagree whenever a sibling's own condition is a
    /// raw (non-comparison) multi-bit signal whose LSB differs from "any
    /// bit set", e.g. `if (sel)` with `sel == 2'b10` (LSB `0`, so
    /// `is_condition_true()` is false, but a bitwise "any bit set" check
    /// is true). See [`RuntimeGate::is_true`]'s own doc comment for the
    /// full argument; this test pins the runtime behavior directly, with
    /// no `select_delay`/`run_design` plumbing involved (the end-to-end
    /// regression is
    /// `run_design_ifnone_fires_when_a_raw_multibit_sibling_condition_has_lsb_zero`
    /// below, live-verified against `iverilog -g2012 -gspecify`).
    #[test]
    fn select_delay_ifnone_gate_uses_each_siblings_own_lsb_rule_not_raw_or_truthiness() {
        use super::CondEval;
        use vj_exec::timing::specify::RuntimeGate;

        // `sel == 2'b10`, LSB-first: bit0=0, bit1=1. Its own `if (sel)`
        // eligibility is FALSE (LSB is 0) even though the raw value has a
        // set bit (bit1).
        let sel = CondEval::Const(vec![Bit4::Zero, Bit4::One]);
        assert!(
            !sel.is_condition_true(),
            "sel=2'b10's own `if (sel)` condition must be false per the LSB rule"
        );

        // `ifnone`'s own gate, with `sel` as its one sibling, must
        // therefore be eligible (the sibling's own condition is false, so
        // nothing else claims this transition and the default applies) --
        // not ineligible, which is what a `NOT(OR(raw sel))`-style
        // combination would wrongly give (OR via `truthy()` sees the set
        // bit1 and says the sibling is true).
        let gate = RuntimeGate::IfNone(vec![sel]);
        assert!(
            gate.is_true(),
            "ifnone must fire when its one sibling's own LSB-rule condition is \
             false, even though that sibling's raw value has a set bit"
        );
    }

    /// End-to-end regression for the bug above, through the real
    /// `plan`/`register`/`select_delay` pipeline (not just [`RuntimeGate`]
    /// directly): `if (sel) (in1=>out)=(5,5); ifnone (in1=>out)=(40,40);`
    /// with `sel` held at `2'b10` (constant -- LSB `0`, so `if (sel)` is
    /// false every tick) and `in1` transitioning `0->1` at `t=100`. Per
    /// LRM 30.4.4.1's own LSB rule, `if (sel)` is false throughout, so
    /// `ifnone`'s own delay (40) must apply to EVERY transition of `out`,
    /// including `in1`'s own initial `x->0` elaboration settle (due
    /// `t=0+40=40`) and the real `t=100` transition (due `t=100+40=140`).
    /// Live-verified against `iverilog -g2012 -gspecify`+`vvp` on this
    /// EXACT source, byte for byte: `t=40 out=0` / `t=140 out=1` (plus
    /// Icarus's own bare-`$finish` banner, which vj does not print --
    /// see this file's own established "Expected"/hand-verified-output
    /// discipline, matching every other oracle-divergence note in this
    /// module). Before this fix, vj produced `t=0 out=0` / `t=100
    /// out=1` instead: `ifnone_gate`'s own `NOT(OR(raw sel))` synthesis
    /// saw `sel`'s raw set bit (bit1) via ordinary truthiness and
    /// evaluated FALSE, excluding `ifnone` too, so NEITHER member was
    /// eligible and `select_delay`'s "no candidate" floor (immediate
    /// propagation) fired instead.
    #[test]
    fn run_design_ifnone_fires_when_a_raw_multibit_sibling_condition_has_lsb_zero() {
        let src = "module m(input in1, output out, input [1:0] sel);\n  assign out = \
                    in1;\n  specify\n    if (sel) (in1=>out) = (5,5);\n    ifnone \
                    (in1=>out) = (40,40);\n  endspecify\nendmodule\nmodule top;\n  reg \
                    in1;\n  reg [1:0] sel;\n  wire out;\n  m dut(.in1(in1), .out(out), \
                    .sel(sel));\n  always @(out) $display(\"t=%0t out=%b\", $time, \
                    out);\n  initial begin\n    in1 = 0; sel = 2'b10;\n    #100 in1 = \
                    1;\n    #50 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-sdf-t8-ifnone-lsb-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        assert_eq!(
            stdout, "t=40 out=0\nt=140 out=1\n",
            "ifnone must fire on sel=2'b10 (if(sel)'s own LSB is 0) for EVERY out \
             transition, including the initial x->0 settle: {stdout}"
        );
    }

    /// `plan`'s own `If`/`IfNone`/`Unconditional` wiring, end to end: each
    /// of a destination's three candidate paths gets the right eligibility
    /// shape, and `ifnone`'s own synthesized gate actually changes which
    /// delay `select_delay` picks -- the LRM 30.4.4.2/30.4.4.4 ALU+ifnone
    /// combination, adapted to this workspace's own scalar-source scope
    /// (see this file's own module doc: a module-path SOURCE must be a
    /// single bit, so `opcode` is used only inside the CONDITION, never as
    /// a path terminal itself).
    #[test]
    fn run_design_if_and_ifnone_gate_delay_selection_like_the_lrm_alu_example() {
        let src = "module m(input i1, input i2, output o1, input [1:0] opcode);\n  assign o1 = \
                    (opcode == 2'b01) ? i1 : (opcode == 2'b10) ? i2 : (i1 ^ i2);\n  specify\n    \
                    if (opcode == 2'b01) (i1 => o1) = (5, 9);\n    if (opcode == 2'b10) (i2 => \
                    o1) = (5, 9);\n    ifnone (i2 => o1) = (15, 15);\n  endspecify\nendmodule\n\
                    module top;\n  reg i1, i2;\n  reg [1:0] opcode;\n  wire o1;\n  m dut(.i1(i1), \
                    .i2(i2), .o1(o1), .opcode(opcode));\n  always @(o1) $display(\"t=%0t \
                    o1=%b\", $time, o1);\n  initial begin\n    i1 = 0; i2 = 0; opcode = 2'b00;\n  \
                    #10 opcode = 2'b10; i2 = 1;\n    #20 opcode = 2'b00; i2 = 0;\n    #30 i2 = \
                    1;\n    #50 $finish;\n  end\nendmodule\n";
        let file =
            std::env::temp_dir().join(format!("vj-sdf-t8-alu-ifnone-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        let stdout = String::from_utf8(out).expect("stdout is valid UTF-8");
        // t=10: opcode->10 and i2->1 in the same statement list -- o1's
        // natural (functional) value transitions 0->1 (opcode was 00 so
        // o1=i1^i2=0^0=0; now opcode=10 selects i2=1). `if(opcode==10)
        // (i2=>o1)` is now true AND i2 just changed -> active, delay 5 (its
        // own RISE delay -- the 2-value list `(5,9)` is `(trise,tfall)`,
        // and `0->1` is a rise), due t=15.
        // t=30: opcode->00, i2->0 in the same statement list -- o1's
        // natural value: opcode=00 selects i1^i2=0^0=0 -- but o1 is
        // currently 1 (from t=15), so this is a real 1->0 transition. Per
        // the `if`/`ifnone` grouping on (i2,o1): `if(opcode==10)` is now
        // FALSE (opcode is 00), so the ifnone's own gate (`NOT(if(opcode==
        // 10))`) is TRUE -- ifnone is active, fall delay 15, due t=45.
        // t=60: i2->1 alone (opcode stays 00) -- o1's natural value
        // 0->1 (i1^i2 = 0^1 = 1). ifnone still active (opcode==00, not
        // ==10) -- rise delay 15, due t=75.
        assert_eq!(
            stdout, "t=15 o1=1\nt=45 o1=0\nt=75 o1=1\n",
            "If/ifnone gating must select the condition-appropriate delay at each \
             transition: {stdout}"
        );
    }

    /// Runs `src` through the real `run_design` pipeline and returns its
    /// stdout (the SAME shape as `run_design_ifnone_fires_when_a_raw_multibit_
    /// sibling_condition_has_lsb_zero` above, factored once for the sdf T10
    /// pulse-control tests below).
    fn run_src(tag: &str, src: &str) -> String {
        let file = std::env::temp_dir().join(format!("vj-sdf-t10-{tag}-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design(&file, &mut out)
            .unwrap_or_else(|e| panic!("run_design failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        String::from_utf8(out).expect("stdout is valid UTF-8")
    }

    /// sdf T10 (LRM 30.7.1): a path-specific `PATHPULSE$src$dst` naming a
    /// path that does not exist (here `b` -> `y`, while the only path is
    /// `a` -> `y`) has no effect at all -- the path keeps its default
    /// limits (each = the delay, 10), so a width-4 pulse is rejected
    /// outright. Had the unmatched PATHPULSE wrongly applied to `a -> y`,
    /// limits (2, 6) would filter the pulse to X instead.
    #[test]
    fn run_design_an_unmatched_pathpulse_leaves_the_default_limits_alone() {
        let stdout = run_src(
            "unmatched",
            "module m(input a, input b, output y);\n  assign y = a;\n  specify\n    (a => y) = \
             10;\n    specparam PATHPULSE$b$y = (2, 6);\n  endspecify\nendmodule\nmodule top;\n  \
             reg a, b;\n  wire y;\n  m dut(.a(a), .b(b), .y(y));\n  always @(y) \
             $display(\"t=%0t y=%b\", $time, y);\n  initial begin\n    a = 0; b = 0;\n    #50 \
             a = 1;\n    #4 a = 0;\n    #50 $finish;\n  end\nendmodule\n",
        );
        assert_eq!(
            stdout, "t=10 y=0\n",
            "default full-inertial rejection: {stdout}"
        );
    }

    /// sdf T10 (LRM 30.7.1): "(clr, pre *> q)" is ONE declaration, so only
    /// its first input (`clr`) and first output (`q`) may be named by a
    /// PATHPULSE$. `PATHPULSE$clr$q = (2, 6)` therefore covers BOTH desugared
    /// paths (`clr -> q` and `pre -> q`), while `PATHPULSE$pre$q = (0, 0)`
    /// names a non-first terminal and is ignored (not an error). A width-4
    /// pulse on `clr` is filtered to X by (2, 6); the same pulse on `pre`
    /// is covered by the SAME (2, 6) too (not by the ignored (0, 0), which
    /// would pass it as a clean 1 -> 0 pulse).
    #[test]
    fn run_design_a_multi_path_declaration_is_named_by_its_first_terminal_only() {
        let stdout = run_src(
            "multi",
            "module m(input clr, input pre, output q);\n  assign q = clr | pre;\n  specify\n    \
             (clr, pre *> q) = 10;\n    specparam PATHPULSE$clr$q = (2, 6);\n    specparam \
             PATHPULSE$pre$q = (0, 0);\n  endspecify\nendmodule\nmodule top;\n  reg clr, pre;\n  \
             wire q;\n  m dut(.clr(clr), .pre(pre), .q(q));\n  always @(q) $display(\"t=%0t \
             q=%b\", $time, q);\n  initial begin\n    clr = 0; pre = 0;\n    #50 clr = 1;\n    #4 \
             clr = 0;\n    #46 pre = 1;\n    #4 pre = 0;\n    #50 $finish;\n  end\nendmodule\n",
        );
        assert_eq!(
            stdout, "t=10 q=0\nt=60 q=x\nt=64 q=0\nt=110 q=x\nt=114 q=0\n",
            "both desugared paths share (2, 6); the (0, 0) naming `pre` is ignored: {stdout}"
        );
    }

    /// sdf T10 (LRM 30.7): the three width regions around the limits, with
    /// the exact boundary widths (`width == reject` is NOT rejected,
    /// `width == error` passes) -- `PATHPULSE$a$y = (3, 7)` on a delay-10
    /// path. Widths 2 (< 3: rejected), 3 (== reject: X), 6 (< 7: X) and 7
    /// (== error: passes).
    #[test]
    fn run_design_pulse_width_boundaries_follow_the_reject_and_error_limits() {
        let stdout = run_src(
            "bounds",
            "module m(input a, output y);\n  assign y = a;\n  specify\n    (a => y) = 10;\n    \
             specparam PATHPULSE$a$y = (3, 7);\n  endspecify\nendmodule\nmodule top;\n  reg a;\n  \
             wire y;\n  m dut(.a(a), .y(y));\n  always @(y) $display(\"t=%0t y=%b\", $time, \
             y);\n  initial begin\n    a = 0;\n    #100 a = 1; #2 a = 0;\n    #100 a = 1; #3 a = \
             0;\n    #100 a = 1; #6 a = 0;\n    #100 a = 1; #7 a = 0;\n    #100 $finish;\n  \
             end\nendmodule\n",
        );
        assert_eq!(
            stdout,
            "t=10 y=0\n\
             t=212 y=x\nt=215 y=0\n\
             t=315 y=x\nt=321 y=0\n\
             t=421 y=1\nt=428 y=0\n",
            "width 2 vanishes; 3 and 6 go through X; 7 passes: {stdout}"
        );
    }

    /// sdf T10 (LRM 30.6, "the larger of the two delays shall be used"): a
    /// distributed delay (`assign #20`) longer than the module path delay (10)
    /// is a FLOOR on both pulse limits, not only on the delay. Without a
    /// `PATHPULSE$` the limits would be the path's own 10, and a width-12 pulse
    /// (>= 10) would wrongly pass; with the floor both limits are 20 and it is
    /// rejected. A width-25 pulse (>= 20) still passes, so the floor is not
    /// simply "reject everything". Run once with the default limits and once
    /// with `PATHPULSE$a$y = (2, 6)`, which the floor lifts to (20, 20) too.
    #[test]
    fn run_design_a_longer_distributed_delay_floors_both_pulse_limits() {
        for pulse in ["", "specparam PATHPULSE$a$y = (2, 6);"] {
            let stdout = run_src(
                "floor",
                &format!(
                    "module m(input a, output y);\n  assign #20 y = a;\n  specify\n    (a => y) = \
                     10;\n    {pulse}\n  endspecify\nendmodule\nmodule top;\n  reg a;\n  wire \
                     y;\n  m dut(.a(a), .y(y));\n  always @(y) $display(\"t=%0t y=%b\", $time, \
                     y);\n  initial begin\n    a = 0;\n    #100 a = 1;\n    #12 a = 0;\n    #100 \
                     a = 1;\n    #25 a = 0;\n    #100 $finish;\n  end\nendmodule\n"
                ),
            );
            assert_eq!(
                stdout, "t=20 y=0\nt=232 y=1\nt=257 y=0\n",
                "width 12 < 20 vanishes, width 25 passes ({pulse:?}): {stdout}"
            );
        }
    }

    /// `(reject, error)` limits of the (first) path whose first input is
    /// `input`, asserting that all twelve transitions hold the same pair (a
    /// `PATHPULSE$` names ONE reject and ONE error value for the whole path).
    fn uniform_limits(
        model: &vj_sim::netlist::specify::TimingModel,
        body: Symbol<'_>,
        input: &str,
    ) -> (u64, u64) {
        let uid = body
            .members()
            .find(|s| s.name() == input)
            .unwrap_or_else(|| panic!("no signal `{input}`"))
            .uid();
        let entry = model
            .paths
            .iter()
            .find(|p| p.inputs[0].0 == uid)
            .unwrap_or_else(|| panic!("no path from `{input}`"));
        let pairs = [
            (Bit4::Zero, Bit4::One),
            (Bit4::One, Bit4::Zero),
            (Bit4::Zero, Bit4::Z),
            (Bit4::Z, Bit4::One),
            (Bit4::One, Bit4::Z),
            (Bit4::Z, Bit4::Zero),
            (Bit4::Zero, Bit4::X),
            (Bit4::X, Bit4::One),
            (Bit4::One, Bit4::X),
            (Bit4::X, Bit4::Zero),
            (Bit4::X, Bit4::Z),
            (Bit4::Z, Bit4::X),
        ];
        let (r, e) = (
            entry.reject_limit.of(pairs[0].0, pairs[0].1),
            entry.error_limit.of(pairs[0].0, pairs[0].1),
        );
        for (from, to) in pairs {
            assert_eq!(entry.reject_limit.of(from, to), r, "{from:?}->{to:?}");
            assert_eq!(entry.error_limit.of(from, to), e, "{from:?}->{to:?}");
        }
        (r, e)
    }

    /// Discovers the single instance `src` declares.
    fn discover_src(src: &str) -> Result<(), super::RunError> {
        let mut design = compile(src);
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let result = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"));
        result.map(|_| ())
    }

    fn limits_in(src: &str, inputs: &[&str]) -> Vec<(u64, u64)> {
        let mut design = compile(src);
        let eval = design.eval_session();
        let body = top_body(eval.design());
        let model = discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        inputs
            .iter()
            .map(|i| uniform_limits(&model, body, i))
            .collect()
    }

    /// sdf T10 (LRM 30.7.1's own worked example, reproduced exactly): `clk ->
    /// q` gets (2, 9), `clr -> q` and `pre -> q` (the one `(clr, pre *> q)`
    /// declaration) get (0, 4), and `data -> q`, named by no path-specific
    /// PATHPULSE$, gets the module-wide `PATHPULSE$ = 3` as both limits.
    #[test]
    fn discover_reproduces_the_lrm_30_7_1_worked_example() {
        let limits = limits_in(
            "module m(input clk, input data, input clr, input pre, output q);\n  assign q = \
             clk | data | clr | pre;\n  specify\n    (clk => q) = 12;\n    (data => q) = 10;\n    \
             (clr, pre *> q) = 4;\n\n    specparam\n      PATHPULSE$clk$q = (2,9),\n      \
             PATHPULSE$clr$q = (0,4),\n      PATHPULSE$ = 3;\n  endspecify\nendmodule\n",
            &["clk", "clr", "pre", "data"],
        );
        assert_eq!(limits, [(2, 9), (0, 4), (0, 4), (3, 3)]);
    }

    /// sdf T10 (LRM 30.7.1): "A PATHPULSE$ specparam that specifies anything
    /// other than the first path input and path output terminals shall be
    /// ignored" — ignored, NOT an error. `pre` is not the first input of
    /// `(clr, pre *> q)` and `r` is not the first output of `(a *> q, r)`, so
    /// both leave every path at its default (each transition's own delay).
    #[test]
    fn discover_ignores_a_pathpulse_naming_a_non_first_terminal() {
        let limits = limits_in(
            "module m(input clr, input pre, input a, output q, output r);\n  assign q = clr | \
             pre | a;\n  assign r = a;\n  specify\n    (clr, pre *> q) = 4;\n    (a *> q, r) = 6;\n    \
             specparam PATHPULSE$pre$q = (0, 1);\n    specparam PATHPULSE$a$r = (1, 2);\n  \
             endspecify\nendmodule\n",
            &["clr", "pre", "a"],
        );
        assert_eq!(limits, [(4, 4), (4, 4), (6, 6)]);
    }

    /// sdf T10 (LRM 30.7.1): a path-specific PATHPULSE$ takes precedence over
    /// the module-wide one for the path it names, whichever is declared
    /// first; the module-wide one covers every other path; a single value is
    /// both limits.
    #[test]
    fn discover_path_specific_pathpulse_wins_over_module_wide_in_either_order() {
        for decls in [
            "specparam PATHPULSE$ = (1, 2); specparam PATHPULSE$a$y = 5;",
            "specparam PATHPULSE$a$y = 5; specparam PATHPULSE$ = (1, 2);",
        ] {
            let limits = limits_in(
                &format!(
                    "module m(input a, input b, output y);\n  assign y = a & b;\n  specify\n    \
                     (a => y) = 10;\n    (b => y) = 10;\n    {decls}\n  endspecify\nendmodule\n"
                ),
                &["a", "b"],
            );
            assert_eq!(limits, [(5, 5), (1, 2)], "{decls}");
        }
    }

    /// sdf T10: the documented clamps. An error limit below the reject limit
    /// is raised to it (the same repair LRM 30.7.2 prescribes for the global
    /// percentages), and a negative limit is zero (the same rule LRM 30.5.1
    /// gives a path delay).
    #[test]
    fn discover_clamps_inverted_and_negative_pulse_limits() {
        let limits = limits_in(
            "module m(input a, input b, output y);\n  assign y = a & b;\n  specify\n    (a => y) = \
             10;\n    (b => y) = 10;\n    specparam NEG = -3;\n    specparam PATHPULSE$a$y = (6, \
             2);\n    specparam PATHPULSE$b$y = (NEG, 4);\n  endspecify\nendmodule\n",
            &["a", "b"],
        );
        assert_eq!(limits, [(6, 6), (0, 4)]);
    }

    /// sdf T10: limits are converted with the module's timescale exactly like
    /// the delays they limit (1 ns / 1 ps: 1 unit = 1000 ticks), including
    /// fractional values, and the error limit may be an expression over
    /// specparams (sv-lang 0.1.9 exposes only the first value, so the second
    /// is evaluated separately).
    #[test]
    fn discover_converts_pulse_limits_with_the_timescale_and_evaluates_the_error_limit() {
        let limits = limits_in(
            "`timescale 1ns/1ps\nmodule m(input a, output y);\n  assign y = a;\n  specify\n    \
             specparam hi = 0.5;\n    (a => y) = 2;\n    specparam PATHPULSE$a$y = (0.25, hi + \
             1.0);\n  endspecify\nendmodule\n",
            &["a"],
        );
        assert_eq!(limits, [(250, 1500)]);
    }

    /// sdf T10 (LRM 6.20.5, Table 6-11: a specparam "May be assigned
    /// specparams and parameters"): the error limit may name a module
    /// `parameter` or `localparam`, alone or inside an expression, and takes
    /// its ELABORATED value. Reject limit 2 and error limits 7 / 9 / 6.
    #[test]
    fn discover_evaluates_an_error_limit_over_parameters_and_localparams() {
        let limits = limits_in(
            "module m(input a, input b, input c, output y);\n  parameter P = 7;\n  localparam L = \
             3;\n  assign y = a & b & c;\n  specify\n    (a => y) = 10;\n    (b => y) = 10;\n    \
             (c => y) = 10;\n    specparam PATHPULSE$a$y = (2, P);\n    specparam PATHPULSE$b$y = \
             (2, P + 2);\n    specparam PATHPULSE$c$y = (2, L * 2);\n  endspecify\nendmodule\n",
            &["a", "b", "c"],
        );
        assert_eq!(limits, [(2, 7), (2, 9), (2, 6)]);
    }

    /// sdf T10: the error limit is evaluated in 64 bits. A specparam / parameter
    /// above 2^31 named by (or inside) the second `PATHPULSE$` value used to be
    /// predeclared as a 32-bit `integer`, wrapped negative, clamped to 0 and
    /// silently collapsed the error limit onto the reject limit. 3e9 (> 2^31,
    /// < 2^32), 4e9 + 2 inside an expression, and a parameter of 5e9 (> 2^32),
    /// each written SIZED (an unsized literal is truncated by sv-lang itself
    /// before it gets here: see `reject_truncated_literals`).
    #[test]
    fn discover_evaluates_an_error_limit_above_two_pow_31_without_wrapping() {
        let limits = limits_in(
            "module m(input a, input b, input c, output y);\n  parameter P = 64'd5000000000;\n  \
             specparam big = 64'd3000000000;\n  assign y = a & b & c;\n  specify\n    (a => y) = \
             10;\n    (b => y) = 10;\n    (c => y) = 10;\n    specparam PATHPULSE$a$y = (1, \
             big);\n    specparam PATHPULSE$b$y = (1, big + 1000000000 + 2);\n    specparam \
             PATHPULSE$c$y = (1, P);\n  endspecify\nendmodule\n",
            &["a", "b", "c"],
        );
        assert_eq!(
            limits,
            [(1, 3_000_000_000), (1, 4_000_000_002), (1, 5_000_000_000)]
        );
    }

    /// sdf T10: the same wrap seen end to end -- a width-4 pulse is inside
    /// [1, 3e9), so it must go through x (the old 32-bit wrap made the error
    /// limit 0 and let it pass as a clean 1/0 pulse).
    #[test]
    fn run_design_an_error_limit_above_two_pow_31_filters_to_x() {
        let stdout = run_src(
            "bigerr",
            "module m(input a, output y);\n  assign y = a;\n  specify\n    specparam big = \
             64'd3000000000;\n    (a => y) = 10;\n    specparam PATHPULSE$a$y = (1, big);\n  \
             endspecify\nendmodule\nmodule top;\n  reg a;\n  wire y;\n  m dut(.a(a), .y(y));\n  \
             always @(y) $display(\"t=%0t y=%b\", $time, y);\n  initial begin\n    a = 0;\n    \
             #100 a = 1;\n    #4 a = 0;\n    #100 $finish;\n  end\nendmodule\n",
        );
        assert_eq!(stdout, "t=10 y=0\nt=110 y=x\nt=114 y=0\n", "{stdout}");
    }

    /// sdf T10: sv-lang's default 1800-2017 mode truncates an UNSIZED decimal
    /// literal above 2^31-1 to 32 bits before this crate sees it (`specparam big
    /// = 3000000000` holds -1294967296), which would silently wrap a pulse
    /// limit. Every spelling that reaches a limit -- the literal inline, through
    /// a specparam, through a parameter, through an expression over either -- is
    /// a loud error naming the literal instead; an unrelated big literal, or a
    /// sized one, is fine.
    #[test]
    fn discover_rejects_an_unsized_literal_above_i32_max_in_a_pulse_limit_loudly() {
        for limit in [
            "3000000000",
            "big",
            "P",
            "big + 1",
            "Q",
            "3_000_000_000",
            "99999999999999999999",
        ] {
            let src = format!(
                "module m(input a, output y);\n  parameter P = 5000000000;\n  parameter Q = P;\n  \
                 specparam big = 3000000000;\n  assign y = a;\n  specify\n    (a => y) = \
                 10;\n    specparam PATHPULSE$a$y = (1, {limit});\n  endspecify\nendmodule\n"
            );
            match discover_src(&src) {
                Err(super::RunError::Lowering(e)) => {
                    assert!(
                        e.message.contains("PATHPULSE$") && e.message.contains("truncates"),
                        "{limit}: {}",
                        e.message
                    );
                }
                Err(other) => panic!("{limit}: expected RunError::Lowering, got {other}"),
                Ok(_) => panic!("{limit}: a truncated limit must not be accepted"),
            }
        }
        // 2^31-1 itself is exact, and a big literal no limit names is not an error.
        let limits = limits_in(
            "module m(input a, output y);\n  specparam unused = 3000000000;\n  assign y = a;\n  \
             specify\n    (a => y) = 10;\n    specparam PATHPULSE$a$y = (1, 2147483647);\n  \
             endspecify\nendmodule\n",
            &["a"],
        );
        assert_eq!(limits, [(1, 2_147_483_647)]);
    }

    /// sdf T10: a `parameter` in the error limit takes the INSTANCE's value
    /// (an override and a `defparam`), not the declared default. Two instances
    /// of one module with `P` = 9 (override), 7 (default) and 5 (defparam);
    /// every instance filters a width-8 pulse on a delay-20 path (reject 2) by
    /// its own error limit: 8 < 9 goes through x, 8 >= 7 and 8 >= 5 pass.
    #[test]
    fn run_design_an_error_limit_over_a_parameter_follows_the_instance_override() {
        let stdout = run_src(
            "param",
            "module m #(parameter P = 7)(input a, output y);\n  assign y = a;\n  specify\n    (a => \
             y) = 20;\n    specparam PATHPULSE$a$y = (2, P);\n  endspecify\nendmodule\nmodule \
             top;\n  reg a;\n  wire y1, y2, y3;\n  m #(.P(9)) d1(.a(a), .y(y1));\n  m d2(.a(a), \
             .y(y2));\n  m d3(.a(a), .y(y3));\n  defparam d3.P = 5;\n  always @(y1) \
             $display(\"t=%0t y1=%b\", $time, y1);\n  always @(y2) $display(\"t=%0t y2=%b\", \
             $time, y2);\n  always @(y3) $display(\"t=%0t y3=%b\", $time, y3);\n  initial begin\n    \
             a = 0;\n    #100 a = 1;\n    #8 a = 0;\n    #100 $finish;\n  end\nendmodule\n",
        );
        let mut lines: Vec<&str> = stdout.lines().collect();
        lines.sort();
        assert_eq!(
            lines,
            [
                "t=120 y1=x",
                "t=120 y2=1",
                "t=120 y3=1",
                "t=128 y1=0",
                "t=128 y2=0",
                "t=128 y3=0",
                "t=20 y1=0",
                "t=20 y2=0",
                "t=20 y3=0",
            ],
            "{stdout}"
        );
    }

    /// sdf T10: an error limit this crate cannot evaluate (here a call to a
    /// function, which the scratch session does not know) is a loud, named
    /// lowering error, never a silent fall back to the reject value.
    #[test]
    fn discover_rejects_an_unevaluable_error_limit_loudly() {
        match discover_src(
            "module m(input a, output y);\n  function integer f(input integer x);\n    f = x + \
             1;\n  endfunction\n  assign y = a;\n  specify\n    (a => y) = 10;\n    specparam \
             PATHPULSE$a$y = (2, f(6));\n  endspecify\nendmodule\n",
        ) {
            Err(super::RunError::Lowering(e)) => {
                assert!(e.message.contains("PATHPULSE$"), "{}", e.message);
            }
            Err(other) => panic!("expected RunError::Lowering, got {other}"),
            Ok(_) => panic!("an error limit that cannot be evaluated must not be dropped"),
        }
    }
}