dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
Documentation
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! Table builder tests over the golden grammar corpus.
//!
//! The builder resolves a conflict only when every path that reached a config
//! set allows it: it keeps the union of every path's taint (`INTERIOR_TAINT`
//! marks the paths that never popped the decision boundary). A state that
//! mixed paths reach escapes.

use std::path::{Path, PathBuf};

use dbt_antlr_runtime::analysis::{BOUNDARY_TAINT, EOF, FOREIGN_LINEAGE_TAINT};

use crate::grammar::compiler::compile;
use crate::grammar::diagnostic::Severity;
use crate::grammar::loader::LoadOptions;
use crate::optimization::AtnFallback;

use super::builder::{PARTIAL_DEPTH_CAP, STATIC_ONLY_DEPTH_CAP};
use super::cost::{AttemptKind, AttemptOutcome};
use super::loop_block::LoopBlock;
use super::table::{StaticDfaState, StaticDfaTable};
use super::{
    BudgetCutoff, BudgetLimits, CONFLICT_ESCAPE, DecisionKind, DecisionOutcome,
    DecisionTableBuilder, NoTableReason, ParserDfaBudgets,
};

fn grammars_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crate directory")
        .join("dbt-antlr-runtime")
        .join("grammars")
}

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("codegen-direct")
        .join("fixtures")
        .join(name)
}

/// The table builder of one compiled parser, set up as the static parser DFA
/// pass sets it up.
fn builder(parser: &crate::grammar::atn::CompiledParser) -> DecisionTableBuilder {
    let ll1 = crate::optimization::static_parser_dfa::ll1_disjointness(parser);
    DecisionTableBuilder::new(parser.atn, ll1).with_descent_rules(
        crate::optimization::static_parser_dfa::descent_rules(parser),
    )
}

/// Builds the tables of every decision of every root parser of one grammar
/// file.
fn outcomes(path: &Path) -> Vec<DecisionOutcome> {
    outcomes_with(path, AtnFallback::Allowed)
}

/// [`outcomes`] with an explicit adaptive fallback policy.
fn outcomes_with(path: &Path, atn_fallback: AtnFallback) -> Vec<DecisionOutcome> {
    outcomes_of(path, |builder| builder.with_atn_fallback(atn_fallback))
}

/// [`outcomes_with`] where every build runs with full widening, like the
/// build after a start state that spent the visit budget. The lookahead depth
/// of 64 lets the tables expand beyond the default frontier of a partial
/// table.
fn widened_outcomes_with(path: &Path, atn_fallback: AtnFallback) -> Vec<DecisionOutcome> {
    outcomes_of(path, |builder| {
        builder
            .with_atn_fallback(atn_fallback)
            .with_widening()
            .with_max_k(64)
    })
}

/// The outcomes of the builders that `setup` configures.
fn outcomes_of(
    path: &Path,
    setup: impl Fn(DecisionTableBuilder) -> DecisionTableBuilder,
) -> Vec<DecisionOutcome> {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let mut results = Vec::new();
    for root in &compilation.roots {
        let Some(parser_id) = root.parser else {
            continue;
        };
        let parser = compilation.parser(parser_id).expect("parser artifact");
        results.extend(setup(builder(parser)).build_all());
    }
    results
}

fn rule_names(path: &Path, results: &[DecisionOutcome]) -> Vec<String> {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let Some(root) = compilation.roots.first() else {
        return Vec::new();
    };
    let Some(parser) = compilation.parser(root.parser.expect("parser root")) else {
        return Vec::new();
    };
    results
        .iter()
        .map(|result| parser.semantic.recognizer.rule_names[result.rule_index].clone())
        .collect()
}

fn kinds(path: &Path) -> Vec<DecisionKind> {
    outcomes(path)
        .into_iter()
        .map(|result| result.kind)
        .collect()
}

/// The kinds of the decisions of the golden corpus: how the generated parser
/// predicts each of them.
#[test]
fn golden_corpus_decisions_get_their_kinds() {
    let cases: [(&str, &[DecisionKind]); 7] = [
        ("CSV.g4", &[DecisionKind::Ll1; 4]),
        (
            "Labels.g4",
            &[
                DecisionKind::Ll1,
                DecisionKind::Ll1,
                DecisionKind::Static,
                DecisionKind::Static,
            ],
        ),
        ("SimpleLR.g4", &[DecisionKind::Static]),
        ("VisitorBasic.g4", &[]),
        (
            "VisitorCalc.g4",
            &[DecisionKind::Static, DecisionKind::Static],
        ),
        (
            "ReferenceToATN.g4",
            &[DecisionKind::Hybrid, DecisionKind::Ll1],
        ),
        // The shared-descent group of `expr ';' | expr '.'` cures every
        // conflict of the first decision.
        (
            "Perf.g4",
            &[
                DecisionKind::Static,
                DecisionKind::Ll1,
                DecisionKind::Static,
                DecisionKind::Hybrid,
            ],
        ),
    ];
    for (file, expected) in cases {
        let path = grammars_dir().join(file);
        assert_eq!(kinds(&path), expected, "{file}");
    }

    let shapes = fixture("parser-shapes").join("ParserShapes.g4");
    assert_eq!(
        kinds(&shapes),
        [
            DecisionKind::Ll1,
            DecisionKind::Hybrid,
            DecisionKind::Ll1,
            DecisionKind::Adaptive,
        ]
    );
    let results = outcomes(&shapes);
    let rules = rule_names(&shapes, &results);
    assert_eq!(rules, ["optional", "plus", "star", "nongreedy"]);
}

#[test]
fn ll1_decisions_need_no_table() {
    let results = outcomes(&grammars_dir().join("CSV.g4"));
    for result in &results {
        assert_eq!(result.kind, DecisionKind::Ll1);
        assert_eq!(result.k, 1);
        assert!(result.table.is_none());
        assert!(result.is_fully_static());
        assert_eq!(result.fallback_text(), "0");
    }
}

#[test]
fn hybrid_tables_escape_at_the_conflict_state() {
    let results = outcomes(&grammars_dir().join("ReferenceToATN.g4"));
    let decision = &results[0];
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert_eq!(decision.k, 2);
    assert_eq!(decision.escapes, 1);
    assert!(!decision.is_fully_static());
    assert_eq!(decision.fallback_text(), "1");
    let table = decision.table.as_ref().expect("hybrid table is kept");
    assert_eq!(table.states.len(), 5);
    assert_eq!(table.states[0].edges.len(), 3);
    assert_eq!(decision.conflict_witness.as_deref(), Some(&[2, -1][..]));
}

#[test]
fn precedence_decisions_get_one_table_per_class() {
    let results = outcomes(&grammars_dir().join("SimpleLR.g4"));
    let decision = &results[0];
    assert_eq!(decision.kind, DecisionKind::Static);
    let precedence = decision.precedence.as_ref().expect("precedence tables");
    assert_eq!(precedence.cutoffs, [2]);
    assert_eq!(precedence.tables.len(), 2);
    assert_eq!(precedence.adaptive_classes, 0);
    assert!(precedence.tables.iter().all(Option::is_some));
    assert!(decision.is_fully_static());
    assert_eq!(decision.fallback_text(), "0");
}

#[test]
fn predicated_branches_escape_while_the_loop_stays_static() {
    let shapes = fixture("parser-shapes").join("ParserShapes.g4");
    let results = outcomes(&shapes);
    let plus = &results[1];
    // The `(B | C)+` loop decision itself is static; only the configs the
    // FOLLOW chase reached through `{ready()}?` depend on the parse state, so
    // they escape and the table stays (Tier 3, per-config predicate taint).
    assert_eq!(plus.kind, DecisionKind::Hybrid);
    let table = plus.table.as_ref().expect("the loop keeps a hybrid table");
    assert!(
        table.states.iter().any(|state| state.predicated),
        "the predicated branch escapes"
    );
    assert!(table.escapes() > 0, "the predicated branch escapes");
    assert!(!plus.is_fully_static());
}

#[test]
fn non_greedy_decisions_are_flagged_without_a_table() {
    let shapes = fixture("parser-shapes").join("ParserShapes.g4");
    let results = outcomes(&shapes);
    let nongreedy = &results[3];
    assert_eq!(nongreedy.kind, DecisionKind::Adaptive);
    assert_eq!(nongreedy.no_table, Some(NoTableReason::NonGreedy));
    assert!(nongreedy.table.is_none());
    // The generated parser predicts a non-greedy subrule with
    // `adaptive_predict`.
    assert!(!nongreedy.is_fully_static());
}

#[test]
fn table_builds_are_deterministic() {
    for file in ["Labels.g4", "Perf.g4", "ReferenceToATN.g4", "SimpleLR.g4"] {
        let path = grammars_dir().join(file);
        let first = outcomes(&path);
        let second = outcomes(&path);
        assert_eq!(first.len(), second.len(), "{file}");
        for (first, second) in first.iter().zip(&second) {
            assert_eq!(first.kind, second.kind, "{file}");
            assert_eq!(first.k, second.k, "{file}");
            assert_eq!(first.num_dfa_states, second.num_dfa_states, "{file}");
            assert_eq!(first.table, second.table, "{file}");
            assert_eq!(first.precedence, second.precedence, "{file}");
        }
    }
}

/// A table must never consume EOF in a loop: the runtime's walker does not
/// advance on EOF, so an EOF edge back to the same state would spin forever
/// instead of predicting.
#[test]
fn no_table_has_an_eof_self_loop() {
    let grammars = [
        "CSV.g4",
        "Labels.g4",
        "Perf.g4",
        "ReferenceToATN.g4",
        "SimpleLR.g4",
        "VisitorBasic.g4",
        "VisitorCalc.g4",
    ];
    let mut tables = Vec::new();
    for file in grammars {
        for result in outcomes(&grammars_dir().join(file)) {
            if let Some(table) = &result.table {
                tables.push((file, result.decision, table.clone()));
            }
            if let Some(precedence) = &result.precedence {
                for table in precedence.tables.iter().flatten() {
                    tables.push((file, result.decision, table.clone()));
                }
            }
        }
    }
    assert!(!tables.is_empty(), "the corpus produces tables");
    for (file, decision, table) in tables {
        for (index, state) in table.states.iter().enumerate() {
            for edge in &state.edges {
                assert!(
                    !(edge.lo == -1 && edge.target == index),
                    "{file} decision {decision}: state {index} loops on EOF"
                );
            }
        }
    }
}

/// The table builds must survive a broad slice of the fixture corpus: no panic,
/// no hang, and every table well formed.
///
/// The corpus is sampled (every fourth grammar) because compiling each grammar
/// fronts the ANTLRv4 frontend, which dominates the runtime of a debug build;
/// the sample still spans ambiguous EBNF, left recursion, predicates, and
/// imported grammars. The visit budget is exercised by the largest grammars of
/// the sample.
#[test]
fn fixture_corpus_builds_without_panicking() {
    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("codegen-direct")
        .join("fixtures");
    let mut all = Vec::new();
    collect_grammars(&fixtures, &mut all);
    assert!(all.len() > 100, "fixture corpus found: {}", all.len());
    all.sort();
    let grammars = all
        .into_iter()
        .enumerate()
        .filter(|(index, _)| index % 4 == 0)
        .map(|(_, path)| path)
        .collect::<Vec<_>>();

    let mut built = 0_usize;
    for path in grammars {
        let Ok(compilation) = compile(LoadOptions {
            roots: vec![path.clone()],
            library_directories: Vec::new(),
        }) else {
            continue;
        };
        for root in &compilation.roots {
            let Some(parser_id) = root.parser else {
                continue;
            };
            let parser = compilation.parser(parser_id).expect("parser artifact");
            let results = builder(parser).build_all();
            for result in results {
                built += 1;
                for table in result.table.iter().chain(
                    result
                        .precedence
                        .iter()
                        .flat_map(|p| p.tables.iter().flatten()),
                ) {
                    assert!(
                        !table.states.is_empty(),
                        "{}: decision {} has an empty table",
                        path.display(),
                        result.decision
                    );
                    for state in &table.states {
                        for edge in &state.edges {
                            assert!(
                                edge.target < table.states.len(),
                                "{}: decision {} edge leaves the table",
                                path.display(),
                                result.decision
                            );
                            assert!(
                                edge.lo <= edge.hi,
                                "{}: empty edge interval",
                                path.display()
                            );
                        }
                    }
                }
            }
        }
    }
    assert!(built > 10, "built {built} decisions");
}

fn collect_grammars(directory: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(directory) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_grammars(&path, out);
        } else if path.extension().is_some_and(|extension| extension == "g4") {
            out.push(path);
        }
    }
}

/// The fixture sample, built under a small visit budget: every attempt is
/// bounded, so this checks the budget path on grammars large enough to hit it
/// without paying the production budget's time.
#[test]
fn whole_fixture_corpus_builds_under_a_small_budget() {
    let fixtures = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("codegen-direct")
        .join("fixtures");
    let mut all = Vec::new();
    collect_grammars(&fixtures, &mut all);
    all.sort();
    let grammars = all
        .into_iter()
        .enumerate()
        .filter(|(index, _)| index % 4 == 0)
        .map(|(_, path)| path)
        .collect::<Vec<_>>();
    let mut tables = 0_usize;
    for path in grammars {
        let Ok(compilation) = compile(LoadOptions {
            roots: vec![path.clone()],
            library_directories: Vec::new(),
        }) else {
            continue;
        };
        for root in &compilation.roots {
            let Some(parser_id) = root.parser else {
                continue;
            };
            let parser = compilation.parser(parser_id).expect("parser artifact");
            let results = builder(parser).with_visit_budget(20_000).build_all();
            for result in results {
                for table in result.table.iter().chain(
                    result
                        .precedence
                        .iter()
                        .flat_map(|p| p.tables.iter().flatten()),
                ) {
                    tables += 1;
                    assert!(!table.states.is_empty(), "{}", path.display());
                    for state in &table.states {
                        for edge in &state.edges {
                            assert!(edge.target < table.states.len(), "{}", path.display());
                        }
                    }
                }
            }
        }
    }
    assert!(tables > 0, "the corpus produces tables");
}

/// A start state that spends the visit budget leaves the decision without a
/// table: the config sets built after the budget ran out are incomplete.
#[test]
fn exhausted_start_state_yields_no_table() {
    let reference = outcomes_with_budget(&grammars_dir().join("ReferenceToATN.g4"), 1);
    let decision = &reference[0];
    assert_eq!(decision.kind, DecisionKind::Adaptive);
    assert_eq!(
        decision.no_table,
        Some(NoTableReason::StartBudget(BudgetCutoff::Visits))
    );
    assert!(decision.table.is_none());
    assert!(!decision.is_fully_static());

    // Every precedence class of the decision has no table.
    let precedence = outcomes_with_budget(&grammars_dir().join("SimpleLR.g4"), 1);
    let decision = &precedence[0];
    assert_eq!(decision.kind, DecisionKind::Adaptive);
    let classes = decision.precedence.as_ref().expect("precedence classes");
    assert_eq!(
        decision.no_table,
        Some(NoTableReason::PrecedenceClasses {
            failed: classes.tables.len(),
            total: classes.tables.len(),
            first: Box::new(NoTableReason::StartBudget(BudgetCutoff::Visits)),
        })
    );
    assert!(classes.tables.iter().all(Option::is_none));
    assert!(!decision.is_fully_static());
}

/// The compiled ATN of one grammar's parser root.
fn parser_atn(path: &Path) -> &'static dbt_antlr_runtime::analysis::ATN {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let root = compilation.roots.first().expect("one root");
    compilation
        .parser(root.parser.expect("parser root"))
        .expect("parser artifact")
        .atn
}

/// The precedence-loop decision of the first left-recursive rule: a
/// `StarLoopEntry` whose exit branch ends the rule (the transformed operator
/// loop), not the `( ... )*` loop of a guarded alternative.
fn precedence_decision(
    atn: &dbt_antlr_runtime::analysis::ATN,
) -> dbt_antlr_runtime::analysis::ATNStateRef {
    use dbt_antlr_runtime::analysis::{ATNStateType, RuleStartState};
    atn.decision_to_state
        .iter()
        .copied()
        .find(|state| {
            state.state_type() == ATNStateType::StarLoopEntry
                && atn.rule_to_start_state[state.get_rule_index() as usize]
                    .try_as::<RuleStartState>()
                    .is_some_and(|start| start.is_left_recursive)
                && state.get_transitions().last().is_some_and(|transition| {
                    let loop_end = transition.get_target();
                    loop_end.state_type() == ATNStateType::LoopEnd
                        && loop_end.has_epsilon_only_transitions()
                        && loop_end.get_transitions().first().is_some_and(|epsilon| {
                            epsilon.get_target().state_type() == ATNStateType::RuleStop
                        })
                })
        })
        .expect("a left-recursive rule has a precedence loop")
}

fn outcomes_with_budget(path: &Path, budget: u64) -> Vec<DecisionOutcome> {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let root = compilation.roots.first().expect("one root");
    let parser = compilation
        .parser(root.parser.expect("parser root"))
        .expect("parser artifact");
    builder(parser).with_visit_budget(budget).build_all()
}

/// Builds the runtime tables of one grammar through the pass, exactly as the
/// compiler stage does.
fn build_tables(path: &Path) -> (Vec<DecisionOutcome>, super::super::StaticParserTables) {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let build = crate::optimization::StaticParserDfa::build(
        compilation
            .parser(compilation.roots[0].parser.expect("parser root"))
            .expect("parser artifact"),
        &compilation.sources,
        AtnFallback::Allowed,
        false,
        &ParserDfaBudgets::default(),
    );
    let results = outcomes(path);
    (results, build.tables)
}

#[test]
fn table_image_loads_in_the_runtime() {
    let (results, tables) = build_tables(&grammars_dir().join("ReferenceToATN.g4"));
    assert!(tables.has_table(0), "decision 0 has a hybrid table");
    assert!(tables.defers(0), "the hybrid table keeps an adaptive path");

    let words = tables.words();
    let decoded = load_image(&words);
    assert_eq!(decoded.words(), words, "the image loads in place");
    assert_eq!(
        decoded.table(0, 0).expect("decoded table").num_states(),
        results[0].num_dfa_states
    );
}

#[test]
fn fully_static_decisions_never_defer() {
    let (results, tables) = build_tables(&grammars_dir().join("parser/StaticDFA.g4"));
    assert!(!results.is_empty());
    for result in &results {
        assert!(
            result.is_fully_static(),
            "decision {} of rule index {} should be fully static, got {:?}",
            result.decision,
            result.rule_index,
            result.kind
        );
        if result.kind == DecisionKind::Ll1 {
            // These kinds have no table.
            continue;
        }
        assert!(tables.has_table(result.decision));
        assert!(!tables.defers(result.decision));
    }
}

