vj 0.2.0

vj: a SystemVerilog (IEEE 1800-2023) simulator built on slang and LLVM.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
//! System timing checks, the `vj` half (LRM 1800-2023 clause 31;
//! `docs/superpowers/plans/2026-10-03-sdf.md` Track B).
//!
//! `vj_sim::netlist::specify::TimingModel::discover` decodes every check's
//! arguments by kind (T13). Two things it cannot do live here, for the same
//! reason `crate::specify` evaluates path delays: they need the timescale
//! (`vj-codegen`, which `vj-sim` cannot depend on), or the live
//! signal state (`crate::primitives::Place`).
//!
//! * [`attach_limits`] evaluates every limit / threshold / offset argument to
//!   signed scheduler ticks and stores it in the entry's
//!   [`CheckLimit::ticks`](vj_sim::netlist::specify::CheckLimit) slot --
//!   the "discover the SHAPE, attach the VALUE" split
//!   `PathEntry::delays` documents.
//! * [`notifier_toggle`] / [`toggle_notifier`] are the notifier behavior of
//!   LRM 31.6 (Table 31-13): a plain write to the notifier variable, with no
//!   new ABI -- the same `Place` write path every other process in this crate
//!   uses.
//! * [`edge_matches`] / [`condition_holds`] are LRM 31.5's edge-control
//!   matching and 31.7's `&&&` enabling rule -- the two shared helpers every
//!   check process calls (nothing else may re-implement them).
//! * [`plan`] / [`register`] turn the stability-window checks (T15: `$setup`,
//!   `$hold`; T16: `$setuphold`; T17: `$removal`, `$recovery`) into one native [`CheckProcess`] each, the way
//!   `crate::specify::register` builds a `PathRetimer`. The window arithmetic
//!   is [`window_violation`] (one function, parameterised by
//!   [`BoundaryKind`]) and the per-check event bookkeeping is [`WindowState`]
//!   (`$setup` / `$hold` / `$removal` / `$recovery`) or [`SetupHoldState`]
//!   (`$setuphold`), pure state machines (no simulator types) so every
//!   boundary can be swept by a unit test. `$recrem` (T18) is the same
//!   [`SetupHoldState`] with its limits taken the other way round: it extends
//!   that machine, it does not copy it. The negative-limit / delayed-signal /
//!   timestamp-timecheck-condition forms of `$setuphold` and `$recrem` (LRM 31.9)
//!   are T23a/T23b: [`negative_timing`] solves the delayed signals' delays
//!   (`crate::negtiming`), [`delay_check`] moves each check onto them, a positive-limit
//!   check with conditions is a [`SplitSetupHold`], and the whole feature is behind
//!   [`TimingOptions::negative_timing_checks`] (31.9.4).
//!   `$width` / `$period` (T19) derive their data event from the reference
//!   event (the opposite edge / the same edge; [`WidthState`], [`PeriodState`]),
//!   and `$nochange` (T19, [`NoChangeState`]) is the one check with THREE events:
//!   its trailing edge is the reference's opposite edge, a third watch of the
//!   same [`CheckProcess`]. `$skew` (T20, [`SkewState`]) is the one check whose
//!   data event is measured against a reference event that a violation does
//!   NOT spend, and the one whose data events are DEFERRED to a `Delay(0)`
//!   wake-up so that the reference event of the same instant is always seen
//!   first ([`Machine::settle`]). `$timeskew` (T21a, [`TimeSkewState`]) is `$skew`
//!   plus an active / dormant state and two flags ([`SkewFlags`]); by default it
//!   is the one check decided by a TIMER, so [`CheckProcess`] asks the scheduler
//!   for a wake-up at its deadline ([`Machine::deadline`] / [`Machine::expire`])
//!   and a reference edge whose `&&&` condition is false is told to it
//!   ([`Machine::reference_suppressed`]). `$fullskew` (T21b) is the same machine
//!   with a second limit: an event of EITHER kind can open a window, so it defers
//!   all of them and applies them instant by instant ([`TimeSkewState::settle_limited`]).
//!
//! # What a violation does
//!
//! 1. It toggles the check's notifier, if it has one (LRM 31.6).
//! 2. It prints ONE line, the format chosen here and used by every check kind:
//!
//!    ```text
//!    <now>: <$check> violation: data <data terminal> vs reference <reference terminal>, limit=<limit>, actual=<actual>
//!    ```
//!
//!    `<now>` and the other times are scheduler ticks -- the design's smallest
//!    time precision, which is what `%0t` prints under the default
//!    `$timeformat` -- in plain decimal. `actual` is the separation that
//!    violated: `t_reference - t_data` for `$setup`, `t_data - t_reference` for
//!    `$hold`. A terminal is the signal's hierarchical name, with a `[bit]` /
//!    `[hi:lo]` suffix for a bit- or part-select terminal.
//!
//!    The line is written from a `Region::Postponed` callback registered for
//!    the current time step (exactly like `$strobe`), through the same shared
//!    output buffer `$display` writes. It is NOT routed through
//!    `SchedulerOps::defer_io`: `run_design`'s engine is built with a
//!    `NullIoSink`, which drops every `defer_io` callback, so a diagnostic sent
//!    that way would never appear. A violation line therefore follows the
//!    ordinary `$display` output of the same time step, in detection order.
//!
//! # Events
//!
//! A check's two events are detected by sampling their terminals each time a
//! terminal's cell changes (the process is statically sensitive to both), so
//! several writes to one terminal inside a single dispatch are one event. The
//! first dispatch, at registration, only records the starting values: the
//! `x -> v` that a time-0 initialiser produces afterwards IS an event (a
//! `negedge` / `edge[x0]` matches it, per LRM 31.5), as it is to any `@(...)`.
//!
//! * An event with an edge control is that edge of the terminal's LSB (LRM
//!   9.4.2, 31.7); one with none is ANY bit of a vector terminal changing
//!   (LRM 31.8: a single event, so a single violation -- per-bit expansion of
//!   a vector terminal is T22's).
//! * Both the reference and the data event are only recognised while their
//!   `&&&` condition holds (LRM 31.7), evaluated when the event is sampled.

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

#[cfg(test)]
use std::collections::HashSet;
use sv_lang::kinds::{ExpressionKind, SymbolKind};
use sv_lang::{EvalSession, Symbol};
#[cfg(test)]
use vj_abi::bit4::Bit4;
use vj_codegen::error::LoweringError;
use vj_codegen::process_lower::SignalSlot;
#[cfg(test)]
use vj_exec::timing::specify::CondEval;
use vj_sim::netlist::InstanceId;
#[cfg(test)]
use vj_sim::netlist::specify::CondBinaryOp;
use vj_sim::netlist::specify::EdgeTransition;
use vj_sim::netlist::specify::{CheckArgs, EdgeControl, EventPairArgs, TerminalRef, TimingModel};
use vj_sim::symid::{SymbolId, SymbolUid};

use crate::negtiming::{
    Constraint, DelayTable, Explicit, Limit, NegativeCheck, Role, Solution, solve,
};
use crate::nets::Resolution;
use crate::primitives::{Loc, bank_slot, loc_of};
use crate::run::RunError;
use crate::specify::{CondPlan, compile_cond_plan};
use crate::timing_options::TimingOptions;
use vj_exec::timing::negtiming::LinePlan;
// The execution half (state machines, live limits, the check process) lives in
// `vj-exec`; everything it exports is visible here under the old names.
use vj_exec::timing::check::CheckPlan as ExecCheck;
pub(crate) use vj_exec::timing::check::*;

/// A timing check event argument's `vpiEdge` (VPI 37.40): `vpiPosedge` /
/// `vpiNegedge`, the edges its edge-descriptor list names (z reads as x,
/// 31.5), any edge for a bare `edge`, or `vpiNoEdge`.
pub(crate) fn vpi_edge(a: &sv_lang::SystemTimingCheckArg<'_>) -> i32 {
    let header = |n: &str| crate::vpi::consts::value_of(n).expect("a header constant") as i32;
    match a.edge {
        sv_lang::EdgeKind::PosEdge => header("vpiPosedge"),
        sv_lang::EdgeKind::NegEdge => header("vpiNegedge"),
        sv_lang::EdgeKind::BothEdges if a.edge_descriptors.is_empty() => header("vpiAnyEdge"),
        sv_lang::EdgeKind::BothEdges => a
            .edge_descriptors
            .iter()
            .map(|d| {
                let d = d.to_ascii_lowercase().replace('z', "x");
                header(match d.as_str() {
                    "01" => "vpiEdge01",
                    "10" => "vpiEdge10",
                    "0x" => "vpiEdge0x",
                    "x1" => "vpiEdgex1",
                    "1x" => "vpiEdge1x",
                    "x0" => "vpiEdgex0",
                    _ => "vpiNoEdge",
                })
            })
            .fold(0, |acc, e| acc | e),
        _ => header("vpiNoEdge"),
    }
}

/// The edge control an SDF edge qualifier names (LRM 31.5, 32.4.2), as a check event spells it:
/// `posedge` and `negedge` are the lists the LRM says they abbreviate, `01` and `10` the single
/// transition. `Err` for an edge no SystemVerilog edge identifier can name (`0z`, `z1`, `1z`,
/// `z0`). Lives here, with [`edge_matches`], because `xtask check-timing-check-helpers` keeps
/// every interpretation of an edge control in this file; `sdf_apply` only compares the result
/// with an event's own control.
pub(crate) fn sdf_edge_control(edge: vj_sdf::ast::Edge) -> Result<EdgeControl, String> {
    use vj_sdf::ast::Edge;
    use vj_sim::netlist::specify::EdgeSet;
    Ok(match edge {
        Edge::Posedge => EdgeControl::Edges(EdgeSet::POSEDGE),
        Edge::Negedge => EdgeControl::Edges(EdgeSet::NEGEDGE),
        Edge::T01 => EdgeControl::Edges(EdgeSet::EMPTY.with(EdgeTransition::ZeroOne)),
        Edge::T10 => EdgeControl::Edges(EdgeSet::EMPTY.with(EdgeTransition::OneZero)),
        Edge::T0z | Edge::Tz1 | Edge::T1z | Edge::Tz0 => {
            return Err(format!(
                "the edge {edge:?} has no SystemVerilog edge identifier (posedge/negedge cover \
                 01 and 10 only)"
            ));
        }
    })
}

/// A check event on `terminal` with the plain `edge` keyword and no descriptor list (tests of
/// `sdf_apply`, which must not name the edge-control fields: they are interpreted only here).
#[cfg(test)]
pub(crate) fn test_event(
    terminal: TerminalRef,
    edge: sv_lang::EdgeKind,
    condition: Option<vj_sim::netlist::specify::CondNode>,
) -> vj_sim::netlist::specify::CheckEvent {
    vj_sim::netlist::specify::CheckEvent {
        terminal,
        edge,
        edge_descriptors: Vec::new(),
        edge_control: EdgeControl::from_syntax(edge, &[]).unwrap(),
        condition,
    }
}

/// Every `SystemTimingCheck` member of every specify block across `infos`,
/// keyed by the symbol's own identity (what `CheckEntry::check_uid` stores).
pub(crate) fn timing_check_symbols<'d>(
    infos: &[(InstanceId, Symbol<'d>)],
) -> HashMap<SymbolId, Symbol<'d>> {
    let mut out = HashMap::new();
    for &(_, body) in infos {
        for m in vj_sim::netlist::module_items(&body) {
            if m.kind() != SymbolKind::SpecifyBlock {
                continue;
            }
            for inner in m.members() {
                if inner.kind() == SymbolKind::SystemTimingCheck {
                    out.insert(inner.uid(), inner);
                }
            }
        }
    }
    out
}

/// One limit / threshold / offset constant as signed scheduler ticks.
///
/// Unlike a path delay (30.5.1 clamps a negative one to zero), a timing check
/// limit may legitimately be negative -- `$setuphold` and `$recrem` define
/// negative limits (LRM 31.9) -- so the sign is preserved: the magnitude goes
/// through the same timescale conversion every delay uses, and the sign is
/// re-applied.
fn limit_to_ticks(c: sv_lang::ConstantValue, scope: &Symbol<'_>, tick: i32) -> Result<i64, String> {
    let v = match c {
        sv_lang::ConstantValue::Real(f) => f,
        c => c
            .as_i64()
            .ok_or_else(|| "a limit that is not a number".to_string())? as f64,
    };
    let ticks = vj_codegen::timescale::delay_ticks(v.abs(), scope, tick).map_err(|e| e.message)?;
    let ticks = i64::try_from(ticks).map_err(|_| "a limit too large for 64 bits".to_string())?;
    Ok(if v < 0.0 { -ticks } else { ticks })
}

/// Evaluates every discovered check's limits to ticks and stores them in
/// `model` (see the module doc). A limit that is not a constant, or not a
/// number, is a named [`RunError::Lowering`] at the check.
pub(crate) fn attach_limits<'d>(
    eval: &EvalSession<'d>,
    model: &mut TimingModel,
    infos: &[(InstanceId, Symbol<'d>)],
    _path: &Path,
) -> Result<(), RunError> {
    let symbols = timing_check_symbols(infos);
    for entry in &mut model.timing_checks {
        let sym = symbols.get(&entry.check_uid).unwrap_or_else(|| {
            panic!(
                "timing check {} was discovered but is not reachable from the same infos",
                entry.check_uid
            )
        });
        let args: Vec<_> = sym.system_timing_check_arguments().collect();
        let tick = vj_codegen::timescale::design_tick_exp(sym);
        for limit in entry.args.limits_mut() {
            let fail = |m: String| {
                RunError::Lowering(LoweringError::unsupported_at(
                    &format!("timing check limit: {m}"),
                    sym,
                ))
            };
            let e = args
                .get(limit.arg_index as usize)
                .and_then(|a| a.expr)
                .ok_or_else(|| fail("a limit argument with no expression".to_string()))?;
            // `min:typ:max` takes the typical value, like every delay.
            let e = if e.kind() == ExpressionKind::MinTypMax {
                e.children()
                    .into_iter()
                    .filter_map(|n| n.as_expression())
                    .nth(1)
                    .ok_or_else(|| fail("a min:typ:max limit with no typical value".to_string()))?
            } else {
                e
            };
            let c = e
                .constant_value()
                .or_else(|| eval.eval_constant(e))
                .ok_or_else(|| fail("a limit that is not a constant".to_string()))?;
            limit.ticks = limit_to_ticks(c, sym, tick).map_err(fail)?;
        }
    }
    Ok(())
}

/// One timing check (`$setup` / `$hold` / `$setuphold` / `$removal` /
/// `$recovery` / `$recrem` / `$width` / `$period` / `$nochange`), planned.
struct CheckPlan {
    /// The index of the [`CheckEntry`](vj_sim::netlist::specify::CheckEntry) this check
    /// came from in `TimingModel::timing_checks` (every bit of a per-bit expansion shares it),
    /// which is also its index in [`LiveChecks`].
    entry: usize,
    spec: CheckSpec,
    reference: WatchPlan,
    data: WatchPlan,
    /// `$nochange`'s third event, the trailing reference edge.
    trailing: Option<WatchPlan>,
    /// The notifier's place and the bit of it to toggle.
    notifier: Option<(Loc, u32)>,
    reference_label: String,
    data_label: String,
    /// The instance the check lives in and the two signals it names, which
    /// [`delay_check`] looks up in the [`DelayTable`] (LRM 31.9.1).
    instance: InstanceId,
    reference_signal: SymbolId,
    data_signal: SymbolId,
    /// A `$setuphold` / `$recrem`'s `timestamp_condition` and `timecheck_condition` that
    /// [`associate_conditions`] has NOT put on one of the two events: the check has no negative
    /// limit, so each of its two windows has its own timestamp and timecheck event (LRM 31.9.2's
    /// `$setup` + `$hold` equivalence) and [`SplitSetupHold`] applies them window by window.
    timestamp: Option<CondPlan>,
    timecheck: Option<CondPlan>,
}

/// Every planned stability-window check of a design ([`plan`]'s output,
/// [`register`]'s input).
#[derive(Default)]
pub(crate) struct Plans {
    checks: Vec<CheckPlan>,
    /// The delayed copies of signals the negative timing checks read (LRM 31.9.1).
    lines: Vec<LinePlan>,
    /// The limits of every check entry at time 0, which `$sdf_annotate` rewrites at run time.
    live: Vec<LiveCheck>,
    /// Whether negative timing checks are enabled (LRM 31.9.4).
    negative_timing: bool,
}

impl Plans {
    /// The executor's view of the checks, for the design image.
    pub(crate) fn spec(&self) -> ChecksPlan {
        ChecksPlan {
            checks: self
                .checks
                .iter()
                .map(|c| ExecCheck {
                    entry: c.entry,
                    spec: c.spec,
                    reference: c.reference.clone(),
                    data: c.data.clone(),
                    trailing: c.trailing.clone(),
                    notifier: c.notifier,
                    reference_label: c.reference_label.clone(),
                    data_label: c.data_label.clone(),
                    timestamp: c.timestamp.clone(),
                    timecheck: c.timecheck.clone(),
                })
                .collect(),
            lines: self.lines.clone(),
            live: self.live.clone(),
            negative_timing: self.negative_timing,
        }
    }
}

/// `terminal` as the violation line names it (see the module doc).
fn terminal_label(terminal: &TerminalRef) -> String {
    match terminal.1 {
        None => terminal.0.to_string(),
        Some((lo, 1)) => format!("{}[{lo}]", terminal.0),
        Some((lo, width)) => format!("{}[{}:{lo}]", terminal.0, lo + width - 1),
    }
}

/// The slot of `terminal` in `own`, and the bit window `(lo, width)` of it
/// the terminal names. A terminal discovery produced always resolves; a miss
/// is an internal inconsistency, reported by name.
fn terminal_window(
    terminal: &TerminalRef,
    id: InstanceId,
    scope: &Scope<'_>,
    what: &str,
) -> Result<(InstanceId, SignalSlot, u32, u32), String> {
    let (owner, slot) = scope.slot_of(id, &terminal.0).ok_or_else(|| {
        format!(
            "{what} `{}` has no resolved signal slot in its own instance (unexpected: discovery \
             already validated this reference's existence)",
            terminal.0
        )
    })?;
    let (lo, width) = terminal.1.unwrap_or((0, slot.width));
    if lo.checked_add(width).is_none_or(|end| end > slot.width) {
        return Err(format!(
            "{what} `{}` selects bits {lo}+:{width} of a {}-bit signal",
            terminal.0, slot.width
        ));
    }
    Ok((owner, slot, lo, width))
}

/// The signal tables a check is planned against: every instance's own slots, plus the
/// signals of the interface ports of each (LRM 25.6), which live in the interface instance
/// (`crate::specify::modport_terminals`).
pub(crate) struct Scope<'a> {
    pub(crate) own: &'a HashMap<InstanceId, HashMap<SymbolId, SignalSlot>>,
    pub(crate) iface: &'a HashMap<InstanceId, HashMap<SymbolId, (InstanceId, SignalSlot)>>,
}

impl Scope<'_> {
    /// `uid`'s owning instance and slot, as seen from `id`.
    fn slot_of(&self, id: InstanceId, uid: &SymbolId) -> Option<(InstanceId, SignalSlot)> {
        self.own
            .get(&id)
            .and_then(|m| m.get(uid))
            .map(|&s| (id, s))
            .or_else(|| self.iface.get(&id).and_then(|m| m.get(uid)).copied())
    }
}

fn plan_event(
    event: &vj_sim::netlist::specify::CheckEvent,
    instance: InstanceId,
    scope: &Scope<'_>,
    own: &HashMap<SymbolId, SignalSlot>,
    model: &TimingModel,
    what: &str,
) -> Result<WatchPlan, String> {
    let (owner, slot, lo, width) = terminal_window(&event.terminal, instance, scope, what)?;
    let conditions = event
        .condition
        .as_ref()
        .map(|c| compile_cond_plan(c, own, instance, model))
        .transpose()
        .map_err(|m| format!("{what}'s condition: {m}"))?
        .into_iter()
        .collect();
    Ok(WatchPlan {
        loc: loc_of(owner, slot),
        lo,
        width,
        control: event.edge_control,
        conditions,
    })
}

/// The timestamp and timecheck conditions of a `$setuphold` / `$recrem` (positions 5 and 6,
/// LRM 31.3.3 / 31.3.6), compiled the way an event's `&&&` condition is. Any other check has
/// none.
fn plan_role_conditions(
    args: &CheckArgs,
    instance: InstanceId,
    own: &HashMap<SymbolId, SignalSlot>,
    model: &TimingModel,
    name: &str,
) -> Result<(Option<CondPlan>, Option<CondPlan>), String> {
    let (timestamp, timecheck) = match args {
        CheckArgs::SetupHold(a) => (&a.timestamp_cond, &a.timecheck_cond),
        CheckArgs::RecRem(a) => (&a.timestamp_cond, &a.timecheck_cond),
        _ => return Ok((None, None)),
    };
    let compile = |c: &Option<_>, which: &str| {
        c.as_ref()
            .map(|c| compile_cond_plan(c, own, instance, model))
            .transpose()
            .map_err(|m| format!("{name}'s {which}: {m}"))
    };
    Ok((
        compile(timestamp, "timestamp_condition")?,
        compile(timecheck, "timecheck_condition")?,
    ))
}

