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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! The SLL DFA classifier: subset construction, budgets, and trust rules.
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::num::NonZeroUsize;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use dbt_antlr_runtime::analysis::DFA;
use dbt_antlr_runtime::analysis::{
ATN, ATNConfigSet, ATNStateRef, ATNStateType, Arena, BOUNDARY_TAINT, BitSet, Bump, DFAState,
EOF, FOREIGN_CONSUME_TAINT, FOREIGN_LINEAGE_TAINT, IATNSimulator, INTERIOR_TAINT, MIDWAY_TAINT,
PRECPRED_TAINT, PRED_TAINT, ParserATNSimulator, ParserATNSimulatorManager,
PrecedencePredicateTransition, PredictionContext, PredictionContextRef, PredictionMode,
ProposedDFAState, ROOTED_TAINT, RuleStartState, WIDENED_TAINT, all_subsets_conflict,
all_subsets_equal, conflicting_alt_subsets, get_alts, has_sll_conflict_terminating_prediction,
};
use dbt_antlr_runtime::dfa::static_parser_dfa::{
ContinuationConfigEntry, ContinuationContextNode, ParserContinuation,
};
use super::closure::{
CallSites, ClosedSet, Closure, ClosureFacts, GuardRoots, PrecedenceClass, Taint, taint_of,
};
use super::cost::{AttemptCost, AttemptKind, AttemptOutcome, CostLog, DecisionCost};
use super::descent::{DescentAnalyzer, DescentPlan, DescentRules};
use super::hazard::{self, StackHijackVerdict, StateHazard};
use super::loop_block::{
EXIT_ALT, EXIT_FOREIGN, ITERATE_ALT, ITERATE_REAL, LoopBlock, is_iterate_exit_pair,
};
use super::postfix::{GuardRegions, PostfixShape, epsilon_closure};
use super::table::{StaticDfaEdge, StaticDfaState, StaticDfaTable};
use super::{CONFLICT_ESCAPE, Category, DecisionBudget, ESCAPE, EscapeResolutions, GUARDED};
use crate::optimization::AtnFallback;
/// Depth at which a hybrid table stops expanding and escapes.
pub(crate) const HYBRID_DEPTH_CAP: usize = 4;
/// State count at which a hybrid table stops expanding beyond depth 2.
pub(crate) const HYBRID_STATE_CAP: usize = 64;
/// [`HYBRID_DEPTH_CAP`] under `--static-dfa-only`. Without the adaptive
/// fallback, a frontier state can only guess, so the table looks further. Under
/// `--static-dfa-only`, the hybrid state cap is the state cap of the decision.
pub(crate) const STATIC_ONLY_HYBRID_DEPTH_CAP: usize = 16;
/// Below this share of useful start edges a hybrid table is not emitted,
/// unless `--static-dfa-only` removes the adaptive fallback.
pub(crate) const HYBRID_MIN_COVERAGE_PERCENT: u32 = 10;
/// Largest continuation a hybrid table emits, counted in wire words.
///
/// A continuation saves the `k` steps of a Stage 1 restart, but replaying its
/// config set costs a closure over that set, and storing it costs
/// `continuation_words` words of the emitted table. Both grow with the set, so
/// only small frontier sets are worth serializing: on `CPP14.g4` the median
/// continuation is 112 words and the pool is 61% of the whole section, while
/// the measured runtime difference is a fraction of a percent. 64 words is the
/// largest continuation that still beats a restart on our corpora
/// (`FuzzExpr.g4`'s `item` frontier).
pub(crate) const MAX_CONTINUATION_WORDS: usize = 64;
/// Maximum number of threads that classify the decisions of one parser.
///
/// One build attempt can use several hundred megabytes of scratch memory, and
/// each thread can run an attempt at the same time. On our SQL benchmark
/// grammars, 16 threads give most of the speedup at less than half the memory
/// of 60 threads. The slowest decisions set the wall time.
const MAX_CLASSIFY_THREADS: usize = 16;
/// The escape states of one table that the prefix-hijack analysis analyzes
/// at most, the shallowest first.
const HAZARD_STATES: usize = 48;
/// The escape states of one tie-break group that the prefix-hijack analysis
/// analyzes at most. The analysis of a group stops at its first hijack.
const HAZARD_STATES_PER_GROUP: usize = 4;
/// The guarded states of one table whose stack-hijack hazard the classifier
/// analyzes at most.
const GUARD_HAZARD_STATES: usize = 48;
/// The analyzed guarded states of one guard group at most.
const GUARD_HAZARD_STATES_PER_GROUP: usize = 8;
/// Taint bits that invalidate a trusted verdict when a second path adds them
/// to an already interned state. A decision state that gets one of them is
/// expanded again, so its successors get the bit too.
const TRUST_TAINT: i32 = WIDENED_TAINT
| PRECPRED_TAINT
| BOUNDARY_TAINT
| FOREIGN_CONSUME_TAINT
| FOREIGN_LINEAGE_TAINT
| MIDWAY_TAINT
| ROOTED_TAINT
| INTERIOR_TAINT;
/// The alternative of an optional-postfix decision that takes the postfix
/// element.
const POSTFIX_TAKE_ALT: i32 = 1;
/// The alternative of an optional-postfix decision that skips it.
const POSTFIX_SKIP_ALT: i32 = 2;
/// Whether a set of live alternatives is exactly the take/skip pair of an
/// optional-postfix decision.
fn is_take_skip_pair(alts: &BitSet) -> bool {
alts.len() == 2
&& alts.contains(POSTFIX_TAKE_ALT as usize)
&& alts.contains(POSTFIX_SKIP_ALT as usize)
}
use dbt_antlr_runtime::dfa::static_parser_dfa::VIRTUAL_ALT_BASE;
const MAX_TRACKED_DEPTH: usize = 30;
const VARIABLE_DEPTH: usize = 31;
/// The verdict of one DFA state.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Verdict {
/// The state predicts this alternative.
Accept(i32),
/// The state escapes to the adaptive simulation, with the table marker it
/// carries ([`ESCAPE`] or [`CONFLICT_ESCAPE`]).
Escape(i32),
/// The state is a decision point: it needs outgoing edges.
Decide,
}
/// What the classifier remembers about one interned DFA state.
#[derive(Clone, Debug)]
struct StateFacts {
depth: usize,
verdict: Verdict,
taint: Taint,
fallback: i32,
conflicts: Vec<i32>,
/// The accept was reached by resolving a conflict (exact ambiguity or
/// uniform trust), not by finding a single viable alternative. Only this
/// kind of accept depends on the taint of the paths that reached the
/// state.
resolved_conflict: bool,
/// The state's successors were computed at least once.
expanded: bool,
/// The lowest conflicting alternative of a conflict escape state, `0` when
/// the runtime cannot resolve the conflict directly.
conflict_min_alt: i32,
/// The alternative a guarded state resolves to, `0` when the state is not
/// guarded.
guarded_alt: i32,
/// The other alternative of a guarded state: the skip or the exit.
guard_defer_alt: i32,
/// The guard group of a guarded state.
guard_group: u32,
/// The guard roots of the configs of the state.
roots: GuardRoots,
/// The closed config set of a frontier escape state.
continuation: Option<ParserContinuation>,
/// A predicate in the config set made the state escape.
predicated: bool,
}
/// The attempt-level bookkeeping one classification commits.
///
/// A classification is computed before the state is interned, because the
/// runtime DFA needs the accept flag and the prediction up front. Only a
/// *newly* interned state commits these effects: a lookahead path that reaches
/// an already known config set must not count its conflicts twice, and must
/// not abort a build whose state set is already complete.
#[derive(Debug, Default)]
struct ClassifyEffects {
exact_ambiguity: Option<BitSet>,
utrust: bool,
approximation: Option<BitSet>,
context_sensitive: Option<BitSet>,
conflict: Option<Vec<i32>>,
/// A take-vetoed conflict state that may resolve as a guarded take. The
/// payload is the conflicting alternative set, or `None` for a budget
/// escape that was never conflict-analyzed.
guard_candidate: Option<Option<BitSet>>,
/// An iterate/exit conflict state vetoed only on foreign consumption: a
/// candidate for the guarded iterate.
guard_iterate_candidate: Option<Option<BitSet>>,
/// The decision state of the attempt is behind a predicate, so the whole
/// decision depends on parser state and no table can decide it.
fail_predicated: bool,
/// The state accepts with the virtual alternative of a shared-descent
/// group.
descent_group: bool,
abort: bool,
}
impl StateFacts {
fn accept_value(&self) -> i32 {
match self.verdict {
Verdict::Accept(alt) => alt,
Verdict::Escape(marker) => marker,
Verdict::Decide => 0,
}
}
}
/// The policy of one build attempt.
#[derive(Clone, Copy, Debug)]
struct AttemptPolicy {
/// Widening bound: `i32::MAX` for the unbounded attempt, `0` for the fully
/// widened one.
depth_bound: i32,
/// Bound the construction and escape at the frontier instead of failing.
hybrid: bool,
/// Depth at which a hybrid construction stops expanding.
hybrid_depth_cap: usize,
/// State count at which a hybrid construction stops expanding beyond
/// depth 2.
hybrid_state_cap: usize,
/// The larger hybrid budget of `--static-dfa-only`.
static_only: bool,
/// Stop at the first conflict the construction does not trust, keeping the
/// work small for decisions that end up adaptive anyway.
abort_on_untrusted_conflict: bool,
/// Trust an exact-ambiguity conflict without the witness checks.
trust_exact_ambiguity: bool,
}
impl AttemptPolicy {
const fn unbounded() -> Self {
Self {
depth_bound: i32::MAX,
hybrid: false,
hybrid_depth_cap: HYBRID_DEPTH_CAP,
hybrid_state_cap: HYBRID_STATE_CAP,
static_only: false,
abort_on_untrusted_conflict: false,
trust_exact_ambiguity: true,
}
}
const fn widened() -> Self {
Self {
depth_bound: 0,
..Self::unbounded()
}
}
const fn hybrid() -> Self {
Self {
hybrid: true,
..Self::unbounded()
}
}
/// The hybrid policy with the depth cap of `budget`, when it sets one.
/// When a source set the state cap, the table expands up to that cap.
fn hybrid_within(budget: &DecisionBudget) -> Self {
Self {
hybrid_depth_cap: budget.max_k.unwrap_or(HYBRID_DEPTH_CAP),
hybrid_state_cap: if budget.explicit_max_states {
budget.max_states
} else {
HYBRID_STATE_CAP
},
..Self::hybrid()
}
}
/// The small hybrid policy that `--static-dfa-only` tries when the
/// larger construction fails. A depth cap of `budget` below the default
/// applies here too.
fn fallback_hybrid(budget: &DecisionBudget) -> Self {
Self {
hybrid_depth_cap: budget
.max_k
.map_or(HYBRID_DEPTH_CAP, |max_k| max_k.min(HYBRID_DEPTH_CAP)),
..Self::hybrid()
}
}
/// The larger hybrid policy of `--static-dfa-only`: the state cap is the
/// state cap of the decision.
fn static_only_hybrid(budget: &DecisionBudget) -> Self {
Self {
hybrid_depth_cap: budget.max_k.unwrap_or(STATIC_ONLY_HYBRID_DEPTH_CAP),
hybrid_state_cap: budget.max_states,
static_only: true,
..Self::hybrid()
}
}
const fn kind(&self) -> AttemptKind {
match self {
Self {
hybrid: true,
static_only: true,
..
} => AttemptKind::StaticOnlyHybrid,
Self { hybrid: true, .. } => AttemptKind::Hybrid,
Self { depth_bound: 0, .. } => AttemptKind::Widened {
abort: self.abort_on_untrusted_conflict,
},
Self { .. } => AttemptKind::Unbounded {
abort: self.abort_on_untrusted_conflict,
},
}
}
}
/// The classification of one decision or precedence class, with what a
/// witness pass can reuse.
#[derive(Debug, Default)]
struct ClassRun {
result: DecisionResult,
/// The unbounded attempt stopped at an untrusted conflict.
unbounded_stopped: bool,
/// The widened attempt stopped at an untrusted conflict.
widened_stopped: bool,
/// The unbounded attempt spent its visit budget on the start state.
start_exhausted: bool,
}
/// The result of one build attempt.
#[derive(Debug, Default)]
struct Attempt {
decision: usize,
state_count: usize,
table: Option<StaticDfaTable>,
overflow: bool,
/// Set when the attempt stopped at an untrusted conflict.
stopped: bool,
/// Set when the closure of the start state spent the visit budget.
start_exhausted: bool,
/// Set when the closures of the attempt spent the visit budget.
exhausted: bool,
/// Set when a hybrid attempt spent the state cap or the visit budget and
/// escaped the states it cannot expand.
budget_cutoff: bool,
/// Configs the closures of the attempt visited.
visits: u64,
/// The visited configs by rule index.
rule_visits: Vec<u64>,
facts: ClosureFacts,
utrust_resolutions: usize,
exact_ambiguities: Vec<BitSet>,
context_sensitive: Vec<BitSet>,
approximations: Vec<BitSet>,
/// Alternative sets of the conflicts the construction did not trust.
conflicts: Vec<Vec<i32>>,
/// DFA state number of the first conflict, for the report witness.
first_conflict_state: Option<i32>,
/// The same config set was reached by two paths with different trust
/// taint, so no verdict derived from the first path can be trusted.
taint_conflict: bool,
/// The attempt ran under the hybrid policy.
hybrid: bool,
/// The decision state is behind a predicate: the decision is predicated.
predicated: bool,
/// The decision is an optional-postfix (`X Y?`) shape.
has_postfix_shape: bool,
/// Conflict states the optional-postfix take rule resolved to take.
take_rule_fires: usize,
/// Conflict states a guarded take resolved.
guarded_takes: usize,
/// Conflict states a guarded iterate resolved under the stack guard.
guarded_iterates: usize,
/// Conflict states the iterate reading resolved outright, because no
/// invoking state can trip an iterate guard.
iterate_accepts: usize,
/// States that accept with the virtual alternative of a shared-descent
/// group.
descent_group_states: usize,
/// The shared-descent plan of the attempt, when it had one.
descent: Option<DescentPlan>,
}
/// The precedence classes of one precedence-loop decision.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PrecedenceTables {
/// The precedence cut points of the loop, ascending.
pub(crate) cutoffs: Vec<i32>,
/// One table per class: `p<=cutoffs[0]`, `p=cutoffs[i-1]+1..=cutoffs[i]`,
/// and `p>cutoffs[last]`.
pub(crate) tables: Vec<Option<StaticDfaTable>>,
pub(crate) adaptive_classes: usize,
pub(crate) escapes: usize,
}
/// What the classifier decided about one prediction decision.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct DecisionResult {
pub(crate) decision: usize,
pub(crate) rule_index: usize,
pub(crate) state_number: i32,
pub(crate) category: Category,
/// Longest lookahead of a finite table, `-1` when unbounded or unknown.
pub(crate) k: i32,
pub(crate) num_dfa_states: usize,
pub(crate) cyclic: bool,
pub(crate) used_widening: bool,
pub(crate) saw_predicate: bool,
/// The decision state itself sits behind a predicate, so no construction
/// can decide it and a hybrid retry cannot help.
pub(crate) predicated_start: bool,
pub(crate) first_predicate: Option<(i32, i32)>,
pub(crate) saw_precedence_predicate: bool,
/// The decision is an optional-postfix (`X Y?`) shape.
pub(crate) has_postfix_shape: bool,
/// Conflict states the optional-postfix take rule resolved to take.
pub(crate) take_rule_fires: usize,
/// Conflict states a guarded take resolved (Phase 5.2b).
pub(crate) guarded_takes: usize,
/// Conflict states a guarded iterate resolved under the stack guard.
pub(crate) guarded_iterates: usize,
/// Conflict states the iterate reading resolved outright.
pub(crate) iterate_accepts: usize,
/// States that accept with the virtual alternative of a shared-descent
/// group.
pub(crate) descent_group_states: usize,
/// The shared-descent groups the table accepts with.
pub(crate) descent: Option<DescentPlan>,
pub(crate) utrust_resolutions: usize,
pub(crate) conflict_witness: Option<Vec<i32>>,
pub(crate) budget_witness: Option<Vec<i32>>,
pub(crate) conflicts: Vec<Vec<i32>>,
pub(crate) approximations: Vec<Vec<i32>>,
pub(crate) escapes: usize,
/// Share of the start alphabet that reaches an accept state, in percent.
pub(crate) coverage_percent: u32,
pub(crate) table: Option<StaticDfaTable>,
pub(crate) precedence: Option<PrecedenceTables>,
/// The escape states that `--static-dfa-only` resolved, set once every
/// table of the decision predicts without `adaptive_predict`.
pub(crate) static_only: Option<EscapeResolutions>,
/// What the classification of the decision cost.
pub(crate) cost: DecisionCost,
/// The analysis budget of the decision.
pub(crate) budget: DecisionBudget,
/// The table escapes the states that the state cap or the visit budget
/// did not let the construction expand.
pub(crate) budget_cutoff: bool,
}
impl DecisionResult {
fn new(decision: usize, state: ATNStateRef) -> Self {
Self {
decision,
rule_index: usize::try_from(state.get_rule_index()).unwrap_or(0),
state_number: state.get_state_number(),
category: Category::LLK,
k: -1,
num_dfa_states: 0,
cyclic: false,
used_widening: false,
saw_predicate: false,
predicated_start: false,
first_predicate: None,
saw_precedence_predicate: false,
has_postfix_shape: false,
take_rule_fires: 0,
guarded_takes: 0,
guarded_iterates: 0,
iterate_accepts: 0,
descent_group_states: 0,
descent: None,
utrust_resolutions: 0,
conflict_witness: None,
budget_witness: None,
conflicts: Vec::new(),
approximations: Vec::new(),
escapes: 0,
coverage_percent: 0,
table: None,
precedence: None,
static_only: None,
cost: DecisionCost::default(),
budget: DecisionBudget::default(),
budget_cutoff: false,
}
}
/// A short description of how the decision falls back at runtime, for
/// `--report-decisions`.
///
/// Under `--static-dfa-only`, the text counts the resolved escape states
/// instead:
///
/// - `g`: a stack guard decides the state. It returns the skip or the exit
/// when it defers.
/// - `m`: the state predicts the minimum conflicting alternative.
/// - `v`: the state predicts the minimum viable alternative.
/// - `x`: the state reports a syntax error.
pub(crate) fn fallback_text(&self) -> String {
if let Some(resolved) = &self.static_only {
let mut parts = Vec::new();
if resolved.guarded > 0 {
parts.push(format!("{}g", resolved.guarded));
}
if resolved.min_alt > 0 {
parts.push(format!("{}m", resolved.min_alt));
}
if resolved.min_viable_alt > 0 {
parts.push(format!("{}v", resolved.min_viable_alt));
}
if resolved.syntax_error > 0 {
parts.push(format!("{}x", resolved.syntax_error));
}
if parts.is_empty() {
return "0".to_owned();
}
return parts.join("+");
}
if self.category == Category::LR_PRECEDENCE {
let Some(precedence) = &self.precedence else {
return "all".to_owned();
};
if self.escapes == 0 && precedence.adaptive_classes == 0 {
if self.guarded_iterates > 0 {
return format!("{}g", self.guarded_iterates);
}
return "0".to_owned();
}
let mut text = String::new();
if self.escapes > 0 {
text.push_str(&format!("{}e", self.escapes));
}
if precedence.adaptive_classes > 0 {
if !text.is_empty() {
text.push('+');
}
text.push_str(&format!("{}c", precedence.adaptive_classes));
}
return text;
}
if self.category == Category::LL1 {
return "0".to_owned();
}
if self.table.is_none() {
return "all".to_owned();
}
if self.escapes > 0 {
self.escapes.to_string()
} else if self.guarded_takes > 0 {
format!("{}g", self.guarded_takes)
} else {
"0".to_owned()
}
}
/// `true` when the table of the decision never escapes to the adaptive
/// simulation.
pub(crate) fn is_fully_static(&self) -> bool {
if self.static_only.is_some() {
return true;
}
if self.guarded_takes > 0 || self.guarded_iterates > 0 {
// A guarded conflict defers to the adaptive simulation when the
// parse stack reaches a guard root.
return false;
}
match self.category {
Category::LL1
| Category::NON_GREEDY
| Category::LLK
| Category::LLSTAR
| Category::EXACT_AMBIG => true,
Category::LR_PRECEDENCE => {
self.escapes == 0
&& self
.precedence
.as_ref()
.is_some_and(|precedence| precedence.adaptive_classes == 0)
}
Category::HYBRID => false,
Category::CONTEXT_SENSITIVE | Category::PREDICATED | Category::OVERFLOW => false,
}
}
}
/// Classifies the decision states of one compiled parser unit.
pub(crate) struct DecisionClassifier {
atn: &'static ATN,
ll1_disjoint: Vec<bool>,
/// The token counts from each alternative start state to the stop state
/// of its rule, by ATN state number, computed on first use.
completion_depths: Box<[OnceLock<BitSet>]>,
/// The budget of a decision without an entry in `budgets`.
default_budget: DecisionBudget,
/// The budget of each decision, by decision number.
budgets: Vec<DecisionBudget>,
/// The operator-loop analysis of each precedence-loop decision, built at
/// most once and shared by every class attempt.
loop_blocks: Box<[OnceLock<LoopBlock>]>,
/// The optional-postfix shape of each decision, built at most once.
postfix_shapes: Box<[OnceLock<Option<PostfixShape>>]>,
/// Whether the generated parser can defer to the adaptive simulation. When
/// it cannot (`--static-dfa-only`), a partial table is kept regardless of
/// its coverage, because the alternative is no table at all.
atn_fallback: AtnFallback,
/// The shared-descent plans of the decisions.
descent: DescentAnalyzer,
/// The rule invocations of the ATN, shared by every build attempt.
call_sites: CallSites,
/// The follow regions of the stack guards, computed on first use.
guard_regions: OnceLock<GuardRegions>,
/// Measure the wall-clock time of each decision and attempt.
profile: bool,
}
impl DecisionClassifier {
pub(crate) fn new(atn: &'static ATN, ll1_disjoint: Vec<bool>) -> Self {
Self {
atn,
ll1_disjoint,
completion_depths: once_locks(atn.states_count()),
default_budget: DecisionBudget::default(),
budgets: Vec::new(),
loop_blocks: once_locks(atn.decision_to_state.len()),
postfix_shapes: once_locks(atn.decision_to_state.len()),
atn_fallback: AtnFallback::Allowed,
descent: DescentAnalyzer::new(atn),
call_sites: CallSites::of(atn),
guard_regions: OnceLock::new(),
profile: false,
}
}
/// The loop-block analysis of one precedence-loop decision, built on first
/// use and shared by every class attempt of that decision.
fn loop_block(&self, decision: usize) -> LoopBlock {
self.loop_blocks[decision]
.get_or_init(|| LoopBlock::of(self.atn, self.atn.decision_to_state[decision]))
.clone()
}
/// The optional-postfix shape of one decision, detected on first use.
fn postfix_shape(&self, decision: usize) -> Option<PostfixShape> {
self.postfix_shapes[decision]
.get_or_init(|| PostfixShape::analyze(self.atn, self.atn.decision_to_state[decision]))
.clone()
}
/// Sets the per-attempt visit budget of the decisions without an entry
/// in [`Self::with_budgets`]. The default is
/// [`DEFAULT_VISIT_BUDGET`](super::DEFAULT_VISIT_BUDGET).
#[cfg(test)]
pub(crate) const fn with_visit_budget(mut self, budget: u64) -> Self {
self.default_budget.max_visits = budget;
self
}
/// Sets the budget of each decision, by decision number.
pub(crate) fn with_budgets(mut self, budgets: Vec<DecisionBudget>) -> Self {
self.budgets = budgets;
self
}
/// The budget of decision `decision`.
pub(crate) fn budget(&self, decision: usize) -> DecisionBudget {
self.budgets
.get(decision)
.copied()
.unwrap_or(self.default_budget)
}
/// Enables shared-descent groups with the rule facts of the grammar.
pub(crate) fn with_descent_rules(mut self, rules: DescentRules) -> Self {
self.descent = self.descent.with_rules(rules);
self
}
/// Sets whether the generated parser can defer to the adaptive simulation.
pub(crate) const fn with_atn_fallback(mut self, atn_fallback: AtnFallback) -> Self {
self.atn_fallback = atn_fallback;
self
}
/// Measures the wall-clock time of each decision and each build attempt
/// (`--profile-decisions`). The times differ from run to run, so the
/// results are no longer reproducible.
pub(crate) const fn with_profiling(mut self, profile: bool) -> Self {
self.profile = profile;
self
}
/// The number of threads that [`Self::classify_all`] runs.
pub(crate) fn threads(&self) -> usize {
let available = std::thread::available_parallelism().map_or(1, NonZeroUsize::get);
self.workers(available.min(MAX_CLASSIFY_THREADS))
}
/// The number of threads that [`Self::classify_on`] runs when it can run
/// `threads` threads: never more than there are decisions.
fn workers(&self, threads: usize) -> usize {
threads.clamp(1, self.atn.decision_to_state.len().max(1))
}
/// Classifies every decision, in parallel.
pub(crate) fn classify_all(&self) -> Vec<DecisionResult> {
self.classify_on(self.threads())
}
/// Classifies every decision on at most `threads` threads.
///
/// Each thread takes the next unclassified decision until none is left.
/// The classification of one decision does not depend on the others. The
/// shared caches hold values that do not depend on the order of the
/// computation. Thus the results do not depend on the thread count.
pub(super) fn classify_on(&self, threads: usize) -> Vec<DecisionResult> {
let decisions = self.atn.decision_to_state.len();
let threads = self.workers(threads);
if threads == 1 {
return (0..decisions)
.map(|decision| self.classify(decision))
.collect();
}
let next = AtomicUsize::new(0);
let mut results: Vec<Option<DecisionResult>> = vec![None; decisions];
std::thread::scope(|scope| {
let workers: Vec<_> = (0..threads)
.map(|_| {
scope.spawn(|| {
let mut classified = Vec::new();
loop {
let decision = next.fetch_add(1, Ordering::Relaxed);
if decision >= decisions {
break classified;
}
classified.push((decision, self.classify(decision)));
}
})
})
.collect();
for worker in workers {
let classified = worker
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
for (decision, result) in classified {
results[decision] = Some(result);
}
}
});
results
.into_iter()
.map(|result| result.expect("every decision is classified"))
.collect()
}
/// Classifies one decision and records what the classification cost.
fn classify(&self, decision: usize) -> DecisionResult {
let started = self.profile.then(Instant::now);
let mut log = CostLog::default();
let mut result = self.classify_decision(decision, &mut log);
result.cost = log.finish(started.map(|started| started.elapsed()));
result.budget = self.budget(decision);
result
}
fn classify_decision(&self, decision: usize, log: &mut CostLog) -> DecisionResult {
let state = self.atn.decision_to_state[decision];
let mut result = DecisionResult::new(decision, state);
if state.is_nongreedy_decision() == Some(true) {
result.category = Category::NON_GREEDY;
return result;
}
if self.is_precedence_loop_decision(state) {
return self.classify_precedence(result, log);
}
if self.ll1_disjoint.get(decision).copied() == Some(true) {
result.category = Category::LL1;
result.k = 1;
return result;
}
if state.get_transitions().len() >= VIRTUAL_ALT_BASE as usize {
result.category = Category::OVERFLOW;
return result;
}
let run = self.first_pass(decision, None, log);
self.witness_pass(decision, None, run, log)
}
/// Classifies one decision, or one precedence class of it, and stops the
/// static constructions at the first conflict they do not trust.
///
/// This shortcut keeps the static constructions small when the decision
/// gets a hybrid table. When a static attempt stopped and the pass found
/// no table, [`Self::witness_pass`] classifies again to get the real
/// conflict witness for the report.
fn first_pass(
&self,
decision: usize,
class: Option<PrecedenceClass>,
log: &mut CostLog,
) -> ClassRun {
let mut run = self.static_chain(decision, class, true, false, log);
let eligible = run.result.table.is_none()
&& (class.is_some()
|| !run.result.predicated_start
&& matches!(
run.result.category,
Category::OVERFLOW | Category::CONTEXT_SENSITIVE | Category::PREDICATED
));
if !eligible {
return run;
}
for policy in self.hybrid_policies(decision) {
// The start closure does not depend on the hybrid bounds. A start
// state that spent the visit budget once spends it again.
if run.start_exhausted && policy.depth_bound == i32::MAX {
continue;
}
let mut policy = policy;
policy.trust_exact_ambiguity = class.is_none();
let attempt = self.attempt(decision, policy, class, log);
let candidate = self.finalize(attempt);
if candidate.table.is_some() {
run.result = candidate;
break;
}
}
run
}
/// Classifies again without the shortcut of [`Self::first_pass`], when
/// the first pass stopped and found no table.
///
/// When the first pass found no table, the result is the same as that of
/// a pass without the shortcut. An attempt that did not stop saw the same
/// states as an attempt without the shortcut, so it does not run again. A
/// stopped attempt gives an overflow, so the first pass already tried the
/// hybrid constructions, and they do not use the shortcut.
fn witness_pass(
&self,
decision: usize,
class: Option<PrecedenceClass>,
run: ClassRun,
log: &mut CostLog,
) -> DecisionResult {
if run.result.table.is_some() || !(run.unbounded_stopped || run.widened_stopped) {
return run.result;
}
self.static_chain(decision, class, false, !run.unbounded_stopped, log)
.result
}
/// The static constructions of one decision or precedence class: the
/// unbounded attempt, then the widened attempt when the unbounded one
/// overflows. An attempt that stopped at an untrusted conflict does not
/// count as an overflow here.
///
/// When `skip_unbounded` is set, an earlier unbounded attempt of the same
/// class overflowed without a stop. The abort policy does not change that
/// attempt, so it does not run again.
fn static_chain(
&self,
decision: usize,
class: Option<PrecedenceClass>,
abort_on_untrusted_conflict: bool,
skip_unbounded: bool,
log: &mut CostLog,
) -> ClassRun {
let mut policy = AttemptPolicy::unbounded();
policy.abort_on_untrusted_conflict = abort_on_untrusted_conflict;
policy.trust_exact_ambiguity = class.is_none();
let mut run = ClassRun::default();
let mut retry = true;
if !skip_unbounded {
let attempt = self.attempt(decision, policy, class, log);
run.unbounded_stopped = attempt.stopped;
run.start_exhausted = attempt.start_exhausted;
let overflow = attempt.overflow;
run.result = self.finalize(attempt);
// Full widening is the fallback for a spent budget. An attempt
// that stopped at an untrusted conflict did not spend a budget.
retry = !run.unbounded_stopped
&& match class {
Some(_) => run.result.category == Category::OVERFLOW,
None => overflow,
};
}
if retry {
let widened = AttemptPolicy {
depth_bound: AttemptPolicy::widened().depth_bound,
..policy
};
let attempt = self.attempt(decision, widened, class, log);
run.widened_stopped = attempt.stopped;
run.result = self.finalize(attempt);
}
run
}
/// Turns what one attempt observed into a decision result: the category,
/// and the table when the attempt earns one.
fn finalize(&self, outcome: Attempt) -> DecisionResult {
let decision = outcome.decision;
let mut result = DecisionResult::new(decision, self.atn.decision_to_state[decision]);
apply_facts(&mut result, &outcome);
if outcome.overflow {
result.category = Category::OVERFLOW;
result.num_dfa_states = outcome.state_count;
return result;
}
if outcome.predicated || (outcome.facts.saw_predicate && !outcome.hybrid) {
result.predicated_start = outcome.predicated;
// A predicate in front of the decision, or anywhere in a
// construction that cannot escape, makes viability depend on the
// parse state, so no table can decide it.
result.category = Category::PREDICATED;
result.num_dfa_states = outcome.state_count;
return result;
}
let Some(table) = outcome.table else {
result.category = if outcome.facts.saw_predicate {
Category::PREDICATED
} else if !outcome.conflicts.is_empty() {
Category::CONTEXT_SENSITIVE
} else {
Category::OVERFLOW
};
return result;
};
result.num_dfa_states = table.states.len();
result.cyclic = table.cyclic;
result.k = table.max_k;
result.escapes = table.escapes();
result.coverage_percent = (table.start_coverage() * 100.0) as u32;
result.conflict_witness = table
.first_escape(CONFLICT_ESCAPE)
.or_else(|| {
outcome.first_conflict_state.and_then(|state| {
usize::try_from(state)
.ok()
.filter(|state| *state < table.states.len())
})
})
.and_then(|state| table.witness(state));
if let Some(state) = table.first_escape(ESCAPE) {
result.budget_witness = table.witness(state);
}
if outcome.taint_conflict {
// Two paths disagreed on the taint of one config set, so no accept
// derived from it is trustworthy.
result.category = Category::CONTEXT_SENSITIVE;
return result;
}
if result.escapes > 0 || table.guarded() > 0 {
result.category = Category::HYBRID;
// A table whose start state escapes answers nothing at all. Below
// the coverage threshold, the adaptive simulation decides almost
// every lookahead anyway, unless there is no adaptive simulation.
let start_decides = table.states.first().is_some_and(|state| !state.is_escape());
let covers = result.coverage_percent >= HYBRID_MIN_COVERAGE_PERCENT
|| self.atn_fallback == AtnFallback::Forbidden;
if start_decides && covers {
result.descent = used_groups(outcome.descent.as_ref(), &table);
result.table = Some(table);
}
return result;
}
result.category =
if !outcome.context_sensitive.is_empty() || !outcome.approximations.is_empty() {
Category::CONTEXT_SENSITIVE
} else if !outcome.exact_ambiguities.is_empty() {
Category::EXACT_AMBIG
} else if table.cyclic {
Category::LLSTAR
} else {
Category::LLK
};
// Only a table that decides every reachable lookahead is worth
// emitting: a conflict-resolving state would have to escape anyway.
if matches!(
result.category,
Category::LLK | Category::LLSTAR | Category::EXACT_AMBIG
) {
result.descent = used_groups(outcome.descent.as_ref(), &table);
result.table = Some(table);
}
result
}
/// The hybrid attempt policies, in the order to try them.
///
/// Without the adaptive fallback, every frontier state of a hybrid table
/// is a guess, so a larger budget comes first. The default budget stays as
/// the second choice, for a decision whose larger construction overflows.
fn hybrid_policies(&self, decision: usize) -> Vec<AttemptPolicy> {
let budget = self.budget(decision);
match self.atn_fallback {
AtnFallback::Allowed => vec![AttemptPolicy::hybrid_within(&budget)],
AtnFallback::Forbidden => vec![
AttemptPolicy::static_only_hybrid(&budget),
AttemptPolicy::fallback_hybrid(&budget),
],
}
}
fn is_precedence_loop_decision(&self, state: ATNStateRef) -> bool {
if state.state_type() != ATNStateType::StarLoopEntry {
return false;
}
let rule_start = self.atn.rule_to_start_state[state.get_rule_index() as usize];
let is_left_recursive = rule_start
.try_as::<RuleStartState>()
.is_some_and(|start| start.is_left_recursive);
if !is_left_recursive {
return false;
}
let transitions = state.get_transitions();
let Some(last) = transitions.last() else {
return false;
};
let loop_end = last.get_target();
if loop_end.state_type() != ATNStateType::LoopEnd {
return false;
}
loop_end.has_epsilon_only_transitions()
&& loop_end
.get_transitions()
.first()
.is_some_and(|transition| {
transition.get_target().state_type() == ATNStateType::RuleStop
})
}
fn classify_precedence(&self, mut result: DecisionResult, log: &mut CostLog) -> DecisionResult {
result.category = Category::LR_PRECEDENCE;
let state = self.atn.decision_to_state[result.decision];
let target_rule = state.get_rule_index();
let mut cutoffs = BTreeSet::new();
for atn_state in self.atn.iter_states() {
if atn_state.get_rule_index() != target_rule {
continue;
}
for transition in atn_state.get_transitions() {
if let Some(predicate) = transition.try_as::<PrecedencePredicateTransition>() {
cutoffs.insert(predicate.precedence());
}
}
}
if cutoffs.is_empty() {
return result;
}
let cutoffs: Vec<i32> = cutoffs.into_iter().collect();
let mut representatives = Vec::with_capacity(cutoffs.len() + 1);
representatives.push(0);
for cutoff in &cutoffs {
representatives.push(cutoff.saturating_add(1));
}
let mut tables: Vec<Option<StaticDfaTable>> = vec![None; representatives.len()];
let mut any_table = false;
let mut max_k = 0_i32;
let mut total_states = 0_usize;
let mut adaptive_classes = 0_usize;
let mut escapes = 0_usize;
for class_index in 0..representatives.len() {
let class = PrecedenceClass {
rule_index: target_rule,
eval_value: representatives[class_index],
lo: representatives[class_index],
hi: cutoffs.get(class_index).copied().unwrap_or(i32::MAX),
};
log.class = Some(class_index);
let run = self.first_pass(result.decision, Some(class), log);
let outcome = self.witness_pass(result.decision, Some(class), run, log);
result.used_widening |= outcome.used_widening;
result.saw_predicate |= outcome.saw_predicate;
if result.first_predicate.is_none() {
result.first_predicate = outcome.first_predicate;
}
result.saw_precedence_predicate |= outcome.saw_precedence_predicate;
result.utrust_resolutions += outcome.utrust_resolutions;
result.guarded_takes += outcome.guarded_takes;
result.guarded_iterates += outcome.guarded_iterates;
result.iterate_accepts += outcome.iterate_accepts;
result.take_rule_fires += outcome.take_rule_fires;
result.has_postfix_shape |= outcome.has_postfix_shape;
result.budget_cutoff |= outcome.table.is_some() && outcome.budget_cutoff;
for conflict in &outcome.conflicts {
if !result.conflicts.contains(conflict) {
result.conflicts.push(conflict.clone());
}
}
if result.conflict_witness.is_none() {
result.conflict_witness = outcome.conflict_witness.clone();
}
if result.budget_witness.is_none() {
result.budget_witness = outcome.budget_witness.clone();
}
match outcome.table {
Some(table) => {
any_table = true;
max_k = max_k.max(table.max_k);
total_states += table.states.len();
escapes += table.escapes();
tables[class_index] = Some(table);
}
None => {
adaptive_classes += 1;
}
}
}
result.precedence = Some(PrecedenceTables {
cutoffs,
tables,
adaptive_classes,
escapes,
});
if any_table {
result.k = max_k;
result.num_dfa_states = total_states;
}
result.escapes = escapes;
result
}
/// Runs one build attempt (see [`Self::build_attempt`]) and records its
/// cost in `log`.
fn attempt(
&self,
decision: usize,
policy: AttemptPolicy,
precedence: Option<PrecedenceClass>,
log: &mut CostLog,
) -> Attempt {
let started = self.profile.then(Instant::now);
let mut attempt = self.build_attempt(decision, policy, precedence);
let outcome = if attempt.exhausted {
AttemptOutcome::VisitBudget
} else if attempt.stopped {
AttemptOutcome::Stopped
} else if attempt.overflow || attempt.budget_cutoff {
AttemptOutcome::StateBudget
} else {
AttemptOutcome::Finished
};
log.record(
AttemptCost {
kind: policy.kind(),
class: log.class,
outcome,
visits: attempt.visits,
states: attempt.state_count,
elapsed: started.map(|started| started.elapsed()),
},
&std::mem::take(&mut attempt.rule_visits),
);
attempt
}
/// One build attempt: fresh simulator, fresh arena, fresh scratch arena.
///
/// A fresh manager per attempt is deliberate: each attempt needs an empty
/// DFA. The build reads its states back by their numbers, which a DFA
/// gives out densely in creation order. It also reads back every edge in
/// the DFA. The states and edges of an earlier attempt break both. A
/// shared manager also gives all precedence classes of a decision the same
/// DFA, but one config set can have other successors in another class.
fn build_attempt(
&self,
decision: usize,
policy: AttemptPolicy,
precedence: Option<PrecedenceClass>,
) -> Attempt {
let atn = self.atn;
let decision_state = atn.decision_to_state[decision];
let loop_block = precedence.map(|_| self.loop_block(decision));
let postfix = self.postfix_shape(decision);
let has_postfix_shape = postfix.is_some();
let budget = self.budget(decision);
// Shared-descent groups resolve escapes, so only hybrid attempts use
// them; a precedence class table is selected by the precedence, which a
// group arm cannot see.
let descent = if policy.hybrid && precedence.is_none() {
self.descent.plan(decision)
} else {
None
};
let manager = ParserATNSimulatorManager::new(atn);
Arena::with(|arena| {
let simulator = ParserATNSimulator::new(manager.get_simulator(arena));
let scratch = Bump::new();
let mut build = DecisionBuild {
atn,
simulator: &simulator,
dfa: simulator
.decision_to_dfa(decision)
.expect("every decision has a DFA"),
scratch: &scratch,
closure: Closure::new(
atn,
&self.call_sites,
&scratch,
policy.depth_bound,
precedence,
loop_block,
postfix.clone(),
budget.max_visits,
),
policy,
max_states: budget.max_states,
budget_spent: false,
allow_continuations: policy.hybrid && precedence.is_none(),
precedence_class: precedence.is_some(),
postfix,
descent,
guard_candidates: BTreeMap::new(),
guard_iterate_candidates: BTreeMap::new(),
guard: None,
guard_regions: &self.guard_regions,
static_only: self.atn_fallback == AtnFallback::Forbidden,
decision_state,
decision,
info: HashMap::new(),
states: Vec::new(),
accept_sinks: HashMap::new(),
queue: VecDeque::new(),
completion_depths: &self.completion_depths,
attempt: Attempt {
decision,
hybrid: policy.hybrid,
has_postfix_shape,
..Attempt::default()
},
};
build.run()
})
}
}
/// `len` empty cells.
fn once_locks<T>(len: usize) -> Box<[OnceLock<T>]> {
(0..len).map(|_| OnceLock::new()).collect()
}
/// The groups of `plan` that some state of `table` accepts with.
fn used_groups(plan: Option<&DescentPlan>, table: &StaticDfaTable) -> Option<DescentPlan> {
let groups: Vec<_> = plan?
.groups
.iter()
.filter(|group| {
table
.states
.iter()
.any(|state| state.accept == group.virtual_alt)
})
.cloned()
.collect();
(!groups.is_empty()).then_some(DescentPlan { groups })
}
/// Merges the facts of one attempt into the decision result.
fn apply_facts(result: &mut DecisionResult, attempt: &Attempt) {
result.used_widening |= attempt.facts.used_widening;
result.saw_predicate |= attempt.facts.saw_predicate;
result.saw_precedence_predicate |= attempt.facts.saw_precedence_predicate;
if result.first_predicate.is_none() {
result.first_predicate = attempt.facts.first_predicate;
}
result.utrust_resolutions += attempt.utrust_resolutions;
result.has_postfix_shape |= attempt.has_postfix_shape;
result.take_rule_fires += attempt.take_rule_fires;
result.guarded_takes += attempt.guarded_takes;
result.guarded_iterates += attempt.guarded_iterates;
result.iterate_accepts += attempt.iterate_accepts;
result.descent_group_states += attempt.descent_group_states;
result.budget_cutoff |= attempt.budget_cutoff && attempt.table.is_some();
for conflict in &attempt.conflicts {
if !result.conflicts.contains(conflict) {
result.conflicts.push(conflict.clone());
}
}
for conflict in &attempt.approximations {
let alts = conflict.iter().map(|alt| alt as i32).collect::<Vec<_>>();
if !result.approximations.contains(&alts) {
result.approximations.push(alts);
}
}
}
/// The stack-guard sets of one decision table.
#[derive(Debug)]
struct GuardSets {
/// The danger set of every guard group.
groups: Vec<Vec<i32>>,
/// The pass set that all guard groups share.
pass: Vec<i32>,
}
impl GuardSets {
/// The guard group with the danger set `danger`, added when it is new.
fn group_of(&mut self, danger: Vec<i32>) -> u32 {
let index = match self.groups.iter().position(|group| *group == danger) {
Some(index) => index,
None => {
self.groups.push(danger);
self.groups.len() - 1
}
};
index as u32
}
}
/// One decision build, alive for one attempt.
struct DecisionBuild<'b, 'sim, 'a> {
atn: &'static ATN,
simulator: &'b ParserATNSimulator<'sim>,
dfa: &'sim DFA<'sim, ATNConfigSet<'sim>>,
scratch: &'a Bump,
closure: Closure<'static, 'a>,
policy: AttemptPolicy,
/// The state cap of the table.
max_states: usize,
/// A hybrid attempt spent the state cap or the visit budget: every state
/// that is not expanded yet becomes a frontier escape.
budget_spent: bool,
/// Whether frontier escape states may carry a continuation. Precedence
/// classes never do: their tables are selected by the parser's precedence,
/// which the resumed SLL simulation cannot reproduce from a config set.
allow_continuations: bool,
/// `true` when this attempt builds one precedence class of a precedence
/// loop decision.
precedence_class: bool,
/// The decision's optional-postfix shape, when it has one.
postfix: Option<PostfixShape>,
/// The decision's shared-descent groups, when the attempt may accept with
/// them.
descent: Option<DescentPlan>,
/// Take-vetoed conflict states that may resolve as a guarded take, with
/// their conflicting alternatives (`None` for a budget escape that was
/// never conflict-analyzed). A sorted map keeps the resolution order
/// deterministic.
guard_candidates: BTreeMap<i32, Option<BitSet>>,
/// Iterate/exit states (conflict or budget frontier) vetoed only on foreign
/// consumption.
guard_iterate_candidates: BTreeMap<i32, Option<BitSet>>,
/// The guard sets of the decision, once a state resolved as a guarded
/// state (an optional-postfix take or a precedence-loop iterate).
guard: Option<GuardSets>,
guard_regions: &'a OnceLock<GuardRegions>,
/// `true` under `--static-dfa-only`: the table has no adaptive fallback.
static_only: bool,
decision: usize,
decision_state: ATNStateRef,
info: HashMap<i32, StateFacts>,
/// DFA states in creation order; the index is the state number.
states: Vec<&'sim DFAState<'sim, ATNConfigSet<'sim>>>,
/// For each alternative, the shared accept state of the config sets with
/// only that viable alternative.
accept_sinks: HashMap<i32, &'sim DFAState<'sim, ATNConfigSet<'sim>>>,
queue: VecDeque<i32>,
completion_depths: &'a [OnceLock<BitSet>],
attempt: Attempt,
}
impl<'b, 'sim, 'a> DecisionBuild<'b, 'sim, 'a>
where
'sim: 'a,
{
fn run(&mut self) -> Attempt {
let start = self.closure.start(self.decision_state);
if self.closure.exhausted {
self.attempt.overflow = true;
self.attempt.start_exhausted = true;
return self.take_attempt();
}
let Some(start_state) = self.intern(start, 0) else {
self.attempt.overflow = true;
return self.take_attempt();
};
self.dfa.set_s0(start_state);
if self.attempt.overflow || self.closure.exhausted || self.attempt.predicated {
return self.take_attempt();
}
while let Some(number) = self.queue.pop_front() {
let Some(facts) = self.info.get(&number).cloned() else {
continue;
};
if facts.verdict != Verdict::Decide {
continue;
}
// The hybrid frontier is a *creation* budget: a state that was
// already expanded keeps its successors, even though re-expanding
// it after a taint increase may now run past the cap.
let frontier = !facts.expanded && self.policy.hybrid;
if frontier && (self.budget_spent || self.at_hybrid_frontier(facts.depth)) {
if facts.depth < self.policy.hybrid_depth_cap
&& self.states.len() >= self.max_states
{
self.budget_spent = true;
self.attempt.budget_cutoff = true;
}
self.escape_frontier(number, &facts);
continue;
}
if let Some(facts) = self.info.get_mut(&number) {
facts.expanded = true;
}
let state = self.states[number as usize];
let closed = ClosedSet {
configs: state.configs().get_items().cloned().collect(),
taint: facts.taint.clone(),
roots: facts.roots.clone(),
};
let successors = self.closure.successors(&closed);
// Past the start state, a hybrid table escapes the states that it
// has no budget to expand instead of failing. The check before the
// interning assumes that every successor is new, so no state is
// interned without an edge to it.
let cut_off = frontier
&& facts.depth > 0
&& (self.closure.exhausted
|| self.states.len() + successors.len() > self.max_states);
if cut_off {
self.attempt.exhausted |= self.closure.exhausted;
self.closure.exhausted = false;
self.budget_spent = true;
self.attempt.budget_cutoff = true;
if let Some(facts) = self.info.get_mut(&number) {
facts.expanded = false;
}
self.escape_frontier(number, &facts);
continue;
}
if self.closure.exhausted {
self.attempt.overflow = true;
break;
}
let mut targets = Vec::with_capacity(successors.len());
for (label, successor) in successors {
let Some(target) = self.intern(successor, facts.depth + 1) else {
self.attempt.overflow = true;
break;
};
targets.push((label, target));
}
if self.attempt.overflow {
break;
}
for (label, target) in targets {
for interval in label.as_interval_set().as_slice() {
for token in interval.a..=interval.b {
if token < EOF || token > self.atn.max_token_type {
continue;
}
self.dfa.set_edge(state, (token + 1) as usize, target);
}
}
}
}
if !self.attempt.overflow {
self.finalize_guards();
self.attach_continuations();
// `finalize` drops a table with a taint conflict or an escaping
// start state, so its hazards are not needed.
let start_decides = self
.info
.get(&0)
.is_some_and(|facts| !matches!(facts.verdict, Verdict::Escape(_)));
let hazards = if self.static_only && !self.attempt.taint_conflict && start_decides {
self.state_hazards()
} else {
HashMap::new()
};
let mut table = self.snapshot(&hazards);
if self.static_only && !self.attempt.taint_conflict && start_decides {
self.compute_guard_hazards(&mut table);
}
self.attempt.table = Some(table);
}
self.take_attempt()
}
/// Ends the expansion at a state that the hybrid construction does not
/// expand: a shared-descent group or the iterate of a precedence loop
/// resolves it, or else it escapes.
fn escape_frontier(&mut self, number: i32, facts: &StateFacts) {
if self.accept_descent_group(number, facts) {
return;
}
// A budget frontier that sits on the iterate/exit pair of a
// precedence loop stays decidable by substitution. No conflict
// materialized before the cutoff. The attestations are still a
// lineage property, independent of any collision. So the argument
// below applies, and iterate is the answer the runtime would reach.
// Before depth 2, a multi-token operator of another precedence class
// can still separate the alternatives, so the substitution does not
// apply there.
if self.precedence_class && facts.depth >= 2 && self.resolve_frontier_iterate(number, facts)
{
return;
}
self.set_escape(number, ESCAPE);
if self.postfix.is_some() && self.state_has_take_skip_pair(number) {
// A budget escape of a take/skip state: the guarded take can
// still resolve it (eligibility is evaluated once the
// construction is complete).
self.guard_candidates.insert(number, None);
}
}
/// Whether a hybrid construction stops expanding a state at `depth`.
///
/// The state cap applies from depth 2. When an expansion exceeds the
/// state cap of the table or spends the visit budget, its state escapes
/// (see [`Self::run`]).
fn at_hybrid_frontier(&self, depth: usize) -> bool {
let state_cap = self.policy.hybrid_state_cap.min(self.max_states);
depth >= self.policy.hybrid_depth_cap || (self.states.len() >= state_cap && depth >= 2)
}
/// Moves the attempt out of the build, recording what it observed.
fn take_attempt(&mut self) -> Attempt {
self.attempt.decision = self.decision;
self.attempt.state_count = self.states.len();
self.attempt.facts = std::mem::take(&mut self.closure.facts);
self.attempt.exhausted |= self.closure.exhausted;
self.attempt.visits = self.closure.visits();
self.attempt.rule_visits = self.closure.take_rule_visits();
if self.attempt.descent_group_states > 0 {
self.attempt.descent = self.descent.take();
}
std::mem::take(&mut self.attempt)
}
/// Second chance for take-vetoed conflicts of an optional-postfix decision.
///
/// A vetoed conflict means some skip configuration left the dangling-else
/// discipline: it consumed tokens outside the decision's own take path. Such
/// a configuration is realizable at run time only on stacks whose
/// epsilon-pop chase from the block end reaches the guard root its first
/// out-of-discipline consumption passed through. So the conflict resolves to
/// take under a runtime stack test: defer when the chase can reach a root.
///
/// The roots ride on the skip configurations, so each guarded state tests
/// only the roots of the skip readings that are still alive in it. States
/// with equal danger sets share one guard group.
///
/// The eligibility rules are conservative. A widening-born skip
/// configuration is an analysis artifact unless it is rooted, a clean
/// out-of-discipline skip has no root for the guard to catch, a root that the
/// block end reaches without popping a frame makes the guard fire on every
/// stack, and a block end that cannot pop out of its rule means no root is
/// ever reachable (that case resolves to plain take accepts instead). A
/// state whose danger set is empty resolves to a plain take accept too,
/// when its take is real. The attempt bookkeeping is applied only once
/// every bail has passed.
fn finalize_guards(&mut self) {
self.finalize_guarded_takes();
if self.guard.is_none() {
self.finalize_guarded_iterates();
}
}
/// The guard roots of the configs of `alt` in a state.
fn state_roots(&self, state: i32, alt: i32) -> BTreeSet<i32> {
self.info.get(&state).map_or_else(BTreeSet::new, |facts| {
facts
.roots
.iter()
.filter(|((_, config_alt), _)| *config_alt == alt)
.flat_map(|(_, roots)| roots.iter().copied())
.collect()
})
}
/// Empty guard sets with the pass set of the grammar.
fn new_guard_sets(&self) -> GuardSets {
let regions = self
.guard_regions
.get_or_init(|| GuardRegions::of(self.atn));
GuardSets {
groups: Vec::new(),
pass: regions.pass().to_vec(),
}
}
/// The danger set of a guard-root set.
fn guard_danger(&self, roots: &BTreeSet<i32>) -> Vec<i32> {
self.guard_regions
.get_or_init(|| GuardRegions::of(self.atn))
.danger(roots)
}
/// The take pass of [`Self::finalize_guards`].
fn finalize_guarded_takes(&mut self) {
let Some(postfix) = self.postfix.clone() else {
return;
};
if self.guard_candidates.is_empty() {
return;
}
let candidates = std::mem::take(&mut self.guard_candidates);
// A root in the epsilon closure of the block end trips the guard on
// every stack, so it guards nothing.
let reachable_from_block = epsilon_closure(postfix.block_end_state);
let mut accepted: Vec<(i32, Option<BitSet>, BTreeSet<i32>, bool)> = Vec::new();
for (state, conflicting) in candidates {
let Some(facts) = self.info.get(&state) else {
continue;
};
if facts.predicated
|| !matches!(
facts.verdict,
Verdict::Escape(ESCAPE) | Verdict::Escape(CONFLICT_ESCAPE)
)
{
continue;
}
let roots = self.state_roots(state, POSTFIX_SKIP_ALT);
if roots.is_empty()
|| roots
.iter()
.any(|root| reachable_from_block.contains(*root as usize))
{
continue;
}
let mut eligible = true;
let mut real_take = false;
for config in self.states[state as usize].configs().get_items() {
let taint = taint_of(&facts.taint, config);
if config.get_alt() == POSTFIX_TAKE_ALT && taint & WIDENED_TAINT == 0 {
real_take = true;
}
if config.get_alt() != POSTFIX_SKIP_ALT {
continue;
}
// A widening-born skip is an analysis artifact unless it is
// rooted: then its bottom frame is a real follow state and the
// guard covers its realizability.
if taint & (WIDENED_TAINT | ROOTED_TAINT) == WIDENED_TAINT {
eligible = false;
break;
}
if taint & ROOTED_TAINT != 0
|| postfix.skip_mirrors(config.get_state(), config.get_context(), taint)
{
continue;
}
eligible = false;
break;
}
// Under `--static-dfa-only`, the state predicts the take on every
// stack without the guard, so the guard needs no proof that the
// take is real.
if !eligible || !(real_take || self.static_only) {
continue;
}
accepted.push((state, conflicting, roots, real_take));
}
if accepted.is_empty() {
return;
}
let chase_leaves_the_rule = {
let rule_stop =
self.atn.rule_to_stop_state[self.decision_state.get_rule_index() as usize];
rule_stop.get_state_number() >= 0
&& reachable_from_block.contains(rule_stop.get_state_number() as usize)
};
let mut guard = self.new_guard_sets();
for (state, conflicting, roots, real_take) in accepted {
let danger = if chase_leaves_the_rule {
self.guard_danger(&roots)
} else {
Vec::new()
};
if danger.is_empty() && !real_take {
// Without a guard, only a real take resolves the conflict.
continue;
}
if let Some(chosen) = conflicting {
self.attempt
.approximations
.retain(|conflict| conflict != &chosen);
self.attempt
.context_sensitive
.retain(|conflict| conflict != &chosen);
self.attempt.exact_ambiguities.push(chosen);
}
if danger.is_empty() {
// No guard can ever trip: resolve to a plain take accept.
if let Some(facts) = self.info.get_mut(&state) {
facts.verdict = Verdict::Accept(POSTFIX_TAKE_ALT);
facts.resolved_conflict = true;
}
self.attempt.take_rule_fires += 1;
continue;
}
let group = guard.group_of(danger);
if let Some(facts) = self.info.get_mut(&state) {
facts.verdict = Verdict::Escape(GUARDED);
facts.guarded_alt = POSTFIX_TAKE_ALT;
facts.guard_defer_alt = POSTFIX_SKIP_ALT;
facts.guard_group = group;
}
self.attempt.guarded_takes += 1;
}
if !guard.groups.is_empty() {
self.guard = Some(guard);
}
}
/// Second chance for iterate/exit conflicts that only foreign consumption
/// vetoed.
///
/// The canonical shape is Trino's `BETWEEN ... AND ...`: the exit lineage
/// consumes an operator token in a frame that is not an enclosing invocation
/// of the same loop. Such a conflict resolves to iterate (alt 1) under a
/// stack guard, or outright when no invoking state in the grammar can trip
/// it, because then the foreign consumption is unreachable on every real
/// stack and exit can never uniquely win. Like the guarded take, each state
/// tests only the roots of its own exit readings.
fn finalize_guarded_iterates(&mut self) {
if self.guard_iterate_candidates.is_empty() {
return;
}
let candidates = std::mem::take(&mut self.guard_iterate_candidates);
// A root in the epsilon closure of the rule stop trips the guard on
// every stack, so it guards nothing.
let rule_stop = self.atn.rule_to_stop_state[self.decision_state.get_rule_index() as usize];
let reachable_from_stop =
(rule_stop.get_state_number() >= 0).then(|| epsilon_closure(rule_stop));
let mut accepted: Vec<(i32, Option<BitSet>, BTreeSet<i32>, bool)> = Vec::new();
for (state, conflicting) in candidates {
let Some(facts) = self.info.get(&state) else {
continue;
};
if facts.predicated
|| !matches!(
facts.verdict,
Verdict::Escape(ESCAPE) | Verdict::Escape(CONFLICT_ESCAPE)
)
{
continue;
}
let roots = self.state_roots(state, EXIT_ALT);
if roots.is_empty()
|| reachable_from_stop.as_ref().is_some_and(|reachable| {
roots.iter().any(|root| reachable.contains(*root as usize))
})
{
continue;
}
let mut eligible = true;
let mut real_iterate = false;
for config in self.states[state as usize].configs().get_items() {
let taint = taint_of(&facts.taint, config);
if config.get_alt() == ITERATE_ALT
&& taint & (WIDENED_TAINT | FOREIGN_CONSUME_TAINT) == 0
{
real_iterate = true;
}
if config.get_alt() != EXIT_ALT {
continue;
}
// Foreign consumption must be rooted: then the stack guard
// covers its realizability. A widening-born exit is an analysis
// artifact unless it is rooted too.
if taint & FOREIGN_CONSUME_TAINT != 0 && taint & ROOTED_TAINT == 0 {
eligible = false;
break;
}
if taint & (WIDENED_TAINT | ROOTED_TAINT) == WIDENED_TAINT {
eligible = false;
break;
}
}
// Under `--static-dfa-only`, the state predicts the iterate on
// every stack without the guard, so the guard needs no proof
// that the iterate is real.
if !eligible || !(real_iterate || self.static_only) {
continue;
}
accepted.push((state, conflicting, roots, real_iterate));
}
if accepted.is_empty() {
return;
}
let mut guard = self.new_guard_sets();
for (state, conflicting, roots, real_iterate) in accepted {
let danger = self.guard_danger(&roots);
if danger.is_empty() && !real_iterate {
// Without a guard, only a real iterate resolves the conflict.
continue;
}
if danger.is_empty() && conflicting.is_none() && self.static_only {
// A frontier state without a guard stays an escape, so that
// the `--static-dfa-only` report counts its guess.
continue;
}
if let Some(conflicting) = conflicting {
self.attempt
.approximations
.retain(|conflict| conflict != &conflicting);
self.attempt
.context_sensitive
.retain(|conflict| conflict != &conflicting);
self.attempt.exact_ambiguities.push(conflicting);
}
let Some(facts) = self.info.get_mut(&state) else {
continue;
};
facts.resolved_conflict = true;
if danger.is_empty() {
facts.verdict = Verdict::Accept(ITERATE_ALT);
self.attempt.iterate_accepts += 1;
continue;
}
facts.verdict = Verdict::Escape(GUARDED);
facts.guarded_alt = ITERATE_ALT;
facts.guard_defer_alt = EXIT_ALT;
facts.guard_group = guard.group_of(danger);
self.attempt.guarded_iterates += 1;
}
if !guard.groups.is_empty() {
self.guard = Some(guard);
}
}
/// Attaches a [`ParserContinuation`] to every frontier escape state whose
/// config set the resumed SLL simulation can rebuild faithfully.
///
/// A continuation replays a config set without the input, so it must not
/// carry any approximation: a widened context would erase the caller that
/// only exists at run time, and a precedence-filtered set would need the
/// parser's precedence. Decisions that reach a left-recursive loop are
/// excluded for the same reason - a resumed simulation cannot reapply the
/// precedence filter the static construction applied.
fn attach_continuations(&mut self) {
if !self.allow_continuations {
return;
}
for number in 0..self.states.len() as i32 {
let Some(facts) = self.info.get(&number) else {
continue;
};
if facts.depth == 0 || facts.verdict != Verdict::Escape(ESCAPE) {
continue;
}
let configs = self.states[number as usize].configs();
if !continuation_is_faithful(configs, &facts.taint) {
continue;
}
let continuation = serialize_continuation(number as u32, configs, &facts.taint);
if continuation_words(&continuation) > MAX_CONTINUATION_WORDS {
continue;
}
if let Some(facts) = self.info.get_mut(&number) {
facts.continuation = Some(continuation);
}
}
}
/// Classifies a closed set and interns it as a DFA state.
fn intern(
&mut self,
closed: ClosedSet<'a>,
depth: usize,
) -> Option<&'sim DFAState<'sim, ATNConfigSet<'sim>>> {
let closed = self.closure.canonical_set(closed);
let (facts, effects) = self.classify(&closed, depth);
// An accept state with one viable alternative has no edges, and the
// runtime reads only its alternative. All such accept states of one
// alternative share one state, so they use one state of the state cap.
if let Verdict::Accept(alt) = facts.verdict
&& alt > 0
&& depth > 0
&& !facts.resolved_conflict
&& !facts.predicated
{
return self.accept_sink(alt, facts, effects);
}
let interned = self.closure.merged_config_set(&closed);
let mut proposed = ProposedDFAState::new(interned);
proposed.is_accept_state = matches!(facts.verdict, Verdict::Accept(_));
proposed.prediction = facts.accept_value();
let state = self.dfa.add_state(proposed, self.simulator);
let number = state.state_number();
let newly_interned = !self.info.contains_key(&number);
if number as usize >= self.states.len() {
self.states.push(state);
}
if !newly_interned {
// The same config set is reachable through paths whose taint
// differs, and a DFA state's verdict is decided once. Widening,
// precedence-guard or boundary taint on *any* path invalidates a
// verdict that trusted the config set, so the attempt gives up
// rather than emit a table the runtime could disagree with.
let state_configs = self.states[number as usize].configs();
let mut new_trust_taint = 0;
let mut verdict = Verdict::Decide;
let mut resolved_conflict = false;
let mut roots_grew = false;
let mut expanded = false;
if let Some(existing) = self.info.get_mut(&number) {
verdict = existing.verdict;
resolved_conflict = existing.resolved_conflict;
expanded = existing.expanded;
for (key, taint) in &facts.taint {
let entry = existing.taint.entry(*key).or_insert(0);
new_trust_taint |= *taint & !*entry & TRUST_TAINT;
*entry |= *taint;
}
for (key, roots) in &facts.roots {
let entry = existing.roots.entry(*key).or_default();
let before = entry.len();
entry.extend(roots.iter().copied());
roots_grew |= entry.len() != before;
}
// The fallback is a property of the whole set's taint, so a
// later boundary path can add one.
existing.fallback = fallback_of(state_configs, &existing.taint);
// A predicate on any path makes a later escape of the state a
// syntax error under `--static-dfa-only`, not a guess.
existing.predicated |= facts.predicated;
}
if new_trust_taint != 0 {
self.on_taint_increase(number, verdict, resolved_conflict);
} else if roots_grew && expanded && verdict == Verdict::Decide {
// The roots ride on the configs, so the successors of an
// expanded state must see the new roots too.
self.queue.push_back(number);
}
return Some(state);
}
if number as usize >= self.max_states {
return None;
}
if effects.conflict.is_some() {
self.attempt.first_conflict_state.get_or_insert(number);
}
self.commit(number, effects);
let decide = facts.verdict == Verdict::Decide;
self.info.insert(number, facts);
if decide && !self.attempt.overflow {
self.queue.push_back(number);
}
Some(state)
}
/// The shared accept state of alternative `alt`, interned on first use.
///
/// The shared state has its own config set: one config at the decision
/// state. No closure output contains the decision state, because it has
/// only epsilon transitions. So no other config set of the build becomes
/// this state, and the state keeps no fallback, taint, or roots of one
/// path.
fn accept_sink(
&mut self,
alt: i32,
facts: StateFacts,
effects: ClassifyEffects,
) -> Option<&'sim DFAState<'sim, ATNConfigSet<'sim>>> {
if let Some(state) = self.accept_sinks.get(&alt) {
return Some(*state);
}
let config = dbt_antlr_runtime::analysis::ATNConfig::new(
self.decision_state,
alt,
Some(PredictionContextRef::new_empty()),
);
let sink = ClosedSet {
configs: vec![config],
taint: Taint::default(),
roots: GuardRoots::default(),
};
let mut proposed = ProposedDFAState::new(self.closure.merged_config_set(&sink));
proposed.is_accept_state = true;
proposed.prediction = alt;
let state = self.dfa.add_state(proposed, self.simulator);
let number = state.state_number();
if number as usize >= self.states.len() {
self.states.push(state);
}
if number as usize >= self.max_states {
return None;
}
self.commit(number, effects);
self.accept_sinks.insert(alt, state);
self.info.insert(
number,
StateFacts {
fallback: 0,
taint: Taint::default(),
roots: GuardRoots::default(),
..facts
},
);
Some(state)
}
/// Accepts a budget-frontier state with the virtual alternative of the
/// shared-descent group that covers it, when there is one (see
/// [`DescentPlan::group_for`]).
fn accept_descent_group(&mut self, number: i32, facts: &StateFacts) -> bool {
let Some(plan) = &self.descent else {
return false;
};
let configs: Vec<_> = self.states[number as usize]
.configs()
.get_items()
.cloned()
.collect();
let mut live = BitSet::new();
for config in &configs {
live.insert(config.get_alt() as usize);
}
let Some(alt) = plan
.group_for(&live, facts.depth, &configs, &facts.taint)
.map(|group| group.virtual_alt)
else {
return false;
};
if let Some(facts) = self.info.get_mut(&number) {
facts.verdict = Verdict::Accept(alt);
// The group accept depends on the taint of the paths.
facts.resolved_conflict = true;
}
// The group resolves the frontier like an exact ambiguity: the table is
// not a plain LL(k) table.
self.attempt.exact_ambiguities.push(live);
self.attempt.descent_group_states += 1;
true
}
/// Whether the interned state's live alternatives are exactly the
/// take/skip pair of an optional-postfix decision.
fn state_has_take_skip_pair(&self, number: i32) -> bool {
let mut alts = BitSet::new();
for config in self.states[number as usize].configs().get_items() {
alts.insert(config.get_alt() as usize);
}
is_take_skip_pair(&alts)
}
/// Whether an iterate/exit attestation makes a state a candidate for the
/// guarded iterate: only foreign consumption of the exit lineage vetoes
/// the iterate.
///
/// With the adaptive fallback, the iterate lineage must also be real: a
/// guard that does not defer predicts the iterate without the adaptive
/// simulation. Under `--static-dfa-only`, an iterate lineage that consumes
/// foreign tokens is a candidate too (as in `CAST ( x AS INT64 )`, where
/// the alias reading reaches the `)` of a parenthesis). Without the guard,
/// such a state predicts the iterate on every stack. The guard predicts the
/// exit where the stack reaches a root of the exit lineage, and keeps the
/// iterate everywhere else.
fn is_iterate_guard_candidate(&self, attestation: i32) -> bool {
attestation == (ITERATE_REAL | EXIT_FOREIGN)
|| (self.static_only && attestation == EXIT_FOREIGN)
}
/// Resolves a budget-frontier state of a precedence class to iterate when
/// the iterate/exit substitution attestations permit it.
///
/// Returns `false` when the state is not the loop's iterate/exit pair, when
/// the loop's guarded alternatives are not simple, or when the attestation
/// is anything but a clean iterate reading - the caller then escapes the
/// state as usual.
fn resolve_frontier_iterate(&mut self, number: i32, facts: &StateFacts) -> bool {
let configs: Vec<dbt_antlr_runtime::analysis::ATNConfig<'_>> = self.states[number as usize]
.configs()
.get_items()
.cloned()
.collect();
let mut alts = BitSet::new();
for config in &configs {
alts.insert(config.get_alt() as usize);
}
if !is_iterate_exit_pair(&alts) {
return false;
}
let Some(block) = self.closure.loop_block() else {
return false;
};
if !block.guards_are_simple() {
return false;
}
// Under `--static-dfa-only`, an escape of the iterate/exit pair
// predicts the iterate on every stack, so a guard is never worse than
// the escape. The state stays an escape when no guard applies, so
// that the report counts it.
let covered = block.iterate_covers_exit(&configs, &facts.taint);
if !covered && !self.static_only {
return false;
}
let attestation = block.iterate_exit_attestation(&configs, &facts.taint);
if covered && attestation == ITERATE_REAL && self.keeps_caller_frames() {
if let Some(facts) = self.info.get_mut(&number) {
facts.verdict = Verdict::Accept(ITERATE_ALT);
facts.resolved_conflict = true;
}
self.attempt.exact_ambiguities.push(alts.iter().collect());
return true;
}
if self.postfix.is_none() && self.is_iterate_guard_candidate(attestation) {
self.guard_iterate_candidates.insert(number, None);
}
false
}
/// Reacts to a second path adding trust taint to an already interned
/// state.
///
/// The state's verdict was decided once, from the first path's taint, and a
/// state cannot be both trusted and untrusted: a table cannot carry a
/// verdict that any path contradicts. A trusted accept therefore becomes an
/// escape (hybrid) or invalidates the whole attempt (a non-hybrid table has
/// no escapes), while a decision state is queued again so its successors
/// see the union of both paths' taint.
fn on_taint_increase(&mut self, number: i32, verdict: Verdict, resolved_conflict: bool) {
match verdict {
// A single-viable-alternative accept does not depend on taint: no
// other alternative survives the lookahead, so there is nothing a
// different path could add. A *conflict-resolved* accept does: the
// min-alt argument only holds while every path that reaches the
// state is taint-free.
Verdict::Accept(alt) if resolved_conflict => {
// A group accept rests on the taint of the paths too (see
// `DescentPlan::group_for`).
if alt >= VIRTUAL_ALT_BASE {
self.attempt.descent_group_states -= 1;
}
// A frontier state resolved by substitution carries no
// conflict, so it degrades to a plain escape: the runtime
// restarts the adaptive simulation, and the report keeps the
// budget witness.
let conflicted = self
.info
.get(&number)
.is_some_and(|facts| !facts.conflicts.is_empty());
if conflicted {
self.attempt.first_conflict_state.get_or_insert(number);
}
if self.policy.hybrid {
if let Some(facts) = self.info.get_mut(&number) {
// The taint of every path, the first one included.
let approximated = facts
.taint
.values()
.any(|taint| taint & (WIDENED_TAINT | PRECPRED_TAINT) != 0);
facts.verdict = if conflicted {
Verdict::Escape(CONFLICT_ESCAPE)
} else {
Verdict::Escape(ESCAPE)
};
// A precedence class table never takes the conflict
// short cut: the runtime's full-context restart would
// have to reapply the precedence filter, which the
// table cannot carry.
if !approximated && !self.precedence_class {
facts.conflict_min_alt =
facts.conflicts.iter().min().copied().unwrap_or(0);
}
}
} else {
self.attempt.taint_conflict = true;
}
}
Verdict::Accept(_) | Verdict::Escape(_) => {}
Verdict::Decide => self.queue.push_back(number),
}
}
/// Records the attempt-level bookkeeping of a newly interned state.
fn commit(&mut self, number: i32, effects: ClassifyEffects) {
if let Some(candidate) = effects.guard_candidate {
self.guard_candidates.insert(number, candidate);
}
if let Some(candidate) = effects.guard_iterate_candidate {
self.guard_iterate_candidates.insert(number, candidate);
}
if effects.utrust {
self.attempt.utrust_resolutions += 1;
}
if let Some(alts) = effects.exact_ambiguity {
self.attempt.exact_ambiguities.push(alts);
}
if let Some(alts) = effects.approximation {
self.attempt.approximations.push(alts);
}
if let Some(alts) = effects.context_sensitive {
self.attempt.context_sensitive.push(alts);
}
if let Some(alts) = effects.conflict {
self.attempt.conflicts.push(alts);
}
if effects.fail_predicated {
self.attempt.predicated = true;
}
if effects.descent_group {
self.attempt.descent_group_states += 1;
}
if effects.abort {
self.attempt.stopped = true;
self.attempt.overflow = true;
}
}
/// Decides what a closed config set means: an accept, an escape, or a
/// point that needs successors.
fn classify(&mut self, closed: &ClosedSet<'a>, depth: usize) -> (StateFacts, ClassifyEffects) {
let mut effects = ClassifyEffects::default();
let mut fallback = 0;
let mut alts = BitSet::new();
let mut predicated = false;
for config in &closed.configs {
alts.insert(config.get_alt() as usize);
let taint = closed.taint_of(config);
if taint & BOUNDARY_TAINT != 0 && (fallback == 0 || config.get_alt() < fallback) {
fallback = config.get_alt();
}
if taint & PRED_TAINT != 0 {
predicated = true;
}
}
let mut facts = StateFacts {
depth,
verdict: Verdict::Decide,
taint: closed.taint.clone(),
fallback,
conflicts: Vec::new(),
resolved_conflict: false,
expanded: false,
conflict_min_alt: 0,
guarded_alt: 0,
guard_defer_alt: 0,
guard_group: 0,
roots: closed.roots.clone(),
continuation: None,
predicated: false,
};
if self.policy.hybrid && predicated {
// A config behind a predicate is only viable when that predicate
// holds for the current parse, so this state can never decide:
// predicated branches escape while the unpredicated ones stay
// static. A predicate in front of the decision itself makes the
// whole decision predicated.
if depth == 0 {
effects.fail_predicated = true;
} else {
facts.verdict = Verdict::Escape(ESCAPE);
facts.predicated = true;
}
return (facts, effects);
}
if alts.len() <= 1 {
facts.verdict = Verdict::Accept(alts.iter().next().map_or(0, |alt| alt as i32));
return (facts, effects);
}
let all_stops = !closed.configs.is_empty()
&& closed
.configs
.iter()
.all(|config| config.get_state().state_type() == ATNStateType::RuleStop);
let merged = self.closure.merged_config_set(closed);
// A state where every config sits at a rule stop is a conflict for the
// runtime (`compute_target_state` checks it before the SLL predicate):
// all alternatives already left the decision and only full-context
// prediction can tell which one the caller frame allows.
if !all_stops
&& !has_sll_conflict_terminating_prediction(self.scratch, PredictionMode::SLL, &merged)
{
return (facts, effects);
}
let subsets = conflicting_alt_subsets(self.scratch, &merged);
let exact = all_subsets_conflict(subsets.iter()) && all_subsets_equal(subsets.iter());
let mut widened_tainted = false;
let mut precedence_tainted = false;
let mut any_boundary = false;
let mut all_boundary = true;
for config in &closed.configs {
let taint = closed.taint_of(config);
if taint & WIDENED_TAINT != 0 {
widened_tainted = true;
}
if taint & PRECPRED_TAINT != 0 {
precedence_tainted = true;
}
if taint & BOUNDARY_TAINT != 0 {
any_boundary = true;
}
// "All configs crossed the boundary" only holds when no path
// reached this set from inside the decision.
if taint & BOUNDARY_TAINT == 0 || taint & INTERIOR_TAINT != 0 {
all_boundary = false;
}
}
let conflicting = get_alts(subsets.into_iter());
facts.conflicts = conflicting.iter().map(|alt| alt as i32).collect();
// Enter/exit ambiguity of a precedence loop, resolved to iterate by
// substitution. When the exit lineage consumed every scanned token
// inside the operator loop, no foreign consumption remains. Then every
// exit derivation maps onto an iterate derivation of the same
// sentence.
//
// The mapping is precedence-safe. The outer reading consumes the
// operator through the same loop alternative, with the same guard and
// the same operand precedence. The iterate lineage can always take the
// free loop exit and rejoin the continuation the exit lineage heads
// for. So exit never becomes uniquely viable, and the runtime answers
// iterate whenever it terminates.
//
// Exactness is not required. Inexact subsets are the common case:
// they diverge because exit carries caller continuations that iterate
// only rejoins after its free exit.
//
// Three vetoes decide the state: foreign consumption outside the loop
// block, pending token obligations the iterate reading does not owe,
// and a missing iterate attestation. A compound guarded alternative
// breaks the mapping altogether (see `LoopBlock`).
//
// The vetoes read the frames of the contexts. The widened attempt
// drops every caller frame, so it does not resolve the conflict.
if let Some(block) = self.closure.loop_block()
&& block.guards_are_simple()
&& is_iterate_exit_pair(&conflicting)
{
let attestation = block.iterate_exit_attestation(&closed.configs, &closed.taint);
if attestation == ITERATE_REAL && self.keeps_caller_frames() {
facts.resolved_conflict = true;
effects.exact_ambiguity = Some(conflicting.clone());
facts.verdict = Verdict::Accept(ITERATE_ALT);
return (facts, effects);
}
if self.policy.hybrid
&& self.postfix.is_none()
&& self.is_iterate_guard_candidate(attestation)
{
// Vetoed only by foreign consumption of the exit lineage: a
// candidate for the guarded iterate, resolved once the
// construction is complete.
effects.guard_iterate_candidate = Some(Some(conflicting.clone()));
}
}
// Optional-postfix take rule: resolve a take/skip conflict to take when
// every skip configuration mirrors the take reading and a non-widened
// take configuration attests take viability. Like the iterate/exit
// vetoes, the mirror check reads the frames of the contexts, so the
// widened attempt does not apply the rule.
if let Some(postfix) = self.postfix.clone()
&& is_take_skip_pair(&conflicting)
{
let mut mirror_ok = true;
let mut real_take = false;
for config in &closed.configs {
let taint = closed.taint_of(config);
if config.get_alt() == POSTFIX_SKIP_ALT
&& !postfix.skip_mirrors(config.get_state(), config.get_context(), taint)
{
mirror_ok = false;
}
if config.get_alt() == POSTFIX_TAKE_ALT && taint & WIDENED_TAINT == 0 {
real_take = true;
}
}
if mirror_ok && real_take && self.keeps_caller_frames() {
self.attempt.take_rule_fires += 1;
facts.resolved_conflict = true;
effects.exact_ambiguity = Some(conflicting.clone());
facts.verdict = Verdict::Accept(POSTFIX_TAKE_ALT);
return (facts, effects);
}
if self.policy.hybrid && (real_take || self.static_only) {
// Vetoed only by the mirror check: a candidate for the guarded
// take, resolved once the construction is complete.
effects.guard_candidate = Some(Some(conflicting.clone()));
}
}
let untrusted = precedence_tainted
|| widened_tainted
|| (any_boundary && !all_boundary)
|| !self.uniform_pop_depths(&conflicting, any_boundary, all_boundary)
|| !self.policy.trust_exact_ambiguity;
if !untrusted && exact {
facts.resolved_conflict = true;
effects.exact_ambiguity = Some(conflicting.clone());
facts.verdict = Verdict::Accept(conflicting.iter().next().map_or(0, |alt| alt as i32));
return (facts, effects);
}
if depth > 0 {
let min_alt = self.utrust_min_alt(closed, &conflicting, any_boundary, all_boundary);
if min_alt > 0 {
facts.resolved_conflict = true;
effects.utrust = true;
effects.exact_ambiguity = Some(conflicting);
facts.verdict = Verdict::Accept(min_alt);
return (facts, effects);
}
}
// A conflict among the members of a shared-descent group is resolved
// by the group's tail dispatch after one parse of the shared rule.
if self.policy.hybrid
&& let Some(alt) = self
.descent
.as_ref()
.and_then(|plan| plan.group_for(&alts, depth, &closed.configs, &closed.taint))
.map(|group| group.virtual_alt)
{
effects.guard_candidate = None;
effects.exact_ambiguity = Some(conflicting);
effects.descent_group = true;
facts.resolved_conflict = true;
facts.verdict = Verdict::Accept(alt);
return (facts, effects);
}
if untrusted {
effects.approximation = Some(conflicting.clone());
} else {
effects.context_sensitive = Some(conflicting.clone());
}
effects.conflict = Some(facts.conflicts.clone());
if self.policy.hybrid {
facts.verdict = Verdict::Escape(CONFLICT_ESCAPE);
// The conflict already ended Stage 1, so the runtime can resume at
// Stage 2 without re-walking, but only while the set is a faithful
// SLL set: a widened or precedence-filtered set is an approximation
// whose conflicting alternatives the runtime may not reproduce.
// A precedence class table never takes the conflict short cut: the
// runtime's full-context restart would have to reapply the
// precedence filter, which the table cannot carry.
if depth > 0 && !widened_tainted && !precedence_tainted && !self.precedence_class {
facts.conflict_min_alt = conflicting.iter().next().map_or(0, |alt| alt as i32);
}
} else if self.policy.abort_on_untrusted_conflict {
effects.abort = true;
}
(facts, effects)
}
/// Whether a rule call keeps the frame of its caller, at least up to the
/// widening bound. The widened attempt gives every call an empty context.
const fn keeps_caller_frames(&self) -> bool {
self.policy.depth_bound > 0
}
fn set_escape(&mut self, number: i32, marker: i32) {
if let Some(facts) = self.info.get_mut(&number) {
if matches!(facts.verdict, Verdict::Escape(_)) {
return;
}
facts.verdict = Verdict::Escape(marker);
}
}
/// The prefix-hijack hazards of the escape states that
/// `--static-dfa-only` resolves to an alternative, for at most
/// [`HAZARD_STATES`] of the shallowest of them.
fn state_hazards(&mut self) -> HashMap<i32, StateHazard> {
let mut candidates: Vec<(usize, i32)> = self
.info
.iter()
.filter(|(_, facts)| {
matches!(facts.verdict, Verdict::Escape(ESCAPE | CONFLICT_ESCAPE))
&& !facts.predicated
})
.map(|(number, facts)| (facts.depth, *number))
.collect();
candidates.sort_unstable();
let mut hazards = HashMap::new();
// The analyzed states of each tie-break group, and whether one of
// them is a hijack.
let mut groups: HashMap<(i32, Vec<i32>), (usize, bool)> = HashMap::new();
let mut analyzed = 0;
for (_, number) in candidates {
if analyzed == HAZARD_STATES {
break;
}
let Some(facts) = self.info.get(&number).cloned() else {
continue;
};
let configs: Vec<_> = self.states[number as usize]
.configs()
.get_items()
.cloned()
.collect();
let alts: BTreeSet<i32> = configs
.iter()
.map(|config| config.get_alt())
.filter(|alt| *alt > 0)
.collect();
let conflicts: BTreeSet<i32> = facts
.conflicts
.iter()
.copied()
.filter(|alt| *alt > 0)
.collect();
// The same choice as `StaticDfaTable::resolve_escapes`.
let candidates = if conflicts.is_empty() {
&alts
} else {
&conflicts
};
let Some(&chosen) = candidates.first() else {
continue;
};
let dropped: Vec<i32> = candidates.iter().copied().skip(1).collect();
if dropped.is_empty() {
continue;
}
let group = groups.entry((chosen, dropped.clone())).or_default();
if group.1 || group.0 == HAZARD_STATES_PER_GROUP {
continue;
}
group.0 += 1;
analyzed += 1;
let verdict =
hazard::analyze(&mut self.closure, &configs, &facts.taint, chosen, &dropped);
group.1 = matches!(verdict, hazard::HijackVerdict::Hijack { .. });
let greedy = self.is_greedy_choice(&dropped);
hazards.insert(number, StateHazard { verdict, greedy });
}
hazards
}
/// The stack-hijack hazards of the guarded states of `table`, for at most
/// [`GUARD_HAZARD_STATES`] of them and [`GUARD_HAZARD_STATES_PER_GROUP`]
/// of each guard group. The frontier states come first, then the
/// shallowest states: a frontier state stops where the lookahead budget
/// cut the guarded alternative off, and so can hide a hijack that a
/// conflict state shows the end of.
fn compute_guard_hazards(&mut self, table: &mut StaticDfaTable) {
let mut candidates: Vec<(bool, usize, usize)> = table
.states
.iter()
.enumerate()
.filter(|(_, state)| {
state.is_guarded()
&& state.guarded_alt > 0
&& state.guard_defer_alt > 0
&& !state.predicated
})
.map(|(index, state)| (!state.conflicts.is_empty(), state.depth, index))
.collect();
candidates.sort_unstable();
let decision_rule = self.decision_state.get_rule_index();
// The stacks of each guard group, the analyzed states of the group,
// and whether one of them is a hijack.
let mut groups: HashMap<u32, (hazard::GuardChains, usize, bool)> = HashMap::new();
let mut analyzed = 0;
for (_, _, index) in candidates {
if analyzed == GUARD_HAZARD_STATES {
break;
}
let state = &table.states[index];
let (group_index, guarded_alt, defer_alt) =
(state.guard_group, state.guarded_alt, state.guard_defer_alt);
let Some(witness) = table.witness(index) else {
continue;
};
let group = groups.entry(group_index).or_insert_with(|| {
let danger = table
.guard_groups
.get(group_index as usize)
.map_or(&[][..], Vec::as_slice);
let chains = hazard::guard_chains(
self.closure.call_sites(),
decision_rule,
self.closure.precedence(),
danger,
&table.guard_pass,
);
(chains, 0, false)
});
if group.2 || group.1 == GUARD_HAZARD_STATES_PER_GROUP {
continue;
}
group.1 += 1;
analyzed += 1;
let verdict = hazard::analyze_guard(
&mut self.closure,
self.decision_state,
&group.0,
&witness,
(guarded_alt, defer_alt),
);
group.2 = matches!(verdict, StackHijackVerdict::Hijack { .. });
table.states[index].stack_hazard = Some(verdict);
}
}
/// Whether a guess that drops `dropped` is the greedy choice of the
/// decision: it drops the exit of a loop, or the skip of an optional block
/// or element.
fn is_greedy_choice(&self, dropped: &[i32]) -> bool {
let transitions = self.decision_state.get_transitions();
match self.decision_state.state_type() {
ATNStateType::StarLoopEntry | ATNStateType::PlusLoopBack => dropped == [2],
_ => {
let last = transitions.len();
dropped == [last as i32]
&& transitions.last().is_some_and(|transition| {
transition.get_target().state_type() == ATNStateType::BlockEnd
})
}
}
}
fn snapshot(&self, hazards: &HashMap<i32, StateHazard>) -> StaticDfaTable {
let mut states: Vec<StaticDfaState> = self
.states
.iter()
.map(|state| {
let number = state.state_number();
let facts = self.info.get(&number);
let escape = facts.is_some_and(|facts| matches!(facts.verdict, Verdict::Escape(_)));
let viable_alts = if escape {
let alts: BTreeSet<i32> = state
.configs()
.get_items()
.map(|config| config.get_alt())
.filter(|alt| *alt > 0)
.collect();
alts.into_iter().collect()
} else {
Vec::new()
};
StaticDfaState {
accept: facts.map_or(0, StateFacts::accept_value),
fallback: facts.map_or(0, |facts| facts.fallback),
depth: facts.map_or(0, |facts| facts.depth),
conflicts: facts
.map(|facts| facts.conflicts.clone())
.unwrap_or_default(),
conflict_min_alt: facts.map_or(0, |facts| facts.conflict_min_alt),
guarded_alt: facts.map_or(0, |facts| facts.guarded_alt),
guard_defer_alt: facts.map_or(0, |facts| facts.guard_defer_alt),
guard_group: facts.map_or(0, |facts| facts.guard_group),
continuation: facts.and_then(|facts| facts.continuation.clone()),
viable_alts,
predicated: facts.is_some_and(|facts| facts.predicated),
resolution: None,
hazard: hazards.get(&number).cloned(),
stack_hazard: None,
edges: Vec::new(),
}
})
.collect();
let mut per_state: Vec<Vec<(i32, usize)>> = vec![Vec::new(); states.len()];
for (from, symbol, to) in self.dfa.enumerate_edges() {
let from = from.state_number() as usize;
let to = to.state_number() as usize;
if from < per_state.len() && to < states.len() {
per_state[from].push((symbol as i32 - 1, to));
}
}
for (index, mut edges) in per_state.into_iter().enumerate() {
edges.sort_unstable();
let mut merged: Vec<StaticDfaEdge> = Vec::new();
for (token, target) in edges {
match merged.last_mut() {
Some(edge) if edge.target == target && edge.hi + 1 == token => edge.hi = token,
_ => merged.push(StaticDfaEdge {
lo: token,
hi: token,
target,
}),
}
}
states[index].edges = merged;
}
let mut table = StaticDfaTable::finish(self.decision, states);
if let Some(guard) = &self.guard {
table.guard_groups.clone_from(&guard.groups);
table.guard_pass.clone_from(&guard.pass);
}
table
}
/// `true` when the conflicting alternatives leave the decision after the
/// same number of tokens: the ambiguity is then faithful to the runtime.
fn uniform_pop_depths(
&self,
conflicting: &BitSet,
any_boundary: bool,
all_boundary: bool,
) -> bool {
if !any_boundary {
return true;
}
if !all_boundary {
return false;
}
if self.policy.depth_bound == 0 {
return false;
}
let alt_starts: Vec<ATNStateRef> = self
.decision_state
.get_transitions()
.iter()
.map(|transition| transition.get_target())
.collect();
let mut reference: Option<usize> = None;
for alt in conflicting {
if alt == 0 || alt > alt_starts.len() {
return false;
}
let depths = self.completion_depths(alt_starts[alt - 1]);
if depths.len() != 1 || depths.contains(VARIABLE_DEPTH) {
return false;
}
let depth = depths.iter().next().unwrap();
match reference {
None => reference = Some(depth),
Some(known) if known != depth => return false,
Some(_) => {}
}
}
true
}
fn completion_depths(&self, alt_start: ATNStateRef) -> &'a BitSet {
let state_number = usize::try_from(alt_start.get_state_number())
.expect("an alternative start is a real ATN state");
self.completion_depths[state_number].get_or_init(|| {
let mut visiting = BTreeSet::new();
let mut budget = 100_000_i32;
token_counts_to_stop(alt_start, &mut visiting, &mut budget)
})
}
/// The "untrusted-but-uniform" resolution: when every conflicting state is
/// attested by a faithful config of the lowest alternative, predict it.
fn utrust_min_alt(
&mut self,
closed: &ClosedSet<'a>,
conflicting: &BitSet,
any_boundary: bool,
all_boundary: bool,
) -> i32 {
if any_boundary && !all_boundary {
return 0;
}
let Some(min_alt) = conflicting.iter().next() else {
return 0;
};
let min_alt = min_alt as i32;
let mut clean_by_state: HashMap<i32, Vec<dbt_antlr_runtime::analysis::ATNConfig<'a>>> =
HashMap::new();
for config in &closed.configs {
if config.get_alt() != min_alt {
continue;
}
// Only a config whose every path stayed inside the decision and
// never had its context widened or its precedence guard assumed can
// attest for the lowest alternative.
if closed.taint_of(config) & (BOUNDARY_TAINT | WIDENED_TAINT | PRECPRED_TAINT) != 0 {
continue;
}
clean_by_state
.entry(config.get_state().get_state_number())
.or_default()
.push(config.clone());
}
if clean_by_state.is_empty() {
return 0;
}
let mut by_state_contexts: HashMap<i32, Vec<PredictionContextRef<'a>>> = HashMap::new();
for config in &closed.configs {
// Widening removes frames from the context of a competing config,
// so its context does not show the continuation of its real
// stacks. No attestation can match such a context, and equal
// contexts after widening can make a conflict that the runtime
// never sees.
if config.get_alt() != min_alt && closed.taint_of(config) & WIDENED_TAINT != 0 {
return 0;
}
let state_number = config.get_state().get_state_number();
let context = config.get_context().expect("config has a context");
let entries = by_state_contexts.entry(state_number).or_default();
if !entries.contains(&context) {
entries.push(context);
}
}
for (state_number, contexts) in by_state_contexts {
let Some(attestations) = clean_by_state.get(&state_number) else {
return 0;
};
for context in contexts {
let assured = attestations.iter().any(|config| {
top_prefix_wildcard_match(
config.get_context().expect("config has a context"),
context,
self.scratch,
)
});
if !assured {
return 0;
}
}
}
min_alt
}
}
/// `true` when the config set can be replayed without the input.
///
/// Widening, an unevaluated precedence guard, or a predicate each stand for
/// information only the run time has, so a continuation never carries them.
fn continuation_is_faithful(configs: &ATNConfigSet<'_>, taint: &Taint) -> bool {
// `INTERIOR_TAINT` and `BOUNDARY_TAINT` are facts about where the config
// came from, not approximations: the replay reproduces them.
const APPROXIMATION: i32 = WIDENED_TAINT | PRECPRED_TAINT | PRED_TAINT;
configs.get_items().all(|config| {
let taint = taint
.get(&(config.get_state().get_state_number(), config.get_alt()))
.copied()
.unwrap_or(0);
taint & APPROXIMATION == 0
})
}
fn continuation_words(continuation: &ParserContinuation) -> usize {
let contexts = continuation
.contexts
.iter()
.map(|node| match node {
ContinuationContextNode::Singleton { .. } => 3,
ContinuationContextNode::Array { parents, .. } => 1 + parents.len() * 2,
})
.sum::<usize>();
// state + node count + config count, plus one config entry each.
3 + contexts + continuation.configs.len() * 4
}
/// Serializes the closed config set of a frontier escape state.
///
/// The contexts become a topological node table: parents are always written
/// before the nodes that name them, so the run time rebuilds the DAG in one
/// pass.
fn serialize_continuation(
state: u32,
configs: &ATNConfigSet<'_>,
taint: &Taint,
) -> ParserContinuation {
fn return_state_number(return_state: ATNStateRef) -> i32 {
if return_state == ATNStateRef::empty_return() {
-1
} else {
return_state.get_state_number()
}
}
fn intern_context<'a>(
context: PredictionContextRef<'a>,
nodes: &mut Vec<ContinuationContextNode>,
seen: &mut HashMap<usize, u32>,
) -> u32 {
const EMPTY_CONTEXT: u32 = u32::MAX;
if context.is_empty() {
return EMPTY_CONTEXT;
}
let key = context.as_ref() as *const PredictionContext<'a> as usize;
if let Some(&index) = seen.get(&key) {
return index;
}
let node = if context.length() == 1 {
ContinuationContextNode::Singleton {
parent: context
.get_parent(0)
.map_or(EMPTY_CONTEXT, |parent| intern_context(parent, nodes, seen)),
return_state: return_state_number(context.get_return_state(0)),
}
} else {
let mut parents = Vec::with_capacity(context.length());
let mut return_states = Vec::with_capacity(context.length());
for index in 0..context.length() {
parents.push(
context
.get_parent(index)
.map_or(EMPTY_CONTEXT, |parent| intern_context(parent, nodes, seen)),
);
return_states.push(return_state_number(context.get_return_state(index)));
}
ContinuationContextNode::Array {
parents,
return_states,
}
};
let index = nodes.len() as u32;
nodes.push(node);
seen.insert(key, index);
index
}
let mut contexts = Vec::new();
let mut seen = HashMap::new();
let mut entries = Vec::with_capacity(configs.length());
for config in configs.get_items() {
let context = config.get_context().map_or(u32::MAX, |context| {
intern_context(context, &mut contexts, &mut seen)
});
let taint = taint
.get(&(config.get_state().get_state_number(), config.get_alt()))
.copied()
.unwrap_or(0);
entries.push(ContinuationConfigEntry {
state: config.get_state().get_state_number(),
alt: config.get_alt(),
context,
outer_depth: i32::from(taint & BOUNDARY_TAINT != 0),
});
}
ParserContinuation {
state,
contexts,
configs: entries,
}
}
fn fallback_of(configs: &ATNConfigSet<'_>, taint: &Taint) -> i32 {
let mut fallback = 0;
for config in configs.get_items() {
let key = (config.get_state().get_state_number(), config.get_alt());
if taint.get(&key).copied().unwrap_or(0) & BOUNDARY_TAINT != 0
&& (fallback == 0 || config.get_alt() < fallback)
{
fallback = config.get_alt();
}
}
fallback
}
fn token_counts_to_stop(
state: ATNStateRef,
visiting: &mut BTreeSet<i32>,
budget: &mut i32,
) -> BitSet {
let mut out = BitSet::with_capacity(VARIABLE_DEPTH + 1);
if state.state_type() == ATNStateType::RuleStop {
out.insert(0);
return out;
}
let previous_budget = *budget;
*budget -= 1;
if previous_budget <= 0 || !visiting.insert(state.get_state_number()) {
out.insert(VARIABLE_DEPTH);
return out;
}
for transition in state.get_transitions() {
let sub = if let Some(rule) =
transition.try_as::<dbt_antlr_runtime::analysis::RuleTransition>()
{
let inner = token_counts_to_stop(rule.get_target(), visiting, budget);
let rest = token_counts_to_stop(rule.follow_state, visiting, budget);
sum_depths(&inner, &rest)
} else if transition.is_epsilon() {
token_counts_to_stop(transition.get_target(), visiting, budget)
} else {
shift_depths(&token_counts_to_stop(
transition.get_target(),
visiting,
budget,
))
};
out.union_with(&sub);
}
visiting.remove(&state.get_state_number());
out
}
fn shift_depths(input: &BitSet) -> BitSet {
let mut out = BitSet::with_capacity(VARIABLE_DEPTH + 1);
if input.contains(VARIABLE_DEPTH) {
out.insert(VARIABLE_DEPTH);
return out;
}
for depth in input {
if depth + 1 > MAX_TRACKED_DEPTH {
out.insert(VARIABLE_DEPTH);
return out;
}
out.insert(depth + 1);
}
out
}
fn sum_depths(left: &BitSet, right: &BitSet) -> BitSet {
let mut out = BitSet::with_capacity(VARIABLE_DEPTH + 1);
if left.contains(VARIABLE_DEPTH) || right.contains(VARIABLE_DEPTH) {
out.insert(VARIABLE_DEPTH);
return out;
}
for a in left {
for b in right {
if a + b > MAX_TRACKED_DEPTH {
out.insert(VARIABLE_DEPTH);
return out;
}
out.insert(a + b);
}
}
out
}
/// `true` when every branch of `shadow` reaches `exact`, treating a widened
/// joint (`$` under a return state) as matching anything.
fn top_prefix_wildcard_match<'a>(
shadow: PredictionContextRef<'a>,
exact: PredictionContextRef<'a>,
scratch: &'a Bump,
) -> bool {
if exact.length() > 1 {
for i in 0..exact.length() {
if !top_prefix_wildcard_match(shadow, branch(exact, i, scratch), scratch) {
return false;
}
}
return true;
}
if shadow.is_empty() {
return true;
}
if shadow.length() > 1 {
for i in 0..shadow.length() {
if top_prefix_wildcard_match(branch(shadow, i, scratch), exact, scratch) {
return true;
}
}
return false;
}
if exact.is_empty() {
return false;
}
let return_state = shadow.get_return_state(0);
if return_state == ATNStateRef::empty_return() {
return true;
}
if exact.get_return_state(0) == ATNStateRef::empty_return() {
return false;
}
return_state == exact.get_return_state(0)
&& top_prefix_wildcard_match(
shadow
.get_parent(0)
.unwrap_or_else(PredictionContextRef::new_empty),
exact
.get_parent(0)
.unwrap_or_else(PredictionContextRef::new_empty),
scratch,
)
}
fn branch<'a>(
context: PredictionContextRef<'a>,
index: usize,
scratch: &'a Bump,
) -> PredictionContextRef<'a> {
let parent = context
.get_parent(index)
.unwrap_or_else(PredictionContextRef::new_empty);
let return_state = context.get_return_state(index);
if return_state == ATNStateRef::empty_return() && parent.is_empty() {
return PredictionContextRef::new_empty();
}
PredictionContextRef::from(
scratch.alloc(PredictionContext::new_singleton(Some(parent), return_state)),
)
}