dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! `--static-parser-dfa` optimization pass (parser scope).
//!
//! The pass builds the static prediction tables of the prediction decisions of
//! every root parser unit, and hands the emitter both the tables
//! (which it turns into `dfa_predict` call sites) and the `SDFA` table image
//! that the generated parser embeds beside its packed parser ATN. It reads the
//! runtime ATN of the compiled unit directly, so the analysis never serializes
//! or deserializes words.
//!
//! `--dump-dfas` renders the tables of the selected decisions to stdout, and
//! `--profile-decisions` renders the time and the work that the table builds
//! of each decision took. These flags imply `--report-only`. The optimization
//! manifest of every run lists every decision with its kind
//! (`decisionInventory`), so a build that writes the generated files also
//! writes the inventory.
//!
//! With the adaptive fallback, a decision without a table, or with a table
//! that escapes, is normal: the generated parser calls `adaptive_predict`
//! there, and the pass reports nothing.
//!
//! A decision that spends the visit budget of the analysis gets a warning
//! (`G4S193`) in every mode, because such a decision makes the code generation
//! slow. A rule that many call sites enter gets a warning (`G4S194`) for each
//! block with many single-token alternatives that do not fold into one token
//! set. The analysis follows each of these alternatives at each site.
//!
//! Under `--static-dfa-only`, the pass resolves the escape states of every
//! partial table statically (see `parser_dfa::static_only`). A decision that
//! still needs `adaptive_predict` is an error (`G4S190`), and a decision with
//! resolved escape states gets a warning (`G4S192`). The warning names the
//! alternatives that each guess chooses and drops, and ranks the guesses by
//! their prefix-hijack hazard (see `parser_dfa::hazard`). For guarded states,
//! the warning also names the calls where the stack guard defers: the rule,
//! the label of the alternative, and the line. `--dump-dfas` shows this caller
//! for each invoking state of a danger set, for example
//! `danger=[47 (query:25), 56 (expr#cast:30)]`. The warning also shows the
//! stack-hijack hazard of the guards (see `parser_dfa::hazard`): a guard that
//! defers although the guarded alternative reads a token that the defer
//! alternative cannot read. `--dump-dfas` shows each such hazard on the line
//! of its guard group.
//!
//! Each decision has an analysis budget (see `parser_dfa::budget`). The
//! budget options of the grammar, its rules, and its blocks set it.

use std::collections::BTreeMap;
use std::fmt;
use std::time::{Duration, Instant};

use minijinja::Value;

use super::config::AtnFallback;
use super::descriptor::PassDescriptor;
use super::manifest::{object, option, source_location_value, source_value};
use dbt_antlr_runtime::dfa::static_parser_dfa::{
    StaticParserTables as RuntimeTables, VIRTUAL_ALT_BASE,
};

use super::parser_dfa::{
    AttemptOutcome, BudgetCutoff, BudgetLimits, CONFLICT_ESCAPE, DecisionBudget, DecisionKind,
    DecisionOutcome, DecisionTableBuilder, DescentPlan, DescentRules, ESCAPE, EscapeResolution,
    EscapeResolutions, GuardGroup, HazardLevel, HijackVerdict, NoTableReason,
    PARTIAL_MIN_COVERAGE_PERCENT, ParserDfaBudgets, StackHijackVerdict, StaticDfaTable, TieBreak,
    has_non_budget_option, minimized_states,
};
use crate::grammar::atn::{CompiledParser, FinalizedTransitionKind, left_corner_rules};
use crate::grammar::diagnostic::Diagnostic;
use crate::grammar::frontend::SourceSpan;
use crate::grammar::model::{
    Alternative, Block, Element, ElementKind, ModelNodeId, Quantifier, RecognizerModel, Rule,
    RuleKind, Terminal,
};
use crate::grammar::provenance::Origin;
use crate::grammar::source::SourceSet;
use crate::grammar::transform::SafetyClass;
use crate::optimization::{AlternativeNames, alternative_names};

/// The diagnostic code of the errors of the decisions that still need
/// `adaptive_predict` under `--static-dfa-only`.
const NOT_FULLY_STATIC: &str = "G4S190";
/// The diagnostic code of an unmatched `--dump-dfas` selector.
const DUMP_SELECTOR_NO_MATCH: &str = "G4S191";
/// The diagnostic code of a decision whose escape states `--static-dfa-only`
/// resolved statically.
const STATIC_ONLY_RESOLVED: &str = "G4S192";
/// The diagnostic code of a decision whose analysis spent the visit budget.
const VISIT_BUDGET_SPENT: &str = "G4S193";
/// The diagnostic code of a block of single-token alternatives that do not
/// fold into one token set, in a rule with many call sites.
const TOKEN_BRANCHES: &str = "G4S194";
/// The tie-break groups that a `G4S192` warning names at most.
const TIE_BREAK_GROUPS: usize = 3;
/// The danger callers that a `G4S192` warning names at most.
const DANGER_CALLERS: usize = 3;
/// The stack-hijack hazards that a `G4S192` warning shows at most.
const STACK_HIJACKS: usize = 3;

/// The minimum number of call sites that enter a rule, for a `G4S194`
/// warning.
const TOKEN_BRANCH_ENTRIES: usize = 20;
/// The minimum number of single-token alternatives in a block, for a `G4S194`
/// warning.
const TOKEN_BRANCH_ALTERNATIVES: usize = 64;

/// The number of rules that a `G4S193` warning and a profile row name.
const HOT_RULES: usize = 3;
/// The number of decisions in the table of `--profile-decisions`.
const PROFILE_ROWS: usize = 20;
/// A decision whose table builds take this long is slow.
const SLOW_DECISION: Duration = Duration::from_millis(500);

/// The static tables of one parser unit, as the emitter and the embedded
/// table image need them.
#[derive(Clone, Debug, Default)]
pub(crate) struct StaticParserTables {
    tables: RuntimeTables,
    /// `true` per decision that has at least one static table.
    has_table: Vec<bool>,
    /// `true` per decision that keeps an adaptive path, so the generated code
    /// has to defer to `adaptive_predict` when prediction returns no
    /// alternative.
    defers: Vec<bool>,
    /// The shared-descent groups each decision's table accepts with.
    descent: Vec<Option<DescentPlan>>,
    atn_fallback: AtnFallback,
}

impl StaticParserTables {
    fn new(results: &[DecisionOutcome], atn_fallback: AtnFallback) -> Self {
        let mut has_table = Vec::with_capacity(results.len());
        let mut defers = Vec::with_capacity(results.len());
        for result in results {
            has_table.push(result.has_table());
            defers.push(!result.is_fully_static());
        }
        Self {
            tables: super::parser_dfa::build_tables(results),
            has_table,
            defers,
            descent: results
                .iter()
                .map(|result| result.descent.clone())
                .collect(),
            atn_fallback,
        }
    }

    /// `true` when the decision predicts from a static table.
    pub(crate) fn has_table(&self, decision: usize) -> bool {
        self.has_table.get(decision).copied().unwrap_or(false)
    }

    /// `true` when the decision still reaches the adaptive simulation.
    pub(crate) fn defers(&self, decision: usize) -> bool {
        self.defers.get(decision).copied().unwrap_or(false)
    }

    /// The shared-descent groups the decision's table accepts with, when it
    /// has any: the decision must be emitted as a `DescentAltBlock`.
    pub(crate) fn descent(&self, decision: usize) -> Option<&DescentPlan> {
        self.descent.get(decision).and_then(Option::as_ref)
    }

    /// The shared rules of every decision's groups.
    pub(crate) fn shared_rules(&self) -> impl Iterator<Item = usize> + '_ {
        self.descent
            .iter()
            .flatten()
            .flat_map(|plan| plan.groups.iter().map(|group| group.rule))
    }

    /// Whether the generated parser can call `adaptive_predict` at all.
    pub(crate) const fn atn_fallback(&self) -> AtnFallback {
        self.atn_fallback
    }

    /// The `SDFA` table image, empty when the unit has no table.
    pub(crate) fn words(&self) -> Vec<u32> {
        self.tables.words().to_vec()
    }
}

pub(crate) struct StaticParserDfa;

impl StaticParserDfa {
    pub(crate) const NAME: &'static str = "static-parser-dfa";
    pub(crate) const SAFETY: SafetyClass = SafetyClass::TreeAndApiPreserving;

    /// Builds the static tables of the decisions of one compiled parser unit,
    /// which the generated parser will embed.
    ///
    /// With [`AtnFallback::Forbidden`], the escape states of every partial
    /// table are resolved statically, and every decision that still needs
    /// `adaptive_predict` is an error.
    ///
    /// With `profile`, the report also records the wall-clock times of the
    /// table builds (`--profile-decisions`).
    ///
    /// `budgets` holds the base analysis budgets, which the options of the
    /// grammar, its rules, and its blocks change (see [`ParserDfaBudgets`]).
    pub(crate) fn build(
        compiled: &CompiledParser,
        sources: &SourceSet,
        atn_fallback: AtnFallback,
        profile: bool,
        budgets: &ParserDfaBudgets,
    ) -> StaticParserDfaArtifact {
        let atn = compiled.atn;
        let recognizer = &compiled.semantic.recognizer;
        let ll1_disjoint = ll1_disjointness(compiled);
        let (budget, decision_budgets) = decision_budgets(compiled, budgets);
        let builder = DecisionTableBuilder::new(atn, ll1_disjoint)
            .with_atn_fallback(atn_fallback)
            .with_descent_rules(descent_rules(compiled))
            .with_budgets(decision_budgets)
            .with_profiling(profile);
        let started = profile.then(Instant::now);
        let mut results = builder.build_all();
        let profile = started.map(|started| BuildProfile {
            elapsed: started.elapsed(),
            threads: builder.threads(),
        });
        if atn_fallback == AtnFallback::Forbidden {
            for result in &mut results {
                result.resolve_static_only();
            }
        }
        let tables = StaticParserTables::new(&results, atn_fallback);
        let decisions = results
            .iter()
            .map(|result| StaticParserDecisionReport {
                decision: result.decision,
                state: usize::try_from(result.state_number).unwrap_or(0),
                rule: recognizer
                    .rule_names
                    .get(result.rule_index)
                    .cloned()
                    .unwrap_or_default(),
                source_span: decision_span(compiled, result)
                    .unwrap_or_else(|| compiled.semantic.unit.span.clone()),
                alternatives: alternative_names(compiled, sources, result.decision),
                result: result.clone(),
            })
            .collect::<Vec<_>>();
        let vocabulary = (1..=atn.max_token_type)
            .map(|token_type| token_display_name(recognizer, token_type))
            .collect();
        let report = StaticParserDfaReport {
            grammar: compiled.semantic.unit.name.clone(),
            source_span: compiled.semantic.unit.span.clone(),
            vocabulary,
            rule_names: recognizer.rule_names.clone(),
            invoking_states: danger_invoking_states(compiled, sources, &results),
            decisions,
            atn_fallback,
            budget,
            profile,
        };
        let mut diagnostics = match atn_fallback {
            AtnFallback::Allowed => Vec::new(),
            AtnFallback::Forbidden => static_only_diagnostics(&report),
        };
        diagnostics.extend(visit_budget_diagnostics(&report));
        diagnostics.extend(token_branch_diagnostics(compiled));
        StaticParserDfaArtifact {
            diagnostics,
            report,
            tables,
        }
    }