#[test]
fn hybrid_frontier_escapes_carry_continuations() {
    let (results, tables) = build_tables(&grammars_dir().join("parser/FuzzExpr.g4"));
    // `binding`, the decision with the most frontier escapes.
    let hybrid = results
        .iter()
        .filter(|result| result.kind == DecisionKind::Hybrid)
        .max_by_key(|result| result.escapes)
        .expect("FuzzExpr has a hybrid decision");
    let words = tables.words();
    let decoded = load_image(&words);
    assert_eq!(decoded.words(), words, "the image loads in place");

    let table = decoded
        .table(hybrid.decision as i32, 0)
        .expect("the hybrid decision has a table");
    let continuations = (0..table.num_states() as i32)
        .filter_map(|state| table.continuation(state))
        .count();
    assert!(
        continuations > 0,
        "decision {} has {} escapes, so its frontier must carry continuations",
        hybrid.decision,
        hybrid.escapes
    );
}

#[test]
fn precedence_class_tables_are_deduplicated() {
    let (results, tables) = build_tables(&grammars_dir().join("parser/LrDfa.g4"));
    let precedence = results
        .iter()
        .find(|result| result.precedence.is_some())
        .expect("LrDfa has a precedence decision");
    let classes = precedence.precedence.as_ref().unwrap();
    assert!(classes.tables.iter().flatten().count() > 0);

    let words = tables.words();
    let decoded = load_image(&words);
    assert!(
        decoded.is_precedence_dispatched(precedence.decision as i32),
        "the precedence decision dispatches on its precedence"
    );
    let first = decoded.table(
        precedence.decision as i32,
        classes.cutoffs.last().copied().unwrap_or(0) + 1,
    );
    assert!(first.is_some(), "the highest class resolves to a table");
}

#[test]
fn table_build_is_deterministic() {
    let path = grammars_dir().join("parser/FuzzExpr.g4");
    let (_, first) = build_tables(&path);
    let (_, second) = build_tables(&path);
    assert_eq!(first.words(), second.words());
}

#[test]
fn emitted_tables_validate_against_the_packed_atn() {
    use dbt_antlr_runtime::atn_packed_deserializer::PackedATNDeserializer;
    use dbt_antlr_runtime::dfa::static_parser_dfa::StaticParserTables;

    for grammar in [
        "ReferenceToATN.g4",
        "parser/StaticDFA.g4",
        "parser/LrDfa.g4",
    ] {
        let path = grammars_dir().join(grammar);
        let compilation = compile(LoadOptions {
            roots: vec![path.clone()],
            library_directories: Vec::new(),
        })
        .expect("grammar compiles");
        let parser = compilation
            .parser(compilation.roots[0].parser.expect("parser root"))
            .expect("parser artifact");
        let build = crate::optimization::StaticParserDfa::build(
            parser,
            &compilation.sources,
            AtnFallback::Allowed,
            false,
            &ParserDfaBudgets::default(),
        );
        let packed = crate::grammar::atn::encode_packed_atn(parser.atn);
        let atn = PackedATNDeserializer::new()
            .deserialize(&packed)
            .expect("the packed ATN deserializes");
        let tables =
            StaticParserTables::from_image(Box::leak(build.tables.words().into_boxed_slice()))
                .expect("the emitted image loads");
        assert!(!tables.is_empty(), "{grammar}: the unit has tables");
        tables
            .validate_for_atn(&atn)
            .unwrap_or_else(|error| panic!("{grammar}: {error}"));

        let mut extended = packed.clone();
        extended.push(0);
        extended[25] += 1;
        assert!(
            PackedATNDeserializer::new().deserialize(&extended).is_err(),
            "{grammar}: words after the last packed section are rejected"
        );
    }
}

/// The operator loop of a left-recursive rule covers the loop decision and the
/// operator alternatives, not the base alternatives and not other rules.
#[test]
fn operator_loop_covers_the_loop_positions_only() {
    let atn = parser_atn(&grammars_dir().join("parser").join("LoopSubst.g4"));
    let decision = precedence_decision(atn);
    let block = LoopBlock::of(atn, decision);
    let rule_index = decision.get_rule_index();

    assert!(block.guards_are_simple(), "the arithmetic loop is simple");
    assert!(
        block.is_loop_consumption(decision, None, BOUNDARY_TAINT),
        "the loop decision is part of the loop"
    );
    // An enclosing invocation that continues a base alternative consumes for
    // that alternative.
    let rule_start = atn.rule_to_start_state[rule_index as usize];
    assert!(!block.is_loop_consumption(rule_start, None, BOUNDARY_TAINT));
    assert!(block.is_foreign_call(rule_start, None));
    // An operand body runs with an operator-loop frame in its context, so its
    // own positions are not loop positions.
    let operand_state = atn.make_state_ref(
        atn.iter_states()
            .find(|state| state.get_rule_index() != rule_index)
            .expect("the grammar has another rule")
            .get_state_number(),
    );
    assert!(!block.is_loop_consumption(operand_state, None, BOUNDARY_TAINT));
    assert!(block.is_foreign_call(operand_state, None));
    assert!(!block.is_foreign_call(decision, None));
    // A new invocation that a foreign call started owns its tokens, even at the
    // positions of the loop.
    assert!(!block.is_loop_consumption(decision, None, BOUNDARY_TAINT | FOREIGN_LINEAGE_TAINT));
    // The decision reaches itself by epsilon, so it owes no token.
    assert!(!block.is_pending(decision));
}

/// A guarded alternative that iterates internally and then owes another token
/// breaks the enter/exit mapping, so the substitution is disabled for the
/// whole rule.
#[test]
fn compound_guarded_alternatives_are_not_substitutable() {
    let atn = parser_atn(&grammars_dir().join("parser").join("LoopVeto.g4"));
    let decision = precedence_decision(atn);
    let block = LoopBlock::of(atn, decision);
    assert!(
        !block.guards_are_simple(),
        "`(',' send)* '>>' send` is not a simple guarded alternative"
    );

    let results = outcomes(&grammars_dir().join("parser").join("LoopVeto.g4"));
    let result = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the loop decision");
    assert_eq!(result.escapes, 2, "the vetoed conflict escapes");
    assert!(!result.is_fully_static());
    let table = &result
        .precedence
        .as_ref()
        .expect("precedence tables")
        .tables[0]
        .as_ref()
        .expect("the first class has a table");
    assert!(
        table
            .states
            .iter()
            .any(|state| state.is_escape() && state.conflicts == [1, 2]),
        "the escape is the iterate/exit conflict"
    );
}

/// The same shape without the compound alternative stays fully static: the
/// iterate/exit conflicts after a lambda body (`x -> a + b`) resolve by
/// substitution. Without it this decision escapes 4 times.
#[test]
fn simple_guarded_alternatives_need_no_escape() {
    let results = outcomes(&grammars_dir().join("parser").join("LoopSubst.g4"));
    let result = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the arithmetic loop decision");
    assert_eq!(result.escapes, 0);
    assert!(result.is_fully_static());
    assert_eq!(result.fallback_text(), "0");
    let classes = result.precedence.as_ref().expect("precedence tables");
    assert_eq!(classes.adaptive_classes, 0);
    assert!(classes.tables.iter().all(Option::is_some));
    let tables: Vec<_> = classes.tables.iter().flatten().collect();
    for table in &tables {
        assert!(
            table
                .states
                .iter()
                .all(|state| !(state.is_escape() && state.conflicts == [1, 2])),
            "no iterate/exit state escapes"
        );
    }
    assert!(
        tables
            .iter()
            .flat_map(|table| table.states.iter())
            .any(|state| state.accept == 1 && state.conflicts == [1, 2]),
        "the substitution resolves an iterate/exit conflict to iterate"
    );
}

/// A follow that starts a new invocation of the loop's rule (`expr+`), or that
/// consumes an operator outside the loop (`'set' expr '||' INT EOF`), puts the
/// 32 iterate/exit conflict states under a stack guard. The 3 budget-frontier
/// states escape: their exit configs are widened, so their guard roots can be
/// in a frame that the widening removed.
#[test]
fn foreign_consumption_guards_the_iterate_reading() {
    let results = outcomes(&grammars_dir().join("parser").join("LoopFrontier.g4"));
    let result = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the arithmetic loop decision");
    assert_eq!(result.k, 4);
    assert_eq!(result.num_dfa_states, 88);
    assert_eq!(result.escapes, 3, "the frontier states escape");
    assert_eq!(result.guarded_states(), 32);
    assert!(!result.is_fully_static(), "a guard may defer");
    let classes = result.precedence.as_ref().expect("precedence tables");
    assert_eq!(classes.adaptive_classes, 0);
    let states: Vec<_> = classes
        .tables
        .iter()
        .flatten()
        .flat_map(|table| table.states.iter())
        .collect();
    assert!(
        states
            .iter()
            .all(|state| !(state.accept == 1 && state.conflicts == [1, 2])),
        "no iterate/exit conflict resolves to iterate outright"
    );
    let guarded: Vec<_> = states
        .iter()
        .copied()
        .filter(|state| state.is_guarded())
        .collect();
    assert_eq!(guarded.len(), 32);
    let conflict_guards = guarded
        .iter()
        .filter(|state| state.conflicts == [1, 2])
        .count();
    let frontier_guards = guarded
        .iter()
        .filter(|state| state.conflicts.is_empty())
        .count();
    assert_eq!((conflict_guards, frontier_guards), (32, 0));
    for state in guarded {
        assert_eq!(state.guarded_alt, 1, "a guarded iterate takes alt 1");
    }
    let table = classes.tables[0].as_ref().expect("class 0 table");
    assert!(!table.guard_danger().is_empty(), "the guard can trip");

    let between = outcomes(&grammars_dir().join("parser").join("BetweenExpr.g4"));
    let boolean_loop = &between[3];
    assert_eq!(boolean_loop.kind, DecisionKind::Static);
    assert_eq!(boolean_loop.escapes, 0);
    assert_eq!(boolean_loop.guarded_states(), 2);
    assert_eq!(boolean_loop.fallback_text(), "2g");
    assert!(!boolean_loop.is_fully_static());
}

/// The token types of `names`, each a literal (`'-'`) or a symbolic token name
/// of one grammar's parser root.
fn token_types(path: &Path, names: &[&str]) -> Vec<i32> {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let root = compilation.roots.first().expect("one root");
    let parser = compilation
        .parser(root.parser.expect("parser root"))
        .expect("parser artifact");
    let recognizer = &parser.semantic.recognizer;
    names
        .iter()
        .map(|name| {
            let position = |names: &[Option<String>]| {
                names
                    .iter()
                    .position(|candidate| candidate.as_deref() == Some(*name))
            };
            position(&recognizer.literal_names)
                .or_else(|| position(&recognizer.symbolic_names))
                .unwrap_or_else(|| panic!("unknown token {name}")) as i32
        })
        .collect()
}

/// The state that `tokens` lead to from the start state, or `None` when a token
/// has no edge.
fn walk<'t>(table: &'t StaticDfaTable, tokens: &[i32]) -> Option<&'t StaticDfaState> {
    let mut state = &table.states[0];
    for token in tokens {
        let edge = state
            .edges
            .iter()
            .find(|edge| edge.lo <= *token && *token <= edge.hi)?;
        state = &table.states[edge.target];
    }
    Some(state)
}

/// After the exit, the loop does not own the tokens of a new invocation of the
/// rule, or the tokens that an enclosing alternative still owes.
/// `LoopSibling.g4` reads `a - - a ;` as `a` and `- - a`,
/// `with pair a - pair - a a` as `pair a (- pair (- a) a)`, `if a ? a - a` as
/// `a ? a - a`, and `opt a ? a - a - a !` as `a ? a - a - a !`. No loop can
/// resolve the iterate/exit conflict on these paths to iterate.
#[test]
fn tokens_that_the_loop_does_not_own_veto_the_substitution() {
    let path = grammars_dir().join("parser").join("LoopSibling.g4");
    let results = outcomes(&path);
    let names = rule_names(&path, &results);
    let types = token_types(&path, &["'-'", "'+'", "'pair'", "ID"]);
    let (minus, plus, pair, id) = (types[0], types[1], types[2], types[3]);
    for (rule, tokens) in [
        ("expr", vec![minus, minus, id]),
        ("term", vec![minus, pair, minus, id]),
        ("cond", vec![minus, id]),
        ("tail", vec![minus, id, minus, id]),
        ("prec", vec![plus, id, plus, id]),
    ] {
        let (result, _) = results
            .iter()
            .zip(&names)
            .find(|(result, name)| result.is_precedence_loop() && *name == rule)
            .unwrap_or_else(|| panic!("the loop decision of {rule}"));
        let ends: Vec<&StaticDfaState> = result
            .precedence
            .as_ref()
            .expect("precedence tables")
            .tables
            .iter()
            .flatten()
            .filter_map(|table| walk(table, &tokens))
            .collect();
        assert!(
            ends.iter()
                .any(|state| state.is_escape() || state.is_guarded()),
            "{rule}: the iterate/exit conflict defers"
        );
        assert!(
            ends.iter().all(|state| state.accept != 1),
            "{rule}: no class table iterates on the path"
        );
    }
}

/// In `LoopObligation.g4`, the exit lineage enters the second `p` of
/// `'trim' '(' p p ')'` and owes `')'` at the lookahead budget. That obligation
/// belongs to a foreign invocation that `FOREIGN_CONSUME_TAINT` already roots,
/// so all 10 iterate/exit states (2 conflict states and 8 budget-frontier
/// states) resolve under the stack guard.
#[test]
fn foreign_rooted_obligations_guard_the_iterate_reading() {
    let path = grammars_dir().join("parser").join("LoopObligation.g4");
    let results = outcomes(&path);
    let result = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the loop decision of `p`");
    assert_eq!(result.k, 4);
    assert_eq!(result.num_dfa_states, 27);
    assert_eq!(result.escapes, 0);
    assert_eq!(result.guarded_states(), 10);
    assert!(!result.is_fully_static());
    assert_eq!(result.fallback_text(), "10g");

    let classes = result.precedence.as_ref().expect("precedence tables");
    assert_eq!(classes.adaptive_classes, 0);
    let types = token_types(&path, &["'['", "':'", "'.'", "'prior'", "'trim'", "ID"]);
    let (open, colon, dot, prior, trim, id) =
        (types[0], types[1], types[2], types[3], types[4], types[5]);

    for table in &classes.tables[..2] {
        let table = table.as_ref().expect("hybrid class table");
        assert_eq!(table.guard_danger(), [9, 15]);
        assert_eq!(table.guard_pass, [40]);

        let conflict = walk(table, &[dot, id]).expect("`.` ID edge");
        assert!(conflict.is_guarded());
        assert_eq!(conflict.guarded_alt, 1);
        assert_eq!(conflict.conflicts, [1, 2]);

        for tail in [open, prior, trim, id] {
            let frontier = walk(table, &[open, id, colon, tail]).expect("frontier edge");
            assert!(frontier.is_guarded());
            assert_eq!(frontier.guarded_alt, 1);
            assert!(frontier.conflicts.is_empty());
        }
    }
}

/// The call site of the first of two side-by-side calls of `rule_index`
/// (`r r`): the call whose follow state calls the rule again.
fn first_of_two_calls(atn: &dbt_antlr_runtime::analysis::ATN, rule_index: usize) -> i32 {
    use dbt_antlr_runtime::analysis::RuleTransition;
    let calls = |state: dbt_antlr_runtime::analysis::ATNStateRef| {
        state.get_transitions().iter().any(|transition| {
            transition
                .try_as::<RuleTransition>()
                .is_some_and(|call| call.get_target().get_rule_index() as usize == rule_index)
        })
    };
    atn.iter_states()
        .map(|state| atn.make_state_ref(state.get_state_number()))
        .find(|state| {
            state.get_transitions().iter().any(|transition| {
                transition.try_as::<RuleTransition>().is_some_and(|call| {
                    call.get_target().get_rule_index() as usize == rule_index
                        && calls(call.follow_state)
                })
            })
        })
        .expect("two side-by-side calls")
        .get_state_number()
}

/// After the skip, a new invocation of the decision rule owns the tokens that
/// it reads. `PostfixSibling.g4` reads `A - B ;` as `A` and `- B`, and
/// `with [ A - B ] X` as `[ A (- B) ] X`. On these paths the tables of `r` and
/// `q` must not take, and a guard must defer at the first of the two
/// side-by-side calls. In `mid A - B A - B A - B !` the skip of the second `m`
/// returns into the middle of the take path of the first, so `m` must not take
/// on that path either.
#[test]
fn new_invocations_after_the_skip_are_out_of_discipline() {
    let path = grammars_dir().join("parser").join("PostfixSibling.g4");
    let atn = parser_atn(&path);
    let results = outcomes(&path);
    let names = rule_names(&path, &results);
    let types = token_types(&path, &["'-'", "'B'", "';'", "']'", "'A'"]);
    let (minus, b, semi, close, a) = (types[0], types[1], types[2], types[3], types[4]);
    for (rule, tokens) in [
        ("r", vec![minus, b, semi]),
        ("q", vec![minus, b, close]),
        ("m", vec![minus, b, a, minus]),
    ] {
        let (result, _) = results
            .iter()
            .zip(&names)
            .find(|(result, name)| {
                result.kind != DecisionKind::Ll1
                    && super::postfix::PostfixShape::analyze(
                        atn,
                        atn.decision_to_state[result.decision],
                    )
                    .is_some()
                    && *name == rule
            })
            .unwrap_or_else(|| panic!("the postfix decision of {rule}"));
        let table = result.table.as_ref().expect("a hybrid table");
        let state = walk(table, &tokens).expect("the path has edges");
        assert_ne!(state.accept, 1, "{rule}: the table does not take outright");
        assert!(
            state.is_escape() || state.is_guarded(),
            "{rule}: the conflict defers"
        );
        if state.is_guarded() && rule != "m" {
            let first_call = first_of_two_calls(atn, result.rule_index);
            assert!(
                table.guard_danger().contains(&first_call),
                "{rule}: the guard defers at the first of the two calls"
            );
        }
    }
}

/// A new invocation of the decision rule in an optional element after the
/// postfix can read what the postfix takes (`c : 'A' w? (c 'C' '!')?`), so the
/// shape check rejects it.
#[test]
fn optional_elements_after_the_postfix_starve_it() {
    let path = grammars_dir().join("parser").join("PostfixSibling.g4");
    let atn = parser_atn(&path);
    let results = outcomes(&path);
    let names = rule_names(&path, &results);
    let shaped: Vec<&str> = results
        .iter()
        .zip(&names)
        .filter(|(result, _)| {
            result.kind != DecisionKind::Ll1
                && super::postfix::PostfixShape::analyze(
                    atn,
                    atn.decision_to_state[result.decision],
                )
                .is_some()
        })
        .map(|(_, name)| name.as_str())
        .collect();
    assert_eq!(shaped, ["r", "q", "m"]);
}

