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
//! `$sdf_annotate`'s host side (IEEE 1800-2023 clause 32; SD-B / T25 + T26,
//! `docs/superpowers/plans/2026-10-03-sdf.md`): reads the SDF file, finds the instances and
//! specify paths each construct names, and rewrites those paths' live delays and pulse limits
//! ([`crate::specify::LiveTimes`], which the planned retimers read on every transition).
//!
//! The runtime half (`vj_runtime::sdf_annotate`) decodes the call's seven arguments and
//! hands them to the [`Annotator::apply`] installed for the run (`run.rs`); the arithmetic of
//! a single construct is [`crate::sdf_values`], the comparison of `COND` expressions is
//! [`crate::sdf_cond`]. This module is the matching and the bookkeeping in between.
//!
//! **What is annotated.** DELAY sections: `IOPATH`, `COND`/`CONDELSE` `IOPATH`, `DEVICE`,
//! `PATHPULSE` and `PATHPULSEPERCENT` (Table 32-1), and TIMINGCHECK sections (T27, Table 32-2,
//! [`crate::sdf_checks`]: each SDF check rewrites the live limits of the SystemVerilog checks
//! it maps to, [`crate::timingcheck::LiveChecks`]), and LABEL sections (T28, 32.4.3,
//! [`crate::sdf_labels`]: a specparam is annotated and the specify path delays and timing check
//! limits that read it are re-evaluated), and `PORT`, `NETDELAY` and `INTERCONNECT` (T29, 32.4.4,
//! [`crate::interconnect`]: a retiming stage on the port connection wires between the source and
//! the load). A construct for something this build does not annotate is reported as a warning
//! naming the construct, never skipped silently (LRM 32.3: a warning "for any data it is unable
//! to annotate").
//!
//! **Implementation-defined choices** (the LRM leaves them open), each also at its use:
//! - A plain `IOPATH` annotates every specify path between its two ports, `ifnone` paths
//!   included (Table 32-1 says "conditional and nonconditional"; an `ifnone` path is the
//!   conditional one's complement).
//! - SDF edges map to the path's edge identifier: `posedge`/`01` to `posedge`, `negedge`/`10`
//!   to `negedge`. An SDF edge matches only a path that names that edge: not one with no edge
//!   at all, one sensitive to any transition, or one on `edge` (both). The `z` transitions
//!   (`0z`, `z1`, `1z`, `z0`) have no SystemVerilog edge identifier and match nothing, with a
//!   warning.
//! - A port written with a bit index matches a terminal that is the whole signal, or the same
//!   one-bit window; the index is the bit's offset from the least significant bit (the declared
//!   index for a `[N-1:0]` port, the usual case). A whole-signal terminal of a vector is one
//!   path here, so an SDF bit index annotates that whole path.
//! - `DEVICE` annotates a module's specify paths to its outputs; a module with none gets the
//!   primitives driving its outputs instead (Table 32-1). The module is the cell's own
//!   instance, or a child instance (or one of a child's outputs) the DEVICE's port_instance
//!   names ([`Annotator::device_target`]); the child's delays round to the child's precision.
//!   Those primitives get a live delay
//!   line only in a design that calls `$sdf_annotate` (`primitives::calls_sdf_annotate`), and a
//!   zero-delay one commits one delta later than an unannotated output would. A gate's rise,
//!   fall and turn-off come from the Table 32-4 slots (0->1, 1->0, and the smaller of 0->z and
//!   1->z, which equals Table 28-9 for one to three values and is a choice for six or twelve).
//!   A bit index on the port does not narrow the match, and the pulse limits of a primitive's
//!   delay are not annotated (warned). A continuous assignment's `#delay` is not annotated.
//! - `RETAIN` is ignored (Table 32-1 allows it).
//! - `config_file` is checked for readability and otherwise ignored, with a warning.

use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::path::Path;
use std::sync::{Arc, Mutex};

use sv_lang::Symbol;
use vj_codegen::process_lower::SignalSlot;
use vj_runtime::sdf_annotate::SdfAnnotateCall;
use vj_sdf::ast::{
    Cell, CheckKind, DelayDef, DelayKind, Edge, Instance, IoPath, IoPathCond, LabelBlock,
    PathPulse, Port, PortBit, PortTchk, SdfFile, Timescale, TimingCheck, TimingSpec,
};
use vj_sim::netlist::InstanceId;
use vj_sim::netlist::specify::{
    CheckArgs, CheckEntry, CheckEvent, CondNode, PathCondition, PathDelaySet, PathEdge, PathEntry,
    TerminalRef,
};
use vj_sim::process::cfg::shown_path;
use vj_sim::symid::SymbolId;

use crate::interconnect::{Node, SharedTable};
use crate::primitives::{Delays, DeviceDelays, PrimDelays};
use crate::sdf_checks::{self, SvCheck};
use crate::sdf_cond::{self, CondScope};
use crate::sdf_labels::LabelPlan;
use crate::sdf_values::{
    Mtm, PulsePercent, Scale, Selector, SlotUpdate, apply_update, device_delays, iopath_update,
    pathpulse_update, to_ticks,
};
use crate::specify::LiveTimes;
use crate::timing_options::{SdfMtm, TimingOptions};
use crate::timingcheck::{self, LimitNote, LiveChecks};

/// One instance of the design, as an SDF `INSTANCE` path can name it.
#[derive(Clone, Debug)]
pub(crate) struct SdfInstance {
    pub(crate) id: InstanceId,
    /// The hierarchical path, as `$sdf_annotate`'s scope argument spells it (`m.u1`).
    pub(crate) path: String,
    /// The module definition name, which an SDF `CELLTYPE` must equal.
    pub(crate) module: String,
    /// The instance's time precision exponent (annotated delays round to it, LRM 3.14.2.2).
    pub(crate) precision_exp: i32,
    /// The instance's own signals by their name inside it (`clk`, not `m.u1.clk`).
    pub(crate) signals: HashMap<String, (SymbolId, u32)>,
    /// Those signals' storage slots, which name them in the interconnect table
    /// ([`crate::interconnect::Node`]).
    pub(crate) slots: HashMap<String, u32>,
    names: HashMap<SymbolId, String>,
}

/// The table of every instance, from the elaborated design.
pub(crate) fn instance_table<P>(
    infos: &[(InstanceId, Symbol<'_>, Symbol<'_>, P)],
    instance_signals: &HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
) -> Vec<SdfInstance> {
    infos
        .iter()
        .map(|(id, body, inst, _)| {
            let prefix = format!("{}.", body.hierarchical_path());
            let mut signals = HashMap::new();
            let mut slot_of = HashMap::new();
            let mut names = HashMap::new();
            if let Some(slots) = instance_signals.get(id) {
                for (uid, slot) in slots {
                    // A signal inside a generate block is `blk.sig`: not a port a SDF
                    // path component can name.
                    let Some(rel) = uid.path().strip_prefix(&prefix) else {
                        continue;
                    };
                    if rel.contains('.') {
                        continue;
                    }
                    signals.insert(rel.to_string(), (uid.clone(), slot.width));
                    slot_of.insert(rel.to_string(), slot.slot);
                    names.insert(uid.clone(), rel.to_string());
                }
            }
            SdfInstance {
                id: *id,
                path: shown_path(inst),
                module: inst
                    .instance_definition()
                    .map(|d| d.name().to_string())
                    .unwrap_or_default(),
                precision_exp: vj_codegen::timescale::precision_exp(inst),
                signals,
                slots: slot_of,
                names,
            }
        })
        .collect()
}

/// Every specparam a path condition names, as an unsigned integer (what a condition
/// comparison needs), keyed like `TimingModel::specparam`.
pub(crate) fn condition_specparams(
    model: &vj_sim::netlist::specify::TimingModel,
) -> HashMap<(InstanceId, SymbolId), u64> {
    fn walk(
        node: &CondNode,
        inst: InstanceId,
        model: &vj_sim::netlist::specify::TimingModel,
        out: &mut HashMap<(InstanceId, SymbolId), u64>,
    ) {
        match node {
            CondNode::Specparam(uid) => {
                let value = model
                    .specparam(inst, uid)
                    .and_then(|v| v.as_integer())
                    .and_then(|int| {
                        let mut value = 0u64;
                        let bits = int.bits();
                        if bits.len() > 64 {
                            return None;
                        }
                        for (i, b) in bits.iter().enumerate() {
                            match b {
                                sv_lang::Bit::One => value |= 1 << i,
                                sv_lang::Bit::Zero => {}
                                sv_lang::Bit::X | sv_lang::Bit::Z => return None,
                            }
                        }
                        Some(value)
                    });
                if let Some(v) = value {
                    out.insert((inst, uid.clone()), v);
                }
            }
            CondNode::Signal(_) | CondNode::Const(_) => {}
            CondNode::Unary(_, a) | CondNode::Replication(_, a) => walk(a, inst, model, out),
            CondNode::Binary(_, a, b) => {
                walk(a, inst, model, out);
                walk(b, inst, model, out);
            }
            CondNode::Ternary(a, b, c) => {
                walk(a, inst, model, out);
                walk(b, inst, model, out);
                walk(c, inst, model, out);
            }
            CondNode::Concat(items) => items.iter().for_each(|i| walk(i, inst, model, out)),
        }
    }
    let mut out = HashMap::new();
    for p in &model.paths {
        if let PathCondition::If(node) = &p.condition {
            walk(node, p.instance, model, &mut out);
        }
    }
    out
}

/// An instance's names for [`sdf_cond`].
struct InstScope<'a> {
    inst: &'a SdfInstance,
    specparams: &'a HashMap<(InstanceId, SymbolId), u64>,
}

impl CondScope for InstScope<'_> {
    fn width_of(&self, name: &str) -> Option<u32> {
        self.inst.signals.get(name).map(|(_, w)| *w)
    }
    fn name_of(&self, uid: &SymbolId) -> Option<(String, u32)> {
        let name = self.inst.names.get(uid)?;
        Some((name.clone(), self.inst.signals[name].1))
    }
    fn specparam(&self, uid: &SymbolId) -> Option<u64> {
        self.specparams.get(&(self.inst.id, uid.clone())).copied()
    }
}

/// Whether the SDF port `port` names the terminal `t` of a path in `inst` (see the module doc
/// for the bit-index rule).
fn terminal_matches(inst: &SdfInstance, t: &TerminalRef, port: &Port) -> bool {
    let [name] = port.path.as_slice() else {
        return false;
    };
    if inst.names.get(&t.0) != Some(name) {
        return false;
    }
    match (port.bit, t.1) {
        (None, _) | (Some(_), None) => true,
        (Some(PortBit::Bit(i)), Some((lo, width))) => width == 1 && i64::from(lo) == i,
        (Some(PortBit::Range(a, b)), Some((lo, width))) => {
            i64::from(lo) == a.min(b) && i64::from(width) == (a - b).abs() + 1
        }
    }
}

/// Whether an SDF edge qualifier selects the path's edge. `Err` for an edge no SystemVerilog
/// edge identifier can name.
fn edge_matches(sdf: Option<Edge>, path: PathEdge) -> Result<bool, String> {
    let want = match sdf {
        None => return Ok(true),
        Some(Edge::Posedge | Edge::T01) => sv_lang::EdgeKind::PosEdge,
        Some(Edge::Negedge | Edge::T10) => sv_lang::EdgeKind::NegEdge,
        Some(e @ (Edge::T0z | Edge::Tz1 | Edge::T1z | Edge::Tz0)) => {
            return Err(format!(
                "the edge {e:?} has no SystemVerilog edge identifier (posedge/negedge cover 01 \
                 and 10 only)"
            ));
        }
    };
    Ok(path == PathEdge::Specific(want))
}

/// Whether the SDF timing-check port `port` (its terminal, edge and `COND`) names the check
/// event `ev` (LRM 32.4.2): a check port with no edge or `COND` matches the event whatever its
/// own, one with an edge must name the event's own (`posedge clk` does not match an event on
/// `edge clk`, or on `clk` alone), and a `COND` must be the event's `&&&` condition.
fn event_matches(
    inst: &SdfInstance,
    scope: &InstScope<'_>,
    port: &PortTchk,
    ev: &CheckEvent,
) -> Result<bool, String> {
    if !terminal_matches(inst, &ev.terminal, &port.spec.port) {
        return Ok(false);
    }
    if let Some(edge) = port.spec.edge
        && timingcheck::sdf_edge_control(edge)? != ev.edge_control
    {
        return Ok(false);
    }
    match (&port.cond, &ev.condition) {
        (None, _) => Ok(true),
        (Some(expr), Some(node)) => sdf_cond::equivalent(expr, node, scope),
        (Some(_), None) => Ok(false),
    }
}

/// A check's reference event and, but for `$width` and `$period`, its data event.
fn check_events(args: &CheckArgs) -> (&CheckEvent, Option<&CheckEvent>) {
    match args {
        CheckArgs::Setup(a)
        | CheckArgs::Hold(a)
        | CheckArgs::Recovery(a)
        | CheckArgs::Removal(a)
        | CheckArgs::Skew(a) => (&a.reference, Some(&a.data)),
        CheckArgs::SetupHold(a) => (&a.reference, Some(&a.data)),
        CheckArgs::RecRem(a) => (&a.reference, Some(&a.data)),
        CheckArgs::TimeSkew(a) => (&a.reference, Some(&a.data)),
        CheckArgs::FullSkew(a) => (&a.reference, Some(&a.data)),
        CheckArgs::NoChange(a) => (&a.reference, Some(&a.data)),
        CheckArgs::Period(a) => (&a.reference, None),
        CheckArgs::Width(a) => (&a.reference, None),
    }
}

/// A check's `timestamp_condition` and `timecheck_condition`, which only `$setuphold` and
/// `$recrem` have (an SDF `SCOND` / `CCOND` names them).
fn check_conditions(args: &CheckArgs) -> (Option<&CondNode>, Option<&CondNode>) {
    match args {
        CheckArgs::SetupHold(a) => (a.timestamp_cond.as_ref(), a.timecheck_cond.as_ref()),
        CheckArgs::RecRem(a) => (a.timestamp_cond.as_ref(), a.timecheck_cond.as_ref()),
        CheckArgs::Setup(_)
        | CheckArgs::Hold(_)
        | CheckArgs::Recovery(_)
        | CheckArgs::Removal(_)
        | CheckArgs::Skew(_)
        | CheckArgs::TimeSkew(_)
        | CheckArgs::FullSkew(_)
        | CheckArgs::Period(_)
        | CheckArgs::Width(_)
        | CheckArgs::NoChange(_) => (None, None),
    }
}

/// The warning for a limit annotated to the check `name` that could not be stored as given
/// (`None`: it was).
fn limit_note_warning(note: LimitNote, name: &str) -> Option<String> {
    match note {
        LimitNote::Exact => None,
        LimitNote::NegativeToZero => Some(format!(
            "the negative limit annotated to {name} cannot be negative (it takes no negative \
             limit); set to 0"
        )),
        LimitNote::Unrealisable { negative_timing } => Some(format!(
            "the limit annotated to {name} cannot be realised ({}); set to 0",
            if negative_timing {
                "the delay of the check's delayed signals, solved when the design was planned, \
                 cannot absorb it (LRM 31.9.1)"
            } else {
                "it is negative and negative timing checks are not enabled \
                 (--enable-negative-timing-checks)"
            }
        )),
    }
}

/// Whether the condition `node` reads the specparam `uid`.
fn condition_reads(node: &CondNode, uid: &SymbolId) -> bool {
    match node {
        CondNode::Specparam(u) => u == uid,
        CondNode::Signal(_) | CondNode::Const(_) => false,
        CondNode::Unary(_, a) | CondNode::Replication(_, a) => condition_reads(a, uid),
        CondNode::Binary(_, a, b) => condition_reads(a, uid) || condition_reads(b, uid),
        CondNode::Ternary(a, b, c) => {
            condition_reads(a, uid) || condition_reads(b, uid) || condition_reads(c, uid)
        }
        CondNode::Concat(items) => items.iter().any(|i| condition_reads(i, uid)),
    }
}