    /// Renders the `static-parser-dfa` entry of the optimization manifest.
    pub(super) fn manifest_pass_value(
        id: usize,
        descriptor: &PassDescriptor,
        parsers: &[StaticParserDfaReport],
        sources: &SourceSet,
    ) -> Value {
        let mut totals = ReportMetrics::default();
        for parser in parsers {
            totals.add(parser);
        }
        let metrics = object(vec![
            ("parsers", Value::from(parsers.len())),
            ("decisions", Value::from(totals.decisions)),
            ("staticDecisions", Value::from(totals.static_decisions)),
            ("hybridDecisions", Value::from(totals.hybrid_decisions)),
            ("adaptiveDecisions", Value::from(totals.adaptive_decisions)),
            ("escapeStates", Value::from(totals.escape_states)),
            ("guardedStates", Value::from(totals.guarded_states)),
            ("minAltStates", Value::from(totals.min_alt_states)),
            (
                "minViableAltStates",
                Value::from(totals.min_viable_alt_states),
            ),
            ("syntaxErrorStates", Value::from(totals.syntax_error_states)),
            ("hijackHazards", Value::from(totals.hijack_hazards)),
            (
                "descentGroupStates",
                Value::from(totals.descent_group_states),
            ),
        ]);
        let rendered = Value::from_iter(
            parsers
                .iter()
                .map(|parser| parser_report_value(parser, sources)),
        );
        super::manifest::pass_value(
            id,
            descriptor,
            totals.static_decisions > 0,
            metrics,
            vec![
                (
                    "staticDfaOnly",
                    Value::from(
                        parsers
                            .iter()
                            .any(|parser| parser.atn_fallback == AtnFallback::Forbidden),
                    ),
                ),
                ("parsers", rendered),
            ],
        )
    }

    /// Renders the `--profile-decisions` report of every parser unit.
    pub(crate) fn render_decision_profile(reports: &[StaticParserDfaReport]) -> String {
        render_blocks(
            &reports
                .iter()
                .map(decision_profile_text)
                .collect::<Vec<_>>(),
        )
    }

    /// Renders the `--dump-dfas` dump of every parser unit, together with the
    /// diagnostics of the selectors that match no decision.
    pub(crate) fn render_dfa_dump(
        reports: &[StaticParserDfaReport],
        spec: &str,
    ) -> (String, Vec<Diagnostic>) {
        let mut blocks = Vec::new();
        let mut diagnostics = Vec::new();
        for report in reports {
            let (block, block_diagnostics) = dfa_dump_text(report, spec);
            blocks.push(block);
            diagnostics.extend(block_diagnostics);
        }
        (render_blocks(&blocks), diagnostics)
    }
}

/// What the pass hands back to the compiler.
pub(crate) struct StaticParserDfaArtifact {
    pub(crate) diagnostics: Vec<Diagnostic>,
    pub(crate) report: StaticParserDfaReport,
    /// The tables the generated parser embeds as its table image.
    pub(crate) tables: StaticParserTables,
}

/// The report modes `--dump-dfas` and `--profile-decisions` select.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct StaticParserDfaSelection {
    pub(crate) dump_dfas: Option<String>,
    pub(crate) profile_decisions: bool,
}

/// The wall-clock time of the table builds of one parser unit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct BuildProfile {
    pub(crate) elapsed: Duration,
    /// The threads that built the tables.
    pub(crate) threads: usize,
}

/// What the pass reports about one parser unit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct StaticParserDfaReport {
    pub(crate) grammar: String,
    pub(crate) source_span: SourceSpan,
    /// Display names of the token types `1..=max_token_type`, indexed by
    /// `token_type - 1`.
    pub(crate) vocabulary: Vec<String>,
    /// Rule names, indexed by rule index.
    pub(crate) rule_names: Vec<String>,
    /// The caller of each invoking state in a guard danger set, by ATN state
    /// number.
    pub(crate) invoking_states: BTreeMap<i32, InvokingState>,
    pub(crate) decisions: Vec<StaticParserDecisionReport>,
    /// Whether the generated parser can defer to the adaptive simulation.
    pub(crate) atn_fallback: AtnFallback,
    /// The budget of a decision that no rule, block, or selector budget
    /// changes.
    pub(crate) budget: DecisionBudget,
    /// The times of the table builds, for `--profile-decisions`.
    pub(crate) profile: Option<BuildProfile>,
}

/// The rule that an invoking state calls from, the label of the alternative
/// that holds the call, and the source line of the call.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct InvokingState {
    pub(crate) rule: String,
    pub(crate) label: Option<String>,
    pub(crate) line: Option<usize>,
}

impl fmt::Display for InvokingState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.rule)?;
        if let Some(label) = &self.label {
            write!(f, "#{label}")?;
        }
        if let Some(line) = self.line {
            write!(f, ":{line}")?;
        }
        Ok(())
    }
}

impl InvokingState {
    /// The caller for a sentence, for example `'command' (line 22)`.
    fn called_from_text(&self) -> String {
        let mut text = format!("'{}", self.rule);
        if let Some(label) = &self.label {
            text.push_str(&format!("#{label}"));
        }
        text.push('\'');
        if let Some(line) = self.line {
            text.push_str(&format!(" (line {line})"));
        }
        text
    }
}

impl StaticParserDfaReport {
    /// A danger set with the caller of each invoking state, for example
    /// `[47 (query:25), 56 (expr#cast:30)]`.
    fn danger_text(&self, danger: &[i32]) -> String {
        let states: Vec<String> = danger
            .iter()
            .map(|state| match self.invoking_states.get(state) {
                Some(caller) => format!("{state} ({caller})"),
                None => state.to_string(),
            })
            .collect();
        format!("[{}]", states.join(", "))
    }

    /// The number of decisions whose tables never escape to the adaptive
    /// simulation (see [`DecisionOutcome::is_fully_static`]).
    fn static_decisions(&self) -> usize {
        self.decisions
            .iter()
            .filter(|decision| decision.result.is_fully_static())
            .count()
    }

    /// The number of decisions with a partial table. Under
    /// `--static-dfa-only`, these decisions are also static decisions, because
    /// their escape states are resolved.
    fn hybrid_decisions(&self) -> usize {
        self.decisions
            .iter()
            .filter(|decision| decision.result.kind == DecisionKind::Hybrid)
            .count()
    }

    /// The number of decisions that keep at least one adaptive path.
    fn adaptive_decisions(&self) -> usize {
        self.decisions
            .iter()
            .filter(|decision| !decision.result.is_fully_static())
            .count()
    }

    /// The states that accept with the virtual alternative of a shared-descent
    /// group, summed over the decisions that keep their table.
    fn descent_group_states(&self) -> usize {
        self.decisions
            .iter()
            .map(StaticParserDecisionReport::descent_group_states)
            .sum()
    }

    fn escape_states(&self) -> usize {
        self.decisions
            .iter()
            .map(|decision| decision.result.escapes)
            .sum()
    }

    /// The guarded states of the tables of the decisions.
    fn guarded_states(&self) -> usize {
        self.decisions
            .iter()
            .map(|decision| decision.result.guarded_states())
            .sum()
    }

    /// The tie-break groups of `--static-dfa-only` with a high prefix-hijack
    /// hazard, and the guard groups with a stack-hijack hazard.
    fn hijack_hazards(&self) -> usize {
        self.decisions
            .iter()
            .map(StaticParserDecisionReport::hijack_hazards)
            .sum()
    }

    /// The escape states that `--static-dfa-only` resolved, summed over the
    /// decisions.
    fn resolved_states(&self) -> EscapeResolutions {
        let mut total = EscapeResolutions::default();
        for resolved in self
            .decisions
            .iter()
            .filter_map(|decision| decision.result.static_only.as_ref())
        {
            total.guarded += resolved.guarded;
            total.min_alt += resolved.min_alt;
            total.min_viable_alt += resolved.min_viable_alt;
            total.syntax_error += resolved.syntax_error;
        }
        total
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct ReportMetrics {
    decisions: usize,
    static_decisions: usize,
    hybrid_decisions: usize,
    adaptive_decisions: usize,
    escape_states: usize,
    guarded_states: usize,
    min_alt_states: usize,
    min_viable_alt_states: usize,
    syntax_error_states: usize,
    hijack_hazards: usize,
    descent_group_states: usize,
}

impl ReportMetrics {
    fn add(&mut self, parser: &StaticParserDfaReport) {
        self.decisions += parser.decisions.len();
        self.static_decisions += parser.static_decisions();
        self.hybrid_decisions += parser.hybrid_decisions();
        self.adaptive_decisions += parser.adaptive_decisions();
        self.escape_states += parser.escape_states();
        let resolved = parser.resolved_states();
        self.guarded_states += parser.guarded_states();
        self.min_alt_states += resolved.min_alt;
        self.min_viable_alt_states += resolved.min_viable_alt;
        self.syntax_error_states += resolved.syntax_error;
        self.hijack_hazards += parser.hijack_hazards();
        self.descent_group_states += parser.descent_group_states();
    }
}

/// One prediction decision of a parser unit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct StaticParserDecisionReport {
    pub(crate) decision: usize,
    /// ATN state number of the decision state.
    pub(crate) state: usize,
    pub(crate) rule: String,
    /// The grammar text of the decision, or of its rule when the decision
    /// state has no grammar text of its own.
    pub(crate) source_span: SourceSpan,
    /// The names of the alternatives of the decision, for the diagnostics.
    pub(crate) alternatives: AlternativeNames,
    pub(crate) result: DecisionOutcome,
}

impl StaticParserDecisionReport {
    /// The tie-break groups of `--static-dfa-only` with a high prefix-hijack
    /// hazard, and the guard groups with a stack-hijack hazard.
    fn hijack_hazards(&self) -> usize {
        self.result.static_only.as_ref().map_or(0, |resolved| {
            let prefix = resolved
                .tie_breaks
                .iter()
                .filter(|group| group.level() == HazardLevel::High)
                .count();
            prefix + resolved.stack_hijacks().count()
        })
    }