/// The mirror test of a skip configuration, with no context: the frame that it
/// popped into.
#[test]
fn skip_mirrors_need_the_take_path_of_the_popped_frame() {
    use dbt_antlr_runtime::analysis::{MIDWAY_TAINT, ROOTED_TAINT};

    let atn = parser_atn(&grammars_dir().join("parser").join("DanglingElse.g4"));
    let (decision, shape) = atn
        .decision_to_state
        .iter()
        .find_map(|state| {
            super::postfix::PostfixShape::analyze(atn, *state).map(|shape| (*state, shape))
        })
        .expect("the `e?` shape");
    let take = decision.get_transitions()[0].get_target();
    let rule_start = atn.rule_to_start_state[decision.get_rule_index() as usize];

    assert!(
        shape.skip_mirrors(rule_start, None, 0),
        "inside the decision invocation"
    );
    assert!(
        shape.skip_mirrors(take, None, BOUNDARY_TAINT),
        "on the take path"
    );
    assert!(
        !shape.skip_mirrors(rule_start, None, BOUNDARY_TAINT),
        "off the take path"
    );
    for taint in [MIDWAY_TAINT, FOREIGN_LINEAGE_TAINT, ROOTED_TAINT] {
        assert!(!shape.skip_mirrors(take, None, BOUNDARY_TAINT | taint));
    }
    assert!(
        !shape.is_foreign_call(take, None),
        "the take path calls `e`"
    );
    assert!(shape.is_foreign_call(rule_start, None));
}

/// A skip that consumes on the take path of an enclosing invocation mirrors
/// the take reading: the dangling `else` still resolves to take.
#[test]
fn the_take_path_of_an_enclosing_invocation_mirrors_the_take() {
    let results = outcomes(&grammars_dir().join("parser").join("DanglingElse.g4"));
    let fires: usize = results
        .iter()
        .flat_map(DecisionOutcome::tables)
        .flat_map(|table| &table.states)
        .filter(|state| state.accept == 1 && state.conflicts == [1, 2])
        .count();
    assert_eq!(fires, 1);
    assert!(results.iter().all(DecisionOutcome::is_fully_static));
}

/// `pred=predicate?` is the canonical optional-postfix shape, and the
/// `set expr '=' expr` caller is where skip genuinely wins. The grammar has
/// one postfix decision, with no take-rule fire and 8 guarded takes, as the
/// reference Java tool reports.
#[test]
fn optional_postfix_shapes_are_guarded() {
    let path = grammars_dir().join("parser").join("GuardExpr.g4");
    let atn = parser_atn(&path);
    let results = outcomes(&path);
    let shaped: Vec<&DecisionOutcome> = results
        .iter()
        .filter(|result| {
            super::postfix::PostfixShape::analyze(atn, atn.decision_to_state[result.decision])
                .is_some()
        })
        .collect();
    assert_eq!(shaped.len(), 1, "one `pred=predicate?` decision");
    assert_eq!(shaped[0].rule_index, 2, "the `expr` rule owns the shape");
    let fires: usize = results
        .iter()
        .flat_map(DecisionOutcome::tables)
        .flat_map(|table| &table.states)
        .filter(|state| state.accept == 1 && state.conflicts == [1, 2])
        .count();
    assert_eq!(fires, 0);
    let guarded: usize = results.iter().map(DecisionOutcome::guarded_states).sum();
    assert_eq!(guarded, 8, "matching the reference Java tool");
    assert!(!shaped[0].is_fully_static(), "a guard may defer");
    let table = shaped[0].table.as_ref().expect("the hybrid table is kept");
    assert!(!table.guard_danger().is_empty(), "the guard can trip");
    assert!(!table.guard_pass.is_empty(), "the walk can continue");
    assert!(
        table.states.iter().any(|state| state.is_guarded()),
        "the table carries guarded states"
    );

    // No shape means no report line either: the grammar corpus that has no
    // `X Y?` block must stay silent.
    let csv = grammars_dir().join("CSV.g4");
    let csv_atn = parser_atn(&csv);
    let plain = outcomes(&csv);
    assert!(plain.iter().all(|result| {
        super::postfix::PostfixShape::analyze(csv_atn, csv_atn.decision_to_state[result.decision])
            .is_none()
    }));
}

/// Builds the tables of every decision of one grammar and resolves them for
/// `--static-dfa-only`.
fn resolve_static_only(path: &Path) -> Vec<DecisionOutcome> {
    let mut results = outcomes_with(path, AtnFallback::Forbidden);
    for result in &mut results {
        result.resolve_static_only();
    }
    results
}

/// The runtime decoding of the tables of `results`.
fn decoded_tables(
    results: &[DecisionOutcome],
) -> dbt_antlr_runtime::dfa::static_parser_dfa::StaticParserTables {
    load_image(super::build_tables(results).words())
}

/// Overlays an emitted table image the way a generated parser does, from a
/// `'static` word array.
fn load_image(words: &[u32]) -> dbt_antlr_runtime::dfa::static_parser_dfa::StaticParserTables {
    dbt_antlr_runtime::dfa::static_parser_dfa::StaticParserTables::from_image(Box::leak(
        words.to_vec().into_boxed_slice(),
    ))
    .expect("the emitted image loads")
}

/// Every state of every runtime table accepts an alternative, continues the
/// walk, or is guarded with a defer alternative: no state defers to the
/// adaptive simulation.
fn assert_no_runtime_escapes(results: &[DecisionOutcome]) {
    use dbt_antlr_runtime::dfa::static_parser_dfa::{CONFLICT_ESCAPE, ESCAPE};

    let decoded = decoded_tables(results);
    for result in results {
        let precedences = result.precedence.as_ref().map_or_else(
            || vec![0],
            |precedence| {
                std::iter::once(0)
                    .chain(precedence.cutoffs.iter().map(|cutoff| cutoff + 1))
                    .collect()
            },
        );
        for precedence in precedences {
            let Some(table) = decoded.table(result.decision as i32, precedence) else {
                continue;
            };
            for state in 0..table.num_states() as i32 {
                let accept = table.accept(state);
                assert!(
                    ![ESCAPE, CONFLICT_ESCAPE].contains(&accept),
                    "decision {} state {state} still escapes ({accept})",
                    result.decision
                );
                if let Some(guard) = table.guard(state) {
                    assert!(
                        guard.defer_alt > 0,
                        "decision {} state {state} defers to adaptive_predict ({guard:?})",
                        result.decision
                    );
                }
            }
        }
    }
}

#[test]
fn static_only_resolves_conflict_escapes_to_the_minimum_alternative() {
    let results = resolve_static_only(&grammars_dir().join("ReferenceToATN.g4"));
    let decision = &results[0];
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert_eq!(decision.escapes, 0);
    assert!(decision.is_fully_static());
    assert_eq!(decision.fallback_text(), "1m");
    let resolved = decision.static_only.as_ref().expect("resolved");
    assert_eq!((resolved.min_alt, resolved.syntax_error), (1, 0));
    assert_eq!(resolved.min_alt_witness.as_deref(), Some(&[2, -1][..]));

    let table = decision.table.as_ref().expect("the table is kept");
    let state = &table.states[4];
    assert_eq!(
        state.accept, 1,
        "the ATN/ID conflict predicts alternative 1"
    );
    assert_eq!(state.resolution, Some(super::EscapeResolution::MinAlt));
    assert_eq!(table.escapes(), 0);
    assert_no_runtime_escapes(&results);
}

#[test]
fn static_only_turns_predicated_states_into_syntax_errors() {
    let results = resolve_static_only(&fixture("parser-shapes").join("ParserShapes.g4"));
    let plus = &results[1];
    let resolved = plus.static_only.as_ref().expect("the loop is resolved");
    assert_eq!(resolved.min_alt, 0);
    assert!(resolved.syntax_error > 0, "the predicated branches stop");
    assert!(resolved.syntax_error_witness.is_some());
    assert_eq!(plus.fallback_text(), format!("{}x", resolved.syntax_error));

    let table = plus.table.as_ref().expect("the hybrid table is kept");
    let dead_ends: Vec<_> = table
        .states
        .iter()
        .filter(|state| state.resolution == Some(super::EscapeResolution::SyntaxError))
        .collect();
    assert_eq!(dead_ends.len(), resolved.syntax_error);
    for state in dead_ends {
        assert!(state.predicated, "only a predicate stops the guess");
        assert_eq!(state.accept, 0);
        assert_eq!(
            state.fallback, 0,
            "no error-recovery alternative hides the error"
        );
        assert!(state.edges.is_empty());
        assert!(state.continuation.is_none());
    }

    let decoded = decoded_tables(&results);
    let runtime = decoded.table(1, 0).expect("decision 1 has a table");
    let dead_end = super::tables::minimized(table)
        .states
        .iter()
        .position(|state| state.resolution.is_some())
        .expect("a resolved state") as i32;
    assert_eq!(runtime.accept(dead_end), 0);
    assert_eq!(runtime.fallback(dead_end), None);
    for token in -1..=5 {
        assert_eq!(runtime.edge(dead_end, token), None, "token {token}");
    }
}

#[test]
fn static_only_keeps_the_guard_of_guarded_takes() {
    let path = grammars_dir().join("parser").join("GuardExpr.g4");
    let atn = parser_atn(&path);
    let results = resolve_static_only(&path);
    let shaped = results
        .iter()
        .find(|result| {
            super::postfix::PostfixShape::analyze(atn, atn.decision_to_state[result.decision])
                .is_some()
        })
        .expect("the `pred?` decision");
    assert!(
        shaped.guarded_states() > 0,
        "the guarded takes stay guarded"
    );
    assert!(shaped.is_fully_static());
    let table = shaped.table.as_ref().expect("the hybrid table is kept");
    assert_eq!(table.guarded(), shaped.guarded_states());
    assert!(!table.guard_groups.is_empty(), "the guard can trip");
    assert!(!table.guard_pass.is_empty(), "the walk can continue");
    for state in table.states.iter().filter(|state| state.is_guarded()) {
        assert_eq!(state.resolution, Some(super::EscapeResolution::Guarded));
        assert_eq!(state.guarded_alt, 1, "the take");
        assert_eq!(state.guard_defer_alt, 2, "the skip");
        assert!((state.guard_group as usize) < table.guard_groups.len());
    }
    let resolved = shaped.static_only.as_ref().expect("resolved");
    assert_eq!(resolved.guarded, shaped.guarded_states());
    assert!(
        shaped
            .fallback_text()
            .starts_with(&format!("{}g", resolved.guarded)),
        "{}",
        shaped.fallback_text()
    );
    assert_no_runtime_escapes(&results);

    let decoded = decoded_tables(&results);
    let runtime = decoded
        .table(shaped.decision as i32, 0)
        .expect("the decision has a table");
    let guarded = table
        .states
        .iter()
        .position(|state| state.is_guarded())
        .expect("a guarded state") as i32;
    let guard = runtime
        .guard(guarded)
        .expect("the runtime state is guarded");
    assert_eq!((guard.alt, guard.defer_alt), (1, 2));
}

/// In `InlineAlias.g4`, the alias reading of `AS INT64 )` also reaches the
/// `)` of a parenthesis, so the iterate is not real. With the adaptive
/// fallback, the state escapes. Under `--static-dfa-only`, the guard keeps the
/// iterate and returns the exit where the `CAST` operand is on the stack. The
/// `AND` states guard only the `ROWS BETWEEN` operand.
#[test]
fn static_only_guards_iterates_that_consume_foreign_tokens() {
    let path = grammars_dir().join("parser").join("InlineAlias.g4");
    let hybrid = outcomes(&path);
    let hybrid_loop = hybrid
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the operator loop");
    assert!(hybrid_loop.escapes > 0, "the cast state escapes");

    let results = resolve_static_only(&path);
    let alias_loop = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the operator loop");
    let resolved = alias_loop.static_only.as_ref().expect("resolved");
    assert!(resolved.guarded > 0);
    assert_eq!(
        (
            resolved.min_alt,
            resolved.min_viable_alt,
            resolved.syntax_error
        ),
        (0, 0, 0),
        "every state of the loop is guarded: {resolved:?}"
    );
    assert_no_runtime_escapes(&results);

    let precedence = alias_loop.precedence.as_ref().expect("precedence tables");
    let table = precedence
        .tables
        .iter()
        .flatten()
        .max_by_key(|table| table.guarded())
        .expect("a class table");
    assert!(table.guard_groups.len() >= 2, "{:?}", table.guard_groups);
    let smallest = table
        .guard_groups
        .iter()
        .min_by_key(|group| group.len())
        .expect("a group");
    assert!(
        table
            .guard_groups
            .iter()
            .any(|group| group.len() > smallest.len()),
        "the `AND` states do not guard the `CAST` operand: {:?}",
        table.guard_groups
    );
}

/// Each guarded state tests only the roots of its own readings. In
/// `LoopObligation.g4`, the `.` state and the `[` states of the `p` loop
/// guard different invoking states, so they are in different guard groups.
#[test]
fn guarded_states_have_their_own_guard_groups() {
    let results = outcomes(&grammars_dir().join("parser").join("LoopObligation.g4"));
    let p = results
        .iter()
        .find(|result| result.is_precedence_loop())
        .expect("the `p` loop");
    let precedence = p.precedence.as_ref().expect("precedence tables");
    for table in precedence.tables.iter().flatten() {
        if table.guarded() == 0 {
            continue;
        }
        assert_eq!(table.guard_danger(), [9, 15]);
        assert_eq!(table.guard_groups.len(), 2, "{:?}", table.guard_groups);
        for state in table.states.iter().filter(|state| state.is_guarded()) {
            assert_eq!(state.guard_defer_alt, 2, "the exit");
            assert_eq!(
                table.guard_groups[state.guard_group as usize].len(),
                1,
                "a state guards one invoking state"
            );
        }
    }
}

/// Under `--static-dfa-only`, a hybrid table looks further than with the
/// adaptive fallback. Where the larger budget still stops, a state predicts its
/// minimum viable alternative.
#[test]
fn static_only_looks_further_and_guesses_the_minimum_viable_alternative() {
    let path = grammars_dir().join("parser").join("ParenExpr.g4");
    let adaptive = &outcomes(&path)[1];
    assert_eq!(adaptive.kind, DecisionKind::Hybrid);
    let default_table = adaptive.table.as_ref().expect("the hybrid table");
    assert!(default_table.escapes() > 0);

    let results = resolve_static_only(&path);
    let decision = &results[1];
    let table = decision.table.as_ref().expect("the hybrid table is kept");
    assert!(
        table.states.len() > 4 * default_table.states.len(),
        "{} states with the larger budget, {} without",
        table.states.len(),
        default_table.states.len()
    );
    let resolved = decision.static_only.as_ref().expect("resolved");
    assert!(resolved.min_viable_alt > 0, "{resolved:?}");
    assert_eq!(resolved.syntax_error, 0);
    assert!(resolved.min_viable_alt_witness.is_some());
    assert!(
        decision
            .fallback_text()
            .ends_with(&format!("+{}v", resolved.min_viable_alt)),
        "{}",
        decision.fallback_text()
    );

    let guesses: Vec<_> = table
        .states
        .iter()
        .filter(|state| state.resolution == Some(super::EscapeResolution::MinViableAlt))
        .collect();
    assert_eq!(guesses.len(), resolved.min_viable_alt);
    for state in guesses {
        assert!(!state.predicated);
        assert!(state.conflicts.is_empty(), "a guess is not a conflict");
        assert!(state.viable_alts.len() >= 2, "{:?}", state.viable_alts);
        assert_eq!(state.accept, state.viable_alts[0]);
        assert!(state.continuation.is_none());
    }
    assert_no_runtime_escapes(&results);
}

#[test]
fn static_only_keeps_precedence_classes_static() {
    let results = resolve_static_only(&grammars_dir().join("parser").join("LrDfa.g4"));
    assert!(results.iter().any(|result| result.precedence.is_some()));
    for result in &results {
        assert!(
            result.static_only.is_some(),
            "decision {} ({}) resolves",
            result.decision,
            result.kind
        );
        if let Some(precedence) = &result.precedence {
            assert_eq!(precedence.escapes, 0);
            assert!(
                precedence
                    .tables
                    .iter()
                    .flatten()
                    .all(|table| table.escapes() == 0)
            );
        }
    }
    assert_no_runtime_escapes(&results);
}

#[test]
fn static_only_rejects_decisions_without_a_static_prediction() {
    let mut results = outcomes_with(
        &fixture("parser-shapes").join("ParserShapes.g4"),
        AtnFallback::Forbidden,
    );
    let nongreedy = &mut results[3];
    assert_eq!(nongreedy.kind, DecisionKind::Adaptive);
    assert!(!nongreedy.resolve_static_only());
    assert!(nongreedy.static_only.is_none());

    let optional = &mut results[0];
    assert_eq!(optional.kind, DecisionKind::Ll1);
    assert!(optional.resolve_static_only(), "LL(1) needs no table");
    assert_eq!(optional.fallback_text(), "0");
}

/// Without the adaptive fallback, a partial table below the coverage threshold
/// is still better than no table: the builder keeps it, and the resolution
/// turns its escapes into syntax errors.
#[test]
fn static_only_keeps_partial_tables_below_the_coverage_threshold() {
    let path = grammars_dir().join("parser").join("LowCoverage.g4");
    let adaptive = &outcomes(&path)[0];
    assert_eq!(adaptive.kind, DecisionKind::Adaptive);
    assert!(adaptive.table.is_none());

    let results = resolve_static_only(&path);
    let decision = &results[0];
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert!(
        decision.coverage_percent < super::PARTIAL_MIN_COVERAGE_PERCENT,
        "coverage {}%",
        decision.coverage_percent
    );
    assert!(decision.table.is_some());
    let resolved = decision.static_only.as_ref().expect("resolved");
    assert_eq!((resolved.min_alt, resolved.syntax_error), (0, 10));
    assert_eq!(decision.fallback_text(), "10x");
    assert_no_runtime_escapes(&results);
}

/// Builds the tables of a grammar written to a scratch directory.
fn outcomes_of_source(name: &str, source: &str) -> Vec<DecisionOutcome> {
    let directory =
        std::env::temp_dir().join(format!("dbt-antlr-descent-{}-{name}", std::process::id()));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join(format!("{name}.g4"));
    std::fs::write(&path, source).expect("scratch grammar");
    let results = outcomes(&path);
    let _ = std::fs::remove_dir_all(&directory);
    results
}

/// Whether any decision of rule `rule_index` accepts with a shared-descent
/// group.
fn rule_has_groups(results: &[DecisionOutcome], rule_index: usize) -> bool {
    results
        .iter()
        .filter(|result| result.rule_index == rule_index)
        .any(|result| result.descent.is_some())
}