/// Keeps an [`Annotator`] installed as the runtime's `$sdf_annotate` applier until dropped, so
/// a run never leaves its design's annotator behind for the next run on the same thread.
pub(crate) struct Installed;

impl Installed {
    pub(crate) fn new(mut annotator: Annotator) -> Installed {
        vj_runtime::specparam::clear();
        vj_runtime::sdf_annotate::install_applier(Box::new(move |call| annotator.apply(call)));
        // A failed call finishes the run the way `$finish`/`$fatal` do (the handle argument is
        // unused by the real body: the running scheduler is reached through its own bridge).
        vj_runtime::sdf_annotate::install_finisher(Box::new(|code| {
            vj_sim::sched::real_sv_rt_finish(vj_abi::SimHandle(std::ptr::null_mut()), code);
        }));
        Installed
    }
}

impl Drop for Installed {
    fn drop(&mut self) {
        vj_runtime::sdf_annotate::clear_applier();
        // The annotated specparams belong to this run's design.
        vj_runtime::specparam::clear();
    }
}

/// The annotator `run.rs` installs for a run.
pub(crate) struct Annotator {
    /// A copy of every module path as discovered (index-aligned with `live`).
    paths: Vec<PathEntry>,
    instances: Vec<SdfInstance>,
    specparams: HashMap<(InstanceId, SymbolId), u64>,
    live: LiveTimes,
    /// The primitives `DEVICE` annotates when a module has no specify path to the output.
    device: DeviceDelays,
    /// Every primitive instance's output delays by hierarchical path, which an SDF `CELL`
    /// naming the primitive itself annotates ([`Self::annotate_prim`]).
    prims: PrimDelays,
    tick_exp: i32,
    /// LRM 32.7's reject / error percentages (the invocation options,
    /// [`Annotator::with_options`]).
    pulse: PulsePercent,
    /// What `TOOL_CONTROL` selects (LRM Table 32-5; `--sdf-mtm`, typical by default).
    tool_control: Mtm,
    /// Log files this run has already opened (truncated once, then appended to).
    logs: HashSet<String>,
    /// Every SystemVerilog timing check of the design (index-aligned with `live_checks`).
    checks: Vec<CheckEntry>,
    /// The limits of those checks, which `TIMINGCHECK` annotation rewrites.
    live_checks: Arc<LiveChecks>,
    /// The specparams a `LABEL` annotates and what reads them (T28, [`crate::sdf_labels`]).
    labels: LabelPlan,
    /// The design's port connection wires, which `PORT`, `NETDELAY` and `INTERCONNECT` annotate
    /// (T29, [`crate::interconnect`]); empty until `run.rs` has built them.
    interconnect: Option<SharedTable>,
    /// `vj build-aot` resolves a call without running it: the log is kept, not written.
    capture_log: bool,
    captured_log: Option<(String, Vec<String>)>,
}

impl Annotator {
    pub(crate) fn new(
        paths: Vec<PathEntry>,
        instances: Vec<SdfInstance>,
        specparams: HashMap<(InstanceId, SymbolId), u64>,
        live: LiveTimes,
        device: DeviceDelays,
        tick_exp: i32,
    ) -> Annotator {
        Annotator {
            paths,
            instances,
            specparams,
            live,
            device,
            prims: PrimDelays::new(),
            tick_exp,
            pulse: PulsePercent::DEFAULT,
            tool_control: Mtm::Typ,
            logs: HashSet::new(),
            checks: Vec::new(),
            live_checks: Arc::new(LiveChecks::default()),
            labels: LabelPlan::default(),
            interconnect: None,
            capture_log: false,
            captured_log: None,
        }
    }

    /// The primitive instances' delay cells, which an SDF `CELL` naming a primitive annotates.
    pub(crate) fn with_primitives(mut self, prims: PrimDelays) -> Annotator {
        self.prims = prims;
        self
    }

    /// Keeps each call's log instead of writing it (see [`Self::take_captured_log`]).
    pub(crate) fn capturing_logs(mut self) -> Annotator {
        self.capture_log = true;
        self
    }

    /// The `log_file` and lines of the last call, when logs are captured.
    pub(crate) fn take_captured_log(&mut self) -> Option<(String, Vec<String>)> {
        self.captured_log.take()
    }

    /// Applies the run's invocation options (T31): the default pulse-limit percentages of an
    /// annotated delay written without a pulse form (LRM 32.7) and what `TOOL_CONTROL` selects
    /// (LRM Table 32-5). Without them: 100% / 100% and the typical value.
    pub(crate) fn with_options(mut self, options: &TimingOptions) -> Annotator {
        self.pulse = PulsePercent {
            reject: options.reject_pct(),
            error: options.error_pct(),
        };
        self.tool_control = match options.tool_control() {
            SdfMtm::Minimum => Mtm::Min,
            SdfMtm::Typical => Mtm::Typ,
            SdfMtm::Maximum => Mtm::Max,
        };
        self
    }

    /// Gives the annotator the design's interconnect table ([`crate::interconnect::register`]),
    /// which `PORT`, `NETDELAY` and `INTERCONNECT` annotate. Without one (or while it is empty)
    /// each such construct is reported as having no wire to annotate.
    pub(crate) fn with_interconnect(mut self, table: SharedTable) -> Annotator {
        self.interconnect = Some(table);
        self
    }

    /// Gives the annotator the design's specparams ([`crate::sdf_labels::collect`]), which
    /// `LABEL` sections annotate. Without them every `LABEL` of an SDF file is reported as
    /// naming no specparam.
    pub(crate) fn with_labels(mut self, labels: LabelPlan) -> Annotator {
        self.labels = labels;
        self
    }

    /// Gives the annotator the design's timing checks (`TimingModel::timing_checks`) and their
    /// live limits (`timingcheck::Plans::live`), which `TIMINGCHECK` sections annotate. Without
    /// them every timing check of an SDF file is reported as matching nothing.
    pub(crate) fn with_checks(
        mut self,
        checks: Vec<CheckEntry>,
        live_checks: Arc<LiveChecks>,
    ) -> Annotator {
        self.checks = checks;
        self.live_checks = live_checks;
        self
    }

    /// Runs one `$sdf_annotate` call. `Err` is a call that cannot annotate at all; `Ok` carries
    /// a warning for each construct it could not annotate.
    pub(crate) fn apply(&mut self, call: &SdfAnnotateCall) -> Result<Vec<String>, String> {
        let mtm = Mtm::parse(call.mtm_spec.as_deref(), self.tool_control)?;
        let scale = Scale::parse(call.scale_factors.as_deref(), call.scale_type.as_deref())?;
        let sel = Selector { mtm, scale };
        let mut warnings = Vec::new();
        if let Some(cfg) = &call.config_file {
            std::fs::read_to_string(cfg)
                .map_err(|e| format!("cannot read the config_file \"{cfg}\": {e}"))?;
            warnings.push(format!(
                "the config_file \"{cfg}\" was read, but its directives are not interpreted \
                 (implementation-defined: the LRM does not define the file's format)"
            ));
        }
        let text = std::fs::read_to_string(&call.file)
            .map_err(|e| format!("cannot read the SDF file \"{}\": {e}", call.file))?;
        let mut log = Vec::new();
        self.annotate_text(
            &text,
            &call.file,
            &call.scope,
            &sel,
            &mut warnings,
            &mut log,
        )?;
        if let Some(path) = &call.log_file {
            if self.capture_log {
                self.captured_log = Some((path.clone(), log));
            } else {
                self.write_log(path, &log)?;
            }
        }
        Ok(warnings)
    }

    /// Annotates from SDF `text` (read from `name`) under the instance at `scope_path`.
    fn annotate_text(
        &mut self,
        text: &str,
        name: &str,
        scope_path: &str,
        sel: &Selector,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) -> Result<(), String> {
        let sdf = vj_sdf::parse(text)
            .map_err(|e| format!("{name}:{}:{}: {}", e.line, e.col, e.message))?;
        let scope = self
            .instances
            .iter()
            .position(|i| i.path == scope_path)
            .ok_or_else(|| {
                format!("the scope \"{scope_path}\" is not an instance of the design")
            })?;
        log.push(format!(
            "$sdf_annotate: file \"{name}\", scope \"{scope_path}\""
        ));
        self.annotate_file(&sdf, scope, sel, warnings, log);
        Ok(())
    }

    fn write_log(&mut self, path: &str, lines: &[String]) -> Result<(), String> {
        // The first call of a run to name a log file starts it afresh; later ones append, so
        // one log holds every annotation of the run.
        let first = self.logs.insert(path.to_string());
        let mut f = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .append(!first)
            .truncate(first)
            .open(Path::new(path))
            .map_err(|e| format!("cannot open the log_file \"{path}\": {e}"))?;
        for l in lines {
            writeln!(f, "{l}").map_err(|e| format!("cannot write the log_file \"{path}\": {e}"))?;
        }
        Ok(())
    }

    fn annotate_file(
        &mut self,
        sdf: &SdfFile,
        scope: usize,
        sel: &Selector,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        let ts = sdf.header.timescale.unwrap_or(Timescale::DEFAULT);
        for cell in &sdf.cells {
            let prims = self.resolve_prims(scope, cell);
            let targets = if prims.is_empty() {
                self.resolve(scope, cell, warnings)
            } else {
                // A primitive instance is the cell; only a wildcard can also name modules.
                let mut ignored = Vec::new();
                let modules = self.resolve(scope, cell, &mut ignored);
                if cell.instance.wildcard {
                    modules
                } else {
                    Vec::new()
                }
            };
            for p in &prims {
                self.annotate_prim(p, cell, ts, sel, warnings, log);
            }
            for spec in &cell.specs {
                match spec {
                    TimingSpec::Delay(block) => {
                        for &t in &targets {
                            for def in &block.defs {
                                self.annotate_def(t, def, block.mode, sel, ts, warnings, log);
                            }
                        }
                    }
                    TimingSpec::TimingChecks(checks) => {
                        for &t in &targets {
                            for check in checks {
                                self.annotate_check(t, check, sel, ts, warnings, log);
                            }
                        }
                    }
                    TimingSpec::Labels(block) => {
                        for &t in &targets {
                            self.annotate_labels(t, block, sel, ts, cell.line, warnings, log);
                        }
                    }
                }
            }
        }
    }

    /// The primitive instances `cell` names: `(INSTANCE g1)` with the primitive's name as
    /// `CELLTYPE` (`and`), or a trailing `*` for every primitive of that name at or below the
    /// path. Implementation-defined: LRM 32.4 names only module instances as cells; a gate
    /// netlist that annotates its gates directly is common, so a primitive instance is also a
    /// cell, and its delay is its single `#(rise, fall, turn-off)` triple.
    fn resolve_prims(&self, scope: usize, cell: &Cell) -> Vec<String> {
        let Instance { path, wildcard } = &cell.instance;
        let mut target = self.instances[scope].path.clone();
        for c in path {
            target.push('.');
            target.push_str(c);
        }
        let below = format!("{target}.");
        let mut found: Vec<String> = self
            .prims
            .iter()
            .filter(|(p, (ty, _))| {
                *ty == cell.celltype && (**p == target || (*wildcard && p.starts_with(&below)))
            })
            .map(|(p, _)| p.clone())
            .collect();
        found.sort();
        found
    }

    /// A delay of a primitive instance named as a cell: `IOPATH` and `DEVICE` both set the
    /// primitive's output delays (Table 32-1's `DEVICE` rule, a gate having no per-input
    /// paths; an `IOPATH` therefore applies to every input, and the last one in the file
    /// wins). Pulse limits and the other constructs are reported, not applied.
    fn annotate_prim(
        &mut self,
        path: &str,
        cell: &Cell,
        ts: Timescale,
        sel: &Selector,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        // The enclosing module's precision rounds the delay (LRM 3.14.2.2).
        let precision = self
            .instances
            .iter()
            .filter(|i| path.starts_with(&format!("{}.", i.path)))
            .max_by_key(|i| i.path.len())
            .map_or(0, |i| i.precision_exp);
        let tick_exp = self.tick_exp;
        let magnitude = f64::from(ts.magnitude);
        let convert = move |v: f64| to_ticks(v * magnitude, ts.unit_exp10, precision, tick_exp);
        for spec in &cell.specs {
            let TimingSpec::Delay(block) = spec else {
                warnings.push(format!(
                    "line {}: primitive \"{path}\": only IOPATH and DEVICE delays annotate a \
                     primitive; not annotated",
                    cell.line
                ));
                continue;
            };
            for def in &block.defs {
                let (desc, delays) = match &def.kind {
                    DelayKind::IoPath(io) => (describe_iopath(io), &io.delays),
                    DelayKind::Device { delays, .. } => ("DEVICE".to_string(), delays),
                    _ => {
                        warnings.push(format!(
                            "line {}: primitive \"{path}\": only IOPATH and DEVICE delays \
                             annotate a primitive; not annotated",
                            def.line
                        ));
                        continue;
                    }
                };
                match iopath_update(delays, sel, self.pulse, &convert) {
                    Ok(update) => {
                        let cells = &self.prims[path].1;
                        for c in cells {
                            let mut d = c.lock().unwrap();
                            *d = Delays::from_triple(device_delays(
                                d.triple(),
                                &update.delay,
                                block.mode,
                            ));
                        }
                        log.push(format!(
                            "line {}: {desc} annotated {} output(s) of primitive \"{path}\"",
                            def.line,
                            cells.len()
                        ));
                        if delays.iter().any(|d| d.pulse.is_some()) {
                            warnings.push(format!(
                                "line {}: {desc}: the pulse limits of a primitive's delay are                                  not annotated",
                                def.line
                            ));
                        }
                    }
                    Err(msg) => warnings.push(format!("line {}: {desc}: {msg}", def.line)),
                }
            }
        }
    }

    /// The instances `cell` names (LRM 32.4: relative to the annotation scope). A non-wildcard
    /// `INSTANCE` names one instance, whose module must be the cell's `CELLTYPE`; a trailing
    /// `*` names every instance of that module at or below the path.
    fn resolve(&self, scope: usize, cell: &Cell, warnings: &mut Vec<String>) -> Vec<usize> {
        let Instance { path, wildcard } = &cell.instance;
        let mut target = self.instances[scope].path.clone();
        for c in path {
            target.push('.');
            target.push_str(c);
        }
        let shown = if path.is_empty() && !wildcard {
            "(INSTANCE)".to_string()
        } else {
            format!(
                "INSTANCE {}{}",
                path.join("."),
                if *wildcard { ".*" } else { "" }
            )
        };
        if *wildcard {
            let below = format!("{target}.");
            let found: Vec<usize> = self
                .instances
                .iter()
                .enumerate()
                .filter(|(_, i)| {
                    (i.path == target || i.path.starts_with(&below)) && i.module == cell.celltype
                })
                .map(|(k, _)| k)
                .collect();
            if found.is_empty() {
                warnings.push(format!(
                    "line {}: {shown} names no instance of {} at or below \"{target}\"",
                    cell.line, cell.celltype
                ));
            }
            return found;
        }
        let Some(k) = self.instances.iter().position(|i| i.path == target) else {
            warnings.push(format!(
                "line {}: {shown} names no instance (\"{target}\" is not in the design)",
                cell.line
            ));
            return Vec::new();
        };
        if self.instances[k].module != cell.celltype {
            warnings.push(format!(
                "line {}: CELLTYPE {} does not match the module {} of \"{target}\"; not annotated",
                cell.line, cell.celltype, self.instances[k].module
            ));
            return Vec::new();
        }
        vec![k]
    }