    /// The states that accept with the virtual alternative of a shared-descent
    /// group, when the decision keeps its table.
    fn descent_group_states(&self) -> usize {
        self.result.descent_group_states()
    }
}

fn parser_report_value(parser: &StaticParserDfaReport, sources: &SourceSet) -> Value {
    let resolved = parser.resolved_states();
    object(vec![
        ("grammar", Value::from(parser.grammar.as_str())),
        ("source", source_value(&parser.source_span, sources)),
        ("decisions", Value::from(parser.decisions.len())),
        ("staticDecisions", Value::from(parser.static_decisions())),
        ("hybridDecisions", Value::from(parser.hybrid_decisions())),
        (
            "adaptiveDecisions",
            Value::from(parser.adaptive_decisions()),
        ),
        ("escapeStates", Value::from(parser.escape_states())),
        ("guardedStates", Value::from(parser.guarded_states())),
        ("minAltStates", Value::from(resolved.min_alt)),
        ("minViableAltStates", Value::from(resolved.min_viable_alt)),
        ("syntaxErrorStates", Value::from(resolved.syntax_error)),
        ("hijackHazards", Value::from(parser.hijack_hazards())),
        (
            "descentGroupStates",
            Value::from(parser.descent_group_states()),
        ),
        (
            "decisionInventory",
            Value::from_iter(
                parser
                    .decisions
                    .iter()
                    .map(|decision| decision_report_value(decision, sources)),
            ),
        ),
    ])
}

/// One entry of the decision inventory in the manifest. The counts of the
/// entries add up to the counts of their parser.
fn decision_report_value(decision: &StaticParserDecisionReport, sources: &SourceSet) -> Value {
    let result = &decision.result;
    let resolved = result.static_only.clone().unwrap_or_default();
    object(vec![
        ("decision", Value::from(decision.decision)),
        ("rule", Value::from(decision.rule.as_str())),
        ("state", Value::from(decision.state)),
        (
            "source",
            source_location_value(&decision.source_span, sources),
        ),
        ("kind", Value::from(result.kind.as_str())),
        ("k", option(usize::try_from(result.k).ok(), Value::from)),
        ("fullyStatic", Value::from(result.is_fully_static())),
        ("dfaStates", Value::from(result.num_dfa_states)),
        ("escapeStates", Value::from(result.escapes)),
        ("fallback", Value::from(result.fallback_text())),
        ("guardedStates", Value::from(result.guarded_states())),
        ("minAltStates", Value::from(resolved.min_alt)),
        ("minViableAltStates", Value::from(resolved.min_viable_alt)),
        ("syntaxErrorStates", Value::from(resolved.syntax_error)),
        ("hijackHazards", Value::from(decision.hijack_hazards())),
        (
            "descentGroupStates",
            Value::from(decision.descent_group_states()),
        ),
    ])
}

/// Per-decision `LL(1)` disjointness, indexed by decision number.
///
/// `grammar::atn::analysis` already computes the Java `AnalysisPipeline.disjoint`
/// fast path from the grammar graph; the ATN decision numbers are the graph
/// state numbers, so the vector is a direct lookup.
pub(super) fn ll1_disjointness(compiled: &CompiledParser) -> Vec<bool> {
    let by_state = compiled
        .analysis
        .decision_lookahead
        .iter()
        .map(|lookahead| (lookahead.state, lookahead.disjoint))
        .collect::<BTreeMap<_, _>>();
    compiled
        .atn
        .decision_to_state
        .iter()
        .map(|state| {
            by_state
                .get(&usize::try_from(state.get_state_number()).unwrap_or(usize::MAX))
                .copied()
                .unwrap_or(false)
        })
        .collect()
}

/// The rule facts that decide which rules a shared-descent group may share,
/// indexed by rule index.
pub(super) fn descent_rules(compiled: &CompiledParser) -> DescentRules {
    let rules = &compiled.semantic.unit.rules;
    DescentRules {
        has_arguments: rules
            .iter()
            .map(|rule| {
                compiled
                    .semantic
                    .bindings
                    .attributes
                    .get(&rule.id)
                    .is_some_and(|attributes| !attributes.arguments.is_empty())
            })
            .collect(),
        has_actions: rules
            .iter()
            .map(|rule| {
                rule.actions
                    .iter()
                    .any(|action| matches!(action.name.as_str(), "init" | "after"))
                    || !rule.catches.is_empty()
                    || rule.finally_action.is_some()
                    || block_has_action(&rule.block)
            })
            .collect(),
    }
}

/// Whether a block runs an embedded action. The empty actions that the
/// left-recursion rewrite inserts run nothing.
fn block_has_action(block: &Block) -> bool {
    block.alternatives.iter().any(|alternative| {
        alternative
            .elements
            .iter()
            .any(|element| match &element.kind {
                ElementKind::Action { body, .. } => !body.trim().is_empty(),
                ElementKind::Block(block) => block_has_action(block),
                _ => false,
            })
    })
}

/// The display name of one token type, as the Java tool prints it: the string
/// literal, then the token name, then the numeric type.
fn token_display_name(recognizer: &RecognizerModel, token_type: i32) -> String {
    let Ok(index) = usize::try_from(token_type) else {
        return "EOF".to_owned();
    };
    recognizer
        .literal_names
        .get(index)
        .and_then(Clone::clone)
        .or_else(|| recognizer.symbolic_names.get(index).and_then(Clone::clone))
        .unwrap_or_else(|| token_type.to_string())
}

/// The `--profile-decisions` report of one parser unit: the totals, then the
/// slowest decisions.
fn decision_profile_text(report: &StaticParserDfaReport) -> String {
    let decisions = &report.decisions;
    let mut lines = vec![format!(
        "=== parser decision profile: {} ({} decisions) ===",
        report.grammar,
        decisions.len()
    )];
    let elapsed =
        |decision: &StaticParserDecisionReport| decision.result.cost.elapsed.unwrap_or_default();
    let summed: Duration = decisions.iter().map(elapsed).sum();
    if let Some(profile) = &report.profile {
        lines.push(format!(
            "table builds: {} on {} {}; {} summed over the decisions",
            duration_text(profile.elapsed),
            profile.threads,
            if profile.threads == 1 {
                "thread"
            } else {
                "threads"
            },
            duration_text(summed),
        ));
    }
    let attempts: usize = decisions
        .iter()
        .map(|decision| decision.result.cost.attempts.len())
        .sum();
    let visits: u64 = decisions
        .iter()
        .map(|decision| decision.result.cost.visits())
        .sum();
    let states: usize = decisions
        .iter()
        .map(|decision| decision.result.cost.states())
        .sum();
    lines.push(format!(
        "work: {attempts} build attempts; {visits} configs visited; {states} DFA states built"
    ));
    let spent = |outcome| {
        decisions
            .iter()
            .filter(|decision| decision.result.cost.count(outcome) > 0)
            .count()
    };
    lines.push(format!(
        "budgets: {} decisions spent the visit budget ({} configs); {} decisions spent the \
         state budget ({} states)",
        spent(AttemptOutcome::VisitBudget),
        report.budget.max_visits,
        spent(AttemptOutcome::StateBudget),
        report.budget.max_states,
    ));
    lines.push(format!(
        "slow: {} decisions took {} ms or more",
        decisions
            .iter()
            .filter(|decision| elapsed(decision) >= SLOW_DECISION)
            .count(),
        SLOW_DECISION.as_millis(),
    ));
    lines.push(
        "attempts: D default, S static-only, W widened, (N) milliseconds, cN: precedence class N"
            .to_owned(),
    );
    lines.push("outcomes: $ spent the visit budget, ^ spent the state budget".to_owned());

    let mut slowest: Vec<&StaticParserDecisionReport> = decisions.iter().collect();
    slowest.sort_by(|left, right| {
        elapsed(right)
            .cmp(&elapsed(left))
            .then(right.result.cost.visits().cmp(&left.result.cost.visits()))
            .then(left.decision.cmp(&right.decision))
    });
    slowest.truncate(PROFILE_ROWS);
    lines.push(format!("slowest {} decisions:", slowest.len()));
    lines.extend(profile_rows(report, &slowest, elapsed));
    finish_block(lines)
}

/// The rows of the slowest decisions in the `--profile-decisions` report.
fn profile_rows(
    report: &StaticParserDfaReport,
    decisions: &[&StaticParserDecisionReport],
    elapsed: impl Fn(&StaticParserDecisionReport) -> Duration,
) -> Vec<String> {
    let rows: Vec<[String; 9]> = decisions
        .iter()
        .map(|decision| {
            let cost = &decision.result.cost;
            [
                decision.decision.to_string(),
                decision.rule.clone(),
                decision.state.to_string(),
                decision.result.kind.as_str().to_owned(),
                format!("{:.1}", elapsed(decision).as_secs_f64() * 1000.0),
                cost.visits().to_string(),
                cost.states().to_string(),
                cost.attempts_text(),
                cost.hot_rules_text(&report.rule_names, HOT_RULES),
            ]
        })
        .collect();
    let headers = [
        "#",
        "rule",
        "state",
        "kind",
        "ms",
        "visits",
        "statesBuilt",
        "attempts",
        "most visited rules",
    ];
    let right_aligned = [true, false, true, false, true, true, true, false, false];
    let widths: Vec<usize> = headers
        .iter()
        .enumerate()
        .map(|(column, header)| {
            rows.iter()
                .map(|row| row[column].len())
                .max()
                .unwrap_or(0)
                .max(header.len())
        })
        .collect();
    let line = |cells: Vec<&str>| {
        let mut text = String::from(" ");
        for (column, cell) in cells.iter().enumerate() {
            let width = widths[column];
            text.push(' ');
            if right_aligned[column] {
                text.push_str(&format!("{cell:>width$}"));
            } else if column + 1 < cells.len() {
                text.push_str(&format!("{cell:<width$}"));
            } else {
                text.push_str(cell);
            }
            if column + 1 < cells.len() {
                text.push(' ');
            }
        }
        text.trim_end().to_owned()
    };
    let mut lines = vec![line(headers.to_vec())];
    lines.extend(
        rows.iter()
            .map(|row| line(row.iter().map(String::as_str).collect())),
    );
    lines
}

/// A duration in milliseconds below one second, else in seconds.
fn duration_text(duration: Duration) -> String {
    if duration < Duration::from_secs(1) {
        format!("{:.1} ms", duration.as_secs_f64() * 1000.0)
    } else {
        format!("{:.2} s", duration.as_secs_f64())
    }
}

fn k_text(result: &DecisionOutcome) -> String {
    if result.k < 0 {
        "-".to_owned()
    } else {
        result.k.to_string()
    }
}

fn dfa_dump_text(report: &StaticParserDfaReport, spec: &str) -> (String, Vec<Diagnostic>) {
    let selection = DfaDumpSelection::parse(spec);
    let mut diagnostics = Vec::new();
    let mut lines = vec![
        format!("=== static DFA dump: grammar {} ===", report.grammar),
        vocabulary_line(&report.vocabulary),
    ];

    let mut selected = vec![false; selection.selectors.len()];
    let mut shown = 0_usize;
    for decision in &report.decisions {
        let mut hit = selection.all;
        for (index, selector) in selection.selectors.iter().enumerate() {
            if selector.matches(decision) {
                selected[index] = true;
                hit = true;
            }
        }
        if !hit {
            continue;
        }
        shown += 1;
        lines.extend(decision_dump_lines(report, decision, selection.paths));
    }
    lines.push(String::new());
    lines.push(format!(
        "({shown} of {} decisions dumped)",
        report.decisions.len()
    ));

    if selection.selects_nothing() {
        diagnostics.push(no_matching_decision_error(report, spec));
    }
    diagnostics.extend(
        selection
            .malformed
            .iter()
            .map(|item| no_matching_decision_error(report, item)),
    );
    diagnostics.extend(
        selection
            .selectors
            .iter()
            .zip(&selected)
            .filter(|(_, matched)| !**matched)
            .map(|(selector, _)| no_matching_decision_error(report, &selector.text())),
    );
    (finish_block(lines), diagnostics)
}

fn decision_dump_lines(
    report: &StaticParserDfaReport,
    decision: &StaticParserDecisionReport,
    with_paths: bool,
) -> Vec<String> {
    let result = &decision.result;
    let headline = if !result.has_table() {
        format!(
            "--- decision {}: rule '{}' ({}) ---",
            decision.decision, decision.rule, result.kind
        )
    } else {
        format!(
            "--- decision {}: rule '{}' ({}, k={}, {} states) ---",
            decision.decision,
            decision.rule,
            result.kind,
            k_text(result),
            result.num_dfa_states
        )
    };
    let mut lines = vec![String::new(), headline];
    if !decision.alternatives.all().is_empty() {
        lines.push(format!(
            "alternatives: {}",
            decision.alternatives.all().join("; ")
        ));
    }
    match (&result.table, &result.precedence) {
        (_, Some(precedence)) => {
            lines.push(format!("precedence classes: {:?}", precedence.cutoffs));
            for (index, table) in precedence.tables.iter().enumerate() {
                match table {
                    Some(table) => {
                        lines.push(format!("class {index}:"));
                        lines.extend(table_dump_lines(report, decision, table, with_paths));
                    }
                    None => lines.push(format!(
                        "class {index}: no static table: this precedence class runs on adaptive_predict"
                    )),
                }
            }
        }
        (Some(table), None) => {
            lines.extend(descent_dump_lines(report, result.descent.as_ref()));
            lines.extend(table_dump_lines(report, decision, table, with_paths));
        }
        (None, None) if result.kind == DecisionKind::Ll1 => lines.push(
            "  no table needed: the alternatives have disjoint first tokens, so plain LL(1) \
             prediction decides"
                .to_owned(),
        ),
        (None, None) => lines.push(format!("  no static table: {}", no_table_text(result))),
    }
    lines
}

fn table_dump_lines(
    report: &StaticParserDfaReport,
    decision: &StaticParserDecisionReport,
    table: &StaticDfaTable,
    with_paths: bool,
) -> Vec<String> {
    let runtime_states = minimized_states(table);
    let mut lines = vec![format!(
        "  table: states={}{} cyclic={}{}",
        table.states.len(),
        if runtime_states < table.states.len() {
            format!(" (runtime {runtime_states})")
        } else {
            String::new()
        },
        table.cyclic,
        if table.cyclic {
            String::new()
        } else {
            format!(" maxK={}", table.max_k)
        }
    )];
    if table.guarded() > 0 {
        lines.push(format!(
            "  guards: {} guarded states in {} guard groups (pass={} states). A guard walks up the parse stack through the pass frames. It defers at an invoking state of its danger set.",
            table.guarded(),
            table.guard_groups.len(),
            table.guard_pass.len()
        ));
        for (group, danger) in table.guard_groups.iter().enumerate() {
            let hazard = decision
                .result
                .static_only
                .iter()
                .flat_map(|resolved| &resolved.guard_groups)
                .find(|known| known.danger == *danger)
                .and_then(|known| known.hazard.as_ref())
                .filter(|hazard| matches!(hazard, StackHijackVerdict::Hijack { .. }))
                .map(|hazard| stack_hazard_text(report, Some(hazard)))
                .unwrap_or_default();
            lines.push(format!(
                "    group {group}: danger={}{hazard}",
                report.danger_text(danger)
            ));
        }
    }
    for (index, state) in table.states.iter().enumerate() {
        let mut line = format!("    s{index}: ");
        let mut note = None;
        if state.accept >= VIRTUAL_ALT_BASE {
            line.push_str(&format!("GROUP {}", state.accept));
        } else if state.accept > 0 {
            line.push_str(&format!("accept alt={}", state.accept));
            match state.resolution {
                Some(EscapeResolution::MinAlt) => {
                    line.push_str(" (static-dfa-only: minimum conflicting alternative)");
                }
                Some(EscapeResolution::MinViableAlt) => {
                    line.push_str(" (static-dfa-only: minimum viable alternative)");
                }
                _ => {}
            }
            let dropped: &[i32] = match state.resolution {
                Some(EscapeResolution::MinAlt) => &state.conflicts,
                Some(EscapeResolution::MinViableAlt) => &state.viable_alts,
                _ => &[],
            };
            let dropped: Vec<String> = dropped
                .iter()
                .filter(|alt| **alt > 0 && **alt != state.accept)
                .map(ToString::to_string)
                .collect();
            match dropped.as_slice() {
                [] => {}
                [alt] => note = Some(format!("; over alt {alt}")),
                alts => note = Some(format!("; over alts {}", alts.join(", "))),
            }
        } else if state.is_guarded() {
            let deferred = if state.resolution == Some(EscapeResolution::Guarded) {
                format!("alt={}", state.guard_defer_alt)
            } else {
                "adaptive_predict".to_owned()
            };
            line.push_str(&format!(
                "GUARDED alt={}, or {deferred} when the parse stack reaches a guard root of group {} (danger={})",
                state.guarded_alt,
                state.guard_group,
                report.danger_text(
                    table
                        .guard_groups
                        .get(state.guard_group as usize)
                        .map_or(&[][..], Vec::as_slice)
                )
            ));
        } else if state.is_escape() {
            line.push_str("ESCAPE");
            if state.viable_alts.len() > 1 {
                let viable: Vec<String> =
                    state.viable_alts.iter().map(ToString::to_string).collect();
                note = Some(format!("; viable alts {}", viable.join(", ")));
            }
        } else if state.resolution == Some(EscapeResolution::SyntaxError) {
            line.push_str("SYNTAX ERROR (static-dfa-only: predicated lookahead)");
        } else {
            line.push_str("(non-accept)");
        }
        if state.fallback > 0 {
            line.push_str(&format!("; error-recovery fallback alt={}", state.fallback));
        }
        if let Some(note) = note {
            line.push_str(&note);
        }
        if with_paths && let Some(path) = table.witness(index).filter(|path| !path.is_empty()) {
            line.push_str(&format!("; path: {}", path_text(&report.vocabulary, &path)));
        }
        lines.push(line);
        for edge in &state.edges {
            lines.push(format!(
                "      s{index} {}({}) -> s{}",
                interval_text(&report.vocabulary, edge.lo, edge.hi),
                token_range_text(edge.lo, edge.hi),
                edge.target
            ));
        }
    }
    lines
}

/// One line per shared-descent group of a decision.
fn descent_dump_lines(report: &StaticParserDfaReport, plan: Option<&DescentPlan>) -> Vec<String> {
    let Some(plan) = plan else {
        return Vec::new();
    };
    plan.groups
        .iter()
        .map(|group| {
            let mut text = format!(
                "  group {}: shared rule '{}' after {} prefix tokens, members {:?}; tails:",
                group.virtual_alt,
                report
                    .rule_names
                    .get(group.rule)
                    .map_or("?", String::as_str),
                group.prefix.len(),
                group.alts
            );
            for arm in &group.arms {
                let tokens: Vec<String> = arm
                    .tokens
                    .iter()
                    .map(|token| token_name(&report.vocabulary, *token))
                    .collect();
                text.push_str(&format!(" alt {} on {}", arm.alt, tokens.join(" ")));
                text.push(';');
            }
            if group.default_alt > 0 {
                text.push_str(&format!(" otherwise alt {}", group.default_alt));
            } else {
                text.push_str(&format!(" default alt {}", group.min_alt()));
            }
            text
        })
        .collect()
}

/// The display name of one token type of the unit's vocabulary.
fn token_name(vocabulary: &[String], token: i32) -> String {
    if token < 0 {
        return "EOF".to_owned();
    }
    usize::try_from(token)
        .ok()
        .and_then(|token| token.checked_sub(1))
        .and_then(|index| vocabulary.get(index))
        .cloned()
        .unwrap_or_else(|| token.to_string())
}

fn interval_text(vocabulary: &[String], lo: i32, hi: i32) -> String {
    if lo == hi {
        token_name(vocabulary, lo)
    } else {
        format!(
            "{}..{}",
            token_name(vocabulary, lo),
            token_name(vocabulary, hi)
        )
    }
}

fn token_range_text(lo: i32, hi: i32) -> String {
    if lo == hi {
        lo.to_string()
    } else {
        format!("{lo}..{hi}")
    }
}

fn path_text(vocabulary: &[String], path: &[i32]) -> String {
    path.iter()
        .map(|token| token_name(vocabulary, *token))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Why the decision, or some precedence class of it, has no static table.
fn no_table_text(result: &DecisionOutcome) -> String {
    result.no_table.as_ref().map_or_else(
        || "no static table".to_owned(),
        |reason| reason_text(reason, &result.budget),
    )
}

fn reason_text(reason: &NoTableReason, budget: &DecisionBudget) -> String {
    match reason {
        NoTableReason::NonGreedy => "the decision is a non-greedy subrule, and the generated \
                                     parser predicts non-greedy subrules only with adaptive_predict"
            .to_owned(),
        NoTableReason::TooManyAlternatives => {
            "the decision has too many alternatives for a static table".to_owned()
        }
        NoTableReason::EmptyPrecedenceLoop => {
            "the precedence loop has no precedence predicates to build class tables from".to_owned()
        }
        NoTableReason::PredicatedStart(Some((rule, index))) => format!(
            "the decision depends on predicate {rule}:{index}, so the prediction is not input-only"
        ),
        NoTableReason::PredicatedStart(None) => {
            "the decision depends on a predicate, so the prediction is not input-only".to_owned()
        }
        NoTableReason::StartConflict => {
            "SLL cannot separate the alternatives; only full-context prediction can".to_owned()
        }
        NoTableReason::StartBudget(cutoff) => format!(
            "the SLL DFA exceeded the analysis budget ({})",
            budget_limit_text(*cutoff, budget)
        ),
        NoTableReason::LowCoverage { coverage_percent } => format!(
            "the partial table decides {coverage_percent}% of the start lookahead, less than the \
             {PARTIAL_MIN_COVERAGE_PERCENT}% that a partial table needs"
        ),
        NoTableReason::PrecedenceClasses {
            failed,
            total,
            first,
        } => format!(
            "{failed} of {total} precedence classes have no static table: {}",
            reason_text(first, budget)
        ),
    }
}

fn budget_limit_text(cutoff: BudgetCutoff, budget: &DecisionBudget) -> String {
    match cutoff {
        BudgetCutoff::States => format!("{} states", budget.max_states),
        BudgetCutoff::Visits => format!("{} visited configs", budget.max_visits),
        BudgetCutoff::Both => format!(
            "{} states and {} visited configs",
            budget.max_states, budget.max_visits
        ),
    }
}

fn budget_cutoff_text(cutoff: BudgetCutoff, budget: &DecisionBudget) -> String {
    let option = match cutoff {
        BudgetCutoff::States => "the max_dfa_states option",
        BudgetCutoff::Visits => "the max_dfa_visits option",
        BudgetCutoff::Both => "the max_dfa_states and max_dfa_visits options",
    };
    format!(
        "the analysis budget ({}) stopped the lookahead; \
         raise it with {option} of the grammar, the rule, or the block",
        budget_limit_text(cutoff, budget)
    )
}

fn witness_text(vocabulary: &[String], witness: Option<&[i32]>) -> Option<String> {
    witness
        .filter(|witness| !witness.is_empty())
        .map(|witness| path_text(vocabulary, witness))
}

fn vocabulary_line(vocabulary: &[String]) -> String {
    let tokens = vocabulary
        .iter()
        .enumerate()
        .map(|(index, name)| format!(" {name}={}", index + 1))
        .collect::<String>();
    format!("vocabulary: EOF=-1{tokens}")
}

fn render_blocks(blocks: &[String]) -> String {
    let mut text = blocks.join("\n");
    if !blocks.is_empty() {
        text.push('\n');
    }
    text
}

fn finish_block(lines: Vec<String>) -> String {
    let mut text = lines.join("\n");
    text.push('\n');
    text
}

fn no_matching_decision_error(report: &StaticParserDfaReport, selector: &str) -> Diagnostic {
    Diagnostic::error(
        DUMP_SELECTOR_NO_MATCH,
        report.source_span.clone(),
        format!(
            "--dump-dfas: no parser decision of grammar {} matches '{selector}'",
            report.grammar
        ),
    )
}

/// The parsed selector list of one `--dump-dfas` value.
#[derive(Debug, Default)]
struct DfaDumpSelection {
    all: bool,
    paths: bool,
    selectors: Vec<DfaDumpSelector>,
    malformed: Vec<String>,
}

impl DfaDumpSelection {
    fn parse(spec: &str) -> Self {
        let mut selection = Self::default();
        for raw in spec.split(',') {
            let item = raw.trim();
            if item.is_empty() {
                continue;
            }
            if item.eq_ignore_ascii_case("all") {
                selection.all = true;
            } else if item.eq_ignore_ascii_case("paths") {
                // A modifier of the state dump: it annotates each state with a
                // shortest lookahead path and selects no decision on its own.
                selection.paths = true;
            } else if let Some(selector) = DfaDumpSelector::parse(item) {
                if !selection.selectors.contains(&selector) {
                    selection.selectors.push(selector);
                }
            } else if !selection.malformed.iter().any(|known| known == item) {
                selection.malformed.push(item.to_owned());
            }
        }
        selection
    }

    fn selects_nothing(&self) -> bool {
        !self.all && self.selectors.is_empty() && self.malformed.is_empty()
    }
}

/// One `--dump-dfas` selector: a decision number, a rule name, or both.
#[derive(Clone, Debug, Eq, PartialEq)]
enum DfaDumpSelector {
    Decision(usize),
    Rule(String),
    RuleDecision { rule: String, decision: usize },
}

impl DfaDumpSelector {
    fn parse(item: &str) -> Option<Self> {
        if let Some((rule, decision)) = item.split_once(':') {
            let rule = rule.trim();
            let decision = decision_number(decision.trim())?;
            return (!rule.is_empty()).then(|| Self::RuleDecision {
                rule: rule.to_owned(),
                decision,
            });
        }
        Some(match decision_number(item) {
            Some(decision) => Self::Decision(decision),
            None => Self::Rule(item.to_owned()),
        })
    }

    fn matches(&self, decision: &StaticParserDecisionReport) -> bool {
        match self {
            Self::Decision(wanted) => *wanted == decision.decision,
            Self::Rule(wanted) => *wanted == decision.rule,
            Self::RuleDecision {
                rule,
                decision: wanted,
            } => *rule == decision.rule && *wanted == decision.decision,
        }
    }

    fn text(&self) -> String {
        match self {
            Self::Decision(decision) => decision.to_string(),
            Self::Rule(rule) => rule.clone(),
            Self::RuleDecision { rule, decision } => format!("{rule}:{decision}"),
        }
    }
}

fn decision_number(text: &str) -> Option<usize> {
    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    text.parse().ok()
}

/// The `--static-dfa-only` diagnostics: a `G4S190` error for each decision that
/// still needs `adaptive_predict`, and a `G4S192` warning for each decision with
/// resolved escape states.
fn static_only_diagnostics(report: &StaticParserDfaReport) -> Vec<Diagnostic> {
    report
        .decisions
        .iter()
        .filter_map(|decision| {
            let result = &decision.result;
            let span = decision.source_span.clone();
            let Some(resolved) = &result.static_only else {
                let mut message = format!(
                    "parser decision {} of rule '{}' is not fully static: {}; \
                     --static-dfa-only requires a static table for every decision",
                    decision.decision,
                    decision.rule,
                    no_table_text(result)
                );
                if let Some(witness) = witness_text(
                    &report.vocabulary,
                    result
                        .conflict_witness
                        .as_deref()
                        .or(result.budget_witness.as_deref()),
                ) {
                    message.push_str(&format!("; witness: {witness}"));
                }
                message.push_str(&conflict_text(decision));
                return Some(Diagnostic::error(NOT_FULLY_STATIC, span, message));
            };
            let mut parts = Vec::new();
            if resolved.guarded > 0 {
                parts.push(resolution_text(
                    &report.vocabulary,
                    resolved.guarded,
                    ("guarded state returns", "guarded states return"),
                    "the skip or the exit where the stack guard defers",
                    resolved.guarded_witness.as_deref(),
                    danger_callers_text(report, &resolved.guarded_danger),
                ));
                parts
                    .last_mut()
                    .expect("the guarded clause")
                    .push_str(&stack_hijacks_text(report, resolved));
            }
            if resolved.min_alt > 0 {
                parts.push(resolution_text(
                    &report.vocabulary,
                    resolved.min_alt,
                    ("conflict state predicts", "conflict states predict"),
                    "the minimum alternative",
                    resolved.min_alt_witness.as_deref(),
                    None,
                ));
            }
            if resolved.min_viable_alt > 0 {
                parts.push(resolution_text(
                    &report.vocabulary,
                    resolved.min_viable_alt,
                    ("undecided state predicts", "undecided states predict"),
                    "the minimum viable alternative",
                    resolved.min_viable_alt_witness.as_deref(),
                    None,
                ));
            }
            if resolved.syntax_error > 0 {
                parts.push(resolution_text(
                    &report.vocabulary,
                    resolved.syntax_error,
                    ("predicated state reports", "predicated states report"),
                    "a syntax error",
                    resolved.syntax_error_witness.as_deref(),
                    None,
                ));
            }
            (!parts.is_empty()).then(|| {
                let mut message = format!(
                    "decision {} of rule '{}' applied heuristic resolution of escape states: {}",
                    decision.decision,
                    decision.rule,
                    parts.join(", ")
                );
                message.push_str(&tie_break_text(report, decision));
                if let Some(cutoff) = result.budget_cutoff {
                    message.push_str(&format!("; {}", budget_cutoff_text(cutoff, &result.budget)));
                }
                Diagnostic::warning(STATIC_ONLY_RESOLVED, span, message)
            })
        })
        .collect()
}

/// The `G4S193` warnings: one per decision with a build attempt that spent the
/// visit budget. The counts in the message are the same on every machine.
fn visit_budget_diagnostics(report: &StaticParserDfaReport) -> Vec<Diagnostic> {
    report
        .decisions
        .iter()
        .filter_map(|decision| {
            let result = &decision.result;
            let cost = &result.cost;
            let spent = cost.count(AttemptOutcome::VisitBudget);
            if spent == 0 {
                return None;
            }
            let mut message = format!(
                "the analysis of parser decision {} of rule '{}' is slow: {spent} of {} build \
                 attempts spent the visit budget ({} configs); {} configs visited, {} DFA states \
                 built",
                decision.decision,
                decision.rule,
                cost.attempts.len(),
                result.budget.max_visits,
                cost.visits(),
                cost.states(),
            );
            let hot_rules = cost.hot_rules_text(&report.rule_names, HOT_RULES);
            if !hot_rules.is_empty() {
                message.push_str(&format!("; most visited rules: {hot_rules}"));
            }
            let span = decision.source_span.clone();
            Some(Diagnostic::warning(VISIT_BUDGET_SPENT, span, message))
        })
        .collect()
}

/// The `G4S194` warnings: one per block with many single-token alternatives
/// that do not fold into one token set.
///
/// Each of these alternatives is a separate ATN branch. The closure of each
/// decision that enters the rule follows all of them. The check looks only at
/// the blocks that the rule can reach before it reads a token, and only at the
/// rules that many call sites enter.
fn token_branch_diagnostics(compiled: &CompiledParser) -> Vec<Diagnostic> {
    let mut candidates = Vec::new();
    for rule in &compiled.semantic.unit.rules {
        if rule.kind != RuleKind::Parser {
            continue;
        }
        let mut blocks = Vec::new();
        leading_blocks(compiled, &rule.block, &mut blocks);
        candidates.extend(
            blocks
                .into_iter()
                .filter_map(|block| TokenBranches::of(rule, block))
                .map(|branches| (rule, branches)),
        );
    }
    if candidates.is_empty() {
        return Vec::new();
    }
    let entries = rule_entries(compiled);
    candidates
        .into_iter()
        .filter_map(|(rule, branches)| {
            let entries = compiled
                .semantic
                .recognizer
                .rule_numbers
                .get(&rule.id)
                .and_then(|index| entries.get(*index))
                .copied()?;
            (entries >= TOKEN_BRANCH_ENTRIES).then(|| branches.diagnostic(rule, entries))
        })
        .collect()
}

/// Adds `block` and, in source order, each nested block that the rule can
/// reach from the start of `block` before it reads a token. Returns whether
/// `block` can match the empty string.
fn leading_blocks<'b>(
    compiled: &CompiledParser,
    block: &'b Block,
    out: &mut Vec<&'b Block>,
) -> bool {
    out.push(block);
    let mut nullable = false;
    for alternative in &block.alternatives {
        let mut empty = true;
        for element in &alternative.elements {
            let element_nullable = match &element.kind {
                ElementKind::Block(nested) => leading_blocks(compiled, nested, out),
                ElementKind::Action { .. }
                | ElementKind::Predicate { .. }
                | ElementKind::Epsilon => true,
                ElementKind::RuleCall(_) => compiled
                    .semantic
                    .bindings
                    .rule_calls
                    .get(&element.id)
                    .is_some_and(|call| compiled.analysis.nullable_rules.contains(&call.target)),
                _ => false,
            };
            if !element_nullable
                && !matches!(
                    element.quantifier,
                    Quantifier::Optional { .. } | Quantifier::ZeroOrMore { .. }
                )
            {
                empty = false;
                break;
            }
        }
        nullable |= empty;
    }
    nullable
}

/// The single-token alternatives of one block that did not fold into one
/// token set, with the causes.
struct TokenBranches<'b> {
    block: &'b Block,
    count: usize,
    causes: Vec<String>,
}