#[test]
fn shared_descent_groups_cure_the_escapes_of_the_fuzz_items() {
    let results = outcomes(&grammars_dir().join("parser/FuzzExpr.g4"));
    let path = grammars_dir().join("parser/FuzzExpr.g4");
    let rules = rule_names(&path, &results);
    let by_rule = |name: &str| {
        results
            .iter()
            .zip(&rules)
            .find(|(_, rule)| *rule == name)
            .map(|(result, _)| result)
            .expect("the rule has a decision")
    };

    // `item : e 'as' name | e`: one parse of `e`, then 'as' or anything else.
    let item = by_rule("item");
    assert_eq!(item.kind, DecisionKind::Static);
    assert_eq!(item.escapes, 0);
    assert_eq!(item.descent_group_states(), 15);
    let plan = item.descent.as_ref().expect("item accepts with a group");
    let [group] = &plan.groups[..] else {
        panic!("one group: {plan:?}");
    };
    assert_eq!(group.alts, [1, 2]);
    assert!(group.prefix.is_empty());
    assert_eq!(group.default_alt, 2);
    assert_eq!(group.arms.len(), 1);
    assert_eq!(group.arms[0].alt, 1);
    assert!(
        item.table
            .as_ref()
            .expect("item has a table")
            .states
            .iter()
            .any(|state| state.accept == group.virtual_alt)
    );

    // `alias`: 'as' can follow the rule, so the member follow sets at the
    // shared call site overlap on 'as' and the group is rejected.
    let alias = by_rule("alias");
    assert!(alias.descent.is_none());
    assert!(alias.escapes > 0);
    // `binding`: the members reach `e` through different rules.
    let binding = by_rule("binding");
    assert!(binding.descent.is_none());
    assert!(binding.escapes > 0);
}

#[test]
fn shared_descent_groups_share_a_one_token_prefix() {
    let results = outcomes(&grammars_dir().join("parser/ParenExpr.g4"));
    let primary = results
        .iter()
        .find(|result| result.descent.is_some())
        .expect("the primary block accepts with a group");
    assert_eq!(primary.descent_group_states(), 8);
    assert_eq!(primary.escapes, 8);
    let group = &primary.descent.as_ref().unwrap().groups[0];
    assert_eq!(group.alts, [3, 4]);
    assert_eq!(group.prefix.len(), 1);
    assert_eq!(group.default_alt, 0);
    let arms: Vec<(i32, usize)> = group
        .arms
        .iter()
        .map(|arm| (arm.alt, arm.tokens.len()))
        .collect();
    assert_eq!(arms, [(3, 1), (4, 1)], "',' and ')'");
}

/// A grammar whose `x` decision needs unbounded lookahead between its two
/// alternatives, which share the rule `y` after `prefix`.
fn descent_witness(name: &str, x: &str, y: &str) -> String {
    format!(
        "grammar {name};\ns : x EOF ;\nx : {x} ;\ny : {y} ;\nID : [a-z]+ ;\nWS : [ \\t]+ -> skip ;\n"
    )
}

#[test]
fn shared_descent_accepts_a_plain_group() {
    let results = outcomes_of_source(
        "DescentPlain",
        &descent_witness("DescentPlain", "y '+' ID | y", "'(' y ')' | ID"),
    );
    assert!(rule_has_groups(&results, 1), "{results:?}");
    assert!(results.iter().all(|result| result.escapes == 0));
}

#[test]
fn shared_descent_rejects_a_rule_with_arguments() {
    let results = outcomes_of_source(
        "DescentArgs",
        &descent_witness("DescentArgs", "y[1] '+' ID | y[1]", "'(' y[1] ')' | ID")
            .replace("y : ", "y[i32 depth] : "),
    );
    assert!(!rule_has_groups(&results, 1));
}

#[test]
fn shared_descent_rejects_a_rule_that_runs_an_action() {
    let results = outcomes_of_source(
        "DescentAction",
        &descent_witness(
            "DescentAction",
            "y '+' ID | y",
            "'(' y ')' | ID {}  {let _ = 1;}",
        ),
    );
    assert!(!rule_has_groups(&results, 1));
}

#[test]
fn shared_descent_rejects_members_with_another_prefix_length() {
    // Alternative 1 reaches `y` after one or two tokens, so skipping one token
    // would not land on `y` for every input.
    let results = outcomes_of_source(
        "DescentPrefix",
        &descent_witness(
            "DescentPrefix",
            "('[' | '[' '[') y '+' ID | '[' y",
            "'(' y ')' | ID",
        ),
    );
    assert!(!rule_has_groups(&results, 1));
    // A multi-token set transition before `y` is not a single-token prefix.
    let results = outcomes_of_source(
        "DescentSetPrefix",
        &descent_witness(
            "DescentSetPrefix",
            "('[' | ']') y '+' ID | '[' y",
            "'(' y ')' | ID",
        ),
    );
    assert!(!rule_has_groups(&results, 1));
}

#[test]
fn shared_descent_skips_optional_blocks() {
    // Both alternatives of the optional block start with `y`, but the block is
    // emitted as an optional block, which has no group arms.
    let results = outcomes_of_source(
        "DescentOptional",
        &descent_witness("DescentOptional", "(y '+' ID)? y", "'(' y ')' | ID"),
    );
    assert!(results.iter().all(|result| result.descent.is_none()));
}

#[test]
fn shared_descent_rejects_decisions_and_loops_before_the_shared_rule() {
    // A loop around `y` calls it again after its first call returned.
    let results = outcomes_of_source(
        "DescentLoop",
        &descent_witness(
            "DescentLoop",
            "(y '+')+ ':' ID | y ';' ID",
            "'(' y ')' | ID",
        ),
    );
    assert!(!rule_has_groups(&results, 1));
    // The re-descent of alternative 1 would have to predict the optional block
    // before it reaches `y`.
    let results = outcomes_of_source(
        "DescentOptionalPrefix",
        &descent_witness(
            "DescentOptionalPrefix",
            "'['? y '+' ID | y ';' ID",
            "'(' y ')' | ID",
        ),
    );
    assert!(!rule_has_groups(&results, 1));
}

#[test]
fn shared_descent_excludes_rules_whose_shared_rule_conflicts_with_member_tails() {
    // In `DescentContext.g4`, `d`, `g`, and `k` call a shared rule (`r` or
    // `h`) that can both exit and continue on a token of the member tails
    // ('+' or 'as'), and `h`'s own members overlap on 'as' in FOLLOW(h).
    // Condition 2 excludes all of them at compile time.
    let results = outcomes(&grammars_dir().join("parser/DescentContext.g4"));
    assert!(
        results
            .iter()
            .all(|result| result.descent.is_none() && result.descent_group_states() == 0),
        "{results:?}"
    );
    // Distinct subrules `a` and `b` inside `r` that match the same input `ID`,
    // after which `a` exits `r` while `b` continues with `'+' ID`.
    let results = outcomes_of_source(
        "DescentDistinctSubrules",
        concat!(
            "grammar DescentDistinctSubrules;\n",
            "s : d EOF ;\n",
            "d : r '+' ID ';' ID | r ';' ID INT ;\n",
            "r : '(' r ')' | b '+' ID | a ;\n",
            "a : '[' a ']' | ID ;\n",
            "b : '[' b ']' | ID ;\n",
            "ID : [a-z]+ ;\n",
            "INT : [0-9]+ ;\n",
            "WS : [ \\t\\n]+ -> skip ;\n",
        ),
    );
    assert!(
        results
            .iter()
            .all(|result| result.descent.is_none() && result.descent_group_states() == 0),
        "{results:?}"
    );
}

/// The build attempts of one decision, in order.
fn attempts_of(results: &[DecisionOutcome], decision: usize) -> Vec<AttemptKind> {
    results[decision]
        .cost
        .attempts
        .iter()
        .map(|attempt| attempt.kind)
        .collect()
}

/// A decision gets one build, even when its table has conflict escapes or
/// stays adaptive.
#[test]
fn one_build_per_decision() {
    let path = fixture("vscode-split").join("TParser.g4");
    let results = outcomes_with_budget(&path, super::DEFAULT_VISIT_BUDGET);
    for (decision, result) in results.iter().enumerate() {
        if result.kind == DecisionKind::Ll1 || result.no_table == Some(NoTableReason::NonGreedy) {
            continue;
        }
        let builds = result
            .precedence
            .as_ref()
            .map_or(1, |precedence| precedence.tables.len());
        assert_eq!(
            attempts_of(&results, decision).len(),
            builds,
            "decision {decision}: {result:?}"
        );
    }

    let path = grammars_dir().join("parser").join("LowCoverage.g4");
    let results = outcomes_with_budget(&path, super::DEFAULT_VISIT_BUDGET);
    assert_eq!(results[0].kind, DecisionKind::Adaptive);
    assert!(matches!(
        results[0].no_table,
        Some(NoTableReason::LowCoverage { .. })
    ));
    assert_eq!(attempts_of(&results, 0), [AttemptKind::Default]);
}

/// A start state that spends the visit budget spends it in the default build,
/// so the widened build runs.
#[test]
fn exhausted_start_state_falls_back_to_widening() {
    let path = grammars_dir().join("ReferenceToATN.g4");
    let results = outcomes_with_budget(&path, 1);
    assert_eq!(results[0].kind, DecisionKind::Adaptive);
    assert_eq!(
        attempts_of(&results, 0),
        [AttemptKind::Default, AttemptKind::Widened]
    );
}

/// A build that spends the visit budget after the start state keeps a table:
/// the states that it cannot expand escape. Only a start state that spends
/// the budget leaves the decision without a table.
#[test]
fn builds_escape_where_the_visit_budget_runs_out() {
    let path =
        fixture("testcompositegrammars-testimportlargegrammar-110006096d").join("NewJava.g4");
    let results = outcomes_with_budget(&path, 2_000);
    assert_eq!(results[7].kind, DecisionKind::Hybrid);
    assert_eq!(results[7].budget_cutoff, Some(BudgetCutoff::Visits));
    assert!(results[7].escapes > 0);
    assert_eq!(
        attempts_of(&results, 7),
        [AttemptKind::Default, AttemptKind::Widened]
    );
    assert_eq!(
        results[7].cost.attempts[0].outcome,
        AttemptOutcome::VisitBudget
    );

    let results = outcomes_with_budget(&path, 100);
    assert_eq!(results[7].kind, DecisionKind::Adaptive);
    assert!(results[7].table.is_none());
}

/// Each precedence class keeps a partial table when its construction spends
/// the visit budget after the start state.
#[test]
fn precedence_classes_keep_tables_where_the_visit_budget_runs_out() {
    let path = grammars_dir().join("parser").join("LoopFrontier.g4");
    let results = outcomes_with_budget(&path, 2_000);
    let precedence = results[4].precedence.as_ref().expect("precedence tables");
    assert_eq!(precedence.adaptive_classes, 0);
    assert_eq!(precedence.tables.len(), 5);
    assert!(precedence.tables.iter().all(Option::is_some));
    assert_eq!(results[4].budget_cutoff, Some(BudgetCutoff::Visits));
}

/// A table with a conflict escape does not fall back to full widening. Here
/// the widened construction predicts the first alternative after `'b' 'a'`,
/// but when `a` is not nested, only the second alternative can read
/// `'b' 'a' 'd' 'e'`.
#[test]
fn conflict_escapes_do_not_fall_back_to_widening() {
    let results = outcomes_of_source(
        "WidenedAfterStop",
        "grammar WidenedAfterStop;\n\
         top : a X | a Y ;\n\
         a : ( A | C ( B A | B a E ) ) D ;\n\
         A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; X : 'x' ; Y : 'y' ;\n",
    );
    let decision = &results[1];
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert_eq!(decision.conflicts, [vec![1, 2]]);
    assert!(decision.table.is_some());
    assert_eq!(attempts_of(&results, 1), [AttemptKind::Default]);
}

/// The widened build does not resolve a conflict that only widening makes.
/// In `WidenedTrust.g4`, both alternatives of decision 1 meet after
/// `'b' 'b' 'b' 'b' 'a'` with an empty context, but only the second
/// alternative can read `c b b b b a d e d x`. The state escapes instead of
/// accepting the first alternative.
#[test]
fn widened_competitors_get_no_uniform_trust() {
    let path = grammars_dir().join("parser").join("WidenedTrust.g4");
    let types = token_types(&path, &["'a'", "'b'"]);
    let (a, b) = (types[0], types[1]);
    for atn_fallback in [AtnFallback::Allowed, AtnFallback::Forbidden] {
        let results = widened_outcomes_with(&path, atn_fallback);
        let decision = &results[1];
        assert_eq!(attempts_of(&results, 1), [AttemptKind::Widened]);
        assert!(!decision.is_fully_static(), "{atn_fallback:?}");
        let table = decision.table.as_ref().expect("a partial table");
        assert!(
            !table
                .states
                .iter()
                .any(|state| state.accept > 0 && state.conflicts.len() > 1),
            "{atn_fallback:?}: no conflict state resolves to an alternative"
        );
        let conflict = walk(table, &[b, b, b, b, a]).expect("conflict state");
        assert_eq!(
            conflict.accept, CONFLICT_ESCAPE,
            "{atn_fallback:?}: the table does not decide after `'b' 'b' 'b' 'b' 'a'`"
        );
        assert_eq!(conflict.conflicts, [1, 2], "{atn_fallback:?}");
    }
}

/// The precedence filter of a widened precedence class keeps an exit config
/// that widening made equal to an iterate config. In `WidenedPrecedence.g4`,
/// above class 0 (`p <= 2`), the loop cannot iterate through `e op`. The other
/// iterate reading of `'+' 'q' 'r'` owes `'a'`, so no class table above class
/// 0 can predict the iterate for `'+' 'q' 'r' EOF`: it predicts the exit, or
/// it keeps the exit in a state that escapes or tests a stack guard where
/// widening merges the two readings.
#[test]
fn widened_precedence_filter_keeps_the_exit() {
    let path = grammars_dir().join("parser").join("WidenedPrecedence.g4");
    let types = token_types(&path, &["'+'", "'q'", "'r'"]);
    let tokens = [types[0], types[1], types[2], EOF];
    for widened in [false, true] {
        for atn_fallback in [AtnFallback::Allowed, AtnFallback::Forbidden] {
            let results = if widened {
                widened_outcomes_with(&path, atn_fallback)
            } else {
                outcomes_with(&path, atn_fallback)
            };
            let decision = &results[1];
            assert!(decision.is_precedence_loop());
            assert_eq!(
                decision
                    .cost
                    .attempts
                    .iter()
                    .all(|attempt| attempt.kind == AttemptKind::Widened),
                widened,
                "{atn_fallback:?}"
            );
            let precedence = decision.precedence.as_ref().expect("precedence tables");
            assert_eq!(precedence.cutoffs[0], 2);
            assert_eq!(precedence.adaptive_classes, 0, "{atn_fallback:?}");
            for (class, table) in precedence.tables.iter().enumerate().skip(1) {
                let table = table.as_ref().expect("class table");
                let prediction = (0..=tokens.len())
                    .filter_map(|length| walk(table, &tokens[..length]))
                    .find(|state| state.accept != 0);
                assert!(
                    prediction.is_some_and(|state| {
                        state.accept == 2
                            || (state.accept < 0
                                && (state.conflicts.contains(&2) || state.viable_alts.contains(&2)))
                    }),
                    "{atn_fallback:?}, widened {widened}: class {class} iterates on \
                     `'+' 'q' 'r' EOF`"
                );
            }
        }
    }
}

/// The results of parallel table builds do not depend on the thread count.
#[test]
fn parallel_builds_match_serial_builds() {
    let mut grammars = Vec::new();
    collect_grammars(&grammars_dir(), &mut grammars);
    grammars.push(fixture("vscode-cpp14/CPP14.g4"));
    grammars.sort();
    let mut decisions = 0_usize;
    for path in grammars {
        let Ok(compilation) = compile(LoadOptions {
            roots: vec![path.clone()],
            library_directories: Vec::new(),
        }) else {
            continue;
        };
        for root in &compilation.roots {
            let Some(parser_id) = root.parser else {
                continue;
            };
            let parser = compilation.parser(parser_id).expect("parser artifact");
            for atn_fallback in [AtnFallback::Allowed, AtnFallback::Forbidden] {
                let build_on = |threads| {
                    builder(parser)
                        .with_atn_fallback(atn_fallback)
                        .with_visit_budget(5_000)
                        .build_on(threads)
                };
                // The parallel run comes first, so that it fills the caches of
                // the ATN states from more than one thread.
                let parallel = build_on(8);
                let serial = build_on(1);
                decisions += serial.len();
                assert_eq!(serial, parallel, "{}", path.display());
            }
        }
    }
    assert!(decisions > 800, "decisions built: {decisions}");
}

/// Budget settings with the global visit budget `budget`.
fn visit_budget(budget: u64) -> ParserDfaBudgets {
    ParserDfaBudgets {
        global: BudgetLimits {
            max_visits: Some(budget),
            ..BudgetLimits::default()
        },
    }
}

/// Builds the pass artifact of the first root parser of one grammar under a
/// visit budget.
fn build_with_budget(
    path: &Path,
    budget: u64,
) -> crate::optimization::static_parser_dfa::StaticParserDfaArtifact {
    let compilation = compile(LoadOptions {
        roots: vec![path.to_path_buf()],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let parser = compilation
        .parser(compilation.roots[0].parser.expect("parser root"))
        .expect("parser artifact");
    crate::optimization::StaticParserDfa::build(
        parser,
        &compilation.sources,
        AtnFallback::Allowed,
        false,
        &visit_budget(budget),
    )
}

/// A decision with an attempt that spends the visit budget gets one `G4S193`
/// warning, with the counts of the attempts and the most visited rules.
#[test]
fn spent_visit_budgets_emit_g4s193_warnings() {
    let build = build_with_budget(&grammars_dir().join("Perf.g4"), 100);
    let warnings: Vec<_> = build
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "G4S193")
        .map(|diagnostic| {
            assert_eq!(diagnostic.severity, Severity::Warning);
            diagnostic.message.as_str()
        })
        .collect();
    assert_eq!(
        warnings,
        [
            "the analysis of parser decision 0 of rule 'stat' is slow: 1 of 1 build attempts \
             spent the visit budget (100 configs); 100 configs visited, 6 DFA states built; \
             most visited rules: expr 93%, stat 7%",
            "the analysis of parser decision 3 of rule 'expr' is slow: 3 of 7 build attempts \
             spent the visit budget (100 configs); 548 configs visited, 23 DFA states built; \
             most visited rules: expr 88%, stat 11%",
        ]
    );

    let build = build_with_budget(&grammars_dir().join("Perf.g4"), super::DEFAULT_VISIT_BUDGET);
    assert!(
        build
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.code != "G4S193"),
        "{:?}",
        build.diagnostics
    );
}