    #[allow(clippy::too_many_arguments)]
    fn annotate_def(
        &mut self,
        inst: usize,
        def: &DelayDef,
        mode: vj_sdf::ast::DeltaMode,
        sel: &Selector,
        ts: Timescale,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        let (inst_path, precision) = {
            let i = &self.instances[inst];
            (i.path.clone(), i.precision_exp)
        };
        let tick_exp = self.tick_exp;
        let magnitude = f64::from(ts.magnitude);
        let convert = move |v: f64| to_ticks(v * magnitude, ts.unit_exp10, precision, tick_exp);
        let line = def.line;
        let warn = |w: &mut Vec<String>, msg: String| w.push(format!("line {line}: {msg}"));
        match &def.kind {
            DelayKind::IoPath(io) => {
                let desc = describe_iopath(io);
                let matched = match self.match_iopath(inst, io) {
                    Ok(m) => m,
                    Err(msg) => {
                        warn(warnings, format!("{desc} in \"{inst_path}\": {msg}"));
                        return;
                    }
                };
                if matched.is_empty() {
                    warn(
                        warnings,
                        format!("{desc}: no matching specify path in \"{inst_path}\""),
                    );
                    return;
                }
                match iopath_update(&io.delays, sel, self.pulse, &convert) {
                    Ok(update) => {
                        self.apply_to(&matched, &update, mode);
                        log.push(format!(
                            "line {line}: {desc} annotated {} specify path(s) of \"{inst_path}\"",
                            matched.len()
                        ));
                    }
                    Err(msg) => warn(warnings, format!("{desc}: {msg}")),
                }
            }
            DelayKind::Device { port, delays } => {
                let desc = match port {
                    Some(p) => format!("DEVICE {}", port_text(p)),
                    None => "DEVICE".to_string(),
                };
                // The module the DEVICE annotates: this cell's own instance, or a child
                // instance its port_instance names (Table 32-1). Its delays round to that
                // module's own precision.
                let (target, target_port) = self.device_target(inst, port.as_ref());
                let (inst_path, target_precision) = {
                    let t = &self.instances[target];
                    (t.path.clone(), t.precision_exp)
                };
                let convert = move |v: f64| {
                    to_ticks(v * magnitude, ts.unit_exp10, target_precision, tick_exp)
                };
                let matched = self.match_device(target, target_port.as_ref());
                let cells = if matched.is_empty() {
                    self.device_cells(target, target_port.as_ref())
                } else {
                    Vec::new()
                };
                if matched.is_empty() && cells.is_empty() {
                    warn(
                        warnings,
                        format!(
                            "{desc}: no specify path to a module output and no primitive \
                             driving one in \"{inst_path}\""
                        ),
                    );
                    return;
                }
                match iopath_update(delays, sel, self.pulse, &convert) {
                    Ok(update) if !matched.is_empty() => {
                        self.apply_to(&matched, &update, mode);
                        log.push(format!(
                            "line {line}: {desc} annotated {} specify path(s) of \"{inst_path}\"",
                            matched.len()
                        ));
                    }
                    Ok(update) => {
                        // No specify path: the primitives driving the output(s) (Table 32-1).
                        for cell in &cells {
                            let mut d = cell.lock().unwrap();
                            *d =
                                Delays::from_triple(device_delays(d.triple(), &update.delay, mode));
                        }
                        log.push(format!(
                            "line {line}: {desc} annotated {} primitive output(s) of \
                             \"{inst_path}\"",
                            cells.len()
                        ));
                        if delays.iter().any(|d| d.pulse.is_some()) {
                            warn(
                                warnings,
                                format!(
                                    "{desc}: the pulse limits of a primitive's delay are not \
                                     annotated (a primitive has no module path pulse limits)"
                                ),
                            );
                        }
                    }
                    Err(msg) => warn(warnings, format!("{desc}: {msg}")),
                }
            }
            DelayKind::PathPulse(pp) => {
                let desc = describe_pathpulse(pp);
                let matched = self.match_pathpulse(inst, pp);
                if matched.is_empty() {
                    warn(
                        warnings,
                        format!("{desc}: no matching specify path in \"{inst_path}\""),
                    );
                    return;
                }
                let mut live = self.live.lock().unwrap();
                for &p in &matched {
                    // PATHPULSEPERCENT is a percentage of this path's delays as they stand
                    // (annotation is ordered, LRM 32.5).
                    let update = pathpulse_update(pp, sel, &convert, &live[p].delays);
                    apply_update(&mut live[p], &update, mode);
                }
                log.push(format!(
                    "line {line}: {desc} annotated {} specify path(s) of \"{inst_path}\"",
                    matched.len()
                ));
            }
            DelayKind::Port { port, delays } => self.annotate_interconnect(
                inst,
                &InterconnectDef {
                    what: "PORT",
                    source: None,
                    load: port,
                    net: false,
                    delays,
                },
                mode,
                sel,
                ts,
                line,
                warnings,
                log,
            ),
            DelayKind::NetDelay { net, delays } => self.annotate_interconnect(
                inst,
                &InterconnectDef {
                    what: "NETDELAY",
                    source: None,
                    load: net,
                    net: true,
                    delays,
                },
                mode,
                sel,
                ts,
                line,
                warnings,
                log,
            ),
            DelayKind::Interconnect {
                source,
                load,
                delays,
            } => self.annotate_interconnect(
                inst,
                &InterconnectDef {
                    what: "INTERCONNECT",
                    source: Some(source),
                    load,
                    net: false,
                    delays,
                },
                mode,
                sel,
                ts,
                line,
                warnings,
                log,
            ),
        }
    }

    /// The signal an SDF port names (the instance path is relative to the cell's `inst`): its
    /// node in the interconnect table and the instance it is in.
    fn interconnect_node(&self, inst: usize, p: &Port) -> Option<(Node, usize)> {
        let (name, rel) = p.path.split_last()?;
        let base = &self.instances[inst].path;
        let path = if rel.is_empty() {
            base.clone()
        } else {
            format!("{base}.{}", rel.join("."))
        };
        let k = self.instances.iter().position(|i| i.path == path)?;
        let slot = *self.instances[k].slots.get(name)?;
        Some(((self.instances[k].id, slot), k))
    }

    /// Annotates one `PORT`, `NETDELAY` or `INTERCONNECT` (LRM 32.4.4, Table 32-3) onto the port
    /// connection wires that reach the load ([`crate::interconnect`]). Everything it cannot do
    /// is a warning naming the construct (32.3).
    #[allow(clippy::too_many_arguments)]
    fn annotate_interconnect(
        &mut self,
        inst: usize,
        def: &InterconnectDef<'_>,
        mode: vj_sdf::ast::DeltaMode,
        sel: &Selector,
        ts: Timescale,
        line: u32,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        let mut desc = def.what.to_string();
        if let Some(s) = def.source {
            desc.push(' ');
            desc.push_str(&slash_text(s));
        }
        desc.push(' ');
        desc.push_str(&slash_text(def.load));
        let warn = |w: &mut Vec<String>, msg: String| w.push(format!("line {line}: {desc}: {msg}"));
        let table = match &self.interconnect {
            Some(t) => Arc::clone(t),
            None => {
                warn(
                    warnings,
                    "the design has no port connection wire to annotate".to_string(),
                );
                return;
            }
        };
        let table = table.lock().unwrap();
        if table.is_empty() {
            warn(
                warnings,
                "the design has no port connection wire to annotate".to_string(),
            );
            return;
        }
        let Some((load, load_inst)) = self.interconnect_node(inst, def.load) else {
            warn(
                warnings,
                format!(
                    "\"{}\" is not a signal of any instance of the design; not annotated",
                    slash_text(def.load)
                ),
            );
            return;
        };
        let bits = def.load.bit.as_ref().map(|b| match *b {
            PortBit::Bit(i) => (i, i),
            PortBit::Range(a, b) => (a, b),
        });
        let graph = table.graph();
        let selection = if def.net && !graph.is_port(load) {
            table.select_net_loads(load, bits)
        } else if graph.is_port(load) {
            table.select_feeders(load, bits)
        } else {
            Vec::new()
        };
        if selection.is_empty() {
            warn(
                warnings,
                format!(
                    "\"{}\" has no port connection wire to delay (a top-level port, an output \
                     port, an inout port, an unpacked-array port, a port connected to an \
                     expression and a name that is not a port are not annotated); not annotated",
                    slash_text(def.load)
                ),
            );
            return;
        }
        if let Some((a, b)) = bits {
            let covered: i64 = selection
                .iter()
                .map(|&(_, first, end)| i64::from(end - first))
                .sum();
            let wanted = (a - b).abs() + 1;
            if covered < wanted {
                warn(
                    warnings,
                    format!(
                        "only {covered} of the {wanted} selected bit(s) of \"{}\" are connected \
                         by a wire; the rest are not annotated",
                        slash_text(def.load)
                    ),
                );
            }
        }
        // LRM 32.4.4: "If the source port is not found or if the source port and the load port
        // are not actually on the same net, then a warning is issued, but the delay to the load
        // port is annotated anyway."
        let mut source_node: Option<(crate::interconnect::Node, Option<(i64, i64)>)> = None;
        if let Some(src) = def.source {
            match self.interconnect_node(inst, src) {
                None => warn(
                    warnings,
                    format!(
                        "source port {} is not found; the delay to the load is annotated anyway",
                        slash_text(src)
                    ),
                ),
                Some((s, _)) => {
                    if !graph.net_of(load, Some(s)).source_on_net {
                        warn(
                            warnings,
                            format!(
                                "source port {} is not on the same net as the load; the delay \
                                 to the load is annotated anyway",
                                slash_text(src)
                            ),
                        );
                    }
                    let src_bits = src.bit.as_ref().map(|b| match *b {
                        PortBit::Bit(i) => (i, i),
                        PortBit::Range(a, b) => (a, b),
                    });
                    source_node = Some((s, src_bits));
                }
            }
        }
        // The delays round to the load's own precision.
        let precision = self.instances[load_inst].precision_exp;
        let (tick_exp, magnitude) = (self.tick_exp, f64::from(ts.magnitude));
        let convert = |v: f64| to_ticks(v * magnitude, ts.unit_exp10, precision, tick_exp);
        match iopath_update(def.delays, sel, self.pulse, &convert) {
            Ok(update) => {
                // LRM 32.4.4: on a multisource net the delay is from the named source only.
                match source_node {
                    Some((s, src_bits)) => {
                        table.annotate_source(&selection, s, src_bits, &update, mode);
                    }
                    None => table.annotate(&selection, &update, mode),
                }
                log.push(format!(
                    "line {line}: {desc} annotated {} wire(s) of \"{}\"",
                    selection.len(),
                    self.instances[load_inst].path
                ));
            }
            Err(msg) => warn(warnings, msg),
        }
    }

    /// Annotates the specparams a `LABEL` group names in `inst` (LRM 32.4.3) and re-evaluates
    /// every module path delay and timing check limit that reads one of them (see
    /// [`crate::sdf_labels`] for the choices). A name that is no specparam of the instance, a
    /// specparam that cannot be annotated, and everything that reads an annotated specparam but
    /// is not re-evaluated are warnings; a value of `()` (or an unselected `min:typ:max` member)
    /// holds the specparam.
    #[allow(clippy::too_many_arguments)]
    fn annotate_labels(
        &mut self,
        inst: usize,
        block: &LabelBlock,
        sel: &Selector,
        ts: Timescale,
        line: u32,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        let (id, inst_path, precision) = {
            let i = &self.instances[inst];
            (i.id, i.path.clone(), i.precision_exp)
        };
        let tick_exp = self.tick_exp;
        let warn = |w: &mut Vec<String>, msg: String| w.push(format!("line {line}: {msg}"));
        let Some(plan) = self.labels.get_mut(id) else {
            warn(
                warnings,
                format!("LABEL: \"{inst_path}\" has no specparam information; not annotated"),
            );
            return;
        };
        // The value is a time in the file's unit; the specparam holds the module's. Scaled by
        // an exact power of ten (a `powi` of a negative exponent is not exact).
        let exp = ts.unit_exp10 - plan.unit_exp;
        let to_module = |v: f64| {
            let p = 10f64.powi(exp.abs());
            let v = v * f64::from(ts.magnitude);
            if exp >= 0 { v * p } else { v / p }
        };
        let mut touched: Vec<String> = Vec::new();
        for (name, rv) in &block.labels {
            let Some(sp) = plan.specparam_mut(name) else {
                warn(
                    warnings,
                    format!("LABEL {name}: \"{inst_path}\" has no specparam `{name}`"),
                );
                continue;
            };
            let Some(v) = sel.value(*rv) else { continue };
            match sp.annotate(block.mode, to_module(v)) {
                Ok(_) => {
                    if !touched.contains(name) {
                        touched.push(name.clone());
                    }
                }
                Err(msg) => warn(warnings, format!("LABEL {name}: {msg}")),
            }
        }
        if touched.is_empty() {
            return;
        }
        // What reads a specparam without being re-evaluated.
        for name in &touched {
            let uid = plan
                .specparams
                .iter()
                .find(|s| s.name == *name)
                .map(|s| s.uid().clone());
            if plan.read_by_planned_delay(name) {
                warn(
                    warnings,
                    format!(
                        "LABEL {name}: a gate, continuous-assignment or net delay reads it, and \
                         those delays are fixed when the design is planned; not re-evaluated"
                    ),
                );
            }
            let in_condition = uid.is_some_and(|u| {
                let in_path = self.paths.iter().any(|p| {
                    p.instance == id
                        && matches!(&p.condition, PathCondition::If(n) if condition_reads(n, &u))
                });
                let in_check = self.checks.iter().filter(|c| c.instance == id).any(|c| {
                    let (reference, data) = check_events(&c.args);
                    let (stamp, check) = check_conditions(&c.args);
                    [
                        reference.condition.as_ref(),
                        data.and_then(|d| d.condition.as_ref()),
                    ]
                    .into_iter()
                    .chain([stamp, check])
                    .flatten()
                    .any(|n| condition_reads(n, &u))
                });
                in_path || in_check
            });
            if in_condition {
                warn(
                    warnings,
                    format!(
                        "LABEL {name}: a path or timing check condition reads it, and those \
                         conditions are fixed when the design is planned; not re-evaluated"
                    ),
                );
            }
            for derived in plan
                .specparams
                .iter()
                .filter(|s| s.derived_from().contains(name))
            {
                warn(
                    warnings,
                    format!(
                        "LABEL {name}: the initializer of specparam `{}` reads it; that \
                         specparam is not re-derived",
                        derived.name
                    ),
                );
            }
        }
        // Re-evaluate what reads the annotated specparams, in one scratch session.
        let paths: Vec<_> = plan
            .paths
            .iter()
            .filter(|p| p.dep.reads_any(&touched))
            .collect();
        let limits: Vec<_> = plan
            .limits
            .iter()
            .filter(|l| l.dep.reads_any(&touched))
            .collect();
        let mut jobs: Vec<&[String]> = Vec::new();
        for dep in paths
            .iter()
            .map(|p| &p.dep)
            .chain(limits.iter().map(|l| &l.dep))
        {
            // A dependency with no text to evaluate is reported below, from its own `Err`.
            match &dep.texts {
                Ok(t) => jobs.push(t),
                Err(_) => jobs.push(&[]),
            }
        }
        let results = if jobs.is_empty() {
            Vec::new()
        } else {
            match plan.evaluate_all(&jobs) {
                Ok(r) => r,
                Err(msg) => {
                    warn(
                        warnings,
                        format!("LABEL: cannot re-evaluate the expressions that read it: {msg}"),
                    );
                    return;
                }
            }
        };
        let unit_exp = plan.unit_exp;
        let (mut n_paths, mut n_limits) = (0, 0);
        let mut results = results.into_iter();
        for p in &paths {
            let result = results.next().expect("one result per job");
            let desc = format!("a path delay reading {}", p.dep.refs.join(", "));
            let delays = match (&p.dep.texts, result) {
                (Err(why), _) => Err(why.clone()),
                (Ok(_), Err(msg)) => Err(msg),
                (Ok(_), Ok(values)) => values
                    .iter()
                    .map(|&v| {
                        if !v.is_finite() {
                            return Err(format!("the delay evaluates to {v}"));
                        }
                        // LRM 30.5.1: a negative path delay is zero.
                        Ok(to_ticks(v.max(0.0), unit_exp, precision, tick_exp) as u64)
                    })
                    .collect::<Result<Vec<u64>, String>>()
                    .and_then(|t| PathDelaySet::from_list(&t)),
            };
            match delays {
                Ok(new) => {
                    let mut live = self.live.lock().unwrap();
                    for &k in &p.indices {
                        let t = &mut live[k];
                        let was_default = (t.reject == t.delays, t.error == t.delays);
                        let new = new.at_least(t.floor);
                        t.delays = new;
                        // LRM 30.7: the limits are the delay unless set; they follow it
                        // while they still are.
                        if was_default.0 {
                            t.reject = new;
                        }
                        if was_default.1 {
                            t.error = new;
                        }
                    }
                    n_paths += p.indices.len();
                }
                Err(msg) => warn(
                    warnings,
                    format!("LABEL: {desc} in \"{inst_path}\" is not re-evaluated: {msg}"),
                ),
            }
        }
        for l in &limits {
            let result = results.next().expect("one result per job");
            let name = SvCheck::of(&self.checks[l.entry].args).name();
            let desc = format!("a {name} limit reading {}", l.dep.refs.join(", "));
            let Some(slot) = l.slot else {
                warn(
                    warnings,
                    format!(
                        "LABEL: {desc} in \"{inst_path}\" is the threshold of a $width, which \
                         annotation does not reach; not re-evaluated"
                    ),
                );
                continue;
            };
            let value = match (&l.dep.texts, result) {
                (Err(why), _) => Err(why.clone()),
                (Ok(_), Err(msg)) => Err(msg),
                (Ok(_), Ok(values)) => match values.as_slice() {
                    [v] if v.is_finite() => Ok(*v),
                    [v] => Err(format!("the limit evaluates to {v}")),
                    _ => Err("a limit is one expression".to_string()),
                },
            };
            match value {
                Ok(v) => {
                    // A limit keeps its sign (31.9): the magnitude is converted, then negated.
                    let ticks = to_ticks(v.abs(), unit_exp, precision, tick_exp);
                    let ticks = if v < 0.0 { -ticks } else { ticks };
                    match self.live_checks.set(l.entry, slot, ticks) {
                        Ok(note) => {
                            if let Some(msg) = limit_note_warning(note, name) {
                                warn(warnings, format!("LABEL: {desc}: {msg}"));
                            }
                            n_limits += 1;
                        }
                        Err(msg) => warn(warnings, format!("LABEL: {desc}: {msg}")),
                    }
                }
                Err(msg) => warn(
                    warnings,
                    format!("LABEL: {desc} in \"{inst_path}\" is not re-evaluated: {msg}"),
                ),
            }
        }
        log.push(format!(
            "line {line}: LABEL annotated specparam(s) {} of \"{inst_path}\"; re-evaluated {n_paths} \
             specify path(s) and {n_limits} timing check limit(s)",
            touched.join(", ")
        ));
    }