impl<'b> TokenBranches<'b> {
    /// The single-token alternatives of `block`, when there are enough of them
    /// for a `G4S194` warning and a cause is known.
    fn of(rule: &Rule, block: &'b Block) -> Option<Self> {
        // The left-recursion rewrite moves the operator alternatives out of
        // the primary block, and puts an empty action in front of the first
        // primary alternative.
        let operators = rule
            .left_recursion
            .as_ref()
            .and_then(|_| left_recursion_operators(rule, block))
            .unwrap_or(0);
        let single_tokens = block
            .alternatives
            .iter()
            .enumerate()
            .filter_map(|(index, alternative)| {
                let mut elements = alternative.elements.iter();
                if index == 0
                    && operators > 0
                    && let [first, _, ..] = alternative.elements.as_slice()
                    && matches!(&first.kind, ElementKind::Action { body, .. } if body.is_empty())
                {
                    elements.next();
                }
                match (elements.next(), elements.next()) {
                    (Some(element), None)
                        if element.quantifier == Quantifier::One
                            && matches!(
                                element.kind,
                                ElementKind::Terminal(Terminal::Token(_) | Terminal::Literal(_))
                            ) =>
                    {
                        Some((alternative, element))
                    }
                    _ => None,
                }
            })
            .collect::<Vec<_>>();
        if single_tokens.len() < TOKEN_BRANCH_ALTERNATIVES {
            return None;
        }
        let mut causes = Vec::new();
        let others = block.alternatives.len() - single_tokens.len() + operators;
        if others > 0 {
            causes.push(count_text(
                others,
                "alternative is not a single token",
                "alternatives are not a single token",
            ));
        }
        let labeled = single_tokens
            .iter()
            .filter(|(alternative, _)| alternative.label.is_some())
            .count();
        if labeled > 0 {
            causes.push(count_text(
                labeled,
                "alternative has a label",
                "alternatives have a label",
            ));
        }
        let element_labeled = single_tokens
            .iter()
            .filter(|(_, element)| element.label.is_some())
            .count();
        if element_labeled > 0 {
            causes.push(count_text(
                element_labeled,
                "token has an element label",
                "tokens have an element label",
            ));
        }
        if has_non_budget_option(&block.options)
            || single_tokens
                .iter()
                .any(|(alternative, _)| !alternative.options.is_empty())
        {
            causes.push("the block or its alternatives have options".to_owned());
        }
        // Without a cause, a transform after the block-set reduction made the
        // other alternatives single tokens.
        (!causes.is_empty()).then_some(Self {
            block,
            count: single_tokens.len(),
            causes,
        })
    }