/// The cost of a decision adds up: each attempt visits at most the budget,
/// and the visits by rule sum to the visits of the attempts.
#[test]
fn decision_costs_account_for_every_visit() {
    for budget in [100, super::DEFAULT_VISIT_BUDGET] {
        let results = outcomes_with_budget(&grammars_dir().join("Perf.g4"), budget);
        for result in &results {
            let cost = &result.cost;
            assert!(cost.elapsed.is_none(), "no times without profiling");
            for attempt in &cost.attempts {
                assert!(attempt.visits <= budget, "{attempt:?}");
                assert!(attempt.elapsed.is_none());
                if attempt.outcome == AttemptOutcome::VisitBudget {
                    assert_eq!(attempt.visits, budget, "{attempt:?}");
                }
            }
            let by_rule: u64 = cost.rule_visits.iter().map(|(_, visits)| visits).sum();
            assert_eq!(by_rule, cost.visits(), "decision {}", result.decision);
        }
        assert_eq!(attempts_of(&results, 1), []);
        assert_eq!(attempts_of(&results, 2), [AttemptKind::Default]);
    }
}

/// The attempt codes name the precedence class of each attempt and the
/// builds of `--static-dfa-only`.
#[test]
fn attempt_codes_follow_the_classes_and_the_fallback_policy() {
    let results = outcomes_with_budget(
        &grammars_dir().join("parser").join("LoopFrontier.g4"),
        2_000,
    );
    assert_eq!(
        results[4].cost.attempts_text(),
        "c0: D$; c1: D$; c2: D$; c3: D; c4: D"
    );

    let path = grammars_dir().join("ReferenceToATN.g4");
    assert_eq!(outcomes(&path)[0].cost.attempts_text(), "D");
    assert_eq!(
        outcomes_with(&path, AtnFallback::Forbidden)[0]
            .cost
            .attempts_text(),
        "S"
    );
}

/// With profiling, every decision and every attempt carries its time, and the
/// profile lists the 20 slowest decisions.
#[test]
fn profiled_builds_time_every_decision_and_list_the_slowest() {
    let directory = std::env::temp_dir().join(format!("dbt-antlr-profile-{}", std::process::id()));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join("Many.g4");
    let mut source = String::from("grammar Many;\n");
    for rule in 0..25 {
        source.push_str(&format!("r{rule} : A B | A C ;\n"));
    }
    source.push_str("A : 'a' ; B : 'b' ; C : 'c' ;\n");
    std::fs::write(&path, source).expect("scratch grammar");
    let compilation = compile(LoadOptions {
        roots: vec![path],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let _ = std::fs::remove_dir_all(&directory);
    let parser = compilation
        .parser(compilation.roots[0].parser.expect("parser root"))
        .expect("parser artifact");
    let build = crate::optimization::StaticParserDfa::build(
        parser,
        &compilation.sources,
        AtnFallback::Allowed,
        true,
        &ParserDfaBudgets::default(),
    );

    assert_eq!(build.report.decisions.len(), 25);
    for decision in &build.report.decisions {
        let cost = &decision.result.cost;
        assert!(cost.elapsed.is_some(), "{cost:?}");
        assert_eq!(cost.attempts.len(), 1, "{cost:?}");
        assert!(
            cost.attempts
                .iter()
                .all(|attempt| attempt.elapsed.is_some())
        );
    }
    let profile = crate::optimization::StaticParserDfa::render_decision_profile(&[build.report]);
    let lines: Vec<&str> = profile.lines().collect();
    let slowest = lines
        .iter()
        .position(|line| *line == "slowest 20 decisions:")
        .unwrap_or_else(|| panic!("{profile}"));
    assert!(
        lines[slowest + 1].trim_start().starts_with("#  rule"),
        "{profile}"
    );
    let rows = lines[slowest + 2..]
        .iter()
        .filter(|line| !line.is_empty())
        .count();
    assert_eq!(rows, 20, "{profile}");
}

/// Labeled single-token alternatives keep one branch per token, and all
/// branches end at the block end. Their token classes share one closure, so
/// each extra token adds only a few visits.
#[test]
fn single_token_alternatives_share_one_successor() {
    fn keywords(count: usize) -> DecisionOutcome {
        let mut source = format!("grammar Keywords{count};\ns : word X | word Y ;\nword :");
        for keyword in 0..count {
            source.push_str(&format!(" K{keyword} #k{keyword} |"));
        }
        source.push_str(" L K0 R #nested ;\nX : 'x' ; Y : 'y' ; L : '(' ; R : ')' ;\n");
        for keyword in 0..count {
            source.push_str(&format!("K{keyword} : 'k{keyword}' ;\n"));
        }
        outcomes_of_source(&format!("Keywords{count}"), &source).remove(0)
    }

    let few = keywords(2);
    let many = keywords(200);
    assert_eq!(few.kind, DecisionKind::Static);
    assert_eq!(many.kind, few.kind);
    assert_eq!(many.k, few.k);
    assert_eq!(many.num_dfa_states, few.num_dfa_states);
    let start = &many.table.as_ref().expect("LL(k) table").states[0];
    let covered: i32 = start.edges.iter().map(|edge| edge.hi - edge.lo + 1).sum();
    assert_eq!(
        covered, 201,
        "each keyword and L lead out of the start state"
    );
    let extra = many.cost.visits() - few.cost.visits();
    assert!(extra <= 3 * 198, "{extra} extra visits");
}

/// Builds the pass artifact of a grammar written to a scratch directory.
fn build_source(
    name: &str,
    source: &str,
) -> crate::optimization::static_parser_dfa::StaticParserDfaArtifact {
    let directory =
        std::env::temp_dir().join(format!("dbt-antlr-build-{}-{name}", std::process::id()));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join(format!("{name}.g4"));
    std::fs::write(&path, source).expect("scratch grammar");
    let build = build_with_budget(&path, super::DEFAULT_VISIT_BUDGET);
    let _ = std::fs::remove_dir_all(&directory);
    build
}

/// A grammar whose rule `word` has `alternatives` as its block, with the
/// parser rules `rules`, 70 keyword tokens `K0` to `K69`, and `callers` rules
/// that call `word`.
fn keyword_grammar(name: &str, alternatives: &str, rules: &str, callers: usize) -> String {
    let mut source = format!("grammar {name};\nword : {alternatives} ;\n{rules}");
    for caller in 0..callers {
        source.push_str(&format!("r{caller} : word X ;\n"));
    }
    source.push_str("X : 'x' ; L : '(' ; R : ')' ;\n");
    for keyword in 0..70 {
        source.push_str(&format!("K{keyword} : 'k{keyword}' ;\n"));
    }
    source
}

/// The `G4S194` warnings of a keyword grammar, with their spans as
/// `line:column`.
fn token_branch_warnings(
    name: &str,
    alternatives: &str,
    rules: &str,
    callers: usize,
) -> Vec<(String, String)> {
    let source = keyword_grammar(name, alternatives, rules, callers);
    build_source(name, &source)
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "G4S194")
        .map(|diagnostic| {
            assert_eq!(diagnostic.severity, Severity::Warning);
            let offset = diagnostic.primary.bytes.start as usize;
            let line = source[..offset].matches('\n').count() + 1;
            let column = offset
                - source[..offset]
                    .rfind('\n')
                    .map_or(0, |newline| newline + 1);
            (format!("{line}:{column}"), diagnostic.message.clone())
        })
        .collect()
}

/// The causes and the entry count of one `G4S194` message.
fn token_branch_causes(message: &str) -> &str {
    let start = message.find("because ").expect("causes") + "because ".len();
    let end = message.find(" before they read").expect("entries");
    &message[start..end]
}

/// A block of many single-token alternatives that do not fold into one token
/// set gets one `G4S194` warning when many call sites enter its rule. The
/// warning tells why the block did not fold, and it stops when the tokens are
/// in one subrule.
#[test]
fn unfolded_token_branches_emit_g4s194_warnings() {
    let keywords = (0..70)
        .map(|keyword| format!("K{keyword}"))
        .collect::<Vec<_>>();
    let mixed = format!("{} | L word R", keywords.join(" | "));
    assert_eq!(
        token_branch_warnings("Mixed", &mixed, "", 20),
        [(
            "2:7".to_owned(),
            "rule 'word' has a block with 70 single-token alternatives that do not fold into one \
             token set. The block does not fold because 1 alternative is not a single token. 21 \
             call sites enter the rule before they read a token. The analysis of the static \
             parser DFA follows each alternative at each site. Move the single tokens into one \
             unlabeled subrule, for example `( A | B | C )`, or into a token-only rule"
                .to_owned()
        )]
    );

    let causes = |name: &str, alternatives: &str, rules: &str, callers: usize| {
        token_branch_warnings(name, alternatives, rules, callers)
            .iter()
            .map(|(span, message)| format!("{span} {}", token_branch_causes(message)))
            .collect::<Vec<_>>()
    };
    let labeled = keywords
        .iter()
        .map(|keyword| format!("{keyword} #{}", keyword.to_lowercase()))
        .collect::<Vec<_>>()
        .join(" | ");
    assert_eq!(
        causes("Labeled", &labeled, "", 20),
        ["2:7 70 alternatives have a label. 20 call sites enter the rule"]
    );
    assert_eq!(causes("Callers", &labeled, "", 19), [] as [String; 0]);
    let element_labels = keywords
        .iter()
        .map(|keyword| format!("k={keyword}"))
        .collect::<Vec<_>>()
        .join(" | ");
    assert_eq!(
        causes("ElementLabels", &format!("{element_labels} | L"), "", 20),
        ["2:7 70 tokens have an element label. 20 call sites enter the rule"]
    );

    let threshold = format!("{} | L word R", keywords[..64].join(" | "));
    assert_eq!(causes("Threshold", &threshold, "", 20).len(), 1);
    let few = format!("{} | L word R", keywords[..63].join(" | "));
    assert_eq!(causes("Few", &few, "", 20), [] as [String; 0]);
    assert_eq!(
        causes("Folded", &keywords.join(" | "), "", 20),
        [] as [String; 0]
    );
    let grouped = format!("( {} ) | L word R", keywords.join(" | "));
    assert_eq!(causes("Grouped", &grouped, "", 20), [] as [String; 0]);
    let late = format!("L ( {mixed} ) | X");
    assert_eq!(causes("Late", &late, "", 20), [] as [String; 0]);

    // `inner` is a left corner of `word` behind the nullable rule `opt`.
    let rules = format!("opt : L | ;\ninner : {mixed} ;\n");
    assert_eq!(
        causes("Inner", "opt inner X | L", &rules, 20),
        ["4:8 1 alternative is not a single token. 22 call sites enter the rule"]
    );
    // Only the second nested block comes before a token.
    let nested = format!("X ( {mixed} )? | ( {mixed} ) X");
    let column = "word : ".len() + nested.rfind("( ").expect("second block");
    assert_eq!(
        causes("Nested", &nested, "", 20),
        [format!(
            "2:{column} 1 alternative is not a single token. 22 call sites enter the rule"
        )]
    );
    // A nullable subrule or a call of a nullable rule does not read a token.
    for (name, prefix) in [("NullableBlock", "( L | )"), ("NullableCall", "opt")] {
        let behind = format!("{prefix} ( {mixed} ) X");
        let column = "word : ".len() + behind.rfind("( K0").expect("block");
        assert_eq!(
            causes(name, &behind, "opt : L | ;\n", 20),
            [format!(
                "2:{column} 1 alternative is not a single token. 21 call sites enter the rule"
            )]
        );
    }
    let recursive = format!("{} | word L word", keywords.join(" | "));
    assert_eq!(
        causes("Recursive", &recursive, "", 20),
        ["2:7 1 alternative is not a single token. 21 call sites enter the rule"]
    );
}

/// The compiler diagnostics and the pass artifact of a grammar written to a
/// scratch directory, under `budgets`.
fn build_source_with(
    name: &str,
    source: &str,
    atn_fallback: AtnFallback,
    budgets: &ParserDfaBudgets,
) -> (
    Vec<crate::grammar::diagnostic::Diagnostic>,
    crate::optimization::static_parser_dfa::StaticParserDfaArtifact,
) {
    static SCRATCH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let scratch = SCRATCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let directory = std::env::temp_dir().join(format!(
        "dbt-antlr-budget-{}-{scratch}-{name}",
        std::process::id()
    ));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join(format!("{name}.g4"));
    std::fs::write(&path, source).expect("scratch grammar");
    let compilation = compile(LoadOptions {
        roots: vec![path],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let _ = std::fs::remove_dir_all(&directory);
    let parser = compilation
        .parser(compilation.roots[0].parser.expect("parser root"))
        .expect("parser artifact");
    let build = crate::optimization::StaticParserDfa::build(
        parser,
        &compilation.sources,
        atn_fallback,
        false,
        budgets,
    );
    (compilation.diagnostics.clone(), build)
}

/// The budgets of the decisions of rule `rule`, in decision order.
fn rule_budgets(
    build: &crate::optimization::static_parser_dfa::StaticParserDfaArtifact,
    rule: &str,
) -> Vec<super::DecisionBudget> {
    build
        .report
        .decisions
        .iter()
        .filter(|decision| decision.rule == rule)
        .map(|decision| decision.result.budget)
        .collect()
}

const BUDGET_GRAMMAR: &str = "grammar Budgets;
options { max_dfa_states = 7; }
s : a b EOF ;
a options { max_k = 3; } : A B | A C ;
b : ( options { max_dfa_visits = 5000; } : X Y | X Z ) | W ;
A : 'a' ; B : 'b' ; C : 'c' ; X : 'x' ; Y : 'y' ; Z : 'z' ; W : 'w' ;
";

/// The grammar, rule, and block options set the budgets of the decisions, a
/// block budget wins over a rule budget, which wins over a grammar budget, and
/// each limit resolves on its own.
#[test]
fn budget_options_set_the_budgets_of_their_decisions() {
    let (diagnostics, build) = build_source_with(
        "Budgets",
        BUDGET_GRAMMAR,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    assert!(
        diagnostics
            .iter()
            .all(|diagnostic| !matches!(diagnostic.code, "G4S014" | "G4S015")),
        "{diagnostics:?}"
    );
    let budget = |max_states, max_k, max_visits| super::DecisionBudget {
        max_states,
        max_k,
        max_visits,
        explicit_max_states: true,
    };
    assert_eq!(rule_budgets(&build, "a"), [budget(7, Some(3), 2_000_000)]);
    assert_eq!(
        rule_budgets(&build, "b"),
        [budget(7, None, 5_000), budget(7, None, 2_000_000)]
    );
    assert_eq!(build.report.budget, budget(7, None, 2_000_000));
}

/// The base limits apply only where no option sets a limit.
#[test]
fn budget_options_win_over_the_base_limits() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(50),
            max_k: Some(2),
            max_visits: Some(9_000),
        },
    };
    let (_, build) = build_source_with("Budgets", BUDGET_GRAMMAR, AtnFallback::Allowed, &budgets);
    let budget = |max_states, max_k, max_visits| super::DecisionBudget {
        max_states,
        max_k,
        max_visits,
        explicit_max_states: true,
    };
    assert_eq!(rule_budgets(&build, "a"), [budget(7, Some(3), 9_000)]);
    assert_eq!(
        rule_budgets(&build, "b"),
        [budget(7, Some(2), 5_000), budget(7, Some(2), 9_000)]
    );
}

/// A budget option with a value that is not a positive integer gets a
/// `G4S015` warning, and the pass ignores it.
#[test]
fn incorrect_budget_option_values_emit_g4s015_warnings() {
    let source = "grammar Wrong;
options { max_dfa_states = 0; }
s options { max_k = many; } : A B | A C ;
A : 'a' ; B : 'b' ; C : 'c' ;
";
    let (diagnostics, build) = build_source_with(
        "Wrong",
        source,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    let warnings: Vec<_> = diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "G4S015")
        .map(|diagnostic| diagnostic.message.as_str())
        .collect();
    assert_eq!(
        warnings,
        [
            "unsupported option value max_dfa_states=0: the value must be at least 1",
            "unsupported option value max_k=many: 'many' is not a positive integer",
        ]
    );
    assert_eq!(
        rule_budgets(&build, "s"),
        [super::DecisionBudget::default()]
    );
}

const FANOUT_GRAMMAR: &str = "grammar Fanout;
s : a EOF ;
a : A B X | A C X | A D X | A B Y | E ;
A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; X : 'x' ; Y : 'y' ;
";

/// A hybrid table escapes the state whose expansion would run past the state
/// cap, also below depth 2, instead of losing the whole table. Under
/// `--static-dfa-only`, the escape is a guess and not an error.
#[test]
fn state_caps_cut_hybrid_tables_instead_of_failing_them() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(4),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with("Fanout", FANOUT_GRAMMAR, AtnFallback::Allowed, &budgets);
    let decision = &build.report.decisions[0];
    assert_eq!(decision.rule, "a");
    assert_eq!(decision.result.kind, DecisionKind::Hybrid);
    assert_eq!(decision.result.budget_cutoff, Some(BudgetCutoff::States));
    assert_eq!(decision.result.num_dfa_states, 3);

    let (_, build) = build_source_with("Fanout", FANOUT_GRAMMAR, AtnFallback::Forbidden, &budgets);
    let messages: Vec<_> = build
        .diagnostics
        .iter()
        .map(|diagnostic| (diagnostic.code, diagnostic.message.as_str()))
        .collect();
    assert_eq!(
        messages,
        [(
            "G4S192",
            "decision 0 of rule 'a' applied heuristic resolution of escape states: \
             1 undecided state predicts the minimum viable alternative (witness: 'a'); \
             tie-breaks: 1 state chooses alt 1 (A B X, line 3) over alt 2 (A C X, line 3), \
             alt 3 (A D X, line 3), alt 4 (A B Y, line 3) [prefix-hijack hazard: alt 2 \
             (A C X, line 3) reads 'c' after 'a', and alt 1 cannot]; the analysis budget (4 \
             states) stopped the lookahead; raise it with the max_dfa_states option of the \
             grammar, the rule, or the block"
        )]
    );

    let (_, build) = build_source_with(
        "Fanout",
        FANOUT_GRAMMAR,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    assert!(build.diagnostics.is_empty(), "{:?}", build.diagnostics);
}

#[test]
fn visit_budget_cutoff_reports_max_dfa_visits_in_g4s192() {
    let source = "grammar VisitCutoff;\n\
                  options { max_dfa_visits = 60; }\n\
                  top : 'k' 'p' a0 'x' | 'k' 'p' a0 'y' | 'z' ;\n\
                  a0 : c0 ;\n\
                  c0 : c1 | c2 ; c1 : c3 | c4 ; c2 : c3 | c4 ;\n\
                  c3 : c5 | c6 ; c4 : c5 | c6 ; c5 : c7 | c8 ; c6 : c7 | c8 ;\n\
                  c7 : 'f' | 'g' ; c8 : 'h' | 'i' ;\n";
    let (_, build) = build_source_with(
        "VisitCutoff",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let decision = build
        .report
        .decisions
        .iter()
        .find(|entry| entry.rule == "top")
        .expect("top decision");
    assert_eq!(decision.result.kind, DecisionKind::Hybrid);
    assert_eq!(decision.result.budget_cutoff, Some(BudgetCutoff::Visits));
    let warning = build
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "G4S192")
        .expect("a G4S192 warning");
    assert!(
        warning.message.contains(
            "the analysis budget (60 visited configs) stopped the lookahead; \
             raise it with the max_dfa_visits option of the grammar, the rule, or the block"
        ),
        "{}",
        warning.message
    );
}

#[test]
fn start_state_state_cap_reports_states_in_g4s190() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(2),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with("Fanout", FANOUT_GRAMMAR, AtnFallback::Forbidden, &budgets);
    let decision = &build.report.decisions[0];
    assert_eq!(
        decision.result.no_table,
        Some(NoTableReason::StartBudget(BudgetCutoff::States))
    );
    let error = build
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "G4S190")
        .expect("a G4S190 error");
    assert!(
        error
            .message
            .contains("the SLL DFA exceeded the analysis budget (2 states)"),
        "{}",
        error.message
    );
}