    /// Annotates the SystemVerilog timing checks of `inst` that the SDF check `check` names
    /// (LRM 32.4.2): the checks Table 32-2 maps its kind to ([`sdf_checks::fan_out`]) whose
    /// events and conditions the SDF check's own ports and conditions select
    /// ([`Self::check_matches`]). A value of `()` (or an unselected `min:typ:max` member) holds
    /// that limit, and a limit Table 32-2 gives no value (`x`) is never touched.
    ///
    /// The values are in the cell instance's time precision, like a delay's. A timing check has
    /// no ABSOLUTE/INCREMENT choice in SDF: its limits are always replaced.
    fn annotate_check(
        &mut self,
        inst: usize,
        check: &TimingCheck,
        sel: &Selector,
        ts: Timescale,
        warnings: &mut Vec<String>,
        log: &mut Vec<String>,
    ) {
        let (inst_path, precision) = {
            let i = &self.instances[inst];
            (i.path.clone(), i.precision_exp)
        };
        let tick_exp = self.tick_exp;
        let magnitude = f64::from(ts.magnitude);
        let convert = move |v: f64| to_ticks(v * magnitude, ts.unit_exp10, precision, tick_exp);
        let line = check.line;
        let desc = describe_check(check);
        let warn = |w: &mut Vec<String>, msg: String| w.push(format!("line {line}: {msg}"));
        let want_ports = if matches!(check.kind, CheckKind::Width | CheckKind::Period) {
            1
        } else {
            2
        };
        if check.ports.len() != want_ports
            || check.values.len() != sdf_checks::value_count(check.kind)
        {
            warn(
                warnings,
                format!(
                    "{desc}: {} takes {want_ports} port(s) and {} value(s); not annotated",
                    sdf_checks::sdf_name(check.kind),
                    sdf_checks::value_count(check.kind)
                ),
            );
            return;
        }
        let values: Vec<Option<i64>> = check
            .values
            .iter()
            .map(|&rv| sel.value(rv).map(&convert))
            .collect();
        let matched = match self.match_checks(inst, check) {
            Ok(m) => m,
            Err(msg) => {
                warn(warnings, format!("{desc} in \"{inst_path}\": {msg}"));
                return;
            }
        };
        if matched.is_empty() {
            warn(
                warnings,
                format!("{desc}: no matching timing check in \"{inst_path}\""),
            );
            return;
        }
        let mut annotated = Vec::new();
        let fan_out = sdf_checks::fan_out(check.kind);
        for (entry, target) in matched {
            let sv = fan_out[target].check;
            for &(v, slot) in fan_out[target].slots {
                let Some(ticks) = values[v] else { continue };
                match self.live_checks.set(entry, slot, ticks) {
                    Ok(note) => {
                        if let Some(msg) = limit_note_warning(note, sv.name()) {
                            warn(warnings, format!("{desc}: {msg}"));
                        }
                    }
                    Err(msg) => warn(warnings, format!("{desc}: {msg}")),
                }
            }
            annotated.push(sv.name());
        }
        log.push(format!(
            "line {line}: {desc} annotated {} timing check(s) of \"{inst_path}\" ({})",
            annotated.len(),
            annotated.join(", ")
        ));
    }

    /// The `(check entry, index into [`sdf_checks::fan_out`]` pairs the SDF check `check`
    /// annotates in `inst` (LRM 32.4.2): a check of the instance whose kind Table 32-2 lists and
    /// whose events agree with the SDF check's ports.
    fn match_checks(
        &self,
        inst: usize,
        check: &TimingCheck,
    ) -> Result<Vec<(usize, usize)>, String> {
        let me = &self.instances[inst];
        let scope = InstScope {
            inst: me,
            specparams: &self.specparams,
        };
        let (data_port, ref_port) = match check.ports.as_slice() {
            [only] => (None, only),
            [first, second] if sdf_checks::first_port_is_data(check.kind) => (Some(first), second),
            [first, second] => (Some(second), first),
            _ => return Err("a timing check takes one or two ports".to_string()),
        };
        let mut out = Vec::new();
        for (k, entry) in self.checks.iter().enumerate() {
            if entry.instance != me.id {
                continue;
            }
            let sv = SvCheck::of(&entry.args);
            let Some(target) = sdf_checks::fan_out(check.kind)
                .iter()
                .position(|t| t.check == sv)
            else {
                continue;
            };
            let (reference, data) = check_events(&entry.args);
            if !event_matches(me, &scope, ref_port, reference)? {
                continue;
            }
            match (data_port, data) {
                (Some(p), Some(d)) => {
                    if !event_matches(me, &scope, p, d)? {
                        continue;
                    }
                }
                (None, None) => {}
                // A one-port SDF check names only the reference event; a two-port one needs
                // the SystemVerilog check to have a data event. Table 32-2 pairs them.
                (None, Some(_)) | (Some(_), None) => continue,
            }
            let (timestamp, timecheck) = check_conditions(&entry.args);
            let mut conds_ok = true;
            for (sdf, sv) in [(&check.scond, timestamp), (&check.ccond, timecheck)] {
                if let Some(expr) = sdf {
                    conds_ok &= match sv {
                        Some(node) => sdf_cond::equivalent(expr, node, &scope)?,
                        None => false,
                    };
                }
            }
            if conds_ok {
                out.push((k, target));
            }
        }
        Ok(out)
    }

    fn apply_to(&self, paths: &[usize], update: &SlotUpdate, mode: vj_sdf::ast::DeltaMode) {
        let mut live = self.live.lock().unwrap();
        for &p in paths {
            apply_update(&mut live[p], update, mode);
        }
    }

    fn paths_of(&self, inst: usize) -> impl Iterator<Item = (usize, &PathEntry)> {
        let id = self.instances[inst].id;
        self.paths
            .iter()
            .enumerate()
            .filter(move |(_, p)| p.instance == id)
    }

    /// The specify paths of `inst` an `IOPATH` annotates (Table 32-1).
    fn match_iopath(&self, inst: usize, io: &IoPath) -> Result<Vec<usize>, String> {
        let me = &self.instances[inst];
        let scope = InstScope {
            inst: me,
            specparams: &self.specparams,
        };
        let mut out = Vec::new();
        for (k, p) in self.paths_of(inst) {
            if !terminal_matches(me, &p.inputs[0], &io.input.port)
                || !terminal_matches(me, &p.outputs[0], &io.output)
            {
                continue;
            }
            if !edge_matches(io.input.edge, p.edge)? {
                continue;
            }
            let cond_ok = match (&io.cond, &p.condition) {
                // A plain IOPATH annotates conditional (ifnone too) and unconditional paths.
                (IoPathCond::None, _) => true,
                // COND annotates only conditional paths whose condition is the same one.
                (IoPathCond::Cond { expr, .. }, PathCondition::If(node)) => {
                    sdf_cond::equivalent(expr, node, &scope)?
                }
                (IoPathCond::Cond { .. }, _) => false,
                // CONDELSE annotates `ifnone`.
                (IoPathCond::Else, PathCondition::IfNone) => true,
                (IoPathCond::Else, _) => false,
            };
            if cond_ok {
                out.push(k);
            }
        }
        Ok(out)
    }

    /// The instance a `DEVICE` annotates, and the output of it the DEVICE names (Table 32-1):
    /// - no port_instance: the cell's own instance, every output;
    /// - one of the cell instance's own signals (`z`): that output of the instance;
    /// - a child instance of the cell instance (`c`, `g[1].c`, `c[2]`): that module, every
    ///   output;
    /// - an output of a child instance (`c.q`, `c.q[3]`): that module, that output.
    ///
    /// A port_instance naming none of these returns the cell's own instance with the port, so
    /// the match finds nothing and the caller warns. The child's name is relative to the cell
    /// instance (the SDF hierarchy divider is already split into components); a trailing
    /// `[n]` the parser peeled off as a bit index is also tried as part of an instance name
    /// (an element of an instance array).
    fn device_target(&self, inst: usize, port: Option<&Port>) -> (usize, Option<Port>) {
        let Some(p) = port else {
            return (inst, None);
        };
        let me = &self.instances[inst];
        if let [name] = p.path.as_slice()
            && me.signals.contains_key(name)
        {
            return (inst, Some(p.clone()));
        }
        let child = |comps: &[String]| {
            let want = format!("{}.{}", me.path, comps.join("."));
            self.instances.iter().position(|i| i.path == want)
        };
        // The whole path is an instance (the bit, if any, indexes it; a range names none).
        let mut whole = p.path.clone();
        let whole_is_name = match (p.bit, whole.last_mut()) {
            (None, _) => true,
            (Some(PortBit::Bit(n)), Some(last)) => {
                last.push_str(&format!("[{n}]"));
                true
            }
            (Some(PortBit::Bit(_)), None) | (Some(PortBit::Range(..)), _) => false,
        };
        if whole_is_name && let Some(k) = child(&whole) {
            return (k, None);
        }
        // All but the last component is an instance, the last an output of it.
        if let Some((last, parent)) = p.path.split_last()
            && !parent.is_empty()
            && let Some(k) = child(parent)
        {
            let port = Port {
                path: vec![last.clone()],
                bit: p.bit,
            };
            return (k, Some(port));
        }
        (inst, Some(p.clone()))
    }

    /// `DEVICE`: every specify path to a module output (to the named output when a port is
    /// given). When there is none, Table 32-1 falls back to the primitives driving the
    /// outputs: see [`Self::device_cells`].
    fn match_device(&self, inst: usize, port: Option<&Port>) -> Vec<usize> {
        let me = &self.instances[inst];
        self.paths_of(inst)
            .filter(|(_, p)| port.is_none_or(|port| terminal_matches(me, &p.outputs[0], port)))
            .map(|(k, _)| k)
            .collect()
    }

    /// `DEVICE` with no specify path (Table 32-1: "all primitives driving module outputs", or
    /// "driving that module output" when a port is named): the delays of every such primitive
    /// output `run.rs` planned a live delay line for (`primitives::Plans::device`).
    ///
    /// Implementation-defined: a bit index on the named port does not narrow the match (a
    /// primitive output is a one-bit terminal of the port's signal, and every primitive driving
    /// the signal is annotated).
    fn device_cells(&self, inst: usize, port: Option<&Port>) -> Vec<Arc<Mutex<Delays>>> {
        let me = &self.instances[inst];
        let only = match port {
            None => None,
            Some(p) => match p.path.as_slice() {
                [name] => match me.signals.get(name) {
                    Some((uid, _)) => Some(uid),
                    None => return Vec::new(),
                },
                _ => return Vec::new(),
            },
        };
        self.device
            .iter()
            .filter(|((id, uid), _)| *id == me.id && only.is_none_or(|o| o == uid))
            .flat_map(|(_, cells)| cells.iter().cloned())
            .collect()
    }

    fn match_pathpulse(&self, inst: usize, pp: &PathPulse) -> Vec<usize> {
        let me = &self.instances[inst];
        self.paths_of(inst)
            .filter(|(_, p)| {
                pp.input
                    .as_ref()
                    .is_none_or(|i| terminal_matches(me, &p.inputs[0], i))
                    && pp
                        .output
                        .as_ref()
                        .is_none_or(|o| terminal_matches(me, &p.outputs[0], o))
            })
            .map(|(k, _)| k)
            .collect()
    }
}

/// What one `PORT`, `NETDELAY` or `INTERCONNECT` annotates.
struct InterconnectDef<'a> {
    what: &'static str,
    source: Option<&'a Port>,
    load: &'a Port,
    /// `NETDELAY`: the name may be a net, whose load ports are annotated.
    net: bool,
    delays: &'a [vj_sdf::ast::DelVal],
}

/// A port as the SDF file spells it (`i53/u21/in`), for the interconnect warnings.
fn slash_text(p: &Port) -> String {
    let mut s = p.path.join("/");
    match p.bit {
        None => {}
        Some(PortBit::Bit(i)) => s.push_str(&format!("[{i}]")),
        Some(PortBit::Range(a, b)) => s.push_str(&format!("[{a}:{b}]")),
    }
    s
}

fn port_text(p: &Port) -> String {
    let mut s = p.path.join(".");
    match p.bit {
        None => {}
        Some(PortBit::Bit(i)) => s.push_str(&format!("[{i}]")),
        Some(PortBit::Range(a, b)) => s.push_str(&format!("[{a}:{b}]")),
    }
    s
}

fn describe_iopath(io: &IoPath) -> String {
    let kind = match io.cond {
        IoPathCond::None => "IOPATH",
        IoPathCond::Cond { .. } => "COND IOPATH",
        IoPathCond::Else => "CONDELSE IOPATH",
    };
    format!(
        "{kind} {} {}",
        port_text(&io.input.port),
        port_text(&io.output)
    )
}