    fn diagnostic(&self, rule: &Rule, entries: usize) -> Diagnostic {
        Diagnostic::warning(
            TOKEN_BRANCHES,
            self.block.span.clone(),
            format!(
                "rule '{}' has a block with {} single-token alternatives that do not fold into \
                 one token set. The block does not fold because {}. {entries} call sites enter \
                 the rule before they read a token. The analysis of the static parser DFA \
                 follows each alternative at each site. Move the single tokens into one \
                 unlabeled subrule, for example `( A | B | C )`, or into a token-only rule",
                rule.name,
                self.count,
                self.causes.join(", and "),
            ),
        )
    }
}

/// The number of operator alternatives of a left-recursive rule, when `block`
/// is the primary block of its rewrite.
fn left_recursion_operators(rule: &Rule, block: &Block) -> Option<usize> {
    let [alternative] = rule.block.alternatives.as_slice() else {
        return None;
    };
    let [primary, operators] = alternative.elements.as_slice() else {
        return None;
    };
    match (&primary.kind, &operators.kind) {
        (ElementKind::Block(primary), ElementKind::Block(operators))
            if std::ptr::eq(primary, block) =>
        {
            Some(operators.alternatives.len())
        }
        _ => None,
    }
}

/// The number of call sites that enter each rule before they read a token,
/// by rule index.
///
/// A call site of rule `R` enters `R`. When `R` can call rule `S` before it
/// reads a token, the call site also enters `S`.
fn rule_entries(compiled: &CompiledParser) -> Vec<usize> {
    let graph = &compiled.graph;
    let rules = graph.rule_starts.len();
    let mut direct = vec![0_usize; rules];
    for transition in &graph.transitions {
        if let FinalizedTransitionKind::Rule { rule_index, .. } = transition.kind
            && let Some(count) = direct.get_mut(rule_index)
        {
            *count += 1;
        }
    }
    let recognizer = &compiled.semantic.recognizer;
    let nullable = compiled
        .analysis
        .nullable_rules
        .iter()
        .filter_map(|rule| recognizer.rule_numbers.get(rule).copied())
        .collect();
    let mut callers = vec![Vec::new(); rules];
    for (caller, callees) in left_corner_rules(graph, &nullable).iter().enumerate() {
        for &callee in callees {
            if let Some(callers) = callers.get_mut(callee) {
                callers.push(caller);
            }
        }
    }
    (0..rules)
        .map(|rule| {
            let mut seen = vec![false; rules];
            seen[rule] = true;
            let mut pending = vec![rule];
            let mut entries = 0;
            while let Some(current) = pending.pop() {
                entries += direct[current];
                for &caller in &callers[current] {
                    if !seen[caller] {
                        seen[caller] = true;
                        pending.push(caller);
                    }
                }
            }
            entries
        })
        .collect()
}