const SPLIT_OPERATOR_GRAMMAR: &str = "grammar Split;
s : e EOF ;
e : e '+' 'q' 'a' | e '*' e | e '+' 'q' 'b' | 'x' ;
";

/// The accept of the state that `tokens` reach from the start of `table`.
fn accept_after(table: &StaticDfaTable, tokens: &[i32]) -> Option<i32> {
    let mut state = 0;
    for token in tokens {
        state = table.states[state]
            .edges
            .iter()
            .find(|edge| edge.lo <= *token && *token <= edge.hi)?
            .target;
    }
    Some(table.states[state].accept)
}

/// A frontier state where a multi-token operator has not yet separated the
/// alternatives does not resolve to iterate. In the class of the right operand
/// of `*`, only the first `+` operator iterates, and the exit lineage enters
/// the second `+` operator again: after `+ q`, the input can still be `b`.
#[test]
fn frontier_iterates_need_every_exit_position_in_the_iterate_lineage() {
    let accepts = split_operator_accepts("Split", SPLIT_OPERATOR_GRAMMAR, 4);
    assert_eq!(accepts.len(), 4, "the cutoffs are 2, 3, and 4");
    // The class `p=4` escapes after `+ q` instead of predicting the iterate.
    assert_eq!(accepts[2], Some(super::ESCAPE), "{accepts:?}");
}

/// The accepts after `+ q` in each precedence class, for a grammar built with
/// the state cap `max_states`.
fn split_operator_accepts(name: &str, source: &str, max_states: usize) -> Vec<Option<i32>> {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(max_states),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with(name, source, AtnFallback::Allowed, &budgets);
    let token = |name: &str| {
        build
            .report
            .vocabulary
            .iter()
            .position(|display| display == name)
            .map(|index| index as i32 + 1)
            .expect("token in vocabulary")
    };
    let path = [token("'+'"), token("'q'")];
    let decision = build
        .report
        .decisions
        .iter()
        .find(|decision| decision.result.is_precedence_loop())
        .expect("a precedence loop decision");
    let precedence = decision.result.precedence.as_ref().expect("classes");
    precedence
        .tables
        .iter()
        .map(|table| table.as_ref().and_then(|table| accept_after(table, &path)))
        .collect()
}

/// A foreign exit config does not make the frontier state a guard candidate
/// when another exit config of the state is not in the iterate lineage. The
/// stack guard only sees the roots of the foreign lineage, so it would predict
/// the iterate on `x * x + q b`.
#[test]
fn frontier_iterate_guards_need_every_loop_exit_in_the_iterate_lineage() {
    let source = "grammar SplitGuard;
s : e EOF | 'between' e '+' 'q' 'z' ;
e : e '+' 'q' 'a' | e '*' e | e '+' 'q' 'b' | 'x' ;
";
    let accepts = split_operator_accepts("SplitGuard", source, 4);
    assert_eq!(accepts[2], Some(super::ESCAPE), "{accepts:?}");
}

/// The decisions inside a block get the budget options of the blocks around
/// them, and an inner block wins over an outer block. Only the budget option
/// names set a budget: `k` is not one of them.
#[test]
fn nested_blocks_inherit_the_budget_options_of_outer_blocks() {
    let source = "grammar Nested;
options { k = 2; }
s : ( options { max_k = 5; max_dfa_visits = 7000; } :
      ( options { max_k = 6; } : A B | A C ) D
    | E
    ) EOF ;
A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ;
";
    let (diagnostics, build) = build_source_with(
        "Nested",
        source,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    assert!(
        diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "G4S014"
                && diagnostic.message == "unsupported option k"),
        "{diagnostics:?}"
    );
    let limits: Vec<_> = rule_budgets(&build, "s")
        .iter()
        .map(|budget| (budget.max_k, budget.max_visits))
        .collect();
    assert_eq!(limits, [(Some(6), 7_000), (Some(5), 7_000)]);
}

/// A lexer grammar or a lexer rule has no parser decisions, so the budget
/// options are not supported there.
#[test]
fn lexer_grammars_do_not_support_budget_options() {
    let directory =
        std::env::temp_dir().join(format!("dbt-antlr-budget-lexer-{}", std::process::id()));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join("Words.g4");
    std::fs::write(
        &path,
        "lexer grammar Words;\noptions { max_k = 2; }\nA options { max_k = 3; } : 'a' | 'b' ;\n",
    )
    .expect("scratch grammar");
    let compilation = compile(LoadOptions {
        roots: vec![path],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let _ = std::fs::remove_dir_all(&directory);
    let unsupported = compilation
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.message == "unsupported option max_k")
        .count();
    assert_eq!(unsupported, 2, "{:?}", compilation.diagnostics);
}

/// The accepts of one alternative that have a single viable alternative share
/// one state, so they use one state of the state cap.
#[test]
fn single_alternative_accepts_share_one_state() {
    let source = "grammar Sinks;
s : a EOF ;
a : ( A B | C D | E F ) X | A G Y ;
A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; F : 'f' ; G : 'g' ; X : 'x' ; Y : 'y' ;
";
    let results = outcomes_of_source("Sinks", source);
    let decision = results
        .iter()
        .find(|result| result.table.is_some() && result.k == 2)
        .expect("the LL(2) decision of `a`");
    let table = decision.table.as_ref().expect("table");
    let accepts: Vec<_> = table
        .states
        .iter()
        .filter(|state| state.is_accept())
        .map(|state| state.accept)
        .collect();
    assert_eq!(accepts, [1, 2], "{table:?}");
    let first_alt = table
        .states
        .iter()
        .position(|state| state.accept == 1)
        .expect("an accept of alternative 1");
    let into_first_alt = table
        .states
        .iter()
        .flat_map(|state| &state.edges)
        .filter(|edge| edge.target == first_alt)
        .count();
    assert_eq!(into_first_alt, 3, "`a b`, `c`, and `e` lead to one state");
}

/// A predicated path and a path without a predicate can reach the same config
/// set. The shared accept state has its own config set, so neither path takes
/// the verdict of the other, in each order of the token types.
#[test]
fn shared_accept_states_do_not_absorb_predicated_paths() {
    for order in ["Y W X", "X Y W", "X W Y", "W Y X"] {
        let mut source = String::from(
            "grammar Order;\ns : a EOF ;\na : P ( Y | W Q | X {false}? ) B | P Z ;\nP : 'p' ;\n",
        );
        for token in order.split(' ') {
            source.push_str(&format!("{token} : '{}' ;\n", token.to_lowercase()));
        }
        source.push_str("Q : 'q' ; B : 'b' ; Z : 'z' ;\n");
        let results = resolve_static_only_source("Order", &source);
        let decision = results
            .iter()
            .find(|result| result.table.is_some() && result.k >= 2)
            .unwrap_or_else(|| panic!("{order}: the decision of `a`"));
        let table = decision.table.as_ref().expect("table");
        let token = |name: char| {
            2 + order
                .split(' ')
                .position(|token| token.starts_with(name))
                .expect("token") as i32
        };
        let after = |second: i32| accept_after(table, &[1, second]);
        assert_eq!(after(token('Y')), Some(1), "{order}: `p y` predicts 1");
        assert_eq!(after(token('W')), Some(1), "{order}: `p w` predicts 1");
        let x = table.states[0]
            .edges
            .iter()
            .find(|edge| edge.lo <= 1 && 1 <= edge.hi)
            .map(|edge| &table.states[edge.target])
            .and_then(|state| {
                state
                    .edges
                    .iter()
                    .find(|edge| edge.lo <= token('X') && token('X') <= edge.hi)
            })
            .map(|edge| &table.states[edge.target])
            .expect("an edge for `p x`");
        assert_eq!(
            x.resolution,
            Some(super::EscapeResolution::SyntaxError),
            "{order}: `p x` stops at the predicate"
        );
    }
}

/// Builds and resolves for `--static-dfa-only` the tables of a grammar written
/// to a scratch directory.
fn resolve_static_only_source(name: &str, source: &str) -> Vec<DecisionOutcome> {
    static SCRATCH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let scratch = SCRATCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let directory = std::env::temp_dir().join(format!(
        "dbt-antlr-static-only-{}-{scratch}-{name}",
        std::process::id()
    ));
    std::fs::create_dir_all(&directory).expect("scratch directory");
    let path = directory.join(format!("{name}.g4"));
    std::fs::write(&path, source).expect("scratch grammar");
    let results = resolve_static_only(&path);
    let _ = std::fs::remove_dir_all(&directory);
    results
}

/// Walks a table and its runtime minimization in lockstep from their start
/// states, and checks that the runtime cannot distinguish them.
fn assert_runtime_equivalent(table: &StaticDfaTable, minimized: &StaticDfaTable) {
    let outcome = |state: &StaticDfaState| {
        let accept = if state.accept == CONFLICT_ESCAPE && state.conflict_min_alt <= 0 {
            super::ESCAPE
        } else {
            state.accept
        };
        (
            accept,
            if accept == 0 { state.fallback } else { 0 },
            if accept == CONFLICT_ESCAPE {
                state.conflict_min_alt
            } else {
                0
            },
            state.guarded_alt,
            if state.resolution == Some(super::EscapeResolution::Guarded) {
                state.guard_defer_alt
            } else {
                0
            },
            state.guard_group,
            state
                .continuation
                .as_ref()
                .filter(|_| accept == super::ESCAPE)
                .map(|continuation| (continuation.contexts.clone(), continuation.configs.clone())),
        )
    };
    let target = |state: &StaticDfaState, token: i32| {
        state
            .edges
            .iter()
            .find(|edge| edge.lo <= token && token <= edge.hi)
            .map(|edge| edge.target)
    };
    let mut tokens: Vec<i32> = table
        .states
        .iter()
        .chain(&minimized.states)
        .flat_map(|state| &state.edges)
        .flat_map(|edge| [edge.lo - 1, edge.lo, edge.hi, edge.hi + 1])
        .collect();
    tokens.sort_unstable();
    tokens.dedup();
    let mut seen = std::collections::HashSet::new();
    let mut queue = std::collections::VecDeque::from([(0_usize, 0_usize)]);
    while let Some((left, right)) = queue.pop_front() {
        if !seen.insert((left, right)) {
            continue;
        }
        let (left_state, right_state) = (&table.states[left], &minimized.states[right]);
        assert_eq!(
            outcome(left_state),
            outcome(right_state),
            "states {left} and {right}"
        );
        if left_state.accept != 0 {
            continue;
        }
        for &token in &tokens {
            match (target(left_state, token), target(right_state, token)) {
                (Some(left), Some(right)) => queue.push_back((left, right)),
                (None, None) => {}
                pair => panic!("token {token} from {left}/{right}: {pair:?}"),
            }
        }
    }
}

/// The runtime table of a decision is its minimization, which the runtime
/// cannot distinguish from the built table. The image of the minimized tables
/// loads and validates.
#[test]
fn runtime_tables_are_minimized_and_equivalent() {
    let mut merged = 0;
    for (grammar, fallback) in [
        ("parser/FuzzExpr.g4", AtnFallback::Allowed),
        ("parser/LoopFrontier.g4", AtnFallback::Allowed),
        ("parser/GuardExpr.g4", AtnFallback::Forbidden),
        ("parser/InlineAlias.g4", AtnFallback::Forbidden),
    ] {
        let path = grammars_dir().join(grammar);
        let results = match fallback {
            AtnFallback::Allowed => outcomes(&path),
            AtnFallback::Forbidden => resolve_static_only(&path),
        };
        for result in &results {
            let tables = result.table.iter().chain(
                result
                    .precedence
                    .iter()
                    .flat_map(|precedence| precedence.tables.iter().flatten()),
            );
            for table in tables {
                let minimized = super::tables::minimized(table);
                assert!(minimized.states.len() <= table.states.len());
                merged += table.states.len() - minimized.states.len();
                assert_runtime_equivalent(table, &minimized);
            }
        }
        decoded_tables(&results);
    }
    assert!(merged > 0, "some states merge");
}

/// The alternative names of each decision of a grammar written to a scratch
/// directory, by rule, in decision order.
fn names_of(name: &str, source: &str) -> Vec<(String, Vec<String>)> {
    let (_, build) = build_source_with(
        name,
        source,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    build
        .report
        .decisions
        .iter()
        .map(|decision| (decision.rule.clone(), decision.alternatives.all().to_vec()))
        .collect()
}

/// Each decision names its alternatives by label, or by their first elements,
/// with the line where they start. Loops, optional elements, and optional
/// blocks name their implicit alternatives.
#[test]
fn decisions_name_their_alternatives() {
    let source = "grammar Names;
s : e (COMMA e)* COMMA? EOF ;
e : e STAR e     #mul
  | e PLUS e     #add
  | p            #prim
  ;
p : ID LP e RP OVER LP RP
  | ID LP e RP
  | ( ID | INT ) ( DOT ID )?
  ;
COMMA : ',' ; STAR : '*' ; PLUS : '+' ; ID : [a-z]+ ; INT : [0-9]+ ; LP : '(' ; RP : ')' ;
OVER : 'over' ; DOT : '.' ;
";
    let names = names_of("Names", source);
    let find = |rule: &str, first: &str| {
        names
            .iter()
            .find(|(owner, alternatives)| {
                owner == rule
                    && alternatives
                        .first()
                        .is_some_and(|name| name.starts_with(first))
            })
            .map_or_else(
                || panic!("no decision of {rule} starts with {first}: {names:?}"),
                |(_, alternatives)| alternatives.clone(),
            )
    };
    assert_eq!(
        find("s", "alt 1 (repeat"),
        ["alt 1 (repeat COMMA e, line 2)", "alt 2 (exit the loop)"]
    );
    assert_eq!(
        find("s", "alt 1 (COMMA,"),
        ["alt 1 (COMMA, line 2)", "alt 2 (skip)"]
    );
    assert_eq!(
        find("e", "alt 1 (#mul"),
        ["alt 1 (#mul, line 3)", "alt 2 (#add, line 4)"]
    );
    assert_eq!(
        find("p", "alt 1 (ID LP e ..."),
        [
            "alt 1 (ID LP e ..., line 7)",
            "alt 2 (ID LP e ..., line 8)",
            "alt 3 ((ID | INT) ( ... )?, line 9)",
        ]
    );
    assert_eq!(
        find("p", "alt 1 (DOT ID"),
        ["alt 1 (DOT ID, line 9)", "alt 2 (skip the block)"]
    );
    assert_eq!(
        find("e", "alt 1 (repeat ( #mul"),
        [
            "alt 1 (repeat ( #mul | #add ), line 3)",
            "alt 2 (exit the loop)"
        ]
    );
}

/// `--static-dfa-only` groups the resolved states of a decision by the chosen
/// and the dropped alternatives, over all precedence classes. The most harmful
/// groups come first, then the groups with the most states.
#[test]
fn static_only_groups_its_tie_breaks() {
    let mut results = resolve_static_only(&grammars_dir().join("parser").join("GuardExpr.g4"));
    results.extend(resolve_static_only(
        &grammars_dir().join("ReferenceToATN.g4"),
    ));
    results.extend(resolve_static_only(
        &grammars_dir().join("parser").join("LoopFrontier.g4"),
    ));
    for result in &results {
        let Some(resolved) = &result.static_only else {
            continue;
        };
        let grouped: usize = resolved.tie_breaks.iter().map(|group| group.states).sum();
        assert_eq!(grouped, resolved.min_alt + resolved.min_viable_alt);
        for pair in resolved.tie_breaks.windows(2) {
            assert!(
                (pair[0].level(), pair[0].states) >= (pair[1].level(), pair[1].states),
                "{:?}",
                resolved.tie_breaks
            );
            assert_ne!(
                (pair[0].chosen, &pair[0].dropped),
                (pair[1].chosen, &pair[1].dropped)
            );
        }
        for group in &resolved.tie_breaks {
            assert!(!group.dropped.is_empty());
            assert!(!group.dropped.contains(&group.chosen));
            assert!(group.dropped.iter().all(|alt| *alt > 0));
            assert!(group.witness.is_some());
        }
    }
    assert!(
        results.iter().any(|result| result
            .static_only
            .as_ref()
            .is_some_and(|resolved| !resolved.tie_breaks.is_empty())),
        "the grammars have tie-breaks"
    );
}

/// A non-greedy decision puts its exit or skip first, and its names follow.
#[test]
fn non_greedy_decisions_name_the_exit_first() {
    let source = "grammar Lazy;
s : ID*? INT ( ID ID | INT INT )?? EOF ;
ID : [a-z]+ ; INT : [0-9]+ ;
";
    let names = names_of("Lazy", source);
    let alternatives: Vec<_> = names.iter().map(|(_, names)| names.clone()).collect();
    assert!(
        alternatives.contains(&vec![
            "alt 1 (exit the loop)".to_owned(),
            "alt 2 (repeat ID, line 2)".to_owned(),
        ]),
        "{alternatives:?}"
    );
    assert!(
        alternatives.contains(&vec![
            "alt 1 (skip the block)".to_owned(),
            "alt 2 (ID ID, line 2)".to_owned(),
            "alt 3 (INT INT, line 2)".to_owned(),
        ]),
        "{alternatives:?}"
    );
}

const TIE_GRAMMAR: &str = "grammar Ties;
s : a EOF ;
a : X Y P | X Y Q | X Z P | X Z Q | W Y P | W Y Q | W Z P | W Z Q ;
X : 'x' ; Y : 'y' ; Z : 'z' ; W : 'w' ; P : 'p' ; Q : 'q' ;
";

/// A decision with more tie-break groups than a `G4S192` warning shows
/// orders them and counts the others.
#[test]
fn static_only_warnings_show_the_largest_tie_break_groups() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(8),
            max_k: Some(2),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with("Ties", TIE_GRAMMAR, AtnFallback::Forbidden, &budgets);
    let decision = &build.report.decisions[0];
    let resolved = decision.result.static_only.as_ref().expect("resolved");
    let groups: Vec<_> = resolved
        .tie_breaks
        .iter()
        .map(|group| (group.chosen, group.dropped.clone(), group.states))
        .collect();
    assert_eq!(
        groups,
        [
            (1, vec![2], 1),
            (3, vec![4], 1),
            (5, vec![6], 1),
            (7, vec![8], 1)
        ]
    );
    let message = &build
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "G4S192")
        .expect("a G4S192 warning")
        .message;
    assert!(
        message.contains(
            "tie-breaks: 1 state chooses alt 1 (X Y P, line 3) over alt 2 (X Y Q, line 3) \
             [prefix-hijack hazard: alt 2 (X Y Q, line 3) reads 'q' after 'x' 'y', and alt 1 \
             cannot]; 1 state chooses alt 3 (X Z P, line 3) over alt 4 (X Z Q, line 3) \
             [prefix-hijack hazard: alt 4 (X Z Q, line 3) reads 'q' after 'x' 'z', and alt 3 \
             cannot]; 1 state chooses alt 5 (W Y P, line 3) over alt 6 (W Y Q, line 3) \
             [prefix-hijack hazard: alt 6 (W Y Q, line 3) reads 'q' after 'w' 'y', and alt 5 \
             cannot]; and 1 more tie-break group"
        ),
        "{message}"
    );
}