/// The first stage of LRM 31.9.1's negative timing checks, run before any path is planned:
/// finds every signal a `$setuphold` / `$recrem` names (and every `delayed_reference` /
/// `delayed_data` net it declares), solves the delay of each ([`solve`]) and raises the
/// module paths that start at a delayed signal to at least that delay ("the output shall
/// behave as if its specify path delay were equal to the delay applied to the timing check
/// signal"). Returns the [`DelayTable`] that [`plan`] and [`register`] work from; its
/// `warnings` are the inconsistent limits the solve had to zero.
pub(crate) fn negative_timing(
    model: &mut TimingModel,
    scope: &Scope<'_>,
    options: &TimingOptions,
) -> Result<DelayTable, String> {
    let mut table = DelayTable::new(options.negative_timing_checks);
    let mut constraints: Vec<Constraint> = Vec::new();
    // Per constraint: the entry index, its name for a warning, and the names of its two limits.
    let mut named: Vec<(usize, String, [&'static str; 2])> = Vec::new();
    for (index, entry) in model.timing_checks.iter().enumerate() {
        let (reference, data, first, second, delayed, limit_names, check) = match &entry.args {
            CheckArgs::SetupHold(a) => (
                &a.reference,
                &a.data,
                a.setup_limit.ticks,
                a.hold_limit.ticks,
                [&a.delayed_reference, &a.delayed_data],
                ["setup", "hold"],
                "$setuphold",
            ),
            // The data-first limit of `$recrem` is its REMOVAL limit.
            CheckArgs::RecRem(a) => (
                &a.reference,
                &a.data,
                a.removal_limit.ticks,
                a.recovery_limit.ticks,
                [&a.delayed_reference, &a.delayed_data],
                ["removal", "recovery"],
                "$recrem",
            ),
            _ => continue,
        };
        let name = format!("{check} {}", entry.check_uid);
        if !scope.own.contains_key(&entry.instance) {
            return Err(format!("{name} is in an instance with no signal table"));
        }
        let (r_owner, r_slot, r_lo, r_width) = terminal_window(
            &reference.terminal,
            entry.instance,
            scope,
            &format!("{name}'s reference terminal"),
        )?;
        let (d_owner, d_slot, d_lo, d_width) = terminal_window(
            &data.terminal,
            entry.instance,
            scope,
            &format!("{name}'s data terminal"),
        )?;
        let r_node = table.node(entry.instance, r_owner, &reference.terminal.0, r_slot);
        let d_node = table.node(entry.instance, d_owner, &data.terminal.0, d_slot);
        for (net, node, source_lo, source_width, what) in [
            (delayed[0], r_node, r_lo, r_width, "delayed_reference"),
            (delayed[1], d_node, d_lo, d_width, "delayed_data"),
        ] {
            let Some(net) = net else { continue };
            let (owner, slot, lo, width) =
                terminal_window(net, entry.instance, scope, &format!("{name}'s {what}"))?;
            table.add_explicit(
                node,
                Explicit {
                    loc: loc_of(owner, slot),
                    dst_lo: lo,
                    source_lo,
                    width: width.min(source_width),
                },
            );
        }
        constraints.push(Constraint {
            reference: r_node,
            data: d_node,
            data_first: first,
            data_second: second,
        });
        named.push((index, name, limit_names));
    }
    // LRM 31.9.4: without the option every delayed signal is a copy of its original (delay 0)
    // and the negative limits are those of a positive-limit check at 0 -- the solve is the
    // same, fed nothing to solve.
    let solution = if table.enabled {
        solve(table.signals.len(), &constraints)
    } else {
        Solution {
            delays: vec![0; table.signals.len()],
            effective: constraints
                .iter()
                .map(|c| (c.data_first.max(0), c.data_second.max(0)))
                .collect(),
            zeroed: Vec::new(),
        }
    };
    for (signal, delay) in table.signals.iter_mut().zip(&solution.delays) {
        signal.delay = *delay;
    }
    for z in &solution.zeroed {
        let (_, name, limits) = &named[z.check];
        let which = match z.limit {
            Limit::DataFirst => limits[0],
            Limit::DataSecond => limits[1],
        };
        table.warnings.push(format!(
            "warning: {name}: the negative {which} limit {} cannot be met together with the \
             other negative timing checks; it is set to 0 (LRM 31.9.1)",
            z.was
        ));
    }
    for (i, c) in constraints.iter().enumerate() {
        table.checks.push(NegativeCheck {
            entry: named[i].0,
            check: model.timing_checks[named[i].0].check_uid.clone(),
            reference: c.reference,
            data: c.data,
            declared: (c.data_first, c.data_second),
            effective: solution.effective[i],
        });
    }
    for path in &mut model.paths {
        let delay = path
            .inputs
            .first()
            .map_or(0, |input| table.delay_of(path.instance, &input.0));
        if delay > 0 {
            path.delays = path.delays.at_least(delay.unsigned_abs());
        }
    }
    Ok(table)
}

/// Whether `spec` reads the delayed copies of its signals (LRM 31.9.1: all but the skew
/// checks, "because it can possibly result in the reversal of the order of signal
/// transitions").
fn uses_delayed_signals(spec: CheckSpec) -> bool {
    !matches!(
        spec,
        CheckSpec::Skew { .. } | CheckSpec::TimeSkew { .. } | CheckSpec::FullSkew { .. }
    )
}

/// The delayed copy of bits `lo..lo + width` of `signal`, allocating the implicit whole-signal
/// copy in the bank when the signal has a delay but no declared net covers those bits. `None`
/// for an undelayed signal: its checks read the original.
fn shadow_of(
    table: &mut DelayTable,
    res: &mut Resolution,
    bank: InstanceId,
    instance: InstanceId,
    signal: &SymbolId,
    lo: u32,
    width: u32,
) -> Option<(Loc, u32)> {
    let node = table.find(instance, signal)?;
    if table.signals[node].delay == 0 {
        return None;
    }
    if table.shadow_of(instance, signal, lo, width).is_none() {
        let signal_width = table.signals[node].slot.width;
        let slot = u32::try_from(res.bank_widths.len()).expect("bank cell count fits u32");
        res.bank_widths.push(signal_width);
        table.signals[node].implicit = Some(loc_of(bank, bank_slot(slot, signal_width)));
    }
    table.shadow_of(instance, signal, lo, width)
}

/// Gives a negative `$setuphold` / `$recrem`'s `timestamp_condition` and `timecheck_condition`
/// to the events they belong to (LRM 31.9.2): "timestamp_condition is associated with the
/// delayed signal that transitions first, while timecheck_condition is associated with the
/// delayed signal that transitions second". A negative setup (data-first) limit puts the data
/// window after the reference edge, so the reference transitions first and the data signal
/// carries the timecheck condition (the LRM's `TE_cond_D` on `D`); a negative hold limit
/// mirrors it (`TE_cond_TI` on `CP`). The condition then simply qualifies that event, as an
/// `&&&` condition does (31.7), and the check no longer needs [`CheckPlan::timestamp`] /
/// [`CheckPlan::timecheck`]. A check with no negative limit keeps them for [`SplitSetupHold`].
fn associate_conditions(check: &mut CheckPlan, table: &DelayTable, uid: &SymbolId) {
    let Some(first) = table.first_of(uid) else {
        return;
    };
    let timestamp = check.timestamp.take();
    let timecheck = check.timecheck.take();
    let (first_watch, second_watch) = match first {
        Role::Reference => (&mut check.reference, &mut check.data),
        Role::Data => (&mut check.data, &mut check.reference),
    };
    first_watch.conditions.extend(timestamp);
    second_watch.conditions.extend(timecheck);
}

/// How much later `check`'s data signal is than its reference signal (LRM 31.9.1); 0 for a check
/// that reads no delayed signals ([`uses_delayed_signals`]).
fn check_delta(table: &DelayTable, check: &CheckPlan) -> i64 {
    if !uses_delayed_signals(check.spec) {
        return 0;
    }
    table.delay_of(check.instance, &check.data_signal)
        - table.delay_of(check.instance, &check.reference_signal)
}

/// Moves `check` onto the delayed signals of `table` and into their time (LRM 31.9.1),
/// returning the warning text if a limit had to be clamped. A check that does not read
/// delayed signals ([`uses_delayed_signals`]) is left as written.
fn delay_check(
    check: &mut CheckPlan,
    table: &mut DelayTable,
    res: &mut Resolution,
    bank: InstanceId,
) -> Option<String> {
    if !uses_delayed_signals(check.spec) {
        return None;
    }
    let delta = check_delta(table, check);
    let (spec, clamped) = effective_spec(check.spec, delta);
    let name = check.spec.name();
    let warning = clamped.then(|| {
        format!(
            "warning: {name} of {} and {}: a limit adjusted by the {delta} tick delay between \
             them became <= 0 and is set to 0 (LRM 31.9.1)",
            check.reference_label, check.data_label
        )
    });
    check.spec = spec;
    let instance = check.instance;
    for (watch, signal) in [
        (&mut check.reference, &check.reference_signal),
        (&mut check.data, &check.data_signal),
    ]
    .into_iter()
    .chain(
        check
            .trailing
            .as_mut()
            .map(|t| (t, &check.reference_signal)),
    ) {
        if let Some((loc, lo)) =
            shadow_of(table, res, bank, instance, signal, watch.lo, watch.width)
        {
            watch.loc = loc;
            watch.lo = lo;
        }
    }
    warning
}

/// Plans every `$setup` / `$hold` / `$setuphold` / `$removal` / `$recovery` /
/// `$recrem` / `$width` / `$period` / `$nochange` / `$skew` of `model` against
/// `instance_signals` (the per-instance signal-slot table `crate::specify::plan`
/// also reads). The other check kinds are matched out EXPLICITLY below, not by
/// a wildcard: each is a later task's (T21a-T23), and adding a [`CheckArgs`] variant must fail
/// this match until its enforcement is decided.
pub(crate) fn plan(
    model: &TimingModel,
    scope: &Scope<'_>,
    options: &TimingOptions,
    table: &mut DelayTable,
    res: &mut Resolution,
    bank: InstanceId,
) -> Result<Plans, String> {
    let mut plans = Plans::default();
    let mut live_entries: Vec<LiveCheck> = Vec::new();
    for (index, entry) in model.timing_checks.iter().enumerate() {
        let uid = &entry.check_uid;
        // The data event is an owned `CheckEvent` because `$width` and
        // `$period` derive theirs from the reference event (LRM 31.4.4,
        // 31.4.5); `trailing` is `$nochange`'s third event.
        let (spec, reference, data, trailing, notifier): (CheckSpec, &_, _, Option<_>, _) =
            match &entry.args {
                CheckArgs::Setup(a) => (
                    window_spec(StabilityKind::Setup, a, uid, "31.3.1")?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::Hold(a) => (
                    window_spec(StabilityKind::Hold, a, uid, "31.3.2")?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::SetupHold(a) => (
                    setuphold_spec(a),
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                // `$removal` / `$recovery` take their arguments in the `$hold`
                // order (reference first); discovery has already put each in
                // its own field.
                CheckArgs::Recovery(a) => (
                    window_spec(StabilityKind::Recovery, a, uid, "31.3.5")?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::Removal(a) => (
                    window_spec(StabilityKind::Removal, a, uid, "31.3.4")?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::RecRem(a) => (
                    recrem_spec(a),
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                // "data event = reference event signal with opposite edge".
                CheckArgs::Width(a) => (
                    width_spec(a, uid)?,
                    &a.reference,
                    opposite_event(&a.reference, "$width", uid)?,
                    None,
                    &a.notifier,
                ),
                // "data event = reference event signal with the same edge".
                CheckArgs::Period(a) => (
                    period_spec(a, uid)?,
                    &a.reference,
                    a.reference.clone(),
                    None,
                    &a.notifier,
                ),
                // The reference opens the window; its opposite edge closes it.
                CheckArgs::NoChange(a) => (
                    CheckSpec::NoChange {
                        start: a.start_edge_offset.ticks,
                        end: a.end_edge_offset.ticks,
                    },
                    &a.reference,
                    a.data.clone(),
                    Some(opposite_event(&a.reference, "$nochange", uid)?),
                    &a.notifier,
                ),
                CheckArgs::Skew(a) => (
                    skew_spec(a, uid)?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::TimeSkew(a) => (
                    timeskew_spec(a, uid)?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
                CheckArgs::FullSkew(a) => (
                    fullskew_spec(a, uid)?,
                    &a.reference,
                    a.data.clone(),
                    None,
                    &a.notifier,
                ),
            };
        // A negative check runs on the limits the delay solve settled on (an inconsistent
        // negative limit having been zeroed, LRM 31.9.1).
        let spec = match (spec, table.checks.iter().find(|c| c.entry == index)) {
            (CheckSpec::SetupHold { .. }, Some(c)) => CheckSpec::SetupHold {
                setup: c.effective.0,
                hold: c.effective.1,
            },
            (CheckSpec::RecRem { .. }, Some(c)) => CheckSpec::RecRem {
                recovery: c.effective.1,
                removal: c.effective.0,
            },
            (spec, _) => spec,
        };
        let own = scope.own.get(&entry.instance).ok_or_else(|| {
            format!(
                "{} {} is in an instance with no signal table",
                spec.name(),
                entry.check_uid
            )
        })?;
        let name = format!("{} {}", spec.name(), entry.check_uid);
        let notifier = notifier
            .as_ref()
            .map(|n| {
                terminal_window(n, entry.instance, scope, &format!("{name}'s notifier"))
                    .map(|(owner, slot, lo, _)| (loc_of(owner, slot), lo))
            })
            .transpose()?;
        let (timestamp, timecheck) =
            plan_role_conditions(&entry.args, entry.instance, own, model, &name)?;
        live_entries.push(LiveCheck {
            declared: spec,
            delta: 0,
        });
        let check = CheckPlan {
            entry: index,
            spec,
            reference: plan_event(
                reference,
                entry.instance,
                scope,
                own,
                model,
                &format!("{name}'s reference terminal"),
            )?,
            data: plan_event(
                &data,
                entry.instance,
                scope,
                own,
                model,
                &format!("{name}'s data terminal"),
            )?,
            trailing: trailing
                .as_ref()
                .map(|t| {
                    plan_event(
                        t,
                        entry.instance,
                        scope,
                        own,
                        model,
                        &format!("{name}'s trailing reference edge"),
                    )
                })
                .transpose()?,
            notifier,
            reference_label: terminal_label(&reference.terminal),
            data_label: terminal_label(&data.terminal),
            instance: entry.instance,
            reference_signal: reference.terminal.0.clone(),
            data_signal: data.terminal.0.clone(),
            timestamp,
            timecheck,
        };
        // Expand a vector into its bits first: each bit then finds its own delayed copy.
        let mut checks = if options.per_bit_vectors {
            expand_per_bit(
                check,
                &reference.terminal.0.to_string(),
                &data.terminal.0.to_string(),
            )
        } else {
            vec![check]
        };
        // Every bit of one entry shares its delay: the entry's live limits move by it.
        live_entries[index].delta = checks.first().map_or(0, |c| check_delta(table, c));
        for check in &mut checks {
            associate_conditions(check, table, uid);
            if let Some(warning) = delay_check(check, table, res, bank) {
                // Every bit of one check clamps alike: say it once.
                if !table.warnings.contains(&warning) {
                    table.warnings.push(warning);
                }
            }
        }
        plans.checks.extend(checks);
    }
    // One line per signal that has a delayed copy to drive: every declared net (a zero delay
    // still copies, so the model sees the net follow the signal) and the implicit copy.
    for signal in &table.signals {
        let mut outputs = signal.explicit.clone();
        if let Some(loc) = signal.implicit {
            outputs.push(Explicit {
                loc,
                dst_lo: 0,
                source_lo: 0,
                width: signal.slot.width,
            });
        }
        if outputs.is_empty() {
            continue;
        }
        plans.lines.push(LinePlan {
            source: loc_of(signal.instance, signal.slot),
            delay: signal.delay.unsigned_abs(),
            outputs,
        });
    }
    plans.live = live_entries;
    plans.negative_timing = table.enabled;
    Ok(plans)
}

/// `watch`'s bits as single-bit watches, each with the label `base[bit]` (the absolute bit
/// of the signal, as [`terminal_label`] writes a bit-select). A terminal that is already one
/// bit is its own only bit and keeps `label`.
fn bit_watches(watch: &WatchPlan, label: &str, base: &str) -> Vec<(WatchPlan, String)> {
    if watch.width == 1 {
        return vec![(watch.clone(), label.to_string())];
    }
    (watch.lo..watch.lo + watch.width)
        .map(|bit| {
            let mut single = watch.clone();
            single.lo = bit;
            single.width = 1;
            (single, format!("{base}[{bit}]"))
        })
        .collect()
}

/// LRM 31.8's optional expansion of a vector check into single-bit checks: "For timing
/// checks with only a single signal, such as `$period` or `$width`, a vector of width N
/// results in N unique timing checks. For timing checks with two signals ... where M and N
/// are the widths of the signals, the result is M*N unique timing checks. If there is a
/// notifier, all the timing checks trigger that notifier." `reference_base` / `data_base`
/// are the terminals' signal names (the labels of a bit are `name[bit]`).
///
/// `$width` / `$period` name ONE signal (the data event is derived from the reference
/// event), so their data bit is the reference's own: N checks, not N*N. `$nochange`'s
/// trailing reference edge belongs to the reference, so it follows the reference bit.
/// Each expanded check is a complete [`CheckPlan`], so it owns its own state machine; they
/// share only the notifier place.
fn expand_per_bit(check: CheckPlan, reference_base: &str, data_base: &str) -> Vec<CheckPlan> {
    let references = bit_watches(&check.reference, &check.reference_label, reference_base);
    let datas = bit_watches(&check.data, &check.data_label, data_base);
    let one_signal = matches!(
        check.spec,
        CheckSpec::Width { .. } | CheckSpec::Period { .. }
    );
    let trailing = |index: usize| {
        check.trailing.as_ref().map(|t| {
            // The trailing edge is a second watch of the reference signal, bit for bit.
            bit_watches(t, "", reference_base)
                .into_iter()
                .nth(index)
                .map_or_else(|| t.clone(), |(w, _)| w)
        })
    };
    let make = |ri: usize, di: usize| CheckPlan {
        entry: check.entry,
        spec: check.spec,
        reference: references[ri].0.clone(),
        data: datas[di].0.clone(),
        trailing: trailing(ri),
        notifier: check.notifier,
        reference_label: references[ri].1.clone(),
        data_label: datas[di].1.clone(),
        instance: check.instance,
        reference_signal: check.reference_signal.clone(),
        data_signal: check.data_signal.clone(),
        timestamp: check.timestamp.clone(),
        timecheck: check.timecheck.clone(),
    };
    if one_signal {
        (0..references.len().min(datas.len()))
            .map(|i| make(i, i))
            .collect()
    } else {
        (0..references.len())
            .flat_map(|r| (0..datas.len()).map(move |d| (r, d)))
            .map(|(r, d)| make(r, d))
            .collect()
    }
}

/// The [`CheckSpec`] of a `$setup` / `$hold` / `$removal` / `$recovery`: its
/// limit must not be negative (those checks define no negative window; only
/// `$setuphold` / `$recrem` do, LRM 31.9).
fn window_spec(
    kind: StabilityKind,
    args: &EventPairArgs,
    uid: &SymbolId,
    lrm: &str,
) -> Result<CheckSpec, String> {
    if args.limit.ticks < 0 {
        return Err(format!(
            "{} {uid}: the limit is {} ticks, but {}'s limit must be a non-negative constant \
             expression (LRM {lrm})",
            kind.name(),
            args.limit.ticks,
            kind.name(),
        ));
    }
    Ok(CheckSpec::Window {
        kind,
        limit: args.limit.ticks,
    })
}

/// The [`CheckSpec`] of a `$setuphold` (LRM 31.3.3), with the limits as written (either
/// sign): [`negative_timing`] has already solved for the delays that make a negative one
/// work, and [`plan`] swaps in the limits it settled on.
fn setuphold_spec(a: &vj_sim::netlist::specify::SetupHoldArgs) -> CheckSpec {
    CheckSpec::SetupHold {
        setup: a.setup_limit.ticks,
        hold: a.hold_limit.ticks,
    }
}

/// The [`CheckSpec`] of a `$recrem` (LRM 31.3.6), with the limits as written. Its limits are
/// RECOVERY first, then REMOVAL (Table 31-6).
fn recrem_spec(a: &vj_sim::netlist::specify::RecRemArgs) -> CheckSpec {
    CheckSpec::RecRem {
        recovery: a.recovery_limit.ticks,
        removal: a.removal_limit.ticks,
    }
}

/// The [`CheckSpec`] of a `$width` (LRM 31.4.4): the limit and the threshold
/// are "non-negative constant expression"s (Table 31-10); an elided threshold
/// is 0.
fn width_spec(
    a: &vj_sim::netlist::specify::WidthArgs,
    uid: &SymbolId,
) -> Result<CheckSpec, String> {
    let threshold = a.threshold.as_ref().map_or(0, |t| t.ticks);
    for (which, ticks) in [("limit", a.limit.ticks), ("threshold", threshold)] {
        if ticks < 0 {
            return Err(format!(
                "$width {uid}: the {which} is {ticks} ticks, but $width's {which} must be a \
                 non-negative constant expression (LRM 31.4.4)"
            ));
        }
    }
    Ok(CheckSpec::Width {
        limit: a.limit.ticks,
        threshold,
    })
}

/// The [`CheckSpec`] of a `$skew` (LRM 31.4.1): the limit is a "non-negative
/// constant expression" (Table 31-7). That is also what makes "simultaneous
/// transitions ... shall not cause `$skew` to report a timing violation, even
/// when the skew limit value is zero" hold: a skew of 0 is never above it.
fn skew_spec(
    a: &vj_sim::netlist::specify::EventPairArgs,
    uid: &SymbolId,
) -> Result<CheckSpec, String> {
    if a.limit.ticks < 0 {
        return Err(format!(
            "$skew {uid}: the limit is {} ticks, but $skew's limit must be a non-negative \
             constant expression (LRM 31.4.1)",
            a.limit.ticks
        ));
    }
    Ok(CheckSpec::Skew {
        limit: a.limit.ticks,
    })
}

/// The [`CheckSpec`] of a `$timeskew` (LRM 31.4.2): the limit is a "non-negative
/// constant expression" (Table 31-8) and the two flags are "constant expression"s
/// whose elided value is 0 ("event_based_flag ... default 0"), here and only here.
fn timeskew_spec(
    a: &vj_sim::netlist::specify::TimeSkewArgs,
    uid: &SymbolId,
) -> Result<CheckSpec, String> {
    if a.limit.ticks < 0 {
        return Err(format!(
            "$timeskew {uid}: the limit is {} ticks, but $timeskew's limit must be a \
             non-negative constant expression (LRM 31.4.2)",
            a.limit.ticks
        ));
    }
    Ok(CheckSpec::TimeSkew {
        limit: a.limit.ticks,
        flags: SkewFlags {
            event_based: a.event_based.unwrap_or(false),
            remain_active: a.remain_active.unwrap_or(false),
        },
    })
}

/// The [`CheckSpec`] of a `$fullskew` (LRM 31.4.3): both limits are "non-negative
/// constant expression"s (Table 31-9); the flags are `$timeskew`'s.
fn fullskew_spec(
    a: &vj_sim::netlist::specify::FullSkewArgs,
    uid: &SymbolId,
) -> Result<CheckSpec, String> {
    for (which, ticks) in [
        ("first limit", a.reference_first_limit.ticks),
        ("second limit", a.data_first_limit.ticks),
    ] {
        if ticks < 0 {
            return Err(format!(
                "$fullskew {uid}: the {which} is {ticks} ticks, but $fullskew's limits must be \
                 non-negative constant expressions (LRM 31.4.3)"
            ));
        }
    }
    Ok(CheckSpec::FullSkew {
        limit: a.reference_first_limit.ticks,
        data_first_limit: a.data_first_limit.ticks,
        flags: SkewFlags {
            event_based: a.event_based.unwrap_or(false),
            remain_active: a.remain_active.unwrap_or(false),
        },
    })
}

/// The [`CheckSpec`] of a `$period` (LRM 31.4.5): the limit is a "non-negative
/// constant expression" (Table 31-11).
fn period_spec(
    a: &vj_sim::netlist::specify::PeriodArgs,
    uid: &SymbolId,
) -> Result<CheckSpec, String> {
    if a.limit.ticks < 0 {
        return Err(format!(
            "$period {uid}: the limit is {} ticks, but $period's limit must be a non-negative \
             constant expression (LRM 31.4.5)",
            a.limit.ticks
        ));
    }
    Ok(CheckSpec::Period {
        limit: a.limit.ticks,
    })
}

/// `control` with every edge reversed (LRM 31.4.4's "opposite edge"), or a
/// named error for an event with no edge control. Discovery (T13) already
/// refuses a `$width` / `$nochange` reference with none, so the error is the
/// backstop that keeps this match total rather than a path a design can take.
fn opposite_control(control: EdgeControl, check: &str, what: &str) -> Result<EdgeControl, String> {
    control.opposite().ok_or_else(|| {
        format!(
            "{what} has no edge control, so it has no opposite edge ({check} derives an event \
             from its reference event's edge)"
        )
    })
}

/// `reference` with the opposite edge: `$width`'s data event and `$nochange`'s
/// trailing edge. The terminal and the `&&&` condition are the reference's (the
/// derived event is "the reference event signal", so its qualifying condition
/// qualifies it too, LRM 31.7). Only [`CheckEvent::edge_control`] is what the
/// planner reads; the syntactic `edge` / `edge_descriptors` are left as written.
fn opposite_event(
    reference: &vj_sim::netlist::specify::CheckEvent,
    check: &str,
    uid: &SymbolId,
) -> Result<vj_sim::netlist::specify::CheckEvent, String> {
    let mut event = reference.clone();
    event.edge_control = opposite_control(
        reference.edge_control,
        check,
        &format!("{check} {uid}'s reference event"),
    )?;
    Ok(event)
}

/// A table over `entries`' declared limits (their `CheckLimit::ticks`), every check moved by
/// `delta` ticks (0 for a check on no delayed signals); `$sdf_annotate`'s matching tests build
/// the design's check table this way, without planning a design.
#[cfg(test)]
pub(crate) fn live_checks_for_entries(
    entries: &[vj_sim::netlist::specify::CheckEntry],
    delta: i64,
    negative_timing: bool,
) -> LiveChecks {
    let flags = SkewFlags {
        event_based: false,
        remain_active: false,
    };
    let live = entries
        .iter()
        .map(|e| {
            let window = |kind, a: &vj_sim::netlist::specify::EventPairArgs| CheckSpec::Window {
                kind,
                limit: a.limit.ticks,
            };
            let declared = match &e.args {
                CheckArgs::Setup(a) => window(StabilityKind::Setup, a),
                CheckArgs::Hold(a) => window(StabilityKind::Hold, a),
                CheckArgs::Recovery(a) => window(StabilityKind::Recovery, a),
                CheckArgs::Removal(a) => window(StabilityKind::Removal, a),
                CheckArgs::Skew(a) => CheckSpec::Skew {
                    limit: a.limit.ticks,
                },
                CheckArgs::SetupHold(a) => CheckSpec::SetupHold {
                    setup: a.setup_limit.ticks,
                    hold: a.hold_limit.ticks,
                },
                CheckArgs::RecRem(a) => CheckSpec::RecRem {
                    recovery: a.recovery_limit.ticks,
                    removal: a.removal_limit.ticks,
                },
                CheckArgs::TimeSkew(a) => CheckSpec::TimeSkew {
                    limit: a.limit.ticks,
                    flags,
                },
                CheckArgs::FullSkew(a) => CheckSpec::FullSkew {
                    limit: a.reference_first_limit.ticks,
                    data_first_limit: a.data_first_limit.ticks,
                    flags,
                },
                CheckArgs::Period(a) => CheckSpec::Period {
                    limit: a.limit.ticks,
                },
                CheckArgs::Width(a) => CheckSpec::Width {
                    limit: a.limit.ticks,
                    threshold: a.threshold.map_or(0, |t| t.ticks),
                },
                CheckArgs::NoChange(a) => CheckSpec::NoChange {
                    start: a.start_edge_offset.ticks,
                    end: a.end_edge_offset.ticks,
                },
            };
            LiveCheck { declared, delta }
        })
        .collect();
    LiveChecks::new(live, negative_timing)
}

#[cfg(test)]
mod tests {
    use super::*;
    use sv_lang::{Compilation, Design, Session};
    use vj_sim::netlist::specify::{CheckArgs, CondUnaryOp, EdgeSet};

    /// LRM 31.6 Table 31-13, exhaustively over all four values.
    #[test]
    fn notifier_toggle_matches_table_31_13_for_every_value() {
        assert_eq!(notifier_toggle(Bit4::Zero), Bit4::One, "0 -> 1");
        assert_eq!(notifier_toggle(Bit4::One), Bit4::Zero, "1 -> 0");
        assert_eq!(notifier_toggle(Bit4::Z), Bit4::Z, "z -> z");
        // The documented deterministic choice for the table's "0 or 1".
        assert_eq!(notifier_toggle(Bit4::X), Bit4::Zero, "x -> 0");
    }

    /// Toggling twice from a known value returns to it; `x` and `z` are the
    /// only values that are not an involution's two-cycle.
    #[test]
    fn notifier_toggle_is_an_involution_on_known_values_only() {
        for v in [Bit4::Zero, Bit4::One] {
            assert_eq!(notifier_toggle(notifier_toggle(v)), v);
        }
        assert_eq!(notifier_toggle(notifier_toggle(Bit4::Z)), Bit4::Z);
        // x settles into the 0/1 cycle and never returns to x.
        assert_eq!(notifier_toggle(notifier_toggle(Bit4::X)), Bit4::One);
    }

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

    fn discovered(src: &str) -> Result<TimingModel, RunError> {
        let mut design = compile(src);
        let eval = design.eval_session();
        let body = eval
            .design()
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("top instance has a body");
        crate::specify::discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
    }

    fn ticks_of(model: &mut TimingModel) -> Vec<i64> {
        model.timing_checks[0]
            .args
            .limits_mut()
            .into_iter()
            .map(|l| l.ticks)
            .collect()
    }

    /// `specify::discover` attaches the limit in scheduler ticks: `1ns/1ps`
    /// makes a tick one picosecond, so `2.5` (ns) is 2500 ticks.
    #[test]
    fn discover_converts_a_check_limit_with_the_timescale() {
        let mut model = discovered(
            "`timescale 1ns/1ps\nmodule m(input d, input clk);\n  specify\n    $setup(d, \
             posedge clk, 2.5);\n  endspecify\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(ticks_of(&mut model), [2500]);
    }

    /// LRM 31.9: `$setuphold` limits may be negative; the sign survives (a path
    /// delay would clamp it to zero).
    #[test]
    fn discover_keeps_the_sign_of_a_negative_setuphold_limit() {
        let mut model = discovered(
            "`timescale 1ns/1ps\nmodule m(input d, input clk);\n  specify\n    $setuphold(posedge \
             clk, d, -1, 3);\n  endspecify\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(ticks_of(&mut model), [-1000, 3000]);
    }

    /// A specparam limit, a min:typ:max limit (typical value), and `$width`'s
    /// threshold are all evaluated; a `$width` without one has just the limit.
    #[test]
    fn discover_evaluates_specparam_mintypmax_and_threshold_limits() {
        let mut model = discovered(
            "`timescale 1ns/1ps\nmodule m(input clk);\n  specparam lim = 4;\n  specify\n    \
             $width(posedge clk, lim, (1:2:3));\n  endspecify\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(ticks_of(&mut model), [4000, 2000]);

        let mut model = discovered(
            "`timescale 1ns/1ps\nmodule m(input clk);\n  specify\n    $width(posedge clk, \
             5);\n  endspecify\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("discover failed: {e}"));
        assert_eq!(ticks_of(&mut model), [5000]);
    }

    // -----------------------------------------------------------------------
    // T14, LRM 31.5: `edge_matches`.

    const FOUR: [Bit4; 4] = [Bit4::Zero, Bit4::One, Bit4::X, Bit4::Z];

    fn control(edge: sv_lang::EdgeKind, ds: &[&str]) -> EdgeControl {
        let ds: Vec<String> = ds.iter().map(|d| d.to_string()).collect();
        EdgeControl::from_syntax(edge, &ds).unwrap_or_else(|e| panic!("{e}"))
    }

    /// The `(from, to)` pairs `control` accepts, over all sixteen.
    fn accepted(control: EdgeControl) -> Vec<(Bit4, Bit4)> {
        let mut out = Vec::new();
        for from in FOUR {
            for to in FOUR {
                if edge_matches(control, from, to) {
                    out.push((from, to));
                }
            }
        }
        out
    }

    /// LRM 31.5: "`posedge clr` is equivalent to `edge[01, 0x, x1] clr`", and
    /// the same for `negedge`/`edge[10, x0, 1x]` -- the shorthand and the
    /// explicit form give the same answer for EVERY one of the sixteen
    /// transitions, and both agree with a hand-written table (so a wrong
    /// shorthand AND a wrong explicit list could not agree by accident).
    #[test]
    fn posedge_and_negedge_are_exactly_their_edge_lists_for_every_transition() {
        use sv_lang::EdgeKind::{BothEdges, NegEdge, PosEdge};
        let pos = control(PosEdge, &[]);
        let pos_explicit = control(BothEdges, &["01", "0x", "x1"]);
        let neg = control(NegEdge, &[]);
        let neg_explicit = control(BothEdges, &["10", "x0", "1x"]);
        for from in FOUR {
            for to in FOUR {
                assert_eq!(
                    edge_matches(pos, from, to),
                    edge_matches(pos_explicit, from, to),
                    "posedge vs edge[01,0x,x1] on {from:?}->{to:?}"
                );
                assert_eq!(
                    edge_matches(neg, from, to),
                    edge_matches(neg_explicit, from, to),
                    "negedge vs edge[10,x0,1x] on {from:?}->{to:?}"
                );
            }
        }
        use Bit4::{One as I, X, Z, Zero as O};
        assert_eq!(accepted(pos), [(O, I), (O, X), (O, Z), (X, I), (Z, I)]);
        assert_eq!(accepted(neg), [(I, O), (I, X), (I, Z), (X, O), (Z, O)]);
    }

    /// 31.5: "Edge transitions involving z are treated the same way as edge
    /// transitions involving x" -- and a descriptor never matches a transition
    /// between x and z, or a no-change.
    #[test]
    fn each_descriptor_matches_exactly_its_transition_with_z_as_x() {
        use Bit4::{One as I, X, Z, Zero as O};
        use sv_lang::EdgeKind::BothEdges;
        for (d, want) in [
            ("01", vec![(O, I)]),
            ("10", vec![(I, O)]),
            ("0x", vec![(O, X), (O, Z)]),
            ("0z", vec![(O, X), (O, Z)]),
            ("x0", vec![(X, O), (Z, O)]),
            ("Z0", vec![(X, O), (Z, O)]),
            ("1x", vec![(I, X), (I, Z)]),
            ("1Z", vec![(I, X), (I, Z)]),
            ("x1", vec![(X, I), (Z, I)]),
            ("z1", vec![(X, I), (Z, I)]),
        ] {
            assert_eq!(accepted(control(BothEdges, &[d])), want, "descriptor {d}");
        }
    }

    #[test]
    fn a_descriptor_list_is_the_union_of_its_descriptors() {
        use Bit4::{One as I, X, Z, Zero as O};
        let c = control(sv_lang::EdgeKind::BothEdges, &["01", "1x"]);
        assert_eq!(accepted(c), [(O, I), (I, X), (I, Z)]);
    }

    /// Bare `edge` (31.5 does not define it) is any of the six transitions;
    /// x<->z is none of them.
    #[test]
    fn bare_edge_is_all_six_transitions_but_not_x_to_z() {
        let all = accepted(control(sv_lang::EdgeKind::BothEdges, &[]));
        assert_eq!(all.len(), 10, "01 10 0x 0z x0 z0 1x 1z x1 z1: {all:?}");
        assert!(!all.contains(&(Bit4::X, Bit4::Z)) && !all.contains(&(Bit4::Z, Bit4::X)));
        for v in FOUR {
            assert!(!edge_matches(EdgeControl::Edges(EdgeSet::ALL), v, v));
        }
    }

    /// No edge control: any value change, x<->z included (it is a change of
    /// the signal even though no edge descriptor names it); no change is not
    /// an event.
    #[test]
    fn no_edge_control_matches_every_value_change_and_nothing_else() {
        for from in FOUR {
            for to in FOUR {
                assert_eq!(
                    edge_matches(EdgeControl::AnyChange, from, to),
                    from != to,
                    "{from:?}->{to:?}"
                );
            }
        }
    }

    // -----------------------------------------------------------------------
    // T14, LRM 31.7: `condition_holds`.

    fn lit(bits: &[Bit4]) -> CondEval {
        CondEval::Const(bits.to_vec())
    }

    fn un(op: CondUnaryOp, a: CondEval) -> CondEval {
        CondEval::Unary(op, Box::new(a))
    }

    fn bin(op: CondBinaryOp, a: CondEval, b: CondEval) -> CondEval {
        CondEval::Binary(op, Box::new(a), Box::new(b))
    }

    /// Example 1: `$setup(data, posedge clk &&& clr, 10)` -- the check occurs
    /// only when clr is high. A bare signal is a deterministic comparison, so
    /// an x (or z) does NOT enable it.
    #[test]
    fn a_bare_condition_holds_only_for_a_known_one_31_7_example_1() {
        assert!(condition_holds(&lit(&[Bit4::One])));
        assert!(!condition_holds(&lit(&[Bit4::Zero])));
        assert!(!condition_holds(&lit(&[Bit4::X])), "x must not enable");
        assert!(!condition_holds(&lit(&[Bit4::Z])), "z is treated as x");
    }

    /// Example 2: `&&& (~clr)` and `&&& (clr===0)` both trigger only when clr
    /// is low -- the same on every one of clr's four values, x/z included
    /// (both are deterministic).
    #[test]
    fn tilde_clr_and_clr_case_equals_zero_agree_on_every_value_31_7_example_2() {
        for clr in FOUR {
            let tilde = condition_holds(&un(CondUnaryOp::BitwiseNot, lit(&[clr])));
            let case_eq = condition_holds(&bin(
                CondBinaryOp::CaseEquality,
                lit(&[clr]),
                lit(&[Bit4::Zero]),
            ));
            assert_eq!(tilde, case_eq, "clr = {clr:?}");
            assert_eq!(tilde, clr == Bit4::Zero, "clr = {clr:?}: only a known 0");
        }
    }

    /// Example 3: `and new_gate(clr_and_set, clr, set)` outside the specify
    /// block, then `&&& clr_and_set`. The condition sees only the gate's one
    /// scalar output, so it is an ordinary bare condition: only a known 1 on
    /// BOTH inputs enables the check (a 0 or an x on either does not).
    #[test]
    fn the_external_and_gate_signal_is_an_ordinary_bare_condition_31_7_example_3() {
        for clr in FOUR {
            for set in FOUR {
                // The gate's output, through the same 4-state AND the
                // condition evaluator uses for `&`.
                let gate = bin(CondBinaryOp::BitwiseAnd, lit(&[clr]), lit(&[set]));
                assert_eq!(
                    condition_holds(&gate),
                    clr == Bit4::One && set == Bit4::One,
                    "clr={clr:?} set={set:?}"
                );
            }
        }
    }

    /// 31.7: `==`/`!=` are nondeterministic -- an x on the conditioning signal
    /// ENABLES the check; `===`/`!==` are deterministic -- it does not. All
    /// four operators, both constants, all four signal values.
    #[test]
    fn x_enables_a_nondeterministic_comparison_only_31_7() {
        use CondBinaryOp::{CaseEquality, CaseInequality, Equality, Inequality};
        for sig in FOUR {
            let unknown = matches!(sig, Bit4::X | Bit4::Z);
            for k in [Bit4::Zero, Bit4::One] {
                let holds = |op| condition_holds(&bin(op, lit(&[sig]), lit(&[k])));
                // Nondeterministic: an unknown signal enables regardless of k.
                assert_eq!(holds(Equality), unknown || sig == k, "{sig:?} == {k:?}");
                assert_eq!(holds(Inequality), unknown || sig != k, "{sig:?} != {k:?}");
                // Deterministic: an unknown signal never enables -- not even
                // `x !== 0`, which as a 4-state comparison is true.
                assert_eq!(
                    holds(CaseEquality),
                    !unknown && sig == k,
                    "{sig:?} === {k:?}"
                );
                assert_eq!(
                    holds(CaseInequality),
                    !unknown && sig != k,
                    "{sig:?} !== {k:?}"
                );
            }
        }
    }

    /// 31.7: "if a vector net or an expression resulting in a multibit value is
    /// used, then the LSB of the vector net or the expression value is used."
    /// Every vector below has a non-LSB bit that would change the answer under
    /// an any-bit or whole-value reading.
    #[test]
    fn a_multibit_conditioning_signal_is_read_at_its_lsb_31_7() {
        use Bit4::{One as I, X, Zero as O};
        // LSB first: value 4'b0010 (LSB 0, bit1 1) -- a bare vector is false.
        assert!(!condition_holds(&lit(&[O, I, O, O])));
        // 4'b0001 -- true.
        assert!(condition_holds(&lit(&[I, O, O, O])));
        // 4'b111x: LSB x -> a bare condition does not enable.
        assert!(!condition_holds(&lit(&[X, I, I, I])));
        // `vec == 1'b1` compares the LSB only: 4'b1110 is not enabled, 4'b0001 is.
        let eq1 = |v: &[Bit4]| condition_holds(&bin(CondBinaryOp::Equality, lit(v), lit(&[I])));
        assert!(!eq1(&[O, I, I, I]));
        assert!(eq1(&[I, O, O, O]));
        // ... and an x LSB enables the nondeterministic comparison.
        assert!(eq1(&[X, O, O, O]));
        // An unsized `0` (32 bits) is still the scalar constant 0.
        let ceq0 =
            |v: &[Bit4]| condition_holds(&bin(CondBinaryOp::CaseEquality, lit(v), lit(&[O; 32])));
        assert!(ceq0(&[O, I, I, I]), "LSB 0 === 0");
        assert!(!ceq0(&[I, O, O, O]));
        // `~vec` is a multibit expression: its LSB is ~vec[0].
        let not = |v: &[Bit4]| condition_holds(&un(CondUnaryOp::BitwiseNot, lit(v)));
        assert!(not(&[O, I, I, I]), "~4'b1110 = 4'b0001, LSB 1");
        assert!(!not(&[I, O, O, O]), "~4'b0001 = 4'b1110, LSB 0");
        assert!(!not(&[X, O, O, O]), "~4'b000x has LSB x");
    }

    /// Not the real condition grammar (31.7's `scalar_timing_check_condition`
    /// is `expr`, `~expr` or `expr op scalar_constant`), but slang accepts any
    /// expression: those evaluate as one multibit value read at its LSB, and
    /// are deterministic (x does not enable).
    #[test]
    fn any_other_expression_is_a_bare_deterministic_condition_read_at_its_lsb() {
        use Bit4::{One as I, X, Zero as O};
        // `a && b`
        let and = |a, b| condition_holds(&bin(CondBinaryOp::LogicalAnd, lit(&[a]), lit(&[b])));
        assert!(and(I, I));
        assert!(!and(I, O));
        assert!(!and(I, X), "1 && x = x does not enable");
        // `!a`
        let not = |a| condition_holds(&un(CondUnaryOp::LogicalNot, lit(&[a])));
        assert!(not(O));
        assert!(!not(X));
        // `a == 2'b10` is not a scalar-constant comparison: whole-value result
        // (a 1-bit `==`, x on any bit makes it x -> enables, since == is
        // nondeterministic by its operator).
        let eq = |a: &[Bit4]| condition_holds(&bin(CondBinaryOp::Equality, lit(a), lit(&[O, I])));
        assert!(eq(&[O, I]));
        assert!(!eq(&[I, I]));
        assert!(eq(&[X, I]));
    }

    // -----------------------------------------------------------------------
    // The conditions discovery actually produces for 31.7's worked examples,
    // evaluated through `condition_holds` with the signals' values supplied.

    /// Replaces every `Signal` leaf of `node` with `Const(value_of(name))`.
    fn cond_with(
        node: &vj_sim::netlist::specify::CondNode,
        names: &[(String, SymbolId)],
        value_of: &dyn Fn(&str) -> Vec<Bit4>,
    ) -> CondEval {
        use vj_sim::netlist::specify::CondNode as N;
        let go = |n: &N| Box::new(cond_with(n, names, value_of));
        match node {
            N::Signal((uid, bits)) => {
                let name = &names
                    .iter()
                    .find(|(_, u)| u == uid)
                    .unwrap_or_else(|| panic!("unknown signal {uid}"))
                    .0;
                let v = value_of(name);
                CondEval::Const(match bits {
                    None => v,
                    Some((lo, w)) => v[*lo as usize..(*lo + *w) as usize].to_vec(),
                })
            }
            N::Const(b) => CondEval::Const(b.clone()),
            N::Unary(op, a) => CondEval::Unary(*op, go(a)),
            N::Binary(op, a, b) => CondEval::Binary(*op, go(a), go(b)),
            N::Specparam(_) | N::Ternary(..) | N::Concat(_) | N::Replication(..) => {
                panic!("not used by these examples: {node:?}")
            }
        }
    }

    fn first_reference_condition(
        call: &str,
    ) -> (vj_sim::netlist::specify::CondNode, Vec<(String, SymbolId)>) {
        let src = format!(
            "module m(input clk, input data, input clr, input [3:0] bus);\n  specify\n    {call}\n  \
             endspecify\nendmodule\n"
        );
        let mut design = compile(&src);
        let eval = design.eval_session();
        let body = eval
            .design()
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("top instance has a body");
        let names: Vec<(String, SymbolId)> = body
            .members()
            .filter(|s| matches!(s.kind(), SymbolKind::Net | SymbolKind::Variable))
            .map(|s| (s.name().to_string(), s.uid()))
            .collect();
        let model = crate::specify::discover(&eval, &[(InstanceId(0), body)], Path::new("<test>"))
            .unwrap_or_else(|e| panic!("discover failed: {e}"));
        let CheckArgs::Setup(a) = &model.timing_checks[0].args else {
            panic!("not $setup")
        };
        let cond = a.reference.condition.clone().expect("a conditioned event");
        (cond, names)
    }

    fn holds_for(call: &str, clr: &[Bit4]) -> bool {
        let (node, names) = first_reference_condition(call);
        let value_of = |n: &str| match n {
            "clr" => clr.to_vec(),
            "bus" => clr.to_vec(),
            other => panic!("unexpected signal {other}"),
        };
        condition_holds(&cond_with(&node, &names, &value_of))
    }

    #[test]
    fn discovered_31_7_examples_enable_the_check_as_the_lrm_says() {
        use Bit4::{One as I, X, Z, Zero as O};
        let bare = "$setup(data, posedge clk &&& clr, 10);";
        let tilde = "$setup(data, posedge clk &&& (~clr), 10);";
        let case_eq = "$setup(data, posedge clk &&& (clr===0), 10);";
        let eq = "$setup(data, posedge clk &&& (clr==0), 10);";
        let ne = "$setup(data, posedge clk &&& (clr!=1'b1), 10);";
        for (v, want_bare, want_low, want_eq) in [
            (O, false, true, true),
            (I, true, false, false),
            (X, false, false, true),
            (Z, false, false, true),
        ] {
            assert_eq!(holds_for(bare, &[v]), want_bare, "&&& clr, clr={v:?}");
            assert_eq!(holds_for(tilde, &[v]), want_low, "&&& (~clr), clr={v:?}");
            assert_eq!(
                holds_for(case_eq, &[v]),
                want_low,
                "&&& (clr===0), clr={v:?}"
            );
            assert_eq!(holds_for(eq, &[v]), want_eq, "&&& (clr==0), clr={v:?}");
            assert_eq!(holds_for(ne, &[v]), want_eq, "&&& (clr!=1'b1), clr={v:?}");
        }
        // A bit-select conditioning terminal: `bus[1]` is the scalar.
        let sel = "$setup(data, posedge clk &&& bus[1], 10);";
        assert!(holds_for(sel, &[O, I, O, O]));
        assert!(!holds_for(sel, &[I, O, I, I]));
    }

    // -----------------------------------------------------------------------

    /// Every limit slot of every kind is reachable through `limits_mut`, with
    /// the position the LRM table gives it.
    #[test]
    fn every_kind_exposes_its_limit_slots_in_argument_order() {
        let model = discovered(
            "`timescale 1ns/1ps\nmodule m(input d, input clk, input clr);\n  reg n;\n  specify\n    \
             $setup(d, posedge clk, 1);\n    $hold(posedge clk, d, 2);\n    $setuphold(posedge \
             clk, d, 3, 4);\n    $recovery(posedge clr, posedge clk, 5);\n    $removal(posedge \
             clr, posedge clk, 6);\n    $recrem(posedge clr, posedge clk, 7, 8);\n    \
             $skew(posedge clk, d, 9);\n    $timeskew(posedge clk, d, 10);\n    \
             $fullskew(posedge clk, d, 11, 12);\n    $period(posedge clk, 13);\n    \
             $width(posedge clk, 14, 15);\n    $nochange(posedge clk, d, 16, 17);\n  \
             endspecify\nendmodule\n",
        )
        .unwrap_or_else(|e| panic!("discover failed: {e}"));
        let mut model = model;
        let per_check: Vec<Vec<i64>> = model
            .timing_checks
            .iter_mut()
            .map(|c| c.args.limits_mut().into_iter().map(|l| l.ticks).collect())
            .collect();
        assert_eq!(
            per_check,
            vec![
                vec![1000],
                vec![2000],
                vec![3000, 4000],
                vec![5000],
                vec![6000],
                vec![7000, 8000],
                vec![9000],
                vec![10000],
                vec![11000, 12000],
                vec![13000],
                vec![14000, 15000],
                vec![16000, 17000],
            ]
        );
        assert!(matches!(
            model.timing_checks[2].args,
            CheckArgs::SetupHold(_)
        ));
    }

    // -----------------------------------------------------------------------
    // T15, LRM 31.3.1 / 31.3.2: `window_violation`, the stability-window state
    // machine, and `$setup` / `$hold` end to end.

    /// `window_violation` against hand-written truth tables over
    /// `begin-1 ..= end+1` for a window (10, 20): LRM 31.3.1 "the end points
    /// of the time window are not part of the violation region" (open at both
    /// ends) and 31.3.2 "only the end of the time window is not part of the
    /// violation region" (closed at the start, open at the end). The two
    /// kinds differ at exactly one point, `begin`, and a copy-paste of one
    /// onto the other fails here.
    #[test]
    fn window_violation_truth_tables_for_both_boundary_kinds() {
        // (t, OpenBoth, ClosedStartOpenEnd)
        let table = [
            (9, false, false),  // begin - 1
            (10, false, true),  // begin: the ONE point the kinds differ at
            (11, true, true),   // begin + 1
            (15, true, true),   // interior
            (19, true, true),   // end - 1
            (20, false, false), // end: never part of the region
            (21, false, false), // end + 1
        ];
        for (t, open_both, closed_start) in table {
            assert_eq!(
                window_violation(BoundaryKind::OpenBoth, 10, 20, t),
                open_both,
                "OpenBoth at t={t}"
            );
            assert_eq!(
                window_violation(BoundaryKind::ClosedStartOpenEnd, 10, 20, t),
                closed_start,
                "ClosedStartOpenEnd at t={t}"
            );
        }
    }

    /// The `$setuphold` data-first window (LRM 31.3.3: "only the beginning of
    /// the time window is not part of the violation region"), against the same
    /// window (10, 20) as the table above. It is the mirror image of
    /// `ClosedStartOpenEnd` -- it differs from `OpenBoth` at exactly one point,
    /// `end` -- and a copy-paste of either neighbour fails here.
    #[test]
    fn window_violation_truth_table_for_the_open_start_closed_end_kind() {
        // (t, OpenStartClosedEnd, OpenBoth, ClosedStartOpenEnd)
        let table = [
            (9, false, false, false),  // begin - 1
            (10, false, false, true),  // begin: not part of THIS region
            (11, true, true, true),    // begin + 1
            (15, true, true, true),    // interior
            (19, true, true, true),    // end - 1
            (20, true, false, false),  // end: part of THIS region, no other
            (21, false, false, false), // end + 1
        ];
        for (t, open_start, open_both, closed_start) in table {
            assert_eq!(
                window_violation(BoundaryKind::OpenStartClosedEnd, 10, 20, t),
                open_start,
                "OpenStartClosedEnd at t={t}"
            );
            // Pin the three kinds apart, so none can be quietly aliased.
            assert_eq!(
                window_violation(BoundaryKind::OpenBoth, 10, 20, t),
                open_both,
                "OpenBoth at t={t}"
            );
            assert_eq!(
                window_violation(BoundaryKind::ClosedStartOpenEnd, 10, 20, t),
                closed_start,
                "ClosedStartOpenEnd at t={t}"
            );
        }
    }

    /// A window that is empty or inverted contains nothing, for every kind.
    #[test]
    fn window_violation_of_an_empty_or_inverted_window_is_never_a_violation() {
        for kind in [
            BoundaryKind::OpenBoth,
            BoundaryKind::ClosedStartOpenEnd,
            BoundaryKind::OpenStartClosedEnd,
        ] {
            for t in 8..=12 {
                assert!(
                    !window_violation(kind, 10, 10, t),
                    "{kind:?} zero width t={t}"
                );
                assert!(!window_violation(kind, 12, 8, t), "{kind:?} inverted t={t}");
            }
        }
    }

    /// limit = 0 never violates (31.3.1 / 31.3.2), for BOTH kinds, by an
    /// explicit short-circuit rather than by the accident that a zero-width
    /// window is empty: handed a window that WOULD contain `t`, a zero limit
    /// still says no. (A closed-start zero-width window and an open-both one
    /// are different degenerate cases; each is covered.)
    #[test]
    fn a_zero_limit_short_circuits_both_boundary_kinds() {
        for kind in [
            BoundaryKind::OpenBoth,
            BoundaryKind::ClosedStartOpenEnd,
            BoundaryKind::OpenStartClosedEnd,
        ] {
            for t in 8..=12 {
                assert!(
                    !stability_violation(kind, 0, 10, 10, t),
                    "{kind:?} zero width"
                );
            }
            assert!(
                window_violation(kind, 0, 100, 50),
                "the window itself contains 50"
            );
            assert!(
                !stability_violation(kind, 0, 0, 100, 50),
                "{kind:?}: limit 0 must not violate even if the window passed in is wide"
            );
            assert!(
                stability_violation(kind, 1, 0, 100, 50),
                "{kind:?}: limit 1 does"
            );
        }
    }

    const SETUP: StabilityKind = StabilityKind::Setup;
    const HOLD: StabilityKind = StabilityKind::Hold;
    const REMOVAL: StabilityKind = StabilityKind::Removal;
    const RECOVERY: StabilityKind = StabilityKind::Recovery;

    /// The ordering of the two events inside one simulation time step is not
    /// defined by the LRM (and the scheduler does not promise one), so every
    /// same-time scenario below is run both ways.
    #[derive(Clone, Copy, Debug)]
    enum Order {
        DataFirst,
        ReferenceFirst,
    }

    /// Feeds a data event at `data_t` and a reference event at `ref_t` (the
    /// earlier first; at the same time, in `order`), returning every reported
    /// `actual`.
    fn pair(kind: StabilityKind, limit: i64, data_t: i64, ref_t: i64, order: Order) -> Vec<i64> {
        let mut w = WindowState::new(kind, limit);
        let mut out = Vec::new();
        let data_first = match data_t.cmp(&ref_t) {
            std::cmp::Ordering::Less => true,
            std::cmp::Ordering::Greater => false,
            std::cmp::Ordering::Equal => matches!(order, Order::DataFirst),
        };
        if data_first {
            out.extend(w.data_event(data_t));
            out.extend(w.reference_event(ref_t));
        } else {
            out.extend(w.reference_event(ref_t));
            out.extend(w.data_event(data_t));
        }
        out
    }

    /// LRM 31.3.1 `$setup` boundary sweep: the reference (timecheck) event is
    /// at 100 and the data (timestamp) event at every offset from
    /// `-limit-1` to `+limit+1` of it. The violation region is `100-limit <
    /// t_data < 100`: NO violation at either exact end point (offset `-limit`
    /// and offset 0), a violation one unit inside each, none outside.
    #[test]
    fn setup_boundary_sweep_is_open_at_both_ends() {
        let limit = 5;
        let t_ref = 100;
        for off in -(limit + 1)..=(limit + 1) {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = pair(SETUP, limit, t_ref + off, t_ref, order);
                let want: Vec<i64> = if (-limit + 1..=-1).contains(&off) {
                    vec![-off]
                } else {
                    vec![]
                };
                assert_eq!(got, want, "$setup, data at ref{off:+} ({order:?})");
            }
        }
        // The two exact end points and their inner neighbours, spelled out.
        assert!(
            pair(SETUP, limit, 95, t_ref, Order::DataFirst).is_empty(),
            "begin"
        );
        assert_eq!(
            pair(SETUP, limit, 96, t_ref, Order::DataFirst),
            [4],
            "begin+1"
        );
        assert_eq!(
            pair(SETUP, limit, 99, t_ref, Order::DataFirst),
            [1],
            "end-1"
        );
        assert!(
            pair(SETUP, limit, 100, t_ref, Order::DataFirst).is_empty(),
            "end"
        );
        assert!(
            pair(SETUP, limit, 100, t_ref, Order::ReferenceFirst).is_empty(),
            "end"
        );
    }

    /// LRM 31.3.2 `$hold` boundary sweep, SEPARATE from the `$setup` one (the
    /// shapes differ): the reference (timestamp) event is at 100 and the data
    /// (timecheck) event at every offset from `-limit-1` to `+limit+1`. The
    /// region is `100 <= t_data < 100+limit`: the START (offset 0, the data
    /// changing in the very instant of the reference edge) IS a violation, in
    /// either processing order and reported exactly once; the END (offset
    /// `+limit`) is not.
    #[test]
    fn hold_boundary_sweep_is_closed_at_the_start_and_open_at_the_end() {
        let limit = 5;
        let t_ref = 100;
        for off in -(limit + 1)..=(limit + 1) {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = pair(HOLD, limit, t_ref + off, t_ref, order);
                let want: Vec<i64> = if (0..limit).contains(&off) {
                    vec![off]
                } else {
                    vec![]
                };
                assert_eq!(got, want, "$hold, data at ref{off:+} ({order:?})");
            }
        }
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert_eq!(
                pair(HOLD, limit, 100, t_ref, order),
                [0],
                "start IS a violation"
            );
            assert_eq!(pair(HOLD, limit, 104, t_ref, order), [4], "end-1");
            assert!(
                pair(HOLD, limit, 105, t_ref, order).is_empty(),
                "end is not"
            );
            assert!(
                pair(HOLD, limit, 99, t_ref, order).is_empty(),
                "before the window"
            );
        }
    }

    /// A zero limit never violates, through the state machine, for both
    /// checks, with the events simultaneous (the case a closed-start window
    /// would otherwise flag).
    #[test]
    fn a_zero_limit_never_violates_through_the_state_machine() {
        for kind in [SETUP, HOLD] {
            for off in -2..=2 {
                for order in [Order::DataFirst, Order::ReferenceFirst] {
                    assert!(
                        pair(kind, 0, 100 + off, 100, order).is_empty(),
                        "{kind:?} off={off} ({order:?})"
                    );
                }
            }
        }
    }

    /// `$setup`: an earlier data event inside the window violates even when a
    /// SECOND data event lands in the reference's own time step (the end
    /// point, which alone would not): the check looks at the data event
    /// before the reference edge, not merely the latest.
    #[test]
    fn setup_sees_the_earlier_data_event_when_another_lands_at_the_reference_time() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            let mut w = WindowState::new(SETUP, 5);
            let mut got = Vec::new();
            got.extend(w.data_event(98));
            if matches!(order, Order::DataFirst) {
                got.extend(w.data_event(100));
                got.extend(w.reference_event(100));
            } else {
                got.extend(w.reference_event(100));
                got.extend(w.data_event(100));
            }
            assert_eq!(got, [2], "({order:?})");
        }
    }

    /// `$setup` reports once per reference event (the timecheck event), however
    /// many data events fall in its window, and a later reference event is
    /// checked against its own window.
    #[test]
    fn setup_reports_once_per_reference_event() {
        let mut w = WindowState::new(SETUP, 5);
        assert_eq!(w.data_event(96), None);
        assert_eq!(w.data_event(98), None);
        assert_eq!(w.reference_event(100), Some(2), "nearest data event");
        assert_eq!(
            w.reference_event(101),
            Some(3),
            "next reference: its own window"
        );
        assert_eq!(w.reference_event(104), None, "98 is 6 before 104: outside");
    }

    /// `$hold` is checked against the MOST RECENT reference (timestamp) event.
    #[test]
    fn hold_uses_the_most_recent_reference_event() {
        let mut w = WindowState::new(HOLD, 5);
        assert_eq!(w.reference_event(100), None);
        assert_eq!(w.reference_event(102), None);
        // 106 is outside [100,105) but inside [102,107).
        assert_eq!(w.data_event(106), Some(4));
        let mut w = WindowState::new(HOLD, 5);
        assert_eq!(w.reference_event(100), None);
        assert_eq!(w.data_event(103), Some(3));
        assert_eq!(w.data_event(105), None, "end of the window");
    }

    /// `$hold`: the one data event at the reference's own time is ONE
    /// violation, even if it had already been flagged against an EARLIER
    /// reference event whose window it was also inside.
    #[test]
    fn hold_reports_a_data_event_at_most_once() {
        let mut w = WindowState::new(HOLD, 5);
        assert_eq!(w.reference_event(100), None);
        assert_eq!(w.data_event(102), Some(2), "against the 100 edge");
        assert_eq!(
            w.reference_event(102),
            None,
            "same data event, already reported"
        );
    }

    /// `$hold` with no reference event yet has nothing to hold against.
    #[test]
    fn hold_before_any_reference_event_is_clean() {
        let mut w = WindowState::new(HOLD, 5);
        assert_eq!(w.data_event(3), None);
        let mut w = WindowState::new(SETUP, 5);
        assert_eq!(w.reference_event(3), None, "$setup: no data event yet");
    }

    // -----------------------------------------------------------------------
    // T17, LRM 31.3.4 / 31.3.5: `$removal` and `$recovery` through the same
    // state machine as `$setup` / `$hold`.

    /// LRM 31.3.4 `$removal` boundary sweep. Table 31-4: the REFERENCE event
    /// is the timecheck event and the data event the timestamp event, so the
    /// window is `(t_ref - limit, t_ref)` and, "the end points of the time
    /// window are not part of the violation region": the reference event is at
    /// 100 and the data event at every offset from `-limit-1` to `+limit+1` of
    /// it -- NO violation at either exact end point (offset `-limit`, and
    /// offset 0 = both events in one instant, in either processing order), a
    /// violation one unit inside each, none outside.
    #[test]
    fn removal_boundary_sweep_is_open_at_both_ends() {
        let limit = 5;
        let t_ref = 100;
        for off in -(limit + 1)..=(limit + 1) {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = pair(REMOVAL, limit, t_ref + off, t_ref, order);
                let want: Vec<i64> = if (-limit + 1..=-1).contains(&off) {
                    vec![-off]
                } else {
                    vec![]
                };
                assert_eq!(got, want, "$removal, data at ref{off:+} ({order:?})");
            }
        }
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert!(
                pair(REMOVAL, limit, 95, t_ref, order).is_empty(),
                "begin ({order:?})"
            );
            assert_eq!(
                pair(REMOVAL, limit, 96, t_ref, order),
                [4],
                "begin+1 ({order:?})"
            );
            assert_eq!(
                pair(REMOVAL, limit, 99, t_ref, order),
                [1],
                "end-1 ({order:?})"
            );
            assert!(
                pair(REMOVAL, limit, 100, t_ref, order).is_empty(),
                "end, simultaneous ({order:?})"
            );
        }
    }

    /// LRM 31.3.5 `$recovery` boundary sweep, SEPARATE from `$removal`'s (the
    /// shapes differ). Table 31-5: the reference event is the timestamp event
    /// and the data event the timecheck event: window `[t_ref, t_ref + limit)`,
    /// "only the end of the time window is not part of the violation region".
    /// The START (offset 0, the data event in the very instant of the
    /// reference event, either processing order) IS a violation, reported once;
    /// the END (offset `+limit`) is not.
    #[test]
    fn recovery_boundary_sweep_is_closed_at_the_start_and_open_at_the_end() {
        let limit = 5;
        let t_ref = 100;
        for off in -(limit + 1)..=(limit + 1) {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = pair(RECOVERY, limit, t_ref + off, t_ref, order);
                let want: Vec<i64> = if (0..limit).contains(&off) {
                    vec![off]
                } else {
                    vec![]
                };
                assert_eq!(got, want, "$recovery, data at ref{off:+} ({order:?})");
            }
        }
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert_eq!(
                pair(RECOVERY, limit, 100, t_ref, order),
                [0],
                "start IS a violation ({order:?})"
            );
            assert_eq!(pair(RECOVERY, limit, 104, t_ref, order), [4], "end-1");
            assert!(
                pair(RECOVERY, limit, 105, t_ref, order).is_empty(),
                "end is not ({order:?})"
            );
            assert!(
                pair(RECOVERY, limit, 99, t_ref, order).is_empty(),
                "before the window ({order:?})"
            );
        }
    }

    /// The two kinds differ at exactly the simultaneous instant (the one point
    /// a closed-start window and an open one disagree on), so a `$removal`
    /// mapped onto `$recovery`'s shape, or the reverse, fails here.
    #[test]
    fn removal_and_recovery_disagree_exactly_at_the_simultaneous_instant() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert!(pair(REMOVAL, 5, 100, 100, order).is_empty(), "{order:?}");
            assert_eq!(pair(RECOVERY, 5, 100, 100, order), [0], "{order:?}");
        }
    }

    /// limit = 0 never violates (31.3.4 / 31.3.5), through the state machine,
    /// for both kinds and with the events simultaneous (the case a closed-start
    /// `$recovery` window would otherwise flag).
    #[test]
    fn removal_and_recovery_with_a_zero_limit_never_violate() {
        for kind in [REMOVAL, RECOVERY] {
            for off in -2..=2 {
                for order in [Order::DataFirst, Order::ReferenceFirst] {
                    assert!(
                        pair(kind, 0, 100 + off, 100, order).is_empty(),
                        "{kind:?} off={off} ({order:?})"
                    );
                }
            }
        }
    }

    /// `$removal` reports once per reference (timecheck) event, however many
    /// data events fall in its window, against the nearest one; an earlier data
    /// event still inside the window is found when another lands in the
    /// reference's own instant.
    #[test]
    fn removal_reports_once_per_reference_event_and_sees_the_earlier_data_event() {
        let mut w = WindowState::new(REMOVAL, 5);
        assert_eq!(w.data_event(96), None);
        assert_eq!(w.data_event(98), None);
        assert_eq!(w.reference_event(100), Some(2), "nearest data event");
        assert_eq!(w.reference_event(101), Some(3), "its own window");
        assert_eq!(w.reference_event(104), None, "98 is 6 before 104");
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            let mut w = WindowState::new(REMOVAL, 5);
            let mut got = Vec::new();
            got.extend(w.data_event(98));
            if matches!(order, Order::DataFirst) {
                got.extend(w.data_event(100));
                got.extend(w.reference_event(100));
            } else {
                got.extend(w.reference_event(100));
                got.extend(w.data_event(100));
            }
            assert_eq!(got, [2], "({order:?})");
        }
    }

    /// `$recovery` is measured from the MOST RECENT reference (timestamp)
    /// event, and a data event is flagged at most once.
    #[test]
    fn recovery_uses_the_most_recent_reference_event_and_flags_once() {
        let mut w = WindowState::new(RECOVERY, 5);
        assert_eq!(w.reference_event(100), None);
        assert_eq!(w.reference_event(102), None);
        // 106 is outside [100,105) but inside [102,107).
        assert_eq!(w.data_event(106), Some(4));
        let mut w = WindowState::new(RECOVERY, 5);
        assert_eq!(w.reference_event(100), None);
        assert_eq!(w.data_event(102), Some(2), "against the 100 edge");
        assert_eq!(w.reference_event(102), None, "already reported");
        assert_eq!(w.data_event(105), Some(3), "measured from the 102 edge");
    }

    /// Nothing to check against before the other event has happened.
    #[test]
    fn removal_and_recovery_before_any_other_event_are_clean() {
        let mut w = WindowState::new(RECOVERY, 5);
        assert_eq!(w.data_event(3), None, "$recovery: no reference event yet");
        let mut w = WindowState::new(REMOVAL, 5);
        assert_eq!(w.reference_event(3), None, "$removal: no data event yet");
    }

    /// Feeds a data event at `data_t` and a reference event at `ref_t` to a
    /// `$setuphold` (the earlier first; at the same time, in `order`), returning
    /// every reported violation as `(actual, limit)`.
    fn sh_pair(setup: i64, hold: i64, data_t: i64, ref_t: i64, order: Order) -> Vec<(i64, i64)> {
        let mut s = SetupHoldState::setuphold(setup, hold);
        let mut out = Vec::new();
        let data_first = match data_t.cmp(&ref_t) {
            std::cmp::Ordering::Less => true,
            std::cmp::Ordering::Greater => false,
            std::cmp::Ordering::Equal => matches!(order, Order::DataFirst),
        };
        if data_first {
            out.extend(s.data_event(data_t));
            out.extend(s.reference_event(ref_t));
        } else {
            out.extend(s.reference_event(ref_t));
            out.extend(s.data_event(data_t));
        }
        out.into_iter().map(|v| (v.actual, v.limit)).collect()
    }

    /// LRM 31.3.3 boundary sweep of BOTH windows of one `$setuphold(.., 5, 3)`,
    /// in both processing orders of a same-time pair: the reference event is at
    /// 100 and the data event at every offset from -6 to +4.
    ///
    /// * data first, `(95, 100]`: offsets -4..=-1 violate with their own limit
    ///   (5); the begin (-5) does NOT; the END (0) does -- as the simultaneous
    ///   case, `actual` 0;
    /// * data second, `[100, 103)`: offsets 1..=2 violate with the hold limit
    ///   (3); the end (+3) does not.
    #[test]
    fn setuphold_boundary_sweep_covers_both_windows_and_the_simultaneous_point() {
        for off in -6..=4_i64 {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = sh_pair(5, 3, 100 + off, 100, order);
                let want: Vec<(i64, i64)> = match off {
                    -4..=-1 => vec![(-off, 5)],
                    0 => vec![(0, 5)],
                    1..=2 => vec![(off, 3)],
                    _ => vec![],
                };
                assert_eq!(got, want, "$setuphold(5,3), data at ref{off:+} ({order:?})");
            }
        }
    }

    /// The simultaneous case is reported with the LARGER limit, whichever of
    /// the two it is.
    #[test]
    fn setuphold_simultaneous_events_report_the_larger_limit() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert_eq!(sh_pair(2, 7, 50, 50, order), [(0, 7)], "hold larger");
            assert_eq!(sh_pair(7, 2, 50, 50, order), [(0, 7)], "setup larger");
        }
    }

    /// The one place `$setuphold` differs from `$setup` + `$hold`: the data-first
    /// window includes its end, so with a ZERO hold limit a simultaneous pair
    /// still violates (through the setup window), where a `$setup` alone does
    /// not. And symmetrically a zero setup limit leaves the hold window's
    /// closed start. One zero limit empties only its own window.
    #[test]
    fn setuphold_with_one_zero_limit_keeps_only_the_other_window() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            // setup 5, hold 0: only (95, 100].
            for off in -6..=3_i64 {
                let got = sh_pair(5, 0, 100 + off, 100, order);
                let want: Vec<(i64, i64)> = match off {
                    -4..=-1 => vec![(-off, 5)],
                    0 => vec![(0, 5)],
                    _ => vec![],
                };
                assert_eq!(got, want, "$setuphold(5,0), off {off:+} ({order:?})");
            }
            // setup 0, hold 5: only [100, 105).
            for off in -3..=6_i64 {
                let got = sh_pair(0, 5, 100 + off, 100, order);
                let want: Vec<(i64, i64)> = match off {
                    0..=4 => vec![(off, 5)],
                    _ => vec![],
                };
                assert_eq!(got, want, "$setuphold(0,5), off {off:+} ({order:?})");
            }
        }
        // The `$setup` contrast, same events: no violation at the end point.
        assert!(pair(SETUP, 5, 100, 100, Order::DataFirst).is_empty());
        assert!(!sh_pair(5, 0, 100, 100, Order::DataFirst).is_empty());
    }

    /// Both limits zero: "the `$setuphold` check shall never issue a violation".
    #[test]
    fn setuphold_with_both_limits_zero_never_violates_through_the_state_machine() {
        for off in -3..=3_i64 {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                assert!(
                    sh_pair(0, 0, 100 + off, 100, order).is_empty(),
                    "off {off:+} ({order:?})"
                );
            }
        }
    }

    /// A simultaneous pair is ONE violation however the events are repeated or
    /// ordered, and the next instant's events are checked afresh.
    #[test]
    fn setuphold_simultaneous_pair_is_reported_exactly_once() {
        let v = |actual, limit| Violation { actual, limit };
        // data, reference, then the same two again within the step.
        let mut s = SetupHoldState::setuphold(5, 3);
        let mut got = Vec::new();
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        assert_eq!(got, [v(0, 5)], "data first");
        // reference, data, repeated.
        let mut s = SetupHoldState::setuphold(5, 3);
        let mut got = Vec::new();
        got.extend(s.reference_event(100));
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        got.extend(s.data_event(100));
        assert_eq!(got, [v(0, 5)], "reference first");
        // A later simultaneous pair is a new violation.
        got.extend(s.data_event(200));
        got.extend(s.reference_event(200));
        assert_eq!(got, [v(0, 5), v(0, 5)], "next instant");
    }

    /// An earlier data event still inside the setup window is found when
    /// another data event lands in the reference's own time step: that gives
    /// the setup violation AND the simultaneous one, in either order.
    #[test]
    fn setuphold_finds_the_earlier_data_event_beside_a_simultaneous_one() {
        let v = |actual, limit| Violation { actual, limit };
        let mut s = SetupHoldState::setuphold(5, 3);
        let mut got = Vec::new();
        got.extend(s.data_event(98));
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        assert_eq!(got, [v(2, 5), v(0, 5)], "data, data, reference");
        let mut s = SetupHoldState::setuphold(5, 3);
        let mut got = Vec::new();
        got.extend(s.data_event(98));
        got.extend(s.reference_event(100));
        got.extend(s.data_event(100));
        assert_eq!(got, [v(2, 5), v(0, 5)], "data, reference, data");
    }

    /// The hold window is measured from the MOST RECENT reference event, and a
    /// data event is flagged at most once even if a later reference event at its
    /// own instant would flag it again.
    #[test]
    fn setuphold_hold_window_uses_the_latest_reference_and_flags_once() {
        let v = |actual, limit| Violation { actual, limit };
        let mut s = SetupHoldState::setuphold(2, 5);
        assert!(s.reference_event(100).is_empty());
        assert!(s.reference_event(102).is_empty());
        // 106 is outside [100,105) but inside [102,107).
        assert_eq!(s.data_event(106), [v(4, 5)]);
        let mut s = SetupHoldState::setuphold(2, 5);
        assert!(s.reference_event(100).is_empty());
        assert_eq!(s.data_event(102), [v(2, 5)], "against the 100 edge");
        // Same data event, now at a same-time reference edge: already reported.
        assert!(s.reference_event(102).is_empty());
        // ...and 105, the end of the 100 window, is now measured from the 102
        // edge it follows (the most recent one): inside [102,107).
        assert_eq!(s.data_event(105), [v(3, 5)]);
        assert!(s.data_event(107).is_empty(), "end of the 102 window");
    }

    /// Nothing to check against before the other event has happened.
    #[test]
    fn setuphold_before_any_other_event_is_clean() {
        let mut s = SetupHoldState::setuphold(5, 3);
        assert!(s.data_event(3).is_empty(), "no reference event yet");
        let mut s = SetupHoldState::setuphold(5, 3);
        assert!(s.reference_event(3).is_empty(), "no data event yet");
    }

    /// LRM 31.3.3: for non-negative limits a `$setuphold` is "equivalent to"
    /// a `$setup` plus a `$hold`. Over thousands of generated event sequences
    /// (two same-time events in either order included), with both limits
    /// positive, `SetupHoldState` reports exactly what a `WindowState` `$setup`
    /// and a `WindowState` `$hold` report together, event by event -- the
    /// setup's separations first -- (the `$setup` omits the end point, but the
    /// pair's `$hold` flags that same simultaneous instant).
    #[test]
    fn setuphold_equals_setup_plus_hold_over_generated_sequences() {
        let mut x: u64 = 0x5eed_5eed_5eed_5eed;
        let mut next = move |n: u64| {
            x = x
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (x >> 33) % n
        };
        for case in 0..3000 {
            let setup = 1 + next(4) as i64;
            let hold = 1 + next(4) as i64;
            let mut both = SetupHoldState::setuphold(setup, hold);
            let mut su = WindowState::new(SETUP, setup);
            let mut ho = WindowState::new(HOLD, hold);
            let mut t = 100_i64;
            let mut trace = Vec::new();
            for _ in 0..14 {
                t += next(5) as i64;
                let is_data = next(2) == 0;
                trace.push((t, is_data));
                let got: Vec<i64> = if is_data {
                    both.data_event(t).iter().map(|v| v.actual).collect()
                } else {
                    both.reference_event(t).iter().map(|v| v.actual).collect()
                };
                let want: Vec<i64> = if is_data {
                    su.data_event(t)
                        .into_iter()
                        .chain(ho.data_event(t))
                        .collect()
                } else {
                    su.reference_event(t)
                        .into_iter()
                        .chain(ho.reference_event(t))
                        .collect()
                };
                assert_eq!(
                    got, want,
                    "case {case}: $setuphold({setup},{hold}) vs $setup+$hold after \
                     {trace:?} (time, is_data)"
                );
            }
        }
    }

    /// Feeds a reference event at `ref_t` and a data event at `data_t` to a
    /// `$recrem(.., rec, rem)` (the earlier first; at the same time, in
    /// `order`), returning every violation as `(actual, limit)`.
    fn rr_pair(rec: i64, rem: i64, data_t: i64, ref_t: i64, order: Order) -> Vec<(i64, i64)> {
        let mut s = SetupHoldState::recrem(rec, rem);
        let mut out = Vec::new();
        let data_first = match data_t.cmp(&ref_t) {
            std::cmp::Ordering::Less => true,
            std::cmp::Ordering::Greater => false,
            std::cmp::Ordering::Equal => matches!(order, Order::DataFirst),
        };
        if data_first {
            out.extend(s.data_event(data_t));
            out.extend(s.reference_event(ref_t));
        } else {
            out.extend(s.reference_event(ref_t));
            out.extend(s.data_event(data_t));
        }
        out.into_iter().map(|v| (v.actual, v.limit)).collect()
    }

    /// LRM 31.3.6 boundary sweep of `$recrem(.., recovery 3, removal 5)`, the
    /// reference event at 100 and the data event at every offset -7..=5, in both
    /// processing orders of a same-time pair:
    ///
    /// * data first, `(95, 100]`, sized by the REMOVAL limit (5): offsets
    ///   -4..=-1 violate; the begin (-5) does not; the END (0) does;
    /// * data second, `[100, 103)`, sized by the RECOVERY limit (3): offsets
    ///   1..=2 violate; the end (+3) does not.
    #[test]
    fn recrem_boundary_sweep_sizes_data_first_by_removal_and_data_second_by_recovery() {
        for off in -7..=5_i64 {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                let got = rr_pair(3, 5, 100 + off, 100, order);
                let want: Vec<(i64, i64)> = match off {
                    -4..=-1 => vec![(-off, 5)],
                    0 => vec![(0, 5)],
                    1..=2 => vec![(off, 3)],
                    _ => vec![],
                };
                assert_eq!(got, want, "$recrem(3,5), data at ref{off:+} ({order:?})");
            }
        }
    }

    /// The argument-order trap: `$recrem(.., a, b)` is `$setuphold(.., b, a)`,
    /// NOT `$setuphold(.., a, b)`. With unequal limits the two disagree on every
    /// offset where only one window reaches.
    #[test]
    fn recrem_is_setuphold_with_its_limits_the_other_way_round() {
        for off in -7..=7_i64 {
            for order in [Order::DataFirst, Order::ReferenceFirst] {
                assert_eq!(
                    rr_pair(3, 5, 100 + off, 100, order),
                    sh_pair(5, 3, 100 + off, 100, order),
                    "off {off:+} ({order:?})"
                );
            }
        }
        // The two are different checks: same arguments, different windows.
        assert_ne!(
            rr_pair(3, 5, 96, 100, Order::DataFirst),
            sh_pair(3, 5, 96, 100, Order::DataFirst),
            "a data event 4 ticks before the reference is inside removal 5, outside setup 3"
        );
    }

    /// A simultaneous pair is reported once, with the LARGER of the two limits,
    /// whichever of recovery and removal it is.
    #[test]
    fn recrem_simultaneous_events_report_the_larger_limit_once() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            assert_eq!(rr_pair(2, 7, 50, 50, order), [(0, 7)], "removal larger");
            assert_eq!(rr_pair(7, 2, 50, 50, order), [(0, 7)], "recovery larger");
        }
        let mut s = SetupHoldState::recrem(3, 5);
        let mut got = Vec::new();
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        got.extend(s.data_event(100));
        got.extend(s.reference_event(100));
        assert_eq!(
            got,
            [Violation {
                actual: 0,
                limit: 5
            }],
            "once"
        );
    }

    /// One zero limit empties only its own window; both zero never violates
    /// (LRM 31.3.6: "the `$recrem` check shall never issue a violation").
    #[test]
    fn recrem_with_a_zero_limit_keeps_only_the_other_window() {
        for order in [Order::DataFirst, Order::ReferenceFirst] {
            // recovery 4, removal 0: only [100, 104).
            for off in -3..=6_i64 {
                let want: Vec<(i64, i64)> = match off {
                    0..=3 => vec![(off, 4)],
                    _ => vec![],
                };
                assert_eq!(
                    rr_pair(4, 0, 100 + off, 100, order),
                    want,
                    "rec 4 rem 0, {off:+}"
                );
            }
            // recovery 0, removal 4: only (96, 100].
            for off in -6..=3_i64 {
                let want: Vec<(i64, i64)> = match off {
                    -3..=-1 => vec![(-off, 4)],
                    0 => vec![(0, 4)],
                    _ => vec![],
                };
                assert_eq!(
                    rr_pair(0, 4, 100 + off, 100, order),
                    want,
                    "rec 0 rem 4, {off:+}"
                );
            }
            for off in -3..=3_i64 {
                assert!(
                    rr_pair(0, 0, 100 + off, 100, order).is_empty(),
                    "rec 0 rem 0, {off:+} ({order:?})"
                );
            }
        }
    }

    /// LRM 31.3.6: with non-negative limits `$recrem(ref, data, tREC, tREM)` is
    /// "equivalent to" `$removal(ref, data, tREM)` plus `$recovery(ref, data,
    /// tREC)`. Over thousands of generated event sequences (same-time events in
    /// either order included) with both limits positive, the single machine
    /// reports exactly what the `$removal` and `$recovery` `WindowState`s report
    /// together (the `$removal` omits its end point; the pair's `$recovery`
    /// flags that same simultaneous instant).
    #[test]
    fn recrem_equals_removal_plus_recovery_over_generated_sequences() {
        let mut x: u64 = 0x7e57_7e57_7e57_7e57;
        let mut next = move |n: u64| {
            x = x
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (x >> 33) % n
        };
        for case in 0..3000 {
            let rec = 1 + next(4) as i64;
            let rem = 1 + next(4) as i64;
            let mut both = SetupHoldState::recrem(rec, rem);
            let mut re = WindowState::new(REMOVAL, rem);
            let mut rc = WindowState::new(RECOVERY, rec);
            let mut t = 100_i64;
            let mut trace = Vec::new();
            for _ in 0..14 {
                t += next(5) as i64;
                let is_data = next(2) == 0;
                trace.push((t, is_data));
                let mut got: Vec<i64> = if is_data {
                    both.data_event(t).iter().map(|v| v.actual).collect()
                } else {
                    both.reference_event(t).iter().map(|v| v.actual).collect()
                };
                let mut want: Vec<i64> = if is_data {
                    re.data_event(t)
                        .into_iter()
                        .chain(rc.data_event(t))
                        .collect()
                } else {
                    re.reference_event(t)
                        .into_iter()
                        .chain(rc.reference_event(t))
                        .collect()
                };
                got.sort_unstable();
                want.sort_unstable();
                assert_eq!(
                    got, want,
                    "case {case}: $recrem({rec},{rem}) vs $removal+$recovery after {trace:?} \
                     (time, is_data)"
                );
            }
        }
    }

    /// With no condition at all (every event has both roles) the split machine is the one
    /// `$setuphold` machine, including at simultaneous events (data event delivered first).
    #[test]
    fn split_setuphold_without_conditions_equals_the_single_machine() {
        let mut x: u64 = 0x5917_5917_5917_5917;
        let mut next = move |n: u64| {
            x = x
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (x >> 33) % n
        };
        for case in 0..3000 {
            let setup = 1 + next(4) as i64;
            let hold = 1 + next(4) as i64;
            let mut one = SetupHoldState::new(setup, hold);
            let mut split = SplitSetupHold::new(setup, hold);
            let mut t = 100_i64;
            let mut trace = Vec::new();
            for _ in 0..14 {
                t += next(4) as i64;
                let (d, r) = match next(3) {
                    0 => (true, false),
                    1 => (false, true),
                    _ => (true, true),
                };
                trace.push((t, d, r));
                let mut want = Vec::new();
                if d {
                    want.extend(one.data_event(t));
                }
                if r {
                    want.extend(one.reference_event(t));
                }
                let mut got = split.deliver(t, d.then_some(Roles::BOTH), r.then_some(Roles::BOTH));
                got.sort_by_key(|v| (v.actual, v.limit));
                want.sort_by_key(|v| (v.actual, v.limit));
                assert_eq!(
                    got, want,
                    "case {case}: ({setup},{hold}) after {trace:?} (time, data, reference)"
                );
            }
        }
    }

    /// Roles pick the window an event takes part in (LRM 31.9.2's `$setup` + `$hold`): a data
    /// event that is no timestamp starts no setup window, one that is no timecheck ends no
    /// hold window; the reference event the other way round.
    #[test]
    fn split_setuphold_roles_select_the_window() {
        let ts = Roles {
            timestamp: true,
            timecheck: false,
        };
        let tc = Roles {
            timestamp: false,
            timecheck: true,
        };
        let none = Roles {
            timestamp: false,
            timecheck: false,
        };
        let sorted = |mut v: Vec<Violation>| {
            v.sort_by_key(|v| (v.actual, v.limit));
            v
        };
        // Setup window: data (timestamp) at 100, reference (timecheck) at 102, limit 3.
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(100, Some(ts), None).is_empty());
        assert_eq!(
            s.deliver(102, None, Some(tc)),
            [Violation {
                actual: 2,
                limit: 3
            }]
        );
        // The data event was not a timestamp: nothing to violate.
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(100, Some(tc), None).is_empty());
        assert!(s.deliver(102, None, Some(tc)).is_empty());
        // The reference event was not a timecheck.
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(100, Some(ts), None).is_empty());
        assert!(s.deliver(102, None, Some(ts)).is_empty());
        // Hold window: reference (timestamp) at 200, data (timecheck) at 204, limit 5.
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(200, None, Some(ts)).is_empty());
        assert_eq!(
            s.deliver(204, Some(tc), None),
            [Violation {
                actual: 4,
                limit: 5
            }]
        );
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(200, None, Some(tc)).is_empty());
        assert!(s.deliver(204, Some(tc), None).is_empty());
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(200, None, Some(ts)).is_empty());
        assert!(s.deliver(204, Some(ts), None).is_empty());
        // An event with neither role is no event.
        let mut s = SplitSetupHold::new(3, 5);
        assert!(s.deliver(300, Some(none), None).is_empty());
        assert!(s.deliver(301, None, Some(none)).is_empty());
        // Simultaneous events, both roles: ONE violation, the larger limit.
        let mut s = SplitSetupHold::new(3, 5);
        assert_eq!(
            sorted(s.deliver(400, Some(Roles::BOTH), Some(Roles::BOTH))),
            [Violation {
                actual: 0,
                limit: 5
            }]
        );
    }

    /// `event_occurred`: an edge-controlled vector terminal is its LSB's edge
    /// (LRM 9.4.2 / 31.7), a terminal with no edge control is ANY bit changing
    /// (31.8: one event for the whole vector).
    #[test]
    fn event_occurred_reads_a_vector_edge_at_the_lsb_and_a_plain_change_at_any_bit() {
        use Bit4::{One as I, Zero as O};
        let pos = control(sv_lang::EdgeKind::PosEdge, &[]);
        assert!(event_occurred(pos, &[O, O], &[I, O]), "LSB rises");
        assert!(!event_occurred(pos, &[O, O], &[O, I]), "only the MSB rises");
        assert!(!event_occurred(pos, &[I, O], &[O, O]), "LSB falls");
        let any = EdgeControl::AnyChange;
        assert!(event_occurred(any, &[O, O], &[O, I]), "any bit");
        assert!(
            event_occurred(any, &[O, O], &[I, I]),
            "two bits, still one event"
        );
        assert!(!event_occurred(any, &[I, O], &[I, O]), "no change");
    }

    // -- End to end through `run_design` ------------------------------------

    /// Runs `src` through the real pipeline and returns its stdout, with negative timing checks
    /// enabled (LRM 31.9.4; they are off by default and change nothing for a positive limit).
    fn run_src(tag: &str, src: &str) -> String {
        run_src_with(tag, src, negative_on())
    }

    /// A design with one check and a notifier watcher; `stim` is the body of
    /// `top`'s `initial` block (after a `#100` so nothing sits at time 0).
    fn check_design(check: &str, stim: &str) -> String {
        format!(
            "module chk(input clk, input d);\n  reg ntf;\n  specify\n    {check}\n  endspecify\n  \
             always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\nmodule top;\n  \
             reg clk, d;\n  chk u(.clk(clk), .d(d));\n  initial begin\n    clk = 0; d = 0;\n    \
             #100;\n    {stim}\n    #100 $finish;\n  end\nendmodule\n"
        )
    }

    fn violations(stdout: &str) -> Vec<&str> {
        stdout.lines().filter(|l| l.contains("violation")).collect()
    }

    /// `$setup(d, posedge clk, 5, ntf)`: the exact output for one violating
    /// stimulus (data at 97, edge at 100: actual 3 < limit 5), pinning the
    /// notifier toggle (x -> 0, Table 31-13) and the documented message format.
    #[test]
    fn run_design_setup_violation_toggles_the_notifier_and_prints_the_message() {
        let stdout = run_src(
            "setup-exact",
            &check_design(
                "$setup(d, posedge clk, 5, ntf);",
                "#97 d = 1;\n    #3 clk = 1;",
            ),
        );
        assert_eq!(
            stdout,
            "ntf=0 at 200\n200: $setup violation: data top.u.d vs reference top.u.clk, limit=5, \
             actual=3\n"
        );
    }

    /// `$setup` end to end: offsets of the data edge before the clock edge,
    /// the violation region is open at both ends.
    #[test]
    fn run_design_setup_sweep_is_open_at_both_ends() {
        // data changes `off` before the clock edge; limit 5.
        for (off, want) in [(6, 0), (5, 0), (4, 1), (1, 1), (0, 0)] {
            let stim = if off == 0 {
                "d = 1; clk = 1;".to_string()
            } else {
                format!("d = 1;\n    #{off} clk = 1;")
            };
            let stdout = run_src(
                &format!("setup-sweep-{off}"),
                &check_design("$setup(d, posedge clk, 5, ntf);", &stim),
            );
            assert_eq!(violations(&stdout).len(), want, "offset {off}:\n{stdout}");
            assert_eq!(stdout.contains("ntf="), want == 1, "notifier, offset {off}");
        }
    }

    /// `$hold` end to end: the data edge `off` AFTER the clock edge; the
    /// region is closed at the start (offset 0, the same instant) and open at
    /// the end.
    #[test]
    fn run_design_hold_sweep_is_closed_at_the_start_and_open_at_the_end() {
        for (off, want) in [(0, 1), (1, 1), (4, 1), (5, 0), (6, 0)] {
            let stim = if off == 0 {
                "clk = 1; d = 1;".to_string()
            } else {
                format!("clk = 1;\n    #{off} d = 1;")
            };
            let stdout = run_src(
                &format!("hold-sweep-{off}"),
                &check_design("$hold(posedge clk, d, 5, ntf);", &stim),
            );
            assert_eq!(violations(&stdout).len(), want, "offset {off}:\n{stdout}");
            assert_eq!(stdout.contains("ntf="), want == 1, "notifier, offset {off}");
        }
    }

    /// A zero limit never violates, even with both edges in one instant.
    #[test]
    fn run_design_a_zero_limit_never_violates() {
        for check in [
            "$setup(d, posedge clk, 0, ntf);",
            "$hold(posedge clk, d, 0, ntf);",
        ] {
            let stdout = run_src("zero", &check_design(check, "d = 1; clk = 1;"));
            assert!(violations(&stdout).is_empty(), "{check}:\n{stdout}");
            assert!(!stdout.contains("ntf="), "{check}:\n{stdout}");
        }
    }

    /// A check with no notifier still reports (and nothing else breaks).
    #[test]
    fn run_design_a_check_without_a_notifier_still_reports() {
        let stdout = run_src(
            "no-ntf",
            &check_design("$setup(d, posedge clk, 5);", "#97 d = 1;\n    #3 clk = 1;"),
        );
        assert_eq!(violations(&stdout).len(), 1, "{stdout}");
        assert!(!stdout.contains("ntf="));
    }

    /// LRM 31.7: the check is only performed while the `&&&` condition holds
    /// -- a reference event while it is low does nothing, the same stimulus
    /// with it high violates. A data event's own condition gates the data
    /// event the same way.
    #[test]
    fn run_design_a_condition_gates_the_reference_and_the_data_event() {
        let src = |en: u32, den: u32| {
            format!(
                "module chk(input clk, input d, input en, input den);\n  reg ntf;\n  specify\n    \
                 $setup(d &&& den, posedge clk &&& en, 5, ntf);\n  endspecify\nendmodule\n\
                 module top;\n  reg clk, d, en, den;\n  chk u(.clk(clk), .d(d), .en(en), \
                 .den(den));\n  initial begin\n    clk = 0; d = 0; en = {en}; den = {den};\n    \
                 #100 d = 1;\n    #3 clk = 1;\n    #10 $finish;\n  end\nendmodule\n"
            )
        };
        assert_eq!(violations(&run_src("cond-11", &src(1, 1))).len(), 1);
        assert!(
            violations(&run_src("cond-01", &src(0, 1))).is_empty(),
            "reference gated"
        );
        assert!(
            violations(&run_src("cond-10", &src(1, 0))).is_empty(),
            "data gated"
        );
    }

    /// LRM 31.8: a vector data terminal changing in several bits at once is
    /// ONE event, so one violation, not one per bit.
    #[test]
    fn run_design_a_vector_terminal_changing_in_many_bits_is_one_event() {
        let src = "module chk(input clk, input [3:0] d);\n  reg ntf;\n  specify\n    $setup(d, \
                   posedge clk, 5, ntf);\n  endspecify\nendmodule\nmodule top;\n  reg clk;\n  \
                   reg [3:0] d;\n  chk u(.clk(clk), .d(d));\n  initial begin\n    clk = 0; \
                   d = 0;\n    #100 d = 4'b1111;\n    #3 clk = 1;\n    #10 $finish;\n  \
                   end\nendmodule\n";
        assert_eq!(violations(&run_src("vec", src)).len(), 1);
    }

    /// Two instances of one module each carry their own check state: only the
    /// instance whose own data edge is too close to ITS clock violates.
    #[test]
    fn run_design_each_instance_has_its_own_check_state() {
        let src = "module chk(input clk, input d);\n  specify\n    $setup(d, posedge clk, 5);\n  \
                   endspecify\nendmodule\nmodule top;\n  reg clk1, d1, clk2, d2;\n  chk \
                   a(.clk(clk1), .d(d1));\n  chk b(.clk(clk2), .d(d2));\n  initial begin\n    \
                   clk1 = 0; d1 = 0; clk2 = 0; d2 = 0;\n    #100 d1 = 1; d2 = 1;\n    #3 clk1 \
                   = 1;\n    #20 clk2 = 1;\n    #10 $finish;\n  end\nendmodule\n";
        let stdout = run_src("two-inst", src);
        let v = violations(&stdout);
        assert_eq!(v.len(), 1, "{stdout}");
        assert!(
            v[0].contains("top.a") || v[0].contains(".a."),
            "instance a: {}",
            v[0]
        );
    }

    // -----------------------------------------------------------------------
    // T16, LRM 31.3.3: `$setuphold` end to end.

    /// The violation lines of `$setuphold(posedge clk, d, setup, hold, ntf)`
    /// for `stim` (the body of `top`'s `initial` block after a `#100`).
    fn sh_violations(setup: i64, hold: i64, stim: &str, tag: &str) -> Vec<String> {
        let stdout = run_src(
            tag,
            &check_design(
                &format!("$setuphold(posedge clk, d, {setup}, {hold}, ntf);"),
                stim,
            ),
        );
        violations(&stdout).iter().map(|l| l.to_string()).collect()
    }

    /// Data `off` BEFORE the clock edge (data event first); setup 5, hold 3.
    /// LRM 31.3.3: `begin < t_data <= end` with `begin = t_clk - 5`, `end =
    /// t_clk` -- the START is excluded, the END (offset 0, simultaneous) IS a
    /// violation, so the sweep is NOT the `$setup` one (whose end is open).
    #[test]
    fn run_design_setuphold_data_first_window_is_open_at_the_start_closed_at_the_end() {
        for (off, want) in [(7, 0), (6, 0), (5, 0), (4, 1), (1, 1), (0, 1)] {
            let stim = if off == 0 {
                "d = 1; clk = 1;".to_string()
            } else {
                format!("d = 1;\n    #{off} clk = 1;")
            };
            let v = sh_violations(5, 3, &stim, &format!("sh-first-{off}"));
            assert_eq!(v.len(), want, "data {off} before the edge: {v:?}");
            if want == 1 {
                // Offset 0 is the simultaneous case: the larger limit (5).
                assert!(
                    v[0].ends_with(&format!("limit=5, actual={off}")),
                    "{}",
                    v[0]
                );
            }
        }
    }

    /// Data `off` AFTER the clock edge (data event second); setup 5, hold 3.
    /// `begin <= t_data < end` with `begin = t_clk`, `end = t_clk + 3`: the
    /// start (simultaneous) IS a violation, the END is not.
    #[test]
    fn run_design_setuphold_data_second_window_is_closed_at_the_start_open_at_the_end() {
        for (off, want) in [(0, 1), (1, 1), (2, 1), (3, 0), (4, 0)] {
            let stim = if off == 0 {
                "clk = 1; d = 1;".to_string()
            } else {
                format!("clk = 1;\n    #{off} d = 1;")
            };
            let v = sh_violations(5, 3, &stim, &format!("sh-second-{off}"));
            assert_eq!(v.len(), want, "data {off} after the edge: {v:?}");
            if want == 1 && off != 0 {
                assert!(
                    v[0].ends_with(&format!("limit=3, actual={off}")),
                    "{}",
                    v[0]
                );
            }
        }
    }

    /// The exact output of one violation of each window: the message names
    /// `$setuphold`, carries the violated window's own limit, and the notifier
    /// toggles x -> 0 -> 1 (Table 31-13).
    #[test]
    fn run_design_setuphold_reports_the_violated_windows_limit_and_toggles_the_notifier() {
        let stdout = run_src(
            "sh-exact",
            &check_design(
                "$setuphold(posedge clk, d, 5, 3, ntf);",
                "#97 d = 1;\n    #3 clk = 1;\n    #1 d = 0;",
            ),
        );
        assert_eq!(
            stdout,
            "ntf=0 at 200\n200: $setuphold violation: data top.u.d vs reference top.u.clk, \
             limit=5, actual=3\nntf=1 at 201\n201: $setuphold violation: data top.u.d vs \
             reference top.u.clk, limit=3, actual=1\n"
        );
    }

    /// LRM 31.3.3: "When both limits are zero, the `$setuphold` check shall
    /// never issue a violation" -- not even for simultaneous events.
    #[test]
    fn run_design_setuphold_with_both_limits_zero_never_violates() {
        for stim in [
            "d = 1; clk = 1;",
            "clk = 1; d = 1;",
            "d = 1;\n    #1 clk = 1;",
            "clk = 1;\n    #1 d = 1;",
        ] {
            let stdout = run_src(
                "sh-zero",
                &check_design("$setuphold(posedge clk, d, 0, 0, ntf);", stim),
            );
            assert!(violations(&stdout).is_empty(), "{stim}:\n{stdout}");
            assert!(!stdout.contains("ntf="), "{stim}:\n{stdout}");
        }
    }

    /// A single zero limit: that side's window is empty (a zero-limit `$setup`
    /// or `$hold` never violates), but simultaneous events still violate (both
    /// windows' own text says so) while the other limit is positive.
    #[test]
    fn run_design_setuphold_with_one_zero_limit_keeps_only_the_other_window() {
        // setup 0, hold 3.
        assert!(sh_violations(0, 3, "d = 1;\n    #1 clk = 1;", "sh-s0-first").is_empty());
        assert_eq!(
            sh_violations(0, 3, "clk = 1;\n    #1 d = 1;", "sh-s0-second").len(),
            1
        );
        assert_eq!(
            sh_violations(0, 3, "clk = 1; d = 1;", "sh-s0-simul").len(),
            1
        );
        // setup 5, hold 0.
        assert_eq!(
            sh_violations(5, 0, "d = 1;\n    #1 clk = 1;", "sh-h0-first").len(),
            1
        );
        assert!(sh_violations(5, 0, "clk = 1;\n    #1 d = 1;", "sh-h0-second").is_empty());
        assert_eq!(
            sh_violations(5, 0, "clk = 1; d = 1;", "sh-h0-simul").len(),
            1
        );
    }

    /// 31.3.3: "`$setuphold(posedge clk, data, tSU, tHLD)` is equivalent in
    /// functionality to `$setup(data, posedge clk, tSU); $hold(posedge clk,
    /// data, tHLD)`, if tSU and tHLD are not negative" -- one instance with
    /// the one check and one with the pair, on the same stimulus, report the
    /// same violations at the same times with the same separations. (The
    /// stimulus is T15's setup/hold boundary walk, simultaneous event
    /// included: with a positive hold limit `$hold` reports it too.)
    #[test]
    fn run_design_setuphold_is_equivalent_to_a_setup_plus_hold_pair() {
        let src = "module one(input clk, input d);\n  specify\n    $setuphold(posedge clk, d, 3, \
                   2);\n  endspecify\nendmodule\nmodule two(input clk, input d);\n  specify\n    \
                   $setup(d, posedge clk, 3);\n    $hold(posedge clk, d, 2);\n  endspecify\n\
                   endmodule\nmodule top;\n  reg clk, d;\n  one a(.clk(clk), .d(d));\n  two \
                   b(.clk(clk), .d(d));\n  initial begin\n    clk = 0; d = 0;\n    #10 d = 1;\n    \
                   #2 clk = 1;\n    #10 clk = 0;\n    #1 d = 0;\n    #7 d = 1;\n    #3 clk = 1;\n    \
                   #1 d = 0;\n    #5 clk = 0;\n    #1 d = 1;\n    #5 clk = 1;\n    #2 d = 0;\n    \
                   #1 clk = 0;\n    #4 begin clk = 1; d = 1; end\n    #20 $finish;\n  end\n\
                   endmodule\n";
        let stdout = run_src("sh-equiv", src);
        // `<now>: <check> violation: data <d> vs reference <clk>, limit=L, actual=A`
        let key = |l: &str| {
            let now = l.split(':').next().unwrap_or("").to_string();
            let actual = l.rsplit("actual=").next().unwrap_or("").to_string();
            (now, actual)
        };
        let of = |inst: &str| -> Vec<(String, String)> {
            violations(&stdout)
                .into_iter()
                .filter(|l| l.contains(&format!("top.{inst}.")))
                .map(key)
                .collect()
        };
        let one = of("a");
        let two = of("b");
        assert_eq!(one.len(), 3, "{stdout}");
        assert_eq!(one, two, "{stdout}");
    }

    /// Where `$setuphold` and a separate `$setup` DO differ (LRM 31.3.3's own
    /// text): the data-first window includes its end, so with no hold limit a
    /// simultaneous reference and data event is a `$setuphold` violation but
    /// not a `$setup` one.
    #[test]
    fn run_design_setuphold_is_closed_at_its_setup_end_where_setup_is_open() {
        let both = |check: &str| {
            let stdout = run_src("sh-vs-setup", &check_design(check, "d = 1; clk = 1;"));
            violations(&stdout).len()
        };
        assert_eq!(both("$setuphold(posedge clk, d, 5, 0, ntf);"), 1);
        assert_eq!(both("$setup(d, posedge clk, 5, ntf);"), 0);
    }

    /// A reference event's `&&&` condition gates the check, as for `$setup`.
    #[test]
    fn run_design_setuphold_conditions_gate_the_reference_and_the_data_event() {
        let src = |en: u32, den: u32| {
            format!(
                "module chk(input clk, input d, input en, input den);\n  reg ntf;\n  specify\n    \
                 $setuphold(posedge clk &&& en, d &&& den, 5, 3, ntf);\n  endspecify\nendmodule\n\
                 module top;\n  reg clk, d, en, den;\n  chk u(.clk(clk), .d(d), .en(en), \
                 .den(den));\n  initial begin\n    clk = 0; d = 0; en = {en}; den = {den};\n    \
                 #100 d = 1;\n    #3 clk = 1;\n    #10 $finish;\n  end\nendmodule\n"
            )
        };
        assert_eq!(violations(&run_src("shc-11", &src(1, 1))).len(), 1);
        assert!(violations(&run_src("shc-01", &src(0, 1))).is_empty());
        assert!(violations(&run_src("shc-10", &src(1, 0))).is_empty());
    }

    /// LRM 31.8: a vector data terminal changing in many bits at once is one
    /// event, one violation.
    #[test]
    fn run_design_setuphold_vector_terminal_is_one_event() {
        let src = "module chk(input clk, input [3:0] d);\n  specify\n    $setuphold(posedge clk, d, \
                   5, 3);\n  endspecify\nendmodule\nmodule top;\n  reg clk;\n  reg [3:0] d;\n  chk \
                   u(.clk(clk), .d(d));\n  initial begin\n    clk = 0; d = 0;\n    #100 d = \
                   4'b1111;\n    #3 clk = 1;\n    #10 $finish;\n  end\nendmodule\n";
        assert_eq!(violations(&run_src("sh-vec", src)).len(), 1);
    }

    /// Runs `src` and returns the error text of a failing run.
    fn run_src_err(tag: &str, src: &str) -> String {
        let file = std::env::temp_dir().join(format!("vj-sdf-t16-{tag}-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let r = crate::run::run_design(&file, &mut out);
        let _ = std::fs::remove_file(&file);
        match r {
            Ok(code) => panic!("expected an error, run finished with {code}:\n{out:?}"),
            Err(e) => e.to_string(),
        }
    }

    /// One `$setuphold` / `$recrem` with a condition net `c`, driven so the FIRST of the two
    /// events sees `c = x` and the SECOND sees `c = y` (`c` flips in between), two ticks
    /// apart. Returns the number of violations.
    fn cond_gate(check: &str, first: &str, second: &str, x: u8, y: u8, tag: &str) -> usize {
        let src = format!(
            "module chk(input clk, input d, input c);\n  reg ntf;\n  specify\n    {check}\n  \
             endspecify\nendmodule\nmodule top;\n  reg clk, d, c;\n  chk u(.clk(clk), .d(d), \
             .c(c));\n  initial begin\n    clk = 0; d = 0; c = 0;\n    #100 c = {x};\n    #1 \
             {first} = 1;\n    #1 c = {y};\n    #1 {second} = 1;\n    #100 $finish;\n  end\n\
             endmodule\n"
        );
        violations(&run_src(tag, &src)).len()
    }

    /// For POSITIVE limits a `$setuphold`'s timestamp and timecheck conditions follow the
    /// `$setup` + `$hold` equivalence of LRM 31.9.2: in each window the first event is the
    /// timestamp event and the second the timecheck event, so `timestamp_condition` gates
    /// the first event's value of `c` and `timecheck_condition` the second's -- whichever of
    /// `clk` / `d` that is.
    #[test]
    fn run_design_setuphold_conditions_gate_each_window_by_event_order() {
        // (first event, second event): data first is the setup window, the clock first the
        // hold window.
        for (order, first, second) in [("setup", "d", "clk"), ("hold", "clk", "d")] {
            for (what, check, wants) in [
                (
                    "ts",
                    "$setuphold(posedge clk, d, 3, 3, ntf, c);",
                    (true, false),
                ),
                (
                    "tc",
                    "$setuphold(posedge clk, d, 3, 3, ntf, , c);",
                    (false, true),
                ),
                (
                    "both",
                    "$setuphold(posedge clk, d, 3, 3, ntf, c, c);",
                    (true, true),
                ),
            ] {
                for x in 0..2u8 {
                    for y in 0..2u8 {
                        let want = (!wants.0 || x == 1) && (!wants.1 || y == 1);
                        let n = cond_gate(
                            check,
                            first,
                            second,
                            x,
                            y,
                            &format!("shc-{order}-{what}-{x}{y}"),
                        );
                        assert_eq!(n, usize::from(want), "{order} {what} c={x}->{y}");
                    }
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // T23a, LRM 31.9.1: negative limits, delayed signals and the delay solve, end to end.

    /// The violation lines of `$setuphold(posedge clk, d, <limits>, ntf)` under the stimulus
    /// `stim` (run at time 100 of `check_design`).
    fn nt_violations(limits: &str, stim: &str, tag: &str) -> Vec<String> {
        let check = format!("$setuphold(posedge clk, d, {limits}, ntf);");
        let stdout = run_src(tag, &check_design(&check, stim));
        violations(&stdout).iter().map(|l| l.to_string()).collect()
    }

    /// 31.9.1 Example 1, `$setuphold(posedge CLK, DATA, -10, 20)`: the window is the data
    /// changing between 10 and 20 after the clock edge, "exclusive of the end points". The
    /// check is evaluated on the delayed clock (10 + 1 tick late), so the violation is
    /// reported when the data change arrives, against the adjusted limits (setup 1, hold 9).
    #[test]
    fn run_design_negative_setup_window_is_shifted_after_the_edge() {
        let limits = "-10, 20";
        for (off, violates) in [
            (1, false),
            (5, false),
            (9, false),
            (10, false),
            (11, true),
            (15, true),
            (19, true),
            (20, false),
            (21, false),
            (30, false),
        ] {
            let v = nt_violations(
                limits,
                &format!("clk = 1;\n    #{off} d = 1;"),
                &format!("nt-setup-{off}"),
            );
            assert_eq!(
                v.len(),
                usize::from(violates),
                "data {off} after clk: {v:?}"
            );
        }
        let v = nt_violations(limits, "clk = 1;\n    #15 d = 1;", "nt-setup-exact");
        assert_eq!(
            v,
            ["115: $setuphold violation: data top.u.d vs reference top.u.clk, limit=9, actual=4"]
        );
    }

    /// The negative HOLD mirror: `$setuphold(posedge clk, d, 20, -10)` is the data changing
    /// between 20 and 10 BEFORE the edge. The data is the delayed signal, so the violation is
    /// reported when the clock edge arrives.
    #[test]
    fn run_design_negative_hold_window_is_shifted_before_the_edge() {
        let limits = "20, -10";
        for (off, violates) in [
            (1, false),
            (9, false),
            (10, false),
            (11, true),
            (15, true),
            (19, true),
            (20, false),
            (25, false),
        ] {
            let v = nt_violations(
                limits,
                &format!("d = 1;\n    #{off} clk = 1;"),
                &format!("nt-hold-{off}"),
            );
            assert_eq!(
                v.len(),
                usize::from(violates),
                "data {off} before clk: {v:?}"
            );
        }
        let v = nt_violations(limits, "d = 1;\n    #15 clk = 1;", "nt-hold-exact");
        assert_eq!(
            v,
            ["115: $setuphold violation: data top.u.d vs reference top.u.clk, limit=9, actual=4"]
        );
    }

    // -----------------------------------------------------------------------
    // T17, LRM 31.3.4 / 31.3.5: `$removal` / `$recovery` end to end. The
    // reference event is `rst` and the data event `clk` throughout (the usual
    // roles: "a control signal like clear, reset, or set" and "a clock signal").

    /// A design with one reset/clock check and a notifier watcher; `stim` is
    /// the body of `top`'s `initial` block after a `#100`.
    fn rr_design(check: &str, stim: &str) -> String {
        format!(
            "module chk(input rst, input clk);\n  reg ntf;\n  specify\n    {check}\n  endspecify\n  \
             always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\nmodule top;\n  \
             reg rst, clk;\n  chk u(.rst(rst), .clk(clk));\n  initial begin\n    rst = 0; clk = 0;\n    \
             #100;\n    {stim}\n    #100 $finish;\n  end\nendmodule\n"
        )
    }

    /// The violation lines of `check` under `stim`.
    fn rr_violations(check: &str, stim: &str, tag: &str) -> Vec<String> {
        let stdout = run_src(tag, &rr_design(check, stim));
        violations(&stdout).iter().map(|l| l.to_string()).collect()
    }

    /// `$removal(posedge rst, posedge clk, 5, ntf)` with the clock edge 3 before
    /// the reset release (inside the window): the exact output, pinning the
    /// roles (the line names the clock as the DATA terminal and the reset as the
    /// REFERENCE), the notifier toggle (x -> 0, Table 31-13) and the format.
    #[test]
    fn run_design_removal_violation_prints_the_message_and_toggles_the_notifier() {
        let stdout = run_src(
            "rem-exact",
            &rr_design(
                "$removal(posedge rst, posedge clk, 5, ntf);",
                "clk = 1;\n    #3 rst = 1;\n    #1 clk = 0;\n    #1 clk = 1;\n    #1 rst = 0;\n    #1 rst = 1;",
            ),
        );
        // clk@100 then rst@103 (actual 3); the next clk edge @105 is after the
        // release at 103 (no removal window holds it); the second release @107
        // sees clk@105 two before it (actual 2): a second violation, ntf 0 -> 1.
        assert_eq!(
            stdout,
            "ntf=0 at 103\n103: $removal violation: data top.u.clk vs reference top.u.rst, \
             limit=5, actual=3\nntf=1 at 107\n107: $removal violation: data top.u.clk vs reference \
             top.u.rst, limit=5, actual=2\n"
        );
    }

    /// `$recovery(posedge rst, posedge clk, 5, ntf)`: reset release at 100, the
    /// clock edge 3 after it.
    #[test]
    fn run_design_recovery_violation_prints_the_message_and_toggles_the_notifier() {
        let stdout = run_src(
            "rec-exact",
            &rr_design(
                "$recovery(posedge rst, posedge clk, 5, ntf);",
                "rst = 1;\n    #3 clk = 1;\n    #1 clk = 0;\n    #1 clk = 1;",
            ),
        );
        // clk@103 is 3 after the release (actual 3); clk@105 is 5 after it: the
        // window's END, no violation.
        assert_eq!(
            stdout,
            "ntf=0 at 103\n103: $recovery violation: data top.u.clk vs reference top.u.rst, \
             limit=5, actual=3\n"
        );
    }

    /// `$removal` end to end: the reset release `off` AFTER the clock edge; the
    /// region is open at both ends, so neither the exact end point (offset 0,
    /// either order of the two assignments) nor the begin point (offset 5) is a
    /// violation.
    #[test]
    fn run_design_removal_sweep_is_open_at_both_ends() {
        let check = "$removal(posedge rst, posedge clk, 5, ntf);";
        for (off, want) in [(6, 0), (5, 0), (4, 1), (1, 1)] {
            let v = rr_violations(
                check,
                &format!("clk = 1;\n    #{off} rst = 1;"),
                &format!("rem-sweep-{off}"),
            );
            assert_eq!(v.len(), want, "clk {off} before the release: {v:?}");
            if want == 1 {
                assert!(v[0].ends_with(&format!("limit=5, actual={off}")), "{v:?}");
            }
        }
        for (stim, tag) in [
            ("clk = 1; rst = 1;", "rem-simul-a"),
            ("rst = 1; clk = 1;", "rem-simul-b"),
        ] {
            let v = rr_violations(check, stim, tag);
            assert!(
                v.is_empty(),
                "{stim}: the end point is not a violation: {v:?}"
            );
        }
    }

    /// `$recovery` end to end: the clock edge `off` AFTER the reset release; the
    /// region is closed at the start (offset 0, either order) and open at the end.
    #[test]
    fn run_design_recovery_sweep_is_closed_at_the_start_and_open_at_the_end() {
        let check = "$recovery(posedge rst, posedge clk, 5, ntf);";
        for (off, want) in [(1, 1), (4, 1), (5, 0), (6, 0)] {
            let v = rr_violations(
                check,
                &format!("rst = 1;\n    #{off} clk = 1;"),
                &format!("rec-sweep-{off}"),
            );
            assert_eq!(v.len(), want, "clk {off} after the release: {v:?}");
            if want == 1 {
                assert!(v[0].ends_with(&format!("limit=5, actual={off}")), "{v:?}");
            }
        }
        for (stim, tag) in [
            ("rst = 1; clk = 1;", "rec-simul-a"),
            ("clk = 1; rst = 1;", "rec-simul-b"),
        ] {
            let v = rr_violations(check, stim, tag);
            assert_eq!(v.len(), 1, "{stim}: the start IS a violation: {v:?}");
            assert!(v[0].ends_with("limit=5, actual=0"), "{v:?}");
        }
    }

    /// The roles are not interchangeable (Tables 31-4 / 31-5): a `$removal` only
    /// looks at a clock edge BEFORE the release and a `$recovery` only at one
    /// AFTER it. The same two close events, in the other order, violate nothing.
    #[test]
    fn run_design_removal_looks_before_the_release_and_recovery_after_it() {
        let rem = "$removal(posedge rst, posedge clk, 5, ntf);";
        let rec = "$recovery(posedge rst, posedge clk, 5, ntf);";
        let clk_then_rst = "clk = 1;\n    #2 rst = 1;";
        let rst_then_clk = "rst = 1;\n    #2 clk = 1;";
        assert_eq!(rr_violations(rem, clk_then_rst, "role-rem-a").len(), 1);
        assert!(rr_violations(rem, rst_then_clk, "role-rem-b").is_empty());
        assert!(rr_violations(rec, clk_then_rst, "role-rec-a").is_empty());
        assert_eq!(rr_violations(rec, rst_then_clk, "role-rec-b").len(), 1);
    }

    /// A zero limit never violates, even with both edges in one instant.
    #[test]
    fn run_design_removal_and_recovery_with_a_zero_limit_never_violate() {
        for check in [
            "$removal(posedge rst, posedge clk, 0, ntf);",
            "$recovery(posedge rst, posedge clk, 0, ntf);",
        ] {
            for stim in ["clk = 1; rst = 1;", "rst = 1; clk = 1;"] {
                let stdout = run_src("rr-zero", &rr_design(check, stim));
                assert!(
                    violations(&stdout).is_empty(),
                    "{check} / {stim}:\n{stdout}"
                );
                assert!(!stdout.contains("ntf="), "{check} / {stim}:\n{stdout}");
            }
        }
    }

    /// Only the edge named is an event: the opposite edge of either signal
    /// neither starts nor completes a window.
    #[test]
    fn run_design_removal_and_recovery_ignore_the_other_edge() {
        // `$recovery`: the release at 100 opens [100,105); the FALLING reset at
        // 110 is not a reference event (it would open [110,115), which holds the
        // clock edge at 111); the clock edge at 111 is outside the real window.
        let rec = "$recovery(posedge rst, posedge clk, 5);";
        let v = rr_violations(
            rec,
            "rst = 1;\n    #10 rst = 0;\n    #1 clk = 1;",
            "edge-rec-rst",
        );
        assert!(v.is_empty(), "{v:?}");
        // `$recovery`: the FALLING clock at 101 is not a data event (it would
        // be inside [100,105)); the clock rise at 120 is outside it.
        let v = rr_violations(
            rec,
            "clk = 1;\n    #1 rst = 1;\n    #1 clk = 0;\n    #20 clk = 1;",
            "edge-rec-clk",
        );
        assert!(v.is_empty(), "{v:?}");
        // `$removal`: the clock rise at 100 is 21 before the release at 121; the
        // FALLING clock at 120 (1 before it) is not a data event.
        let rem = "$removal(posedge rst, posedge clk, 5);";
        let v = rr_violations(
            rem,
            "clk = 1;\n    #20 clk = 0;\n    #1 rst = 1;",
            "edge-rem-clk",
        );
        assert!(v.is_empty(), "{v:?}");
        // `$removal`: the FALLING reset at 102 is not a reference event (it
        // would see the clock rise at 101 inside (97,102)); the release at 100
        // precedes that clock rise, so nothing is inside ITS window.
        let v = rr_violations(
            rem,
            "rst = 1;\n    #1 clk = 1;\n    #1 rst = 0;",
            "edge-rem-rst",
        );
        assert!(v.is_empty(), "{v:?}");
    }

    /// LRM 31.7: both events' `&&&` conditions gate the check, for both kinds.
    #[test]
    fn run_design_removal_and_recovery_conditions_gate_both_events() {
        let src = |kind: &str, stim: &str, en: u32, den: u32| {
            let args = "posedge rst &&& en, posedge clk &&& den";
            format!(
                "module chk(input rst, input clk, input en, input den);\n  reg ntf;\n  specify\n    \
                 {kind}({args}, 5, ntf);\n  endspecify\nendmodule\nmodule top;\n  reg rst, \
                 clk, en, den;\n  chk u(.rst(rst), .clk(clk), .en(en), .den(den));\n  initial \
                 begin\n    rst = 0; clk = 0; en = {en}; den = {den};\n    #100;\n    {stim}\n    \
                 #10 $finish;\n  end\nendmodule\n"
            )
        };
        for (kind, stim) in [
            ("$removal", "clk = 1;\n    #3 rst = 1;"),
            ("$recovery", "rst = 1;\n    #3 clk = 1;"),
        ] {
            let n = |en, den, tag: &str| violations(&run_src(tag, &src(kind, stim, en, den))).len();
            assert_eq!(n(1, 1, "rrc-11"), 1, "{kind}");
            assert_eq!(n(0, 1, "rrc-01"), 0, "{kind}: reference gated");
            assert_eq!(n(1, 0, "rrc-10"), 0, "{kind}: data gated");
        }
    }

    /// Both checks in one module are independent, each with its own state: the
    /// one stimulus below violates `$removal` (clock 1 before the release, limit
    /// 2) and not `$recovery` (the next clock edge 6 after it, limit 3).
    #[test]
    fn run_design_removal_and_recovery_in_one_module_are_independent() {
        let stdout = run_src(
            "rr-both",
            &rr_design(
                "$removal(posedge rst, posedge clk, 2, ntf);\n    $recovery(posedge rst, posedge \
                 clk, 3, ntf);",
                "clk = 1;\n    #1 begin clk = 0; rst = 1; end\n    #6 clk = 1;",
            ),
        );
        let v = violations(&stdout);
        assert_eq!(v.len(), 1, "{stdout}");
        assert!(
            v[0].contains("$removal") && v[0].ends_with("limit=2, actual=1"),
            "{v:?}"
        );
    }

    /// A negative limit is a named error: `$removal` / `$recovery` define no
    /// negative window (their limit is a "non-negative constant expression",
    /// Tables 31-4 / 31-5).
    #[test]
    fn run_design_removal_and_recovery_reject_a_negative_limit_by_name() {
        for (check, clause) in [
            ("$removal(posedge rst, posedge clk, -1);", "31.3.4"),
            ("$recovery(posedge rst, posedge clk, -1);", "31.3.5"),
        ] {
            let e = run_src_err("rr-neg", &rr_design(check, "clk = 1;"));
            let name = check.split('(').next().unwrap_or("");
            assert!(
                e.contains(name) && e.contains("non-negative") && e.contains(clause),
                "{check}: unexpected error: {e}"
            );
        }
    }

    // -----------------------------------------------------------------------
    // T18, LRM 31.3.6: `$recrem` end to end. The reference event is `rst`
    // and the data event `clk`, as for T17. `$recrem(.., REC, REM)` takes the
    // RECOVERY limit first: the data-first window (the reference event is the
    // timecheck event, `$removal`'s role) is sized by REM and the data-second
    // one (`$recovery`'s role) by REC -- every test below uses REC != REM so a
    // swapped pair of limits cannot pass.

    /// The violation lines of `$recrem(posedge rst, posedge clk, rec, rem, ntf)`
    /// for `stim` (the body of `top`'s `initial` block after a `#100`).
    fn rcr_violations(rec: i64, rem: i64, stim: &str, tag: &str) -> Vec<String> {
        rr_violations(
            &format!("$recrem(posedge rst, posedge clk, {rec}, {rem}, ntf);"),
            stim,
            tag,
        )
    }

    /// Exact output for one violation of each window of `$recrem(.., 3, 5)`:
    /// the message names `$recrem` and carries the violated window's own limit
    /// (the REMOVAL limit 5 for the clock edge before the release, the RECOVERY
    /// limit 3 for the one after), and the notifier toggles x -> 0 -> 1
    /// (Table 31-13).
    #[test]
    fn run_design_recrem_reports_the_violated_windows_limit_and_toggles_the_notifier() {
        let stdout = run_src(
            "rcr-exact",
            &rr_design(
                "$recrem(posedge rst, posedge clk, 3, 5, ntf);",
                "clk = 1;\n    #2 rst = 1;\n    #1 clk = 0;\n    #1 clk = 1;",
            ),
        );
        // clk@100, release@102: data first, actual 2 (limit = removal, 5);
        // clk@104 is 2 after the release: data second, actual 2 (limit =
        // recovery, 3).
        assert_eq!(
            stdout,
            "ntf=0 at 102\n102: $recrem violation: data top.u.clk vs reference top.u.rst, \
             limit=5, actual=2\nntf=1 at 104\n104: $recrem violation: data top.u.clk vs \
             reference top.u.rst, limit=3, actual=2\n"
        );
    }

    /// Data BEFORE the release (data event first), recovery 3, removal 5.
    /// LRM 31.3.6: `begin < t_data <= end` with `begin = t_rst - 5`, `end =
    /// t_rst` -- the START is excluded, the END (offset 0, simultaneous) IS a
    /// violation, so the sweep is NOT `$removal`'s (open at both ends), and the
    /// window is sized by the SECOND limit.
    #[test]
    fn run_design_recrem_data_first_window_uses_the_removal_limit_and_is_closed_at_the_end() {
        for (off, want) in [(7, 0), (6, 0), (5, 0), (4, 1), (1, 1), (0, 1)] {
            let stim = if off == 0 {
                "clk = 1; rst = 1;".to_string()
            } else {
                format!("clk = 1;\n    #{off} rst = 1;")
            };
            let v = rcr_violations(3, 5, &stim, &format!("rcr-first-{off}"));
            assert_eq!(v.len(), want, "clock {off} before the release: {v:?}");
            if want == 1 {
                // Offset 0 is the simultaneous case: the larger limit (5).
                assert!(
                    v[0].ends_with(&format!("limit=5, actual={off}")),
                    "{}",
                    v[0]
                );
            }
        }
    }

    /// Data AFTER the release (data event second): `begin <= t_data < end` with
    /// `begin = t_rst`, `end = t_rst + 3` -- the start (simultaneous) IS a
    /// violation, the END is not, and the window is sized by the FIRST limit.
    #[test]
    fn run_design_recrem_data_second_window_uses_the_recovery_limit_and_is_open_at_the_end() {
        for (off, want) in [(0, 1), (1, 1), (2, 1), (3, 0), (4, 0), (5, 0)] {
            let stim = if off == 0 {
                "rst = 1; clk = 1;".to_string()
            } else {
                format!("rst = 1;\n    #{off} clk = 1;")
            };
            let v = rcr_violations(3, 5, &stim, &format!("rcr-second-{off}"));
            assert_eq!(v.len(), want, "clock {off} after the release: {v:?}");
            if want == 1 && off != 0 {
                assert!(
                    v[0].ends_with(&format!("limit=3, actual={off}")),
                    "{}",
                    v[0]
                );
            }
        }
    }

    /// The limits are NOT `$setuphold`'s way round: `$recrem(.., 3, 5)` flags a
    /// clock edge 4 before the release (inside the 5-wide removal window) but
    /// not 4 after it (outside the 3-wide recovery window); the same two limits
    /// in the other order flag the reverse.
    #[test]
    fn run_design_recrem_takes_recovery_first_and_removal_second() {
        let before = "clk = 1;\n    #4 rst = 1;";
        let after = "rst = 1;\n    #4 clk = 1;";
        assert_eq!(rcr_violations(3, 5, before, "rcr-ord-a").len(), 1);
        assert!(rcr_violations(3, 5, after, "rcr-ord-b").is_empty());
        assert!(rcr_violations(5, 3, before, "rcr-ord-c").is_empty());
        assert_eq!(rcr_violations(5, 3, after, "rcr-ord-d").len(), 1);
    }

    /// LRM 31.3.6: "When both limits are zero, the `$recrem` check shall never
    /// issue a violation" -- not even for simultaneous events.
    #[test]
    fn run_design_recrem_with_both_limits_zero_never_violates() {
        for stim in [
            "clk = 1; rst = 1;",
            "rst = 1; clk = 1;",
            "clk = 1;\n    #1 rst = 1;",
            "rst = 1;\n    #1 clk = 1;",
        ] {
            let stdout = run_src(
                "rcr-zero",
                &rr_design("$recrem(posedge rst, posedge clk, 0, 0, ntf);", stim),
            );
            assert!(violations(&stdout).is_empty(), "{stim}:\n{stdout}");
            assert!(!stdout.contains("ntf="), "{stim}:\n{stdout}");
        }
    }

    /// A single zero limit empties only its own window; simultaneous events
    /// still violate (both windows' own text says so) while the other limit is
    /// positive.
    #[test]
    fn run_design_recrem_with_one_zero_limit_keeps_only_the_other_window() {
        let before = "clk = 1;\n    #1 rst = 1;";
        let after = "rst = 1;\n    #1 clk = 1;";
        let same = "clk = 1; rst = 1;";
        // recovery 0, removal 3: only the data-first window.
        assert_eq!(rcr_violations(0, 3, before, "rcr-r0-first").len(), 1);
        assert!(rcr_violations(0, 3, after, "rcr-r0-second").is_empty());
        assert_eq!(rcr_violations(0, 3, same, "rcr-r0-simul").len(), 1);
        // recovery 3, removal 0: only the data-second window.
        assert!(rcr_violations(3, 0, before, "rcr-m0-first").is_empty());
        assert_eq!(rcr_violations(3, 0, after, "rcr-m0-second").len(), 1);
        assert_eq!(rcr_violations(3, 0, same, "rcr-m0-simul").len(), 1);
    }

    /// 31.3.6: "`$recrem(posedge clear, posedge clk, tREC, tREM)` is equivalent
    /// in functionality to `$removal(posedge clear, posedge clk, tREM);
    /// $recovery(posedge clear, posedge clk, tREC)`, if tREC and tREM are not
    /// negative" -- one instance with the one check and one with the pair, on
    /// the same stimulus, report the same violations at the same times with the
    /// same separations. (The stimulus walks both windows' boundaries and ends
    /// on a simultaneous pair, which a positive recovery limit flags in the pair
    /// too.) The limits are distinct so a swap would show.
    #[test]
    fn run_design_recrem_is_equivalent_to_a_removal_plus_recovery_pair() {
        let src = "module one(input rst, input clk);\n  specify\n    $recrem(posedge rst, \
                   posedge clk, 2, 3);\n  endspecify\nendmodule\nmodule two(input rst, input \
                   clk);\n  specify\n    $removal(posedge rst, posedge clk, 3);\n    \
                   $recovery(posedge rst, posedge clk, 2);\n  endspecify\nendmodule\nmodule \
                   top;\n  reg rst, clk;\n  one a(.rst(rst), .clk(clk));\n  two b(.rst(rst), \
                   .clk(clk));\n  initial begin\n    rst = 0; clk = 0;\n    #10 clk = 1;\n    \
                   #2 rst = 1;\n    #1 clk = 0;\n    #1 clk = 1;\n    #1 clk = 0;\n    #1 clk = 1;\n    \
                   #1 begin clk = 0; rst = 0; end\n    #6 clk = 1;\n    #1 clk = 0;\n    #3 rst = 1;\n    \
                   #1 clk = 1;\n    #1 clk = 0;\n    #1 rst = 0;\n    #7 begin rst = 1; clk = 1; end\n    \
                   #1 clk = 0;\n    #1 clk = 1;\n    #1 clk = 0;\n    #1 rst = 0;\n    #1 clk = 1;\n    #1 clk = 0;\n    #1 rst = 1;\n    #1 clk = 1;\n    #20 $finish;\n  end\nendmodule\n";
        let stdout = run_src("rcr-equiv", src);
        // `<now>: <check> violation: data <clk> vs reference <rst>, limit=L, actual=A`
        let key = |l: &str| {
            let now = l.split(':').next().unwrap_or("").to_string();
            let actual = l.rsplit("actual=").next().unwrap_or("").to_string();
            (now, actual)
        };
        let of = |inst: &str| -> Vec<(String, String)> {
            violations(&stdout)
                .into_iter()
                .filter(|l| l.contains(&format!("top.{inst}.")))
                .map(key)
                .collect()
        };
        let one = of("a");
        let two = of("b");
        assert_eq!(one.len(), 5, "{stdout}");
        assert_eq!(one, two, "{stdout}");
    }

    /// Where `$recrem` and a separate `$removal` DO differ (LRM 31.3.6's own
    /// text): the data-first window includes its end, so with no recovery limit
    /// a simultaneous reference and data event is a `$recrem` violation but not
    /// a `$removal` one.
    #[test]
    fn run_design_recrem_is_closed_at_its_removal_end_where_removal_is_open() {
        let n = |check: &str| {
            let stdout = run_src("rcr-vs-rem", &rr_design(check, "clk = 1; rst = 1;"));
            violations(&stdout).len()
        };
        assert_eq!(n("$recrem(posedge rst, posedge clk, 0, 5, ntf);"), 1);
        assert_eq!(n("$removal(posedge rst, posedge clk, 5, ntf);"), 0);
    }

    /// LRM 31.7: both events' `&&&` conditions gate the check.
    #[test]
    fn run_design_recrem_conditions_gate_the_reference_and_the_data_event() {
        let src = |stim: &str, en: u32, den: u32| {
            format!(
                "module chk(input rst, input clk, input en, input den);\n  reg ntf;\n  specify\n    \
                 $recrem(posedge rst &&& en, posedge clk &&& den, 3, 5, ntf);\n  endspecify\n\
                 endmodule\nmodule top;\n  reg rst, clk, en, den;\n  chk u(.rst(rst), .clk(clk), \
                 .en(en), .den(den));\n  initial begin\n    rst = 0; clk = 0; en = {en}; \
                 den = {den};\n    #100;\n    {stim}\n    #10 $finish;\n  end\nendmodule\n"
            )
        };
        for (stim, what) in [
            ("clk = 1;\n    #2 rst = 1;", "data first"),
            ("rst = 1;\n    #2 clk = 1;", "data second"),
        ] {
            let n = |en, den, tag: &str| violations(&run_src(tag, &src(stim, en, den))).len();
            assert_eq!(n(1, 1, "rcrc-11"), 1, "{what}");
            assert_eq!(n(0, 1, "rcrc-01"), 0, "{what}: reference gated");
            assert_eq!(n(1, 0, "rcrc-10"), 0, "{what}: data gated");
        }
    }

    /// Only the edge named is an event: the falling edge of either signal
    /// neither starts nor completes a window.
    #[test]
    fn run_design_recrem_ignores_the_other_edge() {
        // The FALLING reset at 105 is not a reference event (it would open
        // [105,108), which holds the clock edge at 106).
        let v = rcr_violations(
            3,
            5,
            "rst = 1;\n    #5 rst = 0;\n    #1 clk = 1;",
            "rcr-edge-rst",
        );
        assert!(v.is_empty(), "{v:?}");
        // The FALLING clock at 120 is not a data event (it would be inside the
        // data-first window (116,121] of the release at 121); the clock rise
        // at 100 is 21 before it.
        let v = rcr_violations(
            3,
            5,
            "clk = 1;\n    #20 clk = 0;\n    #1 rst = 1;",
            "rcr-edge-clk",
        );
        assert!(v.is_empty(), "{v:?}");
    }

    /// LRM 31.8: a vector data terminal changing in several bits at once is one
    /// event, one violation.
    #[test]
    fn run_design_recrem_vector_terminal_is_one_event() {
        let src = "module chk(input rst, input [3:0] d);\n  specify\n    $recrem(posedge rst, d, 3, \
                   5);\n  endspecify\nendmodule\nmodule top;\n  reg rst;\n  reg [3:0] d;\n  chk \
                   u(.rst(rst), .d(d));\n  initial begin\n    rst = 0; d = 0;\n    #100 d = \
                   4'b1111;\n    #2 rst = 1;\n    #10 $finish;\n  end\nendmodule\n";
        assert_eq!(violations(&run_src("rcr-vec", src)).len(), 1);
    }

    /// `$recrem`'s timestamp/timecheck conditions (LRM 31.9.2) gate the same way: the
    /// first event of each window carries `timestamp_condition`, the second
    /// `timecheck_condition` (removal: reference first; recovery: data first).
    #[test]
    fn run_design_recrem_conditions_gate_each_window_by_event_order() {
        // `clk` plays the reference and `d` the data of `$recrem(posedge clk, posedge d)`.
        for (order, first, second) in [("removal", "clk", "d"), ("recovery", "d", "clk")] {
            for (what, check, wants) in [
                (
                    "ts",
                    "$recrem(posedge clk, posedge d, 3, 3, ntf, c);",
                    (true, false),
                ),
                (
                    "tc",
                    "$recrem(posedge clk, posedge d, 3, 3, ntf, , c);",
                    (false, true),
                ),
            ] {
                for x in 0..2u8 {
                    for y in 0..2u8 {
                        let want = (!wants.0 || x == 1) && (!wants.1 || y == 1);
                        let n = cond_gate(
                            check,
                            first,
                            second,
                            x,
                            y,
                            &format!("rcc-{order}-{what}-{x}{y}"),
                        );
                        assert_eq!(n, usize::from(want), "{order} {what} c={x}->{y}");
                    }
                }
            }
        }
    }

    /// Two `$recrem`s in one module and one instance each carry their own
    /// state: only the check whose own events are too close violates.
    #[test]
    fn run_design_recrem_each_check_has_its_own_state() {
        let src = "module chk(input rst, input clk, input rst2, input clk2);\n  specify\n    \
                   $recrem(posedge rst, posedge clk, 3, 5);\n    $recrem(posedge rst2, posedge \
                   clk2, 3, 5);\n  endspecify\nendmodule\nmodule top;\n  reg rst, clk, rst2, \
                   clk2;\n  chk u(.rst(rst), .clk(clk), .rst2(rst2), .clk2(clk2));\n  initial \
                   begin\n    rst = 0; clk = 0; rst2 = 0; clk2 = 0;\n    #100 clk = 1;\n    #2 \
                   rst = 1;\n    #20 clk2 = 1;\n    #20 rst2 = 1;\n    #10 $finish;\n  end\n\
                   endmodule\n";
        let stdout = run_src("rcr-two", src);
        let v = violations(&stdout);
        assert_eq!(v.len(), 1, "{stdout}");
        assert!(v[0].starts_with("102: $recrem"), "{}", v[0]);
    }

    // -----------------------------------------------------------------------
    // T19, LRM 31.4.4 / 31.4.5 / 31.4.6: `$width`, `$period`, `$nochange`.

    /// `$width` (31.4.4): "threshold < (timecheck time) - (timestamp time) <
    /// limit", both bounds exclusive, swept over every combination of a small
    /// range so each boundary is hit from both sides.
    #[test]
    fn width_state_sweep_matches_the_inequality() {
        let mut hits = 0;
        for threshold in 0..=3 {
            for limit in 0..=6 {
                for width in 0..=8 {
                    let mut s = WidthState::new(limit, threshold);
                    s.reference_event(100);
                    let got = s.data_event(100 + width);
                    let want = (threshold < width && width < limit).then_some(width);
                    assert_eq!(
                        got, want,
                        "threshold {threshold}, limit {limit}, width {width}"
                    );
                    hits += usize::from(got.is_some());
                }
            }
        }
        assert!(
            hits > 0,
            "the sweep must contain violations or it proves nothing"
        );
    }

    /// A timecheck with no timestamp before it measures nothing, and one pulse
    /// is one check: the timestamp is spent by the timecheck that uses it (a
    /// `negedge` also matches `1->x` then `x->0`, which is one falling pulse).
    #[test]
    fn width_state_needs_a_timestamp_and_spends_it() {
        let mut s = WidthState::new(10, 0);
        assert_eq!(s.data_event(5), None, "no timestamp yet");
        s.reference_event(10);
        assert_eq!(s.data_event(14), Some(4));
        assert_eq!(s.data_event(15), None, "the timestamp was spent");
        s.reference_event(20);
        assert_eq!(s.data_event(21), Some(1));
    }

    /// A later timestamp replaces an unspent one (`0->x` then `x->1` are both
    /// `posedge`): the width is measured from the latest.
    #[test]
    fn width_state_measures_from_the_latest_timestamp() {
        let mut s = WidthState::new(10, 0);
        s.reference_event(10);
        s.reference_event(14);
        assert_eq!(s.data_event(17), Some(3));
    }

    /// `$period` (31.4.5): "(timecheck time) - (timestamp time) < limit", the
    /// timestamp being the previous reference edge; the first edge has none.
    #[test]
    fn period_state_sweep_matches_the_inequality() {
        let mut hits = 0;
        for limit in 0..=6 {
            // 0 is excluded: two edges of one signal cannot share an instant.
            for period in 1..=8 {
                let mut s = PeriodState::new(limit);
                assert_eq!(s.data_event(100), None, "the first edge has no period");
                s.reference_event(100);
                let got = s.data_event(100 + period);
                s.reference_event(100 + period);
                let want = (period < limit).then_some(period);
                assert_eq!(got, want, "limit {limit}, period {period}");
                hits += usize::from(got.is_some());
            }
        }
        assert!(
            hits > 0,
            "the sweep must contain violations or it proves nothing"
        );
    }

    /// Each edge is measured against the one before it, not the first one.
    #[test]
    fn period_state_measures_consecutive_edges() {
        let mut s = PeriodState::new(10);
        let mut got = Vec::new();
        for now in [0, 12, 14, 30, 39] {
            got.push(s.data_event(now));
            s.reference_event(now);
        }
        assert_eq!(got, [None, None, Some(2), None, Some(9)]);
    }

    /// One `$nochange` event the state machine is fed.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Nc {
        Lead,
        Trail,
        Data,
    }

    /// Feeds `events` (time, kind), in the order given, to a fresh machine; the
    /// `(time it was reported, actual)` of every violation.
    fn nc_run(start: i64, end: i64, events: &[(i64, Nc)]) -> Vec<(i64, i64)> {
        let mut s = NoChangeState::new(start, end);
        let mut out = Vec::new();
        for &(now, e) in events {
            let found = match e {
                Nc::Lead => s.reference_event(now),
                Nc::Trail => s.trailing_event(now),
                Nc::Data => s.data_event(now),
            };
            out.extend(found.into_iter().map(|actual| (now, actual)));
        }
        out
    }

    /// The LRM 31.4.6 example, `$nochange(posedge clk, d, 0, 0)`: "a violation if
    /// the data signal changes while clk is high. It shall not be a violation if
    /// posedge clk and a transition on data occur simultaneously", nor at the
    /// negedge.
    #[test]
    fn nochange_zero_offsets_flag_a_change_strictly_inside_the_high_period() {
        use Nc::{Data, Lead, Trail};
        for (t, want) in [
            (9, false),
            (10, false),
            (11, true),
            (19, true),
            (20, false),
            (21, false),
        ] {
            let got = if t < 10 {
                nc_run(0, 0, &[(t, Data), (10, Lead), (20, Trail)])
            } else if t <= 20 {
                nc_run(0, 0, &[(10, Lead), (t, Data), (20, Trail)])
            } else {
                nc_run(0, 0, &[(10, Lead), (20, Trail), (t, Data)])
            };
            assert_eq!(!got.is_empty(), want, "data change at {t}");
            if want {
                // Not certain until the trailing edge could no longer share its
                // instant (end offset 0): reported at the trailing edge.
                assert_eq!(got, [(20, t - 10)], "data change at {t}");
            }
        }
    }

    /// The same-instant cases for the zero-offset check, in both orders: a data
    /// change simultaneous with either reference edge is an end point.
    #[test]
    fn nochange_zero_offsets_ignore_a_change_at_either_reference_edge() {
        use Nc::{Data, Lead, Trail};
        for first_is_data in [true, false] {
            let at = |t: i64, edge: Nc| {
                if first_is_data {
                    [(t, Data), (t, edge)]
                } else {
                    [(t, edge), (t, Data)]
                }
            };
            let mut events = Vec::new();
            events.extend(at(10, Lead));
            events.extend(at(20, Trail));
            let got = nc_run(0, 0, &events);
            assert!(got.is_empty(), "data-first {first_is_data}: {got:?}");
        }
    }

    /// Offsets move the end points of the window (`(L - start, T + end)`, both
    /// excluded): a positive offset extends it, a negative one shrinks it.
    #[test]
    fn nochange_offsets_extend_and_shrink_the_window() {
        use Nc::{Data, Lead, Trail};
        // L = 100, T = 110.
        for (start, end, t, want) in [
            // start 3: the window begins at 97
            (3, 0, 96, false),
            (3, 0, 97, false),
            (3, 0, 98, true),
            (3, 0, 100, true),
            // start -3 (shrink): begins at 103
            (-3, 0, 103, false),
            (-3, 0, 104, true),
            // end 4: ends at 114
            (0, 4, 113, true),
            (0, 4, 114, false),
            // end -4 (shrink): ends at 106
            (0, -4, 105, true),
            (0, -4, 106, false),
        ] {
            let events = if t < 100 {
                [(t, Data), (100, Lead), (110, Trail)]
            } else if t <= 110 {
                [(100, Lead), (t, Data), (110, Trail)]
            } else {
                [(100, Lead), (110, Trail), (t, Data)]
            };
            let got = nc_run(start, end, &events);
            assert_eq!(
                !got.is_empty(),
                want,
                "$nochange(.., {start}, {end}), data at {t}: {got:?}"
            );
            if want {
                assert_eq!(got.len(), 1);
                assert_eq!(got[0].1, t - 100, "actual is relative to the leading edge");
            }
        }
    }

    /// The fixture `nochange.sv`'s stimulus, driven directly: `$nochange(posedge
    /// clk, d, 2, 3)` and `(.., 0, 0)`, in both same-instant orders.
    #[test]
    fn nochange_the_fixtures_two_checks_in_both_same_instant_orders() {
        use Nc::{Data, Lead, Trail};
        // (instant, [edge], data?)
        let script: [(i64, Option<Nc>, bool); 14] = [
            (0, Some(Trail), true),
            (11, None, true),
            (12, Some(Lead), false),
            (16, None, true),
            (20, Some(Trail), false),
            (22, None, true),
            (30, Some(Lead), true),
            (36, Some(Trail), true),
            (40, None, true),
            (47, None, true),
            (48, Some(Lead), false),
            (50, None, true),
            (52, Some(Trail), false),
            (57, None, true),
        ];
        for data_first in [true, false] {
            let mut events = Vec::new();
            for (t, edge, data) in script {
                let mut pair: Vec<(i64, Nc)> = Vec::new();
                if data {
                    pair.push((t, Data));
                }
                if let Some(e) = edge {
                    pair.push((t, e));
                }
                if !data_first {
                    pair.reverse();
                }
                events.extend(pair);
            }
            assert_eq!(
                nc_run(0, 0, &events),
                [(20, 4), (52, 2)],
                "(0, 0), data first {data_first}"
            );
            let mut got = nc_run(2, 3, &events);
            got.sort_unstable();
            assert_eq!(
                got,
                [
                    (12, -1),
                    (16, 4),
                    (22, 10),
                    (30, 0),
                    (36, 6),
                    (48, -1),
                    (50, 2)
                ],
                "(2, 3), data first {data_first}"
            );
        }
    }

    /// A second leading edge while the window is open (`0->x` then `x->1`, both
    /// `posedge`) does not move its start, and a trailing edge with no window
    /// open (the initial `x->0`) opens nothing: the check is the window the
    /// FIRST leading edge opened, closed by the first trailing edge after it.
    #[test]
    fn nochange_ignores_a_second_leading_edge_and_an_unmatched_trailing_edge() {
        use Nc::{Data, Lead, Trail};
        assert_eq!(
            nc_run(
                0,
                0,
                &[(5, Trail), (10, Lead), (12, Lead), (14, Data), (20, Trail)]
            ),
            [(20, 4)],
            "actual is from the first leading edge (10), not the second (12)"
        );
        assert!(
            nc_run(0, 0, &[(10, Lead), (20, Trail), (22, Trail), (25, Data)]).is_empty(),
            "a second trailing edge does not reopen the window"
        );
    }

    /// The documented limitation: a data change inside a window whose end is
    /// not yet known (end offset <= 0) is reported when the trailing edge
    /// arrives, so a window the simulation ends inside never reports it.
    #[test]
    fn nochange_a_window_still_open_at_the_end_does_not_report_its_pending_change() {
        use Nc::{Data, Lead};
        assert!(nc_run(0, 0, &[(10, Lead), (14, Data)]).is_empty());
        // With a positive end offset the violation is certain on arrival.
        assert_eq!(nc_run(0, 1, &[(10, Lead), (14, Data)]), [(14, 4)]);
    }

    /// One data change is one violation even when it lies in two windows
    /// (overlapping because of a large end offset), reported against the
    /// earlier window.
    #[test]
    fn nochange_reports_a_data_change_once_across_overlapping_windows() {
        use Nc::{Data, Lead, Trail};
        // Windows (10, 22) and (14, 26): 15 is in both, 24 only in the second.
        let got = nc_run(
            0,
            10,
            &[
                (10, Lead),
                (12, Trail),
                (14, Lead),
                (15, Data),
                (16, Trail),
                (24, Data),
            ],
        );
        assert_eq!(got, [(15, 5), (24, 10)]);
    }

    /// A deterministic generator for the property test below.
    fn lcg(seed: &mut u64) -> u64 {
        *seed = seed
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        *seed >> 33
    }

    /// `$nochange` against LRM 31.4.6 read straight off the text: build the
    /// windows `(L - start, T + end)` from the reference signal's alternating
    /// edges, then a data change at `t` is a violation iff some window strictly
    /// contains it (the earliest such window gives `actual = t - L`). The state
    /// machine must agree on every trace, whichever of two same-instant events
    /// it is fed first.
    #[test]
    fn nochange_state_matches_the_lrm_windows_on_random_traces_in_every_event_order() {
        let mut violations_seen = 0;
        for start in -2..=3 {
            for end in -2..=3 {
                for seed0 in 0..120u64 {
                    let mut seed = seed0 * 7919 + 13;
                    // (time, edge, data?)
                    let mut trace: Vec<(i64, Option<Nc>, bool)> = Vec::new();
                    let mut t = 0;
                    for _ in 0..8 {
                        t += 1 + (lcg(&mut seed) % 3) as i64;
                        let edge = match lcg(&mut seed) % 4 {
                            0 => Some(Nc::Lead),
                            1 => Some(Nc::Trail),
                            _ => None,
                        };
                        trace.push((t, edge, lcg(&mut seed).is_multiple_of(2)));
                    }
                    // Close any open window so every window's end is known.
                    trace.push((t + 20, Some(Nc::Trail), false));

                    let mut windows: Vec<(i64, i64)> = Vec::new();
                    let mut open = None;
                    for &(t, edge, _) in &trace {
                        match edge {
                            Some(Nc::Lead) if open.is_none() => open = Some(t),
                            Some(Nc::Trail) => {
                                if let Some(l) = open.take() {
                                    windows.push((l, t));
                                }
                            }
                            _ => {}
                        }
                    }
                    let mut want: Vec<i64> = trace
                        .iter()
                        .filter(|&&(_, _, data)| data)
                        .filter_map(|&(t, _, _)| {
                            windows
                                .iter()
                                .find(|&&(l, tt)| l - start < t && t < tt + end)
                                .map(|&(l, _)| t - l)
                        })
                        .collect();
                    want.sort_unstable();
                    violations_seen += want.len();

                    let instants_with_two =
                        trace.iter().filter(|&&(_, e, d)| e.is_some() && d).count();
                    let mut canonical: Option<Vec<(i64, i64)>> = None;
                    for mask in 0..1u32 << instants_with_two {
                        let mut events = Vec::new();
                        let mut bit = 0;
                        for &(t, edge, data) in &trace {
                            let mut pair = Vec::new();
                            if data {
                                pair.push((t, Nc::Data));
                            }
                            if let Some(e) = edge {
                                pair.push((t, e));
                            }
                            if pair.len() == 2 {
                                if mask >> bit & 1 == 1 {
                                    pair.reverse();
                                }
                                bit += 1;
                            }
                            events.extend(pair);
                        }
                        let mut got = nc_run(start, end, &events);
                        got.sort_unstable();
                        let mut actuals: Vec<i64> = got.iter().map(|g| g.1).collect();
                        actuals.sort_unstable();
                        assert_eq!(
                            actuals, want,
                            "$nochange(.., {start}, {end}) on {trace:?}, order mask {mask:b}"
                        );
                        match &canonical {
                            None => canonical = Some(got),
                            Some(c) => assert_eq!(
                                &got, c,
                                "report times differ with the order of same-instant events: \
                                 $nochange(.., {start}, {end}) on {trace:?}, mask {mask:b}"
                            ),
                        }
                    }
                }
            }
        }
        assert!(
            violations_seen > 1000,
            "only {violations_seen} violations in the sweep"
        );
    }

    /// `$nochange`, `$width` and `$period` each need an edge reference
    /// (discovery's) and a derived event from it: the opposite of a bare
    /// `edge` is that same set of all six, and any change has none.
    #[test]
    fn opposite_event_controls_follow_the_reference_edge() {
        let pos = control(sv_lang::EdgeKind::PosEdge, &[]);
        let neg = control(sv_lang::EdgeKind::NegEdge, &[]);
        assert_eq!(opposite_control(pos, "$width", "x"), Ok(neg));
        assert_eq!(opposite_control(neg, "$width", "x"), Ok(pos));
        let e = opposite_control(EdgeControl::AnyChange, "$width", "x").unwrap_err();
        assert!(e.contains("$width") && e.contains("edge"), "{e}");
    }

    // -- End to end ----------------------------------------------------------

    /// A one-signal pulse design: `check` in a specify block with the specparams
    /// the LRM's `$width` examples use, a notifier watcher, and `stim` as the
    /// body of `top`'s `initial` block after a `#100`.
    fn pulse_design(check: &str, stim: &str) -> String {
        format!(
            "module chk(input clr, input en);\n  reg ntf;\n  specparam lim = 10, thresh = 3;\n  \
             specify\n    {check}\n  endspecify\n  always @(ntf) $display(\"ntf=%b at %0t\", ntf, \
             $time);\nendmodule\nmodule top;\n  reg clr, en;\n  chk u(.clr(clr), .en(en));\n  \
             initial begin\n    clr = 1; en = 1;\n    #100;\n    {stim}\n    #100 $finish;\n  \
             end\nendmodule\n"
        )
    }

    /// Runs `check` against a low pulse of `w` ticks on `clr` (the LRM's own
    /// calls are `negedge clr`); the violation lines.
    fn low_pulse(check: &str, w: i64, tag: &str) -> (String, Vec<String>) {
        let stdout = run_src(
            &format!("{tag}-{w}"),
            &pulse_design(check, &format!("clr = 0;\n    #{w} clr = 1;")),
        );
        let v = violations(&stdout).iter().map(|l| l.to_string()).collect();
        (stdout, v)
    }

    /// LRM 31.4.4's first legal call: `$width ( negedge clr, lim );` -- no
    /// threshold (so 0) and no notifier.
    #[test]
    fn run_design_width_call_shape_limit_only() {
        for (w, want) in [(1, true), (5, true), (9, true), (10, false), (11, false)] {
            let (stdout, v) = low_pulse("$width(negedge clr, lim);", w, "w1");
            assert_eq!(v.len(), usize::from(want), "width {w}:\n{stdout}");
            assert!(!stdout.contains("ntf="), "no notifier is declared");
        }
        let (_, v) = low_pulse("$width(negedge clr, lim);", 4, "w1x");
        // The reference (negedge, the timestamp) and the derived data event
        // (posedge, the timecheck) are the one signal.
        assert_eq!(
            v,
            ["104: $width violation: data top.u.clr vs reference top.u.clr, limit=10, actual=4"]
        );
    }

    /// LRM 31.4.4's second legal call: `$width ( negedge clr, lim, thresh, notif );`
    /// -- "no violation is reported for glitches smaller than the threshold".
    #[test]
    fn run_design_width_call_shape_limit_threshold_notifier() {
        for (w, want) in [(2, false), (3, false), (4, true), (9, true), (10, false)] {
            let (stdout, v) = low_pulse("$width(negedge clr, lim, thresh, ntf);", w, "w2");
            assert_eq!(v.len(), usize::from(want), "width {w}:\n{stdout}");
            assert_eq!(stdout.contains("ntf=0 at"), want, "notifier, width {w}");
        }
    }

    /// LRM 31.4.4's third legal call: `$width ( negedge clr, lim, 0, notif );` --
    /// the threshold the notifier forces you to write, and the same as omitting it.
    #[test]
    fn run_design_width_call_shape_zero_threshold_with_notifier() {
        for (w, want) in [(1, true), (9, true), (10, false)] {
            let (stdout, v) = low_pulse("$width(negedge clr, lim, 0, ntf);", w, "w3");
            assert_eq!(v.len(), usize::from(want), "width {w}:\n{stdout}");
            assert_eq!(stdout.contains("ntf=0 at"), want, "notifier, width {w}");
        }
    }

    /// LRM 31.4.4's own example of a notifier with a null threshold:
    /// `$width (posedge clk, 6, 0, ntfr_reg);` -- a `posedge` reference measures
    /// the HIGH pulse (from its rising edge to the falling one).
    #[test]
    fn run_design_width_posedge_reference_measures_the_high_pulse() {
        for (w, want) in [(5, true), (6, false)] {
            let stdout = run_src(
                &format!("w-pos-{w}"),
                &pulse_design(
                    "$width(posedge clr, 6, 0, ntf);",
                    &format!("clr = 0;\n    #20 clr = 1;\n    #{w} clr = 0;"),
                ),
            );
            assert_eq!(violations(&stdout).len(), usize::from(want), "{stdout}");
        }
    }

    /// LRM 31.4.4's two ILLEGAL calls are compile errors by name: a notifier
    /// with a null threshold, and a notifier in the threshold's position.
    #[test]
    fn run_design_width_illegal_call_shapes_are_named_errors() {
        // The first is diagnosed by discovery (T13), the second by the compiler
        // before it gets there (the notifier is a variable, not a constant).
        for (tag, call, what) in [
            (
                "ill1",
                "$width(negedge clr, lim, , ntf);",
                ["$width", "threshold"],
            ),
            (
                "ill2",
                "$width(negedge clr, lim, ntf);",
                ["ntf", "constant"],
            ),
        ] {
            let e = run_src_err(tag, &pulse_design(call, "clr = 0;"));
            assert!(what.iter().all(|w| e.contains(w)), "{tag}: {e}");
        }
    }

    /// `$width` and `$period` define no negative limit or threshold (Tables
    /// 31-10 and 31-11 "non-negative constant expression"): named errors.
    #[test]
    fn run_design_width_and_period_reject_a_negative_limit_or_threshold_by_name() {
        for (tag, call, what) in [
            ("neg-wl", "$width(negedge clr, -1);", "$width"),
            ("neg-wt", "$width(negedge clr, 5, -1, ntf);", "threshold"),
            ("neg-pl", "$period(posedge clr, -1);", "$period"),
        ] {
            let e = run_src_err(tag, &pulse_design(call, "clr = 0;"));
            assert!(
                e.contains(what) && e.contains("non-negative"),
                "{tag}: unexpected error: {e}"
            );
        }
    }

    /// The derived data events inherit the reference event's `&&&` condition
    /// (LRM 31.7: the condition qualifies the check's events). `$width(posedge
    /// clr &&& en, 10)`: a pulse whose falling edge arrives while `en` is low
    /// has no timecheck event, so no violation; with `en` high it does.
    #[test]
    fn run_design_width_derived_data_event_is_gated_by_the_reference_condition() {
        let check = "$width(posedge clr &&& en, 10);";
        let pulse = |en_at_fall: &str, tag: &str| {
            let stdout = run_src(
                tag,
                &pulse_design(
                    check,
                    &format!(
                        "clr = 0;\n    #10 clr = 1;\n    #3 en = {en_at_fall};\n    #2 clr = 0;"
                    ),
                ),
            );
            violations(&stdout).len()
        };
        assert_eq!(pulse("1", "w-cond-1"), 1, "en high at the falling edge");
        assert_eq!(pulse("0", "w-cond-0"), 0, "en low at the falling edge");
    }

    /// `$period` end to end: the exact line, and the boundary (a period equal to
    /// the limit is NOT a violation).
    #[test]
    fn run_design_period_reports_a_short_period_and_not_one_equal_to_the_limit() {
        let run = |period: i64, tag: &str| {
            run_src(
                tag,
                &pulse_design(
                    "$period(posedge clr, lim, ntf);",
                    &format!(
                        "clr = 0;\n    #5 clr = 1;\n    #{} clr = 0;\n    #1 clr = 1;",
                        period - 1
                    ),
                ),
            )
        };
        // The design's own `x -> 1` at time 0 is the first rising edge (it has
        // no period); the next is at 105, 105 ticks later, and the one the
        // sweep measures is at 105 + period.
        let stdout = run(7, "p-short");
        assert_eq!(
            stdout,
            "ntf=0 at 112\n112: $period violation: data top.u.clr vs reference top.u.clr, \
             limit=10, actual=7\n"
        );
        assert_eq!(violations(&run(10, "p-eq")).len(), 0, "period == limit");
        assert_eq!(violations(&run(11, "p-long")).len(), 0, "period > limit");
        assert_eq!(violations(&run(9, "p-9")).len(), 1, "period < limit");
    }

    /// The derived `$period` data event inherits the reference's `&&&`
    /// condition: an edge while the condition is false is neither a timestamp
    /// nor a timecheck, so the next enabled edge is measured from the last
    /// ENABLED one.
    #[test]
    fn run_design_period_edges_while_the_condition_is_false_are_not_events() {
        let stim = "clr = 0;\n    #5 clr = 1;\n    #2 clr = 0;\n    #1 en = 0;\n    #1 clr = 1;\n    \
                    #1 clr = 0;\n    #1 en = 1;\n    #1 clr = 1;";
        let stdout = run_src(
            "p-cond",
            &pulse_design("$period(posedge clr &&& en, lim);", stim),
        );
        // Enabled rising edges at 105 and 112 (the one at 109 is ignored): one
        // violation, period 7 < 10, reported at 112 -- not a second one at 109
        // (which an ungated data event would measure, 4, from 105).
        let v = violations(&stdout);
        assert_eq!(v.len(), 1, "{stdout}");
        assert!(v[0].starts_with("112: $period"), "{}", v[0]);
        assert!(v[0].ends_with("actual=7"), "{}", v[0]);
    }

    /// A design with a `$nochange` over `clk` and `d`; `stim` is the body of
    /// `top`'s `initial` block after a `#100` (clk starts low).
    fn nochange_design(check: &str, stim: &str) -> String {
        format!(
            "module chk(input clk, input d);\n  reg ntf;\n  specify\n    {check}\n  endspecify\n  \
             always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\nmodule top;\n  \
             reg clk, d;\n  chk u(.clk(clk), .d(d));\n  initial begin\n    clk = 0; d = 0;\n    \
             #100;\n    {stim}\n    #100 $finish;\n  end\nendmodule\n"
        )
    }

    /// Negative offsets shrink the window (LRM 31.4.6): `$nochange(posedge clk,
    /// d, -2, -1)` over clk high 100..110 is the window (102, 109).
    #[test]
    fn run_design_nochange_negative_offsets_shrink_the_window() {
        for (off, want) in [
            (1, false),
            (2, false),
            (3, true),
            (8, true),
            (9, false),
            (10, false),
        ] {
            let stdout = run_src(
                &format!("nc-shrink-{off}"),
                &nochange_design(
                    "$nochange(posedge clk, d, -2, -1, ntf);",
                    &format!("clk = 1;\n    #{off} d = 1;\n    #{} clk = 0;", 10 - off),
                ),
            );
            assert_eq!(
                violations(&stdout).len(),
                usize::from(want),
                "d at +{off}:\n{stdout}"
            );
            assert_eq!(stdout.contains("ntf="), want, "notifier, d at +{off}");
        }
    }

    /// A positive start offset reaches BEFORE the leading edge: the violation is
    /// found when the edge arrives, with a negative `actual`.
    #[test]
    fn run_design_nochange_start_offset_flags_a_change_before_the_leading_edge() {
        let stdout = run_src(
            "nc-early",
            &nochange_design(
                "$nochange(posedge clk, d, 3, 0, ntf);",
                "#7 d = 1;\n    #2 clk = 1;\n    #5 clk = 0;",
            ),
        );
        assert_eq!(
            stdout,
            "ntf=0 at 109\n109: $nochange violation: data top.u.d vs reference top.u.clk, \
             limit=3,0, actual=-2\n"
        );
        // 3 ticks before the edge is the (open) start of the window: no violation.
        let stdout = run_src(
            "nc-early-edge",
            &nochange_design(
                "$nochange(posedge clk, d, 3, 0, ntf);",
                "#6 d = 1;\n    #3 clk = 1;\n    #5 clk = 0;",
            ),
        );
        assert_eq!(violations(&stdout).len(), 0, "{stdout}");
    }

    /// A `negedge` reference makes the LOW period the window.
    #[test]
    fn run_design_nochange_negedge_reference_watches_the_low_period() {
        let run = |at: &str, tag: &str| {
            let stdout = run_src(
                tag,
                &nochange_design(
                    "$nochange(negedge clk, d, 0, 0);",
                    &format!("clk = 1;\n    #10 clk = 0;\n    {at}\n    #10 clk = 1;"),
                ),
            );
            violations(&stdout).len()
        };
        assert_eq!(
            run("#4 d = 1;", "nc-neg-in"),
            1,
            "d changes while clk is low"
        );
        assert_eq!(
            run("#0 d = 1;", "nc-neg-edge"),
            0,
            "d changes AT the negedge"
        );
    }

    // -----------------------------------------------------------------------
    // T20, LRM 31.4.1: `$skew`.

    /// One data event at `at`, measured at once: the skew if it violated.
    fn skew_measure(s: &mut SkewState, at: i64) -> Option<i64> {
        s.data_event(at);
        let n = s.pending();
        s.settle(n).first().copied()
    }

    /// `(timecheck time) - (timestamp time) > limit`, swept over every
    /// combination of a small range so the boundary is hit from both sides: a
    /// skew equal to the limit is not a violation.
    #[test]
    fn skew_state_sweep_matches_the_inequality() {
        let mut hits = 0;
        for limit in 0..=6 {
            for skew in 0..=8 {
                let mut s = SkewState::new(limit);
                s.reference_event(100);
                let got = skew_measure(&mut s, 100 + skew);
                let want = (skew > limit).then_some(skew);
                assert_eq!(got, want, "limit {limit}, skew {skew}");
                hits += usize::from(got.is_some());
            }
        }
        assert!(
            hits > 0,
            "the sweep must contain violations or it proves nothing"
        );
    }

    /// "After a reference event, the `$skew` timing check shall never stop
    /// checking data events": a violation does not spend the reference event, so
    /// EVERY later data event beyond the limit violates, each measured from it.
    #[test]
    fn skew_state_reports_every_late_data_event() {
        let mut s = SkewState::new(5);
        s.reference_event(10);
        let got: Vec<_> = [15, 16, 18, 30, 31].map(|t| skew_measure(&mut s, t)).into();
        assert_eq!(got, [None, Some(6), Some(8), Some(20), Some(21)]);
    }

    /// "A second consecutive reference event shall cancel the old wait for the
    /// data event and begin a new one": the skew is measured from the latest.
    #[test]
    fn skew_state_a_second_reference_event_replaces_the_first() {
        let mut s = SkewState::new(5);
        s.reference_event(10);
        s.reference_event(20);
        // Against the first reference this would be 12 > 5.
        assert_eq!(skew_measure(&mut s, 22), None);
        assert_eq!(skew_measure(&mut s, 26), Some(6));
    }

    /// "Simultaneous transitions on the reference and data signals shall not
    /// cause `$skew` to report a timing violation, even when the skew limit value
    /// is zero."
    #[test]
    fn skew_state_simultaneous_events_never_violate_even_with_limit_zero() {
        let mut s = SkewState::new(0);
        s.reference_event(10);
        assert_eq!(skew_measure(&mut s, 10), None);
        // The next data event, one tick later, does.
        assert_eq!(skew_measure(&mut s, 11), Some(1));
    }

    /// A data event is only PENDED until [`SkewState::settle`]: a reference event
    /// that arrives after it (a later delta of the same instant) is the one it is
    /// measured against, so the pair is simultaneous. Measured at once, the same
    /// data event would be 20 > 0 against the old reference.
    #[test]
    fn skew_state_a_data_event_waits_for_a_later_reference_event_of_its_instant() {
        let mut s = SkewState::new(0);
        s.reference_event(10);
        s.data_event(30);
        assert_eq!(s.pending(), 1);
        s.reference_event(30);
        assert_eq!(s.settle(1), Vec::<i64>::new());
        assert_eq!(s.pending(), 0);
        // Settling only the oldest `n`: the later data event stays pending.
        s.data_event(40);
        s.data_event(41);
        assert_eq!(s.settle(1), [10]);
        assert_eq!(s.pending(), 1);
        assert_eq!(s.settle(1), [11]);
    }

    /// "If there is never a data event ... no timing violation shall ever be
    /// reported": a reference event alone evaluates nothing, and a data event
    /// before any reference event has no timestamp to measure from.
    #[test]
    fn skew_state_is_never_evaluated_without_a_reference_and_a_data_event() {
        let mut s = SkewState::new(0);
        assert_eq!(skew_measure(&mut s, 5), None, "no reference event yet");
        assert_eq!(s.evaluations(), 0);
        s.reference_event(10);
        s.reference_event(20);
        assert_eq!(s.evaluations(), 0, "reference events evaluate nothing");
        assert_eq!(skew_measure(&mut s, 21), Some(1));
        assert_eq!(s.evaluations(), 1);
    }

    /// `deliver` takes a `$skew` data event without reporting it (even one that
    /// arrives with the reference event, in either order of the caller's list),
    /// `settle` measures it against the latest reference event; the other kinds
    /// still answer at once -- `$width` measures its timecheck against the
    /// PREVIOUS timestamp.
    #[test]
    fn deliver_defers_a_skew_data_event_and_only_a_skew_data_event() {
        let mut skew = Machine::Skew(SkewState::new(0));
        // The old reference at 10 would make a data event at 25 a 15 > 0 violation.
        assert!(skew.deliver(10, false, true, false).is_empty());
        assert!(skew.deliver(25, true, true, false).is_empty());
        assert_eq!(skew.pending(), 1);
        assert!(
            skew.settle(1).is_empty(),
            "the simultaneous reference event is the one the data event measures"
        );
        assert!(skew.deliver(26, true, false, false).is_empty());
        assert_eq!(skew.settle(1).len(), 1);

        let mut width = Machine::Width(WidthState::new(10, 0));
        assert!(width.deliver(10, false, true, false).is_empty());
        // Data first: the timecheck at 14 is measured against the timestamp at
        // 10 (4 < 10), then the new timestamp replaces it.
        let v = width.deliver(14, true, true, false);
        assert_eq!(v.len(), 1, "{v:?}");
        assert_eq!(v[0].actual, 4);
        assert_eq!(width.pending(), 0);
    }

    /// A negative limit is a named error: `$skew`'s limit is a "non-negative
    /// constant expression" (Table 31-7).
    #[test]
    fn run_design_skew_rejects_a_negative_limit_by_name() {
        let e = run_src_err(
            "skew-neg",
            &check_design("$skew(posedge clk, d, -1, ntf);", "clk = 1;"),
        );
        assert!(
            e.contains("$skew") && e.contains("non-negative") && e.contains("31.4.1"),
            "unexpected error: {e}"
        );
    }

    /// The exact output of one violation: a data change 8 ticks after a
    /// reference edge, limit 5. The notifier toggles x -> 0 (Table 31-13) and the
    /// message names the data and reference terminals, the limit and the skew.
    #[test]
    fn run_design_skew_violation_toggles_the_notifier_and_prints_the_message() {
        let stdout = run_src(
            "skew-exact",
            &check_design("$skew(posedge clk, d, 5, ntf);", "clk = 1;\n    #8 d = 1;"),
        );
        assert_eq!(
            stdout,
            "ntf=0 at 108\n108: $skew violation: data top.u.d vs reference top.u.clk, \
             limit=5, actual=8\n"
        );
    }

    /// The limit is closed: a skew of exactly the limit passes, one more fails;
    /// swept end to end.
    #[test]
    fn run_design_skew_sweep_is_closed_at_the_limit() {
        for (at, want) in [(0, false), (4, false), (5, false), (6, true), (9, true)] {
            let stdout = run_src(
                &format!("skew-sweep-{at}"),
                &check_design(
                    "$skew(posedge clk, d, 5, ntf);",
                    &format!("clk = 1;\n    #{at} d = 1;"),
                ),
            );
            assert_eq!(violations(&stdout).len(), usize::from(want), "at +{at}");
            assert_eq!(stdout.contains("ntf="), want, "notifier at +{at}");
        }
    }

    /// Every data event beyond the limit is reported (not only the first), and
    /// a data event with no reference event before it is never checked.
    #[test]
    fn run_design_skew_reports_every_data_event_and_none_before_a_reference() {
        let stdout = run_src(
            "skew-every",
            &check_design(
                "$skew(posedge clk, d, 5, ntf);",
                "d = 1;\n    #5 d = 0;\n    #5 clk = 1;\n    #7 d = 1;\n    #1 d = 0;\n    \
                 #1 d = 1;",
            ),
        );
        // The two changes of d before the edge at 110 have no timestamp.
        let v = violations(&stdout);
        assert_eq!(v.len(), 3, "{stdout}");
        assert!(
            v[0].starts_with("117:") && v[0].ends_with("actual=7"),
            "{}",
            v[0]
        );
        assert!(
            v[1].starts_with("118:") && v[1].ends_with("actual=8"),
            "{}",
            v[1]
        );
        assert!(
            v[2].starts_with("119:") && v[2].ends_with("actual=9"),
            "{}",
            v[2]
        );
    }

    /// A reference event with no data event after it reports nothing, and a
    /// second reference edge cancels the wait: the skew is measured from it.
    #[test]
    fn run_design_skew_a_second_reference_edge_cancels_the_old_wait() {
        let stdout = run_src(
            "skew-cancel",
            &check_design(
                "$skew(posedge clk, d, 5, ntf);",
                "clk = 1;\n    #3 clk = 0;\n    #3 clk = 1;\n    #3 d = 1;",
            ),
        );
        // d at 109: 9 after the first edge (would violate), 3 after the second.
        assert_eq!(stdout, "", "{stdout}");
        let stdout = run_src(
            "skew-never",
            &check_design(
                "$skew(posedge clk, d, 0, ntf);",
                "clk = 1;\n    #3 clk = 0;",
            ),
        );
        assert_eq!(stdout, "");
    }

    /// Simultaneous reference and data transitions never violate, even with a
    /// limit of 0 and an old reference event far in the past (so a data event
    /// that found it, instead of the simultaneous one, would violate).
    #[test]
    fn run_design_skew_simultaneous_transitions_do_not_violate_with_limit_zero() {
        let stdout = run_src(
            "skew-simul",
            &check_design(
                "$skew(posedge clk, d, 0, ntf);",
                "clk = 1;\n    #20 clk = 0;\n    #20 begin clk = 1; d = 1; end",
            ),
        );
        assert_eq!(stdout, "", "{stdout}");
        // The same events one tick apart do violate.
        let stdout = run_src(
            "skew-apart",
            &check_design(
                "$skew(posedge clk, d, 0, ntf);",
                "clk = 1;\n    #20 clk = 0;\n    #20 clk = 1;\n    #1 d = 1;",
            ),
        );
        assert_eq!(violations(&stdout).len(), 1, "{stdout}");
    }

    /// A design whose `$skew` reference reaches the check through `depth`
    /// continuous assignments (so it arrives `depth` deltas after the root `r0`),
    /// while the data signal `d` is written directly. `stim` is `top`'s `initial`
    /// body after `r0 = 0; d = 0;`.
    fn skew_late_reference_design(limit: i64, depth: usize, stim: &str) -> String {
        let mut wires = String::new();
        let mut prev = "r0".to_string();
        for i in 1..=depth {
            wires.push_str(&format!("  wire r{i};\n  assign r{i} = {prev};\n"));
            prev = format!("r{i}");
        }
        format!(
            "module chk(input r, input d);\n  reg ntf;\n  specify\n    $skew(posedge r, d, {limit}, \
             ntf);\n  endspecify\n  always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\n\
             endmodule\nmodule top;\n  reg r0, d;\n{wires}  chk u(.r({prev}), .d(d));\n  initial \
             begin\n    r0 = 0; d = 0;\n    {stim}\n    #100 $finish;\n  end\nendmodule\n"
        )
    }

    /// LRM 31.4.1: "Simultaneous transitions on the reference and data signals
    /// shall not cause `$skew` to report a timing violation, even when the skew
    /// limit value is zero." The reference reaches the check through continuous
    /// assignments, so it lands 1..3 delta cycles AFTER the data signal that the
    /// testbench writes in the same time step. The data event must still find the
    /// reference event of its own instant, not the one 20 ticks earlier (a
    /// 20 > 0 violation if it were measured in the dispatch that sees it).
    #[test]
    fn run_design_skew_a_reference_a_delta_late_is_still_simultaneous() {
        for depth in 1..=3 {
            let stdout = run_src(
                &format!("skew-delta-{depth}"),
                &skew_late_reference_design(
                    0,
                    depth,
                    "#10 r0 = 1;\n    #10 r0 = 0;\n    #10 begin d = 1; r0 = 1; end",
                ),
            );
            assert_eq!(stdout, "", "reference {depth} delta(s) late: {stdout}");
            // The reference written FIRST in the block: same instant, same answer.
            let stdout = run_src(
                &format!("skew-delta-rf-{depth}"),
                &skew_late_reference_design(
                    0,
                    depth,
                    "#10 r0 = 1;\n    #10 r0 = 0;\n    #10 begin r0 = 1; d = 1; end",
                ),
            );
            assert_eq!(
                stdout, "",
                "reference first, {depth} delta(s) late: {stdout}"
            );
        }
    }

    /// The deferral measures, it does not drop: with the same late reference, a
    /// data event after the reference edge still violates (limit 0) at the data
    /// event's own time, and a simultaneous pair between two violations is
    /// skipped.
    #[test]
    fn run_design_skew_a_delta_late_reference_still_reports_real_violations() {
        let stdout = run_src(
            "skew-delta-real",
            &skew_late_reference_design(
                0,
                2,
                "#10 r0 = 1;\n    #1 d = 1;\n    #5 r0 = 0;\n    #5 begin d = 0; r0 = 1; end\n    \
                 #5 d = 1;",
            ),
        );
        // d at 11 is 1 > 0 after the edge at 10; d at 21 is simultaneous with the
        // new edge (none); d at 26 is 5 after it.
        assert_eq!(
            stdout,
            "ntf=0 at 11\n11: $skew violation: data top.u.d vs reference top.u.r, limit=0, \
             actual=1\nntf=1 at 26\n26: $skew violation: data top.u.d vs reference top.u.r, \
             limit=0, actual=5\n"
        );
    }

    /// The reference event's edge selection and condition apply: a falling edge
    /// is no reference event for `posedge`, and `&&&` gates the data event.
    #[test]
    fn run_design_skew_edge_and_condition_select_the_events() {
        let stdout = run_src(
            "skew-edge",
            &check_design(
                "$skew(posedge clk, d, 5, ntf);",
                "clk = 1;\n    #10 clk = 0;\n    #10 d = 1;",
            ),
        );
        assert_eq!(violations(&stdout).len(), 1, "d at +20 from the posedge");
        let stdout = run_src(
            "skew-neg-ref",
            &check_design(
                "$skew(negedge clk, d, 5, ntf);",
                "clk = 1;\n    #10 clk = 0;\n    #3 d = 1;\n    #10 d = 0;",
            ),
        );
        // The reference is the negedge at 110: d at 113 is 3 after it (within
        // the limit, but 13 after the posedge at 100), d at 123 is 13 after it.
        // (The `x -> 0` of `clk = 0` at time 0 is a negedge too, but d does not change before 110.)
        let v = violations(&stdout);
        assert_eq!(v.len(), 1, "{stdout}");
        assert!(
            v[0].starts_with("123:") && v[0].ends_with("actual=13"),
            "{}",
            v[0]
        );
        let stdout = run_src(
            "skew-cond",
            &check_design(
                "$skew(posedge clk, d &&& clk, 5, ntf);",
                "clk = 1;\n    #10 d = 1;\n    #10 clk = 0;\n    #10 d = 0;",
            ),
        );
        // d rises at +10 with clk high: condition true, skew 10 > 5. d falls
        // at +30 with clk low: the condition gates that data event out.
        assert_eq!(violations(&stdout).len(), 1, "{stdout}");
    }

    // -----------------------------------------------------------------------
    // T21a, LRM 31.4.2: `$timeskew`, the state machine.

    /// One event of a `$timeskew` / `$fullskew` replay.
    #[derive(Clone, Copy, Debug)]
    enum Ev {
        /// A reference event whose condition holds: a timestamp event.
        Ref,
        /// A reference EDGE whose `&&&` condition is false.
        RefFalse,
        /// A data event.
        Data,
        /// A data EDGE whose `&&&` condition is false (a `$fullskew` data event is
        /// a timestamp event too).
        DataFalse,
    }

    /// Replays `events` (`(time, event)`, in time order) through `s` the way
    /// [`CheckProcess::resume`] drives one: at every instant the reference events
    /// come first, then the data events, which are measured against the latest of
    /// them, and last the timer, which is decided only once the instant's other
    /// events are in. Returns each violation as `(time it is reported, actual,
    /// limit)`.
    fn skew_replay(mut s: TimeSkewState, events: &[(i64, Ev)]) -> Vec<(i64, i64, i64)> {
        let mut hits = Vec::new();
        let mut i = 0;
        loop {
            let now = match (events.get(i).map(|e| e.0), s.deadline()) {
                (None, None) => break,
                (Some(t), None) | (None, Some(t)) => t,
                (Some(t), Some(d)) => t.min(d),
            };
            let from = i;
            while events.get(i).is_some_and(|e| e.0 == now) {
                i += 1;
            }
            let batch = &events[from..i];
            for (_, ev) in batch {
                match ev {
                    Ev::Ref => s.reference_event(now),
                    Ev::RefFalse => s.reference_suppressed(now),
                    Ev::DataFalse => s.data_suppressed(now),
                    Ev::Data => {}
                }
            }
            for _ in batch.iter().filter(|(_, ev)| matches!(ev, Ev::Data)) {
                s.data_event(now);
            }
            let n = s.pending();
            hits.extend(s.settle_limited(n).into_iter().map(|(a, l)| (now, a, l)));
            hits.extend(s.expire_limited(now).map(|(a, l)| (now, a, l)));
        }
        hits
    }

    /// [`skew_replay`] of a `$timeskew`: each violation as `(time it is reported,
    /// actual)`.
    fn timeskew_replay(limit: i64, flags: SkewFlags, events: &[(i64, Ev)]) -> Vec<(i64, i64)> {
        skew_replay(TimeSkewState::new(limit, flags), events)
            .into_iter()
            .map(|(t, actual, _)| (t, actual))
            .collect()
    }

    fn flags(event_based: bool, remain_active: bool) -> SkewFlags {
        SkewFlags {
            event_based,
            remain_active,
        }
    }

    /// LRM Figure 31-1's waveform as state-machine events, the lettered points
    /// at the times `figure_31_1` of the end-to-end tests uses (limit 50).
    fn figure_31_1_events() -> Vec<(i64, Ev)> {
        let mut e = vec![(100, Ev::Ref)];
        e.extend([160, 170, 180].map(|t| (t, Ev::Data)));
        e.push((185, Ev::RefFalse));
        e.extend([190, 200, 210, 220].map(|t| (t, Ev::Data)));
        e
    }

    /// Figure 31-2's: F (MODE false) before the limit expires at B.
    fn figure_31_2_events() -> Vec<(i64, Ev)> {
        let mut e = vec![(100, Ev::Ref), (120, Ev::RefFalse)];
        e.extend([160, 170, 180, 190].map(|t| (t, Ev::Data)));
        e
    }

    /// The four flag combinations of 31.4.2 in the LRM's Case order.
    fn timeskew_cases() -> [SkewFlags; 4] {
        [
            flags(false, false),
            flags(true, false),
            flags(true, true),
            flags(false, true),
        ]
    }

    /// Figure 31-1, all four cases against one waveform: the violations the
    /// prose names at each lettered point.
    #[test]
    fn timeskew_state_replays_figure_31_1_for_all_four_cases() {
        let want: [Vec<(i64, i64)>; 4] = [
            // Case 1: at B (A + 50) only.
            vec![(150, 50)],
            // Case 2: at C only, dormant after it and at F.
            vec![(160, 60)],
            // Case 3: C, D, E, then (F ignored) G, H, I, J.
            [160, 170, 180, 190, 200, 210, 220]
                .map(|t| (t, t - 100))
                .to_vec(),
            // Case 4: the same as Case 1.
            vec![(150, 50)],
        ];
        for (f, want) in timeskew_cases().into_iter().zip(want) {
            assert_eq!(timeskew_replay(50, f, &figure_31_1_events()), want, "{f:?}");
        }
    }

    /// Figure 31-2: the reference event F, MODE false, before the limit
    /// expires. Only `remain_active_flag` keeps A's wait alive.
    #[test]
    fn timeskew_state_replays_figure_31_2_for_all_four_cases() {
        let want: [Vec<(i64, i64)>; 4] = [
            vec![],
            vec![],
            vec![(160, 60), (170, 70), (180, 80), (190, 90)],
            vec![(150, 50)],
        ];
        for (f, want) in timeskew_cases().into_iter().zip(want) {
            assert_eq!(timeskew_replay(50, f, &figure_31_2_events()), want, "{f:?}");
        }
    }

    /// The same Figure 31-2 waveform where F's condition is TRUE: it is a new
    /// timestamp event, which cancels A's wait in every case and restarts it (so
    /// the violations are measured from F), whatever the flags -- the proof that
    /// the two figures differ only by F's condition.
    #[test]
    fn timeskew_state_a_true_conditioned_reference_restarts_the_wait_in_every_case() {
        let mut events = figure_31_2_events();
        events[1].1 = Ev::Ref;
        let want: [Vec<(i64, i64)>; 4] = [
            // Timer from F=120 expires at 170 (before any data: the first CPN
            // fall is at 160, within the new limit: dormant at once).
            vec![],
            // Event-based: 160 is 40 after F (within), 170 is 50 (the limit), 180
            // is 60: the first violation, dormant afterwards.
            vec![(180, 60)],
            vec![(180, 60), (190, 70)],
            vec![],
        ];
        for (f, want) in timeskew_cases().into_iter().zip(want) {
            assert_eq!(timeskew_replay(50, f, &events), want, "{f:?}");
        }
    }

    /// Both modes swept over every (limit, data time) of a small range, so the
    /// boundary is hit from both sides: a skew equal to the limit never violates;
    /// beyond it the timer (default) reports at the EXPIRY with `actual` = the
    /// limit, the event-based check at the data event with the skew itself.
    #[test]
    fn timeskew_state_sweep_is_closed_at_the_limit_in_both_modes() {
        let mut violations = 0;
        for limit in 0..=5 {
            for skew in 0..=8 {
                let events = [(100, Ev::Ref), (100 + skew, Ev::Data)];
                let timer = timeskew_replay(limit, flags(false, false), &events);
                let event = timeskew_replay(limit, flags(true, false), &events);
                if skew > limit {
                    assert_eq!(
                        timer,
                        [(100 + limit, limit)],
                        "timer: limit {limit}, skew {skew}"
                    );
                    assert_eq!(
                        event,
                        [(100 + skew, skew)],
                        "event: limit {limit}, skew {skew}"
                    );
                    violations += 2;
                } else {
                    assert_eq!(timer, [], "timer: limit {limit}, skew {skew}");
                    assert_eq!(event, [], "event: limit {limit}, skew {skew}");
                }
            }
        }
        assert!(violations > 0, "a sweep with no violation proves nothing");
    }

    /// No data event at all: the timer-based check still reports (at the expiry);
    /// the event-based one never does ("evaluated only after a data event").
    #[test]
    fn timeskew_state_reports_a_missing_data_event_only_when_timer_based() {
        let events = [(100, Ev::Ref)];
        assert_eq!(timeskew_replay(7, flags(false, false), &events), [(107, 7)]);
        assert_eq!(timeskew_replay(7, flags(false, true), &events), [(107, 7)]);
        assert_eq!(timeskew_replay(7, flags(true, false), &events), []);
        assert_eq!(timeskew_replay(7, flags(true, true), &events), []);
    }

    /// "The $timeskew check behaves like the $skew check when both the
    /// event_based_flag and the remain_active_flag are set": the same model, run
    /// on the same random-looking stimulus, reports exactly what [`SkewState`] does
    /// (every data event beyond the limit of the latest reference event, and not
    /// the ones at it), reference events with a true condition only.
    #[test]
    fn timeskew_state_event_based_and_remain_active_is_skew() {
        let stimulus = [
            (3, Ev::Ref),
            (5, Ev::Data),
            (12, Ev::Data),
            (12, Ev::Ref),
            (14, Ev::Data),
            (20, Ev::Data),
            (20, Ev::Ref),
            (31, Ev::Data),
            (31, Ev::Data),
            (40, Ev::RefFalse),
            (47, Ev::Data),
        ];
        for limit in [0, 1, 2, 5] {
            let got = timeskew_replay(limit, flags(true, true), &stimulus);
            // SkewState, fed the same events instant by instant.
            let mut skew = SkewState::new(limit);
            let mut want = Vec::new();
            let mut i = 0;
            while i < stimulus.len() {
                let now = stimulus[i].0;
                let batch: Vec<Ev> = stimulus[i..]
                    .iter()
                    .take_while(|e| e.0 == now)
                    .map(|e| e.1)
                    .collect();
                i += batch.len();
                if batch.iter().any(|e| matches!(e, Ev::Ref)) {
                    skew.reference_event(now);
                }
                for _ in batch.iter().filter(|e| matches!(e, Ev::Data)) {
                    skew.data_event(now);
                }
                let n = skew.pending();
                want.extend(skew.settle(n).into_iter().map(|a| (now, a)));
            }
            assert_eq!(got, want, "limit {limit}");
        }
    }

    /// "The $timeskew check behaves like the $skew check when only the
    /// event_based_flag is set, except that it becomes dormant after reporting the
    /// first violation or if it detects a conditioned reference event when its
    /// condition is false": data within the limit does NOT make it dormant (unlike
    /// the timer-based check), the first violation does, the next true-conditioned
    /// reference event wakes it.
    #[test]
    fn timeskew_state_event_based_goes_dormant_only_after_a_violation_or_a_false_reference() {
        let f = flags(true, false);
        let events = [
            (100, Ev::Ref),
            (103, Ev::Data), // within the limit: still active
            (105, Ev::Data), // exactly the limit: still active
            (106, Ev::Data), // VIOLATION, then dormant
            (107, Ev::Data),
            (110, Ev::Ref), // active again
            (118, Ev::Data),
            (120, Ev::RefFalse), // dormant
            (130, Ev::Data),
            (140, Ev::Ref),
            (146, Ev::Data),
        ];
        assert_eq!(
            timeskew_replay(5, f, &events),
            [(106, 6), (118, 8), (146, 6)]
        );
    }

    /// Timer-based: "if a data event occurs within the limit ... the check shall
    /// become dormant immediately", and stays so "until after the next reference
    /// event" -- through any number of later data events and the old expiry.
    #[test]
    fn timeskew_state_timer_based_goes_dormant_at_an_in_limit_data_event_until_the_next_reference()
    {
        let events = [
            (100, Ev::Ref),
            (102, Ev::Data),
            (104, Ev::Data),
            (110, Ev::Data),
            (200, Ev::Ref),
        ];
        assert_eq!(timeskew_replay(5, flags(false, false), &events), [(205, 5)]);
    }

    /// A false-conditioned reference event is not a timestamp event: it neither
    /// arms an idle check nor, with remain_active, moves the wait it ignores.
    #[test]
    fn timeskew_state_a_false_reference_arms_nothing_and_moves_nothing() {
        for ra in [false, true] {
            let f = flags(false, ra);
            let mut s = TimeSkewState::new(10, f);
            s.reference_suppressed(0);
            assert_eq!(s.deadline(), None, "idle, remain_active {ra}");
            s.reference_event(50);
            assert_eq!(s.deadline(), Some(60));
            s.reference_suppressed(55);
            assert_eq!(
                s.deadline(),
                ra.then_some(60),
                "armed at 50, remain_active {ra}: kept (not moved) iff the flag is set"
            );
        }
    }

    /// `deadline`: the timer exists only for the timer-based check, only while
    /// it is active, and is the LAST reference event's.
    #[test]
    fn timeskew_state_deadline_follows_the_active_timer_based_wait() {
        let mut s = TimeSkewState::new(10, flags(false, false));
        assert_eq!(s.deadline(), None, "no reference event yet");
        s.reference_event(5);
        assert_eq!(s.deadline(), Some(15));
        s.reference_event(8);
        assert_eq!(s.deadline(), Some(18), "the second reference restarts it");
        assert_eq!(s.expire(17), None, "not yet");
        assert_eq!(s.deadline(), Some(18));
        assert_eq!(s.expire(18), Some(10));
        assert_eq!(s.deadline(), None, "dormant after the violation");
        assert_eq!(s.expire(18), None, "reported once");
        let mut e = TimeSkewState::new(10, flags(true, true));
        e.reference_event(5);
        assert_eq!(e.deadline(), None, "event-based: no timer");
        assert_eq!(e.expire(1000), None);
    }

    /// The expiry is decided only when no data event waits to be measured: a
    /// data event that arrived at the expiry itself is "within the limit".
    #[test]
    fn timeskew_state_expiry_waits_for_the_pending_data_events() {
        let mut s = TimeSkewState::new(5, flags(false, false));
        s.reference_event(100);
        s.data_event(105);
        assert_eq!(s.expire(105), None, "a data event is still to be measured");
        assert_eq!(s.settle(1), Vec::<i64>::new(), "skew 5 = limit: within it");
        assert_eq!(s.expire(105), None, "dormant: nothing to report");
        assert_eq!(s.deadline(), None);
    }

    /// The backstop of the model itself: a timer-based check handed a data event
    /// beyond the limit that its timer never fired for (the caller does not call
    /// [`TimeSkewState::expire`]) still reports `(timecheck) - (timestamp) >
    /// limit` and becomes dormant, rather than silently dropping it.
    #[test]
    fn timeskew_state_a_late_data_event_with_no_expiry_still_violates_once() {
        let mut s = TimeSkewState::new(5, flags(false, false));
        s.reference_event(100);
        s.data_event(120);
        s.data_event(121);
        assert_eq!(s.settle(2), [20], "reported once; dormant for the second");
        assert_eq!(s.deadline(), None);
    }

    /// A data event with no timestamp, or once dormant, is not measured; and a
    /// data event is only pended until settled, like `$skew`'s.
    #[test]
    fn timeskew_state_data_events_without_a_wait_are_ignored() {
        let mut s = TimeSkewState::new(0, flags(true, true));
        s.data_event(5);
        assert_eq!(s.pending(), 1);
        assert_eq!(s.settle(1), Vec::<i64>::new(), "no reference event yet");
        assert_eq!(s.pending(), 0);
    }

    /// A data event pended in one dispatch is measured against a reference event
    /// of a later delta of its instant ([`SkewState`]'s rule, kept): simultaneous
    /// with limit 0 never violates, in either order.
    #[test]
    fn timeskew_state_a_data_event_waits_for_a_later_reference_event_of_its_instant() {
        for event_based in [false, true] {
            let mut s = TimeSkewState::new(0, flags(event_based, true));
            s.reference_event(10);
            s.data_event(30);
            s.reference_event(30);
            assert_eq!(s.settle(1), Vec::<i64>::new(), "event_based {event_based}");
        }
    }

    /// `Machine::TimeSkew` carries the state through every `Machine` entry
    /// point: `deliver` pends a data event, `settle` measures it with the check's
    /// limit, `deadline`/`expire` are the timer, `reference_suppressed` the
    /// false-condition reference. Every other kind has none of those.
    #[test]
    fn machine_time_skew_routes_every_entry_point() {
        let spec = CheckSpec::TimeSkew {
            limit: 5,
            flags: flags(true, false),
        };
        assert_eq!(spec.name(), "$timeskew");
        assert_eq!(spec.limit_label(), None);
        let mut m = spec.machine();
        assert!(m.deliver(10, false, true, false).is_empty());
        assert!(m.deliver(20, true, false, false).is_empty(), "pended");
        assert_eq!(m.pending(), 1);
        let v = m.settle(1);
        assert_eq!(v.len(), 1);
        assert_eq!((v[0].actual, v[0].limit), (10, 5));
        // Event-based and not remain_active: the violation made it dormant.
        assert!(m.deliver(30, true, false, false).is_empty());
        assert!(m.settle(1).is_empty());

        let mut t = CheckSpec::TimeSkew {
            limit: 5,
            flags: flags(false, false),
        }
        .machine();
        assert_eq!(t.deadline(), None);
        t.deliver(100, false, true, false);
        assert_eq!(t.deadline(), Some(105));
        let v = t.expire(105).expect("the timer expires");
        assert_eq!((v.actual, v.limit), (5, 5));
        assert_eq!(t.deadline(), None);
        t.deliver(110, false, true, false);
        t.reference_suppressed(110);
        assert_eq!(
            t.deadline(),
            None,
            "dormant by the false-condition reference"
        );

        for other in [
            Machine::Skew(SkewState::new(1)),
            Machine::Period(PeriodState::new(1)),
        ] {
            let mut other = other;
            assert_eq!(other.deadline(), None);
            assert!(other.expire(1000).is_none());
            other.reference_suppressed(0);
            assert_eq!(other.pending(), 0);
        }
    }

    /// `$timeskew`'s limit is validated like `$skew`'s, naming the clause.
    #[test]
    fn timeskew_spec_rejects_a_negative_limit_and_decodes_the_flags() {
        let src = "`timescale 1ns/1ps\nmodule m(input d, input clk);\n  reg n;\n  specify\n    \
                   $timeskew(posedge clk, d, 5, n);\n    $timeskew(posedge clk, d, 6, n, 1);\n    \
                   $timeskew(posedge clk, d, 7, n, 0, 1);\n    $timeskew(posedge clk, d, 8, n, \
                   , 1);\n  endspecify\nendmodule\n";
        let model = discovered(src).unwrap_or_else(|e| panic!("discover failed: {e}"));
        let specs: Vec<CheckSpec> = model
            .timing_checks
            .iter()
            .map(|c| {
                let CheckArgs::TimeSkew(a) = &c.args else {
                    panic!("not $timeskew: {:?}", c.args)
                };
                timeskew_spec(a, &c.check_uid).expect("valid")
            })
            .collect();
        let want = [
            (5, false, false),
            (6, true, false),
            (7, false, true),
            (8, false, true),
        ]
        .map(|(limit, event_based, remain_active)| CheckSpec::TimeSkew {
            limit: limit * 1000,
            flags: flags(event_based, remain_active),
        });
        assert_eq!(specs, want, "elided flags are 0, the LRM default");
    }

    // -----------------------------------------------------------------------
    // T21a, LRM 31.4.2: `$timeskew`, end to end.

    /// One `chk(cp, cpn, mode)` carrying the check text, driven by `top`:
    /// `cp = 0; cpn = 1; mode = 1;` at time 0 and then `events`, each an
    /// ABSOLUTE time and a statement, in time order (the design waits until 100
    /// first, so nothing sits at time 0), then `$finish` at 300.
    fn timeskew_design(check: &str, events: &[(i64, &str)]) -> String {
        skew_design(check, events, 300)
    }

    /// [`timeskew_design`] finishing at `finish` instead of 300.
    fn skew_design(check: &str, events: &[(i64, &str)], finish: i64) -> String {
        let mut stim = String::new();
        let mut at = 100;
        for &(t, stmt) in events {
            assert!(t >= at, "events must be in time order: {t} after {at}");
            if t > at {
                stim.push_str(&format!("#{} ", t - at));
            }
            stim.push_str(stmt);
            stim.push('\n');
            at = t;
        }
        format!(
            "module chk(input cp, input cpn, input mode);\n  reg ntf;\n  specify\n    {check}\n  \
             endspecify\n  always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\n\
             module top;\n  reg cp, cpn, mode;\n  chk u(.cp(cp), .cpn(cpn), .mode(mode));\n  \
             initial begin\n    cp = 0; cpn = 1; mode = 1;\n    #100;\n    {stim}    #{} $finish;\n  \
             end\nendmodule\n",
            finish - at
        )
    }

    /// Every violation line of `stdout` as `(time it is reported, actual)`.
    fn timeskew_hits(stdout: &str) -> Vec<(i64, i64)> {
        violations(stdout)
            .into_iter()
            .map(|l| {
                assert!(l.contains("$timeskew violation"), "unexpected line: {l}");
                let time = l.split(':').next().unwrap().parse().expect("time");
                let actual = l.rsplit("actual=").next().unwrap().parse().expect("actual");
                (time, actual)
            })
            .collect()
    }

    /// A falling edge of `cpn` (a data event of `negedge cpn`) at `t`, back up
    /// one tick later.
    fn cpn_fall(events: &mut Vec<(i64, &'static str)>, t: i64) {
        events.push((t, "cpn = 0;"));
        events.push((t + 1, "cpn = 1;"));
    }

    /// LRM Figure 31-1's waveform, with the lettered points of the figure at
    /// these times (the limit is 50):
    ///
    /// ```text
    ///   A=100  CP rises, MODE true       B=150  A + 50
    ///   C=160  D=170  E=180  CPN falls   F=185  CP rises, MODE false
    ///   G=190  H=200  I=210  J=220       CPN falls
    /// ```
    fn figure_31_1() -> Vec<(i64, &'static str)> {
        let mut e = vec![(100, "cp = 1;"), (110, "cp = 0;")];
        for t in [160, 170, 180] {
            cpn_fall(&mut e, t);
        }
        e.push((183, "mode = 0;"));
        e.push((185, "cp = 1;"));
        for t in [190, 200, 210, 220] {
            cpn_fall(&mut e, t);
        }
        e.sort_by_key(|&(t, _)| t);
        e
    }

    /// LRM Figure 31-2's waveform: the second CP edge F (MODE false) comes
    /// BEFORE the limit expires at B.
    ///
    /// ```text
    ///   A=100  CP rises, MODE true       F=120  CP rises, MODE false
    ///   B=150  A + 50
    ///   C=160  D=170  E=180  G=190       CPN falls
    /// ```
    fn figure_31_2() -> Vec<(i64, &'static str)> {
        let mut e = vec![
            (100, "cp = 1;"),
            (110, "cp = 0;"),
            (115, "mode = 0;"),
            (120, "cp = 1;"),
        ];
        for t in [160, 170, 180, 190] {
            cpn_fall(&mut e, t);
        }
        e.sort_by_key(|&(t, _)| t);
        e
    }

    /// `(event_based_flag, remain_active_flag)` of Cases 1-4 of 31.4.2, in the
    /// LRM's order.
    const TIMESKEW_CASES: [(u8, u8); 4] = [(0, 0), (1, 0), (1, 1), (0, 1)];

    /// The violations, as `(report time, actual)`, one `$timeskew` makes on
    /// `events`, with the figures' check and the given flags.
    fn figure_hits(
        tag: &str,
        events: &[(i64, &str)],
        event_based: u8,
        remain_active: u8,
    ) -> Vec<(i64, i64)> {
        let check = format!(
            "$timeskew(posedge cp &&& mode, negedge cpn, 50, ntf, {event_based}, {remain_active});"
        );
        let stdout = run_src(tag, &timeskew_design(&check, events));
        let hits = timeskew_hits(&stdout);
        // The notifier toggles once per violation (Table 31-13).
        assert_eq!(
            stdout.matches("ntf=").count(),
            hits.len(),
            "one notifier toggle per violation: {stdout}"
        );
        hits
    }

    /// LRM 31.4.2, Figure 31-1, all four cases against the SAME waveform: the
    /// exact set of violations the prose names at each lettered point.
    #[test]
    fn run_design_timeskew_figure_31_1_cases_1_to_4() {
        let all_late = vec![
            (160, 60),
            (170, 70),
            (180, 80),
            (190, 90),
            (200, 100),
            (210, 110),
            (220, 120),
        ];
        let want: [(&str, Vec<(i64, i64)>); 4] = [
            // Case 1: "a violation is reported at B as soon as 50 time units
            // have passed, turning the $timeskew check dormant, and no further
            // violations are reported."
            ("case 1", vec![(150, 50)]),
            // Case 2: "the negative transition on CPN at point C causes a
            // timing violation, turning the check dormant ... The second
            // reference event at F occurs while MODE is false; therefore, the
            // check remains dormant."
            ("case 2", vec![(160, 60)]),
            // Case 3: C, D, E violate; F is ignored (remain_active_flag); G, H,
            // I and J violate: "identical to $skew behavior".
            ("case 3", all_late),
            // Case 4: "the same behavior in Case 4 as in Case 1".
            ("case 4", vec![(150, 50)]),
        ];
        for (i, ((eb, ra), (name, hits))) in TIMESKEW_CASES.into_iter().zip(want).enumerate() {
            let got = figure_hits(&format!("ts-f1-{i}"), &figure_31_1(), eb, ra);
            assert_eq!(got, hits, "{name} (event_based {eb}, remain_active {ra})");
        }
    }

    /// LRM 31.4.2, Figure 31-2: the reference event F falls (MODE false) before
    /// the limit expires. "Although the reference event on CP at F occurs while
    /// MODE is false, it does not turn the $timeskew check dormant because the
    /// remain_active_flag is set. A violation will hence be reported at time B,
    /// whereas for Case 1, where the remain_active_flag is not set, the
    /// $timeskew check would turn dormant at F, and no violation would be
    /// reported."
    #[test]
    fn run_design_timeskew_figure_31_2_remain_active_decides_the_violation_at_b() {
        let want: [Vec<(i64, i64)>; 4] = [
            // Case 1: dormant at F, nothing at B.
            vec![],
            // Case 2: dormant at F; the later CPN falls are not looked at.
            vec![],
            // Case 3: F ignored, and every CPN fall violates against A.
            vec![(160, 60), (170, 70), (180, 80), (190, 90)],
            // Case 4: F ignored, the timer of A expires at B.
            vec![(150, 50)],
        ];
        for (i, ((eb, ra), hits)) in TIMESKEW_CASES.into_iter().zip(want).enumerate() {
            let got = figure_hits(&format!("ts-f2-{i}"), &figure_31_2(), eb, ra);
            assert_eq!(
                got,
                hits,
                "case {} (event_based {eb}, remain_active {ra})",
                i + 1
            );
        }
    }

    /// The figures' own spelling: an EMPTY notifier slot (`50, , 1, 1`) is a
    /// check without a notifier, and each flag may also be elided.
    #[test]
    fn run_design_timeskew_accepts_an_empty_notifier_slot_and_elided_flags() {
        let stdout = run_src(
            "ts-nontf",
            &timeskew_design(
                "$timeskew(posedge cp &&& mode, negedge cpn, 50, , 1, 1);",
                &figure_31_1(),
            ),
        );
        assert_eq!(timeskew_hits(&stdout).len(), 7, "{stdout}");
        assert!(!stdout.contains("ntf="), "no notifier is toggled: {stdout}");
        // `$timeskew(ref, data, limit)`: both flags elided = Case 1.
        let stdout = run_src(
            "ts-elided",
            &timeskew_design(
                "$timeskew(posedge cp &&& mode, negedge cpn, 50);",
                &figure_31_1(),
            ),
        );
        assert_eq!(timeskew_hits(&stdout), [(150, 50)], "{stdout}");
        // `$timeskew(ref, data, limit, ntf, 1)`: remain_active elided = 0.
        let stdout = run_src(
            "ts-one-flag",
            &timeskew_design(
                "$timeskew(posedge cp &&& mode, negedge cpn, 50, ntf, 1);",
                &figure_31_1(),
            ),
        );
        assert_eq!(timeskew_hits(&stdout), [(160, 60)], "{stdout}");
    }

    /// The flags are constant expressions (Table 31-8) and the remain_active
    /// flag a constant MINTYPMAX expression (Syntax 31-10): a parameter and a
    /// `min:typ:max` triple both decode.
    #[test]
    fn run_design_timeskew_flags_are_constant_expressions() {
        // The parameters belong in the module body, before `specify`.
        let src = timeskew_design(
            "$timeskew(posedge cp &&& mode, negedge cpn, 50, ntf, EB, RA);",
            &figure_31_1(),
        )
        .replacen(
            "  reg ntf;\n",
            "  parameter EB = 1;\n  localparam RA = 1 + 0;\n  reg ntf;\n",
            1,
        );
        assert_eq!(timeskew_hits(&run_src("ts-param", &src)).len(), 7);
        let stdout = run_src(
            "ts-mtm",
            &timeskew_design(
                "$timeskew(posedge cp &&& mode, negedge cpn, 50, ntf, 1, (1:1:1));",
                &figure_31_1(),
            ),
        );
        assert_eq!(timeskew_hits(&stdout).len(), 7, "{stdout}");
    }

    /// The default (timer-based) check reports at the instant the limit
    /// elapses, with NO data event at all, and says so exactly: the notifier
    /// toggles x -> 0 and the line names the check, the terminals, the limit and
    /// the elapsed time. (`$skew` would report nothing here: it is only ever
    /// evaluated at a data event.)
    #[test]
    fn run_design_timeskew_timer_reports_a_missing_data_event_exactly() {
        let stdout = run_src(
            "ts-exact",
            &timeskew_design(
                "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                &[(100, "cp = 1;")],
            ),
        );
        assert_eq!(
            stdout,
            "ntf=0 at 105\n105: $timeskew violation: data top.u.cpn vs reference top.u.cp, \
             limit=5, actual=5\n"
        );
    }

    /// The limit is closed on both sides of the timer: a data event AT the
    /// expiry (a skew equal to the limit) is within the limit, so it is not a
    /// violation and the check is dormant; one tick later is a violation of the
    /// timer, which had fired.
    #[test]
    fn run_design_timeskew_a_data_event_at_the_expiry_is_within_the_limit() {
        for (at, want) in [(103, vec![]), (105, vec![]), (106, vec![(105, 5)])] {
            let stdout = run_src(
                &format!("ts-edge-{at}"),
                &timeskew_design(
                    "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                    &[(100, "cp = 1;"), (at, "cpn = 0;")],
                ),
            );
            assert_eq!(timeskew_hits(&stdout), want, "data at {at}: {stdout}");
        }
    }

    /// "If a data event occurs within the limit, then a violation shall not be
    /// reported, and the check shall become dormant immediately": the later
    /// data event beyond the limit is not reported either, and the next
    /// reference event re-arms the check.
    #[test]
    fn run_design_timeskew_goes_dormant_after_an_in_limit_data_event_until_the_next_reference() {
        let stdout = run_src(
            "ts-dormant",
            &timeskew_design(
                "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                &[
                    (100, "cp = 1;"),
                    (103, "cpn = 0;"),
                    (104, "cpn = 1;"),
                    (108, "cpn = 0;"),
                    (120, "cp = 0;"),
                    (130, "cp = 1;"),
                ],
            ),
        );
        // Nothing for A=100 (dormant at 103, not even at 105 or for 108); the
        // reference at 130 is armed again and its timer expires at 135.
        assert_eq!(timeskew_hits(&stdout), [(135, 5)], "{stdout}");
    }

    /// "$timeskew shall also not report a violation if a new timestamp event
    /// occurs exactly at the expiration of the time limit": the new reference
    /// event cancels the old wait, and begins its own (so there is exactly one
    /// violation, at its expiry).
    #[test]
    fn run_design_timeskew_a_new_reference_at_the_expiry_cancels_the_violation() {
        let stdout = run_src(
            "ts-cancel",
            &timeskew_design(
                "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                &[(100, "cp = 1;"), (102, "cp = 0;"), (105, "cp = 1;")],
            ),
        );
        assert_eq!(timeskew_hits(&stdout), [(110, 5)], "{stdout}");
    }

    /// "Simultaneous transitions on the reference and data signals shall not
    /// cause $timeskew to report a timing violation, even when the skew limit
    /// value is zero", in either order of the two writes. (With limit 0 and NO
    /// data event the timer expires with the reference event itself: a
    /// violation, at once.)
    #[test]
    fn run_design_timeskew_simultaneous_transitions_do_not_violate_with_limit_zero() {
        for (tag, stmt) in [
            ("ts-simul-rd", "begin cp = 1; cpn = 0; end"),
            ("ts-simul-dr", "begin cpn = 0; cp = 1; end"),
        ] {
            let stdout = run_src(
                tag,
                &timeskew_design(
                    "$timeskew(posedge cp, negedge cpn, 0, ntf);",
                    &[(100, stmt)],
                ),
            );
            assert_eq!(stdout, "", "{tag}: {stdout}");
        }
        let stdout = run_src(
            "ts-simul-none",
            &timeskew_design(
                "$timeskew(posedge cp, negedge cpn, 0, ntf);",
                &[(100, "cp = 1;")],
            ),
        );
        assert_eq!(timeskew_hits(&stdout), [(100, 0)], "{stdout}");
    }

    /// `$timeskew` whose data / reference events reach the check `depth` delta
    /// cycles after the testbench writes them (through continuous assignments),
    /// `stim` being `top`'s `initial` body after `cp0 = 0; dn0 = 1;` (the
    /// design waits until 100 first).
    fn timeskew_late_design(check: &str, depth: usize, stim: &str) -> String {
        let (mut wires, mut cp, mut dn) = (String::new(), "cp0".to_string(), "dn0".to_string());
        for i in 1..=depth {
            wires.push_str(&format!(
                "  wire cp{i}, dn{i};\n  assign cp{i} = {cp};\n  assign dn{i} = {dn};\n"
            ));
            (cp, dn) = (format!("cp{i}"), format!("dn{i}"));
        }
        format!(
            "module chk(input cp, input cpn);\n  reg ntf;\n  specify\n    {check}\n  endspecify\n  \
             always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\nmodule top;\n  \
             reg cp0, dn0;\n{wires}  chk u(.cp({cp}), .cpn({dn}));\n  initial begin\n    cp0 = 0; \
             dn0 = 1;\n    #100;\n    {stim}\n    #200 $finish;\n  end\nendmodule\n"
        )
    }

    /// The expiry is decided only after the instant's other events: a data event
    /// at exactly the expiry that reaches the check `depth` deltas after the
    /// timer's own wake-up is still "within the limit" -- a timer that decided
    /// in its own dispatch would report a violation the data event had already
    /// answered.
    #[test]
    fn run_design_timeskew_a_data_event_a_delta_late_at_the_expiry_still_cancels() {
        for depth in 1..=3 {
            let stdout = run_src(
                &format!("ts-late-data-{depth}"),
                &timeskew_late_design(
                    "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                    depth,
                    "cp0 = 1;\n    #5 dn0 = 0;",
                ),
            );
            assert_eq!(stdout, "", "data {depth} delta(s) late: {stdout}");
            // One tick later it is a violation, reported at the expiry.
            let stdout = run_src(
                &format!("ts-late-data-after-{depth}"),
                &timeskew_late_design(
                    "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                    depth,
                    "cp0 = 1;\n    #6 dn0 = 0;",
                ),
            );
            assert_eq!(timeskew_hits(&stdout), [(105, 5)], "{stdout}");
        }
    }

    /// The same for a REFERENCE event at the expiry that is `depth` deltas
    /// late: it replaces the old one, so the violation is the new one's.
    #[test]
    fn run_design_timeskew_a_reference_a_delta_late_at_the_expiry_still_cancels() {
        for depth in 1..=3 {
            let stdout = run_src(
                &format!("ts-late-ref-{depth}"),
                &timeskew_late_design(
                    "$timeskew(posedge cp, negedge cpn, 5, ntf);",
                    depth,
                    "cp0 = 1;\n    #2 cp0 = 0;\n    #3 cp0 = 1;",
                ),
            );
            assert_eq!(timeskew_hits(&stdout), [(110, 5)], "{stdout}");
        }
    }

    /// A conditioned reference event whose condition is false arms nothing, with
    /// either setting of the remain_active flag (it is not a timestamp event).
    #[test]
    fn run_design_timeskew_a_false_conditioned_reference_never_arms_the_check() {
        for ra in [0, 1] {
            let stdout = run_src(
                &format!("ts-false-ref-{ra}"),
                &timeskew_design(
                    &format!("$timeskew(posedge cp &&& mode, negedge cpn, 5, ntf, 0, {ra});"),
                    &[(100, "mode = 0;"), (101, "cp = 1;")],
                ),
            );
            assert_eq!(stdout, "", "remain_active {ra}: {stdout}");
        }
    }

    /// The simulation ends before the limit expires: the check is still waiting,
    /// so nothing is reported.
    #[test]
    fn run_design_timeskew_a_simulation_that_ends_inside_the_limit_reports_nothing() {
        let src = "module chk(input cp, input cpn);\n  reg ntf;\n  specify\n    \
                   $timeskew(posedge cp, negedge cpn, 5, ntf);\n  endspecify\nendmodule\nmodule \
                   top;\n  reg cp, cpn;\n  chk u(.cp(cp), .cpn(cpn));\n  initial begin\n    cp = 0; \
                   cpn = 1;\n    #100 cp = 1;\n    #3 $finish;\n  end\nendmodule\n";
        assert_eq!(run_src("ts-early-finish", src), "");
    }

    /// A negative limit is a named error: `$timeskew`'s limit is a "non-negative
    /// constant expression" (Table 31-8).
    #[test]
    fn run_design_timeskew_rejects_a_negative_limit_by_name() {
        let e = run_src_err(
            "ts-neg",
            &timeskew_design("$timeskew(posedge cp, negedge cpn, -1, ntf);", &[]),
        );
        assert!(
            e.contains("$timeskew") && e.contains("non-negative") && e.contains("31.4.2"),
            "unexpected error: {e}"
        );
    }

    // -----------------------------------------------------------------------
    // T21b, LRM 31.4.3: `$fullskew`, the state machine.

    /// [`skew_replay`] of a `$fullskew` with the two limits (reference event
    /// first, data event first): `(time reported, actual, limit)`.
    fn fullskew_replay(
        l1: i64,
        l2: i64,
        f: SkewFlags,
        events: &[(i64, Ev)],
    ) -> Vec<(i64, i64, i64)> {
        skew_replay(TimeSkewState::fullskew(l1, l2, f), events)
    }

    /// The `(time, actual, limit)` triple of a violation, for brevity.
    fn v(time: i64, actual: i64, limit: i64) -> (i64, i64, i64) {
        (time, actual, limit)
    }

    /// LRM Figure 31-3 as events (limits 50 and 70), at the times
    /// `figure_31_3` of the end-to-end tests uses. The figure is a drawing, so
    /// this is one concrete realisation of it: A is the CP rise (MODE true) and
    /// B its limit; C, E, F, G, H, I are the CPN falls, D the expiry of C's 70;
    /// MODE falls and CP rises (a false-condition reference edge) between E's
    /// window and F, and J is the CP rise with MODE true that answers I.
    fn figure_31_3_events() -> Vec<(i64, Ev)> {
        let mut e = vec![(100, Ev::Ref)];
        e.extend([170, 260].map(|t| (t, Ev::Data)));
        e.push((340, Ev::RefFalse));
        e.extend([350, 430, 510, 590].map(|t| (t, Ev::Data)));
        e.push((620, Ev::Ref));
        e
    }

    /// Figure 31-3, Case 1 (timer-based): the timer reports at B (50 after A),
    /// at D (70 after C), and for each of E, F, G and H, "but not the
    /// transition at I because it is followed by a positive transition on CP
    /// while MODE is true". Either setting of remain_active_flag: the false CP
    /// edge comes after E's window has expired, so there is nothing to turn
    /// dormant.
    #[test]
    fn fullskew_state_replays_figure_31_3_case_1() {
        let want = [
            v(150, 50, 50),
            v(240, 70, 70),
            v(330, 70, 70),
            v(420, 70, 70),
            v(500, 70, 70),
            v(580, 70, 70),
        ];
        for ra in [false, true] {
            assert_eq!(
                fullskew_replay(50, 70, flags(false, ra), &figure_31_3_events()),
                want,
                "remain_active {ra}"
            );
        }
    }

    /// Figure 31-3, Case 2 (event-based): "a violation is reported at C ...
    /// because it occurs beyond the 50 time unit limit", and "for transitions on
    /// CPN at C through H, there is no positive transition on CP while MODE is
    /// true; therefore, no timing violations are reported". I is answered by J.
    #[test]
    fn fullskew_state_replays_figure_31_3_case_2() {
        for ra in [false, true] {
            assert_eq!(
                fullskew_replay(50, 70, flags(true, ra), &figure_31_3_events()),
                [v(170, 70, 50)],
                "remain_active {ra}"
            );
        }
    }

    /// The role of remain_active_flag the figure does not show: a false-condition
    /// reference edge INSIDE a data-first window turns it dormant (and so
    /// silences its violation) unless the flag is set.
    #[test]
    fn fullskew_state_a_false_reference_inside_a_data_window_needs_remain_active() {
        let events = [(260, Ev::Data), (300, Ev::RefFalse)];
        assert_eq!(fullskew_replay(50, 70, flags(false, false), &events), []);
        assert_eq!(
            fullskew_replay(50, 70, flags(false, true), &events),
            [v(330, 70, 70)]
        );
    }

    /// The plan's cross-check against `$timeskew` (T21a), on its Figure 31-1 and
    /// 31-2 waveforms. A `$fullskew` whose second limit can never be reached sees
    /// the same reference-first windows as a `$timeskew`, so what it reports with
    /// the first limit is what the `$timeskew` of the same flags reports; the
    /// data-first windows it also opens only add reports against the second
    /// limit, which are filtered out. The exception is Case 3
    /// (event_based + remain_active), which is `$skew` for a `$timeskew` (every
    /// late data event violates against the reference) but for a `$fullskew` the
    /// first late data event is itself a timestamp event: only the FIRST of the
    /// `$timeskew`'s violations is common.
    #[test]
    fn fullskew_state_with_an_unreachable_second_limit_agrees_with_timeskew() {
        const FAR: i64 = 1_000_000;
        let waveforms = [figure_31_1_events(), figure_31_2_events()];
        let mut compared = 0;
        for events in &waveforms {
            for (case, f) in timeskew_cases().into_iter().enumerate() {
                let skew = timeskew_replay(50, f, events);
                let full: Vec<(i64, i64)> = fullskew_replay(50, FAR, f, events)
                    .into_iter()
                    .filter(|&(_, _, limit)| limit == 50)
                    .map(|(t, actual, _)| (t, actual))
                    .collect();
                let want: Vec<(i64, i64)> = if case == 2 {
                    skew.into_iter().take(1).collect()
                } else {
                    skew
                };
                assert_eq!(full, want, "case {} {f:?}", case + 1);
                compared += want.len();
            }
        }
        assert!(
            compared >= 6,
            "a cross-check that compares nothing proves nothing"
        );
    }

    /// The two limits are told apart by which event came first, at every skew,
    /// in both modes. Timer-based, a late timecheck event is a violation of the
    /// timer (`actual` = the limit) and then itself a timestamp event of the
    /// OTHER limit, whose expiry is reported too ("a reference event or data
    /// event is a timestamp event and starts a new timing window, unless it is a
    /// timecheck event occurring within the time limit"); event-based it is
    /// reported at once with the skew, and ends the window as the timestamp
    /// event of the next.
    #[test]
    fn fullskew_state_sweep_uses_the_limit_of_the_first_event() {
        let (l1, l2) = (3, 7);
        let mut violations = 0;
        for skew in 0..=10 {
            for (first, second, limit, other) in
                [(Ev::Ref, Ev::Data, l1, l2), (Ev::Data, Ev::Ref, l2, l1)]
            {
                let events = [(100, first), (100 + skew, second)];
                let timer = fullskew_replay(l1, l2, flags(false, false), &events);
                let event = fullskew_replay(l1, l2, flags(true, false), &events);
                if skew > limit {
                    assert_eq!(
                        timer,
                        [
                            v(100 + limit, limit, limit),
                            v(100 + skew + other, other, other)
                        ],
                        "timer: {first:?} first, skew {skew}"
                    );
                    assert_eq!(
                        event,
                        [v(100 + skew, skew, limit)],
                        "event: {first:?} first, skew {skew}"
                    );
                    violations += 2;
                } else {
                    assert_eq!(timer, [], "timer: {first:?} first, skew {skew}");
                    assert_eq!(event, [], "event: {first:?} first, skew {skew}");
                }
            }
        }
        assert!(violations > 0, "a sweep with no violation proves nothing");
    }

    /// "Simultaneous transitions on the reference and data signals shall not
    /// cause $fullskew to report a timing violation, even when the skew limit
    /// value is zero", in both modes, and the check is dormant afterwards.
    #[test]
    fn fullskew_state_simultaneous_events_never_violate_and_leave_the_check_dormant() {
        for eb in [false, true] {
            let mut s = TimeSkewState::fullskew(0, 0, flags(eb, false));
            s.reference_event(100);
            s.data_event(100);
            let n = s.pending();
            assert_eq!(s.settle_limited(n), [], "event_based {eb}");
            assert_eq!(s.deadline(), None, "event_based {eb}: dormant");
            assert_eq!(s.expire_limited(100), None);
        }
    }

    /// Timer-based, limit 0, a lone event of either kind: the limit elapses at
    /// the event's own instant.
    #[test]
    fn fullskew_state_a_lone_event_with_limit_zero_violates_at_its_instant() {
        assert_eq!(
            fullskew_replay(0, 9, flags(false, false), &[(100, Ev::Ref)]),
            [v(100, 0, 0)]
        );
        assert_eq!(
            fullskew_replay(9, 0, flags(false, false), &[(100, Ev::Data)]),
            [v(100, 0, 0)]
        );
    }

    /// "$fullskew shall also not report a violation if a new timestamp event
    /// occurs exactly at the expiration of the time limit": a SAME-kind event
    /// replaces the window, whichever kind it is.
    #[test]
    fn fullskew_state_a_new_timestamp_at_the_expiry_cancels_the_violation() {
        let t = flags(false, false);
        assert_eq!(
            fullskew_replay(5, 9, t, &[(100, Ev::Ref), (105, Ev::Ref)]),
            [v(110, 5, 5)]
        );
        assert_eq!(
            fullskew_replay(5, 7, t, &[(100, Ev::Data), (107, Ev::Data)]),
            [v(114, 7, 7)]
        );
        // One tick later the first window had expired and was reported.
        assert_eq!(
            fullskew_replay(5, 9, t, &[(100, Ev::Ref), (106, Ev::Ref)]),
            [v(105, 5, 5), v(111, 5, 5)]
        );
    }

    /// Event-based: a timecheck beyond the limit reports and begins a new window
    /// "where it acts as the timestamp event of the new window" (so the next
    /// event of the other kind is measured against the other limit); a
    /// timecheck within the limit turns the check dormant, and a timestamp event
    /// activates it again.
    #[test]
    fn fullskew_state_event_based_chains_windows_through_late_timechecks() {
        let events = [
            (100, Ev::Ref),
            (110, Ev::Data), // 10 > 5: violation, opens a data-first window
            (125, Ev::Ref),  // 15 > 7: violation, opens a reference-first window
            (128, Ev::Data), // 3 <= 5: dormant
            (140, Ev::Data), // dormant: a timestamp event, activates
            (160, Ev::Ref),  // 20 > 7: violation
        ];
        assert_eq!(
            fullskew_replay(5, 7, flags(true, false), &events),
            [v(110, 10, 5), v(125, 15, 7), v(160, 20, 7)]
        );
    }

    /// A false-condition edge of EITHER event is "a second timestamp event ...
    /// [with] a condition whose value is false": ignored with remain_active_flag,
    /// otherwise it turns an ACTIVE check dormant, and it never arms an idle one.
    #[test]
    fn fullskew_state_a_false_edge_of_either_event_follows_remain_active() {
        for (open, edge, l1, l2) in [
            (Ev::Ref, Ev::DataFalse, 5, 9),
            (Ev::Ref, Ev::RefFalse, 5, 9),
            (Ev::Data, Ev::RefFalse, 9, 5),
            (Ev::Data, Ev::DataFalse, 9, 5),
        ] {
            let events = [(100, open), (102, edge)];
            assert_eq!(
                fullskew_replay(l1, l2, flags(false, false), &events),
                [],
                "{open:?} then {edge:?}: dormant"
            );
            assert_eq!(
                fullskew_replay(l1, l2, flags(false, true), &events),
                [v(105, 5, 5)],
                "{open:?} then {edge:?}: ignored"
            );
        }
        for ra in [false, true] {
            for edge in [Ev::RefFalse, Ev::DataFalse] {
                assert_eq!(
                    fullskew_replay(5, 5, flags(false, ra), &[(100, edge)]),
                    [],
                    "an idle check is not armed by {edge:?}"
                );
            }
        }
    }

    /// A false-condition edge in the instant of a true event is not a timestamp
    /// event: it is applied after it, so it can silence it (no
    /// remain_active_flag), whichever the order of arrival.
    #[test]
    fn fullskew_state_a_false_edge_is_applied_after_the_events_of_its_instant() {
        let a = [(100, Ev::Ref), (100, Ev::DataFalse)];
        assert_eq!(fullskew_replay(5, 5, flags(false, false), &a), []);
        assert_eq!(
            fullskew_replay(5, 5, flags(false, true), &a),
            [v(105, 5, 5)]
        );
    }

    /// The deadline is the active window's own limit after its timestamp event:
    /// the first limit for a reference event, the second for a data event;
    /// none while dormant or event-based.
    #[test]
    fn fullskew_state_deadline_follows_the_active_windows_limit() {
        let mut s = TimeSkewState::fullskew(5, 9, flags(false, false));
        assert_eq!(s.deadline(), None);
        s.reference_event(100);
        let n = s.pending();
        s.settle_limited(n);
        assert_eq!(s.deadline(), Some(105));
        s.data_event(103); // within the limit: dormant
        let n = s.pending();
        s.settle_limited(n);
        assert_eq!(s.deadline(), None);
        s.data_event(200);
        let n = s.pending();
        s.settle_limited(n);
        assert_eq!(s.deadline(), Some(209));
        // An event pending means the expiry waits for it.
        s.reference_event(209);
        assert_eq!(s.expire_limited(209), None);
        let n = s.pending();
        assert_eq!(s.settle_limited(n), [], "209 is within the 9 of 200");
        let mut e = TimeSkewState::fullskew(5, 9, flags(true, true));
        e.reference_event(100);
        let n = e.pending();
        e.settle_limited(n);
        assert_eq!(e.deadline(), None, "event-based has no timer");
    }

    /// Both kinds at one instant while a window is open: the event of the
    /// opposite kind is measured against that window first (a violation if it
    /// is late and the check is event-based), then the two are simultaneous and
    /// the check is dormant.
    #[test]
    fn fullskew_state_both_kinds_in_an_instant_check_the_open_window_then_go_dormant() {
        let events = [
            (100, Ev::Ref),
            (120, Ev::Ref),
            (120, Ev::Data),
            (130, Ev::Data),
        ];
        // Event-based, limit 5: the data event at 120 is 20 after the reference
        // event at 100 (late); the reference at 120 is simultaneous with it;
        // the later data event at 130 finds the check dormant and opens a window.
        assert_eq!(
            fullskew_replay(5, 5, flags(true, false), &events),
            [v(120, 20, 5)]
        );
        // Within the limit: nothing, dormant.
        assert_eq!(fullskew_replay(50, 50, flags(true, false), &events), []);
    }

    /// The answer must not depend on the order in which the events of one
    /// instant reach the machine (a delta-cycle artefact): every order of every
    /// non-empty set of the instant's events, after a window is open.
    #[test]
    fn fullskew_state_does_not_depend_on_the_arrival_order_within_an_instant() {
        let kinds = [Ev::Ref, Ev::Data, Ev::RefFalse, Ev::DataFalse];
        let mut checked = 0;
        for eb in [false, true] {
            for ra in [false, true] {
                for open in [Ev::Ref, Ev::Data] {
                    for mask in 1u32..16 {
                        let set: Vec<Ev> = (0..4)
                            .filter(|i| mask & (1 << i) != 0)
                            .map(|i| kinds[i])
                            .collect();
                        let mut first: Option<Vec<(i64, i64)>> = None;
                        for perm in permutations(set.len()) {
                            let mut s = TimeSkewState::fullskew(4, 6, flags(eb, ra));
                            match open {
                                Ev::Ref => s.reference_event(100),
                                _ => s.data_event(100),
                            }
                            let n = s.pending();
                            s.settle_limited(n);
                            for &i in &perm {
                                match set[i] {
                                    Ev::Ref => s.reference_event(110),
                                    Ev::Data => s.data_event(110),
                                    Ev::RefFalse => s.reference_suppressed(110),
                                    Ev::DataFalse => s.data_suppressed(110),
                                }
                            }
                            let n = s.pending();
                            let mut got = s.settle_limited(n);
                            got.extend(s.expire_limited(150));
                            match &first {
                                None => first = Some(got),
                                Some(f) => assert_eq!(
                                    &got, f,
                                    "eb {eb} ra {ra} open {open:?} set {set:?} perm {perm:?}"
                                ),
                            }
                            checked += 1;
                        }
                    }
                }
            }
        }
        assert_eq!(checked, 512);
    }

    /// Every order of `0..n` (n <= 4).
    fn permutations(n: usize) -> Vec<Vec<usize>> {
        fn go(rest: &mut Vec<usize>, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
            if rest.is_empty() {
                out.push(cur.clone());
                return;
            }
            for i in 0..rest.len() {
                let x = rest.remove(i);
                cur.push(x);
                go(rest, cur, out);
                cur.pop();
                rest.insert(i, x);
            }
        }
        let mut out = Vec::new();
        go(&mut (0..n).collect(), &mut Vec::new(), &mut out);
        out
    }

    /// The two events are symmetric but for the limit that goes with each: a
    /// `$fullskew(l1, l2)` on a waveform and a `$fullskew(l2, l1)` on the same
    /// waveform with the roles of the two events swapped report the same
    /// violations. Swept over pseudo-random waveforms of both modes and both
    /// flags.
    #[test]
    fn fullskew_state_is_symmetric_under_swapping_the_two_events_and_limits() {
        fn mirror(e: Ev) -> Ev {
            match e {
                Ev::Ref => Ev::Data,
                Ev::Data => Ev::Ref,
                Ev::RefFalse => Ev::DataFalse,
                Ev::DataFalse => Ev::RefFalse,
            }
        }
        let mut seed = 0x2545_f491_u64;
        let mut next = move |bound: u64| {
            seed = seed
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (seed >> 33) % bound
        };
        let (mut runs, mut hits) = (0, 0);
        for _ in 0..400 {
            let mut t = 100;
            let mut events = Vec::new();
            for _ in 0..(3 + next(10)) {
                t += next(6) as i64;
                events.push((
                    t,
                    [
                        Ev::Ref,
                        Ev::Data,
                        Ev::Ref,
                        Ev::Data,
                        Ev::RefFalse,
                        Ev::DataFalse,
                    ][next(6) as usize],
                ));
            }
            let mirrored: Vec<(i64, Ev)> = events.iter().map(|&(t, e)| (t, mirror(e))).collect();
            let (l1, l2) = (next(5) as i64, next(5) as i64);
            for f in timeskew_cases() {
                let a = fullskew_replay(l1, l2, f, &events);
                let b = fullskew_replay(l2, l1, f, &mirrored);
                assert_eq!(a, b, "limits ({l1}, {l2}) {f:?} events {events:?}");
                runs += 1;
                hits += a.len();
            }
        }
        assert!(runs == 1600 && hits > 200, "{runs} runs, {hits} violations");
    }

    /// Both limits are validated, naming the clause, and the flags decode like
    /// `$timeskew`'s.
    #[test]
    fn fullskew_spec_rejects_a_negative_limit_and_decodes_both_limits_and_the_flags() {
        let src = "`timescale 1ns/1ps\nmodule m(input d, input clk);\n  reg n;\n  specify\n    \
                   $fullskew(posedge clk, d, 5, 6, n);\n    $fullskew(posedge clk, d, 7, 8, n, 1);\n    \
                   $fullskew(posedge clk, d, 9, 10, n, 0, 1);\n    $fullskew(posedge clk, d, 11, \
                   12);\n  endspecify\nendmodule\n";
        let model = discovered(src).unwrap_or_else(|e| panic!("discover failed: {e}"));
        let specs: Vec<CheckSpec> = model
            .timing_checks
            .iter()
            .map(|c| {
                let CheckArgs::FullSkew(a) = &c.args else {
                    panic!("not $fullskew: {:?}", c.args)
                };
                fullskew_spec(a, &c.check_uid).expect("valid")
            })
            .collect();
        let want = [
            (5, 6, false, false),
            (7, 8, true, false),
            (9, 10, false, true),
            (11, 12, false, false),
        ]
        .map(|(l1, l2, event_based, remain_active)| CheckSpec::FullSkew {
            limit: l1 * 1000,
            data_first_limit: l2 * 1000,
            flags: flags(event_based, remain_active),
        });
        assert_eq!(
            specs, want,
            "limit 1 = reference first, limit 2 = data first"
        );
    }

    // -----------------------------------------------------------------------
    // T21b, LRM 31.4.3: `$fullskew`, end to end.

    /// Every `$fullskew` violation line of `stdout` as `(time reported, actual,
    /// limit)`.
    fn fullskew_hits(stdout: &str) -> Vec<(i64, i64, i64)> {
        violations(stdout)
            .into_iter()
            .map(|l| {
                assert!(l.contains("$fullskew violation"), "unexpected line: {l}");
                let time = l.split(':').next().unwrap().parse().expect("time");
                let actual = l.rsplit("actual=").next().unwrap().parse().expect("actual");
                let limit = l
                    .split("limit=")
                    .nth(1)
                    .and_then(|r| r.split(',').next())
                    .unwrap()
                    .parse()
                    .expect("limit");
                (time, actual, limit)
            })
            .collect()
    }

    /// The violations (and the notifier toggles, one each) one `check` makes on
    /// `events`, the design finishing at `finish`.
    fn fullskew_run(
        tag: &str,
        check: &str,
        events: &[(i64, &str)],
        finish: i64,
    ) -> Vec<(i64, i64, i64)> {
        let stdout = run_src(tag, &skew_design(check, events, finish));
        let hits = fullskew_hits(&stdout);
        assert_eq!(
            stdout.matches("ntf=").count(),
            hits.len(),
            "one notifier toggle per violation: {stdout}"
        );
        hits
    }

    /// LRM Figure 31-3's waveform (limits 50 and 70), the lettered points at
    /// these times:
    ///
    /// ```text
    ///   A=100  CP rises, MODE true        B=150  A + 50
    ///   C=170  CPN falls                  D=240  C + 70
    ///   E=260  CPN falls                  (E + 70 = 330)
    ///   CP rises at 340, MODE false (MODE falls at 335)
    ///   F=350  G=430  H=510  I=590        CPN falls
    ///   J=620  CP rises, MODE true again (MODE rises at 595)
    /// ```
    fn figure_31_3() -> Vec<(i64, &'static str)> {
        let mut e = vec![(100, "cp = 1;"), (110, "cp = 0;")];
        for t in [170, 260] {
            cpn_fall(&mut e, t);
        }
        e.extend([(335, "mode = 0;"), (340, "cp = 1;"), (345, "cp = 0;")]);
        for t in [350, 430, 510, 590] {
            cpn_fall(&mut e, t);
        }
        e.extend([(595, "mode = 1;"), (620, "cp = 1;")]);
        e.sort_by_key(|&(t, _)| t);
        e
    }

    fn figure_31_3_hits(tag: &str, event_based: u8, remain_active: u8) -> Vec<(i64, i64, i64)> {
        let check = format!(
            "$fullskew(posedge cp &&& mode, negedge cpn, 50, 70, ntf, {event_based}, \
             {remain_active});"
        );
        fullskew_run(tag, &check, &figure_31_3(), 700)
    }

    /// LRM 31.4.3, Figure 31-3, Case 1 (timer-based), run through the simulator.
    #[test]
    fn run_design_fullskew_figure_31_3_case_1() {
        for ra in [0, 1] {
            assert_eq!(
                figure_31_3_hits(&format!("fs-f3-c1-{ra}"), 0, ra),
                [
                    v(150, 50, 50),
                    v(240, 70, 70),
                    v(330, 70, 70),
                    v(420, 70, 70),
                    v(500, 70, 70),
                    v(580, 70, 70),
                ],
                "remain_active {ra}"
            );
        }
    }

    /// Figure 31-3, Case 2 (event-based): one violation, at C.
    #[test]
    fn run_design_fullskew_figure_31_3_case_2() {
        for ra in [0, 1] {
            assert_eq!(
                figure_31_3_hits(&format!("fs-f3-c2-{ra}"), 1, ra),
                [v(170, 70, 50)],
                "remain_active {ra}"
            );
        }
    }

    /// The cross-check against `$timeskew` of the state-level test, through the
    /// simulator, on Figures 31-1 and 31-2 (the limit of the other order is
    /// 100000, never reached).
    #[test]
    fn run_design_fullskew_with_an_unreachable_second_limit_agrees_with_timeskew() {
        let mut compared = 0;
        for (fig, events) in [("1", figure_31_1()), ("2", figure_31_2())] {
            for (i, (eb, ra)) in TIMESKEW_CASES.into_iter().enumerate() {
                let skew = figure_hits(&format!("fs-x-ts-{fig}-{i}"), &events, eb, ra);
                let check = format!(
                    "$fullskew(posedge cp &&& mode, negedge cpn, 50, 100000, ntf, {eb}, {ra});"
                );
                let full: Vec<(i64, i64)> =
                    fullskew_run(&format!("fs-x-fs-{fig}-{i}"), &check, &events, 300)
                        .into_iter()
                        .filter(|&(_, _, limit)| limit == 50)
                        .map(|(t, a, _)| (t, a))
                        .collect();
                let want: Vec<(i64, i64)> = if i == 2 {
                    skew.into_iter().take(1).collect()
                } else {
                    skew
                };
                assert_eq!(full, want, "figure 31-{fig} case {}", i + 1);
                compared += want.len();
            }
        }
        assert!(compared >= 6, "{compared}");
    }

    /// The exact output of a timer-based violation of EITHER order: the notifier
    /// toggles x -> 0, and the line carries the limit of the window that
    /// expired.
    #[test]
    fn run_design_fullskew_timer_reports_each_order_with_its_own_limit_exactly() {
        let reference_first = run_src(
            "fs-exact-ref",
            &skew_design(
                "$fullskew(posedge cp, negedge cpn, 5, 9, ntf);",
                &[(100, "cp = 1;")],
                300,
            ),
        );
        assert_eq!(
            reference_first,
            "ntf=0 at 105\n105: $fullskew violation: data top.u.cpn vs reference top.u.cp, \
             limit=5, actual=5\n"
        );
        let data_first = run_src(
            "fs-exact-data",
            &skew_design(
                "$fullskew(posedge cp, negedge cpn, 5, 9, ntf);",
                &[(100, "cpn = 0;")],
                300,
            ),
        );
        assert_eq!(
            data_first,
            "ntf=0 at 109\n109: $fullskew violation: data top.u.cpn vs reference top.u.cp, \
             limit=9, actual=9\n"
        );
    }

    /// Event-based, both orders, at and beyond the limit (a skew equal to the
    /// limit is within it; the violation reports the skew and the limit of the
    /// order).
    #[test]
    fn run_design_fullskew_event_based_boundaries_in_both_orders() {
        let check = "$fullskew(posedge cp, negedge cpn, 5, 9, ntf, 1);";
        for (tag, first, second, at, want) in [
            ("a", "cp = 1;", "cpn = 0;", 105, vec![]),
            ("b", "cp = 1;", "cpn = 0;", 106, vec![v(106, 6, 5)]),
            ("c", "cpn = 0;", "cp = 1;", 109, vec![]),
            ("d", "cpn = 0;", "cp = 1;", 110, vec![v(110, 10, 9)]),
        ] {
            let got = fullskew_run(
                &format!("fs-eb-{tag}"),
                check,
                &[(100, first), (at, second)],
                300,
            );
            assert_eq!(got, want, "{tag}");
        }
    }

    /// Simultaneous transitions, limit 0, in either order of the two writes and
    /// in either mode: nothing; a lone event of either kind: the limit elapses
    /// at once.
    #[test]
    fn run_design_fullskew_simultaneous_transitions_do_not_violate_with_limit_zero() {
        for eb in [0, 1] {
            for (tag, stmt) in [
                ("rd", "begin cp = 1; cpn = 0; end"),
                ("dr", "begin cpn = 0; cp = 1; end"),
            ] {
                let got = fullskew_run(
                    &format!("fs-simul-{tag}-{eb}"),
                    &format!("$fullskew(posedge cp, negedge cpn, 0, 0, ntf, {eb});"),
                    &[(100, stmt)],
                    300,
                );
                assert_eq!(got, [], "{tag} event_based {eb}");
            }
        }
        for (tag, stmt) in [("ref", "cp = 1;"), ("data", "cpn = 0;")] {
            let got = fullskew_run(
                &format!("fs-lone0-{tag}"),
                "$fullskew(posedge cp, negedge cpn, 0, 0, ntf);",
                &[(100, stmt)],
                300,
            );
            assert_eq!(got, [v(100, 0, 0)], "{tag}");
        }
    }

    /// A false `&&&` condition on the DATA event: it is a timestamp event with a
    /// false condition, so it turns the active check dormant unless
    /// remain_active_flag is set (the reference event's `&&&` is Figure 31-3's).
    #[test]
    fn run_design_fullskew_a_false_data_condition_follows_remain_active() {
        for (ra, want) in [(0, vec![]), (1, vec![v(105, 5, 5)])] {
            let got = fullskew_run(
                &format!("fs-false-data-{ra}"),
                &format!("$fullskew(posedge cp, negedge cpn &&& mode, 5, 5, ntf, 0, {ra});"),
                &[(100, "cp = 1;"), (101, "mode = 0;"), (102, "cpn = 0;")],
                300,
            );
            assert_eq!(got, want, "remain_active {ra}");
        }
    }

    /// An empty notifier slot and elided flags (the figure's own spelling).
    #[test]
    fn run_design_fullskew_accepts_an_empty_notifier_slot_and_elided_flags() {
        let stdout = run_src(
            "fs-nontf",
            &skew_design(
                "$fullskew(posedge cp &&& mode, negedge cpn, 50, 70, , 1, 1);",
                &figure_31_3(),
                700,
            ),
        );
        assert_eq!(fullskew_hits(&stdout), [v(170, 70, 50)], "{stdout}");
        assert!(!stdout.contains("ntf="), "{stdout}");
        let stdout = run_src(
            "fs-elided",
            &skew_design(
                "$fullskew(posedge cp &&& mode, negedge cpn, 50, 70);",
                &figure_31_3(),
                700,
            ),
        );
        assert_eq!(fullskew_hits(&stdout).len(), 6, "{stdout}");
    }

    /// The expiry is decided only after the instant's other events, in both
    /// orders: the opposite event arriving `depth` deltas after the timer's own
    /// wake-up, at exactly the limit, is still within it; one tick later the
    /// timer had reported, and the late event is a timestamp event of the other
    /// window.
    #[test]
    fn run_design_fullskew_a_timecheck_a_delta_late_at_the_expiry_still_cancels() {
        let check = "$fullskew(posedge cp, negedge cpn, 5, 5, ntf);";
        for depth in 1..=3 {
            for (tag, first, second) in [
                ("ref", "cp0 = 1;", "dn0 = 0;"),
                ("data", "dn0 = 0;", "cp0 = 1;"),
            ] {
                let on_time = fullskew_run_late(
                    &format!("fs-late-{tag}-{depth}"),
                    check,
                    depth,
                    &format!("{first}\n    #5 {second}"),
                );
                assert_eq!(on_time, [], "{tag}, {depth} delta(s) late");
                let late = fullskew_run_late(
                    &format!("fs-late-after-{tag}-{depth}"),
                    check,
                    depth,
                    &format!("{first}\n    #6 {second}"),
                );
                assert_eq!(
                    late,
                    [v(105, 5, 5), v(111, 5, 5)],
                    "{tag}, {depth} delta(s)"
                );
            }
        }
    }

    /// A same-kind timestamp event a delta late at the expiry replaces the
    /// window (the violation is the new window's), in both orders.
    #[test]
    fn run_design_fullskew_a_timestamp_a_delta_late_at_the_expiry_still_replaces() {
        let check = "$fullskew(posedge cp, negedge cpn, 5, 7, ntf);";
        for depth in 1..=3 {
            let got = fullskew_run_late(
                &format!("fs-late-ts-ref-{depth}"),
                check,
                depth,
                "cp0 = 1;\n    #2 cp0 = 0;\n    #3 cp0 = 1;",
            );
            assert_eq!(got, [v(110, 5, 5)], "reference, {depth} delta(s)");
            let got = fullskew_run_late(
                &format!("fs-late-ts-data-{depth}"),
                check,
                depth,
                "dn0 = 0;\n    #2 dn0 = 1;\n    #5 dn0 = 0;",
            );
            assert_eq!(got, [v(114, 7, 7)], "data, {depth} delta(s)");
        }
    }

    fn fullskew_run_late(tag: &str, check: &str, depth: usize, stim: &str) -> Vec<(i64, i64, i64)> {
        fullskew_hits(&run_src(tag, &timeskew_late_design(check, depth, stim)))
    }

    /// Either limit that is negative is a named error.
    #[test]
    fn run_design_fullskew_rejects_a_negative_limit_by_name() {
        for check in [
            "$fullskew(posedge cp, negedge cpn, -1, 5, ntf);",
            "$fullskew(posedge cp, negedge cpn, 5, -1, ntf);",
        ] {
            let e = run_src_err("fs-neg", &skew_design(check, &[], 300));
            assert!(
                e.contains("$fullskew") && e.contains("non-negative") && e.contains("31.4.3"),
                "unexpected error for {check}: {e}"
            );
        }
    }

    // -----------------------------------------------------------------------
    // T22, LRM 31.8: vector signals in timing checks.

    fn per_bit() -> TimingOptions {
        TimingOptions {
            per_bit_vectors: true,
            ..TimingOptions::default()
        }
    }

    /// [`run_src`] under `options`.
    fn run_src_with(tag: &str, src: &str, options: TimingOptions) -> String {
        let file = std::env::temp_dir().join(format!("vj-sdf-t22-{tag}-{}.sv", std::process::id()));
        std::fs::write(&file, src).expect("write temp fixture");
        let mut out = Vec::new();
        let code = crate::run::run_design_with_options(&file, &[], options, &mut out)
            .unwrap_or_else(|e| panic!("run_design_with_options failed: {e}"));
        let _ = std::fs::remove_file(&file);
        assert_eq!(code, 0);
        String::from_utf8(out).expect("stdout is valid UTF-8")
    }

    /// LRM 31.8's own example: `DAT` goes 'b00101110 -> 'b01010011 at 100 and `CLK`
    /// rises at 105, against `$setup (DAT, posedge CLK, 10)`.
    fn dff_design(check: &str) -> String {
        format!(
            "module DFF(input CLK, input [7:0] DAT);\n  reg ntf;\n  specify\n    {check}\n  \
             endspecify\n  always @(ntf) $display(\"ntf=%b at %0t\", ntf, $time);\nendmodule\n\
             module top;\n  reg CLK;\n  reg [7:0] DAT;\n  DFF u(.CLK(CLK), .DAT(DAT));\n  \
             initial begin\n    CLK = 0; DAT = 8'b00101110;\n    #100 DAT = 8'b01010011;\n    \
             #5 CLK = 1;\n    #100 $finish;\n  end\nendmodule\n"
        )
    }

    /// The violation lines' data labels, sorted.
    fn data_labels(stdout: &str) -> Vec<String> {
        let mut labels: Vec<String> = violations(stdout)
            .into_iter()
            .map(|l| {
                l.split("data ")
                    .nth(1)
                    .and_then(|r| r.split(' ').next())
                    .expect("a data label")
                    .to_string()
            })
            .collect();
        labels.sort();
        labels
    }

    /// 31.8: "the $setup timing check shall still only report a single timing violation".
    #[test]
    fn vector_data_is_one_check_by_default() {
        let out = run_src(
            "vec-default",
            &dff_design("$setup(DAT, posedge CLK, 10, ntf);"),
        );
        assert_eq!(violations(&out).len(), 1, "{out}");
        assert!(
            out.contains("data top.u.DAT vs reference top.u.CLK"),
            "{out}"
        );
        assert!(
            out.contains("limit=10, actual=5"),
            "the vector's one event: {out}"
        );
        assert_eq!(out.matches("ntf=").count(), 1, "{out}");
    }

    /// 31.8: with the option, "6 timing violation because 6 bits of DAT transitioned"
    /// ('b00101110 ^ 'b01010011 = 'b01111101), each its own single-bit check, all
    /// triggering the one notifier.
    #[test]
    fn per_bit_option_reports_one_violation_per_changed_bit() {
        let out = run_src_with(
            "vec-per-bit",
            &dff_design("$setup(DAT, posedge CLK, 10, ntf);"),
            per_bit(),
        );
        assert_eq!(
            data_labels(&out),
            [
                "top.u.DAT[0]",
                "top.u.DAT[2]",
                "top.u.DAT[3]",
                "top.u.DAT[4]",
                "top.u.DAT[5]",
                "top.u.DAT[6]"
            ],
            "{out}"
        );
        assert!(
            violations(&out)
                .iter()
                .all(|l| l.starts_with("105: $setup violation") && l.contains("limit=10, actual=5")),
            "{out}"
        );
        // Every one of the six checks drives the same notifier (31.8): six toggles from
        // x (x -> 0 -> 1 -> 0 -> 1 -> 0 -> 1), where the one-check default makes one (x -> 0).
        assert!(
            out.contains("ntf=1 at 105"),
            "six toggles of one notifier: {out}"
        );
    }

    /// The option leaves a scalar-only check alone, and the default stays the default
    /// when the option is explicitly off.
    #[test]
    fn per_bit_option_changes_nothing_for_scalar_terminals() {
        let src = check_design(
            "$setup(d, posedge clk, 5, ntf);",
            "#2 d = 1;\n    #2 clk = 1;",
        );
        let on = run_src_with("vec-scalar-on", &src, per_bit());
        let off = run_src("vec-scalar-off", &src);
        assert_eq!(on, off);
        assert_eq!(violations(&on).len(), 1, "{on}");
        assert_eq!(run_src_with("vec-off", &src, TimingOptions::default()), off);
    }

    /// A bit-select terminal is already a single bit; a part-select expands to its own
    /// bits only.
    #[test]
    fn per_bit_option_expands_a_part_select_to_its_own_bits() {
        let out = run_src_with(
            "vec-part",
            &dff_design("$setup(DAT[3:1], posedge CLK, 10, ntf);"),
            per_bit(),
        );
        // Bits 1..=3 of the change mask 'b01111101 are bits 2 and 3.
        assert_eq!(data_labels(&out), ["top.u.DAT[2]", "top.u.DAT[3]"], "{out}");
        let out = run_src_with(
            "vec-select",
            &dff_design("$setup(DAT[4], posedge CLK, 10, ntf);"),
            per_bit(),
        );
        assert_eq!(data_labels(&out), ["top.u.DAT[4]"], "{out}");
        let out = run_src(
            "vec-part-default",
            &dff_design("$setup(DAT[3:1], posedge CLK, 10, ntf);"),
        );
        assert_eq!(data_labels(&out), ["top.u.DAT[3:1]"], "{out}");
    }

    /// A two-signal check with an edge control on a vector reference: each reference
    /// bit is its own edge (LSB of a one-bit terminal), so M x N checks each see only
    /// their own bits.
    #[test]
    fn per_bit_option_pairs_every_reference_bit_with_every_data_bit() {
        // $hold(posedge R, D, 10): D must stay stable for 10 after each R bit rise.
        let src = "module chk(input [1:0] r, input [2:0] d);\n  specify\n    $hold(posedge r, d, \
                   10);\n  endspecify\nendmodule\nmodule top;\n  reg [1:0] r;\n  reg [2:0] d;\n  \
                   chk u(.r(r), .d(d));\n  initial begin\n    r = 2'b00; d = 3'b000;\n    #100 \
                   r = 2'b10;\n    #1 d = 3'b101;\n    #100 $finish;\n  end\nendmodule\n";
        let out = run_src_with("vec-mn", src, per_bit());
        // r[1] rose (r[0] did not): 3 checks of the 6; d[0] and d[2] changed: 2 violate.
        let lines = violations(&out);
        assert_eq!(lines.len(), 2, "{out}");
        assert!(
            lines.iter().all(|l| l.contains("reference top.u.r[1]")),
            "only the bit that rose: {out}"
        );
        assert_eq!(data_labels(&out), ["top.u.d[0]", "top.u.d[2]"], "{out}");
        // By default the whole of r is one reference (any bit with an edge on its LSB:
        // posedge looks at bit 0 for a vector, 31.7), so r[1] alone is no event.
        let out = run_src("vec-mn-default", src);
        assert_eq!(violations(&out).len(), 0, "{out}");
    }

    fn vec_watch(width: u32) -> WatchPlan {
        WatchPlan {
            loc: loc_of(InstanceId(0), crate::primitives::bank_slot(0, width)),
            lo: 0,
            width,
            control: EdgeControl::AnyChange,
            conditions: Vec::new(),
        }
    }

    fn vec_plan(spec: CheckSpec, m: u32, n: u32, trailing: bool) -> CheckPlan {
        CheckPlan {
            entry: 0,
            spec,
            reference: vec_watch(m),
            data: vec_watch(n),
            trailing: trailing.then(|| vec_watch(m)),
            notifier: Some((loc_of(InstanceId(0), crate::primitives::bank_slot(1, 1)), 0)),
            reference_label: format!("r[{}:0]", m - 1),
            data_label: format!("d[{}:0]", n - 1),
            instance: InstanceId(0),
            reference_signal: SymbolId::synthetic("r"),
            data_signal: SymbolId::synthetic("d"),
            timestamp: None,
            timecheck: None,
        }
    }

    /// 31.8: two-signal kinds make M*N unique checks, one-signal kinds N, and every one
    /// triggers the one notifier. All the kinds, by name.
    #[test]
    fn per_bit_expansion_counts_follow_the_lrm() {
        let window = |kind| CheckSpec::Window { kind, limit: 1 };
        let two = [
            window(StabilityKind::Setup),
            window(StabilityKind::Hold),
            window(StabilityKind::Recovery),
            window(StabilityKind::Removal),
            CheckSpec::SetupHold { setup: 1, hold: 1 },
            CheckSpec::RecRem {
                recovery: 1,
                removal: 1,
            },
            CheckSpec::Skew { limit: 1 },
            CheckSpec::TimeSkew {
                limit: 1,
                flags: SkewFlags {
                    event_based: false,
                    remain_active: false,
                },
            },
            CheckSpec::FullSkew {
                limit: 1,
                data_first_limit: 1,
                flags: SkewFlags {
                    event_based: false,
                    remain_active: false,
                },
            },
        ];
        for spec in two {
            let expanded = expand_per_bit(vec_plan(spec, 3, 4, false), "r", "d");
            assert_eq!(expanded.len(), 12, "{}: M*N", spec.name());
            let pairs: HashSet<(u32, u32)> = expanded
                .iter()
                .map(|c| (c.reference.lo, c.data.lo))
                .collect();
            assert_eq!(pairs.len(), 12, "{}: every pair once", spec.name());
            assert!(
                expanded.iter().all(|c| {
                    c.reference.width == 1 && c.data.width == 1 && c.notifier.is_some()
                })
            );
        }
        // `$nochange` has two signals too; its trailing edge follows the reference bit.
        let nc = vec_plan(CheckSpec::NoChange { start: 0, end: 0 }, 3, 4, true);
        let expanded = expand_per_bit(nc, "r", "d");
        assert_eq!(expanded.len(), 12);
        assert!(
            expanded
                .iter()
                .all(|c| c.trailing.as_ref().map(|t| t.lo) == Some(c.reference.lo))
        );
        // One-signal kinds: N, the data bit the reference's own.
        for spec in [
            CheckSpec::Width {
                limit: 1,
                threshold: 0,
            },
            CheckSpec::Period { limit: 1 },
        ] {
            let expanded = expand_per_bit(vec_plan(spec, 5, 5, false), "r", "r");
            assert_eq!(expanded.len(), 5, "{}: N", spec.name());
            assert!(
                expanded.iter().all(|c| c.reference.lo == c.data.lo),
                "{}",
                spec.name()
            );
        }
    }

    /// Labels name the absolute bit; a terminal that is already one bit keeps its label,
    /// and a scalar check is passed through unchanged.
    #[test]
    fn per_bit_expansion_labels_and_scalars() {
        let one = expand_per_bit(
            vec_plan(CheckSpec::Skew { limit: 1 }, 1, 1, false),
            "r",
            "d",
        );
        assert_eq!(one.len(), 1);
        assert_eq!(
            (one[0].reference_label.as_str(), one[0].data_label.as_str()),
            ("r[0:0]", "d[0:0]"),
            "a width-1 terminal keeps the label it was planned with"
        );
        let mut p = vec_plan(CheckSpec::Skew { limit: 1 }, 1, 3, false);
        p.data.lo = 4; // d[6:4]
        p.data_label = "d[6:4]".into();
        let labels: Vec<_> = expand_per_bit(p, "r", "d")
            .into_iter()
            .map(|c| c.data_label)
            .collect();
        assert_eq!(labels, ["d[4]", "d[5]", "d[6]"]);
    }

    // -----------------------------------------------------------------------
    // T23a, LRM 31.9.1: delayed-signal creation, planned (no simulation).

    /// The bank pseudo-instance the implicit copies live in.
    const BANK: InstanceId = InstanceId(u32::MAX - 7);

    /// Everything [`negative_timing`] and [`plan`] produce for `src` (one top module holding
    /// the checks), with every signal a check names given a one-bit slot of its own.
    struct NegPlan {
        model: TimingModel,
        table: DelayTable,
        res: Resolution,
        plans: Plans,
    }

    /// [`neg_plan_with`] under the option that enables negative timing checks (31.9.4).
    fn neg_plan(src: &str) -> NegPlan {
        neg_plan_with(src, &negative_on())
    }

    fn negative_on() -> TimingOptions {
        TimingOptions {
            negative_timing_checks: true,
            ..TimingOptions::default()
        }
    }

    fn neg_plan_with(src: &str, options: &TimingOptions) -> NegPlan {
        let mut model = discovered(src).unwrap_or_else(|e| panic!("discover failed: {e}"));
        let mut own: HashMap<SymbolId, SignalSlot> = HashMap::new();
        let mut name = |t: &TerminalRef| {
            let next = own.len() as u32;
            own.entry(t.0.clone()).or_insert(SignalSlot {
                slot: next,
                width: 1,
                signed: false,
                class: vj_codegen::process_lower::SignalSlotClass::Inline,
            });
        };
        for entry in &model.timing_checks {
            let (reference, data, notifier, delayed) = match &entry.args {
                CheckArgs::SetupHold(a) => (
                    &a.reference,
                    &a.data,
                    &a.notifier,
                    [&a.delayed_reference, &a.delayed_data],
                ),
                CheckArgs::RecRem(a) => (
                    &a.reference,
                    &a.data,
                    &a.notifier,
                    [&a.delayed_reference, &a.delayed_data],
                ),
                CheckArgs::Setup(a) | CheckArgs::Hold(a) => {
                    (&a.reference, &a.data, &a.notifier, [&None, &None])
                }
                other => panic!("neg_plan does not name the terminals of {other:?}"),
            };
            name(&reference.terminal);
            name(&data.terminal);
            for t in [notifier, delayed[0], delayed[1]].into_iter().flatten() {
                name(t);
            }
        }
        let signals = HashMap::from([(InstanceId(0), own)]);
        let no_iface = HashMap::new();
        let scope = Scope {
            own: &signals,
            iface: &no_iface,
        };
        let mut table = negative_timing(&mut model, &scope, options).expect("solve");
        let mut res = Resolution::default();
        let plans = plan(&model, &scope, options, &mut table, &mut res, BANK).expect("plan");
        NegPlan {
            model,
            table,
            res,
            plans,
        }
    }

    fn neg_src(checks: &str) -> String {
        format!(
            "module m(input clk, input d1, input d2, input d3);\n  reg ntf;\n  wire dclk, dd1, \
             dd2;\n  specify\n    {checks}\n  endspecify\nendmodule\n"
        )
    }

    /// 31.9.1 Example 1: `$setuphold(posedge CLK, DATA, -10, 20)` creates an implicit delayed
    /// CLK (10 + the 1-tick margin) that the check reads; DATA keeps no delay, so the check
    /// reads it as it is. One copy in the bank, one line that drives it.
    #[test]
    fn example_1_creates_one_implicit_delayed_clock() {
        let p = neg_plan(&neg_src("$setuphold(posedge clk, d1, -10, 20, ntf);"));
        assert_eq!(p.res.bank_widths, [1], "one implicit copy (CLK)");
        assert_eq!(p.plans.lines.len(), 1);
        assert_eq!(p.plans.lines[0].delay, 11);
        assert_eq!(p.plans.lines[0].outputs.len(), 1);
        let c = &p.plans.checks[0];
        assert_eq!(
            c.reference.loc.instance(),
            BANK,
            "the check reads the delayed clock"
        );
        assert_eq!(
            c.data.loc.instance(),
            InstanceId(0),
            "the undelayed data is read as is"
        );
        // Adjusted into the delayed time: setup -10 + 11, hold 20 - 11.
        assert_eq!(c.spec, CheckSpec::SetupHold { setup: 1, hold: 9 });
    }

    /// Example 2: CLK is named by two checks and gets ONE delayed copy, sized by the larger
    /// negative limit (15 + 1), which both checks read.
    #[test]
    fn example_2_shares_one_implicit_copy_of_the_common_clock() {
        let p = neg_plan(&neg_src(
            "$setuphold(posedge clk, d1, -10, 20, ntf);\n    $setuphold(posedge clk, d2, -15, \
             18, ntf);",
        ));
        assert_eq!(
            p.res.bank_widths,
            [1],
            "one copy for CLK, not one per check"
        );
        assert_eq!(p.plans.lines.len(), 1);
        assert_eq!(p.plans.lines[0].delay, 16);
        let [a, b] = &p.plans.checks[..] else {
            panic!("two checks")
        };
        assert_eq!(a.reference.loc.slot.slot, b.reference.loc.slot.slot);
        assert_eq!(a.reference.loc.instance(), BANK);
        assert_eq!(a.spec, CheckSpec::SetupHold { setup: 6, hold: 4 });
        assert_eq!(b.spec, CheckSpec::SetupHold { setup: 1, hold: 2 });
    }

    /// Example 3: a signal that has an explicit delayed net in one check uses it in every
    /// check, rather than getting a second, implicit one for the other.
    #[test]
    fn example_3_uses_the_explicit_net_in_both_checks() {
        let p = neg_plan(&neg_src(
            "$setuphold(posedge clk, d1, -10, 20, ntf, , , dclk, dd1);\n    \
             $setuphold(posedge clk, d2, -15, 18, ntf);",
        ));
        assert!(
            p.res.bank_widths.is_empty(),
            "no implicit copy: dclk covers CLK"
        );
        let [a, b] = &p.plans.checks[..] else {
            panic!("two checks")
        };
        assert_eq!(a.reference.loc.instance(), InstanceId(0));
        assert_eq!(
            a.reference.loc.slot.slot, b.reference.loc.slot.slot,
            "both read dclk"
        );
        // dclk is the net, not CLK itself.
        assert_ne!(
            a.reference.loc.slot.slot, a.data.loc.slot.slot,
            "the check reads a net of its own"
        );
        let lines: Vec<(u64, usize)> = p
            .plans
            .lines
            .iter()
            .map(|l| (l.delay, l.outputs.len()))
            .collect();
        // CLK -> dclk (16 ticks), DATA1 -> dd1 (a declared net copies even at delay 0).
        assert_eq!(lines, [(16, 1), (0, 1)]);
    }

    /// A signal with no negative limit anywhere has no delayed copy, and its checks are as
    /// written.
    #[test]
    fn positive_checks_create_nothing() {
        let p = neg_plan(&neg_src("$setuphold(posedge clk, d1, 5, 7, ntf);"));
        assert!(p.res.bank_widths.is_empty());
        assert!(p.plans.lines.is_empty());
        assert_eq!(
            p.plans.checks[0].spec,
            CheckSpec::SetupHold { setup: 5, hold: 7 }
        );
    }

    /// A `$hold` on the delayed clock has its limit adjusted to the delayed time; when that
    /// makes it <= 0 it becomes 0 and a warning is issued (31.9.1). `$setup` grows instead.
    #[test]
    fn a_hold_on_a_delayed_clock_is_clamped_to_zero_with_a_warning() {
        let p = neg_plan(&neg_src(
            "$setuphold(posedge clk, d1, -10, 20, ntf);\n    $hold(posedge clk, d2, 5, ntf);\n    \
             $setup(d3, posedge clk, 5, ntf);",
        ));
        let specs: Vec<CheckSpec> = p.plans.checks.iter().map(|c| c.spec).collect();
        assert_eq!(
            specs,
            [
                CheckSpec::SetupHold { setup: 1, hold: 9 },
                // 5 + (0 - 11) < 0
                CheckSpec::Window {
                    kind: StabilityKind::Hold,
                    limit: 0
                },
                // 5 - (0 - 11)
                CheckSpec::Window {
                    kind: StabilityKind::Setup,
                    limit: 16
                },
            ]
        );
        assert_eq!(p.table.warnings.len(), 1, "{:?}", p.table.warnings);
        assert!(
            p.table.warnings[0].contains("$hold"),
            "{:?}",
            p.table.warnings
        );
    }

    /// Mutually inconsistent negative limits: the warning names the zeroed limit and the
    /// check runs on the limits that were left.
    #[test]
    fn inconsistent_negative_limits_warn_and_run_with_the_smallest_zeroed() {
        let p = neg_plan(&neg_src(
            "$setuphold(posedge clk, d1, -9, 12, ntf);\n    $setuphold(posedge d1, clk, -1, 0, \
             ntf);",
        ));
        // The zeroing warning, then the clamp warning of the zeroed check, whose adjusted
        // limit lands at or below 0 against the 9-tick delay the other check gave CLK.
        assert_eq!(p.table.warnings.len(), 2, "{:?}", p.table.warnings);
        assert!(
            p.table.warnings[0].contains("setup limit -1"),
            "{:?}",
            p.table.warnings
        );
        assert!(
            p.table.warnings[1].contains("set to 0"),
            "{:?}",
            p.table.warnings
        );
        assert_eq!(
            p.table
                .checks
                .iter()
                .map(|c| c.effective)
                .collect::<Vec<_>>(),
            [(-9, 12), (0, 0)]
        );
    }

    /// A module path from a delayed signal is raised to at least the delay (31.9.1's
    /// `(CLK => Q) = 6` with a -7 setup).
    #[test]
    fn paths_from_a_delayed_signal_are_raised_to_its_delay() {
        let p = neg_plan(
            "module m(input clk, input d, output q);\n  reg ntf;\n  assign q = clk & d;\n  \
             specify\n    (clk => q) = 6;\n    (d => q) = 3;\n    $setuphold(posedge clk, d, -7, \
             13, ntf);\n  endspecify\nendmodule\n",
        );
        let ticks: Vec<u64> = p
            .model
            .paths
            .iter()
            .map(|path| path.delays.min_all())
            .collect();
        // CLK is delayed by 7 + 1, so its path is 8 ticks; D is not delayed.
        assert_eq!(ticks, [8, 3]);
    }

    /// A check on a signal named by a skew check family never reads the delayed copy.
    #[test]
    fn the_skew_checks_never_read_delayed_signals() {
        assert!(!uses_delayed_signals(CheckSpec::Skew { limit: 1 }));
        assert!(!uses_delayed_signals(CheckSpec::TimeSkew {
            limit: 1,
            flags: SkewFlags {
                event_based: false,
                remain_active: false
            }
        }));
        assert!(!uses_delayed_signals(CheckSpec::FullSkew {
            limit: 1,
            data_first_limit: 1,
            flags: SkewFlags {
                event_based: false,
                remain_active: false
            }
        }));
        assert!(uses_delayed_signals(CheckSpec::Width {
            limit: 1,
            threshold: 0
        }));
        assert!(uses_delayed_signals(CheckSpec::NoChange {
            start: 0,
            end: 0
        }));
    }

    /// `adjust_spec` for every kind that has limits to move: data-first limits shrink by the
    /// data signal's extra delay, data-second limits grow, `$nochange`'s window moves whole,
    /// and a signal delayed against itself (`$width`, `$period`) is as written.
    #[test]
    fn adjust_spec_moves_each_kind_by_its_own_sign() {
        let w = |kind, limit| CheckSpec::Window { kind, limit };
        assert_eq!(
            adjust_spec(w(StabilityKind::Setup, 10), 4),
            (w(StabilityKind::Setup, 6), false)
        );
        assert_eq!(
            adjust_spec(w(StabilityKind::Removal, 10), 4),
            (w(StabilityKind::Removal, 6), false)
        );
        assert_eq!(
            adjust_spec(w(StabilityKind::Hold, 10), 4),
            (w(StabilityKind::Hold, 14), false)
        );
        assert_eq!(
            adjust_spec(w(StabilityKind::Recovery, 10), 4),
            (w(StabilityKind::Recovery, 14), false)
        );
        // At or below 0: set to 0, and say so.
        assert_eq!(
            adjust_spec(w(StabilityKind::Setup, 4), 4),
            (w(StabilityKind::Setup, 0), true)
        );
        assert_eq!(
            adjust_spec(
                CheckSpec::RecRem {
                    recovery: 3,
                    removal: 8
                },
                5
            ),
            (
                CheckSpec::RecRem {
                    recovery: 8,
                    removal: 3
                },
                false
            )
        );
        assert_eq!(
            adjust_spec(CheckSpec::NoChange { start: 2, end: -1 }, 3),
            (CheckSpec::NoChange { start: -1, end: 2 }, false)
        );
        let width = CheckSpec::Width {
            limit: 5,
            threshold: 1,
        };
        assert_eq!(adjust_spec(width, 4), (width, false));
        // Nothing to move: unchanged and silent, even at a limit of 0.
        assert_eq!(
            adjust_spec(w(StabilityKind::Hold, 0), 0),
            (w(StabilityKind::Hold, 0), false)
        );
    }

    /// A negative-limit `$setuphold(posedge clk, d, <limits>, ntf, <ts>, <tc>)` where `c`
    /// holds `x` from time 100 until the second event's lead-up (113) and `y` after it:
    /// `first` is the real-time first event (at 100), `second` the later one (at 115).
    /// Returns the number of violations.
    fn neg_cond_gate(args: &str, first: &str, second: &str, x: u8, y: u8, tag: &str) -> usize {
        let src = format!(
            "module chk(input clk, input d, input c);\n  reg ntf;\n  wire dclk, dd;\n  specify\n    \
             $setuphold(posedge clk, d, {args}, dclk, dd);\n  endspecify\nendmodule\nmodule \
             top;\n  reg clk, d, c;\n  chk u(.clk(clk), .d(d), .c(c));\n  initial begin\n    clk \
             = 0; d = 0; c = 0;\n    #100 c = {x}; {first} = 1;\n    #13 c = {y};\n    #2 \
             {second} = 1;\n    #100 $finish;\n  end\nendmodule\n"
        );
        violations(&run_src(tag, &src)).len()
    }

    /// LRM 31.9.2 on a NEGATIVE SETUP, `$setuphold(posedge clk, d, -10, 20, ntf, ts, tc)`:
    /// the window is `d` 10..20 after `clk`, so `clk` carries `timestamp_condition` and `d`
    /// `timecheck_condition` (the clause's own example associates the timecheck condition
    /// with the data signal). `c` is read at each signal's delayed event.
    #[test]
    fn run_design_negative_setup_conditions_follow_the_delayed_signals() {
        for (what, args, wants) in [
            ("ts", "-10, 20, ntf, c, ", (true, false)),
            ("tc", "-10, 20, ntf, , c", (false, true)),
            ("both", "-10, 20, ntf, c, c", (true, true)),
        ] {
            for x in 0..2u8 {
                for y in 0..2u8 {
                    let want = (!wants.0 || x == 1) && (!wants.1 || y == 1);
                    let n = neg_cond_gate(args, "clk", "d", x, y, &format!("ncs-{what}-{x}{y}"));
                    assert_eq!(n, usize::from(want), "negative setup {what} c={x}->{y}");
                }
            }
        }
    }

    /// The mirror: a NEGATIVE HOLD, `$setuphold(posedge clk, d, 20, -10, ntf, ts, tc)`, is
    /// `d` 10..20 BEFORE `clk`; `d` (delayed) carries `timestamp_condition` and `clk`
    /// `timecheck_condition`.
    #[test]
    fn run_design_negative_hold_conditions_follow_the_delayed_signals() {
        for (what, args, wants) in [
            ("ts", "20, -10, ntf, c, ", (true, false)),
            ("tc", "20, -10, ntf, , c", (false, true)),
            ("both", "20, -10, ntf, c, c", (true, true)),
        ] {
            for x in 0..2u8 {
                for y in 0..2u8 {
                    let want = (!wants.0 || x == 1) && (!wants.1 || y == 1);
                    let n = neg_cond_gate(args, "d", "clk", x, y, &format!("nch-{what}-{x}{y}"));
                    assert_eq!(n, usize::from(want), "negative hold {what} c={x}->{y}");
                }
            }
        }
    }

    /// 31.9.3: the notifier toggles when the DELAYED signals violate the ADJUSTED limits,
    /// not when the model inputs violate the written ones. `$setuphold(posedge clk, d, -10,
    /// 20)` with `clk` at 100 and `d` at 115: the window is violated at the data change
    /// (115), and the notifier changes then -- not at 100 (when `clk` rose) and not at 111
    /// (when the delayed `clk` did).
    #[test]
    fn run_design_negative_check_notifier_toggles_at_the_delayed_violation() {
        let stdout = run_src(
            "neg-ntf",
            &check_design(
                "$setuphold(posedge clk, d, -10, 20, ntf);",
                "clk = 1;\n    #15 d = 1;",
            ),
        );
        let ntf: Vec<&str> = stdout.lines().filter(|l| l.starts_with("ntf=")).collect();
        assert_eq!(ntf, ["ntf=0 at 115"], "{stdout}");
        assert_eq!(violations(&stdout).len(), 1, "{stdout}");
    }

    // -- LRM 31.9.4: the option that enables negative timing checks ----------

    /// Without the option (the default) nothing is delayed: Example 1 makes no implicit copy
    /// and no line, the check reads the original signals, and its negative setup limit is the
    /// 0 a positive-limit check would have. The same planning with every delay at 0.
    #[test]
    fn option_off_plans_no_delay_and_clamps_the_negative_limit() {
        let off = TimingOptions::default();
        let p = neg_plan_with(&neg_src("$setuphold(posedge clk, d1, -10, 20, ntf);"), &off);
        assert!(p.res.bank_widths.is_empty());
        assert!(p.plans.lines.is_empty());
        let c = &p.plans.checks[0];
        assert_eq!(
            c.reference.loc.instance(),
            InstanceId(0),
            "the original clock"
        );
        assert_eq!(c.spec, CheckSpec::SetupHold { setup: 0, hold: 20 });
        assert!(p.table.warnings.is_empty());
        // The same source, with the option, is the delayed plan of Example 1.
        let on = neg_plan(&neg_src("$setuphold(posedge clk, d1, -10, 20, ntf);"));
        assert_eq!(on.plans.lines.len(), 1);
        assert_eq!(
            on.plans.checks[0].spec,
            CheckSpec::SetupHold { setup: 1, hold: 9 }
        );
    }

    /// Option off, the declared `delayed_reference` / `delayed_data` nets are plain copies:
    /// still driven, with no delay. Conditions stay with the per-window roles (no negative
    /// limit is left to order the two signals).
    #[test]
    fn option_off_drives_declared_nets_as_zero_delay_copies() {
        let off = TimingOptions::default();
        let p = neg_plan_with(
            &neg_src("$setuphold(posedge clk, d1, -10, 20, ntf, , , dclk, dd1);"),
            &off,
        );
        let lines: Vec<(u64, usize)> = p
            .plans
            .lines
            .iter()
            .map(|l| (l.delay, l.outputs.len()))
            .collect();
        assert_eq!(lines, [(0, 1), (0, 1)]);
        assert!(
            p.table
                .checks
                .iter()
                .all(|c| p.table.first_of(&c.check).is_none())
        );
    }

    /// End to end, Example 3's nets with the option off: `dclk` follows `clk` at once, where
    /// with it on it follows 11 ticks later.
    #[test]
    fn run_design_option_off_delayed_nets_are_copies() {
        let src = "module chk(input clk, input d);\n  reg ntf;\n  wire dclk, dd;\n  specify\n    \
                   $setuphold(posedge clk, d, -10, 20, ntf, , , dclk, dd);\n  endspecify\n  \
                   always @(dclk) if ($time >= 100) $display(\"dclk=%b at %0t\", dclk, $time);\n  \
                   always @(dd) if ($time >= 100) $display(\"dd=%b at %0t\", dd, $time);\n\
                   endmodule\nmodule top;\n  reg clk, d;\n  chk u(.clk(clk), .d(d));\n  initial \
                   begin\n    clk = 0; d = 0;\n    #100 clk = 1;\n    #3 d = 1;\n    #100 \
                   $finish;\n  end\nendmodule\n";
        let off = run_src_with("neg-off-nets", src, TimingOptions::default());
        let lines: Vec<&str> = off.lines().filter(|l| !l.contains("violation")).collect();
        assert_eq!(lines, ["dclk=1 at 100", "dd=1 at 103"], "{off}");
        // The negative setup is 0: the data change at +3 is inside the hold window (20).
        assert_eq!(violations(&off).len(), 1, "{off}");
    }

    /// Option off, the path floor of 31.9.1 is not applied: `Q` follows `CLK` after the path's
    /// own 6 -- what iverilog, which ignores negative limits, also does (the probe corpus).
    #[test]
    fn run_design_option_off_leaves_the_module_path_alone() {
        let src = "module dut(input clk, input d, output reg q);\n  reg ntf;\n  wire dclk, dd;\n  \
                   always @(posedge clk) q <= d;\n  specify\n    (clk => q) = 6;\n    \
                   $setuphold (posedge clk, posedge d, -3, 8, ntf, , , dclk, dd);\n    \
                   $setuphold (posedge clk, negedge d, -7, 13, ntf, , , dclk, dd);\n  \
                   endspecify\nendmodule\nmodule top;\n  reg clk, d;\n  wire q;\n  dut u(.clk(clk), \
                   .d(d), .q(q));\n  initial begin\n    clk = 0; d = 0;\n    #10 d = 1;\n    #10 \
                   clk = 1;\n    #6.5 $display(\"q=%b\", q);\n    $finish;\n  end\nendmodule\n";
        let off = run_src_with("neg-off-path", src, TimingOptions::default());
        assert_eq!(off, "q=1\n", "{off}");
        let on = run_src("neg-on-path", src);
        assert_eq!(on, "q=x\n", "{on}");
    }

    /// A positive-limit check is the same with the option on or off.
    #[test]
    fn option_does_not_change_a_positive_limit_check() {
        let src = check_design(
            "$setuphold(posedge clk, d, 5, 7, ntf);",
            "d = 1;\n    #3 clk = 1;\n    #4 d = 0;",
        );
        let off = run_src_with("neg-opt-pos-off", &src, TimingOptions::default());
        let on = run_src_with("neg-opt-pos-on", &src, negative_on());
        assert_eq!(off, on);
        assert_eq!(violations(&off).len(), 2, "{off}");
    }

    /// 31.9.1 Example 3's explicit nets, end to end: the delayed clock is the `dclk` the model
    /// names and changes 10 + 1 ticks after the clock; `dd`, given no delay, follows `d` at once.
    #[test]
    fn run_design_explicit_delayed_nets_follow_their_signals() {
        let src = "module chk(input clk, input d);\n  reg ntf;\n  wire dclk, dd;\n  specify\n    \
                   $setuphold(posedge clk, d, -10, 20, ntf, , , dclk, dd);\n  endspecify\n  \
                   always @(dclk) if ($time >= 100) $display(\"dclk=%b at %0t\", dclk, $time);\n  \
                   always @(dd) if ($time >= 100) $display(\"dd=%b at %0t\", dd, $time);\n\
                   endmodule\nmodule top;\n  reg clk, d;\n  chk u(.clk(clk), .d(d));\n  initial \
                   begin\n    clk = 0; d = 0;\n    #100 clk = 1;\n    #3 d = 1;\n    #100 $finish;\n  \
                   end\nendmodule\n";
        let stdout = run_src("neg-explicit", src);
        let lines: Vec<&str> = stdout
            .lines()
            .filter(|l| !l.contains("violation"))
            .collect();
        assert_eq!(lines, ["dd=1 at 103", "dclk=1 at 111"], "{stdout}");
    }
}