/// `count` with the singular or the plural phrase, for example `1 alternative
/// has a label`.
fn count_text(count: usize, singular: &str, plural: &str) -> String {
    format!("{count} {}", if count == 1 { singular } else { plural })
}

/// The text that names the alternatives behind the witness of a decision:
/// the alternatives of its first conflict, or else the viable alternatives of
/// its first escape state. The text is empty when the decision has neither.
fn conflict_text(decision: &StaticParserDecisionReport) -> String {
    let result = &decision.result;
    let conflicting = |alts: &[i32]| {
        format!(
            "; conflicting alternatives: {}",
            decision.alternatives.list(alts)
        )
    };
    if let Some(alts) = result.conflicts.first().filter(|alts| alts.len() > 1) {
        return conflicting(alts);
    }
    let first_state = |marker| {
        result.tables().find_map(|table| {
            table
                .first_escape(marker)
                .and_then(|index| table.states.get(index))
        })
    };
    if let Some(state) = first_state(CONFLICT_ESCAPE) {
        return if state.conflicts.len() > 1 {
            conflicting(&state.conflicts)
        } else {
            String::new()
        };
    }
    match first_state(ESCAPE) {
        Some(state) if state.viable_alts.len() > 1 => format!(
            "; viable alternatives: {}",
            decision.alternatives.list(&state.viable_alts)
        ),
        _ => String::new(),
    }
}

