vj-codegen 0.1.0

LLVM code generator of the vj SystemVerilog simulator.
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
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
//! T9/T10 (`docs/superpowers/plans/2026-10-03-sva.md`): the automaton builder
//! -- `fn build_automaton`, consuming T3's [`super::ranges`], T4's
//! [`sv_sim_sim::sva::ir`], and T5's leaf shape (a Boolean leaf is identified
//! here and compiled later, by [`super::leaf::compile_leaf`], never
//! re-implemented). LRM 16.7 (Simple sequences, `##` concatenation), 16.9.1
//! (operator precedence/evaluation), 16.9.2 (`boolean_abbrev` repetition) and,
//! from T10, 16.9.2.1 (repetition, concatenation and EMPTY matches).
//!
//! ## Empty matches (T10, LRM 16.9.2.1)
//!
//! A sequence can match over an interval of length 0 (`a[*0]`, the zero
//! branch of `a[*0:2]`). Such an empty match is not a path through the
//! automaton -- every path spends at least the tick it starts on -- so a
//! [`Fragment`] carries it separately: `exits` are the ends of its NONEMPTY
//! matches, `empty` says whether it ALSO admits the empty match, and
//! [`build_automaton`] copies the top-level flag onto
//! [`ir::Automaton::admits_empty`]. [`concat`] is the one place the
//! 16.9.2.1 rules live, implemented over that representation:
//!
//! 1. `empty ##0 seq` and
//! 2. `seq ##0 empty` do not match (a `##0` fusion needs a tick on both
//!    sides, and an empty match has none);
//! 3. `empty ##n seq` (n > 0) is `##(n-1) seq`;
//! 4. `seq ##n empty` (n > 0) is `seq ##(n-1) 1` (`1` is the LRM's
//!    `` `true ``);
//!
//! and, because a delay RANGE or a sequence admitting both kinds of match is
//! the union of its members, each rule applies per member: the LRM's own
//! recipe ("rewrite the sequence as the union of an empty sequence and a
//! nonempty sequence") is what `concat` does -- `(ne ∪ ε) ##d (ne' ∪ ε)` is
//! the union of the four pairings, each wired by its own rule. When BOTH
//! operands are empty the 16.9.2.1 prose does not spell out the result;
//! the rules above, applied repeatedly, give Annex F.5.2's plain word
//! concatenation: `##0` no match, `##1` the empty match, `##n` (n >= 2)
//! `1[*n-1]`. A repetition whose unit itself admits the empty match,
//! `(u)[*m:n]`, is `ne(u)[*0:n]` by the same algebra (each repeat may
//! vanish).
//!
//! A leading delay (`##2 b`, `##[1:3] a ##1 b`) is `1[*m:n] ##1 seq`, i.e.
//! `empty ##[m+1:n+1] seq` (16.9.2.1 rule 3 read right to left; F.3.4.2.2).
//! A plain `( ... )` around a sequence is transparent (see
//! [`ranges::peel_sequence_parens`]).
//!
//! ## Sequence operators (T11, LRM 16.9.5-16.9.10)
//!
//! `and` / `intersect` ([`build_product`]) are a LOCKSTEP PRODUCT of the two
//! operand NFAs, both started on the same tick. A component is a real state,
//! a `Wait` (a `Delay{min,max}` edge it has taken but whose delay has not
//! elapsed) or `Done` (an `and` operand that already matched and now waits
//! for the other). One tick passes only when no side still has a same-tick
//! move and at least one side is a `Wait`. `intersect` ends when both sides
//! end on the same tick; `and` when both have ended (the later end is the
//! match end, 16.9.5). The empty match is a flag on the product: it is
//! admitted when both operands admit it; an `and` whose one operand is empty
//! starts that side already `Done`. `or` ([`build_or`]) is a fresh entry with
//! an epsilon to each operand; `throughout` is `(cond)[*0:$] intersect seq`
//! and `within` is `(1[*0:$] ##1 seq1 ##1 1[*0:$]) intersect seq2`, exactly
//! the LRM's stated rewrites (16.9.9, 16.9.10).
//!
//! The product is built by BFS from the start, so state numbering is
//! deterministic (the `HashMap` is a lookup table only, never iterated), and
//! is capped at [`MAX_PRODUCT_STATES`] with a loud error that names the
//! operator, because the construction is the cross product of its operands.
//! [`trim_dead_product_states`] then cuts edges into states that reach
//! neither an exit nor a `FirstMatchEnd` edge, which keeps nested products
//! (the within-in-within shape) tractable; it KEEPS `FirstMatchEnd` edges
//! even into a dead state, because the earliest end tick of a `first_match`
//! region is recorded whether or not the other operand agrees with it.
//!
//! `first_match(R)` ([`build_first_match`]) wraps R in a
//! `FirstMatchBegin`/`FirstMatchEnd` pair on a fresh group
//! ([`ir::Automaton::first_match_groups`]). The engine contract is a
//! per-attempt table keyed (group, begin tick) holding the earliest end
//! tick: `Begin` stamps the thread, `End` records the tick when absent,
//! takes the edge when equal, and kills the thread when an earlier tick is
//! already recorded. The contract is documented on the IR variants and
//! implemented, for tests, by `sv_sim_sim::sva::trace`. An empty R makes
//! `first_match(R)` the empty match (F.5.2: the earliest match is the empty
//! one). A match-item list on `first_match` (T14) is attached to R INSIDE the
//! `FirstMatchBegin`/`FirstMatchEnd` bracket (`first_match(R, items)` is
//! `first_match((R, items))`, 16.9.8), so a subroutine call fires at every end
//! point of R (16.11) even when `first_match` then discards that match.
//!
//! `prune_unreachable` now runs at the end of every build (BFS renumbering
//! from the start state), so T9/T10 state numbers differ from before; the
//! recognised language does not.
//!
//! ## Named sequence instances (T12, LRM 16.8/16.8.1)
//!
//! A use of a named sequence is an `AssertionInstance` expression operand
//! ([`build_instance`]): its body is expanded in place, once per use (a
//! repeated instance is a fresh copy per repeat, so the automaton is exactly
//! the one the sequence's body written inline would give). slang substitutes a
//! formal that stands for a Boolean or a sequence by the ACTUAL's own
//! expression, so leaves and nested instances need no rewriting here. What it
//! cannot hand over is a formal used as a `##`/`[...]` bound: that is folded
//! by [`ranges`] from syntax, so each instance pushes a
//! [`ranges::FormalFrame`] binding its formals to their actuals (folded in the
//! CALLER's frame first; a typed integral formal casts the value to its type,
//! 16.8.1; `$` is legal only for an untyped formal used as an upper bound).
//!
//! A clocking event inside an instance (`sequence rule; @(posedge c) ...`) is
//! one clock of the assertion ([`LeafTable::intern_clock`]); the root clock the
//! caller stripped is passed to [`build_automaton`] as `root_clock` and is
//! [`ClockId`] 0. Property instances are `build_property`'s (a loud error
//! here) and cyclic instantiation (16.8, by name) is a loud error; the cycle check is the one
//! `named::check_named_sequence_cycles` delegates to slang for, plus the
//! builder's own check on LRM 16.8's declaration graph (below).
//!
//! ## Multiclocked sequences (T28, LRM 16.13.1)
//!
//! Every clocking event the builder meets is interned by structural equality
//! ([`events_equivalent`]), so `@(posedge clk)` written twice is ONE clock and
//! `@(posedge clk1)` / `@(posedge clk2)` are two even if the signals happen to
//! carry equal values (16.16.1: "identical", not "equal"). [`LeafTable::cur`] is
//! the clock a node is built on (the context clock, which a `Clocking` node sets
//! for its body), and each [`Fragment`] carries the [`Span`] of clocks it covers
//! when it contains a clocking event of its own (`None`: it takes the context's,
//! like a Boolean). [`concat_clocked`] joins two fragments: the same clock is the
//! ordinary single-clock concatenation, and a different one is a
//! [`Transition::ClockSync`] edge from every end point of the left operand to the
//! entry of the right (`##1`: first tick of the right clock strictly after, `##0`:
//! at or after). 16.13.1 allows nothing else between differently clocked
//! operands: only `##1`/`##0`, and both maximal singly clocked subsequences must
//! be nonempty. The sequence operators ([`join_clocks`]) and repetition need a
//! singly clocked operand and a clock they all share.
//!
//! ## Local variables (T13, LRM 16.8.2, 16.10, Annex F.5.4)
//!
//! Every local variable (a sequence's declared local, a `local` formal) gets a
//! CANONICAL slot ([`ir::LocalVarId`]) minted when its named sequence instance
//! is expanded, so a repeated instance never shares variables with another
//! copy. A thread's frame is indexed by slot. An instance's initialisation
//! assignments are ONE build-time-ordered action list prefixed to the body's
//! entry: the `input`/`inout` formals first (the actual cast to the formal's
//! type), then the declared initialisers in declaration order, so an
//! initialiser may read a formal (16.8.2). An `output`/`inout` formal is
//! written back to the caller's variable by a [`Transition::LocalVarCopy`]
//! after the body's exits.
//!
//! Legality is the F.5.4 flow algebra ([`flow`]): every fragment carries a
//! `Flow` triple, [`LeafTable::flow_in`] is the set of variables definitely
//! assigned where the node being built starts, and [`LeafTable::push_leaf`]
//! rejects a read of a variable outside it with a "does not flow out" error.
//! `and`/`intersect`/`throughout`/`within` run their operands as parallel
//! threads that each own a copy of the variables (rule (d)): the second operand
//! reads and writes lazily-created shadow slots ([`ShadowCtx`]), initialised by
//! a prefix `LocalVarCopy` and copied back, after the product, for the
//! variables only that operand assigns. Sequence match items (T14, 16.11) are
//! all lowered here: `v = e`, `v op= e`, `v++`/`--v` (a [`ir::Transition::LocalVarStep`]
//! edge) and subroutine calls ([`super::actions`], a [`ir::Transition::SubroutineCall`]
//! edge), in list order, with the nondegeneracy check in `attach_match_items`.
//!
//! Slots hold two-state `i64` values cast through the variable's declared
//! width and signedness ([`ir::LocalVarDecl`]); a leaf that reads a variable
//! records it in [`LeafTable::locals_of`] for the runtime engine (T29), which
//! also has to apply that cast. [`sv_sim_sim::sva::trace::attempt_with_locals`]
//! is the executable specification of the frame semantics.
//!
//! The builder's check walks a dependency chain ([`LeafTable::chain`]), not
//! the expansion stack: an edge X -> Y is "X's declaration instantiates Y" or
//! "an instance of X instantiates Y within an actual argument". slang
//! substitutes the actual for a formal reference, so the actual's instance is
//! met while the callee's body is being expanded; it is expanded under the
//! chain of its CALL SITE plus the instantiated declaration
//! ([`ranges::FormalFrame::origins`]; a forwarded formal keeps the chain of the
//! actual it forwards). `outer(inner(a))` with `outer(w): inner(w) ##1 c` is
//! legal (`outer -> inner`); `s(s(a))` and `s(wrap(a))` with `wrap(w): s(w)`
//! are cycles.
//!
//! ## Deviation from the plan's literal file location
//!
//! Plan §3's T9 text puts this builder at `crates/sv-sim-sim/src/sva/
//! build.rs`. That is not buildable as written: `sv-sim-sim` cannot depend
//! on `sv-sim-codegen` (`sv-sim-codegen`'s own `Cargo.toml` already depends
//! on `sv-sim-sim`, and `sv-sim-sim`'s `Cargo.toml` depends on neither
//! `sv-sim-codegen` nor `inkwell` -- a reverse dependency would be a cycle),
//! yet T9's own "Files" line also says this builder "consum[es] T3's
//! ranges... T5's leaves", both of which live in `sv-sim-codegen` (T3/T5's
//! own, already-committed module-doc text explains why *they* live there:
//! `ranges` casts to `sv-lang` *syntax* node types no `AnalyzedAssertion`
//! accessor exposes, and `leaf::compile_leaf` calls `process_lower::
//! compile_iff_guard`, an `inkwell`-dependent LLVM emitter `sv-sim-sim` has
//! no access to at all). The only way to satisfy "lives in `sv-sim-sim`" AND
//! "consumes `ranges`/`leaf`" simultaneously would be duplicating T3's
//! syntax-casting folder a second time in `sv-sim-sim` -- a real, divergent
//! second implementation of the exact thing this project's own
//! "duplicate pure-function eval diverges" lesson warns against, for no
//! benefit. This module instead lives beside `ranges`/`op`/`leaf` in
//! `sv-sim-codegen::sva` (which already legitimately depends on both
//! `sv-lang` and `sv-sim-sim`), and produces a [`sv_sim_sim::sva::ir::
//! Automaton`] -- the pure, elaboration-independent IR type `ir.rs` itself
//! says must stay `sv-lang`-free -- as its one piece of state that crosses
//! back into `sv-sim-sim`'s own ownership. The companion [`LeafTable`]
//! (mapping each [`LeafId`] back to the `Expression` a later wiring task
//! compiles via [`super::leaf::compile_leaf`]) is this module's own sibling
//! output, deliberately kept OUT of `ir::Automaton` for the same reason.
#![allow(dead_code)]

use std::collections::{BTreeSet, HashMap, HashSet};

use sv_lang::kinds::{AssertionExprKind, ExpressionKind, SymbolKind};
use sv_lang::nodes::{
    IdentifierNameSyntax, ParenthesizedSequenceExprSyntax, SequenceRepetitionSyntax,
    SimpleSequenceExprSyntax,
};
use sv_lang::{
    ArgumentDirection, AssertionExpr, AstNode, Expression, KnownSystemName, Node, SemNode, Symbol,
    UnaryOp,
};

use sv_sim_sim::sva::ir::{self, ClockId, LeafId, LocalVarId, ThreadStateId, Transition};

use super::actions::{self, CallSite};
use super::flow::{Flow, VarSet};
use super::op::{AssertionBinaryOp, Op};
use super::ranges::{self, SequenceRangeValue};
use super::trees::{Trees, key};
use crate::error::LoweringError;

pub mod property;

/// What a Boolean leaf (or a match item's / initializer's value expression)
/// needs from the local-variable frame (T13): which local variables its
/// expression reads and, for a match item's value, which slot an
/// `LValueReference` (the target of a compound assignment, `v += e`) stands for.
/// The slots are PHYSICAL ones (what a thread's frame is indexed by), already
/// resolved through `and`/`intersect` shadow copies (see [`ShadowCtx`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LeafLocals<'d> {
    /// Every distinct local variable symbol the expression names, in the order
    /// the expression tree reaches them, with the frame slot it reads.
    pub reads: Vec<(Symbol<'d>, LocalVarId)>,
    /// The slot an `LValueReference` node of the expression reads.
    pub lvalue: Option<LocalVarId>,
    /// T15: one slot per end-point application (`inst.triggered`/`inst.matched`)
    /// the expression holds inside a larger expression, in the PRE-ORDER of the
    /// calls in the expression tree (the order [`collect_end_points`] lists them
    /// in; an end-point call's own operand is not descended into). The engine
    /// stores the application's value (`1`/`0`) in the slot before the leaf is
    /// evaluated (a [`ir::Transition::EndPoint`] edge with a `flag`), and an
    /// evaluator reads it where the call stands. Empty for a leaf with none.
    pub end_flags: Vec<LocalVarId>,
}

/// Which 64-bit limb of a wide local variable (LRM 16.10) a value leaf stands
/// for. A variable of more than 64 bits occupies [`ir::LocalVarDecl::slots`]
/// frame slots (its value limbs, then its unknown-plane limbs, see
/// [`sv_sim_sim::sva::wide`]), and one assignment of it is one
/// [`Transition::LocalVarWrite`] per slot: each of those leaves is the SAME
/// expression, and says which word of the four-state value it yields.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LimbSel {
    /// The width of the variable the expression is fitted to.
    pub width: u32,
    /// The leaf is a word of the unknown plane (`x`/`z` bits) rather than of
    /// the value plane.
    pub unknown: bool,
    /// The word's index within its plane (bits `64 * index ..`).
    pub index: u32,
    /// The first leaf of the assignment's group of limb leaves. The group shares
    /// one right-hand side, which the code generator lowers ONCE into a
    /// per-group function writing every limb to a buffer (code size linear in
    /// the width); each limb leaf is a small wrapper reading its word.
    pub group: u32,
}

/// The widest local variable the builder mints (the huge-value limit the rest of
/// the simulator supports). An assignment of one is `2 * ceil(width / 64)` limb
/// leaves, but the right-hand side is lowered once ([`LimbSel::group`]).
pub const MAX_LOCAL_VAR_BITS: u32 = 1 << 20;

/// What the builder knows about one end-point application beyond what the IR
/// carries (see [`ir::EndPoint::site`]).
#[derive(Clone, Copy, Debug)]
pub struct EndSite<'d> {
    pub method: ir::EndMethod,
    /// The `AssertionInstance` expression the method is applied to.
    pub instance: Expression<'d>,
    /// The first clocking event met expanding the instance (its own `@(...)`), or
    /// `None` when it has none and so ends on the clock of the context that tests
    /// it. The engine runs the instance's automaton on this clock; for
    /// [`ir::EndMethod::Triggered`] the builder has already proven it equal to the
    /// context's when both are known.
    pub clock: Option<SemNode<'d>>,
}

/// One local variable in scope: a sequence's declared local or a `local`
/// formal, bound to the CANONICAL slot minted for this expansion.
#[derive(Clone, Copy, Debug)]
struct ScopeVar<'d> {
    sym: Symbol<'d>,
    slot: LocalVarId,
}

/// The shadow slots the second operand of an `and`/`intersect`/`throughout`/
/// `within` gets (LRM 16.10 rule (d): the operands are parallel threads, each
/// with its OWN copy of the variables, initialised from the value at the start
/// of the operator). The first operand keeps the shared slot; the second reads
/// and writes a shadow of every variable the first one touched, so neither
/// sees the other's assignments. `made` is in creation order.
#[derive(Debug)]
struct ShadowCtx {
    /// Canonical slots the first operand read or wrote.
    outer_touched: BTreeSet<LocalVarId>,
    /// `(canonical, the slot it resolved to outside this context, its shadow)`.
    made: Vec<(LocalVarId, LocalVarId, LocalVarId)>,
}

/// Maps each [`LeafId`] a built [`ir::Automaton`] references back to the
/// Boolean-leaf [`Expression`] it stands for. Kept outside `ir::Automaton`
/// itself (see this module's own doc comment) -- a later wiring task
/// compiles each entry via [`super::leaf::compile_leaf`] into the real
/// `PredicateFn` the engine invokes; this task only identifies and numbers
/// them.
#[derive(Debug)]
pub struct LeafTable<'d> {
    leaves: Vec<Expression<'d>>,
    /// Parallel to `leaves`: the leaf stands for `!expr` (4-state logical
    /// negation collapsed to a Boolean, so it holds only where `expr` is KNOWN
    /// false), the gap sample of a goto repetition (see [`build_goto`]).
    negated: Vec<bool>,
    /// T13: the local variables each leaf reads, parallel to `leaves`.
    leaf_locals: Vec<LeafLocals<'d>>,
    /// Parallel to `leaves`: the limb of a wide local variable the leaf yields
    /// ([`LimbSel`]); `None` for every other leaf.
    limbs: Vec<Option<LimbSel>>,
    /// T13: the local variables in scope, innermost expansion last (the lookup
    /// scans from the back, so a nearer declaration wins).
    scope: Vec<ScopeVar<'d>>,
    /// T13: the canonical slots definitely assigned at the node being built
    /// (the `X` of F.5.4's `flow(X, R)`); every builder function reads it on
    /// entry and restores it on return.
    flow_in: VarSet,
    /// T13: every canonical slot read or written so far, in order. The first
    /// operand of a shadowing operator is delimited by a mark into this log.
    touched: Vec<LocalVarId>,
    /// T13: the open shadow contexts, outermost first.
    shadows: Vec<ShadowCtx>,
    /// T12: the named-sequence instances being expanded right now (see the
    /// module doc's "Named sequence instances"). Builder state that rides
    /// along with the leaf table because every builder function already
    /// threads it.
    env: ranges::FormalEnv,
    /// LRM 16.8's dependency chain above the node being built: the
    /// declarations whose body (or whose instance's actual argument) the node
    /// sits in, outermost first. Not the expansion stack: an actual argument
    /// is expanded under the chain of its call site (see
    /// [`ranges::FormalFrame::origins`]).
    chain: Vec<ranges::ChainLink>,
    /// How many instance expansions enclose the node being built.
    instance_depth: usize,
    /// T28: the clocks of the assertion, indexed by [`ClockId`]: the clocking
    /// events met, interned by [`events_equivalent`]. Entry 0 is the root clock;
    /// it is `None` only until the first event met binds it, when the caller
    /// stripped no clock (the unit-test convention of [`build_automaton`]).
    clocks: Vec<Option<SemNode<'d>>>,
    /// T28: the context clock of the node being built (see the module doc's
    /// "Multiclocked sequences").
    cur: ClockId,
    /// T31 (16.14.7): the context clock at the entry of each enclosing
    /// named-sequence or property instance, innermost last. A default actual
    /// `$inferred_clock` resolves to the clock the instance was written under.
    inferred: Vec<Option<SemNode<'d>>>,
    /// T31: the root clock is the one the context supplied (a procedural block's
    /// or the default clocking, 16.14.6), not one the assertion wrote. A property
    /// that opens with its own clocking event (a clocked property declaration
    /// instantiated with no clock) replaces it: the default applies only to what
    /// has no clock (14.12).
    root_inferred: bool,
    /// T38 (16.14.7, 17.4): the assertion's `disable iff` is `$inferred_disable`
    /// (the default actual of a checker or property formal), so the condition is the
    /// `default disable iff` of the INSTANTIATION context rather than of the scope
    /// the assertion was declared in.
    disable_inferred: bool,
    /// T14: the subroutine calls attached as match items, indexed by
    /// [`ir::CallId`] (see [`super::actions`]).
    pub(super) calls: Vec<CallSite<'d>>,
    /// T15: every end-point application of the assertion, at every nesting level,
    /// indexed by [`ir::EndPoint::site`].
    end_sites: Vec<EndSite<'d>>,
    /// T18: the assertion uses a global clocking future sampled value
    /// function (16.9.4), so its action block runs at the global tick after
    /// the attempt ends.
    future_gclk: bool,
}

impl<'d> LeafTable<'d> {
    fn new(root_clock: Option<SemNode<'d>>) -> Self {
        LeafTable {
            future_gclk: false,
            calls: Vec::new(),
            end_sites: Vec::new(),
            leaves: Vec::new(),
            negated: Vec::new(),
            leaf_locals: Vec::new(),
            limbs: Vec::new(),
            scope: Vec::new(),
            flow_in: VarSet::new(),
            touched: Vec::new(),
            shadows: Vec::new(),
            env: ranges::FormalEnv::default(),
            chain: Vec::new(),
            instance_depth: 0,
            clocks: vec![root_clock],
            cur: ClockId(0),
            inferred: Vec::new(),
            root_inferred: false,
            disable_inferred: false,
        }
    }

    /// Whether the assertion's `disable iff` condition is `$inferred_disable`
    /// (see [`LeafTable::disable_inferred`]).
    pub fn disable_inferred(&self) -> bool {
        self.disable_inferred
    }

    /// The [`ClockId`] of the clocking event `event`: an equivalent one met
    /// before, or a new clock. When the caller gave no root clock, the first event
    /// met IS the root clock.
    fn intern_clock(&mut self, event: SemNode<'d>) -> ClockId {
        for (i, known) in self.clocks.iter().enumerate() {
            if known.is_some_and(|k| events_equivalent(k, event)) {
                return ClockId(i as u32);
            }
        }
        if self.clocks[0].is_none() {
            self.clocks[0] = Some(event);
            return ClockId(0);
        }
        self.clocks.push(Some(event));
        ClockId(self.clocks.len() as u32 - 1)
    }

    /// T31 (16.14.7): the clock of the clocking event `event` of a `Clocking`
    /// node. An event that is just `$inferred_clock` (the default actual of a
    /// formal, left as a call by slang) is the context clock at the instance
    /// that substituted it ([`LeafTable::inferred`]); any other event is
    /// interned.
    fn resolve_clock(
        &mut self,
        event: SemNode<'d>,
        scope: &Symbol<'d>,
    ) -> Result<ClockId, LoweringError> {
        if is_inferred_clock_event(event) {
            let at = self
                .inferred
                .last()
                .copied()
                .unwrap_or(self.clocks[self.cur.0 as usize]);
            let Some(ev) = at else {
                return Err(LoweringError::unsupported_at(
                    "`$inferred_clock` (LRM 16.14.7) in an assertion whose instantiation \
                     context has no clock (clock inference, 16.14.6, found none)",
                    scope,
                ));
            };
            return Ok(self.intern_clock(ev));
        }
        Ok(self.intern_clock(event))
    }

    /// T31: the outermost clocking event of the property, `event`, replaces an
    /// inferred root clock (see [`LeafTable::root_inferred`]). Called once, by the
    /// `Clocking` node at the very top of the property.
    fn rebind_inferred_root(&mut self, event: SemNode<'d>) {
        if std::mem::take(&mut self.root_inferred)
            && self.cur == ClockId(0)
            && self.clocks.len() == 1
            && !is_inferred_clock_event(event)
        {
            self.clocks[0] = Some(event);
        }
    }

    /// How many distinct clocks the assertion has (T28).
    pub fn clock_count(&self) -> usize {
        self.clocks.len()
    }

    /// The clocking event of `clock` (T28): `None` only for the root clock of an
    /// assertion whose caller gave none and that met no event.
    pub fn clock_event(&self, clock: ClockId) -> Option<SemNode<'d>> {
        self.clocks[clock.0 as usize]
    }

    /// The local variables leaf `id` reads (T13); empty for a leaf that names
    /// none. A leaf that reads any cannot be compiled by
    /// [`super::leaf::compile_leaf`] (a pure function of signals) yet: the
    /// runtime engine (T29) evaluates it against the thread's frame.
    pub fn locals_of(&self, id: LeafId) -> &LeafLocals<'d> {
        &self.leaf_locals[id.0 as usize]
    }

    /// The subroutine call `id` names (T14): its callee expression and how each
    /// argument is passed. Panics if `id` was not minted by this table.
    pub fn call_site(&self, id: ir::CallId) -> &CallSite<'d> {
        &self.calls[id.0 as usize]
    }

    /// Whether the assertion contains a global clocking future sampled value
    /// function (T18, LRM 16.9.4): its attempt ends at the last assertion-clock
    /// tick as usual, but the action block (and the default `$error`) must run
    /// at the next global clock tick, through
    /// `sv_sim_sim::sched::maturation::report_at_global_tick`.
    pub fn uses_future_gclk(&self) -> bool {
        self.future_gclk
    }

    /// How many subroutine calls the automaton attaches as match items.
    pub fn call_count(&self) -> usize {
        self.calls.len()
    }

    /// The subroutine calls the automaton attaches as match items, indexed by
    /// [`ir::CallId`].
    pub fn calls(&self) -> &[CallSite<'d>] {
        &self.calls
    }

    /// The end-point application [`ir::EndPoint::site`] `site` names (T15).
    /// Panics if `site` was not minted by this table.
    pub fn end_site(&self, site: u32) -> &EndSite<'d> {
        &self.end_sites[site as usize]
    }

    /// How many end-point applications the assertion has, at every nesting level.
    pub fn end_site_count(&self) -> usize {
        self.end_sites.len()
    }

    /// Registers `e` as a leaf after checking every local variable it names
    /// against the flow set `self.flow_in` (LRM 16.10, F.5.4): a read of a
    /// variable that is not definitely assigned on every path reaching it is a
    /// loud error. `lvalue` is the canonical slot an `LValueReference` inside
    /// `e` stands for (a compound assignment's own target, which counts as a
    /// read of that variable).
    ///
    /// An end-point application (`s.triggered`/`s.matched`, T15) is refused here:
    /// it needs the [`ir::Transition::EndPoint`] edge that sets its flag, which
    /// only a Boolean leaf of a sequence gets (see [`build_leaf`]), so a value
    /// expression of a match item or a declaration initializer holding one is a
    /// loud error instead of a leaf nothing could evaluate.
    pub(super) fn push_leaf(
        &mut self,
        a: &mut ir::Automaton,
        e: Expression<'d>,
        lvalue: Option<LocalVarId>,
        scope: &Symbol<'d>,
    ) -> Result<LeafId, LoweringError> {
        let mut points = Vec::new();
        collect_end_points(e, &mut points);
        if !points.is_empty() {
            return Err(LoweringError::unsupported_at(
                "a sequence method `.triggered`/`.matched` inside a match item or a local \
                 variable initializer is not implemented (the end point is tested where a \
                 sequence operand stands, LRM 16.9.11/16.13.5; sva T15)",
                scope,
            ));
        }
        self.push_leaf_flags(a, e, lvalue, &[], false, scope)
    }

    /// [`Self::push_leaf`] for a Boolean leaf whose end-point applications have
    /// each been given a flag slot, `flags[i]` for the i-th in pre-order.
    fn push_leaf_flags(
        &mut self,
        a: &mut ir::Automaton,
        e: Expression<'d>,
        lvalue: Option<LocalVarId>,
        flags: &[LocalVarId],
        negated: bool,
        scope: &Symbol<'d>,
    ) -> Result<LeafId, LoweringError> {
        let mut syms = Vec::new();
        let mut reads_lvalue = false;
        collect_local_reads(e.as_sem_node(), &mut syms, &mut reads_lvalue);
        let mut locals = LeafLocals {
            end_flags: flags.to_vec(),
            ..LeafLocals::default()
        };
        for sym in syms {
            let slot = self.resolve(sym, scope)?;
            self.check_flows(sym, slot, scope)?;
            let phys = self.phys_of(a, slot);
            if !locals.reads.iter().any(|(s, _)| *s == sym) {
                locals.reads.push((sym, phys));
            }
        }
        if let Some(target) = lvalue {
            if reads_lvalue {
                let name = self
                    .scope
                    .iter()
                    .rev()
                    .find(|v| v.slot == target)
                    .map(|v| v.sym.name().to_string())
                    .unwrap_or_default();
                if !self.flow_in.contains(&target) {
                    return Err(not_flowing(&name, scope));
                }
            }
            locals.lvalue = Some(self.phys_of(a, target));
        }
        let id = LeafId(self.leaves.len() as u32);
        self.leaves.push(e);
        self.negated.push(negated);
        self.leaf_locals.push(locals);
        self.limbs.push(None);
        Ok(id)
    }

    /// The limb of a wide local variable leaf `id` yields, `None` for a leaf
    /// that is an ordinary value or condition.
    pub fn limb_of(&self, id: LeafId) -> Option<LimbSel> {
        self.limbs[id.0 as usize]
    }

    /// The leaves of a by-value subroutine-call argument `e` (16.11) wider than
    /// 64 bits: one per 64-bit word of its four-state value, value limbs first
    /// and then the unknown-plane limbs ([`LimbSel`], the layout a wide
    /// assertion input has). An argument of at most 64 bits is one plain leaf.
    pub(super) fn push_arg_leaves(
        &mut self,
        a: &mut ir::Automaton,
        e: Expression<'d>,
        width: u32,
        scope: &Symbol<'d>,
    ) -> Result<Vec<LeafId>, LoweringError> {
        if width <= 64 {
            return Ok(vec![self.push_leaf(a, e, None, scope)?]);
        }
        if width > MAX_LOCAL_VAR_BITS {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "a by-value argument of {width} bits in a sequence match-item call (16.11): \
                     at most {MAX_LOCAL_VAR_BITS} bits is implemented"
                ),
                scope,
            ));
        }
        let n = width.div_ceil(64);
        let mut out = Vec::with_capacity(2 * n as usize);
        let mut group = None;
        for slot in 0..2 * n {
            let leaf = self.push_leaf(a, e, None, scope)?;
            self.limbs[leaf.0 as usize] = Some(LimbSel {
                width,
                unknown: slot >= n,
                index: slot % n,
                group: group.get_or_insert(leaf.0).to_owned(),
            });
            out.push(leaf);
        }
        Ok(out)
    }

    /// The `(slot, leaf)` assignments that give the local variable at physical
    /// slot `var` the value of `e` (16.8.2, 16.10): one for a variable of at
    /// most 64 bits, and for a wider one a leaf per slot of it, value limbs
    /// first ([`LimbSel`]). `lvalue` is as for [`Self::push_leaf`].
    ///
    /// The leaves are evaluated one after the other, so a limb leaf that reads
    /// the variable would see the limbs written before it; callers whose
    /// right-hand side can read the target use [`Self::assign_var`].
    pub(super) fn slot_leaves(
        &mut self,
        a: &mut ir::Automaton,
        var: LocalVarId,
        e: Expression<'d>,
        lvalue: Option<LocalVarId>,
        scope: &Symbol<'d>,
    ) -> Result<Vec<(LocalVarId, LeafId)>, LoweringError> {
        let decl = *a.local_var(var);
        if !decl.is_wide() {
            return Ok(vec![(var, self.push_leaf(a, e, lvalue, scope)?)]);
        }
        let n = decl.limbs() as u32;
        let mut out = Vec::with_capacity(2 * n as usize);
        let mut group = None;
        for slot in 0..2 * n {
            let leaf = self.push_leaf(a, e, lvalue, scope)?;
            self.limbs[leaf.0 as usize] = Some(LimbSel {
                width: decl.width,
                unknown: slot >= n,
                index: slot % n,
                group: group.get_or_insert(leaf.0).to_owned(),
            });
            out.push((LocalVarId(var.0 + slot), leaf));
        }
        Ok(out)
    }

    /// The actions of the assignment `target = e` of a match item (16.11):
    /// [`Self::slot_leaves`] as [`Transition::LocalVarWrite`]s. When `e` reads
    /// the target (`w = {w, 1'b0}`, `w += 1`) and the target is wide, the limbs
    /// are written into a fresh variable and copied over by a final
    /// [`Transition::LocalVarCopy`], so that every limb of `e` is computed from
    /// the OLD value of the target.
    pub(super) fn assign_var(
        &mut self,
        a: &mut ir::Automaton,
        canon: LocalVarId,
        phys: LocalVarId,
        e: Expression<'d>,
        scope: &Symbol<'d>,
    ) -> Result<Vec<Transition>, LoweringError> {
        let decl = *a.local_var(phys);
        let mut syms = Vec::new();
        let mut reads_lvalue = false;
        collect_local_reads(e.as_sem_node(), &mut syms, &mut reads_lvalue);
        let reads_target = reads_lvalue
            || syms
                .iter()
                .any(|s| self.resolve(*s, scope).is_ok_and(|c| c == canon));
        let temp =
            (decl.is_wide() && reads_target).then(|| a.new_local_var(decl.width, decl.signed));
        let dst = temp.unwrap_or(phys);
        let mut out: Vec<Transition> = self
            .slot_leaves(a, dst, e, Some(canon), scope)?
            .into_iter()
            .map(|(var, value)| Transition::LocalVarWrite { var, value })
            .collect();
        if let Some(src) = temp {
            out.push(Transition::LocalVarCopy { dst: phys, src });
        }
        Ok(out)
    }

    /// The canonical slot of local variable `sym`: its nearest declaration in
    /// scope. A local variable that no enclosing named sequence declares
    /// (a property-level one, T19/T20's) is a loud error.
    fn resolve(&self, sym: Symbol<'d>, scope: &Symbol<'d>) -> Result<LocalVarId, LoweringError> {
        self.scope
            .iter()
            .rev()
            .find(|v| v.sym == sym)
            .map(|v| v.slot)
            .ok_or_else(|| {
                LoweringError::unsupported_at(
                    &format!(
                        "local variable `{}` is not declared by an enclosing named sequence \
                         (assertion variable declarations of a property or assertion statement \
                         are sva T19/T20's)",
                        sym.name()
                    ),
                    scope,
                )
            })
    }

    /// The F.5.4 read check: `slot` must be in the current flow set.
    fn check_flows(
        &self,
        sym: Symbol<'d>,
        slot: LocalVarId,
        scope: &Symbol<'d>,
    ) -> Result<(), LoweringError> {
        if self.flow_in.contains(&slot) {
            Ok(())
        } else {
            Err(not_flowing(sym.name(), scope))
        }
    }

    /// The physical slot a thread at the current build point reads and writes
    /// for canonical variable `canon`: logs the touch, and (inside the second
    /// operand of a shadowing operator) mints the shadow of a variable the
    /// first operand also touched, outermost context first so a nested context
    /// shadows the slot its parent resolved to.
    fn phys_of(&mut self, a: &mut ir::Automaton, canon: LocalVarId) -> LocalVarId {
        self.touched.push(canon);
        let mut current = canon;
        for ctx in &mut self.shadows {
            if let Some(&(_, _, s)) = ctx.made.iter().find(|(c, _, _)| *c == canon) {
                current = s;
            } else if ctx.outer_touched.contains(&canon) {
                let decl = *a.local_var(canon);
                let shadow = a.new_local_var(decl.width, decl.signed);
                ctx.made.push((canon, current, shadow));
                current = shadow;
            }
        }
        current
    }

    /// Mints the canonical slot of `sym` (a declared local or a formal's body
    /// copy) and brings it into scope.
    fn declare(
        &mut self,
        a: &mut ir::Automaton,
        sym: Symbol<'d>,
        scope: &Symbol<'d>,
    ) -> Result<LocalVarId, LoweringError> {
        // A `real`/`realtime`/`shortreal` local (LRM 16.10) is a slot of its IEEE bits, as a
        // real variable's cell is everywhere else: 64 bits for the first two (`shortreal`
        // keeps its f32 bits in the low 32, see `real::to_storage`).
        //
        // A `string` local (LRM 16.10 "any data type") is the 64-bit id of an interned
        // string (`crate::strings`), so it is a plain unsigned 64-bit slot: a fresh frame
        // holds id 0, the empty string, which is the string default value (6.16). A class
        // handle local (6.14) is likewise the 64-bit object id (0 = `null`, the default).
        //
        // A queue, dynamic array or associative array local (LRM 16.10) is likewise a 64-bit
        // handle (0, the empty collection, in a fresh frame). The row holds an immutable
        // snapshot of each collection the assertion reads (`AssertionSpec::coll_words`), so
        // `q = src` stores the snapshot handle itself: frames, forks and both evaluators
        // share it read-only. Only integral and handle-free struct elements are implemented.
        let ty = sym.declared_type().filter(|t| {
            t.is_integral()
                || t.is_floating()
                || t.is_string()
                || t.is_class()
                || is_stored_aggregate(t)
                || is_integral_collection(t)
        });
        let Some(ty) = ty else {
            if sym
                .declared_type()
                .is_some_and(|t| t.is_dynamically_sized_array())
            {
                return Err(LoweringError::unsupported_at(
                    &format!(
                        "local variable `{}` is a queue, dynamic array or associative array \
                         whose elements are not integral or unpacked structs of integral fields \
                         (they are themselves collections, or hold handles): only collections of \
                         integral or plain-struct elements are implemented as sequence local \
                         variables (LRM 16.10)",
                        sym.name()
                    ),
                    scope,
                ));
            }
            return Err(LoweringError::unsupported_at(
                &format!(
                    "local variable `{}` has a type that is neither integral, real, string, class handle nor unpacked struct nor fixed-size unpacked array of integral elements; only \
                     those local variables are implemented",
                    sym.name()
                ),
                scope,
            ));
        };
        let is_coll = is_integral_collection(&ty);
        let width = if ty.is_string() || ty.is_class() || is_coll {
            64
        } else if let Some(rows) = flat_array_rows(&ty) {
            let shape = crate::arrays::array_shape(&ty).expect("flat_array_rows saw a shape");
            rows * u64::from(crate::types::TypeWidth::value_width(&shape.elem))
        } else if ty.is_floating() || is_stored_aggregate(&ty) {
            u64::from(crate::types::TypeWidth::value_width(&ty))
        } else {
            ty.bit_width()
        };
        if width == 0 || width > u64::from(MAX_LOCAL_VAR_BITS) {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "local variable `{}` is {width} bits wide; a local variable of 1 to \
                     {MAX_LOCAL_VAR_BITS} bits is implemented (a variable wider than 64 bits \
                     takes a frame slot per 64-bit limb of its value and of its unknown bits, \
                     and each assignment of it a leaf per slot)",
                    sym.name()
                ),
                scope,
            ));
        }
        let slot = a.new_local_var(
            width as u32,
            !(ty.is_string() || ty.is_class() || is_coll || is_stored_aggregate(&ty))
                && ty.is_signed(),
        );
        self.scope.push(ScopeVar { sym, slot });
        Ok(slot)
    }

    /// The `Expression` [`LeafId`] `id` was assigned to. Panics if `id`
    /// was not produced by this same table (a builder-internal invariant,
    /// never reachable from untrusted input -- see `ir::Automaton::
    /// add_edge`'s identical note).
    pub fn get(&self, id: LeafId) -> Expression<'d> {
        self.leaves[id.0 as usize]
    }

    /// Whether leaf `id` stands for `!expr` of its [`Self::get`] expression (the
    /// gap sample of a goto/nonconsecutive repetition, 16.9.2) rather than for
    /// the expression itself. The compiled guard is then
    /// [`super::leaf::compile_negated_leaf`]: `!expr` evaluated in 4-state logic,
    /// so an `x`/`z` expression makes it false, exactly as the hand-written
    /// `!b` is. Panics if `id` was not produced by this table.
    pub fn is_negated(&self, id: LeafId) -> bool {
        self.negated[id.0 as usize]
    }

    pub fn len(&self) -> usize {
        self.leaves.len()
    }
}

/// Every local-variable symbol an expression tree names, in the order the walk
/// reaches them (a variable named twice is listed twice), and whether it holds
/// an `LValueReference` (the target of a compound assignment).
///
/// Only `NamedValue` nodes count: slang's `Conversion` nodes report the symbol
/// of their operand too, and would otherwise double every converted read.
pub(super) fn collect_local_reads<'d>(
    n: SemNode<'d>,
    out: &mut Vec<Symbol<'d>>,
    lvalue: &mut bool,
) {
    if let Some(e) = n.as_expression() {
        // The instance an end-point method is applied to is evaluated in a frame
        // of its own (T15), so what it reads is not a read of this expression.
        if end_point_call(e).is_some() {
            return;
        }
        // A deliberate two-kind filter, not a dispatch over every kind: every
        // other expression kind is simply not a local read, so it is compared
        // with `==` rather than matched with a wildcard arm.
        let k = e.kind();
        if k == ExpressionKind::NamedValue {
            if let Some(s) = e
                .referenced_symbol()
                .filter(|s| s.kind() == SymbolKind::LocalAssertionVar)
            {
                out.push(s);
            }
        } else if k == ExpressionKind::LValueReference {
            *lvalue = true;
        }
    }
    for c in n.children() {
        collect_local_reads(c, out, lvalue);
    }
}

/// `e` as the application of a sequence method to a sequence instance
/// (`inst.triggered`, `inst.matched`; LRM 16.9.11, 16.13.5, 16.13.6): the method
/// and the `AssertionInstance` expression it is applied to. `None` for anything
/// else, including `event.triggered`, whose operand is an event (an ordinary
/// value, lowered by the expression lowerer).
fn end_point_call<'d>(e: Expression<'d>) -> Option<(ir::EndMethod, Expression<'d>)> {
    if e.kind() != ExpressionKind::Call {
        return None;
    }
    let name = e.system_subroutine()?.known_name_id();
    // Two names out of every system subroutine: compared, not matched.
    let method = if name == KnownSystemName::Triggered {
        ir::EndMethod::Triggered
    } else if name == KnownSystemName::Matched {
        ir::EndMethod::Matched
    } else {
        return None;
    };
    let operand = *e.operands().first()?;
    (operand.kind() == ExpressionKind::AssertionInstance).then_some((method, operand))
}

/// Every end-point application in `e`, in pre-order (`!(a.triggered && b.matched)`
/// is `[a.triggered, b.matched]`), not descending into an application's own
/// operand (its instance has its own expressions, built as an automaton of their
/// own). The order is the one [`LeafLocals::end_flags`] is indexed by.
pub(crate) fn collect_end_points<'d>(
    e: Expression<'d>,
    out: &mut Vec<(ir::EndMethod, Expression<'d>)>,
) {
    if let Some(p) = end_point_call(e) {
        out.push(p);
        return;
    }
    for c in e.as_sem_node().children() {
        if let Some(c) = c.as_expression() {
            collect_end_points(c, out);
        }
    }
}

/// Whether the match-item call `e` is a built-in method of a queue, dynamic array or
/// associative array that is a sequence local variable (see `attach_match_items`).
fn is_local_collection_method(e: Expression<'_>) -> bool {
    let ops = e.operands();
    e.call_subroutine().is_none()
        && ops.first().is_some_and(|r| {
            crate::collections::coll_of_expr(r).is_some()
                && r.kind() == ExpressionKind::NamedValue
                && r.referenced_symbol()
                    .is_some_and(|s| s.kind() == SymbolKind::LocalAssertionVar)
        })
}

/// The error for a read of local variable `name` that does not flow to it
/// (LRM 16.10, Annex F.5.4).
/// A queue, dynamic array or associative array of integral or unpacked-struct elements
/// holding no handle (a collection element would stay live inside the shared snapshot): a
/// sequence local of that type is a 64-bit collection handle (LRM 16.10).
fn is_integral_collection(t: &sv_lang::Type<'_>) -> bool {
    sv_sim_sim::state::storage::is_collection(t)
        && t.element_type().is_some_and(|e| {
            (e.is_integral()
                || e.is_unpacked_struct()
                || sv_sim_sim::state::storage::is_collection(&e))
                && crate::collections::handle_offsets(&e)
                    .iter()
                    .all(|s| s.kind == crate::collections::HandleKind::Coll && s.guards.is_empty())
                && collection_nest(t).is_some()
        })
}

/// Where the collections inside the elements of the collection type `ty` sit
/// (a queue of queues, a struct element with a queue field; none for a flat
/// collection): the snapshot of a collection read by an assertion copies those
/// inner collections too, so a sequence local assigned from it is a sampled
/// value copy (LRM 16.10, 7.6). `None` for an element holding a class handle.
pub(super) fn collection_nest(ty: &sv_lang::Type<'_>) -> Option<sv_sim_sim::collections::Nest> {
    let elem = ty.element_type()?;
    let mut slots = Vec::new();
    nest_slots(&elem, 0, &mut slots)?;
    Some(sv_sim_sim::collections::Nest { slots })
}

fn nest_slots(
    ty: &sv_lang::Type<'_>,
    base: u32,
    out: &mut Vec<(u32, sv_sim_sim::collections::Nest)>,
) -> Option<()> {
    use sv_sim_sim::state::storage;
    if storage::is_collection(ty) {
        out.push((base, collection_nest(ty)?));
    } else if ty.is_class() {
        return None;
    } else if ty.is_unpacked_struct() {
        for f in ty.fields() {
            let (Some(fty), Some((lo, _))) =
                (f.value_type(), storage::field_slice(ty, f.field_index()))
            else {
                continue;
            };
            nest_slots(&fty, base + lo as u32, out)?;
        }
    } else if ty.is_unpacked_array() {
        let elem = ty.element_type()?;
        let ew = storage::storage_width(&elem)?;
        for i in 0..ty.fixed_unpacked_array_range().width() {
            nest_slots(&elem, base + i * ew as u32, out)?;
        }
    } else if !crate::collections::handle_offsets(ty).is_empty() {
        return None;
    }
    Some(())
}

/// An unpacked struct: a value sv-sim holds as one flat run of stored bits (fields
/// concatenated, `sv_sim_sim::state::storage`), so a sequence local of that type (LRM 16.10)
/// is a slot of that many bits, like any wide integral local, and `s.f` is the usual slice
/// of the base's stored bits. A fixed-size unpacked array is NOT included: an array
/// variable's reads and element selects go through a row buffer (`arrays::Backing::Local`),
/// not the flat bits, so it stays refused by name.
fn is_stored_aggregate(t: &sv_lang::Type<'_>) -> bool {
    t.is_unpacked_struct() || flat_array_rows(t).is_some()
}

/// The row count of a fixed-size unpacked array of integral (or packed/enum) elements small
/// enough to unroll (`arrays::pack_array_value`'s limit), the arrays a sequence local can be
/// (LRM 16.10): the slot holds the array's flat stored bits (row `r` in bits `[r*w +: w]`)
/// and a read primes a row buffer from them (`emit.rs prime_locals`), so element selects use
/// the ordinary local-array path. `None` for any other array (dynamic, queue, associative,
/// real, string or handle elements), which stays refused by name.
fn flat_array_rows(t: &sv_lang::Type<'_>) -> Option<u64> {
    let shape = crate::arrays::array_shape(t)?;
    (!shape.dims.is_empty()
        && shape.rows() <= crate::arrays::MAX_UNROLLED_ROWS
        && shape.elem.is_integral()
        && crate::collections::handle_offsets(&shape.elem).is_empty())
    .then(|| shape.rows())
}

fn not_flowing(name: &str, scope: &Symbol<'_>) -> LoweringError {
    LoweringError::unsupported_at(
        &format!(
            "local variable `{name}` does not flow out to this read: it is not assigned on every \
             path that reaches it, or it is blocked by the parallel threads of an `and`/\
             `intersect` that both assign it (LRM 16.10, Annex F.5.4)"
        ),
        scope,
    )
}

/// One in-progress piece of automaton under construction -- a standard
/// NFA-fragment shape (Thompson construction): a single entry state, and
/// the set of states ("exits") from which the next operand (or, at the top
/// level, [`build_automaton`]'s own `Match` finalization) should continue.
///
/// The fragment's language is the set of paths from `entry` to an `exits`
/// state (its NONEMPTY matches, each spending at least the tick it starts
/// on), plus -- when `empty` -- the empty match (16.9.2.1: zero operands
/// consumed, zero elapsed ticks). `entry` is never itself an exit: the empty
/// match is a flag, not a state, because it contributes no path (see the
/// module doc comment). A fragment with no exits and `empty == false` never
/// matches (`a[*0] ##0 b`).
///
/// `flow` is the F.5.4 triple of the fragment (T13); every combinator composes
/// it with the same operator that composes the states (see [`Flow`]).
struct Fragment {
    entry: ThreadStateId,
    exits: Vec<ThreadStateId>,
    empty: bool,
    flow: Flow,
    /// The clocks the fragment spans (T28); `None` while it has no clocking event
    /// of its own and so takes the context clock of whatever contains it.
    clock: Option<Span>,
}

/// The clocks a sequence fragment spans (16.13.1, T28): the clock its first
/// Boolean operand is evaluated in (`start`), the one its last is (`end`), and
/// whether it changes clock anywhere in between (`multi`, a `##1`/`##0` between
/// differently clocked operands). A singly clocked fragment has
/// `start == end && !multi`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
struct Span {
    start: ClockId,
    end: ClockId,
    multi: bool,
}

impl Span {
    fn single(c: ClockId) -> Self {
        Span {
            start: c,
            end: c,
            multi: false,
        }
    }
}

/// Builds a complete automaton for one sequence/property tree rooted at
/// `root` (typically an `AnalyzedAssertion::root()`, with any `Clocking`
/// wrapper already stripped by the caller -- the same convention T6/T7/T8's
/// own tests already use). `tree`/`scope` are used exactly as `ranges`/`op`
/// already use them (syntax lookup, error location).
///
/// `root_clock` is the event expression of the `Clocking` wrapper the caller
/// stripped (its `[event, body]` first child), or `None` when `root` had no
/// clock of its own. It seeds the builder's clocking-event check, so a named
/// sequence instance that carries a DIFFERENT event (`assert property
/// (@(negedge clk) s)` with `sequence s; @(posedge sysclk) ...`) is the loud
/// multiclock error of [`build_clocking`] instead of being built on the
/// instance's clock alone.
///
/// This task's own scope is `AssertionExprKind::{Simple, SequenceConcat,
/// SequenceWithMatch-as-a-bare-repetition-wrapper}` -- see [`build_assertion`]
/// for the full, named list of what is deliberately not yet implemented
/// (every rejection is a [`LoweringError`], never a panic or a silent wrong
/// answer).
///
/// Returns the finished [`ir::Automaton`] (every reachable exit of `root`'s
/// own top-level fragment gets a `Transition::Match { actions: vec![] }`
/// self-loop edge -- T29 onward fills in real actions; the builder's own job
/// stops at the automaton's *shape*, plus [`ir::Automaton::admits_empty`] for
/// the empty match) plus the [`LeafTable`] a later wiring task compiles into
/// real predicates.
pub fn build_automaton<'d>(
    root: AssertionExpr<'d>,
    root_clock: Option<SemNode<'d>>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<(ir::Automaton, LeafTable<'d>), LoweringError> {
    let mut automaton = blank_automaton();
    let mut leaves = LeafTable::new(root_clock);
    leaves.future_gclk = super::gclk::check(root, scope)?;
    let frag = build_assertion(&mut automaton, &mut leaves, root, tree, scope)?;
    finish_automaton(&mut automaton, frag);
    Ok((automaton, leaves))
}

/// An automaton with no state yet (the builder allocates its own entry).
fn blank_automaton() -> ir::Automaton {
    ir::Automaton {
        states: Vec::new(),
        start: ThreadStateId(0),
        admits_empty: false,
        first_match_groups: 0,
        local_vars: Vec::new(),
        end_points: Vec::new(),
        entry_clock: ClockId(0),
    }
}

/// Closes `a` over its top-level fragment: the fragment's entry is the start,
/// its empty flag the automaton's, and every distinct exit gets its `Match`
/// self-loop. Its entry clock is the clock the fragment starts in.
fn finish_automaton(a: &mut ir::Automaton, frag: Fragment) {
    a.entry_clock = frag.clock.map_or(ClockId(0), |s| s.start);
    a.start = frag.entry;
    a.admits_empty = frag.empty;
    add_match_edges(a, frag.exits);
    // The operators that rebuild their operands (T11's products) leave the
    // operands' own states behind, unreferenced.
    prune_unreachable(a);
}

/// Gives every distinct state of `exits` its `Match` self-loop: the edge that
/// says a match of the fragment ends there.
fn add_match_edges(a: &mut ir::Automaton, exits: Vec<ThreadStateId>) {
    // `seen` is membership-only (never iterated), so the Match edges stay in
    // `exits` order -- deterministic.
    let mut seen = HashSet::new();
    for exit in exits {
        if !seen.insert(exit) {
            continue;
        }
        a.add_edge(
            exit,
            None,
            Transition::Match {
                actions: Vec::new(),
            },
            exit,
        );
    }
}

/// Drops every state not reachable from `a.start` and renumbers the rest in
/// breadth-first order from the start (so `start` becomes state 0), following
/// each state's edges in their stored order: the numbering is a pure function
/// of the graph, never of allocation order or of any hash iteration.
fn prune_unreachable(a: &mut ir::Automaton) {
    prune_from(a, &[a.start]);
}

/// [`prune_unreachable`] for an automaton with several entry points (a property
/// holds one per sequence): keeps what any of `roots` reaches, numbers it
/// breadth-first from the first root, then the next root not yet reached, and so
/// on, and returns the new id of every old state (`None` for a dropped one).
/// `a.start` becomes the first root's new id.
fn prune_from(a: &mut ir::Automaton, roots: &[ThreadStateId]) -> Vec<Option<ThreadStateId>> {
    let mut new_id: Vec<Option<u32>> = vec![None; a.states.len()];
    let mut order: Vec<ThreadStateId> = Vec::new();
    let mut next = 0;
    for &root in roots {
        if new_id[root.0 as usize].is_none() {
            new_id[root.0 as usize] = Some(order.len() as u32);
            order.push(root);
        }
        while next < order.len() {
            let s = order[next];
            next += 1;
            for e in &a.states[s.0 as usize].edges {
                let slot = &mut new_id[e.target.0 as usize];
                if slot.is_none() {
                    *slot = Some(order.len() as u32);
                    order.push(e.target);
                }
            }
        }
    }
    let states = order
        .iter()
        .map(|s| {
            let mut st = a.states[s.0 as usize].clone();
            for e in &mut st.edges {
                // Every target of a reachable state was reached above.
                e.target = ThreadStateId(
                    new_id[e.target.0 as usize].expect("a reachable state's targets are reachable"),
                );
            }
            st
        })
        .collect();
    a.states = states;
    a.start = roots
        .first()
        .and_then(|r| new_id[r.0 as usize])
        .map_or(ThreadStateId(0), ThreadStateId);
    new_id.into_iter().map(|n| n.map(ThreadStateId)).collect()
}

/// Dispatches on `expr.kind()`. The kinds implemented are `Simple`,
/// `SequenceConcat`, `SequenceWithMatch` (T9/T10) and, from T11, the sequence
/// operators `Binary` (`and`/`or`/`intersect`/`throughout`/`within`) and
/// `FirstMatch`; every other kind is a named, loud [`LoweringError`] citing
/// which later task owns it -- never a silent guess (ARCHITECTURE §7 item 9's
/// "every kind match shouts" discipline, applied here since
/// `AssertionExprKind` is a `sv-lang`-mirrored kind enum).
fn build_assertion<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    match expr.kind() {
        AssertionExprKind::Simple => build_simple(a, leaves, expr, tree, scope),
        AssertionExprKind::SequenceConcat => build_concat(a, leaves, expr, tree, scope),
        AssertionExprKind::SequenceWithMatch => {
            build_sequence_with_match(a, leaves, expr, tree, scope)
        }
        AssertionExprKind::Binary => build_binary(a, leaves, expr, tree, scope),
        AssertionExprKind::FirstMatch => build_first_match(a, leaves, expr, tree, scope),
        // A clocking event inside a sequence: a named sequence's body carrying the
        // declaration's own `@(...)`, or a clocked operand of a multiclocked
        // sequence (16.13.1); see `build_clocking`. At the root the caller has
        // already stripped the assertion's own clock (T7).
        AssertionExprKind::Clocking => build_clocking(a, leaves, expr, tree, scope),
        other => Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: AssertionExprKind::{other:?} is a property expression, \
                 not a sequence (LRM 16.12.1): a sequence is built from Boolean operands, \
                 `##` concatenation, repetition, match items, first_match and the sequence \
                 operators and/or/intersect/throughout/within; the property operators are \
                 built by `build_property`"
            ),
            scope,
        )),
    }
}

/// Builds the fragment for one generic operand node (an `AssertionExpr`
/// child or a bare `Expression` leaf child -- the same dual shape
/// `sv-sim-codegen::sva::{collect_boolean_leaves, assertion_expr_leaf_
/// children}` already dispatch on). Used by [`build_concat`] for each of a
/// concatenation's operands.
fn build_node<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    node: SemNode<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    if let Some(e) = node.as_expression() {
        return build_operand(a, leaves, e, tree, scope);
    }
    if let Some(ae) = node.as_assertion_expr() {
        return build_assertion(a, leaves, ae, tree, scope);
    }
    Err(LoweringError::unsupported_at(
        "sva automaton builder: a sequence operand is neither an Expression nor an \
         AssertionExpr (unexpected SemNode kind)",
        scope,
    ))
}

/// 16.9.1's atomic step: one Boolean leaf, sampled over exactly the tick it
/// is evaluated on. Modeled as `entry --[guard=Some(leaf), Epsilon]--> exit`
/// (zero ADDITIONAL elapsed ticks -- see `ir::Edge`'s own doc comment in
/// `sv-sim-sim` for why a leaf's own evaluation never advances a sequence's
/// clock; only a `##`/repetition-link delay does). Never empty (`empty:
/// false`): a real Boolean sample always consumes exactly one real leaf
/// check, which is the LRM's technical definition of non-empty (16.9.2.1).
///
/// A leaf that applies `.triggered`/`.matched` to a sequence instance inside a
/// larger expression (`!s.triggered`, `a && s.matched`, T15) first passes one
/// flag-form [`Transition::EndPoint`] edge per application, in pre-order: each
/// stores whether its instance reached its end point on this tick in a fresh
/// frame slot, which the leaf reads where the application stands (see
/// [`LeafLocals::end_flags`]). Nothing flows out of such an application (16.10:
/// it is not a maximal Boolean expression), so the fragment's flow stays the
/// identity.
///
/// `negated` builds the sample of `!leaf` instead (the gap of a goto repetition,
/// see [`build_goto`]): the guard is a leaf marked [`LeafTable::is_negated`], so
/// nothing else about the fragment changes.
fn build_leaf<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    leaf: Expression<'d>,
    negated: bool,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let mut points = Vec::new();
    collect_end_points(leaf, &mut points);
    let entry = a.new_state();
    let mut at = entry;
    let mut flags = Vec::with_capacity(points.len());
    for (method, inst) in points {
        let built = build_end_point(a, leaves, method, inst, false, tree, scope)?;
        let flag = a.new_local_var(1, false);
        let next = a.new_state();
        a.add_edge(
            at,
            None,
            Transition::EndPoint {
                point: built.point,
                flag: Some(flag),
            },
            next,
        );
        flags.push(flag);
        at = next;
    }
    let exit = a.new_state();
    // A read of a local variable is checked against what flows in (16.10).
    let id = leaves.push_leaf_flags(a, leaf, None, &flags, negated, scope)?;
    a.add_edge(at, Some(id), Transition::Epsilon, exit);
    Ok(Fragment {
        entry,
        exits: vec![exit],
        empty: false,
        flow: Flow::identity(),
        clock: None,
    })
}

/// The fragment of the sequence that matches only the empty match
/// (`a[*0]`; also the starting point of a leading `##` delay): no exits,
/// `empty`. The entry state is a fresh edgeless state.
fn empty_fragment(a: &mut ir::Automaton) -> Fragment {
    Fragment {
        entry: a.new_state(),
        exits: Vec::new(),
        empty: true,
        flow: Flow::identity(),
        clock: None,
    }
}

/// `AssertionExprKind::Simple` (16.7): one Boolean operand, optionally
/// wrapped in a `[*n:m]`/`[+]`/`[->n:m]`/`[=n:m]` repetition (16.9.2). The
/// repetition bound itself is never a semantic child (T3's own module doc:
/// slang folds it to a plain syntax-level `min`/`max` struct) -- recovered
/// here from `tree.syntax(&expr)` cast to [`SimpleSequenceExprSyntax`],
/// exactly as [`ranges::sequence_range_of`]'s own `Simple` arm does (after
/// peeling any plain parens: `(a[*2])` is a `Simple` whose syntax node is
/// the paren, see [`ranges::peel_sequence_parens`]).
fn build_simple<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let kids = expr.children();
    let [leaf_node] = kids.as_slice() else {
        if kids.is_empty() {
            // slang drops an operand it could not bind (an invalid expression,
            // e.g. an instance whose actual is not cast compatible with a typed
            // formal, 16.8.1 (c), or an event expression bound to a `sequence`
            // formal, 16.8.1 (a)) from the semantic tree but keeps the node.
            return Err(LoweringError::unsupported_at(
                "sva automaton builder: a Boolean operand has no semantic expression -- slang \
                 could not bind it, so the design has an error (check `Design::diagnostics()`; \
                 `named::check_formal_argument_rules` names the LRM 16.8/16.8.1 rule; also the \
                 case of an omitted checker actual (LRM 17.3) whose sequence/property default \
                 names a SIBLING formal of the same checker, e.g. `sequence s = req`, which \
                 slang does not bind -- pass the actual explicitly)",
                scope,
            ));
        }
        return Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: Simple node must have exactly one child (its Boolean \
                 operand), found {}",
                kids.len()
            ),
            scope,
        ));
    };
    let leaf_expr = leaf_node.as_expression().ok_or_else(|| {
        LoweringError::unsupported_at(
            "sva automaton builder: Simple node's own child is not an Expression",
            scope,
        )
    })?;

    let syn = tree.syntax(&expr).ok_or_else(|| {
        LoweringError::unsupported_at(
            "sva automaton builder: Simple node has no syntax node in the given tree",
            scope,
        )
    })?;
    let syn = ranges::peel_sequence_parens(syn);
    let simple_syn = SimpleSequenceExprSyntax::cast(syn).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: expected SimpleSequenceExprSyntax, found {:?}",
                syn.kind()
            ),
            scope,
        )
    })?;

    match simple_syn.repetition() {
        None => build_operand(a, leaves, leaf_expr, tree, scope),
        Some(rep) => {
            if leaf_expr.kind() == ExpressionKind::AssertionInstance
                && matches!(rep.op().map(|t| t.text()), Some("->") | Some("="))
            {
                // 16.9.2: goto/nonconsecutive repetition is defined on a
                // Boolean expression only (slang's `SeqInstanceRepetition`).
                return Err(LoweringError::unsupported_at(
                    "goto/nonconsecutive repetition (`[->n:m]`/`[=n:m]`) cannot be applied to a \
                     named sequence instance (LRM 16.9.2: only a Boolean expression may carry \
                     it; only `[*...]`/`[+]` may repeat a sequence)",
                    scope,
                ));
            }
            build_repetition(
                a,
                leaves,
                rep,
                scope,
                &mut |a, leaves| build_operand(a, leaves, leaf_expr, tree, scope),
                &mut |a, leaves| build_gap_operand(a, leaves, leaf_expr, tree, scope),
            )
        }
    }
}

/// The deepest chain of nested named-sequence expansions [`build_instance`]
/// follows before giving up. A real cycle is reported by name long before this
/// (the declaration is on [`LeafTable::chain`]); the cap is the
/// backstop for a cycle through an instance that has no formal arguments, which
/// slang already diagnoses (`RecursiveSequence`) but a caller that ignored the
/// diagnostics would otherwise send into unbounded recursion.
const MAX_INSTANCE_DEPTH: usize = 128;

/// One `Expression` operand of a sequence: a named sequence instance
/// (16.8) is expanded in place, anything else is a Boolean leaf (16.9.1).
fn build_operand<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    e: Expression<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    if e.kind() == ExpressionKind::AssertionInstance {
        build_instance(a, leaves, e, tree, scope)
    } else if let Some((method, inst)) = end_point_call(e) {
        build_end_point_guard(a, leaves, method, inst, tree, scope)
    } else {
        build_leaf(a, leaves, e, false, tree, scope)
    }
}

/// The sample of `!e` for the Boolean operand `e` of a goto/nonconsecutive
/// repetition (16.9.2): one tick on which `e` is false. A `.triggered`/`.matched`
/// application is read in flag form (it is an operand of `!`, so nothing flows
/// out of it, 16.10), which [`build_leaf`] already does for any expression that
/// holds one.
fn build_gap_operand<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    e: Expression<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    if e.kind() == ExpressionKind::AssertionInstance {
        return Err(LoweringError::unsupported_at(
            "goto/nonconsecutive repetition (`[->n:m]`/`[=n:m]`) cannot be applied to a named \
             sequence instance (LRM 16.9.2: only a Boolean expression may carry it)",
            scope,
        ));
    }
    build_leaf(a, leaves, e, true, tree, scope)
}

/// The maximal application of `.triggered`/`.matched` to `inst` as a whole
/// sequence operand (`... ##1 s.triggered ##1 ...`, T15): one guard-form
/// [`Transition::EndPoint`] edge, taken only on a tick `inst` reached its end
/// point and forking per distinct valuation of the local variables that flow out
/// (LRM 16.10). The fragment's flow assigns exactly those variables, so a later
/// read of one is legal (`seq2a`).
fn build_end_point_guard<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    method: ir::EndMethod,
    inst: Expression<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let built = build_end_point(a, leaves, method, inst, true, tree, scope)?;
    let entry = a.new_state();
    let exit = a.new_state();
    a.add_edge(
        entry,
        None,
        Transition::EndPoint {
            point: built.point,
            flag: None,
        },
        exit,
    );
    let mut flow = Flow::identity();
    for v in built.flows_out {
        flow = flow.concat(&Flow::assign(v));
    }
    Ok(Fragment {
        entry,
        exits: vec![exit],
        empty: false,
        flow,
        clock: None,
    })
}

/// What [`build_end_point`] registered.
struct BuiltEndPoint {
    point: ir::EndPointId,
    /// The canonical slots of the caller's local variables that flow out of the
    /// application (empty unless it is maximal).
    flows_out: Vec<LocalVarId>,
}

/// Builds the automaton of the sequence instance `inst`, to which `method` is
/// applied, and registers it on `a` as an end point (T15, LRM 16.9.11, 16.13.5,
/// 16.13.6, 16.10).
///
/// The instance is built as an automaton of its OWN, by [`build_instance`] like
/// any other instance, with the usual rules:
///
/// - nothing is assigned where it starts (`flow_in` is empty): the instance runs
///   from any tick, so what its caller assigned before the application has no
///   relationship to its start (16.10), and a caller local it reads before it
///   assigns it is the usual "does not flow out" error (restriction 2 of 16.10);
/// - it runs in a frame of its own whose slots begin with `a`'s, so a slot id
///   means the same variable on both sides; the thread-local shadows of an
///   enclosing `and`/`intersect` are not applied to it;
/// - an instance with an `input`/`inout` local variable formal is an error
///   (16.8.2: the value is bound at the START of the match, and there is none);
/// - its own clocking event (`@(posedge sysclk)` in its declaration) is the clock
///   it ends on. `.triggered` needs it to be the clock of the context (16.9.11):
///   a different one is an error when both are known. `.matched` accepts any, the
///   whole point of the handoff (16.13.5). An instance with no event of its own
///   ends on the context's clock; whether the clock a `.triggered` context
///   INFERS agrees is the runtime's to check (T29).
///
/// For a `maximal` application the local variables that flow out of the instance
/// end are returned and recorded on the end point with the thread's physical slot
/// each is copied into.
fn build_end_point<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    method: ir::EndMethod,
    inst: Expression<'d>,
    maximal: bool,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<BuiltEndPoint, LoweringError> {
    let what = if method == ir::EndMethod::Triggered {
        "triggered"
    } else {
        "matched"
    };
    for g in inst.assertion_arguments() {
        if !g.port.assertion_port_is_local_var() {
            continue;
        }
        // A `local` formal defaults to `input` (16.8.2).
        let dir = g
            .port
            .assertion_port_direction()
            .unwrap_or(ArgumentDirection::In);
        if dir == ArgumentDirection::In || dir == ArgumentDirection::InOut {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "the sequence method `.{what}` is applied to an instance of a sequence with \
                     the `input`/`inout` local variable formal argument `{}` (LRM 16.8.2: it is \
                     an error to apply `triggered` or `matched` to such an instance)",
                    g.port.name()
                ),
                scope,
            ));
        }
    }

    let prefix = a.local_vars.len() as u32;
    let mut sub = blank_automaton();
    sub.local_vars = a.local_vars.clone();
    let saved_flow = std::mem::take(&mut leaves.flow_in);
    let saved_shadows = std::mem::take(&mut leaves.shadows);
    let touched = leaves.touched.len();
    let built = build_instance(&mut sub, leaves, inst, tree, scope);
    leaves.touched.truncate(touched);
    leaves.shadows = saved_shadows;
    leaves.flow_in = saved_flow;
    let frag = built?;
    // The clocks the instance spans: `None` when it has no clocking event of its
    // own, and then it runs on the context's.
    let span = frag.clock;
    let own_clock = span.and_then(|s| leaves.clock_event(s.start));

    if method == ir::EndMethod::Triggered
        && let Some(s) = span
        && s.end != leaves.cur
    {
        return Err(LoweringError::unsupported_at(
            "the sequence method `.triggered` is applied to an instance that ends on a different \
             clock than the context it appears in (LRM 16.9.11, 16.13.5: the ending clock shall \
             be the same; `.matched` synchronises two clocks)",
            scope,
        ));
    }

    let flowing = frag.flow.flow_out(&VarSet::new());
    finish_automaton(&mut sub, frag);
    sub.entry_clock = span.map_or(leaves.cur, |s| s.start);
    let flows_out: Vec<LocalVarId> = if maximal {
        flowing.into_iter().filter(|v| v.0 < prefix).collect()
    } else {
        Vec::new()
    };
    let flow_out = flows_out
        .iter()
        .map(|&v| (v, leaves.phys_of(a, v)))
        .collect();

    let site = leaves.end_sites.len() as u32;
    leaves.end_sites.push(EndSite {
        method,
        instance: inst,
        clock: own_clock,
    });
    let point = a.new_end_point(ir::EndPoint {
        method,
        site,
        automaton: sub,
        flow_out,
    });
    Ok(BuiltEndPoint { point, flows_out })
}

/// A named sequence instance (16.8), or a reference to a sequence-typed formal
/// (which slang also models as a zero-argument instance wrapping the actual's
/// body): the instance's body is expanded in place -- slang has already
/// substituted nothing, the body is the declaration's, with the formals still
/// symbolic -- with the formals bound on [`LeafTable::env`] so that a `##`/
/// `[...]` bound naming a formal folds to its actual (see [`ranges`]'s
/// "Formal arguments"). Every repeat of the same instance builds its own copy
/// (and its own leaves): the instance's own `Fragment`s are never shared.
///
/// Local variables and `local` formals are handled by
/// [`begin_instance_locals`]/[`finish_instance_locals`] (T13).
///
/// Errors, all loud: a property instance (T19/T20's), a declaration already on the
/// instance's dependency chain (the cyclic dependency 16.8 forbids, including
/// the `s(s(a))`-inside-another-sequence shape slang's own check misses), a
/// sequence declared outside `tree`, and a runaway nesting depth.
fn build_instance<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    inst: Expression<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    // slang models a reference to a sequence formal as the ACTUAL's own
    // instance expression, placed where the reference is written (its syntax
    // is the formal's identifier). That actual was written at the call site,
    // so under 16.8's dependency graph it hangs off the call site's chain, not
    // off the chain of the body holding the reference: `outer(inner(a))` with
    // `outer(w): inner(w) ##1 c` expands `inner` for the actual while `inner`
    // is already being expanded for `outer`'s body, and that is no cycle.
    let origin = formal_reference_origin(tree.syntax(&inst), &leaves.env).map(<[_]>::to_vec);
    let Some(origin) = origin else {
        return expand_instance(a, leaves, inst, tree, scope);
    };
    let saved = std::mem::replace(&mut leaves.chain, origin);
    let built = expand_instance(a, leaves, inst, tree, scope);
    leaves.chain = saved;
    built
}

/// The dependency chain the actual of formal `name` is expanded under, when
/// `syntax` is an identifier naming a formal of the declaration it is written
/// in (a formal shadows every other name, so the match is unambiguous); `None`
/// for anything else, i.e. a real instance written in a body.
fn formal_reference_origin<'e>(
    syntax: Option<Node<'_>>,
    env: &'e ranges::FormalEnv,
) -> Option<&'e [ranges::ChainLink]> {
    let node = syntax?;
    let ident = IdentifierNameSyntax::cast(node)?.identifier()?;
    env.origin_of(&key(node), ident.value_text())
}

/// [`build_instance`] once `leaves.chain` is the chain `inst` hangs off.
fn expand_instance<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    inst: Expression<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    if !inst.expr_type().is_some_and(|t| t.is_sequence_type()) {
        return Err(LoweringError::unsupported_at(
            "a property instance stands where a sequence is required (LRM 16.12.1: a property \
             is not a sequence_expr, so it cannot be an operand of a sequence operator, a \
             delay or a repetition; a property is built by `build_property`)",
            scope,
        ));
    }
    let args = inst.assertion_arguments();
    let body = inst
        .as_sem_node()
        .children()
        .into_iter()
        .find_map(|c| c.as_assertion_expr())
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                "sva automaton builder: a sequence instance has no body AssertionExpr",
                scope,
            )
        })?;

    // A sequence declared in a clocking block with no event of its own is
    // clocked by the block's (16.18).
    let block_event = if body.kind() == AssertionExprKind::Clocking {
        None
    } else {
        enclosing_clocking_event(body, tree, scope)?
    };
    let entered = enter_instance(a, leaves, inst, &args, true, tree, scope)?;
    let built = match block_event {
        Some(event) => build_clocked(a, leaves, event, body, tree, scope),
        None => build_assertion(a, leaves, body, tree, scope),
    };
    let locals = leave_instance(leaves, entered);
    match locals {
        None => built,
        Some(l) => finish_instance_locals(a, leaves, l, built?, scope),
    }
}

/// What [`enter_instance`] pushed, for [`leave_instance`] to take back.
struct EnteredInstance<'d> {
    chain_len: usize,
    pushed: bool,
    caller_flow: VarSet,
    locals: Option<InstanceLocals<'d>>,
}

/// The part of expanding a named sequence or property instance that precedes its
/// body (16.8, 16.8.2, 16.12.19): checks the nesting depth, binds the formals to
/// their actuals on [`LeafTable::env`] and the dependency chain, mints the local
/// variable slots and builds the initialisation of the `local input` formals and
/// declared locals in the CALLER's frame and flow set, then makes the body's
/// flow set current and counts the nesting.
///
/// `check_cycle` rejects an instance of a declaration already on the chain,
/// 16.8's cyclic dependency among sequences; a property instance passes `false`
/// because a recursive property (16.12.17) is legal, and `build_property`
/// resolves it itself.
fn enter_instance<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    inst: Expression<'d>,
    args: &[sv_lang::AssertionInstanceArg<'d>],
    check_cycle: bool,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<EnteredInstance<'d>, LoweringError> {
    if leaves.instance_depth >= MAX_INSTANCE_DEPTH {
        return Err(LoweringError::unsupported_at(
            &format!(
                "named sequence or property instances nest more than {MAX_INSTANCE_DEPTH} deep \
                 (a cyclic dependency among named sequences, LRM 16.8, a recursive property \
                 that does not terminate, or an absurd design)"
            ),
            scope,
        ));
    }
    let frame = match args.first() {
        None => None,
        Some(first) => {
            let seq = first.port.parent().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "sva automaton builder: a formal argument has no parent declaration",
                    scope,
                )
            })?;
            let name = seq.name().to_string();
            let decl = key(tree.syntax(&seq).ok_or_else(|| {
                LoweringError::unsupported_at(
                    &format!(
                        "`{name}` has no syntax node in any source file of the compilation, so \
                         its formals cannot be bound (a declaration slang made up)"
                    ),
                    scope,
                )
            })?);
            if check_cycle && leaves.chain.iter().any(|(_, d)| *d == decl) {
                let walk: Vec<String> = leaves
                    .chain
                    .iter()
                    .map(|(n, _)| n.as_str())
                    .chain(std::iter::once(name.as_str()))
                    .map(|n| format!("`{n}`"))
                    .collect();
                return Err(LoweringError::unsupported_at(
                    &format!(
                        "cyclic dependency among named sequences (LRM 16.8): `{name}` is \
                         instantiated while it is already being expanded ({})",
                        walk.join(" -> ")
                    ),
                    scope,
                ));
            }
            // What an instance written as an actual of THIS instance hangs off:
            // this instance's chain plus this declaration (16.8: an instance of
            // X that instantiates Y within an actual argument is an edge X ->
            // Y). An actual that merely forwards a formal of the caller keeps
            // that formal's own chain.
            let mut here = leaves.chain.clone();
            here.push((name.clone(), decl.clone()));
            // Every actual is folded in the CALLER's environment: the frame
            // being built is not pushed yet.
            let mut bindings = Vec::new();
            let mut origins = Vec::new();
            for g in args {
                let actual = actual_syntax(g.actual, tree);
                bindings.push((
                    g.port.name().to_string(),
                    ranges::bind_actual(actual, formal_cast(&g.port), scope, &leaves.env),
                ));
                let origin = formal_reference_origin(actual, &leaves.env)
                    .map_or_else(|| here.clone(), <[_]>::to_vec);
                origins.push((g.port.name().to_string(), origin));
            }
            Some((
                ranges::FormalFrame {
                    name: name.clone(),
                    decl: decl.clone(),
                    bindings,
                    origins,
                },
                (name, decl),
            ))
        }
    };

    // The locals' slots, the actuals of the `local input`/`inout` formals and the
    // declaration initializers are all built in the CALLER's frame and flow set,
    // before the body's own frame is pushed.
    let caller_flow = leaves.flow_in.clone();
    let locals = begin_instance_locals(a, leaves, inst, args, scope)?;
    if let Some(l) = &locals {
        leaves.flow_in = l.x_body.clone();
    }

    let chain_len = leaves.chain.len();
    let pushed = frame.is_some();
    if let Some((f, link)) = frame {
        leaves.env.push(f);
        leaves.chain.push(link);
    }
    leaves.instance_depth += 1;
    leaves.inferred.push(leaves.clocks[leaves.cur.0 as usize]);
    Ok(EnteredInstance {
        chain_len,
        pushed,
        caller_flow,
        locals,
    })
}

/// Undoes [`enter_instance`] once the body is built, handing back the locals
/// the caller finishes (see [`finish_instance_locals`]).
fn leave_instance<'d>(
    leaves: &mut LeafTable<'d>,
    entered: EnteredInstance<'d>,
) -> Option<InstanceLocals<'d>> {
    leaves.instance_depth -= 1;
    leaves.inferred.pop();
    leaves.chain.truncate(entered.chain_len);
    if entered.pushed {
        leaves.env.pop();
    }
    leaves.flow_in = entered.caller_flow;
    entered.locals
}

/// What a named sequence instance with local variables or `local` formals
/// needs around its body (T13, LRM 16.8.2, 16.10).
struct InstanceLocals<'d> {
    /// The local variable symbols of the instance (the `local` formals' body
    /// copies first, then the declared locals) and the canonical slot minted for
    /// each, parallel.
    syms: Vec<Symbol<'d>>,
    slots: Vec<LocalVarId>,
    /// The canonical slots minted for this expansion: they go out of scope with
    /// it, so they leave the instance's flow sets.
    own: VarSet,
    /// The initialisation assignments in the order the LRM requires (16.8.2:
    /// `local input`/`inout` formals first, then the declared locals in
    /// declaration order): `LocalVarWrite` actions run before the body.
    init: Vec<Transition>,
    /// What flows in to the body: the caller's set, the initialised formals and
    /// the declared locals that have an initializer.
    x_body: VarSet,
    /// `(formal slot, the caller's local it writes back to, the formal's name)`
    /// for every `local output`/`inout` formal, in argument order.
    write_back: Vec<(LocalVarId, LocalVarId, String)>,
    /// `leaves.scope.len()` before the locals were declared.
    scope_len: usize,
}

/// The local variable an actual of an `output`/`inout` formal names, looking
/// through the `Conversion` slang wraps a differently typed actual in (the value
/// is cast back to the actual's type at write-back, 16.8.2).
fn local_actual<'d>(actual: SemNode<'d>) -> Option<Symbol<'d>> {
    let mut e = actual.as_expression()?;
    while e.kind() == ExpressionKind::Conversion {
        e = e
            .as_sem_node()
            .children()
            .into_iter()
            .next()?
            .as_expression()?;
    }
    if e.kind() != ExpressionKind::NamedValue {
        return None;
    }
    e.referenced_symbol()
        .filter(|s| s.kind() == SymbolKind::LocalAssertionVar)
}

/// The caller-side half of a named sequence instance's local variables: mints a
/// canonical slot for every local the body declares (the `local` formals' body
/// copies and the declared variables, in that order, as slang lists them),
/// builds the leaves of the initialisation assignments and records them as the
/// ordered action list in [`InstanceLocals::init`]. `None` for an instance that
/// has no local variable at all.
///
/// LRM 16.8.2: the actual of a `local input`/`inout` formal is evaluated in the
/// caller and CAST to the formal's type to give the formal's initial value; an
/// `output` formal starts unassigned. The declared locals' initializers run
/// after (16.10: "assertion_variable_declarations ... in the order they appear"),
/// and may read the formals and the locals declared before them.
fn begin_instance_locals<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    inst: Expression<'d>,
    args: &[sv_lang::AssertionInstanceArg<'d>],
    scope: &Symbol<'d>,
) -> Result<Option<InstanceLocals<'d>>, LoweringError> {
    let syms = inst.assertion_local_vars();
    let local_formals: Vec<_> = args
        .iter()
        .filter(|g| g.port.assertion_port_is_local_var())
        .collect();
    if syms.is_empty() {
        if let Some(g) = local_formals.first() {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "sva automaton builder: `local` formal `{}` has no local variable in the \
                     sequence body",
                    g.port.name()
                ),
                scope,
            ));
        }
        return Ok(None);
    }
    let scope_len = leaves.scope.len();
    let mut own = VarSet::new();
    let mut slots = Vec::with_capacity(syms.len());
    for sym in &syms {
        let slot = leaves.declare(a, *sym, scope)?;
        own.insert(slot);
        slots.push(slot);
    }
    let slot_of = |name: &str| -> Option<LocalVarId> {
        syms.iter().position(|s| s.name() == name).map(|i| slots[i])
    };

    let mut x = leaves.flow_in.clone();
    let mut init = Vec::new();
    let mut write_back = Vec::new();
    let mut bound = BTreeSet::new();
    for g in local_formals {
        let name = g.port.name().to_string();
        let slot = slot_of(&name).ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!(
                    "sva automaton builder: `local` formal `{name}` has no local variable in the \
                     sequence body"
                ),
                scope,
            )
        })?;
        // `local` formals default to `input` (16.8.2).
        let dir = g
            .port
            .assertion_port_direction()
            .unwrap_or(ArgumentDirection::In);
        match dir {
            ArgumentDirection::Ref => {
                return Err(LoweringError::unsupported_at(
                    &format!(
                        "`local` formal `{name}` is a `ref` argument; a local variable formal \
                         argument is `input`, `inout` or `output` (LRM 16.8.2)"
                    ),
                    scope,
                ));
            }
            ArgumentDirection::In | ArgumentDirection::InOut => {
                // The caller evaluates the actual: its own reads must flow.
                leaves.flow_in = x.clone();
                let actual = g.actual.as_expression().ok_or_else(|| {
                    LoweringError::unsupported_at(
                        &format!("the actual of `local` formal `{name}` is not an expression"),
                        scope,
                    )
                })?;
                let phys = leaves.phys_of(a, slot);
                for (var, value) in leaves.slot_leaves(a, phys, actual, None, scope)? {
                    init.push(Transition::LocalVarWrite { var, value });
                }
                x.insert(slot);
            }
            ArgumentDirection::Out => {}
        }
        if matches!(dir, ArgumentDirection::Out | ArgumentDirection::InOut) {
            let target = local_actual(g.actual).ok_or_else(|| {
                LoweringError::unsupported_at(
                    &format!(
                        "the actual of the `{}` formal `{name}` must be a local variable (LRM \
                         16.8.2)",
                        if dir == ArgumentDirection::Out {
                            "output"
                        } else {
                            "inout"
                        }
                    ),
                    scope,
                )
            })?;
            let actual = leaves.resolve(target, scope)?;
            // 16.8.2: the same local bound to two inout/output formals of one
            // instance is an error (the two copies would race on it). A local
            // bound to outputs of two different instances is legal.
            if !bound.insert(actual) {
                return Err(LoweringError::unsupported_at(
                    &format!(
                        "the local variable `{}` is bound to two or more `inout`/`output` \
                         `local` formal arguments of one instance, the second being `{name}` \
                         (LRM 16.8.2)",
                        target.name()
                    ),
                    scope,
                ));
            }
            write_back.push((slot, actual, name));
        }
    }
    for (sym, &slot) in syms.iter().zip(&slots) {
        if let Some(initializer) = sym.initializer() {
            leaves.flow_in = x.clone();
            let phys = leaves.phys_of(a, slot);
            for (var, value) in leaves.slot_leaves(a, phys, initializer, None, scope)? {
                init.push(Transition::LocalVarWrite { var, value });
            }
            x.insert(slot);
        }
    }
    Ok(Some(InstanceLocals {
        syms,
        slots,
        own,
        init,
        x_body: x,
        write_back,
        scope_len,
    }))
}

/// The other half: wraps the built `body` of an instance whose locals
/// [`begin_instance_locals`] set up. Prefixes the initialisation actions to the
/// entry, suffixes the write-back of every `output`/`inout` formal to the exits,
/// and composes the flow: the instance's own slots leave every set, and the
/// caller's locals the formals write back to count as assigned.
///
/// LRM 16.8.2: it is an error if an `inout`/`output` formal is not assigned on
/// every match (F.5.4: it must flow out of the body), and an error to instantiate
/// such a sequence where it admits an empty match (there is no match end to
/// write back at).
fn finish_instance_locals<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    il: InstanceLocals<'d>,
    body: Fragment,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    leaves.scope.truncate(il.scope_len);
    if !il.write_back.is_empty() {
        if body.empty {
            return Err(LoweringError::unsupported_at(
                "a named sequence with a `local` output or inout formal argument admits an \
                 empty match, which has no end to write the formal back at (LRM 16.8.2)",
                scope,
            ));
        }
        let out = body.flow.flow_out(&il.x_body);
        for (formal, _, name) in &il.write_back {
            if !out.contains(formal) {
                return Err(not_flowing(name, scope));
            }
        }
    }
    let mut flow = body.flow.scoped(&il.own);
    let mut copies = Vec::with_capacity(il.write_back.len());
    for &(formal, actual, _) in &il.write_back {
        let dst = leaves.phys_of(a, actual);
        copies.push(Transition::LocalVarCopy { dst, src: formal });
        flow = flow.concat(&Flow::assign(actual));
    }
    let entry = if body.exits.is_empty() {
        body.entry
    } else {
        prefix_actions(a, il.init, body.entry)
    };
    let exits = suffix_actions(a, body.exits, copies);
    Ok(Fragment {
        entry,
        exits,
        empty: body.empty,
        flow,
        clock: body.clock,
    })
}

/// The cast a TYPED integral formal applies to its actual (16.8.1); `None` for
/// an untyped formal and for the sequence/event/property formal types.
fn formal_cast(port: &Symbol<'_>) -> Option<ranges::FormalCast> {
    let ty = port.declared_type()?;
    if !ty.is_integral() || ty.is_untyped_type() {
        return None;
    }
    Some(ranges::FormalCast {
        width: ty.bit_width(),
        signed: ty.is_signed(),
    })
}

/// The syntax of an actual argument as the caller wrote it. slang wraps an
/// actual converted to a typed formal's type in a `Conversion` that has no
/// syntax of its own; the written expression is its operand.
fn actual_syntax<'t>(actual: SemNode<'_>, tree: Trees<'t>) -> Option<Node<'t>> {
    let e = actual.as_expression()?;
    if let Some(s) = tree.syntax(&e) {
        return Some(s);
    }
    if e.kind() == ExpressionKind::Conversion {
        let inner = e.as_sem_node().children().into_iter().next()?;
        return actual_syntax(inner, tree);
    }
    None
}

/// A `Clocking` node inside a sequence (T28): a named sequence's body is
/// `@(event) body` (the declaration's clocking event, 16.8/16.16), and an operand
/// of a multiclocked sequence is `@(event) s` (16.13.1). The event is interned
/// ([`LeafTable::intern_clock`], by [`events_equivalent`] -- the resolved
/// structure, not the text: the declaration's `@(e)` is the same text for every
/// actual) and is the context clock while the body is built, so the body's
/// unclocked operands are evaluated on it. The result is stamped with the clocks
/// the body spans: the body's own when it changed clock inside, else this one.
fn build_clocking<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let ch = super::op::clocking_children(expr, scope)?;
    build_clocked(a, leaves, ch.event, ch.body, tree, scope)
}

/// `body` built with `event` as the context clock (see [`build_clocking`]).
fn build_clocked<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    event: SemNode<'d>,
    body: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let id = leaves.resolve_clock(event, scope)?;
    let saved = std::mem::replace(&mut leaves.cur, id);
    let built = build_assertion(a, leaves, body, tree, scope);
    leaves.cur = saved;
    let mut frag = built?;
    frag.clock = Some(frag.clock.unwrap_or(Span::single(id)));
    Ok(frag)
}

/// The clocking event of the clocking block a property or sequence is declared
/// in, for the declaration whose body is `body`. LRM 16.18's example makes
/// `a2: assert property (cb_with_input.p1)` equivalent to the clocked `a1`: a
/// property declared in a clocking block (`clocking_item ::= ...
/// assertion_item_declaration`, 14.3) is clocked by that block's event. `None`
/// for a declaration outside any clocking block. An error when the clocking
/// block is not one of the instance `scope` is in (an assertion referring into
/// another instance's clocking block): its symbol is not reachable from here.
pub(super) fn enclosing_clocking_event<'d>(
    body: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Option<SemNode<'d>>, LoweringError> {
    use sv_lang::kinds::SyntaxKind;
    let declaration_of = |mut node: Node<'_>| -> Option<std::ops::Range<usize>> {
        loop {
            if node.kind() == SyntaxKind::ClockingDeclaration {
                return Some(key(node));
            }
            node = node.parent()?;
        }
    };
    let Some(range) = tree.syntax(&body).and_then(declaration_of) else {
        return Ok(None);
    };
    let inst = sv_sim_sim::netlist::enclosing_instance_body(scope).unwrap_or(*scope);
    // Two instances of one checker are flattened into this one instance, and
    // each contributes a clocking block of the same declaration: the one whose
    // lexical parent encloses the assertion is its own.
    let mut chain = Vec::new();
    let mut up = Some(*scope);
    while let Some(s) = up {
        chain.push(s);
        up = s.parent();
    }
    let candidates: Vec<Symbol<'d>> = sv_sim_sim::netlist::module_items(&inst)
        .into_iter()
        .filter(|m| m.kind() == SymbolKind::ClockingBlock)
        .filter(|cb| {
            tree.syntax(cb)
                .and_then(declaration_of)
                .is_some_and(|r| r == range)
        })
        .collect();
    let cb = candidates
        .iter()
        .find(|cb| cb.parent().is_some_and(|p| chain.contains(&p)))
        .or_else(|| candidates.first())
        .copied();
    let Some(cb) = cb else {
        return Err(LoweringError::unsupported_at(
            "a property or sequence declared in a clocking block of another instance than the \
             assertion's is not executable yet (its clocking event is not reachable from the \
             assertion's scope)",
            scope,
        ));
    };
    cb.clocking_block_event().map(Some).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!("the clocking block `{}` has no clocking event", cb.name()),
            scope,
        )
    })
}

/// Whether a clocking event is exactly the `$inferred_clock` call (T31): an
/// event control whose only operand is that call, or the call itself.
pub(super) fn is_inferred_clock_event(event: SemNode<'_>) -> bool {
    if let Some(e) = event.as_expression() {
        return e.call_subroutine_name().as_deref() == Some("$inferred_clock");
    }
    match event.children().as_slice() {
        [only] => is_inferred_clock_event(*only),
        _ => false,
    }
}

/// Whether two clocking events are the same event: the same edge of the same
/// expression, with the same `iff` condition. Exact, and conservative in the
/// loud direction -- anything not provably identical is "different", which
/// surfaces as the multiclock error rather than a silently flattened clock.
///
/// Expression operands are compared by slang's own structural equivalence
/// (`Expression::isEquivalentTo`: operator, literal values, select indices,
/// resolved symbols; an expression kind it cannot compare is unequal). The
/// timing-control layers above them (`@(a, b)` lists, `posedge x iff c`) are
/// compared here: kind, edge, then every child in order. Any other node kind
/// is unequal.
pub(super) fn events_equivalent(a: SemNode<'_>, b: SemNode<'_>) -> bool {
    match (a.as_expression(), b.as_expression()) {
        (Some(x), Some(y)) => return x.is_equivalent_to(&y),
        (None, None) => {}
        _ => return false,
    }
    let (Some(x), Some(y)) = (a.as_timing_control(), b.as_timing_control()) else {
        return false;
    };
    if x.kind() != y.kind() || x.edge() != y.edge() {
        return false;
    }
    let (xs, ys) = (a.children(), b.children());
    xs.len() == ys.len() && xs.iter().zip(&ys).all(|(p, q)| events_equivalent(*p, *q))
}

/// `AssertionExprKind::SequenceConcat` (16.7, Syntax 16-4): a `##`-chain.
/// Semantic children are `[first, elem_0, elem_1, ...]` (confirmed live,
/// [`ranges::sequence_range_of`]'s own doc comment), or, when the chain opens
/// with a delay (`##2 b`, `##[1:3] a ##1 b`), just `[elem_0, elem_1, ...]`
/// with no `first` (also confirmed live: `children().len() ==
/// delays.len()`). Per-element delay bounds come from
/// [`ranges::sequence_range_of`]'s `SequenceConcat` arm (one entry per `##`,
/// in order).
///
/// The chain is folded left to right through [`concat`] (`##` is
/// associative, 16.9.2.1 / Annex F). A leading delay `##[m:n] R` is
/// `1[*m:n] ##1 R` = `empty ##[m+1:n+1] R`, so the fold starts from the empty
/// fragment with the first delay widened by one.
fn build_concat<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let kids = expr.children();
    let delays = ranges::sequence_range_of_in(expr, tree, scope, &leaves.env)?;
    let leading = kids.len() == delays.len();
    if !leading && kids.len() != delays.len() + 1 {
        return Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: SequenceConcat has {} semantic children but {} \
                 recovered delay(s) -- expected children.len() == delays.len() (a leading \
                 delay) or delays.len() + 1",
                kids.len(),
                delays.len()
            ),
            scope,
        ));
    }

    // 16.10: each operand starts with what flows out of the ones before it
    // (`flow(flow(X, R1), R2)`, F.5.4), so a local variable a match item
    // assigned in one operand is readable in the next.
    let x0 = leaves.flow_in.clone();
    let (mut frag, first_operand) = if leading {
        (empty_fragment(a), 0)
    } else {
        (build_node(a, leaves, kids[0], tree, scope)?, 1)
    };
    for (i, delay) in delays.iter().enumerate() {
        if delay.max.is_some_and(|max| delay.min > max) {
            return Err(LoweringError::unsupported_at(
                &format!(
                    "sva automaton builder: `##` delay range has min ({}) > max ({})",
                    delay.min,
                    delay.max.unwrap_or_default()
                ),
                scope,
            ));
        }
        let mut d = *delay;
        if leading && i == 0 {
            // `##[m:n] R` = `empty ##[m+1:n+1] R`.
            let widen = |v: u32| {
                v.checked_add(1).ok_or_else(|| {
                    LoweringError::unsupported_at(
                        "sva automaton builder: leading `##` delay bound overflows u32",
                        scope,
                    )
                })
            };
            d = SequenceRangeValue {
                min: widen(d.min)?,
                max: d.max.map(widen).transpose()?,
            };
        }
        leaves.flow_in = frag.flow.flow_out(&x0);
        let next = build_node(a, leaves, kids[i + first_operand], tree, scope)?;
        frag = concat_clocked(a, leaves, frag, d, next, scope)?;
    }
    leaves.flow_in = x0;
    Ok(frag)
}

/// `left ##d right` where the operands may be clocked differently (16.13.1, T28).
///
/// When the clock the left operand ends in is the one the right begins in, this is
/// the plain [`concat`]: the delay counts ticks of that clock. Otherwise the
/// operands are two maximal singly clocked subsequences and the delay must be
/// exactly `##1` or `##0` (16.13.1: "`##1` ... the nearest strictly subsequent
/// tick of the clock of the second operand; `##0` ... the nearest possibly
/// overlapping tick"); a range or a longer delay between them is an error, as is
/// an operand that admits an empty match (16.13.1: a maximal singly clocked
/// subsequence "shall admit only nonempty matches"). The join is one
/// [`Transition::ClockSync`] edge from every exit of the left operand.
///
/// The result's [`Span`] runs from where the left begins to where the right ends,
/// and is `multi` when either operand or this join changes clock; `None` (the
/// context clock throughout) when neither operand names a clock.
fn concat_clocked<'d>(
    a: &mut ir::Automaton,
    leaves: &LeafTable<'d>,
    l: Fragment,
    d: SequenceRangeValue,
    r: Fragment,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let ls = l.clock.unwrap_or(Span::single(leaves.cur));
    let rs = r.clock.unwrap_or(Span::single(leaves.cur));
    let stamped = if l.clock.is_none() && r.clock.is_none() {
        None
    } else {
        Some(Span {
            start: ls.start,
            end: rs.end,
            multi: ls.multi || rs.multi || ls.end != rs.start,
        })
    };
    if ls.end == rs.start {
        let mut f = concat(a, l, d, r);
        f.clock = stamped;
        return Ok(f);
    }
    let strict = match (d.min, d.max) {
        (0, Some(0)) => false,
        (1, Some(1)) => true,
        _ => {
            return Err(LoweringError::unsupported_at(
                "a `##` delay between differently clocked operands of a multiclocked sequence \
                 must be exactly `##1` or `##0` (LRM 16.13.1: the first synchronises to the \
                 nearest strictly subsequent tick of the second operand's clock, the second to \
                 the nearest possibly overlapping one); a range or a longer delay has no \
                 meaning across a clock change",
                scope,
            ));
        }
    };
    if l.empty || r.empty {
        return Err(LoweringError::unsupported_at(
            "a maximal singly clocked subsequence of a multiclocked sequence admits an empty \
             match (LRM 16.13.1: it shall admit only nonempty matches), e.g. a leading `##n` \
             delay or a `[*0]`/`[*0:n]` repetition next to a clock change",
            scope,
        ));
    }
    let flow = l.flow.concat(&r.flow);
    for &e in &l.exits {
        a.add_edge(
            e,
            None,
            Transition::ClockSync {
                to: rs.start,
                strict,
            },
            r.entry,
        );
    }
    Ok(Fragment {
        entry: l.entry,
        exits: r.exits,
        empty: false,
        flow,
        clock: stamped,
    })
}

/// The one clock of the operands of a sequence operator other than `##` (16.13.1:
/// `and`/`or`/`intersect`/`throughout`/`within`, `first_match` and repetition
/// apply to singly clocked sequences only, on the same clock): the span they all
/// share, resolved against the context clock, as stamped on the result. `None`
/// when no operand names a clock.
fn join_clocks<'d>(
    leaves: &LeafTable<'d>,
    operands: &[&Fragment],
    what: &str,
    scope: &Symbol<'d>,
) -> Result<Option<Span>, LoweringError> {
    if operands.iter().all(|f| f.clock.is_none()) {
        return Ok(None);
    }
    let resolved: Vec<Span> = operands
        .iter()
        .map(|f| f.clock.unwrap_or(Span::single(leaves.cur)))
        .collect();
    let first = resolved[0];
    if resolved.iter().any(|s| s.multi || s.start != first.start) {
        return Err(LoweringError::unsupported_at(
            &format!(
                "the operands of `{what}` are clocked differently or are multiclocked \
                 sequences (LRM 16.13.1: a multiclocked sequence is built only with `##1`/`##0` \
                 between singly clocked subsequences; `{what}` needs its operands on one clock)"
            ),
            scope,
        ));
    }
    Ok(Some(first))
}

/// The one clock of the single operand of `first_match` or a repetition (16.13.1);
/// a multiclocked operand is an error.
fn single_clock(f: &Fragment, what: &str) -> Result<Option<Span>, String> {
    if f.clock.is_some_and(|s| s.multi) {
        return Err(format!(
            "{what} is applied to a multiclocked sequence (LRM 16.13.1: only a singly clocked \
             sequence can be repeated or have its first match selected; the match set of a \
             clock change inside a repeated operand is not defined by Annex F)"
        ));
    }
    Ok(f.clock)
}

/// `left ##d right` over fragments, with 16.9.2.1's empty-match rules (see
/// the module doc comment). `d.min <= d.max` is the caller's invariant.
///
/// Each operand is `ne ∪ ε` (its nonempty matches, plus the empty match when
/// `empty`), so the result is the union of up to four pairings, each wired
/// by its own rule. `k` below is the concrete delay count drawn from `d`:
///
/// - **A** `ne ##k ne'`, `k` in `d` (including `k == 0`, a fusion): every
///   left exit gets a `Delay{d}` edge to the right entry.
/// - **B** `ε ##k ne'`, `k >= 1` (rule 3, and rule 1 for `k == 0`: absent):
///   the right operand starts `k-1` ticks after the start, a `Delay` edge
///   from the (new) start state.
/// - **C** `ne ##k ε`, `k >= 1` (rule 4; rule 2 for `k == 0`: absent): the
///   match ends `k-1` ticks after the left operand did, at a fresh state
///   reached by a `Delay` edge from every left exit.
/// - **D** `ε ##k ε`, `k >= 2` (`k == 1` is the empty match, `k == 0` is
///   absent): `k-1` vacuous ticks from the start, ending at the same fresh
///   state as C.
///
/// The result admits the empty match iff both operands do and `1` is in `d`.
/// When the left operand admits the empty match, a fresh start state holds
/// the epsilon edge into the left operand's own paths (A/C) next to B/D's
/// edges -- both operands' empty matches begin on the same tick.
fn concat(a: &mut ir::Automaton, l: Fragment, d: SequenceRangeValue, r: Fragment) -> Fragment {
    // The F.5.4 triple composes the same way whatever shape the states take
    // (`concat_shape` may hand an operand back unchanged, flow included).
    let flow = l.flow.concat(&r.flow);
    let mut f = concat_shape(a, l, d, r);
    f.flow = flow;
    f
}

/// The states of [`concat`]; its result's `flow` is the caller's to set.
fn concat_shape(
    a: &mut ir::Automaton,
    l: Fragment,
    d: SequenceRangeValue,
    r: Fragment,
) -> Fragment {
    // `empty ##1 R` = R and `L ##1 empty` = L (rules 3 and 4 at n = 1,
    // exactly). Besides being the identity these keep the common
    // `a[*0:3] ##1 b` automaton free of vacuous bridge states.
    if d.min == 1 && d.max == Some(1) {
        if l.empty && l.exits.is_empty() {
            return r;
        }
        if r.empty && r.exits.is_empty() {
            return l;
        }
    }

    let ne_l = !l.exits.is_empty();
    let ne_r = !r.exits.is_empty();
    // The delay counts `k >= 1` / `k >= 2` that `d` admits.
    let k1_min = d.min.max(1);
    let k1_ok = d.max.is_none_or(|m| m >= k1_min);
    let k2_min = d.min.max(2);
    let k2_ok = d.max.is_none_or(|m| m >= k2_min);

    let path_a = ne_l && ne_r;
    let path_b = l.empty && ne_r && k1_ok;
    let path_c = ne_l && r.empty && k1_ok;
    let path_d = l.empty && r.empty && k2_ok;

    let start = if l.empty {
        let s = a.new_state();
        if path_a || path_c {
            a.add_edge(s, None, Transition::Epsilon, l.entry);
        }
        Some(s)
    } else {
        None
    };
    let entry = start.unwrap_or(l.entry);

    if path_a {
        for &e in &l.exits {
            a.add_edge(
                e,
                None,
                Transition::Delay {
                    min: d.min,
                    max: d.max,
                },
                r.entry,
            );
        }
    }
    if path_b {
        let s = start.expect("path_b implies l.empty");
        a.add_edge(
            s,
            None,
            Transition::Delay {
                min: k1_min - 1,
                max: d.max.map(|m| m - 1),
            },
            r.entry,
        );
    }
    let tail = (path_c || path_d).then(|| a.new_state());
    if let Some(t) = tail {
        if path_c {
            for &e in &l.exits {
                a.add_edge(
                    e,
                    None,
                    Transition::Delay {
                        min: k1_min - 1,
                        max: d.max.map(|m| m - 1),
                    },
                    t,
                );
            }
        }
        if path_d {
            let s = start.expect("path_d implies l.empty");
            a.add_edge(
                s,
                None,
                Transition::Delay {
                    min: k2_min - 2,
                    max: d.max.map(|m| m - 2),
                },
                t,
            );
        }
    }

    let mut exits = Vec::new();
    if path_a || path_b {
        exits.extend(r.exits.iter().copied());
    }
    exits.extend(tail);
    Fragment {
        entry,
        exits,
        empty: l.empty && r.empty && d.min <= 1 && d.max.is_none_or(|m| m >= 1),
        flow: Flow::identity(),
        clock: None,
    }
}

/// `AssertionExprKind::SequenceWithMatch` -- slang's one wrapper kind for
/// `( sequence_expr { match_item } ) [ sequence_abbrev ]` (16.7's own
/// grammar for a parenthesized sequence expression), covering THREE
/// distinct source shapes that all bind to this same semantic kind
/// (confirmed live, this task's own investigation): a bare repetition
/// wrapper around a compound sub-sequence with no match items at all
/// (`(a##2b)[*3]`), a match-item-bearing sequence with no repetition
/// (`(a##1b, cnt++)`), or both together. The repetition (if any) and the
/// match-item list (if any) are both purely syntactic here too -- recovered
/// from `tree.syntax(&expr)` cast to [`ParenthesizedSequenceExprSyntax`] (after
/// peeling plain outer parens: `((a##1b)[*2])`), never a semantic child; the
/// semantic children are exactly `[sub_sequence, match_item_expr, ...]`
/// (confirmed live), so the sub-sequence is the one child that casts to
/// `AssertionExpr`.
///
/// Sequence match items (16.10/16.11) are built by [`build_match_items`], once
/// per repeated copy when the unit is repeated (`(a[->1], x += d)[*4]`).
/// `[->]`/`[=]` (goto/nonconsecutive) repetition applied to a sequence that
/// ALSO carries a match item is flatly illegal per 16.9.2/16.10's own worked
/// example (`(b, v=e)[->2]`) -- that specific combination is rejected with
/// its own, specific error.
fn build_sequence_with_match<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let syn = tree.syntax(&expr).ok_or_else(|| {
        LoweringError::unsupported_at(
            "sva automaton builder: SequenceWithMatch node has no syntax node in the given tree",
            scope,
        )
    })?;
    let syn = ranges::peel_sequence_parens(syn);
    let paren = ParenthesizedSequenceExprSyntax::cast(syn).ok_or_else(|| {
        LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: expected ParenthesizedSequenceExprSyntax for a \
                 SequenceWithMatch node, found {:?}",
                syn.kind()
            ),
            scope,
        )
    })?;

    let kids = expr.children();
    let sub_kids: Vec<SemNode<'d>> = kids
        .iter()
        .copied()
        .filter(|c| c.as_assertion_expr().is_some())
        .collect();
    let [sub_node] = sub_kids.as_slice() else {
        return Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: SequenceWithMatch must have exactly one sub-sequence \
                 child, found {}",
                sub_kids.len()
            ),
            scope,
        ));
    };
    let sub = sub_node
        .as_assertion_expr()
        .expect("filtered above to only AssertionExpr-castable nodes");
    let has_match_items = paren.match_list().is_some();
    let items: Vec<SemNode<'d>> = kids
        .iter()
        .copied()
        .filter(|c| c.as_assertion_expr().is_none())
        .collect();

    match paren.repetition() {
        None => {
            if has_match_items {
                return build_match_items(a, leaves, sub, &items, tree, scope);
            }
            build_assertion(a, leaves, sub, tree, scope)
        }
        Some(rep) => {
            let op_text = rep.op().map(|t| t.text());
            if has_match_items && matches!(op_text, Some("->") | Some("=")) {
                return Err(LoweringError::unsupported_at(
                    "goto/nonconsecutive repetition (`[->n:m]`/`[=n:m]`) applied to a sequence \
                     that also carries a match item is illegal (LRM 16.9.2/16.10's own worked \
                     example, `(b, v=e)[->2]`)",
                    scope,
                ));
            }
            // `(seq, items)[*n]` repeats the whole unit, items included
            // (16.10 `rep_v`): every copy is built under the flow set the
            // copies before it leave, which `build_repeated` arranges.
            build_repetition(
                a,
                leaves,
                rep,
                scope,
                &mut |a, leaves| {
                    if has_match_items {
                        build_match_items(a, leaves, sub, &items, tree, scope)
                    } else {
                        build_assertion(a, leaves, sub, tree, scope)
                    }
                },
                // The gap of `(b)[->n]`: 16.9.2 allows the goto forms on a
                // Boolean expression only, so anything else is the error.
                &mut |a, leaves| {
                    // A `Simple` whose own syntax carries a repetition
                    // (`(b[*2])[->2]`) is a sequence, not a Boolean.
                    let plain = tree.syntax(&sub).is_some_and(|syn| {
                        SimpleSequenceExprSyntax::cast(ranges::peel_sequence_parens(syn))
                            .is_some_and(|s| s.repetition().is_none())
                    });
                    let boolean = (sub.kind() == AssertionExprKind::Simple && plain)
                        .then(|| sub.children())
                        .and_then(|kids| match kids.as_slice() {
                            [only] => only.as_expression(),
                            _ => None,
                        });
                    match boolean {
                        Some(e) => build_gap_operand(a, leaves, e, tree, scope),
                        None => Err(LoweringError::unsupported_at(
                            "goto/nonconsecutive repetition (`[->n:m]`/`[=n:m]`) can only be \
                             applied to a Boolean expression, not a compound sequence (LRM \
                             16.9.2)",
                            scope,
                        )),
                    }
                },
            )
        }
    }
}

/// `( sequence_expr { , sequence_match_item } )` (T13/T14, LRM 16.10, 16.11):
/// the match items, run in LIST ORDER on the thread that completes a NONEMPTY
/// match of the sub-sequence (so an empty-admitting sub-sequence is the 16.11
/// error, see [`attach_match_items`]). The items are wired as one shared chain
/// of same-tick edges after every exit of the sub-sequence, the last one's state
/// being the new single exit. A repeated unit (`(seq, items)[*n]`) is built by
/// calling this once per copy.
///
/// Three item shapes:
///
/// - `v = e` and the compound operators (`v += e`, ...): a
///   [`Transition::LocalVarWrite`]. slang gives a compound assignment no syntax
///   of its own: its right-hand side is the operator applied to an
///   `LValueReference` (the target's current value) and `e`, which
///   [`LeafTable::push_leaf`] reads as a read of the target, so `v += e` on a
///   variable that has not flowed in is the "does not flow out" error.
/// - `v++`, `++v`, `v--`, `--v`: a [`Transition::LocalVarStep`]. The variable
///   is read, so the same flow check applies.
/// - a task or void function call: a [`Transition::SubroutineCall`], see
///   [`super::actions`].
///
/// Item `i` is checked against `flow(X, sub)` plus the items before it: an item
/// may read what an earlier item (or the sub-sequence) assigned. The result's
/// flow is `flow(sub) ##0 (1, v1 = e1) ##0 ...` (F.5.4's `(R, v = e)` rule).
fn build_match_items<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    sub: AssertionExpr<'d>,
    items: &[SemNode<'d>],
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let x0 = leaves.flow_in.clone();
    let frag = build_assertion(a, leaves, sub, tree, scope)?;
    attach_match_items(a, leaves, frag, items, &x0, scope)
}

/// How a match item is lowered (16.11): the three item shapes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MatchItemKind {
    /// `v = e` and the compound operators.
    Assignment,
    /// `v++`, `++v`, `v--`, `--v`: the step added to the variable.
    Step(i64),
    /// A task or void function call.
    Call,
}

/// Classifies one match item expression. Decided by `if`s over the three
/// shapes 16.11 allows, so any other kind is the loud error below, never
/// silently skipped.
fn classify_match_item(
    e: Expression<'_>,
    scope: &Symbol<'_>,
) -> Result<MatchItemKind, LoweringError> {
    let ek = e.kind();
    if ek == ExpressionKind::Assignment {
        return Ok(MatchItemKind::Assignment);
    }
    if ek == ExpressionKind::UnaryOp
        && let Some(op) = e.unary_op()
    {
        if matches!(op, UnaryOp::Preincrement | UnaryOp::Postincrement) {
            return Ok(MatchItemKind::Step(1));
        }
        if matches!(op, UnaryOp::Predecrement | UnaryOp::Postdecrement) {
            return Ok(MatchItemKind::Step(-1));
        }
    }
    if actions::is_call(e) {
        return Ok(MatchItemKind::Call);
    }
    Err(LoweringError::unsupported_at(
        &format!(
            "a sequence match item of kind {ek:?} is not a local-variable assignment, an \
             increment/decrement or a subroutine call (LRM 16.11)"
        ),
        scope,
    ))
}

/// The local variable a match item assigns or steps, as its canonical slot: the
/// item's target must be a WHOLE local variable (16.11).
fn match_item_target<'d>(
    leaves: &LeafTable<'d>,
    target: Expression<'d>,
    what: &str,
    scope: &Symbol<'d>,
) -> Result<(Symbol<'d>, LocalVarId), LoweringError> {
    let sym = target
        .referenced_symbol()
        .filter(|s| {
            target.kind() == ExpressionKind::NamedValue && s.kind() == SymbolKind::LocalAssertionVar
        })
        .ok_or_else(|| {
            LoweringError::unsupported_at(
                &format!(
                    "a sequence match item must {what} a whole local variable (LRM 16.11); an \
                     operation on anything else is not a match item"
                ),
                scope,
            )
        })?;
    Ok((sym, leaves.resolve(sym, scope)?))
}

/// Attaches the match `items` of `(sub, items)` to the already built fragment
/// `frag` of `sub`. `x0` is the flow set `sub` started under. Used by
/// [`build_match_items`] and by `first_match(R, items)` (16.9.8: that is
/// `first_match((R, items))`, so the items run on the single survivor).
///
/// The nondegeneracy rule (16.11, T14): "a subsequence with an attached match
/// item shall not admit an empty match", because a match item runs at a tick
/// the match ends on, which an empty match has none of. It is checked here,
/// on the fragment the unit actually built, so it holds for every item kind
/// and every way the subsequence got to admit the empty word (`b[*0:1]`,
/// `first_match` of one, a repetition of one).
fn attach_match_items<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    frag: Fragment,
    items: &[SemNode<'d>],
    x0: &VarSet,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    if frag.empty {
        return Err(LoweringError::unsupported_at(
            "a sequence match item is attached to a sequence that admits an empty match \
             (LRM 16.11: it shall be an error to attach a match item to such a sequence)",
            scope,
        ));
    }
    let mut flow = frag.flow.clone();
    let mut actions = Vec::with_capacity(items.len());
    for item in items {
        let item_expr = item.as_expression().ok_or_else(|| {
            LoweringError::unsupported_at(
                "sva automaton builder: a sequence match item is not an Expression",
                scope,
            )
        })?;
        match classify_match_item(item_expr, scope)? {
            MatchItemKind::Call => {
                // A built-in method of a collection that is itself a sequence local
                // (`q.push_back(x)`, `q.delete()`): the call runs in the Reactive region on a
                // copy of the local, because "if a local variable appears in an actual
                // argument expression, that argument shall be passed by value" and the call
                // "does not wait on or receive data back" (16.11). Nothing it does can reach
                // the attempt's local variable, so the call has no effect to schedule.
                if is_local_collection_method(item_expr) {
                    continue;
                }
                // The by-value arguments are read where the call fires, after
                // the items before it.
                leaves.flow_in = flow.flow_out(x0);
                actions.push(actions::lower_call(a, leaves, item_expr, scope)?);
                continue;
            }
            MatchItemKind::Step(delta) => {
                let kids = item_expr.as_sem_node().children();
                let [operand] = kids.as_slice() else {
                    return Err(LoweringError::unsupported_at(
                        "sva automaton builder: an increment/decrement match item must have \
                         exactly one operand",
                        scope,
                    ));
                };
                let operand = operand.as_expression().ok_or_else(|| {
                    LoweringError::unsupported_at(
                        "sva automaton builder: an increment/decrement operand is not an \
                         Expression",
                        scope,
                    )
                })?;
                let (sym, canon) =
                    match_item_target(leaves, operand, "increment or decrement", scope)?;
                // `x++` reads the variable: it must have been assigned (16.10).
                leaves.flow_in = flow.flow_out(x0);
                leaves.check_flows(sym, canon, scope)?;
                let phys = leaves.phys_of(a, canon);
                actions.push(Transition::LocalVarStep { var: phys, delta });
                flow = flow.concat(&Flow::assign(canon));
                continue;
            }
            MatchItemKind::Assignment => {}
        }
        let kids = item_expr.as_sem_node().children();
        let [lhs, rhs] = kids.as_slice() else {
            return Err(LoweringError::unsupported_at(
                "sva automaton builder: an assignment match item must have a target and a value",
                scope,
            ));
        };
        let (lhs, rhs) = (
            lhs.as_expression().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "sva automaton builder: a match item's target is not an Expression",
                    scope,
                )
            })?,
            rhs.as_expression().ok_or_else(|| {
                LoweringError::unsupported_at(
                    "sva automaton builder: a match item's value is not an Expression",
                    scope,
                )
            })?,
        );
        let (_, canon) = match_item_target(leaves, lhs, "assign", scope)?;
        leaves.flow_in = flow.flow_out(x0);
        let phys = leaves.phys_of(a, canon);
        actions.extend(leaves.assign_var(a, canon, phys, rhs, scope)?);
        flow = flow.concat(&Flow::assign(canon));
    }
    leaves.flow_in = x0.clone();
    let exits = suffix_actions(a, frag.exits, actions);
    Ok(Fragment {
        entry: frag.entry,
        exits,
        empty: false,
        flow,
        clock: frag.clock,
    })
}

/// Dispatches a recovered `[...]` repetition to the right shape (16.9.2):
/// `*`/`+` (consecutive) link `make_unit` copies with exactly `##1`; `->` and
/// `=` are the goto and nonconsecutive forms of 16.9.2, built exactly by
/// [`build_goto`] from `make_unit` (the Boolean's own sample) and `make_gap` (the
/// sample of its negation).
fn build_repetition<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    rep: SequenceRepetitionSyntax<'_>,
    scope: &Symbol<'d>,
    make_unit: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
    make_gap: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    let op_text = rep.op().map(|t| t.text()).ok_or_else(|| {
        LoweringError::unsupported_at(
            "sva automaton builder: `[...]` repetition has no operator token",
            scope,
        )
    })?;
    let range = ranges::repetition_range_in(rep, scope, &leaves.env)?;
    match op_text {
        "*" | "+" => build_repeated(
            a,
            leaves,
            range.min,
            range.max,
            SequenceRangeValue {
                min: 1,
                max: Some(1),
            },
            make_unit,
        ),
        "->" | "=" => build_goto(
            a,
            leaves,
            op_text == "=",
            (range.min, range.max),
            make_unit,
            make_gap,
        ),
        other => Err(LoweringError::unsupported_at(
            &format!("sva automaton builder: unknown sequence repetition operator {other:?}"),
            scope,
        )),
    }
}

/// Goto `b[->n:m]` and nonconsecutive `b[=n:m]` repetition (16.9.2), lowered by
/// their own definitions in terms of consecutive repetition and `##1`:
///
/// - `b[->n:m]` is `(!b[*0:$] ##1 b)[*n:m]`: each repeat waits through any
///   number of ticks where `b` is false (`make_gap`, a [`LeafTable::is_negated`]
///   sample) and ends on the tick `b` is true, so the match ends AT the last
///   true `b`.
/// - `b[=n:m]` is `b[->n:m] ##1 !b[*0:$]`: the same, then any number of further
///   ticks where `b` stays false, so the match may end anywhere after the last
///   true `b` up to (not including) the next one.
///
/// Both go through [`build_repeated`] and [`concat`], so counts of zero, the
/// range and `$` upper bound, the empty match of `[=0]`/`[->0]` and the flow of
/// local variables are decided by the same algebra as every other repetition.
fn build_goto<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    nonconsecutive: bool,
    (min, max): (u32, Option<u32>),
    make_unit: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
    make_gap: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    let one = SequenceRangeValue {
        min: 1,
        max: Some(1),
    };
    let body = {
        // One repeat: `!b[*0:$] ##1 b`.
        let mut repeat = |a: &mut ir::Automaton,
                          leaves: &mut LeafTable<'d>|
         -> Result<Fragment, LoweringError> {
            let gap = build_repeated(a, leaves, 0, None, one, make_gap)?;
            let hit = make_unit(a, leaves)?;
            Ok(concat(a, gap, one, hit))
        };
        build_repeated(a, leaves, min, max, one, &mut repeat)?
    };
    if !nonconsecutive {
        return Ok(body);
    }
    let tail = build_repeated(a, leaves, 0, None, one, make_gap)?;
    Ok(concat(a, body, one, tail))
}

/// Builds `min..=max` (or `min..` when `max` is `None`) repeats of one unit
/// fragment, chained by `link` between consecutive repeats (16.9.2's
/// implicit `##1`, or a wider search window -- see [`build_repetition`]).
///
/// A unit that itself admits the empty match (`(a[*0:1])[*2]`) is handled by
/// the 16.9.2.1 algebra, not special-cased per shape: `u[*k]` is a `##1`-fold
/// of `k` copies of `ne ∪ ε`, and `x ##1 ε = ε ##1 x = x`, so every repeat
/// may vanish and `u[*min:max]` is `ne(u)[*0:max]` (for `max == $`, the same
/// with an open upper bound). The repeats below are therefore built from the
/// unit's NONEMPTY part and `min` drops to 0; the result admits the empty
/// match exactly when that adjusted `min` is 0.
fn build_repeated<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    min: u32,
    max: Option<u32>,
    link: SequenceRangeValue,
    make_unit: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    if max.is_some_and(|m| min > m) {
        return Err(LoweringError::unsupported(
            &format!(
                "sequence repetition range min ({min}) > max ({})",
                max.unwrap_or_default()
            ),
            "sva::build::build_repeated",
        ));
    }
    if max == Some(0) {
        // `[*0:0]`/`[*0]` -- the degenerate "always empty" repetition. (No
        // unit is built at all: nothing of it is ever sampled.)
        return Ok(empty_fragment(a));
    }

    // The first copy decides whether the unit admits the empty match. Every
    // copy is built under the flow set the copies before it leave (16.10, F.5.4:
    // `u[*n]` is `u ##1 u ...`), `x0` for the first.
    let x0 = leaves.flow_in.clone();
    let first = make_unit(a, leaves)?;
    let min = if first.empty { 0 } else { min };
    // The repeats are all on the unit's clock (a multiclocked unit is an error).
    let clock = single_clock(&first, "a sequence repetition")
        .map_err(|msg| LoweringError::unsupported(&msg, "sva::build::build_repeated"))?;
    if first.exits.is_empty() {
        // The unit has no nonempty match at all (it is `empty`-only, or never
        // matches): `u[*k]` is the empty match for every `k` when `u` admits
        // it, and only `u[*0]` otherwise -- no path either way. The empty
        // match assigns nothing, whatever the unit would have.
        return Ok(Fragment {
            entry: first.entry,
            exits: Vec::new(),
            empty: min == 0,
            flow: Flow::identity(),
            clock,
        });
    }
    let built = match max {
        Some(max) => build_repeated_finite(a, leaves, &x0, first, (min, max), link, make_unit),
        None => build_repeated_unbounded(a, leaves, &x0, first, min, link, make_unit),
    };
    leaves.flow_in = x0;
    built.map(|f| Fragment { clock, ..f })
}

/// Chains an unconditional `link`-delay edge from every state in `from` to
/// `target`.
fn link_all(
    a: &mut ir::Automaton,
    from: &[ThreadStateId],
    link: SequenceRangeValue,
    target: ThreadStateId,
) {
    for &e in from {
        a.add_edge(
            e,
            None,
            Transition::Delay {
                min: link.min,
                max: link.max,
            },
            target,
        );
    }
}

/// `min..=max` repeats (16.9.2's bounded forms, `[*n:m]`/`[=n:m]`/
/// `[->n:m]`/`[*n]`) of a unit with at least one nonempty match (`first` is
/// the unit's first copy, already built by [`build_repeated`]): `max` copies,
/// chained by `link`; the thread may stop after any count `k` in
/// `min..=max` (16.9.2: "the match may stop at any count within the range"),
/// so the fragment's `exits` are the UNION of every copy `k`'s own exits for
/// `k` in that range. The zero-repeat empty match (`min == 0`) is the
/// fragment's `empty` flag, not an exit.
fn build_repeated_finite<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    x0: &VarSet,
    first: Fragment,
    (min, max): (u32, u32),
    link: SequenceRangeValue,
    make_unit: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    let entry = first.entry;
    let mut prev_exits = first.exits.clone();
    let mut copy_exits: Vec<Vec<ThreadStateId>> = Vec::with_capacity(max as usize);
    copy_exits.push(first.exits);
    // `acc[k - 1]` is the flow of the first `k` copies chained.
    let mut acc: Vec<Flow> = Vec::with_capacity(max as usize);
    acc.push(first.flow);
    for k in 1..max as usize {
        leaves.flow_in = acc[k - 1].flow_out(x0);
        let unit = make_unit(a, leaves)?;
        link_all(a, &prev_exits, link, unit.entry);
        prev_exits = unit.exits.clone();
        copy_exits.push(unit.exits);
        let chained = acc[k - 1].concat(&unit.flow);
        acc.push(chained);
    }

    let mut exits = Vec::new();
    // The match may stop after any count in the range, so only what EVERY
    // count assigns flows out (`or`); a zero count assigns nothing.
    let mut flow: Option<Flow> = (min == 0).then(Flow::identity);
    for k in min.max(1)..=max {
        exits.extend(copy_exits[(k - 1) as usize].iter().copied());
        let f = &acc[(k - 1) as usize];
        flow = Some(match flow {
            None => f.clone(),
            Some(so_far) => so_far.or(f),
        });
    }
    Ok(Fragment {
        entry,
        exits,
        empty: min == 0,
        flow: flow.unwrap_or_default(),
        clock: None,
    })
}

/// `min..` repeats with no upper bound (16.9.2's `$` forms, `[*]`/`[+]`/
/// `[*n:$]`/...) of a unit with at least one nonempty match: `max(min, 1)`
/// mandatory copies chained by `link`, then one more unit (`loop_unit`) wired
/// as a genuine cycle -- its own entry is reachable from the mandatory
/// chain's tail AND from its own exits (so the thread may take the loop any
/// number of times, including zero), modeling the unbounded upper bound
/// without ever building infinitely many states. `min == 0` only sets the
/// `empty` flag (the empty match); it adds no exit.
fn build_repeated_unbounded<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    x0: &VarSet,
    first: Fragment,
    min: u32,
    link: SequenceRangeValue,
    make_unit: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    let mandatory = min.max(1);
    let entry = first.entry;
    let mut tail_exits = first.exits;
    let mut acc = first.flow;
    for _ in 1..mandatory {
        leaves.flow_in = acc.flow_out(x0);
        let unit = make_unit(a, leaves)?;
        link_all(a, &tail_exits, link, unit.entry);
        tail_exits = unit.exits;
        acc = acc.concat(&unit.flow);
    }

    // Every iteration of the loop starts with at least what the mandatory
    // copies leave: the sets only grow along the chain (`flow0` of a longer
    // chain contains the shorter one's, and its `block` is no larger than the
    // unit's own on top of the shorter one's), so this is a sound entry set for
    // each of the unboundedly many iterations.
    leaves.flow_in = acc.flow_out(x0);
    let loop_unit = make_unit(a, leaves)?;
    link_all(a, &tail_exits, link, loop_unit.entry);
    link_all(a, &loop_unit.exits, link, loop_unit.entry);

    let mut exits = tail_exits;
    exits.extend(loop_unit.exits);
    // The loop may run zero times, so it samples and blocks what the unit does
    // but guarantees no assignment.
    let looped = Flow {
        sample: loop_unit.flow.sample,
        block: loop_unit.flow.block,
        flow0: VarSet::new(),
    };
    let mut flow = acc.concat(&looped);
    if min == 0 {
        flow = flow.or_empty();
    }
    Ok(Fragment {
        entry,
        exits,
        empty: min == 0,
        flow,
        clock: None,
    })
}

// ---------------------------------------------------------------------------
// T11: `and` / `intersect` / `or` / `first_match` / `throughout` / `within`
// (LRM 16.9.5-16.9.10).
// ---------------------------------------------------------------------------

/// The most states one `and`/`intersect` product may allocate before the
/// builder gives up with a named error (a product is the one construction here
/// whose size is a function of the operands' DELAY BOUNDS, e.g. `a ##100000 b
/// intersect c ##100000 d` walks 100000 lockstep ticks; an unbounded budget
/// would turn a typo into an out-of-memory).
const MAX_PRODUCT_STATES: usize = 20_000;

/// The two operators built as a lockstep product of their operands.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ProductKind {
    /// 16.9.6: both operands match over the same interval.
    Intersect,
    /// 16.9.5: both operands match from the same start; the composite ends
    /// where the later one ends.
    And,
}

impl ProductKind {
    fn name(self) -> &'static str {
        match self {
            ProductKind::Intersect => "intersect",
            ProductKind::And => "and",
        }
    }
}

/// One operand's position inside a product state. An operand is a [`Fragment`]
/// of the shared automaton, which is stepped in lockstep with the other; its
/// `Delay` edges cannot be stepped one tick at a time in place (a `Delay`
/// carries a whole window), so a delay in flight is a `Wait` that counts the
/// window down while the other side keeps moving.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Comp {
    /// At this state of the operand, on the current tick.
    Real(ThreadStateId),
    /// A `Delay{min,max}` edge to `target` taken `k` ticks ago short of its
    /// window: it still needs between `lo` and `hi` (`None` = unbounded) more
    /// ticks. `Wait{lo: 0, hi: Some(0)}` is always normalized to `Real` (see
    /// [`Comp::wait`]), so a `Wait` always has at least one tick left to
    /// consume or an eps (`lo == 0`) to resolve.
    Wait {
        target: ThreadStateId,
        lo: u32,
        hi: Option<u32>,
    },
    /// `and` only: this operand has already matched (it ended on an earlier
    /// tick, or is the empty match) and idles while the other one finishes.
    Done,
}

impl Comp {
    fn wait(target: ThreadStateId, lo: u32, hi: Option<u32>) -> Comp {
        if lo == 0 && hi == Some(0) {
            Comp::Real(target)
        } else {
            Comp::Wait { target, lo, hi }
        }
    }

    /// This component after one tick elapses, or `None` if it cannot let a
    /// tick pass (a `Real` state's own continuation is by its edges, which
    /// are either same-tick or a `Delay` that becomes a `Wait`).
    fn tick(self) -> Option<Comp> {
        match self {
            Comp::Real(_) => None,
            // `hi >= 1` here: `wait` turned the only `hi == 0` shape into `Real`.
            Comp::Wait { target, lo, hi } => Some(Comp::wait(
                target,
                lo.saturating_sub(1),
                hi.map(|h| h.saturating_sub(1)),
            )),
            Comp::Done => Some(Comp::Done),
        }
    }
}

/// One edge out of a product state's component, before it is paired with the
/// other component.
struct Move {
    guard: Option<LeafId>,
    label: Transition,
    to: Comp,
}

/// The moves of one component of a product state (see [`Comp`]). `exits` is
/// the operand's exit set: for `and`, a component at an exit may stop
/// (`Done`) on this very tick.
fn comp_moves(
    a: &ir::Automaton,
    c: Comp,
    exits: &HashSet<ThreadStateId>,
    kind: ProductKind,
    scope: &Symbol<'_>,
) -> Result<Vec<Move>, LoweringError> {
    let mut out = Vec::new();
    match c {
        Comp::Done => {}
        Comp::Wait { target, lo, .. } => {
            if lo == 0 {
                out.push(Move {
                    guard: None,
                    label: Transition::Epsilon,
                    to: Comp::Real(target),
                });
            }
        }
        Comp::Real(s) => {
            for e in &a.state(s).edges {
                let (label, to) = match &e.label {
                    Transition::Epsilon => (Transition::Epsilon, Comp::Real(e.target)),
                    // A window with min > max never fires (the builder rejects
                    // those at the source; this keeps the product total).
                    Transition::Delay { min, max } => {
                        if max.is_some_and(|m| *min > m) {
                            continue;
                        }
                        (Transition::Epsilon, Comp::wait(e.target, *min, *max))
                    }
                    // A local-variable action is a same-tick move of the thread
                    // carrying it (T13): the product keeps the action on the edge
                    // and the frame it acts on is the thread's own.
                    Transition::FirstMatchBegin { .. }
                    | Transition::FirstMatchEnd { .. }
                    | Transition::LocalVarWrite { .. }
                    | Transition::LocalVarCopy { .. }
                    | Transition::LocalVarStep { .. } => (e.label.clone(), Comp::Real(e.target)),
                    // Testing an end point is a same-tick move of the thread
                    // too (T15): the runtime asks "did the instance end on this
                    // tick" against the thread's own frame, and a guard-form
                    // edge copies the flowing-out locals into it.
                    Transition::EndPoint { .. } => (e.label.clone(), Comp::Real(e.target)),
                    // A subroutine call fires at every end point of the
                    // sequence it is attached to, even when the sibling operand
                    // then fails (16.11); the product only keeps a thread
                    // whose both components can still finish, so it cannot
                    // promise that. Refused rather than guessed (T29's engine
                    // can lift it).
                    // A clock change (T28) never reaches here: `build_threads`
                    // refuses a multiclocked operand (16.13.1) before the product
                    // is built, so this arm is the same loud backstop.
                    Transition::Match { .. }
                    | Transition::Abort { .. }
                    | Transition::ClockSync { .. }
                    | Transition::SubroutineCall { .. } => {
                        return Err(LoweringError::unsupported_at(
                            &format!(
                                "sva automaton builder: `{}` operand contains a {} edge, which \
                                 the lockstep product does not know how to compose",
                                kind.name(),
                                e.label.kind_name()
                            ),
                            scope,
                        ));
                    }
                };
                out.push(Move {
                    guard: e.guard,
                    label,
                    to,
                });
            }
            if kind == ProductKind::And && exits.contains(&s) {
                out.push(Move {
                    guard: None,
                    label: Transition::Epsilon,
                    to: Comp::Done,
                });
            }
        }
    }
    Ok(out)
}

/// The product state for `key`, allocating (and queueing it) if new.
fn intern_product(
    a: &mut ir::Automaton,
    ids: &mut HashMap<(Comp, Comp), ThreadStateId>,
    order: &mut Vec<(Comp, Comp)>,
    key: (Comp, Comp),
    kind: ProductKind,
    scope: &Symbol<'_>,
) -> Result<ThreadStateId, LoweringError> {
    if let Some(&id) = ids.get(&key) {
        return Ok(id);
    }
    if order.len() >= MAX_PRODUCT_STATES {
        return Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: the `{}` of these operands needs more than \
                 {MAX_PRODUCT_STATES} product states (its operands' delay bounds are too large \
                 to compose in lockstep)",
                kind.name()
            ),
            scope,
        ));
    }
    let id = a.new_state();
    ids.insert(key, id);
    order.push(key);
    Ok(id)
}

/// `l intersect r` (16.9.6) and `l and r` (16.9.5) as a lockstep product of the
/// two operand fragments, which stay in `a` (and become unreachable; see
/// [`prune_unreachable`]).
///
/// A product state is a pair of [`Comp`]s; both operands start on the same
/// tick and every tick advances both together (the one `Delay{1,1}` edge a
/// product state may have), so the product only has a state where both sides
/// are on the SAME tick, and a Boolean leaf's guard is copied onto the product
/// edge unchanged (it samples that tick).
///
/// - `intersect` matches where both operands are at an exit on the same tick:
///   equal length, as 16.9.6 requires.
/// - `and` additionally lets an operand that is at an exit step to `Done` and
///   wait, so the composite ends where the later operand ends, as 16.9.5
///   requires. This is Annex F.3.4.2.4's `((r1 ##1 1[*0:$]) intersect r2) or
///   (r1 intersect (r2 ##1 1[*0:$]))`, with the `1[*0:$]` padding done by
///   idling instead of by extra states.
///
/// Empty matches (16.9.2.1): the composite admits the empty match exactly when
/// both operands do. Under `intersect` an empty operand pairs only with an
/// empty one, so only the flag survives; under `and`, `ε and R` is R's
/// matches (the empty operand is already `Done`).
///
/// First-match markers of the operands are copied through, so each region is
/// still stamped and checked per thread (see [`ir::Transition::FirstMatchEnd`]).
fn build_product<'d>(
    a: &mut ir::Automaton,
    l: Fragment,
    r: Fragment,
    kind: ProductKind,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let ne_l = !l.exits.is_empty();
    let ne_r = !r.exits.is_empty();
    let empty = l.empty && r.empty;

    let mut routes: Vec<(Comp, Comp)> = Vec::new();
    if ne_l && ne_r {
        routes.push((Comp::Real(l.entry), Comp::Real(r.entry)));
    }
    if kind == ProductKind::And {
        if l.empty && ne_r {
            routes.push((Comp::Done, Comp::Real(r.entry)));
        }
        if r.empty && ne_l {
            routes.push((Comp::Real(l.entry), Comp::Done));
        }
    }

    let exits_l: HashSet<ThreadStateId> = l.exits.iter().copied().collect();
    let exits_r: HashSet<ThreadStateId> = r.exits.iter().copied().collect();
    // Lookup only; `order` is the deterministic creation order.
    let mut ids: HashMap<(Comp, Comp), ThreadStateId> = HashMap::new();
    let mut order: Vec<(Comp, Comp)> = Vec::new();

    let mut route_ids = Vec::new();
    for &route in &routes {
        route_ids.push(intern_product(a, &mut ids, &mut order, route, kind, scope)?);
    }

    let mut next = 0;
    while next < order.len() {
        let key @ (cl, cr) = order[next];
        next += 1;
        let from = ids[&key];
        for m in comp_moves(a, cl, &exits_l, kind, scope)? {
            let to = intern_product(a, &mut ids, &mut order, (m.to, cr), kind, scope)?;
            a.add_edge(from, m.guard, m.label, to);
        }
        for m in comp_moves(a, cr, &exits_r, kind, scope)? {
            let to = intern_product(a, &mut ids, &mut order, (cl, m.to), kind, scope)?;
            a.add_edge(from, m.guard, m.label, to);
        }
        // A tick passes only when neither side has anything left to do on this
        // one -- every side is waiting (or, for `and`, finished) -- and at
        // least one side is genuinely waiting.
        let waiting = |c: Comp| matches!(c, Comp::Wait { .. });
        if let (Some(tl), Some(tr)) = (cl.tick(), cr.tick())
            && (waiting(cl) || waiting(cr))
        {
            let to = intern_product(a, &mut ids, &mut order, (tl, tr), kind, scope)?;
            a.add_edge(
                from,
                None,
                Transition::Delay {
                    min: 1,
                    max: Some(1),
                },
                to,
            );
        }
    }

    let is_exit = |&(cl, cr): &(Comp, Comp)| match (kind, cl, cr) {
        (ProductKind::Intersect, Comp::Real(x), Comp::Real(y)) => {
            exits_l.contains(&x) && exits_r.contains(&y)
        }
        (ProductKind::And, Comp::Done, Comp::Done) => true,
        _ => false,
    };
    let live = trim_dead_product_states(a, &ids, &order, is_exit);
    // One live route is the entry; several need a fresh state that starts
    // them all (and none leaves an entry with no edges: no match).
    let live_routes: Vec<ThreadStateId> = route_ids
        .iter()
        .copied()
        .filter(|id| live.contains(id))
        .collect();
    let entry = match live_routes.as_slice() {
        [only] => *only,
        many => {
            let entry = a.new_state();
            for &id in many {
                a.add_edge(entry, None, Transition::Epsilon, id);
            }
            entry
        }
    };
    let exits = order
        .iter()
        .filter(|key| is_exit(key))
        .map(|key| ids[key])
        .collect();
    Ok(Fragment {
        entry,
        exits,
        empty,
        flow: Flow::identity(),
        clock: None,
    })
}

/// Cuts every edge of the product (the states `order` lists, interned in
/// `ids`) into a state that can neither reach an exit nor a
/// [`Transition::FirstMatchEnd`] edge, and returns the live states. Most
/// lockstep pairs are dead (the operands never line up), and nested operators
/// would otherwise multiply those dead states into the next product.
///
/// A state with a `FirstMatchEnd` edge stays live, and keeps that edge, even
/// when no exit follows: the end tick the edge records is a fact about the
/// region, not about this product (`first_match(R) intersect S` discards R's
/// later matches whether or not S agrees with its earliest one, see the
/// edge's doc).
fn trim_dead_product_states(
    a: &mut ir::Automaton,
    ids: &HashMap<(Comp, Comp), ThreadStateId>,
    order: &[(Comp, Comp)],
    is_exit: impl Fn(&(Comp, Comp)) -> bool,
) -> HashSet<ThreadStateId> {
    let index: HashMap<ThreadStateId, usize> = order
        .iter()
        .enumerate()
        .map(|(i, key)| (ids[key], i))
        .collect();
    let mut preds: Vec<Vec<usize>> = vec![Vec::new(); order.len()];
    let mut live = vec![false; order.len()];
    let mut stack = Vec::new();
    for (i, key) in order.iter().enumerate() {
        let edges = &a.state(ids[key]).edges;
        for e in edges {
            // Every product edge targets another product state.
            preds[index[&e.target]].push(i);
        }
        let ends = edges
            .iter()
            .any(|e| matches!(e.label, Transition::FirstMatchEnd { .. }));
        if ends || is_exit(key) {
            live[i] = true;
            stack.push(i);
        }
    }
    while let Some(i) = stack.pop() {
        for &p in &preds[i] {
            if !live[p] {
                live[p] = true;
                stack.push(p);
            }
        }
    }
    for (i, key) in order.iter().enumerate() {
        let id = ids[key];
        if live[i] {
            // A `FirstMatchEnd` edge stays even into a dead state: crossing it
            // is what records the region's earliest end tick.
            a.states[id.0 as usize].edges.retain(|e| {
                live[index[&e.target]] || matches!(e.label, Transition::FirstMatchEnd { .. })
            });
        } else {
            a.states[id.0 as usize].edges.clear();
        }
    }
    order
        .iter()
        .enumerate()
        .filter(|(i, _)| live[*i])
        .map(|(_, key)| ids[key])
        .collect()
}

/// A fragment matching exactly one tick, unconditionally (the LRM's
/// `` `true ``, `1`): the unit of `1[*0:$]`.
fn true_fragment(a: &mut ir::Automaton) -> Fragment {
    let entry = a.new_state();
    let exit = a.new_state();
    a.add_edge(entry, None, Transition::Epsilon, exit);
    Fragment {
        entry,
        exits: vec![exit],
        empty: false,
        flow: Flow::identity(),
        clock: None,
    }
}

/// `1[*0:$]`: any number of vacuous ticks, the empty run included.
fn true_run(a: &mut ir::Automaton, leaves: &mut LeafTable<'_>) -> Result<Fragment, LoweringError> {
    build_repeated(a, leaves, 0, None, CONSECUTIVE_LINK, &mut |a, _| {
        Ok(true_fragment(a))
    })
}

/// The `##1` that links consecutive repeats (16.9.2).
const CONSECUTIVE_LINK: SequenceRangeValue = SequenceRangeValue {
    min: 1,
    max: Some(1),
};

/// `AssertionExprKind::Binary` as a SEQUENCE operator: `and`, `or`,
/// `intersect`, `throughout`, `within` (16.9.5-16.9.10). The operands are the
/// node's two children, left then right, each built as a sequence by
/// [`build_node`] (so a PROPERTY operand reaches the property operator and
/// is rejected there, by name). The other `BinaryAssertionOperator`s are
/// property operators, T19 onward's: a named error.
fn build_binary<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let op = match Op::of(expr, scope)? {
        Op::Binary(op) => op,
        Op::Unary(op) => {
            return Err(LoweringError::unsupported_at(
                &format!("sva automaton builder: a Binary node carries the unary operator {op:?}"),
                scope,
            ));
        }
    };
    let kids = expr.children();
    let [lhs, rhs] = kids.as_slice() else {
        return Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: a `{op:?}` node must have exactly two operands, found {}",
                kids.len()
            ),
            scope,
        ));
    };
    match op {
        AssertionBinaryOp::And | AssertionBinaryOp::Intersect => {
            let kind = if op == AssertionBinaryOp::And {
                ProductKind::And
            } else {
                ProductKind::Intersect
            };
            build_threads(
                a,
                leaves,
                kind,
                if op == AssertionBinaryOp::And {
                    "and"
                } else {
                    "intersect"
                },
                scope,
                &mut |a, leaves| build_node(a, leaves, *lhs, tree, scope),
                &mut |a, leaves| build_node(a, leaves, *rhs, tree, scope),
            )
        }
        // The two operands of an `or` start from the SAME flow set (16.10: it
        // flows in to each), and each matching thread continues as its own
        // thread with its own frame, so no shadowing is needed.
        AssertionBinaryOp::Or => {
            let l = build_node(a, leaves, *lhs, tree, scope)?;
            let r = build_node(a, leaves, *rhs, tree, scope)?;
            let clock = join_clocks(leaves, &[&l, &r], "or", scope)?;
            Ok(Fragment {
                clock,
                ..build_or(a, l, r)
            })
        }
        // 16.9.9: `exp throughout seq` is `(exp)[*0:$] intersect seq`.
        AssertionBinaryOp::Throughout => {
            let cond = *lhs;
            build_threads(
                a,
                leaves,
                ProductKind::Intersect,
                "throughout",
                scope,
                &mut |a, leaves| {
                    build_repeated(a, leaves, 0, None, CONSECUTIVE_LINK, &mut |a, leaves| {
                        build_node(a, leaves, cond, tree, scope)
                    })
                },
                &mut |a, leaves| build_node(a, leaves, *rhs, tree, scope),
            )
        }
        // 16.9.10: `seq1 within seq2` is `(1[*0:$] ##1 seq1 ##1 1[*0:$])
        // intersect seq2` -- `lhs` is seq1 (the inner one), `rhs` the container.
        AssertionBinaryOp::Within => build_threads(
            a,
            leaves,
            ProductKind::Intersect,
            "within",
            scope,
            &mut |a, leaves| {
                let seq1 = build_node(a, leaves, *lhs, tree, scope)?;
                let clock = single_clock(&seq1, "the inner sequence of `within`")
                    .map_err(|msg| LoweringError::unsupported_at(&msg, scope))?;
                let one = CONSECUTIVE_LINK;
                let before = true_run(a, leaves)?;
                let after = true_run(a, leaves)?;
                let inner = concat(a, before, one, seq1);
                Ok(Fragment {
                    clock,
                    ..concat(a, inner, one, after)
                })
            },
            &mut |a, leaves| build_node(a, leaves, *rhs, tree, scope),
        ),
        AssertionBinaryOp::Iff
        | AssertionBinaryOp::Until
        | AssertionBinaryOp::SUntil
        | AssertionBinaryOp::UntilWith
        | AssertionBinaryOp::SUntilWith
        | AssertionBinaryOp::Implies
        | AssertionBinaryOp::OverlappedImplication
        | AssertionBinaryOp::NonOverlappedImplication
        | AssertionBinaryOp::OverlappedFollowedBy
        | AssertionBinaryOp::NonOverlappedFollowedBy => Err(LoweringError::unsupported_at(
            &format!(
                "sva automaton builder: AssertionExprKind::Binary operator {op:?} is a property \
                 operator (LRM 16.12), not a sequence operator: it is built by \
                 `build_property`, and cannot be an operand of a sequence operator, a delay or \
                 a repetition (16.12.1)"
            ),
            scope,
        )),
    }
}

/// `l or r` (16.9.7): the union of the operands' matches -- a fresh entry
/// that starts both, exits that are both operands' exits. The operands share
/// no state, so nothing needs to be copied. An operand that cannot match
/// nonempty contributes nothing but its `empty` flag.
fn build_or(a: &mut ir::Automaton, l: Fragment, r: Fragment) -> Fragment {
    let entry = a.new_state();
    for f in [&l, &r] {
        if !f.exits.is_empty() {
            a.add_edge(entry, None, Transition::Epsilon, f.entry);
        }
    }
    // F.5.4: only what both branches assign flows out.
    let flow = l.flow.or(&r.flow);
    let mut exits = l.exits;
    exits.extend(r.exits);
    Fragment {
        entry,
        exits,
        empty: l.empty || r.empty,
        flow,
        clock: None,
    }
}

/// A chain of same-tick action edges that leads into `target`, returning the
/// state to enter it from; `target` itself when there is nothing to do.
fn prefix_actions(
    a: &mut ir::Automaton,
    actions: Vec<Transition>,
    target: ThreadStateId,
) -> ThreadStateId {
    let Some((last, init)) = actions.split_last() else {
        return target;
    };
    let entry = a.new_state();
    let mut cur = entry;
    for t in init {
        let next = a.new_state();
        a.add_edge(cur, None, t.clone(), next);
        cur = next;
    }
    a.add_edge(cur, None, last.clone(), target);
    entry
}

/// A chain of same-tick action edges that every state of `exits` leads into,
/// returning the chain's end as the new (single) exit; `exits` itself when
/// there is nothing to do or nothing to continue from.
fn suffix_actions(
    a: &mut ir::Automaton,
    exits: Vec<ThreadStateId>,
    actions: Vec<Transition>,
) -> Vec<ThreadStateId> {
    if actions.is_empty() || exits.is_empty() {
        return exits;
    }
    let head = a.new_state();
    for &e in &exits {
        a.add_edge(e, None, Transition::Epsilon, head);
    }
    let mut cur = head;
    for t in actions {
        let next = a.new_state();
        a.add_edge(cur, None, t, next);
        cur = next;
    }
    vec![cur]
}

/// A two-threaded sequence operator: `and`, `intersect`, and (through their
/// rewrites) `throughout` and `within` (16.9.5, 16.9.6, 16.9.9, 16.9.10). Both
/// operands start from the same flow set (16.10: it flows in to each), and run
/// concurrently, each with its OWN copy of every local variable (rule (d): the
/// two threads are merged into one only at the end). `first` keeps the shared
/// slots; every variable it touched is shadowed in `second` (see
/// [`ShadowCtx`]), the shadows initialised from the shared slot at the start
/// and, for a variable only `second` assigns (the F.5.4 difference), copied back
/// at the end. A variable both assign is blocked (its flow is
/// [`Flow::intersect`]'s business) and so is never copied back.
fn build_threads<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    kind: ProductKind,
    what: &str,
    scope: &Symbol<'d>,
    first: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
    second: &mut dyn FnMut(
        &mut ir::Automaton,
        &mut LeafTable<'d>,
    ) -> Result<Fragment, LoweringError>,
) -> Result<Fragment, LoweringError> {
    let mark = leaves.touched.len();
    let l = first(a, leaves)?;
    let outer_touched: BTreeSet<LocalVarId> = leaves.touched[mark..].iter().copied().collect();
    leaves.shadows.push(ShadowCtx {
        outer_touched,
        made: Vec::new(),
    });
    let r = second(a, leaves);
    let ctx = leaves.shadows.pop().expect("pushed above");
    let r = r?;

    let clock = join_clocks(leaves, &[&l, &r], what, scope)?;
    let flow = l.flow.intersect(&r.flow);
    let copy_in: Vec<Transition> = ctx
        .made
        .iter()
        .map(|&(_, outer, shadow)| Transition::LocalVarCopy {
            dst: shadow,
            src: outer,
        })
        .collect();
    let copy_out: Vec<Transition> = ctx
        .made
        .iter()
        .filter(|(canon, _, _)| r.flow.sample.contains(canon) && !l.flow.sample.contains(canon))
        .map(|&(_, outer, shadow)| Transition::LocalVarCopy {
            dst: outer,
            src: shadow,
        })
        .collect();
    let mut p = build_product(a, l, r, kind, scope)?;
    p.entry = prefix_actions(a, copy_in, p.entry);
    p.exits = suffix_actions(a, p.exits, copy_out);
    p.flow = flow;
    p.clock = clock;
    Ok(p)
}

/// `AssertionExprKind::FirstMatch` (16.9.8): only `R`'s matches that end
/// earliest, for a given beginning (Annex F.5.2: `w |= first_match(R)` iff
/// `w |= R` and no proper prefix of `w` -- the empty word included -- satisfies
/// `R`).
///
/// - If `R` admits the empty match, that match is the earliest possible, so
///   the result is the empty match alone.
/// - Otherwise the region is bracketed by a [`Transition::FirstMatchBegin`]
///   from a fresh entry and a [`Transition::FirstMatchEnd`] from every exit of
///   `R` into one fresh exit; the engine's per-attempt table does the rest
///   (see those edges' docs). The group is minted here, one per region.
///
/// Sequence match items (`first_match(R, v = e)`, T14) are
/// `first_match((R, v = e))` (16.9.8): the items belong to the operand, so they
/// are attached to `R` BEFORE the bracket is built (see
/// [`attach_match_items`]) and run at EVERY end point of `R` (16.11: "all
/// subroutine calls attached to a sequence are executed at every end point of
/// the sequence"), including the matches `first_match` then discards. For
/// assignments the position is unobservable (a discarded thread's frame is
/// gone); for calls it is the whole difference. An empty `R` with items is the
/// 16.11 nondegeneracy error. The items are lowered (and so validated) even
/// when `R` can never match.
fn build_first_match<'d>(
    a: &mut ir::Automaton,
    leaves: &mut LeafTable<'d>,
    expr: AssertionExpr<'d>,
    tree: Trees<'_>,
    scope: &Symbol<'d>,
) -> Result<Fragment, LoweringError> {
    let kids = expr.children();
    let Some((seq, items)) = kids.split_first() else {
        return Err(LoweringError::unsupported_at(
            "sva automaton builder: a first_match node has no sequence operand",
            scope,
        ));
    };
    let x0 = leaves.flow_in.clone();
    let r = build_node(a, leaves, *seq, tree, scope)?;
    let clock = single_clock(&r, "`first_match`")
        .map_err(|msg| LoweringError::unsupported_at(&msg, scope))?;
    if r.empty && !items.is_empty() {
        return Err(LoweringError::unsupported_at(
            "a sequence match item is attached to a first_match of a sequence that admits an \
             empty match (LRM 16.11: it shall be an error to attach a match item to such a \
             sequence)",
            scope,
        ));
    }
    if r.empty {
        // F.5.4: `flow(X, first_match(R)) = flow(X, R)`, whichever matches
        // survive.
        let mut f = empty_fragment(a);
        f.flow = r.flow;
        f.clock = clock;
        return Ok(f);
    }
    // `first_match(R, items)` is `first_match((R, items))`: the items run on
    // every end point of R, inside the bracket. Done before the never-matches
    // early-out so the items are validated either way.
    let r = if items.is_empty() {
        r
    } else {
        attach_match_items(a, leaves, r, items, &x0, scope)?
    };
    if r.exits.is_empty() {
        // `R` never matches: neither does first_match(R); nothing to bracket.
        return Ok(r);
    }
    let group = a.new_first_match_group();
    let entry = a.new_state();
    let exit = a.new_state();
    a.add_edge(entry, None, Transition::FirstMatchBegin { group }, r.entry);
    for &e in &r.exits {
        a.add_edge(e, None, Transition::FirstMatchEnd { group }, exit);
    }
    Ok(Fragment {
        entry,
        exits: vec![exit],
        empty: false,
        flow: r.flow,
        clock,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{BTreeMap, BTreeSet, HashSet};

    use sv_lang::kinds::ExpressionKind;
    use sv_lang::{AnalysisFlags, Compilation, Session, SyntaxTree};
    use sv_sim_sim::sva::trace;

    /// Compiles `property_body` as a clocked `assert property` inside an
    /// `always_ff` (same shape as this crate's other `sva` test
    /// scaffolding, `ranges.rs`/`op.rs`/`leaf.rs`), builds its automaton via
    /// [`build_automaton`], and hands `(automaton, leaves)` to `f`.
    /// `extra_decls` is for anything the property body references besides
    /// `clk`/`a`/`b`/`c`/`cnt`.
    fn automaton_of<R>(
        extra_decls: &str,
        property_body: &str,
        f: impl FnOnce(ir::Automaton, LeafTable<'_>) -> R,
    ) -> R {
        let src = format!(
            "module m;\n\
             {extra_decls}\n\
             logic clk, a, b, c;\n\
             int cnt;\n\
             always_ff @(posedge clk) begin\n\
               assert property (@(posedge clk) {property_body});\n\
             end\n\
             endmodule\n"
        );
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(&src).unwrap();
        let design = comp.compile().unwrap();
        assert!(
            !design.has_fatal_errors(),
            "fixture failed to compile: {src}"
        );
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let analysis = design.analyze(AnalysisFlags::NONE, 1).unwrap();
        let proc = analysis.procedures(body).next().unwrap();
        let assertion = analysis.assertions(proc.symbol()).next().unwrap();
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let clocking = assertion.root().as_assertion_expr().unwrap();
        assert_eq!(clocking.kind(), AssertionExprKind::Clocking);
        let root = clocking.children()[1].as_assertion_expr().unwrap();
        let (automaton, leaves) =
            build_automaton(root, Some(clocking.children()[0]), (&tree).into(), &body).unwrap();
        f(automaton, leaves)
    }

    fn automaton_err(extra_decls: &str, property_body: &str) -> LoweringError {
        let src = format!(
            "module m;\n\
             {extra_decls}\n\
             logic clk, a, b, c;\n\
             int cnt;\n\
             always_ff @(posedge clk) begin\n\
               assert property (@(posedge clk) {property_body});\n\
             end\n\
             endmodule\n"
        );
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(&src).unwrap();
        let design = comp.compile().unwrap();
        assert!(
            !design.has_fatal_errors(),
            "fixture failed to compile: {src}"
        );
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let analysis = design.analyze(AnalysisFlags::NONE, 1).unwrap();
        let proc = analysis.procedures(body).next().unwrap();
        let assertion = analysis.assertions(proc.symbol()).next().unwrap();
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let clocking = assertion.root().as_assertion_expr().unwrap();
        let root = clocking.children()[1].as_assertion_expr().unwrap();
        build_automaton(root, Some(clocking.children()[0]), (&tree).into(), &body)
            .expect_err("expected build_automaton to reject this")
    }

    /// Every elapsed-tick count (from `automaton.start` to a reachable
    /// `Match` edge) within `bound` ticks -- the test-only enumeration this
    /// task's own "assert the SET of accepted linear sequences matches the
    /// LRM's own enumeration" acceptance criterion needs. Bounded DFS over
    /// `(state, ticks)` pairs, deduplicated so a genuine cycle (an unbounded
    /// `[*n:$]` repetition's self-loop) terminates instead of looping
    /// forever -- production code never walks the automaton this way (the
    /// real engine steps one tick at a time per live thread, which
    /// terminates trivially because wall-clock time always advances).
    fn reachable_lengths(automaton: &ir::Automaton, bound: u32) -> BTreeSet<u32> {
        let mut out = BTreeSet::new();
        let mut seen: HashSet<(u32, u32)> = HashSet::new();
        let mut stack = vec![(automaton.start, 0u32)];
        while let Some((state_id, ticks)) = stack.pop() {
            if ticks > bound || !seen.insert((state_id.0, ticks)) {
                continue;
            }
            let state = automaton.state(state_id);
            if state.is_accepting() {
                out.insert(ticks);
            }
            for edge in &state.edges {
                match &edge.label {
                    ir::Transition::Delay { min, max } => {
                        let hi = max.unwrap_or(bound);
                        let mut k = *min;
                        while k <= hi {
                            let t = ticks + k;
                            if t > bound {
                                break;
                            }
                            stack.push((edge.target, t));
                            k += 1;
                        }
                    }
                    ir::Transition::Epsilon => stack.push((edge.target, ticks)),
                    // A local-variable action takes no time: it moves the
                    // thread on in the same tick, exactly like an epsilon, and
                    // this walk measures only elapsed ticks (the VALUES the
                    // actions compute are checked by `sva::trace`).
                    ir::Transition::LocalVarWrite { .. }
                    | ir::Transition::LocalVarCopy { .. }
                    | ir::Transition::LocalVarStep { .. }
                    | ir::Transition::SubroutineCall { .. } => stack.push((edge.target, ticks)),
                    // Whether the end point fires depends on the trace, not on
                    // the path, so this length walk cannot decide it; a test
                    // that wants it uses `sva::trace::attempt_with_clocks`.
                    ir::Transition::EndPoint { .. } => {
                        panic!("a length walk cannot decide an EndPoint edge")
                    }
                    // Which instant is the next tick of another clock is a fact
                    // about a timeline (see `sva::trace::Timeline`), not a path.
                    ir::Transition::ClockSync { .. } => {
                        panic!("a length walk cannot decide a ClockSync edge")
                    }
                    ir::Transition::Match { .. } => {
                        // Already accounted for via `is_accepting` above; a
                        // Match edge self-loops onto the same state (this
                        // module's own `build_automaton` convention), so
                        // following it would just re-push an identical pair.
                    }
                    ir::Transition::Abort { .. }
                    | ir::Transition::FirstMatchBegin { .. }
                    | ir::Transition::FirstMatchEnd { .. } => {
                        // Not produced by any fragment the T9/T10 tests build
                        // (first_match is checked by T11's trace battery, not
                        // by this length walk); nothing to walk.
                    }
                }
            }
        }
        out
    }

    // -- 16.9.2's own worked examples (plan T9 "Tests:" text) -------------

    /// `a[*3]` == `a##1a##1a` (16.9.2's own stated equivalence): both must
    /// produce the identical set of accepted lengths, and that set must be
    /// the LRM-correct `{2}` (`a[*3]` spans ticks i..i+2 inclusive -- 2
    /// ticks of elapsed time, not 3; this is the well-known identity that
    /// only holds if a bare Boolean leaf's own evaluation costs zero
    /// ADDITIONAL ticks, which is exactly what `build_leaf`'s `Epsilon`
    /// choice encodes).
    #[test]
    fn a_star_3_equiv_a_hash1_a_hash1_a() {
        let lhs = automaton_of("", "a[*3]", |au, _| reachable_lengths(&au, 10));
        let rhs = automaton_of("", "a ##1 a ##1 a", |au, _| reachable_lengths(&au, 10));
        assert_eq!(lhs, rhs);
        assert_eq!(lhs, BTreeSet::from([2]));
    }

    /// `(a##2b)[*3]`: one accepted length, the LRM-correct 8 (the explicit
    /// unrolling `a##2b##1a##2b##1a##2b` samples its final `b` 8 ticks
    /// after its first `a`).
    #[test]
    fn parenthesized_concat_repeated_fixed_count() {
        automaton_of("", "(a ##2 b)[*3]", |au, _| {
            assert_eq!(reachable_lengths(&au, 20), BTreeSet::from([8]));
        });
    }

    /// `(a##2b)[*1:5]` enumerated 5-way: `{2, 5, 8, 11, 14}` (one repeat
    /// spans 2 ticks; each additional repeat adds the unit's own 2 ticks
    /// plus the implicit `##1` link between repeats, i.e. +3 per repeat).
    #[test]
    fn parenthesized_concat_repeated_range_enumerates_five_lengths() {
        automaton_of("", "(a ##2 b)[*1:5]", |au, _| {
            assert_eq!(
                reachable_lengths(&au, 20),
                BTreeSet::from([2, 5, 8, 11, 14])
            );
        });
    }

    /// `a[*0:3]##1b##1c` enumerated 4-way per the LRM's own stated
    /// expansion (`(b##1c) or (a##1b##1c) or (a##1a##1b##1c) or
    /// (a##1a##1a##1b##1c)`): final `c` lands at ticks `{1, 2, 3, 4}`. This
    /// is the test that would fail if `build_concat`'s one empty-match rule
    /// (this module's own doc comment on `build_concat`) were removed -- a
    /// naive (non-empty-match-aware) chaining would instead report `{2, 3,
    /// 4}` (collapsing the `min == 0` branch into the `k == 1` branch's own
    /// tick value, which is LRM-wrong for the `k == 0` branch).
    #[test]
    fn simple_repeated_range_zero_to_three_then_concat_enumerates_four_lengths() {
        automaton_of("", "a[*0:3] ##1 b ##1 c", |au, _| {
            assert_eq!(reachable_lengths(&au, 20), BTreeSet::from([1, 2, 3, 4]));
        });
    }

    // -- 16.9.2's illegal goto/nonconsecutive-on-match-item example -------

    /// The LRM's own illegal example (16.9.2/16.10): goto repetition
    /// applied to a sequence that also carries a match item is rejected
    /// with a named error, never a wrong (or silently accepted) answer.
    #[test]
    fn goto_repetition_on_sequence_with_match_item_is_rejected() {
        let err = automaton_err("", "(b, cnt = cnt + 1)[->2]");
        assert!(
            err.message.contains("illegal"),
            "error should name the illegal combination: {err}"
        );
    }

    /// Same illegal combination, nonconsecutive (`[=]`) form.
    #[test]
    fn nonconsecutive_repetition_on_sequence_with_match_item_is_rejected() {
        let err = automaton_err("", "(b, cnt = cnt + 1)[=2]");
        assert!(
            err.message.contains("illegal"),
            "error should name the illegal combination: {err}"
        );
    }

    /// The LEGAL counterpart: consecutive (`[*]`) repetition on a
    /// match-item-bearing sequence is not itself illegal -- here it is
    /// rejected only because `cnt` is a module variable, not a local one
    /// (T14), never as the illegal-combination error.
    #[test]
    fn consecutive_repetition_on_sequence_with_match_item_is_not_the_illegal_case() {
        let err = automaton_err("", "(b, cnt = cnt + 1)[*2]");
        assert!(
            !err.message.contains("illegal"),
            "consecutive repetition + match item is LRM-legal (lowered; see the probe fixture \
             sva_match_item_assignments): only the module-variable target is refused: {err}"
        );
        assert!(err.message.contains("match item"), "error was: {err}");
    }

    // -- bare repetition shapes (sanity beyond the plan's named examples) -

    #[test]
    fn bare_leaf_has_single_tick_zero_length() {
        automaton_of("", "a", |au, _| {
            assert_eq!(reachable_lengths(&au, 5), BTreeSet::from([0]));
        });
    }

    #[test]
    fn consecutive_range_two_to_seven() {
        automaton_of("", "a[*2:7]", |au, _| {
            // k consecutive samples span (k-1) ticks; k in 2..=7 -> 1..=6.
            assert_eq!(
                reachable_lengths(&au, 10),
                BTreeSet::from([1, 2, 3, 4, 5, 6])
            );
        });
    }

    /// Goto repetition on a bare Boolean operand (legal, no match item):
    /// unlike consecutive repetition, a gap between the two matching ticks
    /// must be reachable. (What the gap may hold is pinned exactly by the
    /// `goto_*`/`nonconsecutive_*` tests below.)
    #[test]
    fn goto_repetition_on_bare_leaf_allows_a_gap_between_matches() {
        automaton_of("", "a[->2]", |au, _| {
            let lengths = reachable_lengths(&au, 6);
            // Exactly 1 tick apart (no gap) must still be reachable...
            assert!(lengths.contains(&1), "lengths were: {lengths:?}");
            // ...and so must a true gap (>=2 ticks between matches), which
            // would NOT be reachable under consecutive (`[*2]`) repetition
            // -- that is the entire point of `->`'s wider link window.
            assert!(
                lengths.iter().any(|&t| t >= 3),
                "a true multi-tick gap must be reachable via goto repetition: {lengths:?}"
            );
        });
    }

    /// 16.9.2: `b[->n]` is `(!b[*0:$] ##1 b)[*n]`. Pinned word by word, not
    /// only against the rewrite: `b` is false on every tick before a hit that is
    /// not itself a hit, and the match ends AT the last hit, so the first tick is
    /// either a hit or a `!b` (never an unconstrained one).
    #[test]
    fn goto_repetition_is_exact() {
        let (a, na) = ("a", "!a");
        assert_eq!(
            lang_of("a[->1]", 2),
            Lang::from([
                word(&[&[a]]),
                word(&[&[na], &[a]]),
                word(&[&[na], &[na], &[a]]),
            ])
        );
        assert_eq!(
            lang_of("a[->2]", 3),
            Lang::from([
                word(&[&[a], &[a]]),
                word(&[&[a], &[na], &[a]]),
                word(&[&[na], &[a], &[a]]),
                word(&[&[a], &[na], &[na], &[a]]),
                word(&[&[na], &[a], &[na], &[a]]),
                word(&[&[na], &[na], &[a], &[a]]),
            ])
        );
        // The empty match (16.9.2.1) of `[->0]`; `[->0:1]` adds the one-hit forms.
        assert_eq!(lang_of("a[->0]", 3), Lang::from([Word::new()]));
        // The rewrite, for counts, ranges and an open upper bound.
        for (goto, rewrite) in [
            ("a[->1]", "(!a[*0:$] ##1 a)[*1]"),
            ("a[->3]", "(!a[*0:$] ##1 a)[*3]"),
            ("a[->1:2]", "(!a[*0:$] ##1 a)[*1:2]"),
            ("a[->2:3]", "(!a[*0:$] ##1 a)[*2:3]"),
            ("a[->0:2]", "(!a[*0:$] ##1 a)[*0:2]"),
            ("a[->2:$]", "(!a[*0:$] ##1 a)[*2:$]"),
        ] {
            assert_eq!(lang_of(goto, 5), lang_of(rewrite, 5), "`{goto}`");
        }
    }

    /// 16.9.2: `b[=n]` is `b[->n] ##1 !b[*0:$]`: the goto match followed by any
    /// number of further `!b` ticks, so it may end anywhere before the next hit.
    #[test]
    fn nonconsecutive_repetition_is_exact() {
        let (a, na) = ("a", "!a");
        assert_eq!(
            lang_of("a[=1]", 2),
            Lang::from([
                word(&[&[a]]),
                word(&[&[a], &[na]]),
                word(&[&[na], &[a]]),
                word(&[&[a], &[na], &[na]]),
                word(&[&[na], &[a], &[na]]),
                word(&[&[na], &[na], &[a]]),
            ])
        );
        assert_eq!(
            lang_of("a[=2]", 2),
            Lang::from([
                word(&[&[a], &[a]]),
                word(&[&[a], &[a], &[na]]),
                word(&[&[a], &[na], &[a]]),
                word(&[&[na], &[a], &[a]]),
            ])
        );
        for (nonconsecutive, rewrite) in [
            ("a[=1]", "a[->1] ##1 !a[*0:$]"),
            ("a[=2]", "a[->2] ##1 !a[*0:$]"),
            ("a[=1:2]", "a[->1:2] ##1 !a[*0:$]"),
            ("a[=2:$]", "a[->2:$] ##1 !a[*0:$]"),
        ] {
            assert_eq!(
                lang_of(nonconsecutive, 5),
                lang_of(rewrite, 5),
                "`{nonconsecutive}`"
            );
        }
        // `[=0]` is any run of `!b` ticks, the empty match included.
        assert_eq!(lang_of("a[=0]", 4), lang_of("!a[*0:$]", 4));
        // It differs from the goto form exactly by the trailing ticks.
        assert_ne!(lang_of("a[=2]", 4), lang_of("a[->2]", 4));
    }

    /// The gap of a goto repetition is the NEGATED sample of the same leaf, one
    /// [`LeafTable::is_negated`] guard each, so the interpreter takes it only
    /// where the Boolean is false: `a[->2]` over concrete traces.
    #[test]
    fn goto_repetition_runs_on_traces() {
        // (trace of a, end ticks of the matches that START at tick 0)
        for (bits, want) in [
            ("1100", set(&[1])),
            ("0101", set(&[3])),
            ("1001", set(&[3])),
            // A third hit is not part of `a[->2]`.
            ("1111", set(&[1])),
            ("0001", set(&[])),
            ("0000", set(&[])),
        ] {
            let tr = Trace::new(&[("a", bits)]);
            assert_eq!(ends_at("a[->2]", &tr, 0), want, "a[->2] on {bits}");
        }
        // `a[=2]` also ends on every `!a` tick after the second hit.
        for (bits, want) in [
            ("1100", set(&[1, 2, 3])),
            ("0101", set(&[3])),
            ("1011", set(&[2])),
            ("1010", set(&[2, 3])),
            ("0001", set(&[])),
        ] {
            let tr = Trace::new(&[("a", bits)]);
            assert_eq!(ends_at("a[=2]", &tr, 0), want, "a[=2] on {bits}");
        }
    }

    /// 16.9.2 on 4-state traces: the gap of `b[->n]` is the sample `!b`, and
    /// `!x` is `x` (11.4.7), which a Boolean context makes false -- so a tick
    /// where `b` is `x` is neither a hit nor a gap, and the match cannot cross
    /// it. The goto form must agree with its hand-written definition on every
    /// trace, `x` included.
    #[test]
    fn goto_repetition_does_not_cross_an_x_tick() {
        // The gap leaf is the negated sample, the hit leaf the plain one.
        automaton_of("", "a[->1]", |_, leaves| {
            let negated: Vec<bool> = (0..leaves.len() as u32)
                .map(|i| leaves.is_negated(LeafId(i)))
                .collect();
            // The hit is one plain leaf; the gap (a loop body, copied for the
            // mandatory repeat) is negated everywhere it appears.
            assert_eq!(negated.iter().filter(|n| !**n).count(), 1, "{negated:?}");
            assert!(negated.iter().any(|n| *n), "{negated:?}");
        });
        for (bits, want) in [
            ("01x1", set(&[1])),
            ("0x01", set(&[])),
            ("x1", set(&[])),
            ("001x", set(&[2])),
            ("1xxx", set(&[0])),
            ("0011", set(&[2])),
        ] {
            let tr = Trace::new(&[("a", bits)]);
            assert_eq!(ends_at("a[->1]", &tr, 0), want, "a[->1] on {bits}");
            assert_eq!(
                ends_at("!a[*0:$] ##1 a", &tr, 0),
                want,
                "!a[*0:$] ##1 a on {bits}"
            );
        }
        // `a[=1]` may also run on over further known-false ticks, never an `x` one.
        for (bits, want) in [
            ("10x0", set(&[0, 1])),
            ("1x", set(&[0])),
            ("0100", set(&[1, 2, 3])),
            ("01x0", set(&[1])),
        ] {
            let tr = Trace::new(&[("a", bits)]);
            let hand = "!a[*0:$] ##1 a ##1 !a[*0:$]";
            assert_eq!(ends_at("a[=1]", &tr, 0), ends_at(hand, &tr, 0), "{bits}");
            assert_eq!(ends_at("a[=1]", &tr, 0), want, "a[=1] on {bits}");
        }
    }

    /// Unbounded consecutive repetition (`a[*2:$]`): every length from 1
    /// upward (k repeats span k-1 ticks, k >= 2) must be reachable, not just
    /// one extra step past the mandatory minimum -- proving
    /// `build_repeated_unbounded` builds a genuine cycle, not a single
    /// bonus copy.
    #[test]
    fn unbounded_consecutive_repetition_is_a_true_cycle() {
        automaton_of("", "a[*2:$]", |au, _| {
            let lengths = reachable_lengths(&au, 8);
            assert_eq!(lengths, BTreeSet::from([1, 2, 3, 4, 5, 6, 7, 8]));
        });
    }

    // -- error-path coverage: named errors, never a panic ------------------

    /// An `AssertionExprKind::Binary` operator this builder does not implement
    /// (a PROPERTY operator, `|->`: `build_property`'s) must be a named, loud
    /// `LoweringError` that names the operator -- not a wrong automaton and not
    /// a panic.
    #[test]
    fn unsupported_assertion_expr_kind_is_a_named_error() {
        let err = automaton_err("", "a |-> b");
        assert!(err.message.contains("Binary"), "error was: {err}");
        assert!(
            err.message.contains("OverlappedImplication"),
            "error should name the operator: {err}"
        );
    }

    // ======================================================================
    // T10: `##` concatenation + 16.9.2.1 empty-match algebra.
    //
    // The tests below compare the BUILT AUTOMATON against two independent
    // oracles: (1) hand-written, LRM-derived accepted-word sets for the LRM's
    // own worked examples, and (2) a small reference interpreter of Annex
    // F.5.2's tight-satisfaction semantics over explicit word languages (no
    // automata, no empty-match special cases -- plain word concatenation/
    // fusion), driven over a deterministic battery of generated sequence
    // expressions. Both observe the automaton the same way: every accepted
    // match, as a WORD (one Boolean-leaf constraint set per clock tick the
    // match spans), plus whether the empty match is admitted.
    // ======================================================================

    /// One tick of a match: the set of Boolean leaves (by source text) that
    /// must be true on it. A constant-true leaf (`1`) contributes nothing --
    /// it is the LRM's `` `true `` (16.9.2.1), vacuous by definition, which is
    /// also what the empty-match rewrite rules' own `` `true `` stands for.
    type Letter = BTreeSet<String>;
    /// A match as a word: `word.len()` ticks wide; the empty word (`vec![]`)
    /// is the length-0 empty match of 16.9.2.1.
    type Word = Vec<Letter>;
    /// Every match of a sequence spanning at most `cap` letters (clock
    /// ticks), the empty match included when admitted.
    type Lang = BTreeSet<Word>;

    fn word(letters: &[&[&str]]) -> Word {
        letters
            .iter()
            .map(|l| l.iter().map(|s| s.to_string()).collect())
            .collect()
    }

    /// A leaf's source text with whitespace removed and any redundant outer
    /// parentheses stripped (`(b)`, a parenthesized Boolean operand whose leaf
    /// node is the paren expression; `((trdy==0)&&(irdy==0))`), and nothing
    /// else touched -- `(x)&&(y)` keeps its parens, they do not pair up.
    fn norm_leaf(text: &str) -> String {
        let mut s: String = text.chars().filter(|c| !c.is_whitespace()).collect();
        loop {
            let b = s.as_bytes();
            if b.first() != Some(&b'(') || b.last() != Some(&b')') {
                return s;
            }
            // The opening paren must close at the very end.
            let mut depth = 0i32;
            let mut closes_at_end = false;
            for (i, &c) in b.iter().enumerate() {
                match c {
                    b'(' => depth += 1,
                    b')' => {
                        depth -= 1;
                        if depth == 0 {
                            closes_at_end = i == b.len() - 1;
                            break;
                        }
                    }
                    _ => {}
                }
            }
            if !closes_at_end {
                return s;
            }
            s = s[1..s.len() - 1].to_string();
        }
    }

    /// What every leaf in `leaves` stands for, indexed by `LeafId`: the name of
    /// the signal a bare-identifier leaf REFERENCES, else its normalized source
    /// text. The two agree for every leaf that is not a formal argument; for a
    /// formal (`p` in `sequence s(p); p ##1 b;`) slang hands the builder the
    /// ACTUAL's expression -- the semantic node is the actual, only its syntax
    /// still reads `p` -- so the referenced symbol is what shows that the
    /// substitution happened (T12).
    fn leaf_texts(leaves: &LeafTable<'_>, tree: &SyntaxTree) -> Vec<String> {
        (0..leaves.len() as u32)
            .map(|i| {
                let e = leaves.get(LeafId(i));
                let text = if e.kind() == ExpressionKind::NamedValue
                    && let Some(sym) = e.referenced_symbol()
                {
                    sym.name().to_string()
                } else {
                    // A compound match item's value (`v += e` is `v + e` on an
                    // `LValueReference`) is synthesized by slang and has no
                    // source text; it is named by its kind so a test can still
                    // count it.
                    match e.syntax(tree) {
                        Some(node) => norm_leaf(&node.text()),
                        None => format!("<{:?}>", e.kind()),
                    }
                };
                if leaves.is_negated(LeafId(i)) {
                    // A goto gap's `!b`: named exactly as the source text `!b`
                    // would be, so a hand-written expansion compares equal (the
                    // tests use plain identifiers).
                    assert!(
                        text.chars().all(|c| c.is_alphanumeric() || c == '_'),
                        "a negated leaf over `{text}` has no source-text spelling here"
                    );
                    return format!("!{text}");
                }
                text
            })
            .collect()
    }

    /// Enumerates every accepted match of `au` spanning at most `bound`
    /// elapsed ticks (`bound + 1` letters), as words. Bounded DFS over
    /// `(state, elapsed ticks, leaf constraints so far)`; production code never
    /// walks the automaton this way (the engine steps one tick at a time per
    /// live thread). A step cap turns an accidental zero-tick cycle into a
    /// loud failure instead of a hang.
    fn accepted_lang(
        au: &ir::Automaton,
        leaves: &LeafTable<'_>,
        tree: &SyntaxTree,
        bound: u32,
    ) -> Lang {
        let mut out = Lang::new();
        if au.admits_empty {
            out.insert(Vec::new());
        }
        let mut steps = 0u64;
        // (state, elapsed ticks, [(tick, leaf text)] constraints so far)
        type Walk = (ThreadStateId, u32, Vec<(u32, String)>);
        let texts = leaf_texts(leaves, tree);
        // A walk is fully described by where it is and what it has promised
        // so far; the ORDER of those promises is an artifact of eps-edge
        // interleaving (the product automata of T11 interleave their two
        // operands' moves, which would otherwise multiply identical walks
        // exponentially). `seen` is membership-only.
        type Seen = (u32, u32, Vec<(u32, String)>);
        let mut seen: HashSet<Seen> = HashSet::new();
        let mut stack: Vec<Walk> = vec![(au.start, 0, Vec::new())];
        while let Some((state_id, ticks, cons)) = stack.pop() {
            let mut key = cons.clone();
            key.sort();
            key.dedup();
            if !seen.insert((state_id.0, ticks, key)) {
                continue;
            }
            steps += 1;
            assert!(steps < 5_000_000, "automaton walk did not terminate");
            let state = au.state(state_id);
            if state.is_accepting() {
                let mut w: Word = vec![Letter::new(); ticks as usize + 1];
                for (t, name) in &cons {
                    w[*t as usize].insert(name.clone());
                }
                out.insert(w);
            }
            for edge in &state.edges {
                let mut cons2 = cons.clone();
                if let Some(g) = edge.guard {
                    let text = &texts[g.0 as usize];
                    if text != "1" {
                        cons2.push((ticks, text.clone()));
                    }
                }
                match &edge.label {
                    ir::Transition::Epsilon => stack.push((edge.target, ticks, cons2)),
                    ir::Transition::Delay { min, max } => {
                        let hi = max.unwrap_or(bound).min(bound);
                        for k in *min..=hi {
                            if ticks + k <= bound {
                                stack.push((edge.target, ticks + k, cons2.clone()));
                            }
                        }
                    }
                    ir::Transition::Match { .. } => {}
                    // A local-variable action takes no time and constrains no
                    // leaf: the word language is over leaf TEXTS, so it walks
                    // through (the values are `sva::trace`'s, below).
                    ir::Transition::LocalVarWrite { .. }
                    | ir::Transition::LocalVarCopy { .. }
                    | ir::Transition::LocalVarStep { .. }
                    | ir::Transition::SubroutineCall { .. } => {
                        stack.push((edge.target, ticks, cons2))
                    }
                    ir::Transition::Abort { .. } => {
                        panic!("T10 builds no Abort edges")
                    }
                    ir::Transition::EndPoint { .. } => {
                        panic!("a word-language walk cannot decide an EndPoint edge")
                    }
                    ir::Transition::ClockSync { .. } => {
                        panic!("a word-language walk cannot decide a ClockSync edge")
                    }
                    ir::Transition::FirstMatchBegin { .. }
                    | ir::Transition::FirstMatchEnd { .. } => {
                        // A word-language walk has no notion of "earliest
                        // match": first_match filters matches by their END TICK
                        // against the whole evaluation attempt, which a single
                        // path cannot see. Silently walking through the
                        // markers would accept exactly the matches first_match
                        // exists to discard, so refuse loudly; first_match is
                        // checked against concrete traces instead
                        // (`sva::trace`, the T11 batteries below).
                        panic!("accepted_lang cannot interpret first_match markers")
                    }
                }
            }
        }
        out
    }

    /// Compiles `body` as the ANTECEDENT of `body |-> 1` (16.12.7: an
    /// implication's antecedent may admit an empty match, whereas a bare
    /// sequence used as a property may not -- 16.12.2 "shall not admit an
    /// empty match" -- which would make slang reject exactly the shapes this
    /// task needs to build), builds the antecedent's automaton and returns its
    /// accepted language up to `bound` ticks. `None` when slang itself
    /// rejects the source (the generated battery below includes shapes slang
    /// has its own legality diagnostics for); a `build_automaton` failure is a
    /// hard test failure, never a skip.
    fn try_lang_of(body: &str, bound: u32) -> Option<Lang> {
        with_built(body, |au, leaves, tree| {
            accepted_lang(au, leaves, tree, bound)
        })
    }

    /// The shared front end of every antecedent-compiling helper below:
    /// compiles `body |-> 1` (see [`try_lang_of`]), builds the antecedent's
    /// automaton and hands it to `f`. `None` when slang itself rejects the
    /// source; a `build_automaton` failure is a hard test failure.
    fn with_built<R>(
        body: &str,
        f: impl FnOnce(&ir::Automaton, &LeafTable<'_>, &SyntaxTree) -> R,
    ) -> Option<R> {
        with_built_in("", body, f)
    }

    /// [`with_built`] with `extra_decls` (more module-level declarations the
    /// body references -- the LRM figures' own signal names).
    fn with_built_in<R>(
        extra_decls: &str,
        body: &str,
        f: impl FnOnce(&ir::Automaton, &LeafTable<'_>, &SyntaxTree) -> R,
    ) -> Option<R> {
        let src = format!(
            "module m;\n\
             {extra_decls}\n\
             logic clk, a, b, c, d, e;\n\
             always_ff @(posedge clk) begin\n\
               assert property (@(posedge clk) {body} |-> 1);\n\
             end\n\
             endmodule\n"
        );
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(&src).unwrap();
        let design = comp.compile().unwrap();
        if design.has_fatal_errors() {
            return None;
        }
        let m = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let analysis = design.analyze(AnalysisFlags::NONE, 1).unwrap();
        let proc = analysis.procedures(m).next().unwrap();
        let assertion = analysis.assertions(proc.symbol()).next().unwrap();
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let clocking = assertion.root().as_assertion_expr().unwrap();
        let implication = clocking.children()[1].as_assertion_expr().unwrap();
        assert_eq!(implication.kind(), AssertionExprKind::Binary);
        let root = implication.children()[0].as_assertion_expr().unwrap();
        let (au, leaves) = build_automaton(root, Some(clocking.children()[0]), (&tree).into(), &m)
            .unwrap_or_else(|e| panic!("build_automaton failed for `{body}`: {e}"));
        Some(f(&au, &leaves, &tree))
    }

    fn lang_of(body: &str, bound: u32) -> Lang {
        try_lang_of(body, bound).unwrap_or_else(|| panic!("`{body}` failed to compile"))
    }

    // -- 16.9.2.1's four rules, one dedicated test each --------------------

    /// Rule 1 and the LRM's own discriminating pair, verbatim: `a[*0] ##0 b`
    /// "can never be matched", while `` `true ##0 b `` "will match during any
    /// time step when the sampled value of b is true". The pair differs ONLY
    /// in the empty operand, so this test fails if empty operands are treated
    /// as `true` (the naive reading) in either direction.
    #[test]
    fn lrm_empty_hash0_b_never_matches_but_true_hash0_b_matches_whenever_b() {
        assert_eq!(lang_of("a[*0] ##0 b", 8), Lang::new());
        assert_eq!(lang_of("1 ##0 b", 8), Lang::from([word(&[&["b"]])]));
    }

    /// Rule 2: `seq ##0 empty` does not result in a match.
    #[test]
    fn seq_hash0_empty_never_matches() {
        assert_eq!(lang_of("b ##0 a[*0]", 8), Lang::new());
    }

    /// Rule 3: `empty ##n seq` (n > 0) is `##(n-1) seq`, checked against
    /// BOTH the stated rewrite target and its explicit meaning.
    #[test]
    fn empty_hash_n_seq_is_delay_n_minus_1_seq() {
        // n = 1: `##0 b` == `b`.
        assert_eq!(lang_of("a[*0] ##1 b", 8), Lang::from([word(&[&["b"]])]));
        assert_eq!(lang_of("a[*0] ##1 b", 8), lang_of("##0 b", 8));
        // n = 2: `##1 b`, one tick later.
        assert_eq!(
            lang_of("a[*0] ##2 b", 8),
            Lang::from([word(&[&[], &["b"]])])
        );
        assert_eq!(lang_of("a[*0] ##2 b", 8), lang_of("##1 b", 8));
        // n = 4 with a compound right operand.
        assert_eq!(
            lang_of("a[*0] ##4 (b ##1 c)", 12),
            lang_of("##3 (b ##1 c)", 12)
        );
    }

    /// Rule 4: `seq ##n empty` (n > 0) is `seq ##(n-1) `true`.
    #[test]
    fn seq_hash_n_empty_is_seq_delay_n_minus_1_true() {
        // n = 1: `b ##0 1` == `b`.
        assert_eq!(lang_of("b ##1 a[*0]", 8), Lang::from([word(&[&["b"]])]));
        // n = 2: `b ##1 1` -- one extra (vacuous) tick after b.
        assert_eq!(
            lang_of("b ##2 a[*0]", 8),
            Lang::from([word(&[&["b"], &[]])])
        );
        assert_eq!(lang_of("b ##2 a[*0]", 8), lang_of("b ##1 1", 8));
        assert_eq!(lang_of("b ##3 a[*0]", 8), lang_of("b ##2 1", 8));
    }

    /// 16.9.2.1's multiple-concatenation example, verbatim: `b ##1 a[*0:1]
    /// ##2 c` is `(b ##1 a[*0] ##2 c) or (b ##1 a[*1] ##2 c)`, i.e. `(b ##2 c)
    /// or (b ##1 a ##2 c)` -- "the total execution time of the sequence is one
    /// less than when using the 1-tick interval specified by a[*1]".
    #[test]
    fn lrm_multiple_concatenation_example_matches_its_stated_simplification() {
        let got = lang_of("b ##1 a[*0:1] ##2 c", 10);
        let want_b2c = lang_of("b ##2 c", 10);
        let want_b1a2c = lang_of("b ##1 a ##2 c", 10);
        // The two simplified alternatives, spelled out (guards the helper
        // itself, not just the equality).
        assert_eq!(want_b2c, Lang::from([word(&[&["b"], &[], &["c"]])]));
        assert_eq!(
            want_b1a2c,
            Lang::from([word(&[&["b"], &["a"], &[], &["c"]])])
        );
        let expected: Lang = want_b2c.union(&want_b1a2c).cloned().collect();
        assert_eq!(got, expected);
        // One tick shorter for the empty case.
        assert_eq!(got.len(), 2);
    }

    /// Both operands empty (`empty ##n empty`): Annex F.5.2's concatenation
    /// semantics (`x y` over words, `##n` = n-1 vacuous ticks between), which
    /// the 16.9.2.1 prose rules reduce to by repeated application: `##0` no
    /// match, `##1` the empty match, `##n` (n >= 2) `n-1` vacuous ticks.
    #[test]
    fn empty_hash_n_empty() {
        let none = try_lang_of("a[*0] ##0 b[*0]", 8).unwrap();
        assert_eq!(none, Lang::new());
        let one = lang_of("a[*0] ##1 b[*0]", 8);
        assert_eq!(one, Lang::from([Vec::new()]), "empty ##1 empty = empty");
        let three = lang_of("a[*0] ##3 b[*0]", 8);
        assert_eq!(three, Lang::from([word(&[&[], &[]])]), "two vacuous ticks");
    }

    /// Empty-capable operands on both sides (`a[*0:1] ##n b[*0:1]`): every
    /// one of the four empty/nonempty combinations is a distinct accepted
    /// word, enumerated by hand for n = 0, 1, 2.
    #[test]
    fn both_operands_admit_empty_and_nonempty() {
        assert_eq!(
            lang_of("a[*0:1] ##0 b[*0:1]", 8),
            Lang::from([word(&[&["a", "b"]])]),
            "##0 needs both operands nonempty (rules 1-2), fusing a and b into one tick"
        );
        assert_eq!(
            lang_of("a[*0:1] ##1 b[*0:1]", 8),
            Lang::from([
                Vec::new(),              // empty ##1 empty
                word(&[&["b"]]),         // empty ##1 b
                word(&[&["a"]]),         // a ##1 empty
                word(&[&["a"], &["b"]]), // a ##1 b
            ])
        );
        assert_eq!(
            lang_of("a[*0:1] ##2 b[*0:1]", 8),
            Lang::from([
                word(&[&[]]),                 // empty ##2 empty = one vacuous tick
                word(&[&[], &["b"]]),         // empty ##2 b = ##1 b
                word(&[&["a"], &[]]),         // a ##2 empty = a ##1 true
                word(&[&["a"], &[], &["b"]]), // a ##2 b
            ])
        );
    }

    /// A repeated unit that itself admits an empty match: `(a[*0:1])[*2]` is
    /// `empty/a`, `##1`-concatenated twice -- the empty word, `a`, and
    /// `a ##1 a`.
    #[test]
    fn repetition_of_a_unit_that_admits_empty() {
        assert_eq!(
            lang_of("(a[*0:1])[*2]", 8),
            Lang::from([Vec::new(), word(&[&["a"]]), word(&[&["a"], &["a"]])])
        );
    }

    // -- ##N / ##[m:n] / ##[*] / ##[+] shapes -------------------------------

    #[test]
    fn leading_cycle_delay() {
        assert_eq!(lang_of("##2 b", 8), Lang::from([word(&[&[], &[], &["b"]])]));
        assert_eq!(lang_of("##0 b", 8), Lang::from([word(&[&["b"]])]));
        assert_eq!(
            lang_of("##[1:3] a ##1 b", 8),
            Lang::from([
                word(&[&[], &["a"], &["b"]]),
                word(&[&[], &[], &["a"], &["b"]]),
                word(&[&[], &[], &[], &["a"], &["b"]]),
            ])
        );
    }

    #[test]
    fn ranged_delay_includes_zero_as_fusion() {
        assert_eq!(
            lang_of("a ##[0:2] b", 8),
            Lang::from([
                word(&[&["a", "b"]]),
                word(&[&["a"], &["b"]]),
                word(&[&["a"], &[], &["b"]]),
            ])
        );
    }

    /// `##[*]` is `##[0:$]` and `##[+]` is `##[1:$]` (16.7), both in the
    /// infix and the leading position.
    #[test]
    fn star_and_plus_delay_are_zero_and_one_to_dollar() {
        assert_eq!(lang_of("a ##[*] b", 6), lang_of("a ##[0:$] b", 6));
        assert_eq!(lang_of("a ##[+] b", 6), lang_of("a ##[1:$] b", 6));
        assert_eq!(lang_of("##[*] b", 6), lang_of("##[0:$] b", 6));
        assert_eq!(lang_of("##[+] b", 6), lang_of("##[1:$] b", 6));
        // `[*]` includes the same-tick fusion, `[+]` does not.
        assert!(lang_of("a ##[*] b", 6).contains(&word(&[&["a", "b"]])));
        assert!(!lang_of("a ##[+] b", 6).contains(&word(&[&["a", "b"]])));
        // Every length from the minimum up to the bound is reachable (a true
        // unbounded window, not one bonus step).
        assert_eq!(lang_of("a ##[+] b", 6).len(), 6);
        assert_eq!(lang_of("a ##[*] b", 6).len(), 7);
    }

    #[test]
    fn fused_chain() {
        assert_eq!(
            lang_of("a ##0 b ##0 c", 4),
            Lang::from([word(&[&["a", "b", "c"]])])
        );
    }

    /// A parenthesized concatenation as an operand of an outer `##` (slang
    /// binds it as a `SequenceConcat` whose syntax node is the paren node,
    /// not a `DelayedSequenceExpr`).
    #[test]
    fn parenthesized_concat_operands() {
        let want = Lang::from([word(&[&["a"], &["b"], &[], &["c"]])]);
        assert_eq!(lang_of("(a ##1 b) ##2 c", 8), want);
        assert_eq!(lang_of("((a ##1 b)) ##2 c", 8), want);
        assert_eq!(lang_of("a ##1 (b ##2 c)", 8), lang_of("a ##1 b ##2 c", 8));
        assert_eq!(lang_of("(a ##1 b)", 8), lang_of("a ##1 b", 8));
        assert_eq!(
            lang_of("a ##1 (b[*0:1]) ##1 c", 8),
            lang_of("a ##1 b[*0:1] ##1 c", 8)
        );
        assert_eq!(
            lang_of("a ##1 ((b ##1 c)[*0:1]) ##1 a", 8),
            lang_of("a ##1 (b ##1 c)[*0:1] ##1 a", 8)
        );
    }

    /// A reversed delay range is slang-legal source only if slang accepts it
    /// at all; if it does, the builder must reject it by name, not wrap.
    #[test]
    fn reversed_delay_range_is_a_named_error_or_a_slang_error() {
        let src = "module m;\nlogic clk, a, b;\nalways_ff @(posedge clk) begin\n \
                   assert property (@(posedge clk) a ##[3:1] b);\nend\nendmodule\n";
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(src).unwrap();
        let design = comp.compile().unwrap();
        if design.has_fatal_errors() {
            return; // slang's own diagnostic already rejects it
        }
        let err = automaton_err("", "a ##[3:1] b");
        assert!(err.message.contains("min"), "error was: {err}");
    }

    // -- generated differential battery vs the Annex F reference ------------

    /// The reference sequence language: a syntax tree rendered to SV source
    /// AND interpreted by the Annex F.5.2 word semantics below.
    #[derive(Clone, Debug)]
    enum Rx {
        Leaf(&'static str),
        Cat(Box<Rx>, Dl, Box<Rx>),
        Lead(Dl, Box<Rx>),
        Rep(Box<Rx>, Rp),
        Paren(Box<Rx>),
        /// T11: `(l) op (r)` for the binary sequence operators.
        Bin(Box<Rx>, SeqOp, Box<Rx>),
        /// T11: `(cond) throughout (s)`; `cond` is a Boolean leaf's source text.
        Thr(&'static str, Box<Rx>),
        /// T11: `first_match(s)`.
        First(Box<Rx>),
    }

    /// T11: the binary sequence operators (16.9.5-16.9.7, 16.9.10).
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum SeqOp {
        And,
        Or,
        Intersect,
        Within,
    }

    impl SeqOp {
        fn text(self) -> &'static str {
            match self {
                SeqOp::And => "and",
                SeqOp::Or => "or",
                SeqOp::Intersect => "intersect",
                SeqOp::Within => "within",
            }
        }
    }

    /// A `##` delay: `[min, max]` (`None` = `$`), plus its source spelling.
    #[derive(Clone, Copy, Debug)]
    struct Dl {
        min: u32,
        max: Option<u32>,
        text: &'static str,
    }

    /// A `[*...]` repetition: `[min, max]`, plus its source spelling.
    #[derive(Clone, Copy, Debug)]
    struct Rp {
        min: u32,
        max: Option<u32>,
        text: &'static str,
    }

    const DELAYS: &[Dl] = &[
        Dl {
            min: 0,
            max: Some(0),
            text: "##0",
        },
        Dl {
            min: 1,
            max: Some(1),
            text: "##1",
        },
        Dl {
            min: 2,
            max: Some(2),
            text: "##2",
        },
        Dl {
            min: 3,
            max: Some(3),
            text: "##3",
        },
        Dl {
            min: 0,
            max: Some(2),
            text: "##[0:2]",
        },
        Dl {
            min: 1,
            max: Some(3),
            text: "##[1:3]",
        },
        Dl {
            min: 2,
            max: None,
            text: "##[2:$]",
        },
        Dl {
            min: 0,
            max: None,
            text: "##[*]",
        },
        Dl {
            min: 1,
            max: None,
            text: "##[+]",
        },
    ];

    const REPS: &[Rp] = &[
        Rp {
            min: 0,
            max: Some(0),
            text: "[*0]",
        },
        Rp {
            min: 1,
            max: Some(1),
            text: "[*1]",
        },
        Rp {
            min: 2,
            max: Some(2),
            text: "[*2]",
        },
        Rp {
            min: 0,
            max: Some(1),
            text: "[*0:1]",
        },
        Rp {
            min: 0,
            max: Some(2),
            text: "[*0:2]",
        },
        Rp {
            min: 1,
            max: Some(3),
            text: "[*1:3]",
        },
        Rp {
            min: 0,
            max: None,
            text: "[*]",
        },
        Rp {
            min: 1,
            max: None,
            text: "[+]",
        },
        Rp {
            min: 2,
            max: None,
            text: "[*2:$]",
        },
    ];

    /// Left-folded `##` chain rendering: an operand renders unparenthesized
    /// only where the grammar's left-recursive `sequence_expr ##d
    /// sequence_expr` makes that equal to the tree's own shape.
    fn render(rx: &Rx) -> String {
        match rx {
            Rx::Leaf(n) => n.to_string(),
            Rx::Paren(r) => format!("({})", render(r)),
            Rx::Lead(d, r) => format!("{} {}", d.text, render_operand(r)),
            Rx::Cat(l, d, r) => format!("{} {} {}", render_left(l), d.text, render_operand(r)),
            Rx::Rep(r, p) => match **r {
                Rx::Leaf(_) => format!("{}{}", render(r), p.text),
                _ => format!("({}){}", render(r), p.text),
            },
            // Fully parenthesized: the operators' relative precedence is not
            // under test here, only their semantics.
            Rx::Bin(l, op, r) => format!("(({}) {} ({}))", render(l), op.text(), render(r)),
            Rx::Thr(c, r) => format!("(({c}) throughout ({}))", render(r)),
            Rx::First(r) => format!("first_match({})", render(r)),
        }
    }

    /// Left operand of a `##`: a chain or leading delay continues the same
    /// left fold; anything else is itself an atom.
    fn render_left(rx: &Rx) -> String {
        render(rx)
    }

    /// Right operand of a `##` (or the operand of a leading delay): anything
    /// that is itself a chain/delay must be parenthesized to keep its shape.
    fn render_operand(rx: &Rx) -> String {
        match rx {
            Rx::Cat(..) | Rx::Lead(..) => format!("({})", render(rx)),
            _ => render(rx),
        }
    }

    fn cat_words(l1: &Lang, d: Dl, l2: &Lang, cap: usize) -> Lang {
        let mut out = Lang::new();
        // `k` reaches `cap + 1`: two empty words joined by `##(cap + 1)` are
        // `1[*cap]`, a word of `cap` letters.
        let hi = d.max.unwrap_or(cap as u32 + 1).min(cap as u32 + 1);
        for x in l1 {
            for y in l2 {
                for k in d.min..=hi {
                    let w: Word = if k == 0 {
                        // F.5.2: `xyz` with `|y| = 1`, `xy |= R1`, `yz |= R2`:
                        // the last letter of the left word is the first
                        // letter of the right word. Needs both nonempty.
                        if x.is_empty() || y.is_empty() {
                            continue;
                        }
                        let mut w = x[..x.len() - 1].to_vec();
                        let fused: Letter = x[x.len() - 1].union(&y[0]).cloned().collect();
                        w.push(fused);
                        w.extend_from_slice(&y[1..]);
                        w
                    } else {
                        // `R1 ##k R2` = `R1 ##1 1[*k-1] ##1 R2`: plain word
                        // concatenation with `k - 1` vacuous letters between.
                        let mut w = x.clone();
                        w.extend(std::iter::repeat_n(Letter::new(), (k - 1) as usize));
                        w.extend_from_slice(y);
                        w
                    };
                    if w.len() <= cap {
                        out.insert(w);
                    }
                }
            }
        }
        out
    }

    fn lang_ref(rx: &Rx, cap: usize) -> Lang {
        match rx {
            Rx::Leaf("1") => Lang::from([vec![Letter::new()]]),
            Rx::Leaf(n) => Lang::from([vec![Letter::from([n.to_string()])]]),
            Rx::Paren(r) => lang_ref(r, cap),
            Rx::Cat(l, d, r) => cat_words(&lang_ref(l, cap), *d, &lang_ref(r, cap), cap),
            Rx::Lead(d, r) => {
                // `##[m:n] R` = `1[*m:n] ##1 R` (F.3.4.2.2).
                let r = lang_ref(r, cap);
                let mut out = Lang::new();
                let hi = d.max.unwrap_or(cap as u32).min(cap as u32);
                for k in d.min..=hi {
                    for y in &r {
                        let mut w: Word = vec![Letter::new(); k as usize];
                        w.extend_from_slice(y);
                        if w.len() <= cap {
                            out.insert(w);
                        }
                    }
                }
                out
            }
            Rx::Rep(r, p) => {
                // `R[*0]` = the empty word; `R[*k]` = `R[*k-1] ##1 R`.
                let unit = lang_ref(r, cap);
                let one = Dl {
                    min: 1,
                    max: Some(1),
                    text: "##1",
                };
                let mut pow = Lang::from([Vec::new()]);
                let mut out = Lang::new();
                let top = p.max.unwrap_or(cap as u32 + 1).min(cap as u32 + 1);
                if p.min == 0 {
                    out.extend(pow.iter().cloned());
                }
                for k in 1..=top {
                    pow = cat_words(&pow, one, &unit, cap);
                    if k >= p.min {
                        out.extend(pow.iter().cloned());
                    }
                }
                out
            }
            Rx::Bin(l, op, r) => {
                let (l, r) = (lang_ref(l, cap), lang_ref(r, cap));
                let one = Dl {
                    min: 1,
                    max: Some(1),
                    text: "##1",
                };
                match op {
                    SeqOp::Or => l.union(&r).cloned().collect(),
                    SeqOp::Intersect => intersect_words(&l, &r),
                    // Annex F.3.4.2.4's definition, verbatim:
                    //   r1 and r2 = ((r1 ##1 1[*0:$]) intersect r2)
                    //               or (r1 intersect (r2 ##1 1[*0:$]))
                    SeqOp::And => {
                        let pad = true_run_words(cap);
                        let first = intersect_words(&cat_words(&l, one, &pad, cap), &r);
                        let second = intersect_words(&l, &cat_words(&r, one, &pad, cap));
                        first.union(&second).cloned().collect()
                    }
                    // 16.9.10: `s1 within s2` is
                    //   (1[*0:$] ##1 s1 ##1 1[*0:$]) intersect s2
                    // (`l` is s1, `r` is s2).
                    SeqOp::Within => {
                        let pad = true_run_words(cap);
                        let wrapped = cat_words(&cat_words(&pad, one, &l, cap), one, &pad, cap);
                        intersect_words(&wrapped, &r)
                    }
                }
            }
            Rx::Thr(c, r) => {
                // 16.9.9: `exp throughout seq` is `(exp)[*0:$] intersect seq`.
                let run: Lang = (0..=cap)
                    .map(|k| vec![Letter::from([c.to_string()]); k])
                    .collect();
                intersect_words(&run, &lang_ref(r, cap))
            }
            Rx::First(_) => panic!(
                "first_match is a filter over match END TICKS of an attempt, which a word \
                 language cannot express; it is checked against concrete traces"
            ),
        }
    }

    /// `1[*0:$]` as words of at most `cap` letters: every run of vacuous ticks
    /// (the LRM's `` `true ``), the empty run included.
    fn true_run_words(cap: usize) -> Lang {
        (0..=cap).map(|k| vec![Letter::new(); k]).collect()
    }

    /// Annex F.5.2's `intersect`: both operands match the SAME word. Over
    /// constraint-set words that is equal length, letter-wise union.
    fn intersect_words(l: &Lang, r: &Lang) -> Lang {
        let mut out = Lang::new();
        for x in l {
            for y in r {
                if x.len() == y.len() {
                    out.insert(
                        x.iter()
                            .zip(y)
                            .map(|(p, q)| p.union(q).cloned().collect())
                            .collect(),
                    );
                }
            }
        }
        out
    }

    /// Deterministic generator (a fixed-seed LCG: no `rand` dependency, and
    /// the battery never changes between runs).
    struct Lcg(u64);

    impl Lcg {
        fn next(&mut self, n: usize) -> usize {
            self.0 = self
                .0
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((self.0 >> 33) as usize) % n
        }
    }

    fn gen_rx(g: &mut Lcg, depth: u32) -> Rx {
        const LEAVES: &[&str] = &["a", "b", "c", "1"];
        let leaf = |g: &mut Lcg| Rx::Leaf(LEAVES[g.next(LEAVES.len())]);
        if depth == 0 {
            return leaf(g);
        }
        match g.next(10) {
            0..=1 => leaf(g),
            2..=5 => {
                // A left-folded chain of 2-3 operands.
                let mut acc = gen_rx(g, depth - 1);
                for _ in 0..(1 + g.next(2)) {
                    let d = DELAYS[g.next(DELAYS.len())];
                    let rhs = gen_rx(g, depth - 1);
                    acc = Rx::Cat(Box::new(acc), d, Box::new(rhs));
                }
                acc
            }
            6 => Rx::Lead(DELAYS[g.next(DELAYS.len())], Box::new(gen_rx(g, depth - 1))),
            7..=8 => Rx::Rep(Box::new(gen_rx(g, depth - 1)), REPS[g.next(REPS.len())]),
            _ => Rx::Paren(Box::new(gen_rx(g, depth - 1))),
        }
    }

    /// Number of `##` concatenations in `rx` with at least one operand that
    /// admits the empty match -- the sites where 16.9.2.1's rules fire.
    fn concats_with_empty_operand(rx: &Rx, cap: usize) -> usize {
        let admits_empty = |r: &Rx| lang_ref(r, cap).contains(&Vec::new());
        match rx {
            Rx::Leaf(_) => 0,
            Rx::Paren(r) | Rx::Rep(r, _) | Rx::Thr(_, r) | Rx::First(r) => {
                concats_with_empty_operand(r, cap)
            }
            Rx::Lead(_, r) => concats_with_empty_operand(r, cap),
            Rx::Bin(l, _, r) => {
                concats_with_empty_operand(l, cap) + concats_with_empty_operand(r, cap)
            }
            Rx::Cat(l, _, r) => {
                usize::from(admits_empty(l) || admits_empty(r))
                    + concats_with_empty_operand(l, cap)
                    + concats_with_empty_operand(r, cap)
            }
        }
    }

    /// The differential battery: 1000 generated sequences (fixed seed), every
    /// one built into an automaton and compared, match for match, against the
    /// Annex F reference language. This is what pins the empty-match algebra
    /// in every concatenation position (first/middle/last operand, both
    /// operands, nested through repetition and parentheses) at once.
    #[test]
    fn generated_sequences_match_the_annex_f_reference() {
        const BOUND: u32 = 6;
        let mut g = Lcg(0x5eed_5eed_5eed_5eed);
        let (mut compared, mut skipped, mut with_empty, mut empty_sites) = (0usize, 0, 0, 0);
        for _ in 0..1000 {
            let rx = gen_rx(&mut g, 3);
            let src = render(&rx);
            let want = lang_ref(&rx, BOUND as usize + 1);
            match try_lang_of(&src, BOUND) {
                None => skipped += 1,
                Some(got) => {
                    assert_eq!(got, want, "automaton vs Annex F reference for `{src}`");
                    compared += 1;
                    with_empty += usize::from(want.contains(&Vec::new()));
                    empty_sites += concats_with_empty_operand(&rx, BOUND as usize + 1);
                }
            }
        }
        // The battery must actually exercise the empty-match algebra, not
        // vacuously pass on a generator that produced nothing relevant.
        assert!(
            compared >= 700,
            "only {compared} compared, {skipped} skipped"
        );
        assert!(
            with_empty >= 40,
            "only {with_empty} sequences admit an empty match"
        );
        assert!(
            empty_sites >= 150,
            "only {empty_sites} concatenations had an empty-admitting operand"
        );
    }

    // ======================================================================
    // T11: `and` / `intersect` / `or` / `first_match` / `throughout` /
    // `within` (LRM 16.9.5-16.9.10).
    //
    // Three oracles, none of which looks at the builder:
    //  1. hand-derived word languages (this block's first half) -- every
    //     expected set is spelled out from the LRM text or Annex F;
    //  2. the Annex F word-language reference `lang_ref` (operators other
    //     than `first_match`, which no word language can express);
    //  3. `ref_lens`, a trace-level reference over CONCRETE traces that also
    //     covers `first_match`, driven by `sva::trace::attempt` on the
    //     automaton side, plus the LRM's own figures 16-5..16-13.
    // ======================================================================

    // -- or ---------------------------------------------------------------

    /// 16.9.7: "the set of matches of te1 or te2 is the union of the set of
    /// matches of te1 with the set of matches of te2".
    #[test]
    fn or_is_the_union_of_the_operands_matches() {
        assert_eq!(
            lang_of("(a or b)", 8),
            Lang::from([word(&[&["a"]]), word(&[&["b"]])])
        );
        assert_eq!(
            lang_of("((a ##1 b) or (c ##2 a))", 8),
            Lang::from([word(&[&["a"], &["b"]]), word(&[&["c"], &[], &["a"]])])
        );
        // The empty match is a member of the union.
        assert_eq!(
            lang_of("(a[*0] or b)", 8),
            Lang::from([Vec::new(), word(&[&["b"]])])
        );
        // A set union: identical operands do not double up.
        assert_eq!(lang_of("(a or a)", 8), lang_of("a", 8));
        // As an operand of a concatenation it distributes.
        assert_eq!(
            lang_of("(a or b) ##1 c", 8),
            Lang::from([word(&[&["a"], &["c"]]), word(&[&["b"], &["c"]])])
        );
        assert_eq!(
            lang_of("c ##1 (a or (b ##1 b))", 8),
            Lang::from([word(&[&["c"], &["a"]]), word(&[&["c"], &["b"], &["b"]])])
        );
    }

    // -- intersect --------------------------------------------------------

    /// 16.9.6: both operands match and the matches have the same length.
    #[test]
    fn intersect_pairs_matches_of_the_same_length() {
        // `a ##[1:3] b` has lengths 2, 3, 4; `c ##2 d` has length 3.
        assert_eq!(
            lang_of("((a ##[1:3] b) intersect (c ##2 d))", 8),
            Lang::from([word(&[&["a", "c"], &[], &["b", "d"]])])
        );
        assert_eq!(
            lang_of("(a[*1:3] intersect b[*2])", 8),
            Lang::from([word(&[&["a", "b"], &["a", "b"]])])
        );
        // Different, fixed lengths never pair.
        assert_eq!(lang_of("(a[*2] intersect b[*3])", 8), Lang::new());
        assert_eq!(lang_of("(a intersect (b ##1 c))", 8), Lang::new());
        // Unbounded against a window: every common length.
        assert_eq!(
            lang_of("(a[*] intersect b[*2:3])", 8),
            Lang::from([
                word(&[&["a", "b"], &["a", "b"]]),
                word(&[&["a", "b"], &["a", "b"], &["a", "b"]])
            ])
        );
        // The same operand twice is the operand itself (both samples hold).
        assert_eq!(
            lang_of("((a ##1 b) intersect (a ##1 b))", 8),
            lang_of("a ##1 b", 8)
        );
    }

    /// 16.9.2.1 through `intersect`: an empty match has length 0, so it pairs
    /// with another empty match and with nothing else.
    #[test]
    fn intersect_of_empty_matches() {
        assert_eq!(
            lang_of("(a[*0] intersect b[*0])", 8),
            Lang::from([Vec::new()])
        );
        assert_eq!(lang_of("(a[*0] intersect b)", 8), Lang::new());
        assert_eq!(lang_of("(a[*0:2] intersect b[*0:1])", 8), {
            Lang::from([Vec::new(), word(&[&["a", "b"]])])
        });
    }

    // -- and --------------------------------------------------------------

    /// 16.9.5: both operands match, from the same start; the composite ends
    /// where the LATER operand ends. (Annex F.3.4.2.4 spells it out as two
    /// intersects over `##1 1[*0:$]`-padded operands; the expected sets
    /// below are that formula worked by hand.)
    #[test]
    fn and_ends_where_the_later_operand_ends() {
        assert_eq!(lang_of("(a and b)", 8), Lang::from([word(&[&["a", "b"]])]));
        // Lengths 2 and 3: the shorter is padded to the longer.
        assert_eq!(
            lang_of("((a ##1 b) and (c ##2 d))", 8),
            Lang::from([word(&[&["a", "c"], &["b"], &["d"]])])
        );
        // ...in either operand order.
        assert_eq!(
            lang_of("((c ##2 d) and (a ##1 b))", 8),
            Lang::from([word(&[&["a", "c"], &["b"], &["d"]])])
        );
        assert_eq!(
            lang_of("(a and (b ##[1:2] c))", 8),
            Lang::from([
                word(&[&["a", "b"], &["c"]]),
                word(&[&["a", "b"], &[], &["c"]])
            ])
        );
    }

    /// An empty operand of `and` is "already matched": `ε and R` has R's
    /// matches (Annex F.3.4.2.4 applied to the empty word), and `ε and ε` is
    /// the empty match.
    #[test]
    fn and_with_an_empty_operand() {
        assert_eq!(lang_of("(a[*0] and b)", 8), Lang::from([word(&[&["b"]])]));
        assert_eq!(
            lang_of("(a[*0] and (b ##1 c))", 8),
            Lang::from([word(&[&["b"], &["c"]])])
        );
        assert_eq!(lang_of("(a[*0] and b[*0])", 8), Lang::from([Vec::new()]));
        assert_eq!(
            lang_of("(a[*0:1] and b[*0:1])", 8),
            Lang::from([
                Vec::new(),
                word(&[&["a"]]),
                word(&[&["b"]]),
                word(&[&["a", "b"]])
            ])
        );
    }

    /// Annex F.3.4.2.4's definition, as SOURCE TEXT:
    /// `r1 and r2 = ((r1 ##1 1[*0:$]) intersect r2) or (r1 intersect (r2 ##1
    /// 1[*0:$]))`. The built `and` must equal the built rewrite.
    #[test]
    fn and_equals_its_annex_f_rewrite() {
        let operands = [
            "a",
            "a ##2 b",
            "a ##[1:3] b",
            "a[*0:2]",
            "(a ##1 b)[*1:2]",
            "a[*0] ##[0:2] b",
            "a ##[2:$] b",
        ];
        for r1 in operands {
            for r2 in ["c", "c ##1 d", "c[*0:1]", "(c ##2 d)[*1:2]", "c ##[1:3] d"] {
                let and = lang_of(&format!("(({r1}) and ({r2}))"), 7);
                let rewrite = lang_of(
                    &format!(
                        "((({r1}) ##1 1[*0:$]) intersect ({r2})) or \
                         (({r1}) intersect (({r2}) ##1 1[*0:$]))"
                    ),
                    7,
                );
                assert_eq!(and, rewrite, "`({r1}) and ({r2})`");
            }
        }
    }

    // -- throughout / within ---------------------------------------------

    /// 16.9.9: `exp throughout seq` is `(exp)[*0:$] intersect seq`.
    #[test]
    fn throughout_holds_the_condition_on_every_tick() {
        assert_eq!(
            lang_of("(a throughout (b ##2 c))", 8),
            Lang::from([word(&[&["a", "b"], &["a"], &["a", "c"]])])
        );
        assert_eq!(
            lang_of("(a throughout b[*0:2])", 8),
            Lang::from([
                Vec::new(),
                word(&[&["a", "b"]]),
                word(&[&["a", "b"], &["a", "b"]])
            ])
        );
        assert_eq!(lang_of("(a throughout b[*0])", 8), Lang::from([Vec::new()]));
        // Without parentheses around the whole expression, too.
        assert_eq!(
            lang_of("a throughout b ##1 c", 8),
            lang_of("(a throughout (b ##1 c))", 8)
        );
    }

    #[test]
    fn throughout_equals_its_rewrite() {
        for s in [
            "b",
            "b ##2 c",
            "b[*0:2]",
            "(b ##1 c)[*1:3]",
            "b ##[1:3] c",
            "b ##[2:$] c",
        ] {
            assert_eq!(
                lang_of(&format!("(a throughout ({s}))"), 8),
                lang_of(&format!("(a[*0:$] intersect ({s}))"), 8),
                "`a throughout ({s})`"
            );
        }
    }

    /// 16.9.10: `seq1 within seq2` is `(1[*0:$] ##1 seq1 ##1 1[*0:$])
    /// intersect seq2`: seq1 matches along a sub-interval of seq2's match.
    /// The operand order is part of the contract -- `a within b` is "a inside
    /// b", never the reverse.
    #[test]
    fn within_places_the_left_operand_inside_the_right() {
        assert_eq!(
            lang_of("(a within (b ##3 c))", 8),
            Lang::from([
                word(&[&["a", "b"], &[], &[], &["c"]]),
                word(&[&["b"], &["a"], &[], &["c"]]),
                word(&[&["b"], &[], &["a"], &["c"]]),
                word(&[&["b"], &[], &[], &["a", "c"]]),
            ])
        );
        // Reversed, the 4-tick sequence cannot sit inside a 1-tick one.
        assert_eq!(lang_of("((b ##3 c) within a)", 8), Lang::new());
        // Equal length: exactly the intersect.
        assert_eq!(
            lang_of("((a ##1 b) within (c ##1 d))", 8),
            Lang::from([word(&[&["a", "c"], &["b", "d"]])])
        );
        // An empty seq1 sits anywhere: `ε within seq2` is seq2.
        assert_eq!(
            lang_of("(a[*0] within b[*0:1])", 8),
            Lang::from([Vec::new(), word(&[&["b"]])])
        );
    }

    #[test]
    fn within_equals_its_rewrite() {
        for s1 in ["a", "a ##1 b", "a[*0:2]", "a ##[1:2] b"] {
            for s2 in ["c", "c ##3 d", "c[*0:3]", "c ##[1:4] d", "(c ##1 d)[*1:3]"] {
                assert_eq!(
                    lang_of(&format!("(({s1}) within ({s2}))"), 7),
                    lang_of(
                        &format!("((1[*0:$] ##1 ({s1}) ##1 1[*0:$]) intersect ({s2}))"),
                        7
                    ),
                    "`({s1}) within ({s2})`"
                );
            }
        }
    }

    // -- generated differential battery vs the Annex F reference ----------

    /// Operators other than `first_match` (a word language cannot express it).
    fn gen_rx11(g: &mut Lcg, depth: u32, first: bool) -> Rx {
        const LEAVES: &[&str] = &["a", "b", "c", "1"];
        const CONDS: &[&str] = &["a", "b", "c"];
        const OPS: &[SeqOp] = &[SeqOp::And, SeqOp::Or, SeqOp::Intersect, SeqOp::Within];
        let leaf = |g: &mut Lcg| Rx::Leaf(LEAVES[g.next(LEAVES.len())]);
        if depth == 0 {
            return leaf(g);
        }
        match g.next(14) {
            0..=1 => leaf(g),
            2..=3 => {
                let mut acc = gen_rx11(g, depth - 1, first);
                for _ in 0..(1 + g.next(2)) {
                    let d = DELAYS[g.next(DELAYS.len())];
                    let rhs = gen_rx11(g, depth - 1, first);
                    acc = Rx::Cat(Box::new(acc), d, Box::new(rhs));
                }
                acc
            }
            4 => Rx::Lead(
                DELAYS[g.next(DELAYS.len())],
                Box::new(gen_rx11(g, depth - 1, first)),
            ),
            5 => {
                // Half the repetitions can vanish: the empty-match paths of
                // the operators are the subtle ones.
                let zero: Vec<Rp> = REPS.iter().copied().filter(|r| r.min == 0).collect();
                let rep = if g.next(2) == 0 {
                    zero[g.next(zero.len())]
                } else {
                    REPS[g.next(REPS.len())]
                };
                Rx::Rep(Box::new(gen_rx11(g, depth - 1, first)), rep)
            }
            6 => Rx::Paren(Box::new(gen_rx11(g, depth - 1, first))),
            7..=10 => Rx::Bin(
                Box::new(gen_rx11(g, depth - 1, first)),
                OPS[g.next(OPS.len())],
                Box::new(gen_rx11(g, depth - 1, first)),
            ),
            11 => Rx::Thr(
                CONDS[g.next(CONDS.len())],
                Box::new(gen_rx11(g, depth - 1, first)),
            ),
            _ if first => Rx::First(Box::new(gen_rx11(g, depth - 1, first))),
            _ => Rx::Bin(
                Box::new(gen_rx11(g, depth - 1, first)),
                OPS[g.next(OPS.len())],
                Box::new(gen_rx11(g, depth - 1, first)),
            ),
        }
    }

    /// Counts the operators of each kind in `rx`: (and, or, intersect, within,
    /// throughout, first_match).
    fn op_census(rx: &Rx, c: &mut [usize; 6]) {
        match rx {
            Rx::Leaf(_) => {}
            Rx::Paren(r) | Rx::Rep(r, _) | Rx::Lead(_, r) => op_census(r, c),
            Rx::Cat(l, _, r) => {
                op_census(l, c);
                op_census(r, c);
            }
            Rx::Bin(l, op, r) => {
                c[match op {
                    SeqOp::And => 0,
                    SeqOp::Or => 1,
                    SeqOp::Intersect => 2,
                    SeqOp::Within => 3,
                }] += 1;
                op_census(l, c);
                op_census(r, c);
            }
            Rx::Thr(_, r) => {
                c[4] += 1;
                op_census(r, c);
            }
            Rx::First(r) => {
                c[5] += 1;
                op_census(r, c);
            }
        }
    }

    /// 600 generated sequences over `and`/`or`/`intersect`/`within`/
    /// `throughout` (nested in each other and in concatenations and
    /// repetitions), each built and compared match for match, empty match
    /// included, against the Annex F reference language.
    #[test]
    fn generated_sequence_operators_match_the_annex_f_reference() {
        const BOUND: u32 = 6;
        let mut g = Lcg(0x0711_0711_a5a5_5a5a);
        let (mut compared, mut skipped, mut with_empty) = (0usize, 0, 0);
        let mut census = [0usize; 6];
        for _ in 0..600 {
            let rx = gen_rx11(&mut g, 3, false);
            let src = render(&rx);
            let want = lang_ref(&rx, BOUND as usize + 1);
            match try_lang_of(&src, BOUND) {
                None => skipped += 1,
                Some(got) => {
                    assert_eq!(got, want, "automaton vs Annex F reference for `{src}`");
                    compared += 1;
                    with_empty += usize::from(want.contains(&Vec::new()));
                    op_census(&rx, &mut census);
                }
            }
        }
        assert!(
            compared >= 450,
            "only {compared} compared, {skipped} skipped"
        );
        assert!(with_empty >= 40, "only {with_empty} admit an empty match");
        for (name, n) in ["and", "or", "intersect", "within", "throughout"]
            .iter()
            .zip(census)
        {
            assert!(n >= 60, "only {n} `{name}` operators exercised");
        }
    }

    // -- concrete traces ---------------------------------------------------

    /// A concrete trace: one row of 4-state samples per signal (keyed by the
    /// leaf's normalized source text, see [`norm_leaf`]); the constant `1`
    /// needs no row. Ticks are `0..len`. A sample is `Some(known)` or `None`
    /// for `x`/`z`.
    struct Trace {
        rows: BTreeMap<String, Vec<Option<bool>>>,
        len: u32,
    }

    impl Trace {
        /// `rows` are `(leaf text, "0110...")`, a digit being `0`, `1` or `x`;
        /// all rows have the same length.
        fn new(rows: &[(&str, &str)]) -> Trace {
            let mut map = BTreeMap::new();
            let mut len = None;
            for (name, bits) in rows {
                let row: Vec<Option<bool>> = bits
                    .chars()
                    .filter(|c| !c.is_whitespace())
                    .map(|c| match c {
                        '0' => Some(false),
                        '1' => Some(true),
                        'x' => None,
                        other => panic!("trace row `{name}`: bad digit {other:?}"),
                    })
                    .collect();
                assert_eq!(*len.get_or_insert(row.len()), row.len(), "row `{name}`");
                map.insert(norm_leaf(name), row);
            }
            Trace {
                rows: map,
                len: len.expect("a trace needs at least one row") as u32,
            }
        }

        /// A trace numbered like the LRM's figures: tick 1 is the first digit,
        /// tick 0 exists (all false) so a tick number IS an index.
        fn lrm(rows: &[(&str, &str)]) -> Trace {
            let padded: Vec<(&str, String)> =
                rows.iter().map(|(n, b)| (*n, format!("0{b}"))).collect();
            let borrowed: Vec<(&str, &str)> =
                padded.iter().map(|(n, b)| (*n, b.as_str())).collect();
            Trace::new(&borrowed)
        }

        /// The guard value of the leaf `text` at `tick`, as the compiled leaf
        /// predicate gives it: a Boolean context makes an `x` false, and `!b`
        /// (a leaf spelled with a leading `!`, which [`leaf_texts`] also gives
        /// the negated leaf of a goto gap) is 4-state negation THEN that
        /// collapse, so it holds only where `b` is known false.
        fn value(&self, text: &str, tick: u32) -> bool {
            if text == "1" {
                return true;
            }
            // A row keyed by the whole text wins (`!burst_mode` given as a signal
            // of its own); otherwise a leading `!` negates the row of the rest.
            let (name, negated) = match text.strip_prefix('!') {
                Some(inner) if !self.rows.contains_key(text) => (inner, true),
                _ => (text, false),
            };
            let row = self
                .rows
                .get(name)
                .unwrap_or_else(|| panic!("trace has no row for leaf `{name}`"));
            match row.get(tick as usize).copied().flatten() {
                Some(known) => known != negated,
                None => false,
            }
        }
    }

    fn run_attempt(
        au: &ir::Automaton,
        texts: &[String],
        tr: &Trace,
        start: u32,
    ) -> (bool, BTreeSet<u32>) {
        let r = trace::attempt(au, start, tr.len, &|id, t| {
            tr.value(&texts[id.0 as usize], t)
        })
        .unwrap_or_else(|e| panic!("trace interpreter: {e}"));
        (r.admits_empty, r.ends)
    }

    /// One evaluation attempt per `starts` entry of `body` over `tr`:
    /// `(admits the empty match, end ticks of its nonempty matches)`.
    fn attempts_of(
        extra_decls: &str,
        body: &str,
        tr: &Trace,
        starts: &[u32],
    ) -> Vec<(bool, BTreeSet<u32>)> {
        with_built_in(extra_decls, body, |au, leaves, tree| {
            let texts = leaf_texts(leaves, tree);
            starts
                .iter()
                .map(|&s| run_attempt(au, &texts, tr, s))
                .collect()
        })
        .unwrap_or_else(|| panic!("`{body}` failed to compile"))
    }

    fn ends_at(body: &str, tr: &Trace, start: u32) -> BTreeSet<u32> {
        attempts_of("", body, tr, &[start]).remove(0).1
    }

    fn set(v: &[u32]) -> BTreeSet<u32> {
        v.iter().copied().collect()
    }

    // -- the LRM's figures 16-5 .. 16-13 -----------------------------------
    //
    // The figures are drawings; what is checked is what their captions and
    // the surrounding text state: the tick each match ENDS on for the
    // evaluation attempt shown. (A figure also counts matches -- "four of
    // them ending at clock tick 12" -- but a sequence match is a boolean per
    // end tick for every consumer, so the interpreter reports end-tick sets.)

    const TE: &str = "logic te1, te2, te3, te4, te5;";

    /// The signals of Figures 16-5, 16-6, 16-8, 16-10 and 16-11 (the attempt
    /// begins at clock tick 8): te1 at 8; te2 at 9..13 (so `te1 ##2 te2`
    /// matches at 10 and `te1 ##[1:5] te2` at 9..13); te3 at 8, te4 at 9..10,
    /// te5 at 11..13 (`te3 ##2 te4 ##2 te5` matches at 12 only: te4 at 10 and
    /// te5 at 12, with distractors on the neighbouring ticks).
    fn fig_trace() -> Trace {
        Trace::lrm(&[
            ("te1", "00000001000000"),
            ("te2", "00000000111110"),
            ("te3", "00000001000000"),
            ("te4", "00000000110000"),
            ("te5", "00000000001110"),
        ])
    }

    fn fig_ends(body: &str) -> BTreeSet<u32> {
        attempts_of(TE, body, &fig_trace(), &[8]).remove(0).1
    }

    /// Figure 16-5: `(te1 ##2 te2) and (te3 ##2 te4 ##2 te5)` -- operand
    /// matches end at 10 and 12, the composite at 12.
    #[test]
    fn lrm_figure_16_5_and_of_two_sequences() {
        assert_eq!(fig_ends("te1 ##2 te2"), set(&[10]));
        assert_eq!(fig_ends("te3 ##2 te4 ##2 te5"), set(&[12]));
        assert_eq!(
            fig_ends("(te1 ##2 te2) and (te3 ##2 te4 ##2 te5)"),
            set(&[12])
        );
    }

    /// Figure 16-6: with `##[1:5]` the first operand matches at 9..13 and the
    /// composite at 12 (four times) and 13.
    #[test]
    fn lrm_figure_16_6_and_with_a_time_range() {
        assert_eq!(fig_ends("te1 ##[1:5] te2"), set(&[9, 10, 11, 12, 13]));
        assert_eq!(
            fig_ends("(te1 ##[1:5] te2) and (te3 ##2 te4 ##2 te5)"),
            set(&[12, 13])
        );
    }

    /// Figure 16-7: `te1 and te2` on Boolean operands matches at exactly the
    /// ticks where both are true: 1, 3, 8 and 14.
    #[test]
    fn lrm_figure_16_7_and_of_two_booleans() {
        let tr = Trace::lrm(&[("te1", "11101011010111"), ("te2", "10110001100001")]);
        let starts: Vec<u32> = (1..=14).collect();
        let got = attempts_of(TE, "te1 and te2", &tr, &starts);
        for (s, (empty, ends)) in starts.iter().zip(got) {
            assert!(!empty);
            let both = tr.value("te1", *s) && tr.value("te2", *s);
            assert_eq!(ends, if both { set(&[*s]) } else { set(&[]) }, "tick {s}");
        }
        let matching: Vec<u32> = starts
            .iter()
            .copied()
            .filter(|&s| !ends_at_in("te1 and te2", &tr, s).is_empty())
            .collect();
        assert_eq!(matching, vec![1, 3, 8, 14]);
    }

    fn ends_at_in(body: &str, tr: &Trace, s: u32) -> BTreeSet<u32> {
        attempts_of(TE, body, tr, &[s]).remove(0).1
    }

    /// Figure 16-8: the same operands as 16-6 under `intersect`: only the
    /// pair of equal length survives, a single match at 12.
    #[test]
    fn lrm_figure_16_8_intersect() {
        assert_eq!(
            fig_ends("(te1 ##[1:5] te2) intersect (te3 ##2 te4 ##2 te5)"),
            set(&[12])
        );
    }

    /// Figure 16-9: `te1 or te2` on Booleans fails at ticks 7 and 13 only.
    #[test]
    fn lrm_figure_16_9_or_of_two_booleans() {
        let tr = Trace::lrm(&[("te1", "11010101100101"), ("te2", "00101000111000")]);
        let starts: Vec<u32> = (1..=14).collect();
        let got = attempts_of(TE, "te1 or te2", &tr, &starts);
        let failed: Vec<u32> = starts
            .iter()
            .zip(got)
            .filter(|(_, (_, ends))| ends.is_empty())
            .map(|(s, _)| *s)
            .collect();
        assert_eq!(failed, vec![7, 13]);
    }

    /// Figure 16-10: `(te1 ##2 te2) or (te3 ##2 te4 ##2 te5)`: matches at 10
    /// and 12.
    #[test]
    fn lrm_figure_16_10_or_of_two_sequences() {
        assert_eq!(
            fig_ends("(te1 ##2 te2) or (te3 ##2 te4 ##2 te5)"),
            set(&[10, 12])
        );
    }

    /// Figure 16-11: with `##[1:5]`: matches at 9, 10, 11, 12 and 13.
    #[test]
    fn lrm_figure_16_11_or_with_a_time_range() {
        assert_eq!(
            fig_ends("(te1 ##[1:5] te2) or (te3 ##2 te4 ##2 te5)"),
            set(&[9, 10, 11, 12, 13])
        );
    }

    const BURST: &str = "logic mclk, burst_mode, irdy, trdy;";
    const BURST_RULE1: &str = "$fell(burst_mode) ##0 \
         ((!burst_mode) throughout (##2 ((trdy==0)&&(irdy==0))[*7]))";

    /// The rows common to Figures 16-12/16-13: `$fell(burst_mode)` holds at
    /// tick 2 (burst_mode high at 1, low at 2); `(trdy==0)&&(irdy==0)` holds
    /// at ticks 4..10 (the figure numbers them 1..7).
    fn burst_trace(not_burst_mode: &str) -> Trace {
        Trace::lrm(&[
            ("$fell(burst_mode)", "01000000000000"),
            ("!burst_mode", not_burst_mode),
            ("(trdy==0)&&(irdy==0)", "00011111110000"),
        ])
    }

    /// Figure 16-12: burst_mode goes high at tick 9, inside the interval
    /// 2..10, so the `throughout` fails and burst_rule1 does not match.
    #[test]
    fn lrm_figure_16_12_throughout_restriction_fails() {
        let tr = burst_trace("01111111000000");
        assert_eq!(
            attempts_of(BURST, BURST_RULE1, &tr, &[2]).remove(0).1,
            set(&[])
        );
        // Without the restriction the subsequence matches from 2 to 10: the
        // failure is the throughout's doing, not a mistake in the trace.
        assert_eq!(
            attempts_of(
                BURST,
                "$fell(burst_mode) ##0 (##2 ((trdy==0)&&(irdy==0))[*7])",
                &tr,
                &[2]
            )
            .remove(0)
            .1,
            set(&[10])
        );
    }

    /// Figure 16-13: burst_mode stays low through tick 10: burst_rule1
    /// matches from 2 to 10.
    #[test]
    fn lrm_figure_16_13_throughout_restriction_succeeds() {
        let tr = burst_trace("01111111111111");
        assert_eq!(
            attempts_of(BURST, BURST_RULE1, &tr, &[2]).remove(0).1,
            set(&[10])
        );
        // Low only up to tick 9 is not enough: tick 10 is in the interval.
        let tr = burst_trace("01111111100000");
        assert_eq!(
            attempts_of(BURST, BURST_RULE1, &tr, &[2]).remove(0).1,
            set(&[])
        );
    }

    /// 16.9.10's own example, on Figure 16-13's trace: `!trdy[*7] within
    /// ($fell(irdy) ##1 !irdy[*8])` "matches from clock tick 3 to clock tick
    /// 11".
    #[test]
    fn lrm_within_example_matches_from_tick_3_to_11() {
        let tr = Trace::lrm(&[
            ("!trdy", "00011111110000"),
            ("$fell(irdy)", "00100000000000"),
            ("!irdy", "00011111111000"),
        ]);
        let body = "!trdy[*7] within ($fell(irdy) ##1 !irdy[*8])";
        assert_eq!(attempts_of(BURST, body, &tr, &[3]).remove(0).1, set(&[11]));
        // Swapped, the 9-tick sequence cannot sit inside the 7-tick one.
        let swapped = "($fell(irdy) ##1 !irdy[*8]) within !trdy[*7]";
        assert_eq!(attempts_of(BURST, swapped, &tr, &[3]).remove(0).1, set(&[]));
    }

    // -- first_match ------------------------------------------------------

    /// 16.9.8: `ts1 = first_match(te1 ##[2:5] te2)` keeps only the match that
    /// ends first; `t1 = te1 ##[2:5] te2` has them all.
    #[test]
    fn first_match_keeps_the_earliest_ending_match() {
        let tr = Trace::new(&[("a", "10000000"), ("b", "01111110")]);
        assert_eq!(ends_at("a ##[2:5] b", &tr, 0), set(&[2, 3, 4, 5]));
        assert_eq!(ends_at("first_match(a ##[2:5] b)", &tr, 0), set(&[2]));
        // A start with no match at all has none under first_match either.
        assert_eq!(ends_at("first_match(a ##[2:5] b)", &tr, 1), set(&[]));
    }

    /// 16.9.8's second example: `ts2 = first_match((a ##[2:3] b) or (c ##[1:2]
    /// d))` is the earliest-ending of a##2b, a##3b, c##1d, c##2d -- all of
    /// them when several end on that same tick.
    #[test]
    fn first_match_of_an_or_picks_the_earliest_across_both_arms() {
        let body = "first_match((a ##[2:3] b) or (c ##[1:2] d))";
        // a##2b and c##2d both end at 2, c##1d does not match.
        let tr = Trace::new(&[
            ("a", "10000"),
            ("b", "00110"),
            ("c", "10000"),
            ("d", "00100"),
        ]);
        assert_eq!(
            ends_at("(a ##[2:3] b) or (c ##[1:2] d)", &tr, 0),
            set(&[2, 3])
        );
        assert_eq!(ends_at(body, &tr, 0), set(&[2]));
        // c##1d matches too, at 1: it alone is the first match.
        let tr = Trace::new(&[
            ("a", "10000"),
            ("b", "00110"),
            ("c", "10000"),
            ("d", "01100"),
        ]);
        assert_eq!(
            ends_at("(a ##[2:3] b) or (c ##[1:2] d)", &tr, 0),
            set(&[1, 2, 3])
        );
        assert_eq!(ends_at(body, &tr, 0), set(&[1]));
    }

    /// 16.9.8: "when a sequence is a subsequence of a larger sequence, then
    /// applying the first_match operator has significant effect". The earliest
    /// match is THE match even when its continuation then fails: the later,
    /// longer matches stay discarded.
    #[test]
    fn first_match_inside_a_larger_sequence_discards_the_later_matches() {
        let plain = "(a ##[1:3] b) ##1 c";
        let first = "first_match(a ##[1:3] b) ##1 c";
        // `a ##[1:3] b` ends at 1 and 2; only the end-2 match is followed by c.
        let tr = Trace::new(&[("a", "1000000"), ("b", "0110000"), ("c", "0001000")]);
        assert_eq!(ends_at(plain, &tr, 0), set(&[3]));
        assert_eq!(ends_at(first, &tr, 0), set(&[]));
        // c right after the earliest match: both agree.
        let tr = Trace::new(&[("a", "1000000"), ("b", "0110000"), ("c", "0010000")]);
        assert_eq!(ends_at(plain, &tr, 0), set(&[2]));
        assert_eq!(ends_at(first, &tr, 0), set(&[2]));
    }

    /// The earliest end tick of a first_match region is a fact about the
    /// region, not about the product it sits in: `first_match(R) intersect S`
    /// must not fall back to R's LATER match just because S disagrees with
    /// the earliest one (the product's dead-state trim keeps the region's
    /// `FirstMatchEnd` edge for exactly this reason).
    #[test]
    fn first_match_under_a_product_records_its_end_even_when_the_other_side_disagrees() {
        // `a ##[1:2] b` ends at 1 and 2; `a ##2 b` ends at 2 only.
        let tr = Trace::new(&[("a", "100000"), ("b", "011000")]);
        assert_eq!(
            ends_at("(a ##[1:2] b) intersect (a ##2 b)", &tr, 0),
            set(&[2])
        );
        // The earliest R match (end 1) has the wrong length for S: no match.
        assert_eq!(
            ends_at("first_match(a ##[1:2] b) intersect (a ##2 b)", &tr, 0),
            set(&[])
        );
        assert_eq!(
            ends_at("first_match(a ##[1:2] b) and (a ##2 b)", &tr, 0),
            set(&[2])
        );
        // Agreeing lengths keep the match.
        assert_eq!(
            ends_at("first_match(a ##[1:2] b) intersect (a ##1 b)", &tr, 0),
            set(&[1])
        );
    }

    /// Annex F.5.2: `w |= first_match(R)` iff `w |= R` and no proper prefix of
    /// `w` (the empty word included) satisfies R. So when R admits the empty
    /// match, first_match(R) is that empty match and nothing longer.
    #[test]
    fn first_match_of_an_empty_admitting_sequence_is_the_empty_match() {
        let tr = Trace::new(&[("a", "1111"), ("b", "1100")]);
        assert_eq!(
            attempts_of("", "first_match(a[*0:2])", &tr, &[0])[0],
            (true, set(&[]))
        );
        assert_eq!(
            attempts_of("", "a[*0:2]", &tr, &[0])[0],
            (true, set(&[0, 1]))
        );
        // `ε ##1 b` is `b` at the start tick; the longer `a ##1 b` is gone.
        assert_eq!(ends_at("a[*0:2] ##1 b", &tr, 0), set(&[0, 1]));
        assert_eq!(ends_at("first_match(a[*0:2]) ##1 b", &tr, 0), set(&[0]));
    }

    /// Every copy of a repeated first_match is its own region: `(fm(X))[*2]`
    /// is `fm(X) ##1 fm(X)`.
    #[test]
    fn repeated_first_match_is_one_region_per_repeat() {
        let mut g = Lcg(0xfeed_0011);
        let (mut compared, mut nonempty) = (0, 0);
        for _ in 0..60 {
            let tr = random_trace(&mut g, 12);
            let rep = attempts_of(
                "",
                "(first_match(a ##[1:2] b))[*2]",
                &tr,
                &(0..12).collect::<Vec<_>>(),
            );
            let unrolled = attempts_of(
                "",
                "first_match(a ##[1:2] b) ##1 first_match(a ##[1:2] b)",
                &tr,
                &(0..12).collect::<Vec<_>>(),
            );
            assert_eq!(rep, unrolled);
            compared += rep.len();
            nonempty += rep.iter().filter(|(_, e)| !e.is_empty()).count();
        }
        assert_eq!(compared, 720);
        assert!(nonempty >= 40, "only {nonempty} attempts matched");
    }

    /// A repetition around a binary operator (the `SequenceWithMatch` wrapper
    /// path): `(a and b)[*2]` etc.
    #[test]
    fn repetition_of_a_parenthesized_binary_operator() {
        assert_eq!(
            lang_of("(a and b)[*2]", 8),
            Lang::from([word(&[&["a", "b"], &["a", "b"]])])
        );
        assert_eq!(
            lang_of("(a or b)[*1:2]", 8),
            Lang::from([
                word(&[&["a"]]),
                word(&[&["b"]]),
                word(&[&["a"], &["a"]]),
                word(&[&["a"], &["b"]]),
                word(&[&["b"], &["a"]]),
                word(&[&["b"], &["b"]]),
            ])
        );
        assert_eq!(
            lang_of("(a intersect b[*0:1])[*0:1]", 8),
            Lang::from([Vec::new(), word(&[&["a", "b"]])])
        );
    }

    // -- structure: determinism, size, errors ------------------------------

    /// Everything the product construction can reach is reachable from the
    /// start state: the builder prunes the operands' own (now unreferenced)
    /// states, so no dead state is left behind.
    fn reachable_states(au: &ir::Automaton) -> usize {
        let mut seen = vec![false; au.states.len()];
        let mut stack = vec![au.start];
        while let Some(s) = stack.pop() {
            if std::mem::replace(&mut seen[s.0 as usize], true) {
                continue;
            }
            stack.extend(au.state(s).edges.iter().map(|e| e.target));
        }
        seen.iter().filter(|&&r| r).count()
    }

    const OPERATOR_SOURCES: &[&str] = &[
        "a ##1 b",
        "(a ##[1:3] b) intersect (c ##2 d)",
        "(a ##1 b) and (c ##2 d ##1 e)",
        "(a ##[1:2] b) or (c[*2] ##1 d)",
        "first_match(a ##[1:3] b) ##1 c",
        "a throughout (b ##2 c)",
        "a within (b ##4 c)",
        "(first_match(a ##[1:2] b))[*1:$]",
        "((a ##[0:2] b) and (c[*0:2])) within (d ##[2:$] e)",
    ];

    #[test]
    fn every_state_of_a_built_automaton_is_reachable() {
        for src in OPERATOR_SOURCES {
            with_built(src, |au, _, _| {
                assert_eq!(
                    reachable_states(au),
                    au.states.len(),
                    "dead states left in the automaton for `{src}`"
                );
                assert_eq!(au.start, ThreadStateId(0), "`{src}`");
            })
            .unwrap_or_else(|| panic!("`{src}` failed to compile"));
        }
    }

    /// The automaton (state numbering, edge order) is a pure function of the
    /// source: two builds print identically, so nothing iterates a hash
    /// container into the output.
    #[test]
    fn builds_are_deterministic() {
        for src in OPERATOR_SOURCES {
            let dump = || {
                with_built(src, |au, _, _| format!("{au:?}"))
                    .unwrap_or_else(|| panic!("`{src}` failed to compile"))
            };
            let first = dump();
            for _ in 0..3 {
                assert_eq!(first, dump(), "`{src}`");
            }
        }
    }

    /// One first-match group per first_match operator (and per unrolled copy);
    /// an empty-admitting operand needs none.
    #[test]
    fn first_match_groups_are_one_per_region() {
        let groups = |src: &str| {
            with_built(src, |au, _, _| {
                // Every minted group is wired as one Begin and one End at
                // least, and nothing refers to a group that was not minted.
                let (mut begins, mut ends) = (BTreeSet::new(), BTreeSet::new());
                for st in &au.states {
                    for e in &st.edges {
                        match &e.label {
                            ir::Transition::FirstMatchBegin { group } => {
                                begins.insert(group.0);
                            }
                            ir::Transition::FirstMatchEnd { group } => {
                                ends.insert(group.0);
                            }
                            _ => {}
                        }
                    }
                }
                assert_eq!(begins, ends, "`{src}`: Begin/End groups differ");
                assert_eq!(
                    begins,
                    (0..au.first_match_groups).collect::<BTreeSet<_>>(),
                    "`{src}`"
                );
                au.first_match_groups
            })
            .unwrap_or_else(|| panic!("`{src}` failed to compile"))
        };
        assert_eq!(groups("a ##1 b"), 0);
        assert_eq!(groups("first_match(a ##1 b)"), 1);
        assert_eq!(groups("first_match(a ##1 b) ##1 first_match(c)"), 2);
        assert_eq!(groups("first_match(first_match(a ##[1:2] b))"), 2);
        assert_eq!(groups("(first_match(a ##[1:2] b))[*3]"), 3);
        assert_eq!(groups("first_match(a[*0:2])"), 0);
        // A product copies the markers of its operands, it does not mint more.
        assert_eq!(
            groups("first_match(a ##[1:2] b) intersect (c ##[1:2] d)"),
            1
        );
    }

    /// The product construction is bounded: a state count that would run away
    /// is a named error, not an out-of-memory.
    #[test]
    fn a_runaway_product_is_a_named_error() {
        let err = automaton_err("", "(a ##100000 b) intersect (c ##100000 a)");
        assert!(err.message.contains("intersect"), "error was: {err}");
        assert!(err.message.contains("states"), "error was: {err}");
        let err = automaton_err("", "(a ##100000 b) and (c ##100000 a)");
        assert!(err.message.contains("`and`"), "error was: {err}");
    }

    /// A first_match match item that is not a local-variable action is a
    /// loud error (T14); everything else this builder does not implement
    /// still shouts, naming the operator.
    #[test]
    fn unimplemented_neighbours_of_the_new_operators_stay_loud() {
        let err = automaton_err("", "first_match(a, cnt = cnt + 1)");
        assert!(err.message.contains("match item"), "error was: {err}");
        assert!(err.message.contains("local variable"), "error was: {err}");
        let err = automaton_err("", "a until b");
        assert!(err.message.contains("Until"), "error was: {err}");
        // A PROPERTY operand of `and` is not a sequence: recursion reaches
        // the implication and names it.
        let err = automaton_err("", "(a |-> b) and c");
        assert!(
            err.message.contains("OverlappedImplication"),
            "error was: {err}"
        );
    }

    // -- generated differential battery vs the trace reference -------------

    /// Reference for first_match-bearing sequences: the set of LENGTHS (in
    /// ticks; 0 is the empty match) of the matches of `rx` that begin at tick
    /// `s` of `tr`, computed straight from the LRM/Annex F definitions over the
    /// concrete trace -- no automaton, no word language. A match whose last
    /// tick `s + len - 1` is `>= tr.len` is one the trace never reached; [`ref_attempt`]
    /// drops those at the top (they only ever lengthen, so dropping them late
    /// is the same as dropping them early). `first == false` ignores
    /// `first_match` (treats it as the identity), which is how the battery
    /// proves it can tell the operator from its absence.
    fn ref_lens(rx: &Rx, tr: &Trace, s: u32, first: bool) -> BTreeSet<u32> {
        let n = tr.len;
        let rec = |r: &Rx, st: u32| ref_lens(r, tr, st, first);
        match rx {
            Rx::Leaf(t) => {
                if s < n && tr.value(t, s) {
                    set(&[1])
                } else {
                    set(&[])
                }
            }
            Rx::Paren(r) => rec(r, s),
            Rx::Cat(l, d, r) => {
                let mut out = BTreeSet::new();
                // `empty ##k empty` is `1[*k-1]`: k reaches n + 1 for an n-tick length.
                let hi = d.max.unwrap_or(n + 1).min(n + 1);
                for ln in rec(l, s) {
                    for k in d.min..=hi {
                        if k == 0 {
                            // Fusion: the left match's last tick is the right
                            // match's first; neither may be empty.
                            if ln == 0 {
                                continue;
                            }
                            for rn in rec(r, s + ln - 1) {
                                if rn >= 1 {
                                    out.insert(ln - 1 + rn);
                                }
                            }
                        } else {
                            // `ln` ticks, `k - 1` vacuous ticks, then the right
                            // match: 16.9.2.1's four rules at once.
                            for rn in rec(r, s + ln + k - 1) {
                                out.insert(ln + k - 1 + rn);
                            }
                        }
                    }
                }
                out
            }
            Rx::Lead(d, r) => {
                let mut out = BTreeSet::new();
                let hi = d.max.unwrap_or(n).min(n);
                for k in d.min..=hi {
                    for rn in rec(r, s + k) {
                        out.insert(k + rn);
                    }
                }
                out
            }
            Rx::Rep(r, p) => {
                let top = p.max.unwrap_or(n + 2).min(n + 2);
                let mut pow = set(&[0]);
                let mut out = BTreeSet::new();
                if p.min == 0 {
                    out.insert(0);
                }
                for k in 1..=top {
                    let mut next = BTreeSet::new();
                    for &l in &pow {
                        for u in rec(r, s + l) {
                            next.insert(l + u);
                        }
                    }
                    pow = next;
                    if k >= p.min {
                        out.extend(pow.iter().copied());
                    }
                }
                out
            }
            Rx::Bin(l, op, r) => {
                let ll = rec(l, s);
                let rl = rec(r, s);
                match op {
                    SeqOp::Or => ll.union(&rl).copied().collect(),
                    SeqOp::Intersect => ll.intersection(&rl).copied().collect(),
                    // Both match from `s`; the composite ends with the later.
                    SeqOp::And => ll
                        .iter()
                        .flat_map(|&x| rl.iter().map(move |&y| x.max(y)))
                        .collect(),
                    // seq1 matches on a sub-interval `[s+i, s+i+ln)` of a seq2
                    // match of length `rn`.
                    SeqOp::Within => rl
                        .into_iter()
                        .filter(|&rn| {
                            (0..=rn).any(|i| rec(l, s + i).iter().any(|&ln| i + ln <= rn))
                        })
                        .collect(),
                }
            }
            Rx::Thr(c, r) => rec(r, s)
                .into_iter()
                .filter(|&ln| (0..ln).all(|i| tr.value(c, s + i)))
                .collect(),
            Rx::First(r) => {
                let all = rec(r, s);
                match all.first() {
                    Some(&min) if first => set(&[min]),
                    _ => all,
                }
            }
        }
    }

    fn ref_attempt(rx: &Rx, tr: &Trace, s: u32, first: bool) -> (bool, BTreeSet<u32>) {
        let lens = ref_lens(rx, tr, s, first);
        let ends = lens
            .iter()
            .filter(|&&l| l >= 1 && s + l - 1 < tr.len)
            .map(|&l| s + l - 1)
            .collect();
        (lens.contains(&0), ends)
    }

    /// A random trace over `a`, `b`, `c` (each true about 60% of the time, so
    /// matches are common).
    fn random_trace(g: &mut Lcg, len: usize) -> Trace {
        let mut rows = Vec::new();
        for name in ["a", "b", "c"] {
            let bits: String = (0..len)
                .map(|_| if g.next(5) < 3 { '1' } else { '0' })
                .collect();
            rows.push((name, bits));
        }
        let borrowed: Vec<(&str, &str)> = rows.iter().map(|(n, b)| (*n, b.as_str())).collect();
        Trace::new(&borrowed)
    }

    /// The reference checks itself on the cases the LRM states, so a wrong
    /// reference cannot hide a wrong builder (or the reverse).
    #[test]
    fn the_trace_reference_agrees_with_the_lrm_examples() {
        let leaf = |n| Box::new(Rx::Leaf(n));
        let d = |min, max, text| Dl { min, max, text };
        let a_b = Rx::Cat(leaf("a"), d(2, Some(5), "##[2:5]"), leaf("b"));
        let tr = Trace::new(&[("a", "10000000"), ("b", "01111110")]);
        assert_eq!(ref_attempt(&a_b, &tr, 0, true).1, set(&[2, 3, 4, 5]));
        let fm = Rx::First(Box::new(a_b));
        assert_eq!(ref_attempt(&fm, &tr, 0, true).1, set(&[2]));
        assert_eq!(ref_attempt(&fm, &tr, 0, false).1, set(&[2, 3, 4, 5]));
        let ab_and = Rx::Bin(
            Box::new(Rx::Cat(leaf("a"), d(1, Some(1), "##1"), leaf("b"))),
            SeqOp::And,
            Box::new(Rx::Cat(leaf("a"), d(2, Some(2), "##2"), leaf("b"))),
        );
        let tr = Trace::new(&[("a", "111000"), ("b", "011100")]);
        assert_eq!(ref_attempt(&ab_and, &tr, 0, true).1, set(&[2]));
    }

    /// 500 generated sequences, `first_match` nested anywhere, built and run
    /// against 4 random traces from every start tick, end ticks and the empty
    /// match compared with [`ref_attempt`]. The battery must also be able to
    /// tell `first_match` from its absence.
    #[test]
    fn generated_sequences_match_the_trace_reference() {
        const LEN: u32 = 9;
        let mut g = Lcg(0xd1ff_e2e1_7ace_0011);
        let (mut compared, mut skipped, mut attempts) = (0usize, 0, 0usize);
        let (mut first_matters, mut with_matches) = (0usize, 0usize);
        let mut census = [0usize; 6];
        for _ in 0..500 {
            let rx = gen_rx11(&mut g, 3, true);
            let src = render(&rx);
            let traces: Vec<Trace> = (0..4).map(|_| random_trace(&mut g, LEN as usize)).collect();
            let ok = with_built(&src, |au, leaves, tree| {
                let texts = leaf_texts(leaves, tree);
                for tr in &traces {
                    for s in 0..LEN {
                        let got = run_attempt(au, &texts, tr, s);
                        let want = ref_attempt(&rx, tr, s, true);
                        assert_eq!(got, want, "`{src}` from tick {s} over {:?}", tr.rows);
                        attempts += 1;
                        with_matches += usize::from(!want.1.is_empty());
                        first_matters += usize::from(want != ref_attempt(&rx, tr, s, false));
                    }
                }
            });
            match ok {
                Some(()) => {
                    compared += 1;
                    op_census(&rx, &mut census);
                }
                None => skipped += 1,
            }
        }
        assert!(
            compared >= 380,
            "only {compared} compared, {skipped} skipped"
        );
        assert!(
            with_matches >= 2000,
            "only {with_matches} of {attempts} attempts matched"
        );
        assert!(
            first_matters >= 150,
            "first_match changed the result in only {first_matters} attempts"
        );
        for (name, n) in [
            "and",
            "or",
            "intersect",
            "within",
            "throughout",
            "first_match",
        ]
        .iter()
        .zip(census)
        {
            assert!(n >= 40, "only {n} `{name}` operators exercised");
        }
    }

    // -- T12: named sequence instances, LRM 16.8 / 16.8.1 -------------------

    /// Compiles `decls` (module-level declarations: sequences, parameters) and
    /// one concurrent-assertion statement `stmt` inside an `always_ff`, builds
    /// the automaton of that assertion's sequence and hands the build result,
    /// the syntax tree and the compilation's diagnostics to `f`. The root's
    /// `Clocking` wrapper (when the assertion has its own `@(...)`) is stripped
    /// exactly as every other helper in this module does; an assertion that
    /// names a clocked sequence has no such wrapper (the `Clocking` is inside
    /// the instance), so its root is used as is.
    ///
    /// `allow_errors` is for the tests that feed the builder a design slang
    /// itself diagnoses (slang still produces a tree for those): without it a
    /// compile error in the fixture fails the test, so a fixture typo can never
    /// pass as "the builder rejected it".
    fn with_assertion<R>(
        decls: &str,
        stmt: &str,
        allow_errors: bool,
        f: impl FnOnce(
            Result<(ir::Automaton, LeafTable<'_>), LoweringError>,
            &SyntaxTree,
            &sv_lang::Diagnostics,
        ) -> R,
    ) -> R {
        let src = format!(
            "module m;\n\
             logic clk, sysclk, a, b, c, d, e, x, y, z;\n\
             logic [7:0] bb;\n\
             int n;\n\
             parameter my_delay = 2;\n\
             {decls}\n\
             always_ff @(posedge clk) begin\n\
               {stmt}\n\
             end\n\
             endmodule\n"
        );
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(&src).unwrap();
        let design = comp.compile().unwrap();
        let diags = design.diagnostics();
        if !allow_errors {
            assert!(
                !diags.has_errors(),
                "fixture has compile errors:\n{}\n{src}",
                diags.rendered()
            );
        }
        let m = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let analysis = design.analyze(AnalysisFlags::NONE, 1).unwrap();
        let proc = analysis.procedures(m).next().unwrap();
        let Some(assertion) = analysis.assertions(proc.symbol()).next() else {
            panic!(
                "slang dropped the assertion; analysis diagnostics:\n{}",
                analysis.diagnostics().rendered()
            );
        };
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let root = assertion.root().as_assertion_expr().unwrap();
        let (root, root_clock) = if root.kind() == AssertionExprKind::Clocking {
            let kids = root.children();
            (kids[1].as_assertion_expr().unwrap(), Some(kids[0]))
        } else {
            (root, None)
        };
        f(
            build_automaton(root, root_clock, (&tree).into(), &m),
            &tree,
            &diags,
        )
    }

    /// What a T12 equivalence test compares: the automaton's full `Debug`
    /// rendering (`ir::Automaton` has no `PartialEq`), the leaf texts in
    /// `LeafId` order, and the accepted language up to a tick bound.
    struct Built {
        debug: String,
        leaves: Vec<String>,
        lang: Lang,
    }

    fn built(decls: &str, stmt: &str, bound: u32) -> Built {
        with_assertion(decls, stmt, false, |r, tree, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("`{stmt}` failed to build: {e}"));
            Built {
                debug: format!("{au:?}"),
                leaves: leaf_texts(&leaves, tree),
                lang: accepted_lang(&au, &leaves, tree, bound),
            }
        })
    }

    /// The error [`build_automaton`] returns for a design slang accepts.
    fn built_err(decls: &str, stmt: &str) -> LoweringError {
        with_assertion(decls, stmt, false, |r, _, _| {
            r.err()
                .unwrap_or_else(|| panic!("`{stmt}` was expected to be rejected"))
        })
    }

    /// [`built_err`] for a design slang itself diagnoses.
    fn built_err_lenient(decls: &str, stmt: &str) -> LoweringError {
        with_assertion(decls, stmt, true, |r, _, _| {
            r.err()
                .unwrap_or_else(|| panic!("`{stmt}` was expected to be rejected"))
        })
    }

    /// LRM 16.8: `rule` is "equivalent to" the same sequence with `s`'s body
    /// written in place. The instance's own `@(posedge sysclk)` clocking
    /// wrapper must be transparent to the sequence's shape, so the automata
    /// are not merely language-equal but identical.
    #[test]
    fn s1_rule_instantiation_equivalent_to_inline() {
        let decls = "sequence s; a ##1 b ##1 c; endsequence\n\
                     sequence rule; @(posedge clk) x ##1 y ##1 s ##1 z; endsequence";
        let inst = built(decls, "assert property (rule);", 8);
        let inline = built(
            "",
            "assert property (@(posedge clk) x ##1 y ##1 (a ##1 b ##1 c) ##1 z);",
            8,
        );
        assert_eq!(inst.leaves, ["x", "y", "a", "b", "c", "z"]);
        assert_eq!(
            inst.lang,
            Lang::from([word(&[&["x"], &["y"], &["a"], &["b"], &["c"], &["z"]])])
        );
        assert_eq!(inst.lang, inline.lang);
        assert_eq!(inst.leaves, inline.leaves);
        assert_eq!(inst.debug, inline.debug);
    }

    /// 16.8: the rewriting algorithm "substitutes actual arguments for
    /// references to the corresponding formal arguments", for a Boolean actual
    /// and for a sequence actual alike.
    #[test]
    fn untyped_formals_substitute_boolean_and_sequence_actuals() {
        let decls = "sequence s(p, q); p ##2 q; endsequence";
        let b = built(decls, "assert property (@(posedge clk) s(a ##1 b, c));", 8);
        assert_eq!(b.leaves, ["a", "b", "c"]);
        assert_eq!(b.lang, Lang::from([word(&[&["a"], &["b"], &[], &["c"]])]));
        let b = built(decls, "assert property (@(posedge clk) s(a, b));", 8);
        assert_eq!(b.lang, Lang::from([word(&[&["a"], &[], &["b"]])]));
    }

    /// 16.8: a default actual argument is used when the instance omits it, an
    /// explicit actual overrides it, and actuals bind by name as well as by
    /// position. The default `q = c` is a name resolved in the declaration's
    /// scope; the delay default `k = 2` is a bound recovered from the
    /// declaration's own text.
    #[test]
    fn default_actuals_are_used_overridden_and_bound_by_name() {
        let decls = "sequence s(p, q = c, int k = 2); p ##k q; endsequence";
        let w = |stmt: &str| built(decls, stmt, 8).lang;
        assert_eq!(
            w("assert property (@(posedge clk) s(a));"),
            Lang::from([word(&[&["a"], &[], &["c"]])])
        );
        assert_eq!(
            w("assert property (@(posedge clk) s(a, b, 3));"),
            Lang::from([word(&[&["a"], &[], &[], &["b"]])])
        );
        assert_eq!(
            w("assert property (@(posedge clk) s(.p(a), .k(1)));"),
            Lang::from([word(&[&["a"], &["c"]])])
        );
    }

    /// 16.8.1: "If a formal argument of a named sequence is typed ... the
    /// actual argument shall be cast to the type of the formal argument". The
    /// LRM's own pair: `s1(.w(a), .x(bit'(b)), .y(c))` and
    /// `s2(.w(a), .x(b), .y(c))` are equivalent, and with `b` 8 bits wide it
    /// "will be cast to bit by truncation". (`bb` is the 8-bit signal here.)
    /// The leaf is checked directly: a Conversion to width 1 where the untyped
    /// formal keeps the 8-bit operand.
    #[test]
    fn typed_formal_bit_truncates_wider_actual() {
        let decls = "sequence s1(w, x, y); w ##1 x ##[2:10] y; endsequence\n\
                     sequence s2(w, y, bit x); w ##1 x ##[2:10] y; endsequence";
        // The leaf bound to `x` is the second one built (w, x, y).
        let x_leaf = |stmt: &str| {
            with_assertion(decls, stmt, false, |r, _, _| {
                let (au, leaves) = r.unwrap();
                let x = leaves.get(LeafId(1));
                (
                    x.kind() == ExpressionKind::Conversion,
                    x.expr_type().unwrap().bit_width(),
                    reachable_lengths(&au, 20),
                    format!("{au:?}"),
                )
            })
        };
        let (typed_conv, typed_width, typed_lens, typed_au) =
            x_leaf("assert property (@(posedge clk) s2(.w(a), .x(bb), .y(c)));");
        let (_, cast_width, _, cast_au) =
            x_leaf("assert property (@(posedge clk) s1(.w(a), .x(bit'(bb)), .y(c)));");
        let (untyped_conv, untyped_width, _, _) =
            x_leaf("assert property (@(posedge clk) s1(.w(a), .x(bb), .y(c)));");
        assert!(typed_conv, "the typed formal must cast the 8-bit actual");
        assert_eq!(typed_width, 1, "cast to bit = truncation to 1 bit");
        assert_eq!(cast_width, 1);
        assert!(!untyped_conv, "an untyped formal keeps the actual as is");
        assert_eq!(untyped_width, 8);
        // `x` at tick 1, `y` 2..=10 later: matches end at ticks 3..=11.
        assert_eq!(typed_lens, (3..=11).collect::<BTreeSet<u32>>());
        // The LRM's equivalence pair builds the very same automaton.
        assert_eq!(typed_au, cast_au);
    }

    /// 16.8.1: a typed formal used in a delay is cast to its type like any
    /// other typed formal, so `65537` into a `shortint` is `1`.
    #[test]
    fn typed_delay_formal_is_cast_to_its_type() {
        let b = built(
            "sequence s(shortint k, untyped p); p ##k b; endsequence",
            "assert property (@(posedge clk) s(65537, a));",
            8,
        );
        assert_eq!(b.lang, Lang::from([word(&[&["a"], &["b"]])]));
    }

    /// 16.8: "If $ is an actual argument, then the corresponding formal
    /// argument shall be untyped and each of its references either shall be an
    /// upper bound in a cycle_delay_const_range_expression or shall itself be
    /// an actual argument in an instance of a named sequence."
    #[test]
    fn dollar_actual_requires_untyped_formal_used_as_upper_bound() {
        // Legal: an upper bound of a cycle delay range, of a repetition range,
        // and passed on as an actual to another instance.
        let dollar = |decls: &str, stmt: &str| built(decls, stmt, 5);
        let d = dollar(
            "sequence s(max, p); p ##[1:max] b; endsequence",
            "assert property (@(posedge clk) s($, a));",
        );
        assert_eq!(
            d.debug,
            built("", "assert property (@(posedge clk) a ##[1:$] b);", 5).debug
        );
        assert_eq!(d.lang.len(), 5, "b may follow a 1..=5 ticks later");
        let r = dollar(
            "sequence s(max, p); p[*2:max]; endsequence",
            "assert property (@(posedge clk) s($, a) ##1 b);",
        );
        assert_eq!(
            r.debug,
            built("", "assert property (@(posedge clk) a[*2:$] ##1 b);", 5).debug
        );
        let fwd = dollar(
            "sequence inner(m, p); p ##[1:m] b; endsequence\n\
             sequence outer(m2, p); inner(m2, p); endsequence",
            "assert property (@(posedge clk) outer($, a));",
        );
        assert_eq!(d.debug, fwd.debug);

        // Illegal: `$` as a lower bound. slang diagnoses it; the builder, fed
        // the tree slang still produces, must not silently treat it as a
        // number either.
        let decls = "sequence s(k, p); p ##[k:5] b; endsequence";
        let stmt = "assert property (@(posedge clk) s($, a));";
        let e = built_err_lenient(decls, stmt);
        assert!(e.message.contains("upper bound"), "{e}");
        with_assertion(decls, stmt, true, |_, _, diags| {
            let e = crate::sva::named::check_formal_argument_rules(diags)
                .expect_err("`$` into a lower bound is a diagnosed error");
            assert!(e.message.contains("`$`"), "{e}");
        });
    }

    /// LRM 16.8.1's `delay_arg_example`, verbatim: the cover property is
    /// "equivalent to `cover property (x ##2 y[*3:$] ##1 z)`".
    #[test]
    fn lrm_delay_arg_example_equals_its_inline_form() {
        let decls = "sequence delay_arg_example (max, shortint delay1, delay2, min);\n\
                       x ##delay1 y[*min:max] ##delay2 z;\n\
                     endsequence";
        let inst = built(
            decls,
            "cover property (delay_arg_example($, my_delay, my_delay-1, 3));",
            10,
        );
        let inline = built("", "cover property (x ##2 y[*3:$] ##1 z);", 10);
        assert_eq!(inst.debug, inline.debug);
        assert_eq!(inst.leaves, inline.leaves);
        assert_eq!(inst.lang, inline.lang);
        assert!(!inst.lang.is_empty());
    }

    /// LRM 16.8's `delay_example`: the legal instance builds, the illegal one
    /// (`z` and `d` are not elaboration-time constants) is a compile error
    /// that [`crate::sva::named::check_formal_argument_rules`] reports.
    #[test]
    fn lrm_delay_example_legal_builds_and_illegal_is_diagnosed() {
        let decls = "int zz, dd;\n\
                     sequence delay_example(x, y, min, max, delay1);\n\
                       x ##delay1 y[*min:max];\n\
                     endsequence";
        let ok = built(
            decls,
            "assert property (@(posedge clk) delay_example(x, y, 3, $, 2));",
            8,
        );
        assert_eq!(
            ok.debug,
            built("", "assert property (@(posedge clk) x ##2 y[*3:$]);", 8).debug
        );
        with_assertion(
            decls,
            "assert property (@(posedge clk) delay_example(x, y, zz, $, dd));",
            true,
            |r, _, diags| {
                crate::sva::named::check_formal_argument_rules(diags)
                    .expect_err("non-constant actuals in a delay/repetition are illegal");
                // And the builder does not quietly pick some value for them
                // (slang hands it a tree with the bad instance stripped).
                assert!(r.is_err(), "a non-constant bound is not buildable");
            },
        );
    }

    /// LRM 16.8.1's `event_arg_example` and `event_arg_example2`, verbatim: the
    /// instance is equivalent to `@(posedge clk) x ##1 y` either way the
    /// event reaches the body.
    #[test]
    fn lrm_event_arg_examples_equal_the_inline_clocked_sequence() {
        let inline = built("", "cover property (@(posedge clk) x ##1 y);", 4);
        let ev = built(
            "sequence event_arg_example (event ev); @(ev) x ##1 y; endsequence",
            "cover property (event_arg_example(posedge clk));",
            4,
        );
        let ev2 = built(
            "sequence event_arg_example2 (reg sig); @(posedge sig) x ##1 y; endsequence",
            "cover property (event_arg_example2(clk));",
            4,
        );
        assert_eq!(inline.lang, Lang::from([word(&[&["x"], &["y"]])]));
        for got in [&ev, &ev2] {
            assert_eq!(got.debug, inline.debug);
            assert_eq!(got.leaves, inline.leaves);
        }
    }

    /// 16.8 / F.4.1: an actual that is a reference to one of the CALLER's
    /// formals is evaluated in the caller's scope. `outer` hands its own `d`
    /// (3 here, from `my_delay+1`) to `inner` as a delay.
    #[test]
    fn a_callers_formal_passed_as_a_delay_is_resolved_in_the_callers_frame() {
        let b = built(
            "sequence inner(p, int k); p ##k b; endsequence\n\
             sequence outer(w, int d); inner(w, d) ##1 c; endsequence",
            "assert property (@(posedge clk) outer(a, my_delay+1));",
            8,
        );
        assert_eq!(
            b.lang,
            Lang::from([word(&[&["a"], &[], &[], &["b"], &["c"]])])
        );
    }

    /// A SEQUENCE actual's text lives at the call site: its `##d` names the
    /// CALLER's formal `d`, not the callee's `k` or any module constant. `q`'s
    /// `s ##k b` runs `(a ##d c) ##2 b` with `d = 3`.
    #[test]
    fn a_sequence_actual_is_resolved_in_the_call_site_frame() {
        let b = built(
            "sequence q(sequence s, int k); s ##k b; endsequence\n\
             sequence outer(int d); q(a ##d c, 2); endsequence",
            "assert property (@(posedge clk) outer(3));",
            10,
        );
        assert_eq!(
            b.lang,
            Lang::from([word(&[&["a"], &[], &[], &["c"], &[], &["b"]])])
        );
    }

    /// 16.8: names in a declaration resolve in the declaration's scope EXCEPT
    /// formal arguments, which shadow them. The formal `k` is 2 in this
    /// instance; the module constant `k` is 5.
    #[test]
    fn a_formal_shadows_a_module_constant_of_the_same_name() {
        let b = built(
            "parameter k = 5;\n\
             sequence s(k, p); p ##k b; endsequence",
            "assert property (@(posedge clk) s(2, a));",
            8,
        );
        assert_eq!(b.lang, Lang::from([word(&[&["a"], &[], &["b"]])]));
    }

    /// An instance takes a `[*n]` repetition like any sequence operand
    /// (`(a ##1 b)[*2]`), re-expanding the body per repeat.
    #[test]
    fn a_repeated_instance_expands_the_body_per_repeat() {
        let b = built(
            "sequence s(p); p ##1 b; endsequence",
            "assert property (@(posedge clk) s(a)[*2] ##1 c);",
            8,
        );
        assert_eq!(
            b.lang,
            Lang::from([word(&[&["a"], &["b"], &["a"], &["b"], &["c"]])])
        );
        assert_eq!(b.leaves, ["a", "b", "a", "b", "c"]);
    }

    /// 16.8.1 rules (a) and (c): an actual that is not cast compatible with a
    /// typed formal, and an event expression bound to a `sequence` formal, are
    /// illegal. slang diagnoses both and still produces a tree; the builder,
    /// fed that tree, must refuse it rather than return an automaton for an
    /// illegal design. (`named::check_formal_argument_rules` names the rule.)
    #[test]
    fn typed_formal_cast_incompatible_and_event_actuals_are_rejected() {
        let e = built_err_lenient(
            "int arr[2]; sequence s(int k, p); p ##1 (k == 1); endsequence",
            "assert property (@(posedge clk) s(arr, a));",
        );
        assert!(e.message.contains("slang could not bind"), "{e}");
        let e = built_err_lenient(
            "sequence s(sequence q); q; endsequence",
            "assert property (@(posedge clk) s(posedge clk));",
        );
        assert!(e.message.contains("slang could not bind"), "{e}");
    }

    /// 16.9.2: goto and nonconsecutive repetition take a Boolean expression
    /// only, so they are illegal on a sequence instance. slang diagnoses it; the
    /// builder must not model it as a repeated Boolean either.
    #[test]
    fn goto_repetition_on_an_instance_is_rejected() {
        let e = built_err_lenient(
            "sequence s(p); p ##1 b; endsequence",
            "assert property (@(posedge clk) s(a)[->2]);",
        );
        assert!(e.message.contains("named sequence instance"), "{e}");
        let e = built_err_lenient(
            "sequence s(p); p ##1 b; endsequence",
            "assert property (@(posedge clk) s(a)[=2]);",
        );
        assert!(e.message.contains("named sequence instance"), "{e}");
    }

    /// 16.8's actual-argument edge, `s(s(a))`, is a cyclic dependency. slang
    /// reports it when the instance sits directly in an assertion; written
    /// inside another sequence's declaration slang says nothing (pinned by
    /// `named::tests::actual_argument_cycle_inside_another_sequence_is_not_\
    /// reported_by_slang_known_gap`), so the builder refuses to expand a
    /// declaration it is already expanding.
    #[test]
    fn actual_argument_cycle_through_another_sequence_is_rejected() {
        let e = built_err(
            "sequence s(p); p ##1 b; endsequence\n\
             sequence user; s(s(a)); endsequence",
            "assert property (@(posedge clk) user);",
        );
        assert!(e.message.contains("cyclic dependency"), "{e}");
        assert!(e.message.contains("`s`"), "{e}");
        // Directly in the assertion slang diagnoses the cycle itself (and
        // hands the builder a tree with the cyclic instance stripped), so the
        // rejection is the diagnostic's; the builder must still not build it.
        with_assertion(
            "sequence s(p); p ##1 b; endsequence",
            "assert property (@(posedge clk) s(s(a)));",
            true,
            |r, _, diags| {
                let e = crate::sva::named::check_named_sequence_cycles(diags)
                    .expect_err("slang reports s(s(a)) as a cycle");
                assert!(e.message.contains("cyclic dependency"), "{e}");
                assert!(r.is_err(), "the builder must not build a cyclic instance");
            },
        );
    }

    /// 16.8's graph has an edge X -> Y when X's declaration instantiates Y, or
    /// an instance of X instantiates Y within an actual argument. `outer(inner(a))`
    /// is `outer -> inner` only (twice): there is no cycle, and the flattened
    /// `inner(inner(a)) ##1 c` is legal. The builder must not mistake the actual's
    /// `inner` instance, expanded while `outer`'s frame is on the stack, for a
    /// re-entry of `inner`.
    #[test]
    fn an_actual_that_instantiates_a_sequence_the_callee_also_instantiates_is_legal() {
        let decls = "sequence inner(p); p ##1 b; endsequence\n\
                     sequence outer(w); inner(w) ##1 c; endsequence";
        let nested = built(
            decls,
            "assert property (@(posedge clk) outer(inner(a)));",
            8,
        );
        let inline = built(
            "",
            "assert property (@(posedge clk) a ##1 b ##1 b ##1 c);",
            8,
        );
        assert_eq!(
            nested.lang,
            Lang::from([word(&[&["a"], &["b"], &["b"], &["c"]])])
        );
        assert_eq!(nested.lang, inline.lang);
        assert_eq!(nested.leaves, inline.leaves);
        // The same through another declaration, where slang never checks.
        let via_user = built(
            "sequence inner(p); p ##1 b; endsequence\n\
             sequence outer(w); inner(w) ##1 c; endsequence\n\
             sequence user; outer(inner(a)); endsequence",
            "assert property (@(posedge clk) user);",
            8,
        );
        assert_eq!(via_user.lang, nested.lang);
        // Deeper: the actual instantiates the callee's own callee's callee,
        // and the formal is forwarded through two declarations (`w` -> `q` ->
        // `p`), so the forwarded actual must keep its call-site chain.
        let deep = built(
            "sequence inner(p); p ##1 b; endsequence\n\
             sequence mid(q); inner(q) ##1 d; endsequence\n\
             sequence outer(w); mid(w) ##1 c; endsequence",
            "assert property (@(posedge clk) outer(mid(inner(a))));",
            12,
        );
        let deep_inline = built(
            "",
            "assert property (@(posedge clk) a ##1 b ##1 b ##1 d ##1 b ##1 d ##1 c);",
            12,
        );
        assert_eq!(deep.lang, deep_inline.lang);
        assert_eq!(deep.leaves, deep_inline.leaves);
        // A bound inside the doubly-expanded declaration must be read from the
        // innermost expansion of it: `k` is 1 for the wrapper's own `inner` and
        // 3 for the actual's.
        let bound = built(
            "sequence inner(p, int k); p ##k b; endsequence\n\
             sequence outer(w); inner(w, 1) ##1 c; endsequence",
            "assert property (@(posedge clk) outer(inner(a, 3)));",
            12,
        );
        assert_eq!(
            bound.lang,
            Lang::from([word(&[&["a"], &[], &[], &["b"], &["b"], &["c"]])])
        );
        // A repeated formal reference expands the actual once per reference,
        // each under the call-site chain.
        let twice = built(
            "sequence inner(p); p ##1 b; endsequence\n\
             sequence outer(w); w ##1 w; endsequence",
            "assert property (@(posedge clk) outer(inner(a)));",
            8,
        );
        assert_eq!(
            twice.lang,
            Lang::from([word(&[&["a"], &["b"], &["a"], &["b"]])])
        );
        // The actual is a zero-argument instance: no declaration to name, but
        // its body's own instances must still be expanded in its own context.
        let zero = built(
            "sequence inner(p); p ##1 b; endsequence\n\
             sequence zs; inner(a); endsequence\n\
             sequence outer(w); inner(w) ##1 c; endsequence",
            "assert property (@(posedge clk) outer(zs));",
            8,
        );
        assert_eq!(
            zero.lang,
            Lang::from([word(&[&["a"], &["b"], &["b"], &["c"]])])
        );
    }

    /// The false-positive fix must not hide a real cycle: a declaration whose
    /// BODY re-enters itself is still refused, with the declarations named.
    #[test]
    fn a_real_body_cycle_is_still_rejected_after_the_actual_argument_fix() {
        // `user` instantiates `s` inside `s`'s own actual: the s(s(a)) self-edge.
        let e = built_err(
            "sequence s(p); p ##1 b; endsequence\n\
             sequence user; s(s(a)); endsequence",
            "assert property (@(posedge clk) user);",
        );
        assert!(e.message.contains("cyclic dependency"), "{e}");
        // The cycle closes through a forwarded formal: `user` passes `wrap(a)`
        // to `s` (edge s -> wrap, an instance within an actual argument), and
        // `wrap`'s body instantiates `s` (edge wrap -> s). Neither declaration
        // text holds the cycle, and the forwarded actual must keep its
        // call-site chain `user -> s` for the builder to see it.
        let e = built_err(
            "sequence s(p); p ##1 b; endsequence\n\
             sequence wrap(w); s(w); endsequence\n\
             sequence user; s(wrap(a)); endsequence",
            "assert property (@(posedge clk) user);",
        );
        assert!(e.message.contains("cyclic dependency"), "{e}");
        assert!(
            e.message.contains("`s`") && e.message.contains("`wrap`"),
            "{e}"
        );
        // The same through a formal forwarded one level (`w` -> `p`): `user`
        // passes `bb2(a)` to `fa` (edge fa -> bb2), `bb2`'s body instantiates
        // `fa` (edge bb2 -> fa). Only the forwarded actual's own call-site
        // chain `user -> fa` shows the cycle when `bb2` is expanded.
        let e = built_err(
            "sequence fc(p); p; endsequence\n\
             sequence fa(w); fc(w); endsequence\n\
             sequence bb2(q); fa(q); endsequence\n\
             sequence user; fa(bb2(a)); endsequence",
            "assert property (@(posedge clk) user);",
        );
        assert!(e.message.contains("cyclic dependency"), "{e}");
        assert!(
            e.message.contains("`fa`") && e.message.contains("`bb2`"),
            "{e}"
        );
    }

    /// A property instance is loud when a SEQUENCE is required, never built as
    /// a sequence: `build_property` owns it.
    #[test]
    fn property_instance_is_a_loud_error_in_the_sequence_builder() {
        let e = built_err(
            "property p0(q); q ##1 b; endproperty",
            "assert property (@(posedge clk) p0(a));",
        );
        assert!(e.message.contains("property instance"), "{e}");
        assert!(e.message.contains("build_property"), "{e}");
    }

    /// Local variable formals and declarations (T13, formerly a loud pending
    /// error) build, and an unused variable does not change the automaton's
    /// language.
    #[test]
    fn local_variables_in_a_sequence_build() {
        let with_formal = built(
            "sequence s(p, local logic v); p ##1 b; endsequence",
            "assert property (@(posedge clk) s(a, 1'b1));",
            6,
        );
        let with_local = built(
            "sequence s; logic v; a ##1 b; endsequence",
            "assert property (@(posedge clk) s);",
            6,
        );
        let plain = built("", "assert property (@(posedge clk) a ##1 b);", 6);
        assert_eq!(with_formal.lang, plain.lang);
        assert_eq!(with_local.lang, plain.lang);
    }

    /// What T28 reports about an assertion's clocks: how many distinct clocks
    /// it has, the clock its automaton starts in, and every
    /// [`ir::Transition::ClockSync`] as `(to, strict)`, in state order.
    fn clock_info(decls: &str, stmt: &str) -> (usize, ClockId, Vec<(u32, bool)>) {
        with_assertion(decls, stmt, false, |r, _, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("`{stmt}` failed to build: {e}"));
            let syncs = au
                .states
                .iter()
                .flat_map(|st| &st.edges)
                .filter_map(|e| match &e.label {
                    Transition::ClockSync { to, strict } => Some((to.0, *strict)),
                    _ => None,
                })
                .collect();
            (leaves.clock_count(), au.entry_clock, syncs)
        })
    }

    /// A second clocking event inside one automaton is a second clock (16.13.1,
    /// T28; formerly a loud error): two clocked sequences joined by `##1`
    /// build one automaton with a strict clock change between them, and `##0`
    /// is the overlapping change.
    #[test]
    fn a_second_clocking_event_is_a_second_clock() {
        let decls = "sequence sa; @(posedge clk) a ##1 b; endsequence\n\
                     sequence sb; @(negedge clk) c ##1 d; endsequence";
        let (clocks, entry, syncs) = clock_info(decls, "assert property (sa ##1 sb);");
        assert_eq!(clocks, 2);
        assert_eq!(entry, ClockId(0));
        assert_eq!(syncs, [(1, true)]);
        let (_, _, syncs) = clock_info(decls, "assert property (sa ##0 sb);");
        assert_eq!(syncs, [(1, false)]);
    }

    /// LRM 16.13: an assertion clocked `@(negedge clk)` that instantiates a
    /// sequence clocked `@(posedge sysclk)` runs the sequence on its OWN clock
    /// (the instance's `@(...)` is the clock of its Boolean operands), so the
    /// automaton starts in that clock. The stripped root clock takes part in
    /// the comparison (an equal event is transparent, a different one is a
    /// second clock).
    #[test]
    fn a_root_clock_differing_from_an_instances_clock_leads_with_the_instance() {
        let decls = "sequence s; @(posedge sysclk) a ##1 b; endsequence";
        // Different edge of the same signal, different signal, same edge.
        for (root, differs) in [
            ("@(negedge clk)", true),
            ("@(posedge clk)", true),
            ("@(posedge sysclk)", false),
        ] {
            let stmt = format!("assert property ({root} s);");
            if differs {
                let (clocks, entry, syncs) = clock_info(decls, &stmt);
                assert!(syncs.is_empty(), "{root}: nothing changes clock inside s");
                assert_eq!(clocks, 2, "{root}");
                assert_eq!(entry, ClockId(1), "{root}: s runs on its own clock");
            } else {
                // The same event is transparent: identical to the unclocked
                // sequence body written inline under that root.
                let b = built(decls, &stmt, 4);
                let inline = built("", "assert property (@(posedge sysclk) a ##1 b);", 4);
                assert_eq!(b.debug, inline.debug, "{root}");
                assert_eq!(b.lang, Lang::from([word(&[&["a"], &["b"]])]));
            }
        }
        // An `event` formal resolves to the actual before the comparison: the
        // instance's `@(ev)` is the root's `posedge clk` when passed so, and a
        // different event when passed `negedge clk`.
        let ev = "sequence es(event ev); @(ev) a ##1 b; endsequence";
        let ok = built(ev, "assert property (@(posedge clk) es(posedge clk));", 4);
        assert_eq!(ok.lang, Lang::from([word(&[&["a"], &["b"]])]));
        let (clocks, entry, _) =
            clock_info(ev, "assert property (@(posedge clk) es(negedge clk));");
        assert_eq!((clocks, entry), (2, ClockId(1)));
        // A sequence with no clock of its own is clocked by the root, as ever.
        let plain = built(
            "sequence u; a ##1 b; endsequence",
            "assert property (@(negedge clk) u);",
            4,
        );
        assert_eq!(plain.lang, Lang::from([word(&[&["a"], &["b"]])]));
        let (clocks, entry, _) = clock_info(
            "sequence u; a ##1 b; endsequence",
            "assert property (@(negedge clk) u);",
        );
        assert_eq!((clocks, entry), (1, ClockId(0)));
    }

    /// The clock comparison is exact (LRM 16.13): events that differ only in
    /// an operator, a select index, a literal or an `iff` condition are
    /// different clocks, never one flattened clock. Each pair is checked both
    /// ways round (instance vs root, root vs instance), and the identical
    /// event is checked to be ONE clock so the test cannot pass by splitting
    /// everything.
    #[test]
    fn clocking_events_differing_only_in_operator_index_or_iff_are_different_clocks() {
        let pairs: &[(&str, &str)] = &[
            ("@(posedge (a | b))", "@(posedge (a & b))"),
            ("@(posedge (a ^ b))", "@(posedge (a & b))"),
            ("@(posedge bb[1])", "@(posedge bb[0])"),
            ("@(posedge clk iff (n == 2))", "@(posedge clk iff (n == 1))"),
            ("@(posedge clk iff (n == 1))", "@(posedge clk)"),
            ("@(posedge clk or posedge a)", "@(posedge clk or negedge a)"),
            ("@(posedge clk or posedge a)", "@(posedge clk)"),
            ("@(posedge ~a)", "@(posedge !a)"),
        ];
        for (inst_ev, root_ev) in pairs {
            for (decl_ev, root) in [(inst_ev, root_ev), (root_ev, inst_ev)] {
                let decls = format!("sequence s; {decl_ev} c ##1 d; endsequence");
                let (clocks, _, _) = clock_info(&decls, &format!("assert property ({root} s);"));
                assert_eq!(clocks, 2, "{decl_ev} vs {root}");
            }
            // The same event on both sides is one clock.
            let decls = format!("sequence s; {inst_ev} c ##1 d; endsequence");
            let stmt = format!("assert property ({inst_ev} s);");
            let (clocks, _, _) = clock_info(&decls, &stmt);
            assert_eq!(clocks, 1, "{inst_ev}");
            let b = built(&decls, &stmt, 4);
            assert_eq!(b.lang, Lang::from([word(&[&["c"], &["d"]])]), "{inst_ev}");
        }
        // Two instances inside one property, differing only in an operand.
        let (clocks, _, syncs) = clock_info(
            "sequence sa; @(posedge (a | b)) c ##1 d; endsequence\n\
             sequence sb; @(posedge (a & b)) c ##1 d; endsequence",
            "assert property (sa ##1 sb);",
        );
        assert_eq!((clocks, syncs), (2, vec![(1, true)]));
    }

    /// The expansion is a pure function of the design: building twice gives
    /// the identical automaton and leaf table.
    #[test]
    fn instance_expansion_is_deterministic() {
        let decls = "sequence inner(p, int k); p ##k b; endsequence\n\
                     sequence outer(w, int d); inner(w, d)[*1:2] ##1 c; endsequence";
        let stmt = "assert property (@(posedge clk) outer(a, 2) ##1 outer(b, 1));";
        let first = built(decls, stmt, 10);
        let second = built(decls, stmt, 10);
        assert_eq!(first.debug, second.debug);
        assert_eq!(first.leaves, second.leaves);
        assert!(!first.lang.is_empty());
    }

    // -- T13: local variables, LRM 16.10 / 16.8.2 / F.5.4 -------------------

    /// Module-level declarations every T13 fixture shares: the data signals
    /// the LRM's examples use (`int`, so a local `int x = data` needs no
    /// narrowing), and `` `true ``, the LRM's own shorthand in its flow
    /// examples, which is no predefined macro.
    const LV: &str = "`define true 1\nint data, data1, data2, data_in, data_out, do1;\n";

    /// `LV` plus one fixture's own declarations.
    fn lv(decls: &str) -> String {
        format!("{LV}{decls}")
    }

    /// The build result of a design slang accepts, as `Ok(())` or the error.
    fn builds(decls: &str, stmt: &str) -> Result<(), LoweringError> {
        with_assertion(decls, stmt, false, |r, _, _| r.map(|_| ()))
    }

    /// 16.10 intuitive rule (a): variables assigned on parallel threads
    /// cannot be accessed in sibling threads. LRM example `s4`, verbatim.
    #[test]
    fn t13_s4_a_sibling_thread_read_does_not_flow() {
        let e = built_err(
            &lv("sequence s4;\n\
                   int x;\n\
                   (a ##1 (b, x = data) ##1 c) or (d ##1 (e==x)); // illegal\n\
                 endsequence"),
            "assert property (@(posedge clk) s4);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`x`"),
            "{e}"
        );
    }

    /// 16.10 rule (c), `s5`: `y` is assigned on one `or` branch only, so it is
    /// not in the intersection and the read after the `or` is illegal.
    #[test]
    fn t13_s5_a_variable_assigned_on_one_or_branch_does_not_flow_out() {
        let e = built_err(
            &lv("sequence s5;\n\
                   int x,y;\n\
                   ((a ##1 (b, x = data, y = data1) ##1 c)\n\
                      or (d ##1 (`true, x = data) ##0 (e==x))) ##1 (y==data2);\n\
                   // illegal because y is not in the intersection\n\
                 endsequence"),
            "assert property (@(posedge clk) s5);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`y`"),
            "{e}"
        );
    }

    /// 16.10 rule (c), `s6`: `x` is assigned on both `or` branches, so it is in
    /// the intersection and the read after the `or` is legal.
    #[test]
    fn t13_s6_a_variable_assigned_on_both_or_branches_flows_out() {
        builds(
            &lv("sequence s6;\n\
                   int x,y;\n\
                   ((a ##1 (b, x = data, y = data1) ##1 c)\n\
                      or (d ##1 (`true, x = data) ##0 (e==x))) ##1 (x==data2);\n\
                   // legal because x is in the intersection\n\
                 endsequence"),
            "assert property (@(posedge clk) s6);",
        )
        .unwrap();
    }

    /// 16.10 rule (d), `s7`: `x` is assigned in and flows out of each `and`
    /// operand, so it is blocked.
    #[test]
    fn t13_s7_a_variable_assigned_in_both_and_operands_is_blocked() {
        let e = built_err(
            &lv("sequence s7;\n\
                   int x,y;\n\
                   ((a ##1 (b, x = data, y = data1) ##1 c)\n\
                      and (d ##1 (`true, x = data) ##0 (e==x))) ##1 (x==data2);\n\
                   // illegal because x is common to both threads\n\
                 endsequence"),
            "assert property (@(posedge clk) s7);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`x`"),
            "{e}"
        );
    }

    /// 16.10 rule (d), `s8`: `y` is assigned in one `and` operand only (the
    /// difference), so it flows out.
    #[test]
    fn t13_s8_a_variable_in_the_and_difference_flows_out() {
        builds(
            &lv("sequence s8;\n\
                   int x,y;\n\
                   ((a ##1 (b, x = data, y = data1) ##1 c)\n\
                      and (d ##1 (`true, x = data) ##0 (e==x))) ##1 (y==data2);\n\
                   // legal because y is in the difference\n\
                 endsequence"),
            "assert property (@(posedge clk) s8);",
        )
        .unwrap();
    }

    // -- T13: value semantics, driven through the reference interpreter -------

    /// The value of the leaf expression `e` for one thread: signals come from
    /// `sig(name, tick)`, a local variable from the thread's `frame` through
    /// the slot the builder recorded in `locals`. The subset of expressions
    /// the T13 fixtures use; anything else panics rather than guessing.
    fn eval_leaf_expr<'d>(
        e: Expression<'d>,
        locals: &LeafLocals<'d>,
        frame: &[Option<i64>],
        tick: u32,
        sig: &dyn Fn(&str, u32) -> i64,
    ) -> Result<i64, trace::TraceError> {
        eval_leaf_node(e, locals, frame, tick, sig, &std::cell::Cell::new(0))
    }

    /// [`eval_leaf_expr`] for leaf `id` of `leaves`: a negated leaf (a goto gap)
    /// is `!expr`. The values here are 2-state integers, so a negation is plain.
    fn eval_leaf_id<'d>(
        leaves: &LeafTable<'d>,
        id: LeafId,
        frame: &[Option<i64>],
        tick: u32,
        sig: &dyn Fn(&str, u32) -> i64,
    ) -> Result<i64, trace::TraceError> {
        let v = eval_leaf_expr(leaves.get(id), leaves.locals_of(id), frame, tick, sig)?;
        Ok(if leaves.is_negated(id) {
            i64::from(v == 0)
        } else {
            v
        })
    }

    /// [`eval_leaf_expr`]'s walk. `next_flag` counts the end-point applications
    /// met so far: operands are evaluated left to right with no short-circuit, so
    /// the n-th application met is the n-th of [`LeafLocals::end_flags`] (T15,
    /// the pre-order the builder lists them in) -- and the test below that pins a
    /// leaf with two applications fails if that order ever drifts.
    fn eval_leaf_node<'d>(
        e: Expression<'d>,
        locals: &LeafLocals<'d>,
        frame: &[Option<i64>],
        tick: u32,
        sig: &dyn Fn(&str, u32) -> i64,
        next_flag: &std::cell::Cell<usize>,
    ) -> Result<i64, trace::TraceError> {
        let kids = e.as_sem_node().children();
        let sub = |i: usize| -> Result<i64, trace::TraceError> {
            let k = kids[i]
                .as_expression()
                .expect("an operand of a leaf expression is an expression");
            eval_leaf_node(k, locals, frame, tick, sig, next_flag)
        };
        if end_point_call(e).is_some() {
            let n = next_flag.get();
            next_flag.set(n + 1);
            return trace::read_local(frame, locals.end_flags[n]);
        }
        match e.kind() {
            ExpressionKind::IntegerLiteral => Ok(e
                .integer_literal_value()
                .and_then(|v| v.as_i64())
                .expect("an integer literal fits an i64")),
            ExpressionKind::NamedValue => {
                let sym = e.referenced_symbol().expect("a named value has a symbol");
                match locals.reads.iter().find(|(s, _)| *s == sym) {
                    Some((_, slot)) => trace::read_local(frame, *slot),
                    None => Ok(sig(sym.name(), tick)),
                }
            }
            ExpressionKind::LValueReference => trace::read_local(
                frame,
                locals
                    .lvalue
                    .expect("an LValueReference leaf has an lvalue"),
            ),
            ExpressionKind::Conversion => sub(0),
            ExpressionKind::UnaryOp => match e.unary_op() {
                Some(sv_lang::UnaryOp::LogicalNot) => Ok(i64::from(sub(0)? == 0)),
                other => panic!("test evaluator: unary operator {other:?}"),
            },
            ExpressionKind::BinaryOp => {
                let (l, r) = (sub(0)?, sub(1)?);
                match e.binary_op() {
                    Some(sv_lang::BinaryOp::Add) => Ok(l + r),
                    Some(sv_lang::BinaryOp::Subtract) => Ok(l - r),
                    Some(sv_lang::BinaryOp::Equality) => Ok(i64::from(l == r)),
                    Some(sv_lang::BinaryOp::LessThanEqual) => Ok(i64::from(l <= r)),
                    Some(sv_lang::BinaryOp::LogicalAnd) => Ok(i64::from(l != 0 && r != 0)),
                    Some(sv_lang::BinaryOp::LogicalOr) => Ok(i64::from(l != 0 || r != 0)),
                    other => panic!("test evaluator: binary operator {other:?}"),
                }
            }
            other => panic!("test evaluator: expression kind {other:?}"),
        }
    }

    /// One attempt per start tick of `stmt`'s sequence over a trace of integer
    /// signals (`(name, value per tick)`, every row the same length, every
    /// signal a leaf reads listed), plus the slot each local variable's LAST
    /// reading leaf reads (so a test can look a variable up in a match's frame).
    struct Ran {
        attempts: Vec<trace::LocalAttempt>,
        slots: BTreeMap<String, LocalVarId>,
    }

    /// One attempt per `starts` entry of an already built automaton over
    /// `signals` (see [`Ran`]).
    fn attempts_on(
        au: &ir::Automaton,
        leaves: &LeafTable<'_>,
        signals: &[(&str, &[i64])],
        starts: &[u32],
    ) -> Vec<trace::LocalAttempt> {
        let len = signals[0].1.len() as u32;
        assert!(signals.iter().all(|(_, row)| row.len() as u32 == len));
        let sig = |name: &str, t: u32| -> i64 {
            signals
                .iter()
                .find(|(n, _)| *n == name)
                .unwrap_or_else(|| panic!("the trace has no signal `{name}`"))
                .1[t as usize]
        };
        starts
            .iter()
            .map(|&s| {
                trace::attempt_with_locals(au, s, len, &|id, tick, frame| {
                    eval_leaf_id(leaves, id, frame, tick, &sig)
                })
                .unwrap_or_else(|e| panic!("trace interpreter: {e}"))
            })
            .collect()
    }

    fn local_run(decls: &str, stmt: &str, signals: &[(&str, &[i64])], starts: &[u32]) -> Ran {
        with_assertion(&lv(decls), stmt, false, |r, _, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("`{stmt}` failed to build: {e}"));
            let attempts = attempts_on(&au, &leaves, signals, starts);
            let mut slots = BTreeMap::new();
            for i in 0..leaves.len() as u32 {
                for (sym, slot) in &leaves.locals_of(LeafId(i)).reads {
                    slots.insert(sym.name().to_string(), *slot);
                }
            }
            Ran { attempts, slots }
        })
    }

    /// The `(end tick, value of variable `var`)` pairs of attempt `i`.
    fn ends_with(ran: &Ran, i: usize, var: &str) -> BTreeSet<(u32, Option<i64>)> {
        let slot = ran.slots[var].0 as usize;
        ran.attempts[i]
            .matches
            .iter()
            .map(|(t, f)| (*t, f[slot]))
            .collect()
    }

    /// The `(variable, value leaf)` of every initialisation write on the
    /// straight-line prefix of `au`'s start, in the order they run.
    fn init_writes(au: &ir::Automaton) -> Vec<(LocalVarId, LeafId)> {
        let mut writes = Vec::new();
        let mut st = au.start;
        while let [edge] = au.state(st).edges.as_slice() {
            // The first guarded edge is the body's first Boolean leaf.
            if edge.guard.is_some() {
                break;
            }
            match &edge.label {
                Transition::LocalVarWrite { var, value } => writes.push((*var, *value)),
                Transition::Epsilon => {}
                _ => break,
            }
            st = edge.target;
        }
        writes
    }

    /// 16.8.2: an `input` formal starts as the actual, and a declared local's
    /// initialiser (`int v = f + 1`) may read it, because the formals'
    /// assignments come first. Also pins the build-time ORDER of the action
    /// list on the entry: the formal's write precedes the declared one.
    #[test]
    fn t13_input_formals_are_initialised_before_declared_locals() {
        let decls = "sequence q(local input int f); int v = f + 1; a ##1 (v == 8); endsequence";
        let stmt = "assert property (@(posedge clk) q(7));";
        with_assertion(&lv(decls), stmt, false, |r, tree, _| {
            let (au, leaves) = r.unwrap();
            let texts = leaf_texts(&leaves, tree);
            let writes = init_writes(&au);
            assert_eq!(writes.len(), 2, "one write per formal and per initialiser");
            assert_eq!(texts[writes[0].1.0 as usize], "7");
            // slang substitutes a typed `local input` formal's actual into a
            // declared initializer (the leaf is `7 + 1`, its source text
            // `f + 1`), so the formal's write is the FIRST action and the
            // second one needs no slot read; what pins the order is the
            // action list itself.
            assert_eq!(texts[writes[1].1.0 as usize], "f+1");
        });
        let sigs: [(&str, &[i64]); 1] = [("a", &[1, 0, 0])];
        let ran = local_run(decls, stmt, &sigs, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([1]), "7 + 1 == 8");
        let ran = local_run(decls, "assert property (@(posedge clk) q(6));", &sigs, &[0]);
        assert!(ran.attempts[0].matches.is_empty(), "6 + 1 != 8");
    }

    /// 16.8.2: the actual is CAST to the formal's type: `19` into a 4-bit
    /// formal is `3`.
    #[test]
    fn t13_the_input_actual_is_cast_to_the_formals_type() {
        let decls = "sequence q(local input logic [3:0] r); a ##1 (r == 3); endsequence";
        let sigs: [(&str, &[i64]); 1] = [("a", &[1, 0])];
        let ran = local_run(
            decls,
            "assert property (@(posedge clk) q(19));",
            &sigs,
            &[0],
        );
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([1]));
        let ran = local_run(
            decls,
            "assert property (@(posedge clk) q(18));",
            &sigs,
            &[0],
        );
        assert!(ran.attempts[0].matches.is_empty());
    }

    /// 16.8.2: declared locals are initialised in declaration order (`t = v + 1`
    /// reads the initialised `v`), and an uninitialised one is assigned by a
    /// match item before its read.
    #[test]
    fn t13_declared_initialisers_run_in_declaration_order() {
        let decls = "sequence w; int v = data + 1, t = v + 1; int u; (a, u = v) ##1 (u + 1 == t); endsequence";
        let stmt = "assert property (@(posedge clk) w);";
        let sigs: [(&str, &[i64]); 2] = [("a", &[1, 0]), ("data", &[4, 0])];
        let ran = local_run(decls, stmt, &sigs, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([1]));
        // The action list itself: `t`'s initializer runs after `v`'s and reads
        // `v`'s slot (a local read is never substituted by slang).
        with_assertion(&lv(decls), stmt, false, |r, _, _| {
            let (au, leaves) = r.unwrap();
            let writes = init_writes(&au);
            assert_eq!(writes.len(), 2);
            let reads: Vec<LocalVarId> = leaves
                .locals_of(writes[1].1)
                .reads
                .iter()
                .map(|(_, s)| *s)
                .collect();
            assert_eq!(reads, [writes[0].0]);
        });
    }

    /// 16.8.2: an `output` formal is written back to the caller's variable
    /// when the instance matches, and the caller then reads the value.
    #[test]
    fn t13_an_output_formal_flows_back_to_the_callers_variable() {
        let decls = "sequence o(local output int q, local input logic [3:0] r);\n\
                       (a, q = r) ##1 b;\n\
                     endsequence\n\
                     sequence seven; int g; o(g, 4'd7) ##1 (g == 7); endsequence\n\
                     sequence eight; int g; o(g, 4'd7) ##1 (g == 8); endsequence";
        let sigs: [(&str, &[i64]); 2] = [("a", &[1, 0, 0]), ("b", &[0, 1, 0])];
        let ran = local_run(
            decls,
            "assert property (@(posedge clk) seven);",
            &sigs,
            &[0],
        );
        assert_eq!(ends_with(&ran, 0, "g"), BTreeSet::from([(2, Some(7))]));
        let ran = local_run(
            decls,
            "assert property (@(posedge clk) eight);",
            &sigs,
            &[0],
        );
        assert!(ran.attempts[0].matches.is_empty());
    }

    /// 16.8.2's own example: `seq2` (an `inout` formal) and `seq2_inlined`
    /// "match equivalently". Checked on the LRM-shaped trace by value and on
    /// 400 pseudo-random traces by end tick, over every start tick.
    #[test]
    fn t13_sub_seq2_matches_like_seq2_inlined() {
        let decls = "sequence sub_seq2(local inout int lv);\n\
                       (a ##1 !a, lv += data_in) ##1 !b[*0:$] ##1 b && (data_out == lv);\n\
                     endsequence\n\
                     sequence seq2; int v1; (c, v1 = data) ##1 sub_seq2(v1) ##1 (do1 == v1); endsequence\n\
                     sequence seq2_inlined;\n\
                       int v1, lv;\n\
                       (c, v1 = data) ##1\n\
                       ((1, lv = v1) ##0 (a ##1 !a, lv += data_in)\n\
                         ##1 (!b[*0:$] ##1 b && (data_out == lv), v1 = lv))\n\
                       ##1 (do1 == v1);\n\
                     endsequence";
        let (s2, inl) = (
            "assert property (@(posedge clk) seq2);",
            "assert property (@(posedge clk) seq2_inlined);",
        );
        // c@0 with data=3 starts v1 = 3; a@1, !a@2 with data_in=4 makes lv = 7;
        // b@3 with data_out == 7 ends the sub-sequence and writes v1 = 7 back;
        // do1@4 is compared against the WRITTEN-BACK 7.
        let row = |data_out: i64, do1: i64| -> [(&'static str, Vec<i64>); 7] {
            [
                ("a", vec![0, 1, 0, 0, 0, 0]),
                ("b", vec![0, 0, 0, 1, 0, 0]),
                ("c", vec![1, 0, 0, 0, 0, 0]),
                ("data", vec![3, 0, 0, 0, 0, 0]),
                ("data_in", vec![0, 0, 4, 0, 0, 0]),
                ("data_out", vec![0, 0, 0, data_out, 0, 0]),
                ("do1", vec![0, 0, 0, 0, do1, 0]),
            ]
        };
        for (data_out, do1, want) in [
            (7, 7, Some(4)),
            (7, 3, None), // do1 sees the old v1 (3), not the written-back 7
            (3, 7, None), // data_out disagrees with lv (7)
        ] {
            let r = row(data_out, do1);
            let sigs: Vec<(&str, &[i64])> = r.iter().map(|(n, v)| (*n, v.as_slice())).collect();
            for stmt in [s2, inl] {
                let ran = local_run(decls, stmt, &sigs, &[0]);
                assert_eq!(
                    ran.attempts[0].ends(),
                    want.into_iter().collect::<BTreeSet<u32>>(),
                    "{stmt} with data_out={data_out} do1={do1}"
                );
            }
        }
        let mut seed = 0x2545_f491_4f6c_dd1du64;
        let mut next = move |m: u64| {
            seed = seed
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((seed >> 33) % m) as i64
        };
        // Both automata are built once; every trace is run through each.
        let build = |stmt: &str, f: &mut dyn FnMut(&ir::Automaton, &LeafTable<'_>)| {
            with_assertion(&lv(decls), stmt, false, |r, _, _| {
                let (au, leaves) = r.unwrap_or_else(|e| panic!("`{stmt}` failed to build: {e}"));
                f(&au, &leaves);
            });
        };
        let traces: Vec<Vec<(&str, Vec<i64>)>> = (0..4000)
            .map(|_| {
                [
                    ("a", 2),
                    ("b", 2),
                    ("c", 2),
                    ("data", 2),
                    ("data_in", 2),
                    ("data_out", 3),
                    ("do1", 3),
                ]
                .iter()
                .map(|&(name, m)| (name, (0..8).map(|_| next(m)).collect()))
                .collect()
            })
            .collect();
        let starts: Vec<u32> = (0..8).collect();
        let mut ends: Vec<Vec<BTreeSet<u32>>> = Vec::new();
        for stmt in [s2, inl] {
            let mut per_trace = Vec::new();
            build(stmt, &mut |au, leaves| {
                for rows in &traces {
                    let sigs: Vec<(&str, &[i64])> =
                        rows.iter().map(|(n, v)| (*n, v.as_slice())).collect();
                    for at in attempts_on(au, leaves, &sigs, &starts) {
                        per_trace.push(at.ends());
                    }
                }
            });
            ends.push(per_trace);
        }
        assert_eq!(ends[0], ends[1], "seq2 and seq2_inlined disagree");
        let matched = ends[0].iter().filter(|e| !e.is_empty()).count();
        assert!(
            matched >= 100,
            "only {matched} attempts matched; the sweep is vacuous"
        );
    }

    /// 16.10 rule (d): an `and`'s operands are parallel threads, each with its
    /// OWN copy of every variable, initialised from the value at the operator's
    /// start. The second operand reads `x == 5` while the first has assigned 9
    /// (so a shared slot would fail), and the variable only the first operand
    /// assigns flows out with its value.
    #[test]
    fn t13_and_operands_own_their_copies_and_the_difference_flows_out() {
        // (`##` binds tighter than `and`, hence the outer parentheses.)
        let decls = "sequence s; int x = 5; (((a, x = 9) ##1 b) and (c ##1 (x == 5))) ##1 (x == 9); endsequence";
        let sigs: [(&str, &[i64]); 3] = [("a", &[1, 0, 0]), ("b", &[0, 1, 0]), ("c", &[1, 0, 0])];
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &sigs, &[0]);
        assert_eq!(ends_with(&ran, 0, "x"), BTreeSet::from([(2, Some(9))]));
    }

    /// The variable only the SECOND operand of an `and` assigns is copied out
    /// of its shadow, so the read after the `and` sees it (s8's `y`, by value).
    #[test]
    fn t13_a_variable_only_the_second_and_operand_assigns_is_copied_out() {
        // The first operand READS `y` (so `y` is shadowed in the second, which
        // assigns it) and assigns `x`; both flow out of the `and`.
        let decls = "sequence s; int x, y = 0; ((a ##1 (b, x = data) ##0 (y == 0)) and (c ##1 (d, y = data1))) ##1 (x == 1 && y == 2); endsequence";
        let sigs = |data1: i64| -> [(&'static str, Vec<i64>); 6] {
            [
                ("a", vec![1, 0, 0]),
                ("b", vec![0, 1, 0]),
                ("c", vec![1, 0, 0]),
                ("d", vec![0, 1, 0]),
                ("data", vec![0, 1, 0]),
                ("data1", vec![0, data1, 0]),
            ]
        };
        let r = sigs(2);
        let view: Vec<(&str, &[i64])> = r.iter().map(|(n, v)| (*n, v.as_slice())).collect();
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &view, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([2]));
        let r = sigs(3);
        let view: Vec<(&str, &[i64])> = r.iter().map(|(n, v)| (*n, v.as_slice())).collect();
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &view, &[0]);
        assert!(ran.attempts[0].matches.is_empty());
    }

    /// 16.10 rule (c): an `or`'s two threads are independent; the variable
    /// assigned on both branches flows out with the value of the thread that
    /// matched (s6's `x`, by value).
    #[test]
    fn t13_or_flows_the_value_of_the_matching_branch() {
        let decls = "sequence s; int x; ((a ##1 (b, x = data)) or (c ##1 (d, x = data1))) ##1 (x == 5); endsequence";
        let first: [(&str, &[i64]); 6] = [
            ("a", &[1, 0, 0]),
            ("b", &[0, 1, 0]),
            ("c", &[0, 0, 0]),
            ("d", &[0, 0, 0]),
            ("data", &[0, 5, 0]),
            ("data1", &[0, 9, 0]),
        ];
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &first, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([2]));
        let second: [(&str, &[i64]); 6] = [
            ("a", &[0, 0, 0]),
            ("b", &[0, 0, 0]),
            ("c", &[1, 0, 0]),
            ("d", &[0, 1, 0]),
            ("data", &[0, 9, 0]),
            ("data1", &[0, 5, 0]),
        ];
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &second, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([2]));
    }

    /// A compound match item reads and then writes its own target: `t += data`.
    #[test]
    fn t13_a_compound_match_item_accumulates() {
        let decls =
            "sequence s; int t = 1; (a, t += data) ##1 (b, t += data) ##1 (t == 8); endsequence";
        let sigs: [(&str, &[i64]); 3] =
            [("a", &[1, 0, 0]), ("b", &[0, 1, 0]), ("data", &[3, 4, 0])];
        let ran = local_run(decls, "assert property (@(posedge clk) s);", &sigs, &[0]);
        assert_eq!(ran.attempts[0].ends(), BTreeSet::from([2]));
    }

    /// An unbounded repetition's body runs at least once for `[*1:$]`, so its
    /// assignment flows out; `[*0:$]` may not run it, so it does not. (The
    /// match item sits inside the repeated unit: a match item attached to the
    /// repeated sub-sequence itself is T14's, tested below.)
    #[test]
    fn t13_a_repetition_flows_out_only_if_it_runs_at_least_once() {
        builds(
            &lv("sequence s; int v; ((a, v = data) ##1 b)[*1:$] ##1 (v == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        )
        .unwrap();
        let e = built_err(
            &lv("sequence s; int v; ((a, v = data) ##1 b)[*0:$] ##1 (v == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`v`"),
            "{e}"
        );
    }

    /// `intersect` has `and`'s flow rule: assigned in both operands blocks, in
    /// one only flows (16.10 rule (d)).
    #[test]
    fn t13_intersect_blocks_the_common_variable_and_flows_the_difference() {
        let e = built_err(
            &lv(
                "sequence s; int x; ((a ##1 (b, x = data)) intersect (c ##1 (d, x = data1))) ##1 (x == 1); endsequence",
            ),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`x`"),
            "{e}"
        );
        builds(
            &lv("sequence s; int x; ((a ##1 (b, x = data)) intersect (c ##1 d)) ##1 (x == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        )
        .unwrap();
    }

    /// An `output` formal the body assigns on only one `or` branch does not
    /// flow out of the instance, so writing it back is an error (16.8.2).
    #[test]
    fn t13_an_output_formal_must_flow_out_of_its_body() {
        let e = built_err_lenient(
            &lv(
                "sequence o(local output int q); (a, q = data) or (b ##1 c); endsequence\n\
                 sequence s; int g; o(g) ##1 (g == 1); endsequence",
            ),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`q`"),
            "{e}"
        );
    }

    /// 16.8.2: an `inout`/`output` instance that admits an empty match is an
    /// error.
    #[test]
    fn t13_an_inout_instance_that_admits_an_empty_match_is_rejected() {
        let e = built_err_lenient(
            &lv(
                "sequence o(local inout int q); (a ##1 b)[*0:1]; endsequence\n\
                 sequence s; int g = 0; o(g) ##1 b; endsequence",
            ),
            "assert property (@(posedge clk) s);",
        );
        assert!(e.message.contains("empty match"), "{e}");
    }

    /// 16.8.2: "It shall be an error if references to the same local variable
    /// are bound as actual arguments to two or more local variable formal
    /// arguments of direction inout or output." slang does not check it, so
    /// the builder does (two `output`s, and an `inout` with an `output`).
    #[test]
    fn t13_one_local_bound_to_two_output_formals_is_rejected() {
        let e = built_err_lenient(
            &lv("sequence o(local output int p, local output int q);\n\
                   (a, p = data, q = data) ##1 b;\n\
                 endsequence\n\
                 sequence s; int g; o(g, g) ##1 (g == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("`g`")
                && e.message.contains("two or more")
                && e.message.contains("16.8.2"),
            "{e}"
        );
        let e = built_err_lenient(
            &lv("sequence o(local inout int p, local output int q);\n\
                   (a, p = data, q = data) ##1 b;\n\
                 endsequence\n\
                 sequence s; int g = 0; o(g, g) ##1 (g == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("`g`") && e.message.contains("two or more"),
            "{e}"
        );
    }

    /// The legal neighbours of the 16.8.2 duplicate-binding rule must still
    /// build: distinct locals on the two formals, and one local bound to the
    /// output of two DIFFERENT instances.
    #[test]
    fn t13_distinct_or_per_instance_output_bindings_build() {
        builds(
            &lv("sequence o(local output int p, local output int q);\n\
                   (a, p = data, q = data) ##1 b;\n\
                 endsequence\n\
                 sequence s; int g, h; o(g, h) ##1 (g == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        )
        .unwrap();
        builds(
            &lv(
                "sequence o(local output int p); (a, p = data) ##1 b; endsequence\n\
                 sequence s; int g; o(g) ##1 o(g) ##1 (g == 1); endsequence",
            ),
            "assert property (@(posedge clk) s);",
        )
        .unwrap();
    }

    /// 16.10: reading a declared local before anything assigns it is rejected
    /// (slang's own `AssertionLocalUnassigned` agrees, so the fixture is built
    /// leniently), and so is passing an unassigned caller local as an input
    /// actual.
    #[test]
    fn t13_a_read_of_an_unassigned_local_is_rejected() {
        let e = built_err_lenient(
            &lv("sequence s; int v; a ##1 (v == 1); endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`v`"),
            "{e}"
        );
        let e = built_err_lenient(
            &lv(
                "sequence o(local input int f); a ##1 (f == 1); endsequence\n\
                 sequence s; int g; o(g); endsequence",
            ),
            "assert property (@(posedge clk) s);",
        );
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`g`"),
            "{e}"
        );
    }

    /// A local variable wider than 64 bits (16.10) takes a frame slot per limb
    /// of its value and of its unknown bits (100 bits: 2 + 2), its initializer
    /// is one write per slot, and each write's leaf says which word it yields.
    #[test]
    fn t13_a_wide_local_variable_has_a_slot_and_a_leaf_per_limb() {
        with_assertion(
            &lv("sequence s; logic [99:0] v = 0; a ##1 (v == 0); endsequence"),
            "assert property (@(posedge clk) s);",
            false,
            |r, _, _| {
                let (au, leaves) = r.unwrap();
                assert_eq!(au.local_vars.len(), 4, "100 bits = 2 limbs = 4 slots");
                assert_eq!(au.local_vars[0].width, 100);
                let mut writes = Vec::new();
                for e in au.states.iter().flat_map(|s| &s.edges) {
                    if let Transition::LocalVarWrite { var, value } = &e.label {
                        writes.push((var.0, leaves.limb_of(*value), value.0));
                    }
                }
                let group = writes[0].2;
                let sel = |unknown, index| {
                    Some(LimbSel {
                        width: 100,
                        unknown,
                        index,
                        group,
                    })
                };
                assert_eq!(
                    writes.iter().map(|w| (w.0, w.1)).collect::<Vec<_>>(),
                    [
                        (0, sel(false, 0)),
                        (1, sel(false, 1)),
                        (2, sel(true, 0)),
                        (3, sel(true, 1))
                    ]
                );
            },
        );
    }

    /// An assignment whose value reads the wide target is computed into a
    /// fresh variable and copied over, so every limb sees the OLD value.
    #[test]
    fn t13_a_wide_self_assignment_goes_through_a_temporary() {
        with_assertion(
            &lv(
                "sequence s; logic [99:0] v = 0; (a, v = {v[98:0], 1'b1}) ##1 (v != 0); \
                 endsequence",
            ),
            "assert property (@(posedge clk) s);",
            false,
            |r, _, _| {
                let (au, _) = r.unwrap();
                assert_eq!(au.local_vars.len(), 8, "v and its temporary");
                let copies: Vec<_> = au
                    .states
                    .iter()
                    .flat_map(|s| &s.edges)
                    .filter_map(|e| match &e.label {
                        Transition::LocalVarCopy { dst, src } => Some((dst.0, src.0)),
                        _ => None,
                    })
                    .collect();
                assert_eq!(copies, [(0, 4)], "the temporary is copied back to `v`");
            },
        );
        // A narrow target is written in place.
        with_assertion(
            &lv("sequence s; int v = 0; (a, v = v + 1) ##1 (v != 0); endsequence"),
            "assert property (@(posedge clk) s);",
            false,
            |r, _, _| {
                let (au, _) = r.unwrap();
                assert_eq!(au.local_vars.len(), 1);
            },
        );
    }

    /// The widest local variable is a loud error naming the limit.
    #[test]
    fn t13_an_unrepresentable_local_variable_is_a_loud_error() {
        let e = built_err(
            &lv("sequence s; logic [1999999:0] v = 0; a ##1 (v == 0); endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(e.message.contains("1048576"), "{e}");
    }

    /// A match item assigns a LOCAL variable (16.11); `n` is a module variable.
    #[test]
    fn t13_a_match_item_must_assign_a_local_variable() {
        // slang diagnoses this itself ("sequence match items can only modify
        // local variables"); the builder must refuse it too, not skip it.
        let e = built_err_lenient(
            &lv("sequence s; (a, n = 1) ##1 b; endsequence"),
            "assert property (@(posedge clk) s);",
        );
        assert!(e.message.contains("local variable"), "{e}");
    }

    /// 16.10: a thread's variable never leaks between repeated instances: two
    /// uses of one sequence mint two slot sets.
    #[test]
    fn t13_every_instance_gets_its_own_variables() {
        let decls = "sequence s(local input int f); int v = f; a ##1 (v == f); endsequence";
        with_assertion(
            &lv(decls),
            "assert property (@(posedge clk) s(1) ##1 s(2));",
            false,
            |r, _, _| {
                let (au, _) = r.unwrap();
                assert_eq!(au.local_vars.len(), 4, "f and v, once per instance");
            },
        );
    }

    // -- T14: sequence match items (LRM 16.10, 16.11) ---------------------------

    /// The assertion every T14 fixture checks.
    const S: &str = "assert property (@(posedge clk) s);";

    /// 16.10's illegal example, verbatim but for the declaration of the local
    /// variable `x` (the LRM leaves it implicit): a match item attached to
    /// `b[*0:1]`, which admits the empty match.
    #[test]
    fn t14_a_match_item_on_a_subsequence_that_admits_an_empty_match_is_illegal() {
        // slang diagnoses this itself ("sequences with match items cannot
        // admit an empty match"); the builder enforces the rule independently.
        let e = built_err_lenient(
            &lv("sequence s;\n\
                   int x;\n\
                   a ##1 (b[*0:1], x = e) ##1 c[*2]; // illegal\n\
                 endsequence"),
            S,
        );
        assert!(
            e.message.contains("empty match") && e.message.contains("16.11"),
            "{e}"
        );
    }

    /// 16.10's legal example, verbatim but for the local variable: the
    /// concatenated subsequence `a ##1 b[*0:1]` cannot match the empty word.
    #[test]
    fn t14_a_match_item_on_a_concatenation_that_cannot_be_empty_is_legal() {
        builds(
            &lv("sequence s;\n\
                   int x;\n\
                   (a ##1 b[*0:1], x = e) ##1 c[*2]; // legal\n\
                 endsequence"),
            S,
        )
        .unwrap();
    }

    /// The nondegeneracy rule is the same for every kind of match item: an
    /// increment, a decrement and a subroutine call are as illegal on an
    /// empty-admitting subsequence as an assignment is, and so is an item on a
    /// `[*]`-repeated operand that admits the empty match.
    #[test]
    fn t14_every_kind_of_match_item_needs_a_nonempty_subsequence() {
        for item in [
            "x++",
            "--x",
            "x = 1",
            "x += 1",
            "$display(\"%d\", x)",
            "tk(x)",
        ] {
            let e = built_err_lenient(
                &lv(&format!(
                    "task tk(int v); endtask\n\
                     sequence s; int x = 0; a ##1 (b[*0:1], {item}) ##1 c; endsequence"
                )),
                S,
            );
            assert!(e.message.contains("empty match"), "`{item}`: {e}");
        }
        let e = built_err_lenient(
            &lv("sequence s; int x = 0; a ##1 (b[*0:1], x++)[*2] ##1 c; endsequence"),
            S,
        );
        assert!(e.message.contains("empty match"), "{e}");
    }

    /// `x++`, `x--`, `++x` and `--x` (16.11): each reads then writes the whole
    /// local variable, in list order, and the value is cast to the declared
    /// type. Driven through the reference interpreter.
    #[test]
    fn t14_increment_and_decrement_update_the_local_variable() {
        let sig: [(&str, &[i64]); 2] = [("a", &[1, 0, 0]), ("b", &[0, 1, 0])];
        let up = local_run(
            "sequence s; int x; (a, x = 10) ##1 (b, x++, x++, x++, --x) ##1 (x == 12); endsequence",
            S,
            &sig,
            &[0],
        );
        assert_eq!(ends_with(&up, 0, "x"), BTreeSet::from([(2, Some(12))]));
        let down = local_run(
            "sequence s; int x; (a, x = 10) ##1 (b, x--, x--, ++x) ##1 (x == 9); endsequence",
            S,
            &sig,
            &[0],
        );
        assert_eq!(ends_with(&down, 0, "x"), BTreeSet::from([(2, Some(9))]));
        // 2-bit unsigned: 3 + 1 wraps to 0 (the slot holds a value of the
        // variable's declared type).
        let wrap = local_run(
            "sequence s; bit [1:0] y; (a, y = 3) ##1 (b, y++) ##1 (y == 0); endsequence",
            S,
            &sig,
            &[0],
        );
        assert_eq!(ends_with(&wrap, 0, "y"), BTreeSet::from([(2, Some(0))]));
    }

    /// The implicit read of `++`/`--` (16.10): the variable must have been
    /// assigned first, exactly like `x += 1`.
    #[test]
    fn t14_increment_of_an_unassigned_local_variable_is_rejected() {
        for item in ["x++", "x--", "++x", "--x"] {
            let e = built_err(
                &lv(&format!(
                    "sequence s; int x; (a, {item}) ##1 b; endsequence"
                )),
                S,
            );
            assert!(
                e.message.contains("does not flow out") && e.message.contains("`x`"),
                "`{item}`: {e}"
            );
        }
    }

    /// A match item updates a whole LOCAL variable; `n` is a module variable.
    #[test]
    fn t14_increment_must_name_a_local_variable() {
        let e = built_err_lenient(&lv("sequence s; (a, n++) ##1 b; endsequence"), S);
        assert!(e.message.contains("local variable"), "{e}");
    }

    /// 16.10 `rep_v`, verbatim: match items on the operand of a `[*]`
    /// repetition accumulate over the repeats. `a[->1]` is the repeated unit.
    #[test]
    fn t14_rep_v_accumulates_over_a_repetition() {
        let decls = "sequence s;\n\
                       int x = 0;\n\
                       (a[->1], x += data)[*4] ##1 b ##1 c && (data_out == x);\n\
                     endsequence";
        let row = |v: &[i64]| -> Vec<i64> { v.to_vec() };
        let run = |out: i64| {
            let (a, b, c) = (
                row(&[1, 1, 1, 1, 0, 0]),
                row(&[0, 0, 0, 0, 1, 0]),
                row(&[0, 0, 0, 0, 0, 1]),
            );
            let (data, data_out) = (row(&[1, 2, 3, 4, 0, 0]), row(&[0, 0, 0, 0, 0, out]));
            local_run(
                decls,
                S,
                &[
                    ("a", &a),
                    ("b", &b),
                    ("c", &c),
                    ("data", &data),
                    ("data_out", &data_out),
                ],
                &[0],
            )
        };
        // 1 + 2 + 3 + 4 = 10: the match ends at tick 5 with x == 10.
        assert_eq!(ends_with(&run(10), 0, "x"), BTreeSet::from([(5, Some(10))]));
        // A wrong expectation does not match.
        assert!(run(9).attempts[0].matches.is_empty());
    }

    /// 16.10 `count_a_cycles`: `x++` counts the cycles a stays high. The LRM's
    /// own start `$rose(a)` needs a sampled-value call the reference
    /// evaluator does not have, so the run uses `a` itself; the verbatim text
    /// builds too (below).
    #[test]
    fn t14_count_a_cycles_counts_with_an_increment() {
        let decls = "parameter MAX = 3;\n\
                     sequence s;\n\
                       int x;\n\
                       (a, x = 1)\n\
                       ##1 (a, x++)[*0:$]\n\
                       ##1 !a && (x <= MAX);\n\
                     endsequence";
        let run = |max: i64| local_run(decls, S, &[("a", &[1, 1, 1, 0]), ("MAX", &[max; 4])], &[0]);
        // a is high on ticks 0..=2 and low on 3: x = 1 + 2 = 3 at the match.
        assert_eq!(ends_with(&run(3), 0, "x"), BTreeSet::from([(3, Some(3))]));
        assert!(run(2).attempts[0].matches.is_empty());
    }

    #[test]
    fn t14_count_a_cycles_verbatim_builds() {
        builds(
            &lv("parameter MAX = 3;\n\
                 sequence s;\n\
                   int x;\n\
                   ($rose(a), x = 1)\n\
                   ##1 (a, x++)[*0:$]\n\
                   ##1 !a && (x <= MAX);\n\
                 endsequence"),
            S,
        )
        .unwrap();
    }

    /// 16.9.8: `first_match(seq, x = e)` is `first_match((seq, x = e))`: the
    /// item runs for the earliest match only, whichever way it is written.
    #[test]
    fn t14_first_match_with_a_match_item() {
        let sig: [(&str, &[i64]); 3] = [
            ("a", &[1, 0, 0, 0]),
            ("b", &[0, 1, 1, 0]),
            ("data", &[0, 5, 7, 0]),
        ];
        let seq = |fm: &str, want: i64| {
            local_run(
                &format!("sequence s; int x; {fm} ##1 (x == {want}); endsequence"),
                S,
                &sig,
                &[0],
            )
        };
        // The earliest match of `a ##[1:2] b` ends at tick 1, where data == 5.
        for fm in [
            "first_match(a ##[1:2] b, x = data)",
            "first_match((a ##[1:2] b, x = data))",
        ] {
            assert_eq!(
                ends_with(&seq(fm, 5), 0, "x"),
                BTreeSet::from([(2, Some(5))]),
                "{fm}"
            );
            assert!(seq(fm, 7).attempts[0].matches.is_empty(), "{fm}");
        }
        // Without first_match the later match (tick 2, data == 7) survives.
        let all = seq("(a ##[1:2] b, x = data)", 7);
        assert_eq!(ends_with(&all, 0, "x"), BTreeSet::from([(3, Some(7))]));
    }

    #[test]
    fn t14_first_match_match_item_needs_a_nonempty_sequence() {
        let e = built_err_lenient(
            &lv("sequence s; int x; first_match(a[*0:1], x = data) ##1 b; endsequence"),
            S,
        );
        assert!(e.message.contains("empty match"), "{e}");
    }

    /// 16.9.8 and 16.11: `first_match(seq, tk(e))` is `first_match((seq, tk(e)))`,
    /// and a call runs at EVERY end point of the sequence it is attached to, the
    /// matches `first_match` discards included. `a ##[1:2] b` ends at ticks 1
    /// and 2; all three spellings record the call on both. Assignments cannot
    /// tell the positions apart (see `t14_first_match_with_a_match_item`), calls
    /// can.
    #[test]
    fn t14_first_match_calls_fire_at_every_end_point_whichever_way_it_is_written() {
        let sigs: [(&str, &[i64]); 3] = [
            ("a", &[1, 0, 0, 0]),
            ("b", &[0, 1, 1, 0]),
            ("data", &[0, 5, 7, 0]),
        ];
        type Calls = BTreeSet<(u32, Vec<Option<i64>>)>;
        let calls_of = |body: &str| -> (Calls, BTreeSet<u32>) {
            call_run(
                &format!("task tk(int n); endtask\nsequence s; {body}; endsequence"),
                &sigs,
                |leaves, got| {
                    assert_eq!(leaves.call_count(), 1, "`{body}`");
                    (
                        got.calls.iter().map(|c| (c.tick, c.args.clone())).collect(),
                        got.attempt.ends(),
                    )
                },
            )
        };
        let both = BTreeSet::from([(1, vec![Some(5)]), (2, vec![Some(7)])]);
        let (plain, plain_ends) = calls_of("(a ##[1:2] b, tk(data))");
        assert_eq!(plain, both);
        assert_eq!(plain_ends, BTreeSet::from([1, 2]));
        for fm in [
            "first_match(a ##[1:2] b, tk(data))",
            "first_match((a ##[1:2] b, tk(data)))",
        ] {
            let (calls, ends) = calls_of(fm);
            assert_eq!(calls, both, "{fm}: the call fires at both end points");
            // first_match still keeps only the earliest match.
            assert_eq!(ends, BTreeSet::from([1]), "{fm}");
        }
    }

    /// A mixed list on `first_match` keeps list order: the call samples the
    /// variable the assignment before it wrote, at every end point.
    #[test]
    fn t14_first_match_mixed_items_run_in_list_order() {
        let sigs: [(&str, &[i64]); 3] = [
            ("a", &[1, 0, 0, 0]),
            ("b", &[0, 1, 1, 0]),
            ("data", &[0, 5, 7, 0]),
        ];
        call_run(
            "task tk(int n); endtask\n\
             sequence s; int x; first_match(a ##[1:2] b, x = data, tk(x), x++) ##1 (x == 6); endsequence",
            &sigs,
            |_, got| {
                let calls: Vec<_> = got.calls.iter().map(|c| (c.tick, c.args.clone())).collect();
                assert_eq!(calls, vec![(1, vec![Some(5)]), (2, vec![Some(7)])]);
                // Only the earliest match continues, with x == data + 1 == 6.
                assert_eq!(got.attempt.ends(), BTreeSet::from([2]));
            },
        );
    }

    /// The items of a `first_match` whose operand can never match are still
    /// validated: `x++` reads an `x` that never flowed in (16.10).
    #[test]
    fn t14_first_match_items_are_validated_when_the_operand_never_matches() {
        for item in ["x++", "x += 1"] {
            let e = built_err_lenient(
                &lv(&format!(
                    "sequence s; int x; first_match((a ##1 b) intersect (a ##2 b), {item}); \
                     endsequence"
                )),
                S,
            );
            assert!(
                e.message.contains("does not flow out") && e.message.contains("`x`"),
                "`{item}`: {e}"
            );
        }
    }

    /// 16.11 `s1`, verbatim (the `f` signal is the LRM's implicit one).
    #[test]
    fn t14_s1_from_16_11_builds() {
        builds(
            &lv("logic f;\n\
                 sequence s;\n\
                   logic v, w;\n\
                   (a, v = e) ##1\n\
                   (b[->1], w = f, $display(\"b after a with v = %h, w = %h\\n\", v, w));\n\
                 endsequence"),
            S,
        )
        .unwrap();
    }

    /// 16.11: a function call is not a match item unless it is void. slang
    /// rejects it first; the builder must not accept what slang diagnosed.
    #[test]
    fn t14_a_non_void_function_is_not_a_match_item() {
        let e = built_err_lenient(
            &lv("function int fn(int v); return v; endfunction\n\
                 sequence s; int x; (a, x = 1) ##1 (b, fn(x)); endsequence"),
            S,
        );
        assert!(e.message.contains("void"), "{e}");
    }

    /// 16.11: a subroutine called from a match item takes `input` and `ref`
    /// arguments only.
    #[test]
    fn t14_output_and_inout_formals_are_rejected() {
        for dir in ["output", "inout"] {
            let e = built_err_lenient(
                &lv(&format!(
                    "task tk({dir} int o); endtask\n\
                     sequence s; (a, tk(data)) ##1 b; endsequence"
                )),
                S,
            );
            assert!(e.message.contains(dir), "{dir}: {e}");
        }
    }

    /// 16.11: "If a local variable appears in an actual argument expression,
    /// then that argument shall be passed by value."
    #[test]
    fn t14_a_local_variable_cannot_be_passed_by_reference() {
        let e = built_err_lenient(
            &lv("task tk(ref int r); endtask\n\
                 sequence s; int x; (a, x = 1) ##1 (b, tk(x)); endsequence"),
            S,
        );
        assert!(
            e.message.contains("local variable") && e.message.contains("by value"),
            "{e}"
        );
    }

    /// The legal argument shapes: by value (also a local variable), by `ref`
    /// and `const ref`, by name, and with a defaulted formal.
    #[test]
    fn t14_input_ref_and_const_ref_arguments_are_legal() {
        for call in [
            "tk(data, 1)",
            "tk(.n(data), .m(2))",
            "tk(x, x + 1)",
            "tk(data)",
        ] {
            builds(
                &lv(&format!(
                    "task tk(int n, int m = 0); endtask\n\
                     sequence s; int x = 1; (a, {call}) ##1 b; endsequence"
                )),
                S,
            )
            .unwrap_or_else(|e| panic!("`{call}`: {e}"));
        }
        for decl in ["task tk(ref int r);", "task tk(const ref int r);"] {
            builds(
                &lv(&format!(
                    "{decl} endtask\nsequence s; (a, tk(data)) ##1 b; endsequence"
                )),
                S,
            )
            .unwrap_or_else(|e| panic!("`{decl}`: {e}"));
        }
    }

    /// Runs `stmt` over `signals` from tick 0 through the call-tracking
    /// interpreter, handing the call table and the result to `f`.
    fn call_run<R>(
        decls: &str,
        signals: &[(&str, &[i64])],
        f: impl FnOnce(&LeafTable<'_>, &trace::CallAttempt) -> R,
    ) -> R {
        with_assertion(&lv(decls), S, false, |r, _, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("failed to build: {e}"));
            let len = signals[0].1.len() as u32;
            let sig = |name: &str, t: u32| -> i64 {
                signals
                    .iter()
                    .find(|(n, _)| *n == name)
                    .unwrap_or_else(|| panic!("the trace has no signal `{name}`"))
                    .1[t as usize]
            };
            let got = trace::attempt_with_calls(&au, 0, len, &|id, tick, frame| {
                eval_leaf_id(&leaves, id, frame, tick, &sig)
            })
            .unwrap_or_else(|e| panic!("trace interpreter: {e}"));
            f(&leaves, &got)
        })
    }

    /// 16.11: the items of one list run in list order at the end point, each
    /// call sampling the variable as the items before it left it.
    #[test]
    fn t14_calls_and_writes_run_in_list_order() {
        let sigs: [(&str, &[i64]); 3] = [("a", &[1, 0, 0]), ("b", &[0, 1, 0]), ("c", &[0, 0, 1])];
        call_run(
            "task tk(int n); endtask\n\
             sequence s; int x; (a, x = 1) ##1 (b, tk(x), x = 5, tk(x)) ##1 c; endsequence",
            &sigs,
            |leaves, got| {
                assert_eq!(leaves.call_count(), 2);
                let calls: Vec<_> = got
                    .calls
                    .iter()
                    .map(|c| (c.tick, c.call.0, c.args.clone()))
                    .collect();
                assert_eq!(
                    calls,
                    vec![(1, 0, vec![Some(1)]), (1, 1, vec![Some(5)])],
                    "the first call sees x == 1, the second the x = 5 written between them"
                );
                assert_eq!(got.attempt.ends(), BTreeSet::from([2]));
            },
        );
    }

    /// 16.11: a call fires at every end point of the subsequence it is
    /// attached to, even when the longer sequence then fails.
    #[test]
    fn t14_a_call_fires_even_if_the_longer_sequence_fails() {
        // `c` never holds, so the whole sequence never matches.
        let sigs: [(&str, &[i64]); 3] = [("a", &[1, 0, 0]), ("b", &[0, 1, 0]), ("c", &[0, 0, 0])];
        call_run(
            "task tk(int n); endtask\n\
             sequence s; int x; (a, x = 1) ##1 (b, tk(x)) ##1 c; endsequence",
            &sigs,
            |_, got| {
                assert!(got.attempt.matches.is_empty());
                assert_eq!(got.calls.len(), 1, "the call at tick 1 still fired");
            },
        );
    }

    /// 16.11 by-value vs by-reference: `n` is an `input` (sampled), `r` is a
    /// `ref` (bound to the actual). The call table records which is which and
    /// the actual expression of each.
    #[test]
    fn t14_the_call_table_records_how_each_argument_is_passed() {
        call_run(
            "task tk(int n, ref int r); endtask\n\
             sequence s; (a, tk(data, data2)) ##1 b; endsequence",
            &[("a", &[1, 0]), ("b", &[0, 1]), ("data", &[7, 0])],
            |leaves, got| {
                assert_eq!(leaves.call_count(), 1);
                let site = leaves.call_site(ir::CallId(0));
                assert_eq!(site.args.len(), 2);
                assert!(matches!(site.args[0].0, ir::CallArg::Value(_)));
                assert!(matches!(site.args[1].0, ir::CallArg::Ref));
                let event = got.calls.iter().next().expect("the call fired");
                assert_eq!(event.args, vec![Some(7), None], "ref has no sampled value");
            },
        );
    }

    /// A call inside an `and`/`intersect` operand cannot be composed by the
    /// lockstep product: a loud error naming the edge kind, not a silent drop.
    #[test]
    fn t14_a_call_inside_an_and_or_intersect_operand_is_a_loud_error() {
        for op in ["and", "intersect"] {
            let e = built_err(
                &lv(&format!(
                    "task tk(int n); endtask\n\
                     sequence s; ((a, tk(data)) ##1 b) {op} (c ##1 d); endsequence"
                )),
                S,
            );
            assert!(
                e.message.contains("SubroutineCall") && e.message.contains(op),
                "{op}: {e}"
            );
        }
    }

    // -- T15: `.triggered` / `.matched`, LRM 16.9.11, 16.10, 16.13.5, 16.13.6 --

    /// The signals the T15 fixtures use, on top of `with_assertion`'s and `LV`'s.
    const EP: &str = "logic reset, inst, branch_back, ready, proc1, proc2, reset1, branch_back1, \
                      req, w;\n";

    /// `EP`, `LV` and one fixture's own declarations.
    fn ep(decls: &str) -> String {
        format!("{EP}{}", lv(decls))
    }

    /// Builds `stmt` (declarations `decls`) and runs one attempt per `starts`
    /// entry through the two-clock interpreter: the destination clock ticks at
    /// `dest` (simulation times), the source clock at `source`, and each signal
    /// of `sigs` is a row indexed by the tick of ITS OWN clock (a leaf of an
    /// instance a `.matched` is applied to is evaluated at source ticks, the
    /// rest at destination ticks -- the interpreter hands the evaluator the
    /// leaf's own tick, and every name here belongs to one domain). `f` also
    /// sees the automaton and the leaf table.
    fn clock_run<R>(
        decls: &str,
        stmt: &str,
        (dest, source): (&[u64], &[u64]),
        sigs: &[(&str, &[i64])],
        starts: &[u32],
        f: impl FnOnce(&ir::Automaton, &LeafTable<'_>, Vec<trace::CallAttempt>) -> R,
    ) -> R {
        with_assertion(&ep(decls), stmt, false, |r, _, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("`{stmt}` failed to build: {e}"));
            let sig = |name: &str, t: u32| -> i64 {
                sigs.iter()
                    .find(|(n, _)| *n == name)
                    .unwrap_or_else(|| panic!("the trace has no signal `{name}`"))
                    .1[t as usize]
            };
            let clocks = trace::TraceClocks {
                dest: dest.to_vec(),
                source: source.to_vec(),
            };
            let got = starts
                .iter()
                .map(|&s| {
                    trace::attempt_with_clocks(&au, s, &clocks, &|id, tick, frame| {
                        eval_leaf_id(&leaves, id, frame, tick, &sig)
                    })
                    .unwrap_or_else(|e| panic!("trace interpreter: {e}"))
                })
                .collect();
            f(&au, &leaves, got)
        })
    }

    /// One clock: every tick of both domains is the same instant.
    fn one_clock(n: u64) -> Vec<u64> {
        (0..n).map(|t| (t + 1) * 10).collect()
    }

    /// The end ticks of each attempt, one set per start.
    fn ends_of(got: &[trace::CallAttempt]) -> Vec<BTreeSet<u32>> {
        got.iter().map(|g| g.attempt.ends()).collect()
    }

    /// 16.9.11, `zero_or_one_req` verbatim: the sequence admits an empty match
    /// AND a nonempty one, but "such empty matches shall not activate the
    /// .triggered method": `.triggered` is true exactly when `req` is 1.
    #[test]
    fn t15_an_empty_match_never_fires_triggered() {
        let decls = "sequence zero_or_one_req; (req==1'b1)[*0:1]; endsequence";
        let stmt = "assert property (@(posedge clk) a ##1 zero_or_one_req.triggered);";
        let t = one_clock(5);
        let sigs: [(&str, &[i64]); 2] = [("a", &[1, 1, 1, 1, 1]), ("req", &[0, 1, 0, 1, 0])];
        clock_run(
            decls,
            stmt,
            (&t, &t),
            &sigs,
            &[0, 1, 2, 3],
            |au, leaves, got| {
                assert_eq!(au.end_points.len(), 1);
                assert!(
                    au.end_point(ir::EndPointId(0)).automaton.admits_empty,
                    "the instance admits the empty match; that is the point of the test"
                );
                assert_eq!(leaves.end_site_count(), 1);
                // Starting at 0 the end point is tested at tick 1 (req = 1: fires);
                // at 1 it is tested at tick 2 (req = 0, the EMPTY match: must not).
                assert_eq!(
                    ends_of(&got),
                    vec![
                        BTreeSet::from([1]),
                        BTreeSet::new(),
                        BTreeSet::from([3]),
                        BTreeSet::new()
                    ]
                );
            },
        );
    }

    /// The LRM's two-sequence `e1`/`e2` of 16.13.6 (same clock, `.triggered`),
    /// verbatim, builds one end point whose site records the instance's own
    /// clock.
    #[test]
    fn t15_e1_e2_from_16_13_6_build_one_triggered_end_point() {
        let decls = "sequence e1;\n\
                       @(posedge sysclk) $rose(a) ##1 b ##1 c;\n\
                     endsequence\n\
                     sequence e2;\n\
                       @(posedge sysclk) reset ##1 inst ##1 e1.triggered ##1 branch_back;\n\
                     endsequence";
        with_assertion(&ep(decls), "assert property (e2);", false, |r, _, _| {
            let (au, leaves) = r.unwrap();
            assert_eq!(au.end_points.len(), 1);
            let point = au.end_point(ir::EndPointId(0));
            assert_eq!(point.method, ir::EndMethod::Triggered);
            assert_eq!(point.site, 0);
            assert!(point.flow_out.is_empty());
            assert_eq!(leaves.end_site(0).method, ir::EndMethod::Triggered);
            assert!(leaves.end_site(0).clock.is_some(), "e1 has its own clock");
        });
    }

    /// `e2` (16.13.6) by value: `.triggered` tests only the END POINT, so it
    /// holds at the tick `e1` ends whatever tick it started on -- which is
    /// before the point `e2` reaches it. Replacing the application by the
    /// instance (`e1` itself) starts `e1` one tick after `inst` and so needs a
    /// different trace, which discriminates the two.
    #[test]
    fn t15_triggered_tests_the_end_point_and_not_the_start() {
        let decls = "sequence e1x; @(posedge sysclk) a ##1 b ##1 c; endsequence\n\
                     sequence e2x;\n\
                       @(posedge sysclk) reset ##1 inst ##1 e1x.triggered ##1 branch_back;\n\
                     endsequence\n\
                     sequence e2i;\n\
                       @(posedge sysclk) reset ##1 inst ##1 e1x ##1 branch_back;\n\
                     endsequence";
        let t = one_clock(8);
        // e1x: a@0 b@1 c@2 ends at 2. e2x: reset@0 inst@1 triggered@2 bb@3.
        let sigs: [(&str, &[i64]); 6] = [
            ("reset", &[1, 0, 0, 0, 0, 0, 0, 0]),
            ("inst", &[0, 1, 0, 0, 0, 0, 0, 0]),
            ("a", &[1, 0, 0, 0, 0, 0, 0, 0]),
            ("b", &[0, 1, 0, 0, 0, 0, 0, 0]),
            ("c", &[0, 0, 1, 0, 0, 0, 0, 0]),
            ("branch_back", &[0, 0, 0, 1, 0, 0, 0, 0]),
        ];
        clock_run(
            decls,
            "assert property (e2x);",
            (&t, &t),
            &sigs,
            &[0],
            |_, _, got| {
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])]);
            },
        );
        // The instance form needs `a` at 2, `b` at 3, `c` at 4: not in this trace.
        clock_run(
            decls,
            "assert property (e2i);",
            (&t, &t),
            &sigs,
            &[0],
            |_, _, got| {
                assert_eq!(ends_of(&got), vec![BTreeSet::new()]);
            },
        );
        // No end point at tick 2 (c low): no match.
        let mut c_low = sigs.to_vec();
        c_low[4] = ("c", &[0, 0, 0, 0, 0, 0, 0, 0]);
        clock_run(
            decls,
            "assert property (e2x);",
            (&t, &t),
            &c_low,
            &[0],
            |_, _, got| {
                assert_eq!(ends_of(&got), vec![BTreeSet::new()]);
            },
        );
    }

    /// 16.9.11's `e2(a,b,c)` with arguments: the end point of an instance with
    /// ACTUALS, and `rule2a`'s equivalent (a named instance in between).
    #[test]
    fn t15_triggered_on_an_instance_with_arguments_and_through_a_name() {
        let decls = "sequence e2p(p,q,r); @(posedge sysclk) p ##1 q ##1 r; endsequence\n\
                     sequence rule2;\n\
                       @(posedge sysclk) reset ##1 inst ##1 e2p(ready,proc1,proc2).triggered\n\
                         ##1 branch_back;\n\
                     endsequence\n\
                     sequence e2_instantiated; e2p(ready,proc1,proc2); endsequence\n\
                     sequence rule2a;\n\
                       @(posedge sysclk) reset ##1 inst ##1 e2_instantiated.triggered ##1 branch_back;\n\
                     endsequence";
        let t = one_clock(6);
        let sigs: [(&str, &[i64]); 6] = [
            ("reset", &[1, 0, 0, 0, 0, 0]),
            ("inst", &[0, 1, 0, 0, 0, 0]),
            ("ready", &[1, 0, 0, 0, 0, 0]),
            ("proc1", &[0, 1, 0, 0, 0, 0]),
            ("proc2", &[0, 0, 1, 0, 0, 0]),
            ("branch_back", &[0, 0, 0, 1, 0, 0]),
        ];
        for rule in ["rule2", "rule2a"] {
            let stmt = format!("assert property ({rule});");
            clock_run(decls, &stmt, (&t, &t), &sigs, &[0], |_, _, got| {
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])], "{rule}");
            });
        }
    }

    /// 16.9.11's `e3(sequence a, untyped b)`: `.triggered` on a formal argument
    /// of type `sequence`, whose actual (`ready ##1 proc1`) has no clock of its
    /// own and so ends on the clock of the context. `rule3` verbatim.
    #[test]
    fn t15_triggered_on_a_sequence_formal_argument() {
        let decls = "sequence e3f(sequence s, untyped t);\n\
                       @(posedge sysclk) s.triggered ##1 t;\n\
                     endsequence\n\
                     sequence rule3;\n\
                       @(posedge sysclk) reset ##1 e3f(ready ##1 proc1, proc2) ##1 branch_back;\n\
                     endsequence";
        let t = one_clock(5);
        // reset@0; e3f at 1: (ready ##1 proc1) ended at 1 (ready@0, proc1@1);
        // proc2@2; branch_back@3.
        let sigs: [(&str, &[i64]); 5] = [
            ("reset", &[1, 0, 0, 0, 0]),
            ("ready", &[1, 0, 0, 0, 0]),
            ("proc1", &[0, 1, 0, 0, 0]),
            ("proc2", &[0, 0, 1, 0, 0]),
            ("branch_back", &[0, 0, 0, 1, 0]),
        ];
        clock_run(
            decls,
            "assert property (rule3);",
            (&t, &t),
            &sigs,
            &[0],
            |au, _, got| {
                assert_eq!(au.end_points.len(), 1);
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])]);
            },
        );
    }

    /// `e2_with_arg(sequence subseq)` and `e4` of 16.13.6, verbatim: the
    /// application on a formal of type `sequence` whose actual is a clocked
    /// sequence expression, equivalent to `e2`.
    #[test]
    fn t15_e2_with_arg_and_e4_from_16_13_6() {
        let decls = "sequence e2_with_arg(sequence subseq);\n\
                       @(posedge sysclk) reset ##1 inst ##1 subseq.triggered ##1 branch_back;\n\
                     endsequence\n\
                     sequence e4;\n\
                       e2_with_arg(@(posedge sysclk) a ##1 b ##1 c);\n\
                     endsequence";
        let t = one_clock(8);
        let sigs: [(&str, &[i64]); 6] = [
            ("reset", &[1, 0, 0, 0, 0, 0, 0, 0]),
            ("inst", &[0, 1, 0, 0, 0, 0, 0, 0]),
            ("a", &[1, 0, 0, 0, 0, 0, 0, 0]),
            ("b", &[0, 1, 0, 0, 0, 0, 0, 0]),
            ("c", &[0, 0, 1, 0, 0, 0, 0, 0]),
            ("branch_back", &[0, 0, 0, 1, 0, 0, 0, 0]),
        ];
        clock_run(
            decls,
            "assert property (e4);",
            (&t, &t),
            &sigs,
            &[0],
            |au, leaves, got| {
                assert_eq!(au.end_points.len(), 1);
                assert!(leaves.end_site(0).clock.is_some());
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])]);
            },
        );
    }

    /// 16.13.6's `e3` with `.matched` across clocks (`e1` ends on `sysclk`, the
    /// context is `clk`): the end point is stored until the first destination
    /// tick after it, and `.triggered` in its place is a clock mismatch.
    #[test]
    fn t15_matched_synchronises_two_clocks_and_triggered_does_not() {
        let decls = "sequence e1x; @(posedge sysclk) a ##1 b ##1 c; endsequence\n\
                     sequence e3m; @(posedge clk) reset1 ##1 e1x.matched ##1 branch_back1; endsequence\n\
                     sequence e3t; @(posedge clk) reset1 ##1 e1x.triggered ##1 branch_back1; endsequence";
        // sysclk at 5, 15, 25, ...; clk at 10, 20, 30, ...
        let source: Vec<u64> = (0..9).map(|k| 5 + 10 * k).collect();
        let dest: Vec<u64> = (1..=9).map(|k| 10 * k).collect();
        // e1x: a@0 b@1 c@2, ends at source tick 2 = time 25. Destination ticks:
        // reset1@1 (t 20), the first tick after the match is index 2 (t 30), and
        // branch_back1@3.
        let sigs: [(&str, &[i64]); 5] = [
            ("a", &[1, 0, 0, 0, 0, 0, 0, 0, 0]),
            ("b", &[0, 1, 0, 0, 0, 0, 0, 0, 0]),
            ("c", &[0, 0, 1, 0, 0, 0, 0, 0, 0]),
            ("reset1", &[0, 1, 0, 0, 0, 0, 0, 0, 0]),
            ("branch_back1", &[0, 0, 0, 1, 0, 0, 0, 0, 0]),
        ];
        clock_run(
            decls,
            "assert property (e3m);",
            (&dest, &source),
            &sigs,
            &[1],
            |au, leaves, got| {
                assert_eq!(
                    au.end_point(ir::EndPointId(0)).method,
                    ir::EndMethod::Matched
                );
                assert!(leaves.end_site(0).clock.is_some());
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])]);
            },
        );
        // The status persists only to the first destination tick after the match:
        // `reset1` one tick later finds no `.matched` at tick 3.
        let mut late = sigs.to_vec();
        late[3] = ("reset1", &[0, 0, 1, 0, 0, 0, 0, 0, 0]);
        late[4] = ("branch_back1", &[0, 0, 0, 0, 1, 0, 0, 0, 0]);
        clock_run(
            decls,
            "assert property (e3m);",
            (&dest, &source),
            &late,
            &[2],
            |_, _, got| {
                assert_eq!(ends_of(&got), vec![BTreeSet::new()]);
            },
        );
        let e = built_err(&ep(decls), "assert property (e3t);");
        assert!(
            e.message.contains("`.triggered`") && e.message.contains("different clock"),
            "{e}"
        );
    }

    /// 16.13.5's `e2` with `.matched [->1]`: the destination sequence waits for
    /// the source's end point sometime after `inst`.
    #[test]
    fn t15_matched_with_goto_repetition() {
        let decls = "sequence e1p(p,q,r); @(posedge sysclk) p ##1 q ##1 r; endsequence\n\
                     sequence e2g;\n\
                       @(posedge clk) reset ##1 inst ##1 e1p(ready,proc1,proc2).matched [->1]\n\
                         ##1 branch_back;\n\
                     endsequence";
        let source: Vec<u64> = (0..9).map(|k| 5 + 10 * k).collect();
        let dest: Vec<u64> = (1..=9).map(|k| 10 * k).collect();
        // e1p ends at source tick 2 (time 25), seen at destination tick 2 (30):
        // reset@0, inst@1, the end point @2, branch_back@3. `[->1]` is
        // `(!e1p.matched[*0:$] ##1 e1p.matched)`: no end point may come before
        // the one that is waited for (16.9.2), see `build_goto`.
        let sigs: [(&str, &[i64]); 6] = [
            ("ready", &[1, 0, 0, 0, 0, 0, 0, 0, 0]),
            ("proc1", &[0, 1, 0, 0, 0, 0, 0, 0, 0]),
            ("proc2", &[0, 0, 1, 0, 0, 0, 0, 0, 0]),
            ("reset", &[1, 0, 0, 0, 0, 0, 0, 0, 0]),
            ("inst", &[0, 1, 0, 0, 0, 0, 0, 0, 0]),
            ("branch_back", &[0, 0, 0, 1, 0, 0, 0, 0, 0]),
        ];
        clock_run(
            decls,
            "assert property (e2g);",
            (&dest, &source),
            &sigs,
            &[0],
            |au, _, got| {
                // One application per copy of the unit: the two gap samples
                // (`!e1p.matched`, first copy and loop copy) and the hit.
                assert_eq!(au.end_points.len(), 3);
                assert_eq!(ends_of(&got), vec![BTreeSet::from([3])]);
            },
        );
    }

    /// 16.13.6: the matched status "persists until the Observed region following
    /// the arrival of the first clock tick of the destination sequence after the
    /// match" and no longer: `.matched` holds on ONE destination tick per source
    /// match, so `inst ##1 e1x.matched` ends only where that tick is.
    #[test]
    fn t15_matched_holds_on_one_destination_tick_per_match() {
        let decls = "sequence e1x; @(posedge sysclk) a ##1 b; endsequence\n\
                     sequence mm; @(posedge clk) inst ##1 e1x.matched; endsequence";
        let source: Vec<u64> = (0..9).map(|k| 5 + 10 * k).collect();
        let dest: Vec<u64> = (1..=9).map(|k| 10 * k).collect();
        // e1x ends at source tick 3 (time 35): the first destination tick at or
        // after it is index 3 (40); `inst` is high everywhere.
        let sigs: [(&str, &[i64]); 3] = [
            ("a", &[0, 0, 1, 0, 0, 0, 0, 0, 0]),
            ("b", &[0, 0, 0, 1, 0, 0, 0, 0, 0]),
            ("inst", &[1, 1, 1, 1, 1, 1, 1, 1, 1]),
        ];
        let starts: Vec<u32> = (0..9).collect();
        clock_run(
            decls,
            "assert property (mm);",
            (&dest, &source),
            &sigs,
            &starts,
            |_, _, got| {
                let ends = ends_of(&got);
                for (start, e) in ends.iter().enumerate() {
                    let want = if start == 2 {
                        BTreeSet::from([3])
                    } else {
                        BTreeSet::new()
                    };
                    assert_eq!(*e, want, "start {start}");
                }
            },
        );
    }

    /// 16.10 `seq2a`: a local variable passed into `sub_seq2(v1).triggered`
    /// flows out of the (maximal) application, so `do1 == v1` reads the value
    /// `lv = data_in` assigned inside the instance -- and a SECOND distinct
    /// valuation at the same tick forks the thread (16.10: "treated the same way
    /// as matching both disjuncts of an or").
    #[test]
    fn t15_seq2a_a_local_flows_out_of_a_maximal_triggered() {
        let decls = "sequence sub_seq2(lv);\n\
                       (a ##1 !a, lv = data_in) ##1 !b[*0:$] ##1 b && (data_out == lv);\n\
                     endsequence\n\
                     sequence seq2a;\n\
                       int v1; c ##1 sub_seq2(v1).triggered ##1 (do1 == v1);\n\
                       // v1 is now bound to lv\n\
                     endsequence";
        let t = one_clock(4);
        // sub_seq2 started at 0: a@0, !a@1 (lv = data_in = 5), b@2 with
        // data_out == 5. c@1, so the application is tested at tick 2; do1@3.
        let sigs = |do1: i64| -> Vec<(&'static str, Vec<i64>)> {
            vec![
                ("a", vec![1, 0, 0, 0]),
                ("b", vec![0, 0, 1, 0]),
                ("c", vec![0, 1, 0, 0]),
                ("data_in", vec![0, 5, 0, 0]),
                ("data_out", vec![0, 0, 5, 0]),
                ("do1", vec![0, 0, 0, do1]),
            ]
        };
        for (do1, want) in [(5, BTreeSet::from([3])), (6, BTreeSet::new())] {
            let owned = sigs(do1);
            let rows: Vec<(&str, &[i64])> = owned.iter().map(|(n, r)| (*n, r.as_slice())).collect();
            clock_run(
                decls,
                "assert property (@(posedge clk) seq2a);",
                (&t, &t),
                &rows,
                &[1],
                |au, _, got| {
                    assert_eq!(au.end_points.len(), 1);
                    assert_eq!(
                        au.end_point(ir::EndPointId(0)).flow_out.len(),
                        1,
                        "v1 flows out"
                    );
                    assert_eq!(ends_of(&got), vec![want.clone()], "do1 = {do1}");
                },
            );
        }
    }

    /// Two distinct valuations of a flowing local at one end tick fork the
    /// thread (16.10): each of the two later comparisons matches its own.
    #[test]
    fn t15_distinct_flow_out_valuations_fork_the_thread() {
        let decls = "sequence two(lv); (a, lv = data_in) or (b, lv = data_out); endsequence\n\
                     sequence fk; int v1; c ##1 two(v1).triggered ##1 (do1 == v1); endsequence";
        let t = one_clock(3);
        for (do1, want) in [(3, true), (4, true), (9, false)] {
            let sigs: [(&str, &[i64]); 6] = [
                ("a", &[0, 1, 0]),
                ("b", &[0, 1, 0]),
                ("c", &[1, 0, 0]),
                ("data_in", &[0, 3, 0]),
                ("data_out", &[0, 4, 0]),
                ("do1", &[0, 0, do1]),
            ];
            clock_run(
                decls,
                "assert property (@(posedge clk) fk);",
                (&t, &t),
                &sigs,
                &[0],
                |_, _, got| {
                    let ends = ends_of(&got);
                    assert_eq!(
                        ends[0] == BTreeSet::from([2]),
                        want,
                        "do1 = {do1}: {ends:?}"
                    );
                },
            );
        }
    }

    /// 16.10 `seq2b`: negating the application means it is not a maximal Boolean
    /// expression, so `v1` does not flow out and the read of it is an error.
    #[test]
    fn t15_seq2b_a_negated_triggered_does_not_flow_a_local_out() {
        let decls = "sequence sub_seq2(lv);\n\
                       (a ##1 !a, lv = data_in) ##1 !b[*0:$] ##1 b && (data_out == lv);\n\
                     endsequence\n\
                     sequence seq2b;\n\
                       int v1; c ##1 !sub_seq2(v1).triggered ##1 (do1 == v1); // v1 unassigned\n\
                     endsequence";
        let e = built_err(&ep(decls), "assert property (@(posedge clk) seq2b);");
        assert!(
            e.message.contains("does not flow out") && e.message.contains("`v1`"),
            "{e}"
        );
    }

    /// 16.8.2: it is an error to apply `triggered`/`matched` to an instance of a
    /// sequence with an `input`/`inout` local variable formal.
    #[test]
    fn t15_a_local_input_or_inout_formal_is_an_error() {
        for (dir, method) in [
            ("input", "triggered"),
            ("inout", "triggered"),
            ("input", "matched"),
        ] {
            let decls = format!(
                "sequence li(local {dir} int f); a ##1 (f == 1); endsequence\n\
                 sequence u; int k; c ##1 li(k).{method}; endsequence"
            );
            let e = built_err_lenient(&ep(&decls), "assert property (@(posedge clk) u);");
            assert!(
                e.message.contains(&format!("`.{method}`"))
                    && e.message.contains("local variable formal"),
                "{dir}/{method}: {e}"
            );
        }
    }

    /// An application inside a larger expression counts one end point per
    /// application, in the pre-order the leaf's flag slots are listed in; the
    /// leaf reads each at the call's position, so a swapped order changes the
    /// value.
    #[test]
    fn t15_an_application_inside_an_expression_is_a_flag_in_preorder() {
        let decls = "sequence sa; a; endsequence\n\
                     sequence sb; b; endsequence";
        let t = one_clock(2);
        let sigs: [(&str, &[i64]); 3] = [("a", &[1, 0]), ("b", &[0, 1]), ("c", &[1, 1])];
        // `!sa.triggered && sb.triggered` is `!a && b`: true at tick 1 only.
        // The `c ##1` prefix tests the leaf at tick 1.
        clock_run(
            decls,
            "assert property (@(posedge clk) c ##1 (!sa.triggered && sb.triggered));",
            (&t, &t),
            &sigs,
            &[0],
            |au, leaves, got| {
                assert_eq!(au.end_points.len(), 2);
                assert_eq!(leaves.end_site_count(), 2);
                assert_eq!(leaves.end_site(0).method, ir::EndMethod::Triggered);
                let flagged: Vec<_> = (0..leaves.len() as u32)
                    .filter(|&i| !leaves.locals_of(LeafId(i)).end_flags.is_empty())
                    .collect();
                assert_eq!(flagged.len(), 1);
                assert_eq!(leaves.locals_of(LeafId(flagged[0])).end_flags.len(), 2);
                assert_eq!(ends_of(&got), vec![BTreeSet::from([1])]);
            },
        );
        clock_run(
            decls,
            "assert property (@(posedge clk) c ##1 (!sb.triggered && sa.triggered));",
            (&t, &t),
            &sigs,
            &[0],
            |_, _, got| {
                assert_eq!(
                    ends_of(&got),
                    vec![BTreeSet::new()],
                    "!b && a is false at 1"
                )
            },
        );
    }

    /// `.triggered` as an operand of `and`/`intersect`: the lockstep product
    /// carries the end-point edge on the thread.
    #[test]
    fn t15_an_end_point_inside_a_product_operand() {
        let decls = "sequence sc; c ##1 d; endsequence";
        let t = one_clock(4);
        let sigs: [(&str, &[i64]); 4] = [
            ("a", &[1, 1, 0, 0]),
            ("b", &[0, 0, 1, 0]),
            ("c", &[1, 0, 0, 0]),
            ("d", &[0, 1, 0, 0]),
        ];
        // sc ends at tick 1. `(a ##1 sc.triggered) and (a ##1 a)` over [0,1].
        for (op, want) in [
            ("and", BTreeSet::from([1])),
            ("intersect", BTreeSet::from([1])),
        ] {
            let stmt =
                format!("assert property (@(posedge clk) (a ##1 sc.triggered) {op} (a ##1 a));");
            clock_run(decls, &stmt, (&t, &t), &sigs, &[0], |_, _, got| {
                assert_eq!(ends_of(&got), vec![want.clone()], "{op}");
            });
        }
    }

    /// 16.13.6: "There shall be no circular dependencies between sequences
    /// induced by the use of triggered." slang diagnoses it; a caller that
    /// ignores the diagnostic gets a named error from the builder, not
    /// unbounded recursion.
    #[test]
    fn t15_a_circular_triggered_dependency_is_an_error_not_a_loop() {
        let decls = "sequence r1; a ##1 r2.triggered; endsequence\n\
                     sequence r2; b ##1 r1.triggered; endsequence";
        let e = built_err_lenient(&ep(decls), "assert property (@(posedge clk) r1);");
        // slang leaves the cyclic operand unbound, which the builder reports.
        assert!(e.message.contains("slang could not bind"), "{e}");
    }

    /// The expansion with end points is a pure function of the design.
    #[test]
    fn t15_building_end_points_is_deterministic() {
        let decls = ep("sequence e1x; @(posedge sysclk) a ##1 b; endsequence\n\
                        sequence e2x; @(posedge sysclk) reset ##1 e1x.triggered ##1 c; endsequence");
        let render = || {
            with_assertion(&decls, "assert property (e2x);", false, |r, _, _| {
                let (au, _) = r.unwrap();
                format!("{au:?}")
            })
        };
        assert_eq!(render(), render());
    }

    // -- T18: global clocking future functions, LRM 16.9.4 -------------------

    /// A module-level `global clocking` for the `*_gclk` functions to resolve.
    const GCLK: &str = "logic sig; global clocking gc @(posedge sysclk); endclocking\n";

    /// The LRM's `s` of 16.9.4's `a2`: a local variable assigned in a match item.
    const S_WITH_MATCH_ITEM: &str =
        "sequence s; bit v; (a, v = a) ##1 (b == v)[->1]; endsequence\n";

    fn gclk_decls(more: &str) -> String {
        format!("{GCLK}{more}")
    }

    /// Whether the assertion's table says it has future functions, or the
    /// builder's error.
    fn uses_future(decls: &str, stmt: &str) -> Result<bool, String> {
        with_assertion(decls, stmt, false, |r, _, _| {
            r.map(|(_, leaves)| leaves.uses_future_gclk())
                .map_err(|e| e.message)
        })
    }

    /// The five future functions mark the table; the past family and plain
    /// sampled functions do not (they need no delayed action).
    #[test]
    fn t18_future_functions_flag_the_table_and_past_ones_do_not() {
        let decls = gclk_decls("");
        for f in [
            "$future_gclk",
            "$rising_gclk",
            "$falling_gclk",
            "$steady_gclk",
            "$changing_gclk",
        ] {
            let stmt = format!("assert property (@(posedge clk) a ##1 {f}(b));");
            assert_eq!(uses_future(&decls, &stmt), Ok(true), "{f}");
        }
        for f in [
            "$past_gclk",
            "$rose_gclk",
            "$fell_gclk",
            "$stable_gclk",
            "$changed_gclk",
            "$rose",
        ] {
            let stmt = format!("assert property (@(posedge clk) a ##1 {f}(b));");
            assert_eq!(uses_future(&decls, &stmt), Ok(false), "{f}");
        }
        assert_eq!(
            uses_future(&decls, "assert property (@(posedge clk) a ##1 b);"),
            Ok(false)
        );
    }

    /// Where `a2` (16.9.4)'s illegal shapes are stopped: slang's ANALYSIS stage
    /// reports "cannot call '$future_gclk' in an assertion that has sequence
    /// match items" and then drops the assertion from `Analysis::assertions()`
    /// (the shape `sva::clock` documents for the clocking errors), so
    /// [`build_automaton`] is never handed one; when an assertion does reach it
    /// the builder's own check (`gclk::check`) rejects it. Returns the message
    /// of whichever stopped it, and panics if neither did.
    fn a2_rejection(decls: &str, stmt: &str) -> String {
        let src = format!(
            "module m;\nlogic clk, sysclk, a, b, c;\n{decls}\n\
             always_ff @(posedge clk) begin\n{stmt}\nend\nendmodule\n"
        );
        let session = Session::new();
        let mut comp = Compilation::new(&session).unwrap();
        comp.add_source(&src).unwrap();
        let design = comp.compile().unwrap();
        assert!(
            !design.diagnostics().has_errors(),
            "fixture has compile errors:\n{}\n{src}",
            design.diagnostics().rendered()
        );
        let m = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let analysis = design.analyze(AnalysisFlags::NONE, 1).unwrap();
        let proc = analysis.procedures(m).next().unwrap();
        let Some(assertion) = analysis.assertions(proc.symbol()).next() else {
            return analysis.diagnostics().rendered().to_string();
        };
        let tree = design.syntax_trees().into_iter().next().unwrap();
        let root = assertion.root().as_assertion_expr().unwrap();
        let (root, root_clock) = if root.kind() == AssertionExprKind::Clocking {
            let kids = root.children();
            (kids[1].as_assertion_expr().unwrap(), Some(kids[0]))
        } else {
            (root, None)
        };
        match build_automaton(root, root_clock, (&tree).into(), &m) {
            Ok(_) => panic!("`{stmt}` was accepted"),
            Err(e) => e.message,
        }
    }

    /// `a2` (16.9.4): a future function in an assertion whose sequence has
    /// match items is illegal, however the sequence is reached; the other
    /// shapes show the rule is not "any match item" nor "any future function".
    #[test]
    fn t18_a_future_function_with_sequence_match_items_is_rejected_by_name() {
        let decls = gclk_decls(&format!(
            "{S_WITH_MATCH_ITEM}\
             sequence s2; bit v; (a ##1 $rising_gclk(c), v = 1); endsequence\n\
             sequence s3; bit v; first_match(a ##1 b, v = 1); endsequence\n"
        ));
        for stmt in [
            // The LRM's a2, and its sequence form.
            "assert property (@(posedge clk) s |=> $future_gclk(c));",
            "assert property (@(posedge clk) s ##1 $future_gclk(c));",
            // The future function is in the match item's own sequence.
            "assert property (@(posedge clk) s2 ##1 c);",
            // Through `first_match`'s match items.
            "assert property (@(posedge clk) s3 ##1 $steady_gclk(c));",
            // Through a sequence that is itself under another.
            "assert property (@(posedge clk) c ##1 s ##1 $changing_gclk(c));",
        ] {
            let msg = a2_rejection(&decls, stmt);
            assert!(msg.contains("sequence match items"), "{stmt}: {msg}");
        }
        // The same assertions without a future function, and a future function
        // without match items, are legal (the table says which has one).
        assert_eq!(
            uses_future(&decls, "assert property (@(posedge clk) c ##1 s);"),
            Ok(false)
        );
        assert_eq!(
            uses_future(&decls, "assert property (@(posedge clk) s3 ##1 c);"),
            Ok(false)
        );
        assert_eq!(
            uses_future(
                &decls,
                "assert property (@(posedge clk) a ##1 $future_gclk(c));"
            ),
            Ok(true)
        );
    }

    /// `a1` (16.9.4): the future functions shall not be nested. slang reports
    /// it as a compile error; the builder gives its own, so a design that
    /// got past the diagnostic cannot evaluate a future of a future.
    #[test]
    fn t18_nested_future_functions_are_rejected_by_slang_and_the_builder() {
        let decls = gclk_decls("");
        let stmt = "assert property (@(posedge clk) $future_gclk(a || $rising_gclk(b)));";
        let (message, rendered) = with_assertion(&decls, stmt, true, |r, _, d| {
            let Err(e) = r else {
                panic!("nested future functions were accepted")
            };
            (e.message, d.rendered().to_string())
        });
        assert!(rendered.contains("may not be nested"), "{rendered}");
        assert!(message.contains("shall not be nested"), "{message}");
    }

    /// The tick-by-tick sampled values of the LRM's Figure 16-4 reconstruction
    /// that `sv-sim-sim::sva::future`'s own tests derive from Table 16-2
    /// (global ticks at times 0, 10, ..., 110): `sig` and `clk`.
    const SIG: &[u8] = b"110000111000";
    const CLK: &[u8] = b"110011001100";

    /// `$falling_gclk`/`$steady_gclk` of `samples` at global tick `i`.
    fn gclk_fn(f: sv_sim_sim::sva::future::FutureFn, samples: &[u8], i: usize) -> bool {
        sv_sim_sim::sva::future::eval_at(f, samples, i) == Some(b'1')
    }

    /// A 0/1 row over the ticks `0..len`.
    fn row_of(len: usize, f: impl Fn(usize) -> bool) -> String {
        (0..len).map(|i| if f(i) { '1' } else { '0' }).collect()
    }

    /// The end ticks of `body`'s attempt starting at `start` over `rows`.
    fn gclk_ends(decls: &str, body: &str, rows: &[(&str, &str)], start: u32) -> BTreeSet<u32> {
        let tr = Trace::new(rows);
        let stmt = format!("assert property (@(posedge clk) {body});");
        with_assertion(decls, &stmt, false, |r, tree, _| {
            let (au, leaves) = r.unwrap_or_else(|e| panic!("`{body}` failed to build: {e}"));
            let texts = leaf_texts(&leaves, tree);
            run_attempt(&au, &texts, &tr, start).1
        })
    }

    /// Example 4: `##1 $stable_gclk(sig)` (a4) and `$steady_gclk(sig)` (a5) are
    /// equivalent, attempt for attempt; a plain `$stable_gclk(sig)` is not,
    /// at cycle 0, which is why a4 needs its `##1`.
    #[test]
    fn t18_example_4_a4_and_a5_agree_on_every_attempt() {
        use sv_sim_sim::sva::future::FutureFn;
        let decls = gclk_decls("");
        // Every tick that has a successor: 0..=10.
        let n = SIG.len() - 1;
        // `$stable_gclk` is `$stable(sig, @$global_clock)`: equal to the
        // previous tick's sample, the default sampled value x before the first.
        let stable = row_of(n + 1, |i| SIG[i] == if i > 0 { SIG[i - 1] } else { b'x' });
        let steady = row_of(n + 1, |i| gclk_fn(FutureFn::Steady, SIG, i));
        let rows = [
            ("$stable_gclk(sig)", stable.as_str()),
            ("$steady_gclk(sig)", steady.as_str()),
        ];
        let (mut matched, mut failed) = (0, 0);
        for start in 0..n as u32 {
            let a4 = gclk_ends(&decls, "##1 $stable_gclk(sig)", &rows, start);
            let a5 = gclk_ends(&decls, "$steady_gclk(sig)", &rows, start);
            // Same verdict; the `##1` only moves the end point one tick on.
            if a5.is_empty() {
                assert!(a4.is_empty(), "attempt at tick {start}: {a4:?} vs {a5:?}");
                failed += 1;
            } else {
                assert_eq!(a4, set(&[start + 1]), "attempt at tick {start}");
                assert_eq!(a5, set(&[start]), "attempt at tick {start}");
                matched += 1;
            }
        }
        // `sig` holds on some ticks and changes on others, so both verdicts
        // were compared.
        assert!(
            matched > 0 && failed > 0,
            "{matched} matched, {failed} failed"
        );
        // The corner case at cycle 0: `$stable_gclk(sig)` compared with x.
        assert!(gclk_ends(&decls, "$stable_gclk(sig)", &rows, 0).is_empty());
        assert!(!gclk_ends(&decls, "$steady_gclk(sig)", &rows, 0).is_empty());
    }

    /// Example 2: the antecedent of
    /// `$falling_gclk(clk) ##1 (!$falling_gclk(clk)[*1:$]) |-> $steady_gclk(sig)`
    /// matches from each global tick at which `clk` falls, once at every tick
    /// up to the next fall; the consequent is then violated only where `sig`
    /// is about to change inside such a window (time 80).
    #[test]
    fn t18_example_2_between_two_falling_edges_sig_may_change_only_at_a_fall() {
        use sv_sim_sim::sva::future::FutureFn;
        let decls = gclk_decls("");
        let n = CLK.len() - 1;
        let falling = |i: usize| gclk_fn(FutureFn::Falling, CLK, i);
        let fall = row_of(n, falling);
        let not_fall = row_of(n, |i| !falling(i));
        let rows = [
            ("$falling_gclk(clk)", fall.as_str()),
            ("!$falling_gclk(clk)", not_fall.as_str()),
        ];
        let body = "$falling_gclk(clk) ##1 (!$falling_gclk(clk))[*1:$]";
        let ends: Vec<BTreeSet<u32>> = (0..n as u32)
            .map(|s| gclk_ends(&decls, body, &rows, s))
            .collect();
        // clk falls between the ticks at times 10-20, 50-60 and 90-100.
        assert_eq!(ends[1], set(&[2, 3, 4]));
        assert_eq!(ends[5], set(&[6, 7, 8]));
        assert_eq!(ends[9], set(&[10]));
        for (s, e) in ends.iter().enumerate() {
            if ![1, 5, 9].contains(&s) {
                assert!(e.is_empty(), "no attempt at tick {s} may match");
            }
        }
        let violations: Vec<u32> = ends
            .iter()
            .flatten()
            .copied()
            .filter(|&e| !gclk_fn(FutureFn::Steady, SIG, e as usize))
            .collect();
        assert_eq!(violations, [8], "tick 8 is time 80");
    }
}