fn describe_check(check: &TimingCheck) -> String {
    let ports: Vec<String> = check
        .ports
        .iter()
        .map(|p| port_text(&p.spec.port))
        .collect();
    format!("{} {}", sdf_checks::sdf_name(check.kind), ports.join(" "))
}

fn describe_pathpulse(pp: &PathPulse) -> String {
    let kind = if pp.percent {
        "PATHPULSEPERCENT"
    } else {
        "PATHPULSE"
    };
    match (&pp.input, &pp.output) {
        (Some(i), Some(o)) => format!("{kind} {} {}", port_text(i), port_text(o)),
        _ => kind.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::specify::PathTimes;
    use std::sync::{Arc, Mutex};
    use vj_abi::bit4::Bit4;
    use vj_sim::netlist::specify::{
        CheckLimit, CondUnaryOp, EventPairArgs, FullSkewArgs, NoChangeArgs, PathDelaySet,
        PeriodArgs, RecRemArgs, SetupHoldArgs, TimeSkewArgs, WidthArgs,
    };

    fn id(path: &str) -> SymbolId {
        SymbolId::synthetic(path)
    }

    /// An instance at `path` of `module` with one-bit signals `names` and vectors `wide`.
    fn instance(
        n: u32,
        path: &str,
        module: &str,
        names: &[&str],
        wide: &[(&str, u32)],
    ) -> SdfInstance {
        let mut signals = HashMap::new();
        let mut by_id = HashMap::new();
        let all = names.iter().map(|n| (*n, 1)).chain(wide.iter().copied());
        for (name, width) in all {
            let uid = id(&format!("{path}.{name}"));
            signals.insert(name.to_string(), (uid.clone(), width));
            by_id.insert(uid, name.to_string());
        }
        SdfInstance {
            id: InstanceId(n),
            path: path.to_string(),
            module: module.to_string(),
            precision_exp: -12,
            signals,
            slots: HashMap::new(),
            names: by_id,
        }
    }

    fn term(inst: &str, name: &str) -> TerminalRef {
        (id(&format!("{inst}.{name}")), None)
    }

    fn entry(
        n: u32,
        inst: &str,
        from: TerminalRef,
        to: TerminalRef,
        edge: PathEdge,
        condition: PathCondition,
    ) -> PathEntry {
        PathEntry {
            instance: InstanceId(n),
            inputs: vec![from],
            outputs: vec![to],
            connection: sv_lang::TimingPathConnectionKind::Parallel,
            polarity: sv_lang::TimingPathPolarity::Unknown,
            path_uid: id(&format!("{inst}.path")),
            delays: PathDelaySet::uniform(0),
            edge,
            edge_data_source_name: None,
            condition,
            reject_limit: PathDelaySet::uniform(0),
            error_limit: PathDelaySet::uniform(0),
            pulse_style: vj_sim::netlist::specify::PulseStyle::OnEvent,
            showcancelled: false,
        }
    }

    /// `(from => to) = 0;` in `top.d`, no condition and no edge.
    fn plain(from: &str, to: &str) -> PathEntry {
        entry(
            1,
            "top.d",
            term("top.d", from),
            term("top.d", to),
            PathEdge::None,
            PathCondition::Unconditional,
        )
    }

    struct World {
        ann: Annotator,
        live: LiveTimes,
        /// The limits of the design's timing checks ([`world_checks`]).
        checks: Arc<LiveChecks>,
    }

    /// `top` > `d` (module `dut`: sel, mode, zout, a, q, bus[3:0]) and `top.g` > `top.g.d`.
    fn world(paths: Vec<PathEntry>) -> World {
        world_with(paths, HashMap::new())
    }

    /// [`world`] with primitives driving some outputs (`primitives::Plans::device`).
    fn world_with(paths: Vec<PathEntry>, device: DeviceDelays) -> World {
        let names = ["sel", "mode", "zout", "a", "q"];
        let instances = vec![
            instance(0, "top", "top", &[], &[]),
            instance(1, "top.d", "dut", &names, &[("bus", 4)]),
            instance(2, "top.g", "wrap", &[], &[]),
            instance(3, "top.g.d", "dut", &names, &[("bus", 4)]),
        ];
        let times = PathTimes {
            delays: PathDelaySet::uniform(0),
            reject: PathDelaySet::uniform(0),
            error: PathDelaySet::uniform(0),
            floor: 0,
        };
        let live: LiveTimes = Arc::new(Mutex::new(vec![times; paths.len()]));
        let ann = Annotator::new(
            paths,
            instances,
            HashMap::new(),
            Arc::clone(&live),
            device,
            -12,
        );
        World {
            ann,
            live,
            checks: Arc::new(LiveChecks::default()),
        }
    }

    /// [`world`] with no paths and the timing checks `entries` (each of them in `top.d`, so
    /// `InstanceId(1)`), every one moved by `delta` ticks of delayed-signal delay.
    fn world_checks(entries: Vec<CheckEntry>, delta: i64) -> World {
        let mut w = world(Vec::new());
        let live = Arc::new(timingcheck::live_checks_for_entries(&entries, delta, true));
        w.ann = w.ann.with_checks(entries, Arc::clone(&live));
        w.checks = live;
        w
    }

    fn event(name: &str, edge: sv_lang::EdgeKind, cond: Option<CondNode>) -> CheckEvent {
        timingcheck::test_event(term("top.d", name), edge, cond)
    }

    fn lim(arg_index: u32, ticks: i64) -> CheckLimit {
        CheckLimit { arg_index, ticks }
    }

    fn check_entry(kind: sv_lang::SystemTimingCheckKind, args: CheckArgs) -> CheckEntry {
        CheckEntry {
            instance: InstanceId(1),
            check_uid: id("top.d.chk"),
            kind,
            args,
        }
    }

    /// `$setuphold(reference, data, setup, hold)` in `top.d`.
    fn setuphold(reference: CheckEvent, data: CheckEvent, setup: i64, hold: i64) -> CheckEntry {
        check_entry(
            sv_lang::SystemTimingCheckKind::SetupHold,
            CheckArgs::SetupHold(SetupHoldArgs {
                reference,
                data,
                setup_limit: lim(2, setup),
                hold_limit: lim(3, hold),
                notifier: None,
                timestamp_cond: None,
                timecheck_cond: None,
                delayed_reference: None,
                delayed_data: None,
            }),
        )
    }

    fn pair(reference: CheckEvent, data: CheckEvent, limit: i64) -> EventPairArgs {
        EventPairArgs {
            reference,
            data,
            limit: lim(2, limit),
            notifier: None,
        }
    }

    /// A one-cell SDF file whose cell body is `body`, in `d`.
    fn sdf_checks(body: &str) -> String {
        format!(
            "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
             (TIMINGCHECK {body})))"
        )
    }

    impl World {
        /// Annotates from `sdf` under `scope`, returning (warnings, log).
        fn run(&mut self, scope: &str, sdf: &str) -> (Vec<String>, Vec<String>) {
            let sel = Selector {
                mtm: Mtm::Typ,
                scale: Scale::IDENTITY,
            };
            let (mut warnings, mut log) = (Vec::new(), Vec::new());
            self.ann
                .annotate_text(sdf, "t.sdf", scope, &sel, &mut warnings, &mut log)
                .unwrap();
            (warnings, log)
        }

        fn times(&self, i: usize) -> PathTimes {
            self.live.lock().unwrap()[i]
        }

        /// `(rise, fall)` of path `i`, in ticks.
        fn rise_fall(&self, i: usize) -> (u64, u64) {
            let t = self.times(i);
            (
                t.delays.of(Bit4::Zero, Bit4::One),
                t.delays.of(Bit4::One, Bit4::Zero),
            )
        }
    }

    /// A one-cell SDF file for the `dut` instance `d` with `body` as its ABSOLUTE delays.
    fn sdf(body: &str) -> String {
        format!(
            "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
             (DELAY (ABSOLUTE {body}))))"
        )
    }

    fn mode_cond(negated: bool) -> PathCondition {
        let sig = CondNode::Signal(term("top.d", "mode"));
        PathCondition::If(if negated {
            CondNode::Unary(CondUnaryOp::LogicalNot, Box::new(sig))
        } else {
            sig
        })
    }

    fn cond_path(negated: bool) -> PathEntry {
        entry(
            1,
            "top.d",
            term("top.d", "sel"),
            term("top.d", "zout"),
            PathEdge::None,
            mode_cond(negated),
        )
    }

    /// LRM 32.4.1, first example: `(IOPATH sel zout (1.3) (1.7))` against `(sel => zout) = 0;`
    /// annotates the rise/fall times 1.3 and 1.7 (here in picosecond ticks).
    #[test]
    fn lrm_32_4_1_example_1_the_matching_path_gets_the_rise_and_fall_times() {
        let mut w = world(vec![plain("sel", "zout")]);
        let (warnings, _) = w.run("top", &sdf("(IOPATH sel zout (1.3) (1.7))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (1300, 1700));
    }

    /// 32.4.1, second example: `(COND mode (IOPATH sel zout (1.3) (1.7)))` annotates only the
    /// path with the same condition, `if (mode)`, and not `if (!mode)`.
    #[test]
    fn lrm_32_4_1_example_2_a_conditional_iopath_annotates_only_the_same_condition() {
        let mut w = world(vec![cond_path(true), cond_path(false)]);
        let (warnings, _) = w.run("top", &sdf("(COND mode (IOPATH sel zout (1.3) (1.7)))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(
            w.rise_fall(0),
            (0, 0),
            "`if (!mode)` is a different condition"
        );
        assert_eq!(w.rise_fall(1), (1300, 1700), "`if (mode)`");
    }

    /// 32.4.1, third example: a nonconditional IOPATH annotates both conditional paths.
    #[test]
    fn lrm_32_4_1_example_3_a_nonconditional_iopath_annotates_every_path_between_the_ports() {
        let mut w = world(vec![cond_path(true), cond_path(false)]);
        let (warnings, _) = w.run("top", &sdf("(IOPATH sel zout (1.3) (1.7))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (1300, 1700));
        assert_eq!(w.rise_fall(1), (1300, 1700));
    }

    /// Table 32-1: `CONDELSE (IOPATH ...)` annotates `ifnone` and nothing else; a plain `COND`
    /// does not reach the `ifnone` path.
    #[test]
    fn condelse_annotates_only_the_ifnone_path() {
        let ifnone = entry(
            1,
            "top.d",
            term("top.d", "sel"),
            term("top.d", "zout"),
            PathEdge::None,
            PathCondition::IfNone,
        );
        let mut w = world(vec![cond_path(false), ifnone, plain("sel", "zout")]);
        w.run("top", &sdf("(CONDELSE (IOPATH sel zout (4) (5)))"));
        assert_eq!(w.rise_fall(0), (0, 0));
        assert_eq!(w.rise_fall(1), (4000, 5000));
        assert_eq!(
            w.rise_fall(2),
            (0, 0),
            "an unconditional path is not an ifnone path"
        );
        w.run("top", &sdf("(COND mode (IOPATH sel zout (6) (7)))"));
        assert_eq!(w.rise_fall(0), (6000, 7000));
        assert_eq!(w.rise_fall(1), (4000, 5000), "COND never annotates ifnone");
    }

    /// A COND expression that only SPELLS the path's condition differently still matches
    /// (`(COND mode ...)` vs a path conditioned `mode == 1'b1`'s truth table).
    #[test]
    fn a_cond_matches_by_truth_table_not_by_spelling() {
        let mut w = world(vec![cond_path(true)]);
        // `!mode` written as `mode == 1'b0` in the SDF.
        w.run("top", &sdf("(COND mode == 1'b0 (IOPATH sel zout (2) (3)))"));
        assert_eq!(w.rise_fall(0), (2000, 3000));
    }

    fn edge_paths() -> Vec<PathEntry> {
        let mk = |edge| {
            entry(
                1,
                "top.d",
                term("top.d", "a"),
                term("top.d", "q"),
                edge,
                PathCondition::Unconditional,
            )
        };
        vec![
            mk(PathEdge::Specific(sv_lang::EdgeKind::PosEdge)),
            mk(PathEdge::Specific(sv_lang::EdgeKind::NegEdge)),
            mk(PathEdge::None),
            mk(PathEdge::Any),
        ]
    }

    /// An SDF edge selects the path naming that edge; with no edge it selects them all.
    #[test]
    fn an_sdf_edge_selects_the_path_with_that_edge() {
        let mut w = world(edge_paths());
        w.run("top", &sdf("(IOPATH (posedge a) q (1) (1))"));
        assert_eq!(
            (0..4).map(|i| w.rise_fall(i).0).collect::<Vec<_>>(),
            [1000, 0, 0, 0],
            "posedge reaches only the posedge path (not none, any)"
        );
        w.run("top", &sdf("(IOPATH (10 a) q (2) (2))"));
        assert_eq!(
            (0..4).map(|i| w.rise_fall(i).0).collect::<Vec<_>>(),
            [1000, 2000, 0, 0],
            "10 is negedge"
        );
        w.run("top", &sdf("(IOPATH a q (3) (3))"));
        assert_eq!(
            (0..4).map(|i| w.rise_fall(i).0).collect::<Vec<_>>(),
            [3000; 4],
            "no edge in the SDF selects every path"
        );
    }

    /// `0z` and friends have no SystemVerilog edge identifier: nothing is annotated and the
    /// warning says why.
    #[test]
    fn a_z_edge_matches_nothing_and_warns() {
        let mut w = world(edge_paths());
        let (warnings, _) = w.run("top", &sdf("(IOPATH (0z a) q (1) (1))"));
        assert_eq!((0..4).map(|i| w.rise_fall(i).0).sum::<u64>(), 0);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("0z") || warnings[0].contains("T0z"),
            "{warnings:?}"
        );
    }

    /// A construct that names no specify path is a warning naming it, not silence.
    #[test]
    fn an_iopath_with_no_matching_path_warns_with_its_line() {
        let mut w = world(vec![plain("sel", "zout")]);
        let (warnings, _) = w.run("top", &sdf("(IOPATH a q (1) (1))"));
        assert_eq!(w.rise_fall(0), (0, 0));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("IOPATH a q"), "{warnings:?}");
        assert!(warnings[0].starts_with("line 1:"), "{warnings:?}");
    }

    /// A bit-select port matches a whole-signal terminal or the same one-bit window only.
    #[test]
    fn a_port_bit_index_matches_the_whole_signal_or_that_bit() {
        let bit = |lo| -> TerminalRef { (id("top.d.bus"), Some((lo, 1))) };
        let paths = vec![
            entry(
                1,
                "top.d",
                bit(2),
                term("top.d", "q"),
                PathEdge::None,
                PathCondition::Unconditional,
            ),
            entry(
                1,
                "top.d",
                bit(1),
                term("top.d", "q"),
                PathEdge::None,
                PathCondition::Unconditional,
            ),
            entry(
                1,
                "top.d",
                term("top.d", "bus"),
                term("top.d", "q"),
                PathEdge::None,
                PathCondition::Unconditional,
            ),
        ];
        let mut w = world(paths);
        w.run("top", &sdf("(IOPATH bus[2] q (1) (1))"));
        assert_eq!(w.rise_fall(0).0, 1000, "the bit-2 window");
        assert_eq!(w.rise_fall(1).0, 0, "the bit-1 window is another path");
        assert_eq!(
            w.rise_fall(2).0,
            1000,
            "a whole-signal terminal contains bit 2"
        );
        w.run("top", &sdf("(IOPATH bus q (7) (7))"));
        assert_eq!(
            (w.rise_fall(0).0, w.rise_fall(1).0, w.rise_fall(2).0),
            (7000, 7000, 7000),
            "no index matches any terminal of the signal"
        );
    }

    /// 32.4: the CELLTYPE must be the instance's module; a mismatch warns and annotates nothing.
    #[test]
    fn a_celltype_that_is_not_the_instances_module_warns_and_skips() {
        let mut w = world(vec![plain("sel", "zout")]);
        let text = "(DELAYFILE (CELL (CELLTYPE \"other\") (INSTANCE d) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (1) (1))))))";
        let (warnings, _) = w.run("top", text);
        assert_eq!(w.rise_fall(0), (0, 0));
        assert!(
            warnings.iter().any(|m| m.contains("CELLTYPE other")),
            "{warnings:?}"
        );
    }

    /// An INSTANCE path is relative to the annotation scope.
    #[test]
    fn the_instance_path_is_relative_to_the_scope() {
        let inner = entry(
            3,
            "top.g.d",
            term("top.g.d", "sel"),
            term("top.g.d", "zout"),
            PathEdge::None,
            PathCondition::Unconditional,
        );
        let mut w = world(vec![plain("sel", "zout"), inner]);
        let (warnings, _) = w.run("top.g", &sdf("(IOPATH sel zout (1) (2))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (0, 0), "top.d is not under top.g");
        assert_eq!(w.rise_fall(1), (1000, 2000));
    }

    /// A trailing `*` names every instance of the CELLTYPE at or below the path.
    #[test]
    fn a_wildcard_instance_reaches_every_instance_of_the_celltype_below() {
        let inner = entry(
            3,
            "top.g.d",
            term("top.g.d", "sel"),
            term("top.g.d", "zout"),
            PathEdge::None,
            PathCondition::Unconditional,
        );
        let mut w = world(vec![plain("sel", "zout"), inner]);
        let text = "(DELAYFILE (CELL (CELLTYPE \"dut\") (INSTANCE *) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (1) (2))))))";
        let (warnings, _) = w.run("top", text);
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (1000, 2000));
        assert_eq!(w.rise_fall(1), (1000, 2000));
    }

    /// An INSTANCE that is not in the design is a warning, not an abort.
    #[test]
    fn an_unknown_instance_warns() {
        let mut w = world(vec![plain("sel", "zout")]);
        let text = "(DELAYFILE (CELL (CELLTYPE \"dut\") (INSTANCE nope) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (1) (2))))))";
        let (warnings, _) = w.run("top", text);
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("nope"), "{warnings:?}");
    }

    /// A scope that is no instance is an error (the call cannot annotate at all).
    #[test]
    fn an_unknown_scope_is_an_error() {
        let mut w = world(vec![]);
        let sel = Selector {
            mtm: Mtm::Typ,
            scale: Scale::IDENTITY,
        };
        let r = w.ann.annotate_text(
            "(DELAYFILE)",
            "t.sdf",
            "top.zz",
            &sel,
            &mut vec![],
            &mut vec![],
        );
        assert!(r.unwrap_err().contains("top.zz"));
    }

    /// A syntax error is an error naming the file, line and column.
    #[test]
    fn a_syntax_error_names_the_file_line_and_column() {
        let mut w = world(vec![]);
        let sel = Selector {
            mtm: Mtm::Typ,
            scale: Scale::IDENTITY,
        };
        let e = w
            .ann
            .annotate_text(
                "(DELAYFILE\n (CELL",
                "t.sdf",
                "top",
                &sel,
                &mut vec![],
                &mut vec![],
            )
            .unwrap_err();
        assert!(e.starts_with("t.sdf:"), "{e}");
    }

    /// Table 32-1: `DEVICE` is every specify path to a module output; with a port, the paths
    /// ending at that port.
    #[test]
    fn device_annotates_every_path_to_an_output_or_to_the_named_one() {
        let mut w = world(vec![plain("sel", "zout"), plain("a", "q")]);
        w.run("top", &sdf("(DEVICE (3) (4))"));
        assert_eq!(
            (w.rise_fall(0), w.rise_fall(1)),
            ((3000, 4000), (3000, 4000))
        );
        w.run("top", &sdf("(DEVICE q (5) (6))"));
        assert_eq!(w.rise_fall(0), (3000, 4000), "zout is not q");
        assert_eq!(w.rise_fall(1), (5000, 6000));
    }

    fn prim_cell(v: [u64; 3]) -> Arc<Mutex<Delays>> {
        Arc::new(Mutex::new(Delays::from_triple(v)))
    }

    /// Two primitive outputs of `top.d`: one drives `zout` (and a second one too), one `q`.
    fn device_world(paths: Vec<PathEntry>) -> (World, [Arc<Mutex<Delays>>; 3]) {
        let cells = [
            prim_cell([1, 1, 1]),
            prim_cell([2, 2, 2]),
            prim_cell([3, 3, 3]),
        ];
        let mut device = DeviceDelays::new();
        device.insert(
            (InstanceId(1), id("top.d.zout")),
            vec![cells[0].clone(), cells[1].clone()],
        );
        device.insert((InstanceId(1), id("top.d.q")), vec![cells[2].clone()]);
        (world_with(paths, device), cells)
    }

    fn triples(cells: &[Arc<Mutex<Delays>>; 3]) -> [[u64; 3]; 3] {
        [0, 1, 2].map(|i| cells[i].lock().unwrap().triple())
    }

    /// Table 32-1: with no specify path, `DEVICE` is "all primitives driving module outputs",
    /// and `DEVICE port` "all primitives driving that module output". A gate's rise, fall and
    /// turn-off come from the SDF values as Table 28-9 does.
    #[test]
    fn device_with_no_specify_path_annotates_the_primitives_driving_the_outputs() {
        let (mut w, cells) = device_world(vec![]);
        let (warnings, log) = w.run("top", &sdf("(DEVICE (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(
            triples(&cells),
            [[3000, 4000, 3000]; 3],
            "every primitive output, turn-off min(3, 4)"
        );
        assert!(
            log.iter().any(|l| l.contains("3 primitive output(s)")),
            "{log:?}"
        );
        w.run("top", &sdf("(DEVICE q (5) (6) (7))"));
        assert_eq!(triples(&cells)[0], [3000, 4000, 3000], "zout is not q");
        assert_eq!(triples(&cells)[2], [5000, 6000, 7000]);
    }

    /// An INCREMENT adds to the primitive's current delays, in file order.
    #[test]
    fn device_increment_on_primitives_adds_to_what_is_there() {
        let (mut w, cells) = device_world(vec![]);
        let text = "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
                    (DELAY (ABSOLUTE (DEVICE zout (5) (6) (7)))) \
                    (DELAY (INCREMENT (DEVICE zout (1) (1) (1))))))";
        w.run("top", text);
        assert_eq!(triples(&cells)[0], [6000, 7000, 8000]);
        assert_eq!(triples(&cells)[1], [6000, 7000, 8000]);
        assert_eq!(triples(&cells)[2], [3, 3, 3], "q was not named");
    }

    /// The specify paths come first: primitives are only the fallback "if no specify paths".
    #[test]
    fn device_prefers_specify_paths_over_primitives() {
        let (mut w, cells) = device_world(vec![plain("sel", "zout")]);
        let (warnings, _) = w.run("top", &sdf("(DEVICE (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (3000, 4000));
        assert_eq!(triples(&cells), [[1, 1, 1], [2, 2, 2], [3, 3, 3]]);
        // A named output with no path to it still falls back to its own primitives.
        w.run("top", &sdf("(DEVICE q (8) (9))"));
        assert_eq!(triples(&cells)[2], [8000, 9000, 8000]);
    }

    /// No specify path and no primitive driving the output: a warning, nothing annotated.
    #[test]
    fn device_with_nothing_to_annotate_warns() {
        let (mut w, cells) = device_world(vec![]);
        let (warnings, _) = w.run("top", &sdf("(DEVICE a (3) (4))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("no primitive"), "{warnings:?}");
        assert_eq!(triples(&cells), [[1, 1, 1], [2, 2, 2], [3, 3, 3]]);
    }

    /// A pulse form on a primitive's delay has no limit to set: it is reported, not dropped
    /// silently.
    #[test]
    fn device_pulse_limits_on_a_primitive_are_reported() {
        let (mut w, cells) = device_world(vec![]);
        let (warnings, _) = w.run("top", &sdf("(DEVICE q ((3) (1) (2)) (4))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("pulse limits"), "{warnings:?}");
        assert_eq!(triples(&cells)[2], [3000, 4000, 3000]);
    }

    /// A one-cell SDF file for the instance `inst` of module `celltype` (`""` for the scope
    /// itself) with `body` as its ABSOLUTE delays.
    fn sdf_cell(celltype: &str, inst: &str, body: &str) -> String {
        format!(
            "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"{celltype}\") (INSTANCE {inst}) \
             (DELAY (ABSOLUTE {body}))))"
        )
    }

    /// Table 32-1: "If port_instance is a module instance, all specify paths to module
    /// outputs. ... If port_instance is a module instance output, all specify paths to that
    /// module output." The cell is the parent (`top`); `d` and `g.d` are instances below it.
    #[test]
    fn device_naming_a_child_instance_annotates_that_modules_output_paths() {
        let g_d = |from: &str, to: &str| {
            entry(
                3,
                "top.g.d",
                term("top.g.d", from),
                term("top.g.d", to),
                PathEdge::None,
                PathCondition::Unconditional,
            )
        };
        let mut w = world(vec![
            plain("sel", "zout"),
            plain("a", "q"),
            g_d("sel", "zout"),
        ]);
        // A child instance: every path to its outputs, and only that child's.
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE d (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (3000, 4000));
        assert_eq!(w.rise_fall(1), (3000, 4000));
        assert_eq!(w.rise_fall(2), (0, 0), "top.g.d is another instance");
        // A child's output: only the paths ending at it.
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE d.q (5) (6))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (3000, 4000), "zout is not q");
        assert_eq!(w.rise_fall(1), (5000, 6000));
        // A grandchild by its hierarchical path, as an instance and as an output.
        w.run("top", &sdf_cell("top", "", "(DEVICE g.d (7) (8))"));
        assert_eq!(w.rise_fall(2), (7000, 8000));
        w.run("top", &sdf_cell("top", "", "(DEVICE g.d.zout (1) (2))"));
        assert_eq!(w.rise_fall(2), (1000, 2000));
        // The same child, named from the intermediate cell `wrap` (`top.g`).
        w.run("top", &sdf_cell("wrap", "g", "(DEVICE d (9) (9))"));
        assert_eq!(w.rise_fall(2), (9000, 9000));
        assert_eq!(w.rise_fall(0), (3000, 4000), "top.d untouched");
    }

    /// The child's own primitives are the fallback when it has no specify path, for the whole
    /// instance and for one named output (Table 32-1).
    #[test]
    fn device_naming_a_child_instance_falls_back_to_its_primitives() {
        let (mut w, cells) = device_world(vec![]);
        let (warnings, log) = w.run("top", &sdf_cell("top", "", "(DEVICE d.q (5) (6))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(triples(&cells)[2], [5000, 6000, 5000]);
        assert_eq!(triples(&cells)[0], [1, 1, 1], "zout is not q");
        assert!(
            log.iter()
                .any(|l| l.contains("1 primitive output(s)") && l.contains("\"top.d\"")),
            "the log names the annotated child: {log:?}"
        );
        w.run("top", &sdf_cell("top", "", "(DEVICE d (3) (4))"));
        assert_eq!(triples(&cells), [[3000, 4000, 3000]; 3]);
    }

    /// An instance array element is a child named with its index, which the parser reads as a
    /// bit index of the port; the escaped spelling is the same instance. Its output keeps the
    /// bit narrowing of an ordinary port.
    #[test]
    fn device_naming_an_instance_array_element() {
        let mut w = world(vec![]);
        let names = ["sel", "mode", "zout", "a", "q"];
        w.ann
            .instances
            .push(instance(4, "top.arr[1]", "dut", &names, &[("bus", 4)]));
        let arr1 = |from: &str, to: &str| {
            entry(
                4,
                "top.arr[1]",
                term("top.arr[1]", from),
                term("top.arr[1]", to),
                PathEdge::None,
                PathCondition::Unconditional,
            )
        };
        w.ann.paths = vec![arr1("sel", "zout"), arr1("a", "q")];
        w.live.lock().unwrap().resize(
            2,
            PathTimes {
                delays: PathDelaySet::uniform(0),
                reject: PathDelaySet::uniform(0),
                error: PathDelaySet::uniform(0),
                floor: 0,
            },
        );
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE arr[1] (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(
            (w.rise_fall(0), w.rise_fall(1)),
            ((3000, 4000), (3000, 4000))
        );
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE arr\\[1\\].q (5) (6))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (3000, 4000));
        assert_eq!(w.rise_fall(1), (5000, 6000));
    }

    /// A DEVICE port_instance that is no signal and no instance below the cell still warns
    /// (nothing is annotated, nothing is skipped silently).
    #[test]
    fn device_naming_nothing_warns() {
        let mut w = world(vec![plain("sel", "zout")]);
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE nosuch (3) (4))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("DEVICE nosuch"), "{warnings:?}");
        let (warnings, _) = w.run("top", &sdf_cell("top", "", "(DEVICE d.nosuch (3) (4))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("\"top.d\""), "{warnings:?}");
        assert_eq!(w.rise_fall(0), (0, 0));
    }

    /// In-file order (LRM 32.5): a later ABSOLUTE replaces an earlier value; an INCREMENT adds
    /// to whatever is there when it is applied.
    #[test]
    fn annotations_apply_in_file_order() {
        let mut w = world(vec![plain("sel", "zout")]);
        let text = "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (5) (5)))) \
                    (DELAY (INCREMENT (IOPATH sel zout (1) (2)))) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (7) (8))))) \
                    (CELL (CELLTYPE \"dut\") (INSTANCE d) \
                    (DELAY (INCREMENT (IOPATH sel zout (1) (1))))))";
        w.run("top", text);
        assert_eq!(w.rise_fall(0), (8000, 9000), "7+1, 8+1");
    }

    /// A PATHPULSE sets the limits and leaves the delays; one above the delay acts as the delay
    /// (LRM 32.7).
    #[test]
    fn pathpulse_sets_limits_only_and_a_limit_above_the_delay_acts_as_the_delay() {
        let mut w = world(vec![plain("sel", "zout")]);
        w.run("top", &sdf("(IOPATH sel zout (50) (50))"));
        w.run("top", &sdf("(PATHPULSE sel zout (20) (30))"));
        let t = w.times(0);
        assert_eq!(w.rise_fall(0), (50_000, 50_000), "the delay is untouched");
        assert_eq!(t.limits(Bit4::Zero, Bit4::One), (50_000, 20_000, 30_000));
        w.run("top", &sdf("(PATHPULSE sel zout (80) (90))"));
        assert_eq!(
            w.times(0).limits(Bit4::Zero, Bit4::One),
            (50_000, 50_000, 50_000),
            "limits above the delay act as the delay"
        );
    }

    /// PATHPULSEPERCENT is a share of the delay as it stands.
    #[test]
    fn pathpulsepercent_is_a_share_of_the_current_delay() {
        let mut w = world(vec![plain("sel", "zout")]);
        w.run("top", &sdf("(IOPATH sel zout (50) (50))"));
        w.run("top", &sdf("(PATHPULSEPERCENT sel zout (20) (40))"));
        assert_eq!(
            w.times(0).limits(Bit4::Zero, Bit4::One),
            (50_000, 10_000, 20_000)
        );
    }

    /// Sections this build does not annotate are named warnings.
    #[test]
    fn unannotated_sections_are_named_warnings() {
        let mut w = world(vec![plain("sel", "zout")]);
        let text = "(DELAYFILE (CELL (CELLTYPE \"dut\") (INSTANCE d) \
                    (DELAY (ABSOLUTE (INTERCONNECT a sel (1))))))";
        let (warnings, _) = w.run("top", text);
        let joined = warnings.join("\n");
        assert!(joined.contains("INTERCONNECT"), "{joined}");
    }

    // ---- LABEL annotation (T28: LRM 32.4.3) ----

    use crate::sdf_labels::InstLabels;

    /// [`world`] whose `top.d` (module unit 1 ns) has the specparam `cap` (source value
    /// `source`), and the labels `labels` describe what reads it.
    fn label_world(paths: Vec<PathEntry>, labels: InstLabels) -> World {
        let mut plan = LabelPlan::default();
        plan.insert(InstanceId(1), labels);
        let mut w = world(paths);
        w.ann = w.ann.with_labels(plan);
        w
    }

    /// `(LABEL (<mode> <body>))` for `d`, in a file whose time unit is `unit`.
    fn sdf_label(unit: &str, mode: &str, body: &str) -> String {
        format!(
            "(DELAYFILE (TIMESCALE {unit}) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
             (LABEL ({mode} {body}))))"
        )
    }

    /// `specify (A => Z) = 1.4 * cap + 0.7;` of LRM 32.4.3 (the instance's `sel => zout`).
    fn cap_path() -> InstLabels {
        InstLabels::for_test(-9, &[("cap", 0.0)]).with_path(vec![0], &["1.4 * cap + 0.7"], &["cap"])
    }

    /// 32.4.3's second example: annotating `cap` re-evaluates `1.4 * cap + 0.7`, so a `cap` of
    /// 2.5 ns makes the path 4.2 ns (4200 ps ticks); unannotated it is the source's 0.7.
    #[test]
    fn lrm_32_4_3_a_label_reevaluates_the_path_delay_that_reads_the_specparam() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        let (warnings, log) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (2.5))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (4200, 4200));
        assert!(
            log.join("\n").contains("re-evaluated 1 specify path"),
            "{log:?}"
        );
        vj_runtime::specparam::clear();
    }

    /// ABSOLUTE replaces, INCREMENT adds to the value as it stands (32.3).
    #[test]
    fn a_label_increment_adds_to_the_annotated_value() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (2.5))"));
        w.run("top", &sdf_label("1ns", "INCREMENT", "(cap (1))"));
        assert_eq!(w.rise_fall(0), (5600, 5600), "1.4 * 3.5 + 0.7");
        w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(
            w.rise_fall(0),
            (2100, 2100),
            "ABSOLUTE replaces: 1.4 * 1 + 0.7"
        );
        vj_runtime::specparam::clear();
    }

    /// An INCREMENT with no earlier annotation adds to the specparam's source value.
    #[test]
    fn a_first_increment_adds_to_the_source_value() {
        let labels = InstLabels::for_test(-9, &[("cap", 2.0)]).with_path(
            vec![0],
            &["1.4 * cap + 0.7"],
            &["cap"],
        );
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        w.run("top", &sdf_label("1ns", "INCREMENT", "(cap (0.5))"));
        assert_eq!(w.rise_fall(0), (4200, 4200), "cap = 2 + 0.5");
        vj_runtime::specparam::clear();
    }

    /// The value is in the SDF file's unit and the specparam holds the module's (1 ns here):
    /// 2500 ps is a `cap` of 2.5.
    #[test]
    fn a_label_value_is_converted_from_the_sdf_unit_to_the_module_unit() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        w.run("top", &sdf_label("1ps", "ABSOLUTE", "(cap (2500))"));
        assert_eq!(w.rise_fall(0), (4200, 4200));
        assert_eq!(vj_runtime::specparam::get("test.cap"), Some(2.5));
        vj_runtime::specparam::clear();
    }

    /// A value of `()` holds the specparam; a `min:typ:max` takes the selected member.
    #[test]
    fn an_empty_label_value_holds_and_a_triple_takes_the_selected_member() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1:2:3))"));
        assert_eq!(
            w.rise_fall(0),
            (3500, 3500),
            "typ is the default: 1.4 * 2 + 0.7"
        );
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap ())"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (3500, 3500), "held");
        vj_runtime::specparam::clear();
    }

    /// A name that is no specparam of the instance is a named warning; the others still apply.
    #[test]
    fn a_label_naming_no_specparam_warns_and_the_rest_apply() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        let (warnings, _) = w.run(
            "top",
            &sdf_label("1ns", "ABSOLUTE", "(nosuch (1)) (cap (2.5))"),
        );
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("LABEL nosuch"), "{warnings:?}");
        assert_eq!(w.rise_fall(0), (4200, 4200));
        vj_runtime::specparam::clear();
    }

    /// A design planned with no specparams (or one this build could not plan) says so.
    #[test]
    fn a_label_in_an_instance_with_no_plan_warns() {
        let mut w = world(vec![plain("sel", "zout")]);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("no specparam information"),
            "{warnings:?}"
        );
    }

    /// A LABEL replaces an earlier IOPATH annotation of the path it reaches, and a later
    /// IOPATH replaces the LABEL's (annotation is ordered, 32.5).
    #[test]
    fn a_label_and_an_iopath_override_each_other_in_file_order() {
        let mut w = label_world(vec![plain("sel", "zout")], cap_path());
        w.run("top", &sdf("(IOPATH sel zout (9) (9))"));
        assert_eq!(w.rise_fall(0), (9000, 9000));
        w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (2.5))"));
        assert_eq!(w.rise_fall(0), (4200, 4200));
        w.run("top", &sdf("(IOPATH sel zout (7) (7))"));
        assert_eq!(w.rise_fall(0), (7000, 7000));
        vj_runtime::specparam::clear();
    }

    /// 30.5.1: a negative path delay is zero.
    #[test]
    fn a_label_that_makes_a_path_delay_negative_clamps_it_to_zero() {
        let labels =
            InstLabels::for_test(-9, &[("cap", 0.0)]).with_path(vec![0], &["cap - 5"], &["cap"]);
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (2))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.rise_fall(0), (0, 0));
        vj_runtime::specparam::clear();
    }

    /// A rise/fall list: `(A => Z) = (r, f)` re-evaluates both, and the pulse limits that were
    /// the default (the delays) follow the new delays while explicit ones are kept.
    #[test]
    fn a_two_value_delay_list_is_reevaluated_and_default_limits_follow() {
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]).with_path(
            vec![0, 1],
            &["cap", "cap * 2"],
            &["cap"],
        );
        let mut w = label_world(vec![plain("sel", "zout"), plain("sel", "zout")], labels);
        {
            let mut live = w.live.lock().unwrap();
            live[1].reject = PathDelaySet::uniform(77);
        }
        w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (3))"));
        assert_eq!(w.rise_fall(0), (3000, 6000));
        assert_eq!(
            w.times(0).reject.of(Bit4::Zero, Bit4::One),
            3000,
            "followed"
        );
        assert_eq!(
            w.times(1).reject.of(Bit4::Zero, Bit4::One),
            77,
            "explicit, kept"
        );
        vj_runtime::specparam::clear();
    }

    /// A delay expression that cannot be evaluated is a warning that names it, and the delay
    /// it had stays.
    #[test]
    fn a_failing_reevaluation_warns_and_keeps_the_delay() {
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]).with_path(
            vec![0],
            &["cap + undeclared_name"],
            &["cap"],
        );
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        w.run("top", &sdf("(IOPATH sel zout (9) (9))"));
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (2))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("cap + undeclared_name"),
            "{warnings:?}"
        );
        assert_eq!(w.rise_fall(0), (9000, 9000));
        vj_runtime::specparam::clear();
    }

    /// A specparam no expression reads is annotated (the kernels read the table) and nothing
    /// else changes.
    #[test]
    fn a_label_with_no_readers_still_publishes_the_value() {
        let labels = InstLabels::for_test(-9, &[("dhigh", 0.0)]);
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        let (warnings, log) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(dhigh (60))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(vj_runtime::specparam::get("test.dhigh"), Some(60.0));
        assert_eq!(w.rise_fall(0), (0, 0));
        assert!(log.join("\n").contains("dhigh"), "{log:?}");
        vj_runtime::specparam::clear();
    }

    /// A timing check limit that reads the specparam is re-evaluated, keeping its slot:
    /// `$setuphold(.., 111, cap * 2)` with `cap` 1.5 ns has a hold of 3 ns.
    #[test]
    fn a_label_reevaluates_a_timing_check_limit() {
        let entries = vec![setuphold(clk(Ek::PosEdge, None), data(), 111, 222)];
        let mut w = world_checks(entries, 0);
        let labels =
            InstLabels::for_test(-9, &[("cap", 0.0)]).with_limit(0, Some(1), "cap * 2", &["cap"]);
        let mut plan = LabelPlan::default();
        plan.insert(InstanceId(1), labels);
        w.ann = w.ann.with_labels(plan);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1.5))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(sh(&w, 0), (111, 3000), "the setup is untouched");
        vj_runtime::specparam::clear();
    }

    /// A limit that cannot be negative is clamped and warned, as an SDF check's would be.
    #[test]
    fn a_label_that_makes_a_limit_negative_warns_where_it_cannot_be_kept() {
        let setup = check_entry(
            Sk::Setup,
            CheckArgs::Setup(pair(clk(Ek::PosEdge, None), data(), 10)),
        );
        let mut w = world_checks(vec![setup], 0);
        let labels =
            InstLabels::for_test(-9, &[("cap", 0.0)]).with_limit(0, Some(0), "cap - 5", &["cap"]);
        let mut plan = LabelPlan::default();
        plan.insert(InstanceId(1), labels);
        w.ann = w.ann.with_labels(plan);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(w.checks.declared(0, 0), Some(0));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("$setup"), "{warnings:?}");
        vj_runtime::specparam::clear();
    }

    /// The threshold of `$width` is not a limit annotation reaches: named, never silent.
    #[test]
    fn a_label_reaching_a_width_threshold_warns() {
        let width = check_entry(
            Sk::Width,
            CheckArgs::Width(WidthArgs {
                reference: clk(Ek::PosEdge, None),
                limit: lim(1, 1),
                threshold: Some(lim(2, 5)),
                notifier: None,
            }),
        );
        let mut w = world_checks(vec![width], 0);
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]).with_limit(0, None, "cap", &["cap"]);
        let mut plan = LabelPlan::default();
        plan.insert(InstanceId(1), labels);
        w.ann = w.ann.with_labels(plan);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("threshold of a $width"),
            "{warnings:?}"
        );
        vj_runtime::specparam::clear();
    }

    /// A specparam a planned (fixed) delay reads is annotated and the limitation is named.
    #[test]
    fn a_label_a_gate_delay_reads_names_the_limitation() {
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]).reading_in_planned_delay("cap");
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("fixed when the design is planned"),
            "{warnings:?}"
        );
        vj_runtime::specparam::clear();
    }

    /// A specparam a path condition reads is annotated and the limitation is named.
    #[test]
    fn a_label_a_path_condition_reads_names_the_limitation() {
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]);
        let uid = labels.specparam_uid("cap");
        let mut cond = plain("sel", "zout");
        cond.condition = PathCondition::If(CondNode::Specparam(uid));
        let mut w = label_world(vec![cond], labels);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("condition"), "{warnings:?}");
        vj_runtime::specparam::clear();
    }

    /// Another specparam's initializer is not re-derived, and that is named.
    #[test]
    fn a_label_a_specparam_initializer_reads_names_the_limitation() {
        let labels =
            InstLabels::for_test(-9, &[("cap", 0.0), ("twice", 0.0)]).derived("twice", &["cap"]);
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("`twice`"), "{warnings:?}");
        vj_runtime::specparam::clear();
    }

    /// A specparam that cannot be annotated is refused with its reason, and keeps its value.
    #[test]
    fn a_label_naming_a_refused_specparam_warns_with_the_reason() {
        let labels = InstLabels::for_test(-9, &[("cap", 0.0)]).refused("cap", "is a string");
        let mut w = label_world(vec![plain("sel", "zout")], labels);
        let (warnings, _) = w.run("top", &sdf_label("1ns", "ABSOLUTE", "(cap (1))"));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("`cap` is a string"), "{warnings:?}");
        assert_eq!(vj_runtime::specparam::get("test.cap"), None);
    }

    /// `*` / instance-wildcard LABELs reach every matching instance, each with its own table.
    #[test]
    fn a_wildcard_label_annotates_every_matching_instance() {
        let mut plan = LabelPlan::default();
        plan.insert(
            InstanceId(1),
            InstLabels::for_test(-9, &[("cap", 0.0)]).keyed("top.d"),
        );
        plan.insert(
            InstanceId(3),
            InstLabels::for_test(-9, &[("cap", 0.0)]).keyed("top.g.d"),
        );
        let mut w = world(Vec::new());
        w.ann = w.ann.with_labels(plan);
        let text = "(DELAYFILE (TIMESCALE 1ns) (CELL (CELLTYPE \"dut\") (INSTANCE *) \
                    (LABEL (ABSOLUTE (cap (4))))))";
        let (warnings, _) = w.run("top", text);
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(vj_runtime::specparam::get("top.d.cap"), Some(4.0));
        assert_eq!(vj_runtime::specparam::get("top.g.d.cap"), Some(4.0));
        vj_runtime::specparam::clear();
    }

    /// Delays round to the instance's time precision before scaling to ticks (LRM 3.14.2.2):
    /// 1.3 ns in a 1 ns-precision instance is 1 ns, which is 1000 ps ticks.
    #[test]
    fn a_delay_rounds_to_the_instances_precision() {
        let mut w = world(vec![plain("sel", "zout")]);
        w.ann.instances[1].precision_exp = -9;
        w.run("top", &sdf("(IOPATH sel zout (1.3) (1.7))"));
        assert_eq!(w.rise_fall(0), (1000, 2000));
    }

    /// A TIMESCALE in the SDF file sets the unit its values are written in.
    #[test]
    fn the_sdf_timescale_sets_the_unit() {
        let mut w = world(vec![plain("sel", "zout")]);
        let text = "(DELAYFILE (TIMESCALE 10 ps) (CELL (CELLTYPE \"dut\") (INSTANCE d) \
                    (DELAY (ABSOLUTE (IOPATH sel zout (3) (4))))))";
        w.run("top", text);
        assert_eq!(w.rise_fall(0), (30, 40));
    }

    // ---- TIMINGCHECK annotation (T27: Table 32-2, LRM 32.4.2) ----

    use sv_lang::EdgeKind as Ek;
    use sv_lang::SystemTimingCheckKind as Sk;

    /// `data` is `a`, `clk` is `q`, in `top.d`.
    fn clk(edge: Ek, cond: Option<CondNode>) -> CheckEvent {
        event("q", edge, cond)
    }

    fn data() -> CheckEvent {
        event("a", Ek::None, None)
    }

    fn mode_sig() -> CondNode {
        CondNode::Signal(term("top.d", "mode"))
    }

    fn not_mode() -> CondNode {
        CondNode::Unary(CondUnaryOp::LogicalNot, Box::new(mode_sig()))
    }

    /// The three `$setuphold` of LRM 32.4.2's example, all with limits 111 / 222:
    /// `posedge clk &&& mode`, `negedge clk &&& !mode` and `edge clk`.
    fn lrm_32_4_2_checks() -> Vec<CheckEntry> {
        vec![
            setuphold(clk(Ek::PosEdge, Some(mode_sig())), data(), 111, 222),
            setuphold(clk(Ek::NegEdge, Some(not_mode())), data(), 111, 222),
            setuphold(clk(Ek::BothEdges, None), data(), 111, 222),
        ]
    }

    /// The `(setup, hold)` limits of check entry `k`.
    fn sh(w: &World, k: usize) -> (i64, i64) {
        (
            w.checks.declared(k, 0).unwrap(),
            w.checks.declared(k, 1).unwrap(),
        )
    }

    /// LRM 32.4.2, first example: `(SETUPHOLD data clk (3)(4))` names no condition or edge, so
    /// it "annotates all the following $setuphold checks": `posedge clk &&& mode`,
    /// `negedge clk &&& !mode` and `edge clk`.
    #[test]
    fn lrm_32_4_2_example_1_a_check_with_no_edge_or_condition_matches_every_condition() {
        let mut w = world_checks(lrm_32_4_2_checks(), 0);
        let (warnings, _) = w.run("top", &sdf_checks("(SETUPHOLD a q (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        for k in 0..3 {
            assert_eq!(sh(&w, k), (3000, 4000), "check {k}");
        }
    }

    /// 32.4.2, second example: `(SETUPHOLD data (posedge clk) (3)(4))` "annotates only the
    /// first": an SDF `posedge` does not match `edge clk`, nor `negedge clk`.
    #[test]
    fn lrm_32_4_2_example_2_an_sdf_edge_matches_only_that_edge() {
        let mut w = world_checks(lrm_32_4_2_checks(), 0);
        let (warnings, _) = w.run("top", &sdf_checks("(SETUPHOLD a (posedge q) (3) (4))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(sh(&w, 0), (3000, 4000));
        assert_eq!(sh(&w, 1), (111, 222), "negedge clk &&& !mode");
        assert_eq!(sh(&w, 2), (111, 222), "edge clk is not matched by posedge");
    }

    /// 32.4.2, third example: `(SETUPHOLD data (COND !mode (posedge clk)) (3)(4))` "does not
    /// annotate any", since `posedge` and `!mode` are never together in the design.
    #[test]
    fn lrm_32_4_2_example_3_an_sdf_edge_and_condition_must_both_match() {
        let mut w = world_checks(lrm_32_4_2_checks(), 0);
        let (warnings, _) = w.run(
            "top",
            &sdf_checks("(SETUPHOLD a (COND !mode (posedge q)) (3) (4))"),
        );
        for k in 0..3 {
            assert_eq!(sh(&w, k), (111, 222), "check {k}");
        }
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("no matching timing check"),
            "{warnings:?}"
        );
    }

    /// The condition that does match selects its check, and `COND` is compared by meaning
    /// (`mode` against `&&& mode`), not by spelling.
    #[test]
    fn a_matching_check_condition_annotates_that_check_only() {
        let mut w = world_checks(lrm_32_4_2_checks(), 0);
        w.run(
            "top",
            &sdf_checks(
                "(SETUPHOLD a (COND mode (posedge q)) (3) (4)) \
                 (SETUPHOLD a (COND !mode (negedge q)) (5) (6))",
            ),
        );
        assert_eq!(sh(&w, 0), (3000, 4000));
        assert_eq!(sh(&w, 1), (5000, 6000));
        assert_eq!(sh(&w, 2), (111, 222), "edge clk has no condition to match");
    }

    /// An SDF `COND` against an event with no `&&&` condition at all matches nothing.
    #[test]
    fn an_sdf_cond_does_not_match_an_unconditional_event() {
        let mut w = world_checks(vec![setuphold(clk(Ek::PosEdge, None), data(), 111, 222)], 0);
        let (warnings, _) = w.run(
            "top",
            &sdf_checks("(SETUPHOLD a (COND mode (posedge q)) (3) (4))"),
        );
        assert_eq!(sh(&w, 0), (111, 222));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
    }

    /// SCOND / CCOND name the `$setuphold` timestamp / timecheck condition, and an SDF check that
    /// names one matches only a check that has an equal one.
    #[test]
    fn scond_and_ccond_match_the_timestamp_and_timecheck_conditions() {
        let mut with = setuphold(clk(Ek::PosEdge, None), data(), 111, 222);
        let CheckArgs::SetupHold(a) = &mut with.args else {
            unreachable!()
        };
        a.timestamp_cond = Some(mode_sig());
        a.timecheck_cond = Some(not_mode());
        let without = setuphold(clk(Ek::PosEdge, None), data(), 111, 222);
        let mut w = world_checks(vec![with, without], 0);
        let sdf_text = sdf_checks("(SETUPHOLD a (posedge q) (SCOND mode) (CCOND !mode) (3) (4))");
        let (warnings, _) = w.run("top", &sdf_text);
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(sh(&w, 0), (3000, 4000));
        assert_eq!(
            sh(&w, 1),
            (111, 222),
            "no timestamp condition to be equal to"
        );
        // The wrong timecheck condition matches nothing.
        let mut w2 = world_checks(vec![setuphold(clk(Ek::PosEdge, None), data(), 1, 2)], 0);
        let (warnings, _) = w2.run(
            "top",
            &sdf_checks("(SETUPHOLD a (posedge q) (SCOND mode) (3) (4))"),
        );
        assert_eq!(sh(&w2, 0), (1, 2));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
    }

    /// Table 32-2: `SETUP v1` annotates `$setup(v1)` and `$setuphold(v1, x)`: the `$setuphold`
    /// hold limit, which the SDF check names no value for, keeps its value.
    #[test]
    fn table_32_2_setup_leaves_the_setuphold_hold_limit_alone() {
        let setup = check_entry(
            Sk::Setup,
            CheckArgs::Setup(pair(clk(Ek::PosEdge, None), data(), 10)),
        );
        let mut w = world_checks(
            vec![setup, setuphold(clk(Ek::PosEdge, None), data(), 20, 30)],
            0,
        );
        let (warnings, _) = w.run("top", &sdf_checks("(SETUP a (posedge q) (7))"));
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.checks.declared(0, 0), Some(7000));
        assert_eq!(sh(&w, 1), (7000, 30), "x: the hold limit is untouched");
    }

    /// Table 32-2: `HOLD v1` annotates `$hold(v1)` and `$setuphold(x, v1)`.
    #[test]
    fn table_32_2_hold_leaves_the_setuphold_setup_limit_alone() {
        let hold = check_entry(
            Sk::Hold,
            CheckArgs::Hold(pair(clk(Ek::PosEdge, None), data(), 10)),
        );
        let mut w = world_checks(
            vec![hold, setuphold(clk(Ek::PosEdge, None), data(), 20, 30)],
            0,
        );
        w.run("top", &sdf_checks("(HOLD a (posedge q) (7))"));
        assert_eq!(w.checks.declared(0, 0), Some(7000));
        assert_eq!(sh(&w, 1), (20, 7000));
    }

    /// Table 32-2: `SETUPHOLD v1 v2` annotates `$setup(v1)`, `$hold(v2)` and `$setuphold(v1,
    /// v2)`.
    #[test]
    fn table_32_2_setuphold_annotates_setup_hold_and_setuphold() {
        let setup = check_entry(
            Sk::Setup,
            CheckArgs::Setup(pair(clk(Ek::PosEdge, None), data(), 10)),
        );
        let hold = check_entry(
            Sk::Hold,
            CheckArgs::Hold(pair(clk(Ek::PosEdge, None), data(), 11)),
        );
        let mut w = world_checks(
            vec![
                setup,
                hold,
                setuphold(clk(Ek::PosEdge, None), data(), 20, 30),
            ],
            0,
        );
        w.run("top", &sdf_checks("(SETUPHOLD a (posedge q) (7) (8))"));
        assert_eq!(w.checks.declared(0, 0), Some(7000), "$setup(v1)");
        assert_eq!(w.checks.declared(1, 0), Some(8000), "$hold(v2)");
        assert_eq!(sh(&w, 2), (7000, 8000));
    }

    /// A `()` value holds the limit (like a delay's), and a `min:typ:max` value takes the
    /// `mtm_spec` member (`TYPICAL` in the test harness).
    #[test]
    fn an_empty_value_holds_the_limit_and_a_triple_takes_the_typical_member() {
        let mut w = world_checks(vec![setuphold(clk(Ek::PosEdge, None), data(), 20, 30)], 0);
        w.run("top", &sdf_checks("(SETUPHOLD a (posedge q) () (1:2:3))"));
        assert_eq!(sh(&w, 0), (20, 2000));
    }

    /// Table 32-2's recovery / removal rows.
    #[test]
    fn table_32_2_recovery_removal_and_recrem() {
        let rec = check_entry(
            Sk::Recovery,
            CheckArgs::Recovery(pair(clk(Ek::PosEdge, None), data(), 1)),
        );
        let rem = check_entry(
            Sk::Removal,
            CheckArgs::Removal(pair(clk(Ek::PosEdge, None), data(), 2)),
        );
        let recrem = check_entry(
            Sk::RecRem,
            CheckArgs::RecRem(RecRemArgs {
                reference: clk(Ek::PosEdge, None),
                data: data(),
                recovery_limit: lim(2, 3),
                removal_limit: lim(3, 4),
                notifier: None,
                timestamp_cond: None,
                timecheck_cond: None,
                delayed_reference: None,
                delayed_data: None,
            }),
        );
        let mut w = world_checks(vec![rec, rem, recrem], 0);
        let at = |w: &World| {
            (
                w.checks.declared(0, 0).unwrap(),
                w.checks.declared(1, 0).unwrap(),
                sh(w, 2),
            )
        };
        w.run("top", &sdf_checks("(RECOVERY a (posedge q) (5))"));
        assert_eq!(
            at(&w),
            (5000, 2, (5000, 4)),
            "$recovery(v1), $recrem(v1, x)"
        );
        w.run("top", &sdf_checks("(REMOVAL a (posedge q) (6))"));
        assert_eq!(
            at(&w),
            (5000, 6000, (5000, 6000)),
            "$removal(v1), $recrem(x, v1)"
        );
        w.run("top", &sdf_checks("(RECREM a (posedge q) (7) (8))"));
        assert_eq!(at(&w), (7000, 8000, (7000, 8000)));
    }

    /// Table 32-2's skew rows, and the port order: the first SDF port of a `SKEW` or
    /// `BIDIRECTSKEW` is the reference event (implementation-defined, see `sdf_checks`).
    #[test]
    fn table_32_2_skew_timeskew_and_fullskew() {
        let skew = check_entry(
            Sk::Skew,
            CheckArgs::Skew(pair(
                event("q", Ek::PosEdge, None),
                event("a", Ek::PosEdge, None),
                1,
            )),
        );
        let timeskew = check_entry(
            Sk::TimeSkew,
            CheckArgs::TimeSkew(TimeSkewArgs {
                reference: event("q", Ek::PosEdge, None),
                data: event("a", Ek::PosEdge, None),
                limit: lim(2, 2),
                notifier: None,
                event_based: None,
                remain_active: None,
            }),
        );
        let fullskew = check_entry(
            Sk::FullSkew,
            CheckArgs::FullSkew(FullSkewArgs {
                reference: event("q", Ek::PosEdge, None),
                data: event("a", Ek::PosEdge, None),
                reference_first_limit: lim(2, 3),
                data_first_limit: lim(3, 4),
                notifier: None,
                event_based: None,
                remain_active: None,
            }),
        );
        let mut w = world_checks(vec![skew, timeskew, fullskew], 0);
        let at = |w: &World| {
            (
                w.checks.declared(0, 0).unwrap(),
                w.checks.declared(1, 0).unwrap(),
                sh(w, 2),
            )
        };
        // The data event first: names the checks' events the wrong way round.
        let (warnings, _) = w.run("top", &sdf_checks("(SKEW (posedge a) (posedge q) (5))"));
        assert_eq!(at(&w), (1, 2, (3, 4)));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        w.run("top", &sdf_checks("(SKEW (posedge q) (posedge a) (5))"));
        assert_eq!(at(&w), (5000, 5000, (3, 4)), "$skew(v1), $timeskew(v1)");
        w.run(
            "top",
            &sdf_checks("(BIDIRECTSKEW (posedge q) (posedge a) (6) (7))"),
        );
        assert_eq!(at(&w), (5000, 5000, (6000, 7000)), "$fullskew(v1, v2)");
    }

    /// `WIDTH v1` annotates `$width(v1, x)` (the threshold is kept), `PERIOD v1` `$period(v1)`,
    /// `NOCHANGE v1 v2` `$nochange(v1, v2)` with the sign kept.
    #[test]
    fn table_32_2_width_period_and_nochange() {
        let width = check_entry(
            Sk::Width,
            CheckArgs::Width(WidthArgs {
                reference: clk(Ek::PosEdge, None),
                limit: lim(1, 1),
                threshold: Some(lim(2, 5)),
                notifier: None,
            }),
        );
        let period = check_entry(
            Sk::Period,
            CheckArgs::Period(PeriodArgs {
                reference: clk(Ek::PosEdge, None),
                limit: lim(1, 2),
                notifier: None,
            }),
        );
        let nochange = check_entry(
            Sk::NoChange,
            CheckArgs::NoChange(NoChangeArgs {
                reference: clk(Ek::PosEdge, None),
                data: data(),
                start_edge_offset: lim(2, 3),
                end_edge_offset: lim(3, 4),
                notifier: None,
            }),
        );
        let mut w = world_checks(vec![width, period, nochange], 0);
        let (warnings, _) = w.run(
            "top",
            &sdf_checks(
                "(WIDTH (posedge q) (6)) (PERIOD (posedge q) (7)) \
                 (NOCHANGE a (posedge q) (-1) (2))",
            ),
        );
        assert_eq!(warnings, Vec::<String>::new());
        assert_eq!(w.checks.declared(0, 0), Some(6000));
        assert_eq!(w.checks.declared(1, 0), Some(7000));
        assert_eq!(
            (w.checks.declared(2, 0), w.checks.declared(2, 1)),
            (Some(-1000), Some(2000))
        );
    }

    /// A check of another instance is not annotated: the SDF cell names `top.d`.
    #[test]
    fn a_check_of_another_instance_is_not_annotated() {
        let mut other = setuphold(clk(Ek::PosEdge, None), data(), 111, 222);
        other.instance = InstanceId(3);
        let mut w = world_checks(vec![other], 0);
        let (warnings, _) = w.run("top", &sdf_checks("(SETUPHOLD a (posedge q) (3) (4))"));
        assert_eq!(sh(&w, 0), (111, 222));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
    }

    /// A check that takes no negative limit is annotated 0 and warned, and a negative
    /// `$setuphold` limit that the (zero) delayed-signal delay cannot realise is warned too.
    #[test]
    fn a_negative_limit_is_warned_where_it_cannot_be_kept() {
        let setup = check_entry(
            Sk::Setup,
            CheckArgs::Setup(pair(clk(Ek::PosEdge, None), data(), 10)),
        );
        let mut w = world_checks(
            vec![setup, setuphold(clk(Ek::PosEdge, None), data(), 20, 30)],
            0,
        );
        let (warnings, _) = w.run("top", &sdf_checks("(SETUP a (posedge q) (-2))"));
        assert_eq!(
            w.checks.declared(0, 0),
            Some(0),
            "$setup takes no negative limit"
        );
        assert_eq!(warnings.len(), 2, "{warnings:?}");
        assert!(warnings[0].contains("$setup"), "{warnings:?}");
        assert!(warnings[1].contains("$setuphold"), "{warnings:?}");
    }

    /// An edge no SystemVerilog edge identifier can name is a warning, and nothing is annotated.
    #[test]
    fn a_z_edge_check_matches_nothing_and_warns() {
        let mut w = world_checks(vec![setuphold(clk(Ek::PosEdge, None), data(), 111, 222)], 0);
        let (warnings, _) = w.run("top", &sdf_checks("(SETUPHOLD a (0z q) (3) (4))"));
        assert_eq!(sh(&w, 0), (111, 222));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(
            warnings[0].contains("0z") || warnings[0].contains("T0z"),
            "{warnings:?}"
        );
    }

    /// A call's options are validated before any file is read.
    #[test]
    fn a_bad_mtm_spec_is_an_error() {
        let mut w = world(vec![]);
        let call = SdfAnnotateCall {
            file: "/nonexistent.sdf".into(),
            scope: "top".into(),
            config_file: None,
            log_file: None,
            mtm_spec: Some("BOGUS".into()),
            scale_factors: None,
            scale_type: None,
        };
        let e = w.ann.apply(&call).unwrap_err();
        assert!(e.contains("BOGUS"), "{e}");
    }
}