/// The text of the first [`TIE_BREAK_GROUPS`] tie-break groups of a
/// decision: the most harmful groups, then the groups with the most states.
fn tie_break_text(report: &StaticParserDfaReport, decision: &StaticParserDecisionReport) -> String {
    let Some(resolved) = &decision.result.static_only else {
        return String::new();
    };
    let groups = &resolved.tie_breaks;
    let mut parts: Vec<String> = groups
        .iter()
        .take(TIE_BREAK_GROUPS)
        .map(|group| {
            let states = if group.states == 1 {
                "1 state chooses".to_owned()
            } else {
                format!("{} states choose", group.states)
            };
            let mut text = format!(
                "{states} {} over {}",
                decision.alternatives.name(group.chosen),
                decision.alternatives.list(&group.dropped)
            );
            // The summary of the resolutions already shows these witnesses,
            // and a hijack shows its own path.
            let shown = [&resolved.min_alt_witness, &resolved.min_viable_alt_witness];
            let hijack = group
                .hazard
                .as_ref()
                .is_some_and(|hazard| matches!(hazard.verdict, HijackVerdict::Hijack { .. }));
            if !hijack
                && !shown.contains(&&group.witness)
                && let Some(witness) = witness_text(&report.vocabulary, group.witness.as_deref())
            {
                text.push_str(&format!(" (witness: {witness})"));
            }
            text.push_str(&hazard_text(report, decision, group));
            text
        })
        .collect();
    if parts.is_empty() {
        return String::new();
    }
    match groups.len().saturating_sub(TIE_BREAK_GROUPS) {
        0 => {}
        1 => parts.push("and 1 more tie-break group".to_owned()),
        more => parts.push(format!("and {more} more tie-break groups")),
    }
    format!("; tie-breaks: {}", parts.join("; "))
}

/// The prefix-hijack verdict of a tie-break group, in brackets.
fn hazard_text(
    report: &StaticParserDfaReport,
    decision: &StaticParserDecisionReport,
    group: &TieBreak,
) -> String {
    let Some(hazard) = &group.hazard else {
        return " [unverified: no analysis of the hijack hazard]".to_owned();
    };
    let chosen = format!("alt {}", group.chosen);
    match &hazard.verdict {
        HijackVerdict::Hijack { alt, extension } => {
            let (prefix, token) = extension.split_at(extension.len().saturating_sub(1));
            let kind = if hazard.greedy {
                "greedy choice"
            } else {
                "prefix-hijack hazard"
            };
            let after = if prefix.is_empty() {
                String::new()
            } else {
                format!(" after {}", path_text(&report.vocabulary, prefix))
            };
            format!(
                " [{kind}: {} reads {}{after}, and {chosen} cannot]",
                decision.alternatives.name(*alt),
                path_text(&report.vocabulary, token)
            )
        }
        HijackVerdict::Covered if hazard.greedy => " [benign greedy choice]".to_owned(),
        HijackVerdict::Covered => {
            format!(" [benign: {chosen} reads each continuation of the dropped alternatives]")
        }
        HijackVerdict::Unknown if hazard.greedy => " [greedy choice, not verified]".to_owned(),
        HijackVerdict::Unknown => {
            " [unverified: the analysis did not separate the alternatives]".to_owned()
        }
    }
}

/// The stack-hijack verdict of a guard group, in brackets, for example
/// ` [stack-hijack hazard: when called from 'command' (line 22), defers
/// 'SETTINGS' ID even when followed by 'UNION']`.
fn stack_hazard_text(
    report: &StaticParserDfaReport,
    hazard: Option<&StackHijackVerdict>,
) -> String {
    match hazard {
        None => " [unverified: no analysis of the stack guard]".to_owned(),
        Some(StackHijackVerdict::Covered) => " [benign stack guard]".to_owned(),
        Some(StackHijackVerdict::Unknown) => " [stack guard, not verified]".to_owned(),
        Some(StackHijackVerdict::Hijack { caller, extension }) => {
            let (deferred, token) = extension.split_at(extension.len().saturating_sub(1));
            let caller = report.invoking_states.get(caller).map_or_else(
                || format!("invoking state {caller}"),
                InvokingState::called_from_text,
            );
            let deferred = if deferred.is_empty() {
                String::new()
            } else {
                format!(" {}", path_text(&report.vocabulary, deferred))
            };
            format!(
                " [stack-hijack hazard: when called from {caller}, defers{deferred} even when \
                 followed by {}]",
                path_text(&report.vocabulary, token)
            )
        }
    }
}

/// The stack-hijack verdicts of the guard groups of a decision for a
/// `G4S192` warning: each stack hijack, at most [`STACK_HIJACKS`] of them, or
/// else the verdict of the most harmful group.
fn stack_hijacks_text(report: &StaticParserDfaReport, resolved: &EscapeResolutions) -> String {
    let hijacks: Vec<&GuardGroup> = resolved.stack_hijacks().collect();
    if hijacks.is_empty() {
        return resolved
            .guard_groups
            .first()
            .map(|group| stack_hazard_text(report, group.hazard.as_ref()))
            .unwrap_or_default();
    }
    let shown = hijacks.len().min(STACK_HIJACKS);
    let mut text: String = hijacks[..shown]
        .iter()
        .map(|group| stack_hazard_text(report, group.hazard.as_ref()))
        .collect();
    match hijacks.len() - shown {
        0 => {}
        1 => text.push_str(" [and 1 more stack-hijack hazard]"),
        more => text.push_str(&format!(" [and {more} more stack-hijack hazards]")),
    }
    text
}

/// One clause of a `G4S192` warning, for example `2 predicated states report a
/// syntax error (witness: ID EOF)`. The `note` follows the witness in the
/// parentheses.
fn resolution_text(
    vocabulary: &[String],
    count: usize,
    (singular, plural): (&str, &str),
    verdict: &str,
    witness: Option<&[i32]>,
    note: Option<String>,
) -> String {
    let subject = if count == 1 { singular } else { plural };
    let mut text = format!("{count} {subject} {verdict}");
    let details: Vec<String> = witness_text(vocabulary, witness)
        .map(|witness| format!("witness: {witness}"))
        .into_iter()
        .chain(note)
        .collect();
    if !details.is_empty() {
        text.push_str(&format!(" ({})", details.join("; ")));
    }
    text
}

/// The distinct callers of the invoking states of a danger set, for a
/// `G4S192` warning, for example `danger callers: query:25, expr#cast:30`. The
/// caller of the lowest invoking state comes first.
fn danger_callers_text(report: &StaticParserDfaReport, danger: &[i32]) -> Option<String> {
    let mut callers: Vec<String> = Vec::new();
    for caller in danger
        .iter()
        .filter_map(|state| report.invoking_states.get(state))
    {
        let caller = caller.to_string();
        if !callers.contains(&caller) {
            callers.push(caller);
        }
    }
    let shown = callers.len().min(DANGER_CALLERS);
    let mut text = match callers.len() {
        0 => return None,
        1 => "danger caller: ".to_owned(),
        _ => "danger callers: ".to_owned(),
    };
    text.push_str(&callers[..shown].join(", "));
    match callers.len() - shown {
        0 => {}
        1 => text.push_str(" and 1 more danger caller"),
        more => text.push_str(&format!(" and {more} more danger callers")),
    }
    Some(text)
}

/// The caller of every invoking state in a guard danger set of a table of
/// `results`, by ATN state number.
fn danger_invoking_states(
    compiled: &CompiledParser,
    sources: &SourceSet,
    results: &[DecisionOutcome],
) -> BTreeMap<i32, InvokingState> {
    let mut states = BTreeMap::new();
    for result in results {
        for table in result.tables() {
            for state in table.guard_groups.iter().flatten() {
                states
                    .entry(*state)
                    .or_insert_with(|| invoking_state(compiled, sources, *state));
            }
        }
    }
    states
}

/// The rule of ATN state `state`, the label of the alternative of the rule
/// call that leaves the state, and the source line of the call.
fn invoking_state(compiled: &CompiledParser, sources: &SourceSet, state: i32) -> InvokingState {
    let graph_state = usize::try_from(state)
        .ok()
        .and_then(|state| compiled.graph.states.get(state));
    let rule_index = graph_state.and_then(|state| state.rule_index);
    let rule = rule_index
        .and_then(|rule| compiled.semantic.recognizer.rule_names.get(rule))
        .cloned()
        .unwrap_or_else(|| "?".to_owned());
    let span = graph_state.and_then(|state| {
        let call_origins = state
            .transitions
            .iter()
            .flat_map(|transition| compiled.provenance.transition_origins(*transition));
        let state_origins = compiled.provenance.state_origins(state.original);
        call_origins
            .chain(state_origins)
            .find_map(|origin| origin_span(compiled, origin))
    });
    let label = span.as_ref().and_then(|span| {
        let rule = compiled.semantic.unit.rules.get(rule_index?)?;
        labeled_alternative(&rule.block, span)
    });
    let line = span
        .and_then(|span| sources.line_column(span.source, span.bytes.start))
        .map(|(line, _)| line);
    InvokingState { rule, label, line }
}