/// With the adaptive fallback, a partial table is a normal table, and the
/// pass reports no `G4S190`. Without it, a decision without a table gets a
/// `G4S190` error with the reason.
#[test]
fn only_static_dfa_only_reports_decisions_without_a_static_prediction() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(12),
            max_k: Some(2),
            ..BudgetLimits::default()
        },
    };
    // The direct accept of `e` gives the partial table enough coverage.
    let source = TIE_GRAMMAR
        .replace("W Z Q ;", "W Z Q | E ;")
        .replace("Q : 'q' ;", "Q : 'q' ; E : 'e' ;");
    let (_, build) = build_source_with("Ties", &source, AtnFallback::Allowed, &budgets);
    assert!(
        build
            .report
            .decisions
            .iter()
            .any(|decision| decision.result.kind == DecisionKind::Hybrid
                && decision.result.escapes > 0),
        "{:?}",
        build.report.decisions
    );
    assert!(
        build
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.code != "G4S190"),
        "{:?}",
        build.diagnostics
    );

    let source = "grammar PredStart;\ns : r EOF ;\nr : {p()}? A | A B ;\nA : 'a' ; B : 'b' ;\n";
    let (_, build) = build_source_with(
        "PredStart",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let errors: Vec<_> = build
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.code == "G4S190")
        .map(|diagnostic| (diagnostic.severity, diagnostic.message.as_str()))
        .collect();
    assert_eq!(
        errors,
        [(
            Severity::Error,
            "parser decision 0 of rule 'r' is not fully static: the decision depends on \
             predicate 1:0, so the prediction is not input-only; --static-dfa-only requires a \
             static table for every decision"
        )]
    );
}

/// A non-greedy optional element names its skip first, and a list of names
/// in a diagnostic stops after four names.
#[test]
fn optional_elements_and_long_lists_have_short_names() {
    let source = "grammar Short;
s : A?? (B | C | D | E | F | G) EOF ;
A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; F : 'f' ; G : 'g' ;
";
    let (_, build) = build_source_with(
        "Short",
        source,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    let lazy = build
        .report
        .decisions
        .iter()
        .find(|decision| decision.alternatives.all().len() == 2)
        .expect("the decision of `A??`");
    assert_eq!(
        lazy.alternatives.all(),
        ["alt 1 (skip)", "alt 2 (A, line 2)"]
    );
    assert_eq!(
        lazy.alternatives.list(&[1, 2, 1, 2, 1, 2]),
        "alt 1 (skip), alt 2 (A, line 2), alt 1 (skip), alt 2 (A, line 2), \
         and 2 more alternatives"
    );
    assert_eq!(
        lazy.alternatives.list(&[1, 2, 1, 2, 1]),
        "alt 1 (skip), alt 2 (A, line 2), alt 1 (skip), alt 2 (A, line 2), \
         and 1 more alternative"
    );
}

/// The tie-break groups of the decisions of rule `rule` under
/// `--static-dfa-only` with the hybrid depth cap `max_k`.
fn hazards_of(name: &str, source: &str, rule: &str, max_k: usize) -> Vec<(i32, Vec<i32>, String)> {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_k: Some(max_k),
            max_states: Some(3),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with(name, source, AtnFallback::Forbidden, &budgets);
    build
        .report
        .decisions
        .iter()
        .filter(|decision| decision.rule == rule)
        .filter_map(|decision| decision.result.static_only.as_ref())
        .flat_map(|resolved| resolved.tie_breaks.iter())
        .map(|group| {
            let verdict = match &group.hazard {
                Some(hazard) => format!("{:?} {:?}", hazard.level, hazard.verdict),
                None => "none".to_owned(),
            };
            (group.chosen, group.dropped.clone(), verdict)
        })
        .collect()
}

const SUBQUERY_GRAMMAR: &str = "grammar Sub;
s : e EOF ;
e : LP q RP #sub | LP e (COMMA e)* RP #tuple | INT #lit ;
q : SELECT INT | LP q RP ;
LP : '(' ; RP : ')' ; COMMA : ',' ; SELECT : 'select' ; INT : [0-9]+ ;
";

/// A subquery before a tuple that starts with the same parentheses hijacks
/// the tuple: after `(`, the tuple reads `INT` and the subquery cannot.
#[test]
fn narrow_alternatives_before_broad_ones_are_prefix_hijacks() {
    assert_eq!(
        hazards_of("Sub", SUBQUERY_GRAMMAR, "e", 2),
        [(
            1,
            vec![2],
            "High Hijack { alt: 2, extension: [1, 5] }".to_owned()
        )]
    );
    let index = "grammar Index;
s : el EOF ;
el : identifier dtype #col | INDEX identifier TYPE identifier GRANULARITY INT #idx ;
identifier : ID | INDEX | TYPE ;
dtype : ID ;
INDEX : 'index' ; TYPE : 'type' ; GRANULARITY : 'granularity' ; INT : [0-9]+ ; ID : [a-z]+ ;
";
    assert_eq!(
        hazards_of("Index", index, "el", 2),
        [(
            1,
            vec![2],
            "High Hijack { alt: 2, extension: [1, 1] }".to_owned()
        )]
    );
}

/// A hijack of a greedy loop is only a medium hazard, and an exact ambiguity
/// is covered.
#[test]
fn greedy_choices_and_exact_ambiguities_rank_lower() {
    let comma = "grammar Comma;
s : list FROM id EOF ;
list : id (COMMA id)* COMMA? ;
id : ID | FROM ;
FROM : 'from' ; COMMA : ',' ; ID : [a-z]+ ;
";
    assert_eq!(
        hazards_of("Comma", comma, "list", 1),
        [(
            1,
            vec![2],
            "Medium Hijack { alt: 2, extension: [2, 1, 3] }".to_owned()
        )]
    );
    let ambiguous = "grammar Ambig;
s : a EOF ;
a : X Y Z | X Y Z ;
X : 'x' ; Y : 'y' ; Z : 'z' ;
";
    assert_eq!(
        hazards_of("Ambig", ambiguous, "a", 1),
        [(1, vec![2], "Low Covered".to_owned())]
    );
}

/// A `G4S192` warning shows the hazard of each tie-break group.
#[test]
fn static_only_warnings_show_the_hijack_hazards() {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_k: Some(2),
            max_states: Some(3),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with("Sub", SUBQUERY_GRAMMAR, AtnFallback::Forbidden, &budgets);
    let message = &build
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "G4S192")
        .expect("a G4S192 warning")
        .message;
    assert!(
        message.contains(
            "chooses alt 1 (#sub, line 3) over alt 2 (#tuple, line 3) [prefix-hijack hazard: \
             alt 2 (#tuple, line 3) reads INT after '(', and alt 1 cannot]"
        ),
        "{message}"
    );
}

const CALLERS_GRAMMAR: &str = "grammar Callers;
prog : stmt+ EOF ;
stmt : 'set' expr '=' expr ';'
     | 'let' expr '=' expr ';'
     | assign
     | update
     | expr ';'
     ;
assign : 'var' expr '=' expr ';' ;
update : 'put' expr '=' expr ';' ;
expr : value pred? ;
pred : '=' value ;
value : ID | '(' expr ')' ;
ID : [a-z]+ ;
WS : [ \\t\\n]+ -> skip ;
";