/// The label of the alternative of `block` or of a nested block that holds
/// `span`. Only the outer alternatives of a rule have labels, but the
/// left-recursion rewrite can move them into nested blocks.
fn labeled_alternative(block: &Block, span: &SourceSpan) -> Option<String> {
    block.alternatives.iter().find_map(|alternative| {
        if let Some(label) = &alternative.label
            && alternative.span.source == span.source
            && alternative.span.bytes.start <= span.bytes.start
            && span.bytes.end <= alternative.span.bytes.end
        {
            return Some(label.value.clone());
        }
        alternative
            .elements
            .iter()
            .find_map(|element| match &element.kind {
                ElementKind::Block(inner) => labeled_alternative(inner, span),
                _ => None,
            })
    })
}

/// The authored span of one origin, or the span of the model node that a
/// synthetic origin belongs to.
fn origin_span(compiled: &CompiledParser, origin: &Origin) -> Option<SourceSpan> {
    match origin {
        Origin::Authored { span, .. } => Some(span.clone()),
        Origin::Synthetic { owner, .. } => model_node_span(compiled, *owner),
        _ => None,
    }
}

/// The source span of one decision, resolved through the ATN state's
/// provenance: the owning rule or element when the state was synthesized for
/// one, the authored span when the state came straight from the grammar, and
/// the whole rule as the fallback.
fn decision_span(compiled: &CompiledParser, result: &DecisionOutcome) -> Option<SourceSpan> {
    if !result.is_precedence_loop()
        && let Ok(state_number) = usize::try_from(result.state_number)
        && let Some(state) = compiled.graph.states.get(state_number)
    {
        let origins = compiled.provenance.state_origins(state.original);
        for owner in origins.iter().filter_map(|origin| match origin {
            Origin::Synthetic { owner, .. } => Some(*owner),
            _ => None,
        }) {
            if let Some(span) = model_node_span(compiled, owner) {
                return Some(span);
            }
        }
        if let Some(span) = origins.iter().find_map(|origin| match origin {
            Origin::Authored { span, .. } => Some(span),
            _ => None,
        }) {
            return Some(span.clone());
        }
    }
    let rule = compiled.semantic.unit.rules.get(result.rule_index)?;
    Some(rule.span.clone())
}

/// The budget of a decision that no rule or block budget changes,
/// and the budget of each decision, by decision number.
fn decision_budgets(
    compiled: &CompiledParser,
    budgets: &ParserDfaBudgets,
) -> (DecisionBudget, Vec<DecisionBudget>) {
    let atn = compiled.atn;
    let unit = &compiled.semantic.unit;
    let grammar = BudgetLimits::from_options(&unit.options).or(budgets.global);
    let decisions = atn
        .decision_to_state
        .iter()
        .map(|state| {
            let rule_index = usize::try_from(state.get_rule_index()).unwrap_or(usize::MAX);
            let rule = unit.rules.get(rule_index);
            let block = rule
                .zip(usize::try_from(state.get_state_number()).ok())
                .map(|(rule, state)| block_limits(compiled, state, rule))
                .unwrap_or_default();
            let rule = rule
                .map(|rule| BudgetLimits::from_options(&rule.options))
                .unwrap_or_default();
            let limits = block.or(rule).or(grammar);
            DecisionBudget::resolve(limits, atn.max_token_type)
        })
        .collect();
    (
        DecisionBudget::resolve(grammar, atn.max_token_type),
        decisions,
    )
}

/// The limits that the options of the blocks around the decision at ATN state
/// `state` of rule `rule` set. An inner block wins over an outer block.
fn block_limits(compiled: &CompiledParser, state: usize, rule: &Rule) -> BudgetLimits {
    let Some(state) = compiled.graph.states.get(state) else {
        return BudgetLimits::default();
    };
    // The immediate owner of a state is its last synthetic origin.
    let owner = compiled
        .provenance
        .state_origins(state.original)
        .iter()
        .rev()
        .find_map(|origin| match origin {
            Origin::Synthetic {
                owner: ModelNodeId::Element(element),
                ..
            } => Some(*element),
            _ => None,
        });
    let mut blocks = Vec::new();
    if owner.is_none_or(|owner| !enclosing_blocks(&rule.block, owner, &mut blocks)) {
        return BudgetLimits::default();
    }
    blocks
        .iter()
        .rev()
        .fold(BudgetLimits::default(), |limits, block| {
            limits.or(BudgetLimits::from_options(&block.options))
        })
}

/// Pushes the blocks from `block` down to the element `target` onto `path`,
/// the block of `target` included. Returns `false` when `block` does not
/// contain `target`.
fn enclosing_blocks<'a>(
    block: &'a Block,
    target: crate::grammar::model::ElementId,
    path: &mut Vec<&'a Block>,
) -> bool {
    for element in block
        .alternatives
        .iter()
        .flat_map(|alternative| &alternative.elements)
    {
        let ElementKind::Block(inner) = &element.kind else {
            if element.id == target {
                return true;
            }
            continue;
        };
        path.push(inner);
        if element.id == target || enclosing_blocks(inner, target, path) {
            return true;
        }
        path.pop();
    }
    false
}

/// The span of a model node that has grammar syntax behind it.
fn model_node_span(compiled: &CompiledParser, node: ModelNodeId) -> Option<SourceSpan> {
    match node {
        ModelNodeId::Rule(rule_id) => compiled
            .semantic
            .unit
            .rules
            .iter()
            .find(|rule| rule.id == rule_id)
            .map(rule_location),
        ModelNodeId::Element(element_id) => {
            find_element(&compiled.semantic.unit.rules, element_id).map(element_location)
        }
        _ => None,
    }
}

/// The location of a decision that belongs to a whole rule: its block.
fn rule_location(rule: &Rule) -> SourceSpan {
    rule.block.span.clone()
}

/// The location of a decision owned by one element: the element itself, or its
/// whole syntax node (label and quantifier included) when the decision *is*
/// the loop or the optional.
fn element_location(element: &Element) -> SourceSpan {
    let is_quantifier_decision = matches!(
        element.quantifier,
        Quantifier::Optional { .. } | Quantifier::ZeroOrMore { .. } | Quantifier::OneOrMore { .. }
    );
    if is_quantifier_decision {
        return element.enclosing_span.clone();
    }
    element.span.clone()
}

fn find_element(rules: &[Rule], target: crate::grammar::model::ElementId) -> Option<&Element> {
    rules
        .iter()
        .find_map(|rule| find_element_in_block(&rule.block, target))
}

fn find_element_in_block(
    block: &Block,
    target: crate::grammar::model::ElementId,
) -> Option<&Element> {
    block
        .alternatives
        .iter()
        .find_map(|alternative| find_element_in_alt(alternative, target))
}

fn find_element_in_alt(
    alternative: &Alternative,
    target: crate::grammar::model::ElementId,
) -> Option<&Element> {
    for element in &alternative.elements {
        if element.id == target {
            return Some(element);
        }
        if let ElementKind::Block(inner) = &element.kind
            && let Some(found) = find_element_in_block(inner, target)
        {
            return Some(found);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::{BudgetCutoff, DecisionBudget, NoTableReason, budget_cutoff_text, reason_text};

    /// Each reason of a decision without a table has its own text, and a
    /// precedence decision tells why its first class has no table.
    #[test]
    fn no_table_reasons_tell_why() {
        let budget = DecisionBudget::default();
        let cases = [
            (
                NoTableReason::NonGreedy,
                "the decision is a non-greedy subrule, and the generated parser predicts \
                 non-greedy subrules only with adaptive_predict",
            ),
            (
                NoTableReason::TooManyAlternatives,
                "the decision has too many alternatives for a static table",
            ),
            (
                NoTableReason::EmptyPrecedenceLoop,
                "the precedence loop has no precedence predicates to build class tables from",
            ),
            (
                NoTableReason::PredicatedStart(Some((3, 1))),
                "the decision depends on predicate 3:1, so the prediction is not input-only",
            ),
            (
                NoTableReason::PredicatedStart(None),
                "the decision depends on a predicate, so the prediction is not input-only",
            ),
            (
                NoTableReason::StartConflict,
                "SLL cannot separate the alternatives; only full-context prediction can",
            ),
            (
                NoTableReason::StartBudget(BudgetCutoff::States),
                "the SLL DFA exceeded the analysis budget (1000 states)",
            ),
            (
                NoTableReason::StartBudget(BudgetCutoff::Visits),
                "the SLL DFA exceeded the analysis budget (2000000 visited configs)",
            ),
            (
                NoTableReason::StartBudget(BudgetCutoff::Both),
                "the SLL DFA exceeded the analysis budget (1000 states and 2000000 visited configs)",
            ),
            (
                NoTableReason::LowCoverage {
                    coverage_percent: 4,
                },
                "the partial table decides 4% of the start lookahead, less than the 10% that a \
                 partial table needs",
            ),
            (
                NoTableReason::PrecedenceClasses {
                    failed: 1,
                    total: 3,
                    first: Box::new(NoTableReason::StartConflict),
                },
                "1 of 3 precedence classes have no static table: SLL cannot separate the \
                 alternatives; only full-context prediction can",
            ),
        ];
        for (reason, text) in cases {
            assert_eq!(reason_text(&reason, &budget), text, "{reason:?}");
        }
    }

    #[test]
    fn budget_cutoff_texts_name_the_exhausted_budget() {
        let budget = DecisionBudget::default();
        assert_eq!(
            budget_cutoff_text(BudgetCutoff::States, &budget),
            "the analysis budget (1000 states) stopped the lookahead; raise it with the \
             max_dfa_states option of the grammar, the rule, or the block"
        );
        assert_eq!(
            budget_cutoff_text(BudgetCutoff::Visits, &budget),
            "the analysis budget (2000000 visited configs) stopped the lookahead; raise it with \
             the max_dfa_visits option of the grammar, the rule, or the block"
        );
        assert_eq!(
            budget_cutoff_text(BudgetCutoff::Both, &budget),
            "the analysis budget (1000 states and 2000000 visited configs) stopped the lookahead; \
             raise it with the max_dfa_states and max_dfa_visits options of the grammar, the rule, \
             or the block"
        );
    }
}