/// A `G4S192` warning names the callers of the invoking states where the
/// stack guard defers, and `--dump-dfas` shows the caller of each invoking
/// state of a danger set.
#[test]
fn guard_danger_sets_name_their_callers() {
    let (_, build) = build_source_with(
        "Callers",
        CALLERS_GRAMMAR,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let message = &build
        .diagnostics
        .iter()
        .find(|diagnostic| diagnostic.code == "G4S192")
        .expect("a G4S192 warning")
        .message;
    assert!(
        message.contains(
            "the stack guard defers (witness: '=' ID ';'; danger callers: stmt:3, stmt:4, \
             assign:9 and 1 more danger caller)"
        ),
        "{message}"
    );

    let (dump, diagnostics) = crate::optimization::StaticParserDfa::render_dfa_dump(
        std::slice::from_ref(&build.report),
        "expr",
    );
    assert!(diagnostics.is_empty(), "{diagnostics:?}");
    let danger = "danger=[22 (stmt:3), 28 (stmt:4), 41 (assign:9), 47 (update:10)]";
    assert!(dump.contains(&format!("group 0: {danger}\n")), "{dump}");
    assert!(
        dump.contains(&format!("guard root of group 0 ({danger})")),
        "{dump}"
    );
}

/// The most harmful tie-break group comes first, before a group with a lower
/// alternative.
#[test]
fn tie_breaks_rank_by_hazard() {
    let source = "grammar Rank;
s : a EOF ;
a : X Y Z | X Y Z | W Y P | W Y Q ;
X : 'x' ; Y : 'y' ; Z : 'z' ; W : 'w' ; P : 'p' ; Q : 'q' ;
";
    let groups: Vec<_> = hazards_of("Rank", source, "a", 2)
        .into_iter()
        .map(|(chosen, dropped, verdict)| {
            (
                chosen,
                dropped,
                verdict.split(' ').next().map(str::to_owned),
            )
        })
        .collect();
    assert_eq!(
        groups,
        [
            (3, vec![4], Some("High".to_owned())),
            (1, vec![2], Some("Low".to_owned())),
        ]
    );
}

/// A dropped path that pops a widened rule continues where the runtime stack
/// cannot, so it is no hijack evidence.
#[test]
fn widened_paths_are_no_hijack_evidence() {
    let source = "grammar Widened;
s : target EOF ;
target : A LP expr RP X | A parens X ;
expr : LP expr RP | ID ;
parens : LP parens RP | ID ;
A : 'a' ; LP : '(' ; RP : ')' ; X : 'x' ; ID : [a-z]+ ;
";
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(4),
            max_k: Some(2),
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with("Widened", source, AtnFallback::Forbidden, &budgets);
    let groups: Vec<_> = build
        .report
        .decisions
        .iter()
        .filter_map(|decision| decision.result.static_only.as_ref())
        .flat_map(|resolved| &resolved.tie_breaks)
        .collect();
    assert!(!groups.is_empty());
    assert!(
        groups
            .iter()
            .all(|group| group.level() != super::HazardLevel::High),
        "{groups:?}"
    );
}

/// A group with states that the analysis did not reach is not covered.
#[test]
fn partially_analyzed_groups_are_not_covered() {
    let source = "grammar Partial;
s : r EOF ;
r : (A X Y W | B X Y W | C X Y W | D X Y W | P X Q) #one
  | (A X Y W | B X Y W | C X Y W | D X Y W | P X Z) #two
  ;
A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; P : 'p' ; Q : 'q' ; W : 'w' ; X : 'x' ; Y : 'y' ;
Z : 'z' ;
";
    for states in [9, 12] {
        let budgets = ParserDfaBudgets {
            global: BudgetLimits {
                max_states: Some(states),
                ..BudgetLimits::default()
            },
        };
        let (_, build) = build_source_with("Partial", source, AtnFallback::Forbidden, &budgets);
        let groups: Vec<_> = build
            .report
            .decisions
            .iter()
            .filter_map(|decision| decision.result.static_only.as_ref())
            .flat_map(|resolved| &resolved.tie_breaks)
            .collect();
        assert!(!groups.is_empty());
        for group in groups {
            let hazard = group.hazard.as_ref().expect("analyzed");
            assert_ne!(
                hazard.verdict,
                super::HijackVerdict::Covered,
                "{states}: {group:?}"
            );
        }
    }
}

/// A chosen path that reads a token in an assumed caller does not cover a
/// dropped path, and neither does a chosen path across a predicate.
#[test]
fn unsure_chosen_paths_do_not_cover() {
    for (name, source) in [
        (
            "Boundary",
            "grammar Boundary;
s : r EOF ;
r : A | (X r | A) B ;
A : 'a' ; B : 'b' ; X : 'x' ;
",
        ),
        (
            "PredChosen",
            "grammar PredChosen;
s : r EOF ;
r : A X {false}? B | A X B ;
A : 'a' ; B : 'b' ; X : 'x' ;
",
        ),
    ] {
        let groups = hazards_of(name, source, "r", 1);
        assert!(!groups.is_empty(), "{name}");
        for (_, _, verdict) in groups {
            assert!(!verdict.contains("Covered"), "{name}: {verdict}");
        }
    }
}

/// The danger set and the stack-hijack verdict of each guard group of the
/// decisions of `rule`, under `--static-dfa-only` with the lookahead budget
/// `max_k`, and the build.
fn guard_hazards_of(
    name: &str,
    source: &str,
    rule: &str,
    max_k: Option<usize>,
) -> (
    Vec<(Vec<i32>, String)>,
    crate::optimization::static_parser_dfa::StaticParserDfaArtifact,
) {
    let budgets = ParserDfaBudgets {
        global: BudgetLimits {
            max_k,
            ..BudgetLimits::default()
        },
    };
    let (_, build) = build_source_with(name, source, AtnFallback::Forbidden, &budgets);
    let groups = build
        .report
        .decisions
        .iter()
        .filter(|decision| decision.rule == rule)
        .filter_map(|decision| decision.result.static_only.as_ref())
        .flat_map(|resolved| resolved.guard_groups.iter())
        .map(|group| (group.danger.clone(), format!("{:?}", group.hazard)))
        .collect();
    (groups, build)
}

/// The `G4S192` warning of the decisions of `rule`.
fn static_only_warning(
    build: &crate::optimization::static_parser_dfa::StaticParserDfaArtifact,
    rule: &str,
) -> String {
    build
        .diagnostics
        .iter()
        .find(|diagnostic| {
            diagnostic.code == "G4S192" && diagnostic.message.contains(&format!("of rule '{rule}'"))
        })
        .map_or_else(
            || panic!("a G4S192 warning for '{rule}': {:?}", build.diagnostics),
            |diagnostic| diagnostic.message.clone(),
        )
}

const SETTINGS_GRAMMAR: &str = "grammar Settings;
command : query settings? ';' ;
query : select ('UNION' 'ALL' select)* ;
select : 'SELECT' expr settings? ;
settings : 'SETTINGS' ID '=' INT (',' ID '=' INT)* ;
expr : ID | INT ;
ID : [a-z]+ ; INT : [0-9]+ ; WS : [ ]+ -> skip ;
";

/// `command` reads `SETTINGS` after its query too, so the guard of the
/// `settings?` of `select` defers when `command` is on the parse stack. The
/// call of `query` from `command` is an outer wrapper of `select`: inside
/// it, the take of `SETTINGS a = 1` reads `UNION` next, and the skip cannot.
/// A lookahead budget that reaches the `;` of the statement shows that the
/// guard only defers on input where the skip is right.
#[test]
fn outer_wrapper_guards_are_stack_hijacks() {
    let (groups, build) = guard_hazards_of("Settings", SETTINGS_GRAMMAR, "select", Some(4));
    let [(danger, verdict)] = groups.as_slice() else {
        panic!("one guard group: {groups:?}");
    };
    assert_eq!(danger.len(), 1, "{groups:?}");
    let caller = danger[0];
    assert_eq!(
        *verdict,
        format!("Some(Hijack {{ caller: {caller}, extension: [5, 8, 6, 9, 2] }})")
    );
    let warning = static_only_warning(&build, "select");
    assert!(
        warning.ends_with(
            "(witness: 'SETTINGS' ID '=' INT; danger caller: command:2) [stack-hijack hazard: \
             when called from 'command' (line 2), defers 'SETTINGS' ID '=' INT even when \
             followed by 'UNION']"
        ),
        "{warning}"
    );
    let (dump, diagnostics) = crate::optimization::StaticParserDfa::render_dfa_dump(
        std::slice::from_ref(&build.report),
        "select",
    );
    assert!(diagnostics.is_empty(), "{diagnostics:?}");
    assert!(
        dump.contains(&format!(
            "group 0: danger=[{caller} (command:2)] [stack-hijack hazard: when called from \
             'command' (line 2), defers 'SETTINGS' ID '=' INT even when followed by 'UNION']\n"
        )),
        "{dump}"
    );

    let (groups, build) = guard_hazards_of("Settings", SETTINGS_GRAMMAR, "select", Some(8));
    assert_eq!(groups, [(danger.clone(), "Some(Covered)".to_owned())]);
    let warning = static_only_warning(&build, "select");
    assert!(warning.ends_with(" [benign stack guard]"), "{warning}");
    let (dump, _) = crate::optimization::StaticParserDfa::render_dfa_dump(
        std::slice::from_ref(&build.report),
        "select",
    );
    assert!(
        dump.contains(&format!("group 0: danger=[{caller} (command:2)]\n")),
        "a benign group has no note: {dump}"
    );
}

/// The shapes of `CAST(INTERVAL '1' DAY + 1 AS String)`: `DAY` is a unit of
/// the interval and an alias of the column. In `add`, the guard of `unit?`
/// defers when `column` is on the stack. The take reads `+` after
/// `DAY + 1` inside the call of `column`, and the skip cannot. A left
/// recursive `expr` without the pass frame of `add` has the same hazard.
#[test]
fn interval_units_are_stack_hijacks() {
    let rules = [
        (
            "unary",
            "column : add alias? ;
add : unary ('+' unary)* ;
unary : 'INTERVAL' STR unit? | 'CAST' '(' column 'AS' ID ')' | ID | INT ;",
        ),
        (
            "expr",
            "column : expr alias? ;
expr : expr '+' expr | 'INTERVAL' STR unit? | 'CAST' '(' column 'AS' ID ')' | ID | INT ;",
        ),
    ];
    for (rule, rules) in rules {
        let source = format!(
            "grammar Interval;
stmt : 'SELECT' column ('+' INT)? EOF ;
{rules}
unit : 'DAY' | 'HOUR' ;
alias : ID | 'DAY' ;
ID : [a-z]+ ; INT : [0-9]+ ; STR : '\\'' [0-9]+ '\\'' ; WS : [ ]+ -> skip ;
"
        );
        let (groups, build) = guard_hazards_of("Interval", &source, rule, Some(3));
        assert!(
            groups
                .iter()
                .any(|(_, verdict)| verdict.contains("extension: [8, 2, 11, 2]")),
            "{rule}: {groups:?}"
        );
        let warning = static_only_warning(&build, rule);
        assert!(
            warning.contains(
                "[stack-hijack hazard: when called from 'column' (line 3), defers 'DAY' '+' INT \
                 even when followed by '+']"
            ),
            "{rule}: {warning}"
        );
        if rule == "expr" {
            // The iterate of `expr '+' expr` has a guard too: `stmt` reads
            // `+ INT` after the column. The call of `column` from `stmt` is
            // the danger caller, and the iterate pops it after one operand.
            assert!(
                groups.iter().any(|(_, verdict)| verdict == "Some(Covered)"),
                "{groups:?}"
            );
        }
    }
}

/// When the danger caller calls the decision rule directly, as in
/// `CALLERS_GRAMMAR`, the guarded alternative pops the call of the caller
/// right after the optional clause. The skip reads the same continuations
/// there, so the guard is benign.
#[test]
fn direct_danger_callers_are_benign_guards() {
    let (groups, build) = guard_hazards_of("Callers", CALLERS_GRAMMAR, "expr", None);
    assert!(!groups.is_empty());
    for (danger, verdict) in &groups {
        assert_eq!(verdict, "Some(Covered)", "{danger:?}");
    }
    let warning = static_only_warning(&build, "expr");
    assert!(warning.ends_with(" [benign stack guard]"), "{warning}");
}

#[test]
fn reexpansion_respects_state_cap_and_prunes_unreachable_states_on_visit_cutoff() {
    let source = "grammar ReexpandBudget;\n\
                  top : ( r | r1 )? q X | r? q Y ;\n\
                  r : '(' r ')' | B ;\n\
                  r1 : '(' r1 ')' | B Z ;\n\
                  q : K ( M1 M2 | N1 N2 ) ;\n\
                  B : 'b' ; K : 'k' ; M1 : 'm1' ; M2 : 'm2' ; N1 : 'n1' ; N2 : 'n2' ; X : 'x' ; Y : 'y' ; Z : 'z' ;\n";
    let build_with = |budgets: &ParserDfaBudgets| {
        build_source_with("ReexpandBudget", source, AtnFallback::Allowed, budgets).1
    };

    let full = build_with(&ParserDfaBudgets::default());
    let decision = full
        .report
        .decisions
        .iter()
        .rposition(|entry| entry.rule == "top" && entry.result.table.is_some())
        .expect("top decision has a table");
    let full_outcome = &full.report.decisions[decision].result;
    let full_table = full_outcome.table.as_ref().expect("full table");
    let exact_states = full_table.states.len();
    assert_eq!(full_outcome.budget_cutoff, None);
    assert!(full_table.depths().iter().all(|&depth| depth != usize::MAX));

    let capped = build_with(&ParserDfaBudgets {
        global: BudgetLimits {
            max_states: Some(exact_states + 1),
            max_k: None,
            max_visits: None,
        },
    });
    let capped_outcome = &capped.report.decisions[decision].result;
    let capped_table = capped_outcome.table.as_ref().expect("capped table");
    assert_eq!(capped_outcome.budget_cutoff, None);
    assert_eq!(capped_table.states.len(), exact_states);
    assert!(
        capped_table
            .depths()
            .iter()
            .all(|&depth| depth != usize::MAX)
    );

    let mut saw_pruned = false;
    for visits in 1..full_outcome.cost.visits() {
        let limited = build_with(&ParserDfaBudgets {
            global: BudgetLimits {
                max_states: None,
                max_k: None,
                max_visits: Some(visits),
            },
        });
        let outcome = &limited.report.decisions[decision].result;
        if let Some(table) = &outcome.table {
            assert_eq!(outcome.num_dfa_states, table.states.len());
            assert!(
                table.depths().iter().all(|&depth| depth != usize::MAX),
                "visits={visits} emitted unreachable state(s): {:#?}",
                table.states
            );
            if outcome.budget_cutoff == Some(BudgetCutoff::Visits)
                && table.states.len() < exact_states
            {
                saw_pruned = true;
            }
        }
    }
    assert!(
        saw_pruned,
        "visit-budget sweep should exercise post-cutoff pruning"
    );
}

#[test]
fn state_budget_cutoff_without_escape_widens_to_static() {
    let source = "grammar WidenStatic;\n\
                  options { max_dfa_states = 8; }\n\
                  top : r1 | r2 ;\n\
                  r1 : '(' r1 ')' | A X ;\n\
                  r2 : '(' r2 ')' | A Y ;\n\
                  A : 'a' ; X : 'x' ; Y : 'y' ;\n";
    for (atn_fallback, first_attempt) in [
        (AtnFallback::Allowed, AttemptKind::Default),
        (AtnFallback::Forbidden, AttemptKind::StaticOnly),
    ] {
        let (_, build) = build_source_with(
            "WidenStatic",
            source,
            atn_fallback,
            &ParserDfaBudgets::default(),
        );
        let decision = build
            .report
            .decisions
            .iter()
            .find(|entry| entry.rule == "top")
            .expect("top decision");
        assert_eq!(
            decision.result.kind,
            DecisionKind::Static,
            "{atn_fallback:?}"
        );
        assert_eq!(decision.result.escapes, 0, "{atn_fallback:?}");
        assert_eq!(decision.result.guarded_states(), 0, "{atn_fallback:?}");
        assert_eq!(
            decision
                .result
                .cost
                .attempts
                .iter()
                .map(|attempt| attempt.kind)
                .collect::<Vec<_>>(),
            [first_attempt, AttemptKind::Widened],
            "{atn_fallback:?}"
        );
    }
}

#[test]
fn budget_cutoff_after_non_budget_escape_skips_widening() {
    let source = "grammar EscapeBeforeCutoff;\n\
                  options { max_dfa_states = 8; }\n\
                  top : A {true}? B | A C | D E1 E2 E3 ( F1 | F2 ) X | D E1 E2 E3 ( F1 | F2 ) Y ;\n\
                  A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ;\n\
                  E1 : 'e1' ; E2 : 'e2' ; E3 : 'e3' ; F1 : 'f1' ; F2 : 'f2' ;\n\
                  X : 'x' ; Y : 'y' ;\n";
    let (_, build) = build_source_with(
        "EscapeBeforeCutoff",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let decision = &build.report.decisions[0].result;
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert_eq!(decision.budget_cutoff, Some(BudgetCutoff::States));
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [AttemptKind::StaticOnly]
    );
}

#[test]
fn widened_false_conflict_keeps_default_partial_table() {
    let path = grammars_dir().join("parser").join("WidenedTrust.g4");
    let compilation = compile(LoadOptions {
        roots: vec![path],
        library_directories: Vec::new(),
    })
    .expect("grammar compiles");
    let parser = compilation
        .parser(compilation.roots[0].parser.expect("parser root"))
        .expect("parser artifact");
    let budgets = vec![
        super::DecisionBudget::default(),
        super::DecisionBudget {
            max_states: 50,
            explicit_max_states: true,
            ..super::DecisionBudget::default()
        },
    ];
    let results = builder(parser)
        .with_atn_fallback(AtnFallback::Forbidden)
        .with_budgets(budgets)
        .build_all();
    let decision = &results[1];
    assert_eq!(
        attempts_of(&results, 1),
        [AttemptKind::StaticOnly, AttemptKind::Widened]
    );
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    let table = decision.table.as_ref().expect("partial table kept");
    assert!(
        table.states.iter().all(|state| state.conflicts.is_empty()),
        "widened false conflict must not replace default table"
    );
}

#[test]
fn frontier_bounds_late_escapes_and_conflict_free_static_only_cutoffs() {
    let late_default = "grammar LateDefault;\n\
                        top : A B C D E F {true}? G X | A B C D E F G Y | Z ;\n\
                        A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; F : 'f' ;\n\
                        G : 'g' ; X : 'x' ; Y : 'y' ; Z : 'z' ;\n";
    let (_, build) = build_source_with(
        "LateDefault",
        late_default,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    let decision = &build.report.decisions[0].result;
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert!(decision.k <= PARTIAL_DEPTH_CAP as i32);
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [AttemptKind::Default, AttemptKind::Default]
    );

    let late_static_only = "grammar LateStaticOnly;\n\
                            top : T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15 T16 T17 T18 {true}? A X\n\
                                | T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15 T16 T17 T18 A Y ;\n\
                            T1 : 't1' ; T2 : 't2' ; T3 : 't3' ; T4 : 't4' ; T5 : 't5' ; T6 : 't6' ;\n\
                            T7 : 't7' ; T8 : 't8' ; T9 : 't9' ; T10 : 't10' ; T11 : 't11' ; T12 : 't12' ;\n\
                            T13 : 't13' ; T14 : 't14' ; T15 : 't15' ; T16 : 't16' ; T17 : 't17' ; T18 : 't18' ;\n\
                            A : 'a' ; X : 'x' ; Y : 'y' ;\n";
    let (_, build) = build_source_with(
        "LateStaticOnly",
        late_static_only,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let decision = &build.report.decisions[0].result;
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert!(decision.k <= STATIC_ONLY_DEPTH_CAP as i32);
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [AttemptKind::StaticOnly, AttemptKind::StaticOnly]
    );

    let deep_static_cutoff = "grammar DeepStaticOnlyCutoff;\n\
                              options { max_dfa_states = 18; }\n\
                              top : P P P P P P P P P P P P P P P P P P P P A X\n\
                                  | P P P P P P P P P P P P P P P P P P P P A Y ;\n\
                              A : 'a' ; P : 'p' ; X : 'x' ; Y : 'y' ;\n";
    let (_, build) = build_source_with(
        "DeepStaticOnlyCutoff",
        deep_static_cutoff,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let decision = &build.report.decisions[0].result;
    assert_eq!(decision.kind, DecisionKind::Hybrid);
    assert!(decision.k <= STATIC_ONLY_DEPTH_CAP as i32);
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [
            AttemptKind::StaticOnly,
            AttemptKind::Widened,
            AttemptKind::StaticOnly,
        ]
    );
}

#[test]
fn start_exhausted_widened_exceeding_frontier_retries_bounded_with_hazards() {
    let source = "grammar StartExhaustedBounded;\n\
                  options { max_dfa_visits = 350; }\n\
                  entry : top 'u' | top 'v' ;\n\
                  top : H P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 P15 P16 P17 P18 tail\n\
                      | H P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13 P14 P15 P16 P17 P18 tail\n\
                      | a0 'z' ;\n\
                  a0 : c0 ; tail : 'a' ;\n\
                  c0 : c1 | c2 ; c1 : c3 | c4 ; c2 : c3 | c4 ;\n\
                  c3 : c5 | c6 ; c4 : c5 | c6 ; c5 : c7 | c8 ; c6 : c7 | c8 ;\n\
                  c7 : c9 | c10 ; c8 : c9 | c10 ; c9 : c11 | c12 ; c10 : c11 | c12 ;\n\
                  c11 : c13 | c14 ; c12 : c13 | c14 ; c13 : 'f' ; c14 : 'g' ;\n\
                  H : 'h' ;\n\
                  P1 : 'p1' ; P2 : 'p2' ; P3 : 'p3' ; P4 : 'p4' ; P5 : 'p5' ; P6 : 'p6' ;\n\
                  P7 : 'p7' ; P8 : 'p8' ; P9 : 'p9' ; P10 : 'p10' ; P11 : 'p11' ; P12 : 'p12' ;\n\
                  P13 : 'p13' ; P14 : 'p14' ; P15 : 'p15' ; P16 : 'p16' ; P17 : 'p17' ; P18 : 'p18' ;\n";
    let (_, build) = build_source_with(
        "StartExhaustedBounded",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let decision = &build
        .report
        .decisions
        .iter()
        .find(|entry| entry.rule == "top")
        .expect("top decision")
        .result;
    assert_eq!(decision.kind, DecisionKind::Hybrid, "{decision:#?}");
    assert!(decision.k <= STATIC_ONLY_DEPTH_CAP as i32);
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [
            AttemptKind::StaticOnly,
            AttemptKind::Widened,
            AttemptKind::Widened,
        ],
        "{decision:#?}"
    );
    let resolved = decision.static_only.as_ref().expect("resolved");
    assert!(
        resolved
            .tie_breaks
            .iter()
            .any(|group| group.hazard.is_some()),
        "bounded widened retry must run hazard analysis: {resolved:?}"
    );
}

#[test]
fn guarded_zero_escape_table_past_frontier_stays_static_without_truncating() {
    let source = "grammar GuardedPastFrontier;\n\
                  prog : stmt+ EOF ;\n\
                  stmt : 'set' expr K1 K2 K3 K4 '=' expr ';' | expr ';' ;\n\
                  expr : value postfix? ;\n\
                  postfix : K1 K2 K3 K4 '=' value ;\n\
                  value : ID ;\n\
                  K1 : 'k1' ; K2 : 'k2' ; K3 : 'k3' ; K4 : 'k4' ; ID : 'id' ;\n";
    for (atn_fallback, expected_attempt) in [
        (AtnFallback::Allowed, AttemptKind::Default),
        (AtnFallback::Forbidden, AttemptKind::StaticOnly),
    ] {
        let (_, build) = build_source_with(
            "GuardedPastFrontier",
            source,
            atn_fallback,
            &ParserDfaBudgets::default(),
        );
        let decision = build
            .report
            .decisions
            .iter()
            .find(|entry| entry.rule == "expr")
            .expect("expr decision");
        assert_eq!(
            decision.result.kind,
            DecisionKind::Static,
            "{atn_fallback:?}"
        );
        assert_eq!(decision.result.escapes, 0, "{atn_fallback:?}");
        assert!(decision.result.guarded_states() > 0, "{atn_fallback:?}");
        assert!(
            decision.result.k > PARTIAL_DEPTH_CAP as i32,
            "{atn_fallback:?}"
        );
        assert_eq!(
            decision
                .result
                .cost
                .attempts
                .iter()
                .map(|attempt| attempt.kind)
                .collect::<Vec<_>>(),
            [expected_attempt],
            "{atn_fallback:?}"
        );
        if atn_fallback == AtnFallback::Forbidden {
            let resolved = decision.result.static_only.as_ref().expect("resolved");
            assert!(resolved.guarded > 0);
            assert!(
                resolved
                    .guard_groups
                    .iter()
                    .any(|group| group.hazard.is_some()),
                "guard hazard analysis must run"
            );
        }
    }
}

#[test]
fn low_coverage_past_frontier_skips_redundant_bounded_retry() {
    let source = "grammar LowCoverageLateEscape;\n\
                  top : head A B C D E {true}? F X\n\
                      | head A B C D E F Y\n\
                      | T12 ;\n\
                  head : T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10 | T11 ;\n\
                  T1 : 't1' ; T2 : 't2' ; T3 : 't3' ; T4 : 't4' ;\n\
                  T5 : 't5' ; T6 : 't6' ; T7 : 't7' ; T8 : 't8' ;\n\
                  T9 : 't9' ; T10 : 't10' ; T11 : 't11' ; T12 : 't12' ;\n\
                  A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; E : 'e' ; F : 'f' ;\n\
                  X : 'x' ; Y : 'y' ;\n";
    let (_, build) = build_source_with(
        "LowCoverageLateEscape",
        source,
        AtnFallback::Allowed,
        &ParserDfaBudgets::default(),
    );
    let decision = &build.report.decisions[0].result;
    assert!(matches!(
        decision.no_table,
        Some(NoTableReason::LowCoverage { .. })
    ));
    assert_eq!(
        decision
            .cost
            .attempts
            .iter()
            .map(|attempt| attempt.kind)
            .collect::<Vec<_>>(),
        [AttemptKind::Default]
    );
}

#[test]
fn smaller_config_sets_expand_first_at_equal_depth() {
    let source = "grammar CheapFirst;\n\
                  options { max_dfa_visits = 90; }\n\
                  top : ( '-' 's' | '-' 'n' | 'a' big 'x' | 'a' big 'y' ) ;\n\
                  big : c0 ;\n\
                  c0 : c1 | c2 ; c1 : c3 | c4 ; c2 : c3 | c4 ;\n\
                  c3 : c5 | c6 ; c4 : c5 | c6 ; c5 : 'p' | 'q' ; c6 : 'r' | 't' ;\n";
    let (_, build) = build_source_with(
        "CheapFirst",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let token = |name: &str| {
        build
            .report
            .vocabulary
            .iter()
            .position(|display| display == name)
            .map(|index| index as i32 + 1)
            .expect("token in vocabulary")
    };
    let decision = build
        .report
        .decisions
        .iter()
        .find(|entry| entry.rule == "top")
        .expect("top decision");
    let table = decision.result.table.as_ref().expect("table");
    assert_eq!(accept_after(table, &[token("'-'"), token("'s'")]), Some(1));
    assert_eq!(accept_after(table, &[token("'-'"), token("'n'")]), Some(2));
}

#[test]
fn depth1_visit_slice_prevents_expensive_prefix_from_starving_siblings() {
    let source = "grammar Depth1Slice;\n\
                  options { max_dfa_visits = 90; }\n\
                  top : ( 'a' 'p' big 'x' | 'a' 'p' big 'y' | 'b' 'p' | 'b' 'q' | 'b' 'r' ) ;\n\
                  big : r0 ;\n\
                  r0 : r1 | r2 ; r1 : r3 | r4 ; r2 : r5 | r6 ;\n\
                  r3 : r7 | r8 ; r4 : r9 | r10 ; r5 : r11 | r12 ; r6 : r13 | r14 ;\n\
                  r7 : 'k' ; r8 : 'k' ; r9 : 'k' ; r10 : 'k' ;\n\
                  r11 : 'k' ; r12 : 'k' ; r13 : 'k' ; r14 : 'k' ;\n";
    let (_, build) = build_source_with(
        "Depth1Slice",
        source,
        AtnFallback::Forbidden,
        &ParserDfaBudgets::default(),
    );
    let token = |name: &str| {
        build
            .report
            .vocabulary
            .iter()
            .position(|display| display == name)
            .map(|index| index as i32 + 1)
            .expect("token in vocabulary")
    };
    let decision = build
        .report
        .decisions
        .iter()
        .find(|entry| entry.rule == "top")
        .expect("top decision");
    assert_eq!(decision.result.budget_cutoff, Some(BudgetCutoff::Visits));
    let table = decision.result.table.as_ref().expect("table");
    assert_eq!(accept_after(table, &[token("'b'"), token("'p'")]), Some(3));
    assert_eq!(accept_after(table, &[token("'b'"), token("'q'")]), Some(4));
    assert_eq!(accept_after(table, &[token("'b'"), token("'r'")]), Some(5));
}