tabnas-debug 0.3.11

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

//! Whole-emitter tests for `abnf`, mirroring the `TestAbnf*` set in
//! `../../go/debug_test.go` and the cases in `../../ts/test/abnf.test.js`.
//!
//! What the shared `../../test/spec/abnf.tsv` fixture already pins for
//! every runtime is NOT repeated here: alternation, `%s` literals, the
//! synthetic-optional fold, the rule/token name collision and the
//! prose-val fallback all have rows there. What is left are the grammar
//! SHAPES the fixture registry does not hold, each of which needs a
//! purpose-built instance.
//!
//! The canonical TypeScript proves most of these by round-tripping
//! through `@tabnas/abnf`. That suite cannot run here, or in Go: the
//! emitter must never gain an ABNF dependency, and neither port may take
//! one even in a test without putting that independence claim in doubt.
//! So both ports pin the same shapes by asserting the emitted text, and
//! this file is the Rust half.
//!
//! The repeat-loop shapes (`loop_*` and `abnf_renders_a_*_loop_*` below)
//! are held by this set and by the canonical's "abnf repeat loops" suite
//! in `ts/test/abnf.test.js`, which builds the same grammars and pins the
//! same text, test for test: tabnas/bnf#80 changed how every repetition
//! compiles, the Rust emitter rendered it first, and the canonical has
//! followed (`docs/reference.md`, "The repeat loop: the Go port
//! follows"). When the Go port follows too, its suite takes the same
//! shapes.

mod common;

use std::collections::HashMap;

use tabnas::{AltSpec, CompareOp, Condition, RuleSpec, Tabnas, Tin, Value};
use tabnas_debug::abnf;

/// Resolve a built-in token identity, failing loudly if the engine has
/// renamed it.
fn token(parser: &Tabnas, name: &str) -> Tin {
    parser
        .options
        .token(name)
        .unwrap_or_else(|| panic!("the engine has no {name} token"))
}

/// The parts of RFC 5234 the emitter has violated before:
///
/// ```text
/// rulename    = ALPHA *(ALPHA / DIGIT / "-")
/// alternation = concatenation *(*c-wsp "/" *c-wsp concatenation)
/// ```
///
/// so `_gen1_star_x` is not a legal name, and `x = A x /` is not a legal
/// body. Mirrors `assertRfc5234Shape` in the TypeScript and Go suites.
fn assert_rfc5234_shape(out: &str) {
    for line in out.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with(';') {
            continue;
        }
        assert!(
            !trimmed.ends_with('/'),
            "dangling `/`, every `/` needs a concatenation after it:\n{line}\n--- in ---\n{out}"
        );
        if let Some(head) = head_name(line) {
            assert!(
                is_legal_rulename(head),
                "rulename is not ALPHA *(ALPHA / DIGIT / \"-\"):\n{line}\n--- in ---\n{out}"
            );
        }
    }
}

/// The rule name a production line defines, i.e. everything before the
/// first `=`, when the line has one. Mirrors the `^([^\s=]+)\s*=` the
/// other two suites use.
fn head_name(line: &str) -> Option<&str> {
    let (head, _) = line.split_once('=')?;
    let head = head.trim();
    if head.is_empty() || head.contains(char::is_whitespace) {
        return None;
    }
    Some(head)
}

fn is_legal_rulename(name: &str) -> bool {
    let mut chars = name.chars();
    chars
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic())
        && chars.all(|ch| ch.is_ascii_alphanumeric() || '-' == ch)
}

/// The shape the ABNF compiler emitted for a repetition (`rep = *T`)
/// before tabnas/bnf#80: a `_gen…_star_…` production whose empty open
/// alternative marks it zero-or-more, and whose item alternative would
/// push the rule again for the next item (a push chain; this hand-built
/// one stops at a single item). It carries no self-replace entry, so it
/// is not a loop, and it does not reconstruct as `*( … )` reliably, so
/// the emitter must KEEP it as a production rather than fold it — exactly
/// as it did before the loop shape existed.
fn star_grammar() -> Tabnas {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "rep".into();
    let plus = parser.token_with_source("#T", "+");

    parser.define_rule("rep", |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            p: Some("_gen1_star_T".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });
    parser.define_rule("_gen1_star_T", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![plus]],
            ..Default::default()
        });
        // The empty alternative is what makes it zero-or-more.
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
    parser
}

/// An old-shape `_gen…_star_…` synthetic is NOT folded. It stays a
/// bareword reference in its parent and is emitted as its own production.
/// Beyond the folding rule this pins two things RFC 5234 requires: the
/// empty alternative renders as `[ … ]` rather than a trailing `/`, and
/// the synthetic name is sanitised to a legal rulename, so `_gen1_star_T`
/// comes out as `r-gen1-star-T`. The pinned text is unchanged by the loop
/// rendering: a rule without the self-replace entry renders as before.
#[test]
fn abnf_keeps_a_repetition_production() {
    let out = abnf(&star_grammar());
    assert_eq!(
        out, "rep = r-gen1-star-T\nr-gen1-star-T = [ T ]\n\nT = \"+\"",
        "repetition mismatch:\n{out}"
    );
    assert!(
        !out.contains("_gen"),
        "a synthetic _gen name leaked:\n{out}"
    );
    assert_rfc5234_shape(&out);
}

/// The num-val fallback for a fixed token whose literal cannot go inside
/// quotes. RFC 5234 has `char-val = DQUOTE *(%x20-21 / %x23-7E) DQUOTE`,
/// so a control character, a DQUOTE, or anything above `%x7E` has to come
/// back as `%xNN`. Quoting a CR emitted `CR = "<CR>"`, an unterminated
/// char-val.
#[test]
fn abnf_renders_an_unquotable_literal_as_a_num_val() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "top".into();
    let cr = parser.token_with_source("#CR", "\r");
    let dq = parser.token_with_source("#DQ", "\"");

    parser.define_rule("top", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![cr], vec![dq]],
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    for want in ["CR = %x0D", "DQ = %x22"] {
        assert!(out.contains(want), "missing {want:?} in:\n{out}");
    }
    assert_rfc5234_shape(&out);
}

/// The multi-character, padding and non-ASCII cases of the num-val
/// rendering, driven through the public surface rather than the private
/// helper.
#[test]
fn abnf_num_val_covers_multi_char_padding_and_non_ascii() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "top".into();
    let crlf = parser.token_with_source("#CRLF", "\r\n");
    let nul = parser.token_with_source("#NUL", "\0");
    let acc = parser.token_with_source("#ACC", "\u{e9}");
    let tab = parser.token_with_source("#TAB", "\t");

    parser.define_rule("top", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![crlf], vec![nul], vec![acc], vec![tab]],
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    for want in [
        "CRLF = %x0D.0A", // multi-character, dot-concatenated
        "NUL  = %x00",    // zero-padded to two hex digits
        "ACC  = %xE9",    // non-ASCII
        "TAB  = %x09",    // control character
    ] {
        assert!(out.contains(want), "missing {want:?} in:\n{out}");
    }
    assert_rfc5234_shape(&out);
}

/// A rule whose only open alternative is empty, but which has a close
/// continuation, emits the continuation alone.
/// `option = "[" *c-wsp alternation *c-wsp "]"` and `alternation` needs
/// at least one concatenation, so `[ ]` is not a legal option. This used
/// to emit `inner = [  ] AA`.
#[test]
fn abnf_emits_a_continuation_alone_not_an_empty_option() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "top".into();
    let xa = parser.token_with_source("#XA", "a");
    let zz = token(&parser, "#ZZ");

    parser.define_rule("top", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            p: Some("inner".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![zz]],
            ..Default::default()
        });
    });
    parser.define_rule("inner", move |spec| {
        spec.clear();
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            s: vec![vec![xa]],
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![zz]],
            ..Default::default()
        });
    });

    let out = abnf(&parser);
    assert!(!has_empty_option(&out), "an empty `[ ]` option in:\n{out}");
    assert_rfc5234_shape(&out);
}

/// `[` then only whitespace then `]`, the shape the other two suites
/// match with the regex `\[\s*\]`.
fn has_empty_option(out: &str) -> bool {
    let bytes: Vec<char> = out.chars().collect();
    for (index, ch) in bytes.iter().enumerate() {
        if '[' != *ch {
            continue;
        }
        let mut cursor = index + 1;
        while cursor < bytes.len() && bytes[cursor].is_whitespace() {
            cursor += 1;
        }
        if cursor < bytes.len() && ']' == bytes[cursor] {
            return true;
        }
    }
    false
}

/// RFC 5234 §2.1: rule names are case-insensitive, so `Foo-Bar` and
/// `foo-bar` are ONE rule. Sanitising `foo_bar` beside a reserved
/// `Foo-Bar` used to emit two definitions of the same rule.
#[test]
fn abnf_rulename_collisions_are_case_insensitive() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "top".into();
    let xa = parser.token_with_source("#XA", "a");
    let xb = parser.token_with_source("#XB", "b");
    let zz = token(&parser, "#ZZ");

    parser.define_rule("top", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![xa]],
            p: Some("Foo-Bar".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec {
            s: vec![vec![xb]],
            p: Some("foo_bar".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![zz]],
            ..Default::default()
        });
    });
    parser.define_rule("Foo-Bar", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![xa]],
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });
    parser.define_rule("foo_bar", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![xb]],
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    let mut seen: Vec<String> = Vec::new();
    for line in out.lines() {
        let Some(head) = head_name(line) else {
            continue;
        };
        let key = head.to_lowercase();
        assert!(
            !seen.contains(&key),
            "two productions define the same rule (case-insensitively): {head:?} in:\n{out}"
        );
        seen.push(key);
    }
    assert_rfc5234_shape(&out);
}

/// The skip branch of an optional arrives as a FIRST-set-guarded epsilon:
/// an alt carrying the FOLLOW token in `s` with `b` set and NO
/// push/replace target. The token is lookahead, matched to choose the
/// branch and then backtracked, so the alt consumes nothing
/// (`s.len() - b == 0`).
///
/// The emitter used to skip `s` only when `b` was set AND the alt pushed
/// or replaced, so this shape rendered as a CONSUMING alternative:
/// `top = [ X "@" ] Y` came back as `top = [ X T / Y ] Y`, where the
/// optional could swallow the follow and leave nothing for the trailing
/// `Y`.
#[test]
fn abnf_does_not_render_a_follow_guarded_epsilon_as_an_alternative() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "top".into();
    let at = parser.token_with_source("#T", "@");
    let yy = parser.token_with_source("#Y", "b");
    let xx = parser.options.register_token("#X");

    parser.define_rule("top", |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            p: Some("_gen2_opt__gen1_group".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec {
            r: Some("top$step1".into()),
            ..Default::default()
        });
    });
    parser.define_rule("top$step1", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![yy]],
            ..Default::default()
        });
    });
    parser.define_rule("_gen1_group", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![xx], vec![at]],
            ..Default::default()
        });
    });
    parser.define_rule("_gen2_opt__gen1_group", move |spec| {
        spec.clear();
        // Take the optional: peek #X, the pushed group consumes it.
        spec.add_open(AltSpec {
            s: vec![vec![xx]],
            b: 1,
            p: Some("_gen1_group".into()),
            ..Default::default()
        });
        // Skip it: peek the FOLLOW #Y and consume nothing. The shape at
        // issue.
        spec.add_open(AltSpec {
            s: vec![vec![yy]],
            b: 1,
            ..Default::default()
        });
        // Bare epsilon.
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    for line in out.lines() {
        if !line.trim_start().starts_with("top") {
            continue;
        }
        // The follow token must not appear as an alternative INSIDE the
        // option. `top = [ X T ] Y` is right; `top = [ X T / Y ] Y` is
        // the defect.
        if let Some(close) = line.find(']') {
            assert!(
                !line[..close].contains('/'),
                "a follow-guarded epsilon rendered as a consuming alternative:\n{line}\n--- in ---\n{out}"
            );
        }
    }
    assert_rfc5234_shape(&out);
}

/// Every grammar in the shared registry emits ABNF that obeys the two
/// RFC 5234 shapes above. The `.tsv` fixture pins the exact bytes for
/// each; this pins the property, so a new fixture grammar cannot land an
/// illegal name or a dangling `/` merely by having its row regenerated
/// from the canonical runtime.
#[test]
fn every_fixture_grammar_emits_rfc5234_shaped_abnf() {
    for name in ["bare", "add", "greet", "collide"] {
        let parser = common::fixture::build(name).expect("a known grammar");
        assert_rfc5234_shape(&abnf(&parser));
    }
}

// ---------------------------------------------------------------------
// The repeat loop: the shape every repetition compiles to since
// tabnas/bnf#80. Hand-built here, alternate for alternate, from what the
// compiler emits (the emitter must never gain an ABNF dependency, so no
// test compiles ABNF source), for `*A` with helper `H`:
//
//   H             open   { c: {n.rep: 0}, n: {rep: 1}, r: H }   entry: allocate, count
//                        { s: FIRST(A), b: 1, r: H$alt0 } …     continue (a ref item)
//                        { s: A, r: H }                         continue (a terminal item)
//                        { s: FOLLOW(H), b: 1 }  { }            exits
//   H$alt0        open   { p: A, n: {rep: 0} }                  push the item
//                 close  { r: H$alt0$step1, n: {rep: 1} }       capture it
//   H$alt0$step1  open   { r: H }                               back to the loop
//
// and the whole grammar wrapped in the compiler's `__start__`.
// ---------------------------------------------------------------------

/// The `__start__` wrapper the bnf compiler puts round every grammar: its
/// open pushes the real start rule and its close matches `#ZZ`. The
/// emitter sees through it and leads with the real start.
fn wrap_start(parser: &mut Tabnas, start: &str) {
    let end = token(parser, "#ZZ");
    parser.options.rule.start = "__start__".into();
    let start = start.to_string();
    parser.define_rule("__start__", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            p: Some(start),
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![end]],
            ..Default::default()
        });
    });
}

/// A loop's entry: consumes nothing, replaces the rule with itself,
/// guarded by the iteration counter it bumps. Bookkeeping, not syntax.
fn loop_entry(name: &str) -> AltSpec {
    counted(
        AltSpec {
            c: vec![Condition {
                path: vec!["n".into(), "rep".into()],
                op: CompareOp::Eq,
                value: Value::Number(0.0),
            }],
            r: Some(name.into()),
            ..Default::default()
        },
        1,
    )
}

fn counted(alt: AltSpec, rep: i32) -> AltSpec {
    AltSpec {
        n: HashMap::from([("rep".to_string(), rep)]),
        ..alt
    }
}

/// A loop's exits: peek the FOLLOW token and give it back, then anything
/// else (and the end of the input).
fn loop_exits(spec: &mut RuleSpec, follow: Tin) {
    spec.add_open(AltSpec {
        s: vec![vec![follow]],
        b: 1,
        ..Default::default()
    });
    spec.add_open(AltSpec::new());
}

/// `*A` over a terminal item: the continue matches the token and
/// re-enters the loop directly.
fn terminal_loop(parser: &mut Tabnas, name: &str, item: Tin, follow: Tin) {
    let rule = name.to_string();
    parser.define_rule(name, move |spec| {
        spec.clear();
        spec.add_open(loop_entry(&rule));
        spec.add_open(AltSpec {
            s: vec![vec![item]],
            r: Some(rule.clone()),
            ..Default::default()
        });
        loop_exits(spec, follow);
    });
}

/// `*A` over a rule item: one continue per FIRST token of the item,
/// each peeking it and replacing with the iteration `H$alt0`, which
/// pushes the item and, on close, replaces with `H$alt0$step1`, which
/// replaces with `H`.
fn ref_loop(parser: &mut Tabnas, name: &str, firsts: &[Tin], item: &str, follow: Tin) {
    let rule = name.to_string();
    let iteration = format!("{name}$alt0");
    let step = format!("{iteration}$step1");
    let firsts = firsts.to_vec();
    let iteration_for_loop = iteration.clone();
    parser.define_rule(name, move |spec| {
        spec.clear();
        spec.add_open(loop_entry(&rule));
        for first in firsts {
            spec.add_open(AltSpec {
                s: vec![vec![first]],
                b: 1,
                r: Some(iteration_for_loop.clone()),
                ..Default::default()
            });
        }
        loop_exits(spec, follow);
    });
    let item = item.to_string();
    let step_for_iteration = step.clone();
    parser.define_rule(iteration, move |spec| {
        spec.clear();
        spec.add_open(counted(
            AltSpec {
                p: Some(item),
                ..Default::default()
            },
            0,
        ));
        spec.add_close(counted(
            AltSpec {
                r: Some(step_for_iteration),
                ..Default::default()
            },
            1,
        ));
    });
    let rule = name.to_string();
    parser.define_rule(step, move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            r: Some(rule),
            ..Default::default()
        });
    });
}

/// A rule of one open alternative and an empty close.
fn simple_rule(parser: &mut Tabnas, name: &str, open: AltSpec, close: Option<AltSpec>) {
    parser.define_rule(name, move |spec| {
        spec.clear();
        spec.add_open(open);
        if let Some(close) = close {
            spec.add_close(close);
        }
    });
}

/// The compiler's `[ X ]` over a rule: take it when its FIRST token is
/// next (peek, then the pushed rule consumes it), skip it on a FOLLOW
/// token or on anything else.
fn optional_of(parser: &mut Tabnas, name: &str, first: Tin, item: &str, follows: &[Tin]) {
    let item = item.to_string();
    let follows = follows.to_vec();
    parser.define_rule(name, move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![first]],
            b: 1,
            p: Some(item),
            ..Default::default()
        });
        for follow in follows {
            spec.add_open(AltSpec {
                s: vec![vec![follow]],
                b: 1,
                ..Default::default()
            });
        }
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
}

/// `[ "x" ]` as the compiler builds it: a group holding the token, and
/// the optional over the group, named after it. Returns the optional's
/// name, `_gen<index+1>_opt__gen<index>_group`.
fn optional_group(parser: &mut Tabnas, index: u32, item: Tin, follows: &[Tin]) -> String {
    let group = format!("_gen{index}_group");
    let opt = format!("_gen{}_opt_{group}", index + 1);
    simple_rule(
        parser,
        &group,
        AltSpec {
            s: vec![vec![item]],
            ..Default::default()
        },
        None,
    );
    optional_of(parser, &opt, item, &group, follows);
    opt
}

/// The compiler's `1*X` over a rule item: the helper pushes the item
/// and, on close, replaces with a step that pushes the star of the item.
fn plus_chain(parser: &mut Tabnas, name: &str, item: &str, star: &str) {
    let step = format!("{name}$step1");
    simple_rule(
        parser,
        name,
        AltSpec {
            p: Some(item.into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some(step.clone()),
            ..Default::default()
        }),
    );
    simple_rule(
        parser,
        &step,
        AltSpec {
            p: Some(star.into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
}

/// The text a loop test pins, plus the two RFC 5234 shapes and the
/// absence of any leaked synthetic: neither `_gen` / `r-gen` nor the
/// `$alt` / `-alt` of an iteration helper may reach the output.
fn assert_loop_abnf(out: &str, want: &str) {
    assert_eq!(
        out, want,
        "loop rendering mismatch:\n--- got ---\n{out}\n--- want ---\n{want}"
    );
    for leak in ["_gen", "r-gen", "$", "-alt", "step1"] {
        assert!(!out.contains(leak), "a synthetic {leak:?} leaked:\n{out}");
    }
    assert_rfc5234_shape(out);
}

/// `rep = *"a"`: a terminal item. This is THE defect shape: with the
/// entry counted as an alternative the loop rendered as
/// `r-gen1-star-term = [ r-gen1-star-term / A ]`, a production that
/// names itself and, recompiled, accepts less than the original.
#[test]
fn abnf_renders_a_terminal_loop_as_a_star() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "rep",
        AltSpec {
            p: Some("_gen1_star_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    terminal_loop(&mut parser, "_gen1_star_term", a, end);
    wrap_start(&mut parser, "rep");

    assert_loop_abnf(&abnf(&parser), "rep = *A\n\nA = %s\"a\"");
}

/// `rep = 1*"a"`: the `_plus` helper is `A` followed by the star of `A`.
/// With the star a loop the helper folds, and is written back as the
/// `1*A` it was compiled from — not the `A *A` it is element by element.
/// The two recognise the same language, but the abnf crate does not
/// compile them to the same recogniser: where the item is nullable
/// (`1*( [ "+" "e" ] )`) or its FIRST meets its FOLLOW (`1*item` with
/// `item = "]" "e" / [ "d" ]`), the recompiled `A *A` rejected `+e` and
/// `]e`, which the original accepts. This pinned `rep = A *A` until that
/// round trip failed. (With an old-shape star the helper stays a
/// production, as it always did: see
/// `abnf_keeps_an_old_shape_plus_production`.)
#[test]
fn abnf_renders_a_plus_over_a_loop_as_one_or_more() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "rep",
        AltSpec {
            p: Some("_gen1_plus_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    terminal_loop(&mut parser, "_gen1_star_term", a, end);
    simple_rule(
        &mut parser,
        "_gen1_plus_term",
        AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    wrap_start(&mut parser, "rep");

    assert_loop_abnf(&abnf(&parser), "rep = 1*A\n\nA = %s\"a\"");
}

/// `doc = *item` with `item = "x" "y"`: a rule item, so the loop goes
/// through the iteration helpers. `item` keeps its production; `H$alt0`
/// and `H$alt0$step1` do not get one, and their back edges render
/// nothing. The helpers are installed BEFORE the loop, as the compiler
/// installs them, so a production order that merely followed insertion
/// would have leaked them first.
#[test]
fn abnf_renders_a_ref_loop_as_a_star_of_the_rule() {
    let mut parser = Tabnas::new();
    let x = parser.token_with_source("#X", "x");
    let y = parser.token_with_source("#Y", "y");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "doc",
        AltSpec {
            p: Some("_gen1_star_item".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![x], vec![y]],
            ..Default::default()
        },
        None,
    );
    ref_loop(&mut parser, "_gen1_star_item", &[x], "item", end);
    wrap_start(&mut parser, "doc");

    assert_loop_abnf(
        &abnf(&parser),
        "doc = *item\nitem = X Y\n\nX = %s\"x\"\nY = %s\"y\"",
    );
}

/// `list = "[" *( "," item ) "]"` with `item = "x"`: a loop inside a
/// sequence, over a group. The group folds into the iteration, the
/// loop's FOLLOW is the closing bracket (peeked by the exit, never
/// rendered), and the `"]"` comes from `list`'s own chain step.
#[test]
fn abnf_renders_a_group_loop_inside_a_sequence() {
    let mut parser = Tabnas::new();
    let open = parser.token_with_source("#T", "[");
    let close = parser.token_with_source("#T1", "]");
    let comma = parser.token_with_source("#T2", ",");
    let x = parser.token_with_source("#X", "x");
    simple_rule(
        &mut parser,
        "list",
        AltSpec {
            s: vec![vec![open]],
            p: Some("_gen2_star__gen1_group".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("list$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "list$step1",
        AltSpec {
            s: vec![vec![close]],
            ..Default::default()
        },
        None,
    );
    simple_rule(
        &mut parser,
        "_gen1_group",
        AltSpec {
            s: vec![vec![comma]],
            p: Some("item".into()),
            ..Default::default()
        },
        None,
    );
    ref_loop(
        &mut parser,
        "_gen2_star__gen1_group",
        &[comma],
        "_gen1_group",
        close,
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![x]],
            ..Default::default()
        },
        None,
    );
    wrap_start(&mut parser, "list");

    assert_loop_abnf(
        &abnf(&parser),
        "list = T *( T2 item ) T1\nitem = X\n\nT  = \"[\"\nT2 = \",\"\nT1 = \"]\"\nX  = %s\"x\"",
    );
}

/// `s = *( "a" / "b" ) ";"`: a loop over a two-way group has one
/// continue per FIRST token, both replacing with the same iteration. The
/// iteration renders once, as the parenthesised alternation, and the
/// repetition wraps it exactly once: `*( A / B )`, not `*( ( A / B ) )`.
#[test]
fn abnf_renders_a_loop_over_alternatives_once() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let semi = parser.token_with_source("#T", ";");
    simple_rule(
        &mut parser,
        "s",
        AltSpec {
            p: Some("_gen2_star__gen1_group".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("s$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "s$step1",
        AltSpec {
            s: vec![vec![semi]],
            ..Default::default()
        },
        None,
    );
    parser.define_rule("_gen1_group", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            ..Default::default()
        });
        spec.add_open(AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        });
    });
    ref_loop(
        &mut parser,
        "_gen2_star__gen1_group",
        &[a, b],
        "_gen1_group",
        semi,
    );
    wrap_start(&mut parser, "s");

    assert_loop_abnf(
        &abnf(&parser),
        "s = *( A / B ) T\n\nA = %s\"a\"\nB = %s\"b\"\nT = \";\"",
    );
}

/// `outer = *( "<" *"i" ">" )`: a loop nested in a loop's iteration. The
/// inner loop is a loop of its own, rendered as `*I` inside the outer
/// iteration; the outer's exit peeks `#ZZ`, the inner's peeks `">"`.
#[test]
fn abnf_renders_a_loop_nested_in_a_loop() {
    let mut parser = Tabnas::new();
    let lt = parser.token_with_source("#T", "<");
    let gt = parser.token_with_source("#T1", ">");
    let i = parser.token_with_source("#I", "i");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "outer",
        AltSpec {
            p: Some("_gen3_star__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    terminal_loop(&mut parser, "_gen1_star_term", i, gt);
    simple_rule(
        &mut parser,
        "_gen2_group",
        AltSpec {
            s: vec![vec![lt]],
            p: Some("_gen1_star_term".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("_gen2_group$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "_gen2_group$step1",
        AltSpec {
            s: vec![vec![gt]],
            ..Default::default()
        },
        None,
    );
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_group",
        &[lt],
        "_gen2_group",
        end,
    );
    wrap_start(&mut parser, "outer");

    assert_loop_abnf(
        &abnf(&parser),
        "outer = *( T *I T1 )\n\nT  = \"<\"\nI  = %s\"i\"\nT1 = \">\"",
    );
}

/// `rep = 2*"a"`: a counted repetition compiles to a `_rep` helper, the
/// item `n` times then the star of the item, in one alternative for a
/// terminal item. It is written back as `2*A` for the reason `1*A` is.
#[test]
fn abnf_renders_a_counted_repetition_over_a_loop_with_its_count() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "rep",
        AltSpec {
            p: Some("_gen1_rep_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    terminal_loop(&mut parser, "_gen1_star_term", a, end);
    simple_rule(
        &mut parser,
        "_gen1_rep_term",
        AltSpec {
            s: vec![vec![a], vec![a]],
            p: Some("_gen1_star_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    wrap_start(&mut parser, "rep");

    assert_loop_abnf(&abnf(&parser), "rep = 2*A\n\nA = %s\"a\"");
}

/// `n = 2*4"z"`: a bounded repetition compiles to a `_rep` helper too,
/// but one that ends in nested optionals rather than a loop. Its body is
/// not an item then a repetition, so it renders as it is; the count
/// rewrite must not reach for a `_rep` name alone.
#[test]
fn abnf_leaves_a_bounded_repetition_as_its_optionals() {
    let mut parser = Tabnas::new();
    let z = parser.token_with_source("#Z", "z");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "n",
        AltSpec {
            p: Some("_gen1_rep_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    let inner = optional_group(&mut parser, 1, z, &[end]);
    simple_rule(
        &mut parser,
        "_gen3_group",
        AltSpec {
            s: vec![vec![z]],
            p: Some(inner),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    optional_of(
        &mut parser,
        "_gen4_opt__gen3_group",
        z,
        "_gen3_group",
        &[end],
    );
    simple_rule(
        &mut parser,
        "_gen1_rep_term",
        AltSpec {
            s: vec![vec![z], vec![z]],
            p: Some("_gen4_opt__gen3_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    wrap_start(&mut parser, "n");

    assert_loop_abnf(&abnf(&parser), "n = Z Z [ Z [ Z ] ]\n\nZ = %s\"z\"");
}

/// `top = *[ "," ]`: a loop over an optional. The star's helper is named
/// after its item, `_gen3_star__gen2_opt__gen1_group`, and so are its
/// iteration helpers, and deciding the `[ … ]` wrap by a substring test
/// for `_opt` reached all three: the option was wrapped again, and the
/// step, whose only content is the back edge, became the empty option in
/// `*[ [ T ] [  ] ]`. RFC 5234 has no room for it: an option holds an
/// alternation, and an alternation at least one concatenation. Read from
/// the rule's own segment, only the optional's helper is an optional.
/// (The optional's exits peek the item's own token as well as the end:
/// inside a loop, the item is its own FOLLOW.)
#[test]
fn abnf_renders_a_loop_over_an_optional_without_an_empty_option() {
    let mut parser = Tabnas::new();
    let comma = parser.token_with_source("#T", ",");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_star__gen2_opt__gen1_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    let opt = optional_group(&mut parser, 1, comma, &[comma, end]);
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_opt__gen1_group",
        &[comma],
        &opt,
        end,
    );
    wrap_start(&mut parser, "top");

    let out = abnf(&parser);
    assert!(!has_empty_option(&out), "an empty `[ ]` option in:\n{out}");
    assert_loop_abnf(&out, "top = *[ T ]\n\nT = \",\"");
}

/// `top = 1*[ "a" ]`: the `_plus` helper over an optional is named after
/// it too (`_gen3_plus__gen2_opt__gen1_group`), as is its chain step. The
/// same substring test rendered `[ [ A ] [ *[ [ A ] [  ] ] ] ]`; the
/// helper is a plus, its step a step, and the whole is the `1*[ A ]` it
/// came from.
#[test]
fn abnf_renders_a_plus_over_an_optional_loop_as_one_or_more() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_plus__gen2_opt__gen1_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    let opt = optional_group(&mut parser, 1, a, &[a, end]);
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_opt__gen1_group",
        &[a],
        &opt,
        end,
    );
    plus_chain(
        &mut parser,
        "_gen3_plus__gen2_opt__gen1_group",
        &opt,
        "_gen3_star__gen2_opt__gen1_group",
    );
    wrap_start(&mut parser, "top");

    let out = abnf(&parser);
    assert!(!has_empty_option(&out), "an empty `[ ]` option in:\n{out}");
    assert_loop_abnf(&out, "top = 1*[ A ]\n\nA = %s\"a\"");
}

/// `top = 1*( "a" "b" )` and `top = 1*( "a" / "b" )`: a plus over a
/// group. The loop writes the sequence as `*( A B )` and the alternation,
/// already one parenthesised element, as `*( A / B )`; the plus is the
/// item as the loop wrote it, once, then the loop, in either spelling,
/// and comes back as `1*( A B )` and `1*( A / B )`.
#[test]
fn abnf_renders_a_plus_over_a_group_loop_as_one_or_more() {
    for (alternation, want) in [
        (false, "top = 1*( A B )\n\nA = %s\"a\"\nB = %s\"b\""),
        (true, "top = 1*( A / B )\n\nA = %s\"a\"\nB = %s\"b\""),
    ] {
        let mut parser = Tabnas::new();
        let a = parser.token_with_source("#A", "a");
        let b = parser.token_with_source("#B", "b");
        let end = token(&parser, "#ZZ");
        simple_rule(
            &mut parser,
            "top",
            AltSpec {
                p: Some("_gen2_plus__gen1_group".into()),
                ..Default::default()
            },
            Some(AltSpec::new()),
        );
        parser.define_rule("_gen1_group", move |spec| {
            spec.clear();
            if alternation {
                spec.add_open(AltSpec {
                    s: vec![vec![a]],
                    ..Default::default()
                });
                spec.add_open(AltSpec {
                    s: vec![vec![b]],
                    ..Default::default()
                });
            } else {
                spec.add_open(AltSpec {
                    s: vec![vec![a], vec![b]],
                    ..Default::default()
                });
            }
        });
        let firsts: &[Tin] = if alternation { &[a, b] } else { &[a] };
        ref_loop(
            &mut parser,
            "_gen2_star__gen1_group",
            firsts,
            "_gen1_group",
            end,
        );
        plus_chain(
            &mut parser,
            "_gen2_plus__gen1_group",
            "_gen1_group",
            "_gen2_star__gen1_group",
        );
        wrap_start(&mut parser, "top");

        assert_loop_abnf(&abnf(&parser), want);
    }
}

/// Design point 5: a grammar in the OLD shape renders exactly as before.
/// `1*"a"` compiled to a `_plus` helper pushing a push-chain star; the
/// star is a kept production, so the helper stays one too, and the output
/// is what the emitter gave before the loop shape existed: the productions
/// in installation order (the compiler installs the star before the plus),
/// the star's empty alternative as `[ … ]`.
#[test]
fn abnf_keeps_an_old_shape_plus_production() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "rep".into();
    let a = parser.token_with_source("#A", "a");
    simple_rule(
        &mut parser,
        "rep",
        AltSpec {
            p: Some("_gen1_plus_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        // The push chain: each item pushes the rule again.
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
    simple_rule(
        &mut parser,
        "_gen1_plus_A",
        AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );

    let out = abnf(&parser);
    assert_eq!(
        out,
        "rep = r-gen1-plus-A\nr-gen1-star-A = [ A r-gen1-star-A ]\nr-gen1-plus-A = A r-gen1-star-A\n\nA = %s\"a\"",
        "old-shape plus mismatch:\n{out}"
    );
    assert_rfc5234_shape(&out);
}

/// A user rule with a non-consuming self-replace open alternative that is
/// NOT a loop entry: a guarded or counted state transition, such as
/// `{ c: [n.mode == 0], n: {mode: 1}, r: st }`. Its `s`, `b`, `p` and
/// `r` are the entry's, and it is no repetition: the entry's own guard
/// `n.rep == 0` and its counter set to 1 are part of the shape, and each
/// is tried without the other here too. Read as a loop, the whole rule
/// was rewritten as `st = *( A / B )`, accepting the empty input and any
/// number of items where the original takes one. It renders as the
/// emitter always rendered it, a reference to the rule among its
/// alternatives (`st = st / A / B` is what origin/main emits), and never
/// as `*…`.
#[test]
fn abnf_does_not_read_an_unguarded_self_replace_as_a_loop() {
    let guard = |name: &str, value: f64| Condition {
        path: vec!["n".into(), name.into()],
        op: CompareOp::Eq,
        value: Value::Number(value),
    };
    let transitions = [
        // Another counter's transition.
        AltSpec {
            c: vec![guard("mode", 0.0)],
            n: HashMap::from([("mode".to_string(), 1)]),
            r: Some("st".into()),
            ..Default::default()
        },
        // The bare self-replace.
        AltSpec {
            r: Some("st".into()),
            ..Default::default()
        },
        // The guard without the counter.
        AltSpec {
            c: vec![guard("rep", 0.0)],
            r: Some("st".into()),
            ..Default::default()
        },
        // The counter without the guard.
        counted(
            AltSpec {
                r: Some("st".into()),
                ..Default::default()
            },
            1,
        ),
    ];
    for transition in transitions {
        let mut parser = Tabnas::new();
        parser.options.rule.start = "st".into();
        let a = parser.token_with_source("#A", "a");
        let b = parser.token_with_source("#B", "b");
        parser.define_rule("st", move |spec| {
            spec.clear();
            spec.add_open(transition);
            spec.add_open(AltSpec {
                s: vec![vec![a]],
                ..Default::default()
            });
            spec.add_open(AltSpec {
                s: vec![vec![b]],
                ..Default::default()
            });
            spec.add_close(AltSpec::new());
        });

        let out = abnf(&parser);
        assert_eq!(
            out, "st = st / A / B\n\nA = %s\"a\"\nB = %s\"b\"",
            "a self-replace that is not the loop entry:\n{out}"
        );
        assert!(!out.contains('*'), "read as a repetition:\n{out}");
        assert_rfc5234_shape(&out);
    }
}

/// `one = A [ one ]`, hand-built as a guarded close continuation: the
/// open consumes `A`, and the closes are `{ s: A, b: 1, r: one }`, which
/// peeks the next `A` and re-enters the rule, and `{ }`. The continuation
/// replaces with the rule being rendered and is not its loop entry (a
/// close, and unguarded), so it keeps its content. Calling it empty for
/// the self-replace alone skipped it and emitted `one = A`: exactly one
/// where the rule takes one or more. origin/main emits the pinned text.
#[test]
fn abnf_keeps_a_guarded_self_replacing_close_continuation() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "one".into();
    let a = parser.token_with_source("#A", "a");
    parser.define_rule("one", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![a]],
            b: 1,
            r: Some("one".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    assert_eq!(
        out, "one = A [ one ]\n\nA = %s\"a\"",
        "one-or-more continuation mismatch:\n{out}"
    );
    assert_rfc5234_shape(&out);
}

/// The open alternatives of a rule, over the tokens `A` and `B`.
type Opens = fn(Tin, Tin) -> Vec<AltSpec>;

/// A rule of the given open alternatives, named `once` and started
/// from, with no close.
fn rule_of_opens(opens: Opens) -> String {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "once".into();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    parser.define_rule("once", move |spec| {
        spec.clear();
        for alt in opens(a, b) {
            spec.add_open(alt);
        }
    });
    abnf(&parser)
}

/// The entry alone does not make a loop: the whole scaffold does, the
/// entry first, continues that each come back to the rule having taken
/// something, and an exit that shadows none of them. Each rule
/// here has the entry and not the rest, and none of them repeats
/// anything:
///
/// - the continue `{ s: A }` never comes back, so with the exit the rule
///   takes one `A` or nothing;
/// - `{ s: A, r: once }` comes back and `{ s: B }` does not, so a `B`
///   ends the rule;
/// - the continue comes back and there is no exit, so the rule never
///   stops;
/// - the continue pushes as well as replacing, and the engine takes the
///   push and not the replace;
/// - the continue only peeks and comes back, taking nothing;
/// - the empty exit `{ }` comes before the continue, which it shadows;
/// - the entry comes after a continue, not first as the compiler puts
///   it;
/// - an empty exit with a condition comes before the continue, which it
///   shadows whenever the condition holds;
/// - a function decides the entry's route;
/// - a second entry follows the continue, with an exit after it or
///   none: the compiler writes one, and a second is neither a continue
///   nor an exit;
/// - the only exit carries a condition, which may never hold, and the
///   compiler never guards an exit;
/// - the only exit is a FOLLOW peek, with no empty exit, so the rule
///   stops only where that token comes next;
/// - the entry carries a further condition, which may keep it from
///   setting the counter the continue is guarded on;
/// - the entry peeks a token, and so sets the counter only where that
///   token comes next;
/// - a continue is guarded on `n.rep == 0`, which the entry has already
///   left behind, and a continue may carry no guard but the compiler's
///   suffix-debt counter;
/// - a FOLLOW peek before the only continue covers it, so it never runs;
/// - a peek covers one continue, whose item no live continue takes, so
///   rendering it would offer an alternative the rule never takes;
/// - a continue consumes an empty token slot, which takes any token and
///   renders as nothing;
/// - the entry sets a further counter, which turns off a continue
///   guarded on it;
/// - a function decides the continue's route.
///
/// Read as a loop on its entry alone, all but one rendered as `*A`, which
/// takes any number, and the one that takes nothing as `once = `, which
/// RFC 5234 has no room for. Each renders as debug's main emits it, the entry a
/// reference to the rule among its alternatives, with no repetition. The
/// whole scaffold, last, still reads as the loop it is.
#[test]
fn abnf_does_not_read_an_entry_without_its_scaffold_as_a_loop() {
    fn back(tin: Tin) -> AltSpec {
        AltSpec {
            s: vec![vec![tin]],
            r: Some("once".into()),
            ..Default::default()
        }
    }
    fn take(tin: Tin) -> AltSpec {
        AltSpec {
            s: vec![vec![tin]],
            ..Default::default()
        }
    }
    let cases: [(&str, Opens, &str); 21] = [
        (
            "a continue that never comes back",
            |a, _| vec![loop_entry("once"), take(a), AltSpec::new()],
            "once = [ once / A ]\n\nA = %s\"a\"",
        ),
        (
            "one continue of two that does not come back",
            |a, b| vec![loop_entry("once"), back(a), take(b), AltSpec::new()],
            "once = [ once / A once / B ]\n\nA = %s\"a\"\nB = %s\"b\"",
        ),
        (
            "no exit",
            |a, _| vec![loop_entry("once"), back(a)],
            "once = once / A once\n\nA = %s\"a\"",
        ),
        (
            "a continue that pushes as well as replacing, which the engine takes as a push",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        s: vec![vec![a]],
                        p: Some("once".into()),
                        r: Some("once".into()),
                        ..Default::default()
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a continue that only peeks and comes back, taking nothing",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        s: vec![vec![a]],
                        b: 1,
                        r: Some("once".into()),
                        ..Default::default()
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once ]",
        ),
        (
            "the empty exit before the continue, which it shadows",
            |a, _| vec![loop_entry("once"), AltSpec::new(), back(a)],
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "the entry after a continue",
            |a, _| vec![back(a), loop_entry("once"), AltSpec::new()],
            "once = [ A once / once ]\n\nA = %s\"a\"",
        ),
        (
            "an empty exit with a condition before the continue, which shadows it when the condition holds",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "x".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(0.0),
                        }],
                        ..Default::default()
                    },
                    back(a),
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "an entry whose route a function decides",
            |a, _| {
                vec![
                    AltSpec {
                        r_fn: Some(std::sync::Arc::new(|_, _| None)),
                        ..loop_entry("once")
                    },
                    back(a),
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a second entry after the continue, with no exit",
            |a, _| vec![loop_entry("once"), back(a), loop_entry("once")],
            "once = once / A once\n\nA = %s\"a\"",
        ),
        (
            "a second entry after the continue, before the exit",
            |a, _| vec![loop_entry("once"), back(a), loop_entry("once"), AltSpec::new()],
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "an exit under a condition that may never hold",
            |a, _| {
                vec![
                    loop_entry("once"),
                    back(a),
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "never".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(1.0),
                        }],
                        ..Default::default()
                    },
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a FOLLOW peek and no empty exit",
            |a, b| {
                vec![
                    loop_entry("once"),
                    back(a),
                    AltSpec {
                        s: vec![vec![b]],
                        b: 1,
                        ..Default::default()
                    },
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "an entry under a further condition, before a continue guarded on the counter it sets",
            |a, _| {
                let mut entry = loop_entry("once");
                entry.c.push(Condition {
                    path: vec!["n".into(), "never".into()],
                    op: CompareOp::Eq,
                    value: Value::Number(1.0),
                });
                vec![
                    entry,
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "rep".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(1.0),
                        }],
                        ..back(a)
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "an entry that peeks a token, before a continue guarded on the counter it sets",
            |a, b| {
                vec![
                    AltSpec {
                        s: vec![vec![b]],
                        b: 1,
                        ..loop_entry("once")
                    },
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "rep".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(1.0),
                        }],
                        ..back(a)
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a continue guarded on the state the entry has already left",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "rep".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(0.0),
                        }],
                        ..back(a)
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a FOLLOW peek before the only continue, covering it",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        s: vec![vec![a]],
                        b: 1,
                        ..Default::default()
                    },
                    back(a),
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "an entry that sets a further counter a continue is guarded on",
            |a, _| {
                let mut entry = loop_entry("once");
                entry.n.insert("debt_x".into(), 1);
                vec![
                    entry,
                    AltSpec {
                        c: vec![Condition {
                            path: vec!["n".into(), "debt_x".into()],
                            op: CompareOp::Eq,
                            value: Value::Number(0.0),
                        }],
                        ..back(a)
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
        (
            "a dead continue with an item no live continue takes",
            |a, b| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        s: vec![vec![a]],
                        b: 1,
                        ..Default::default()
                    },
                    back(a),
                    back(b),
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once / B once ]\n\nA = %s\"a\"\nB = %s\"b\"",
        ),
        (
            "a continue that consumes an empty token slot",
            |_, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        s: vec![vec![]],
                        r: Some("once".into()),
                        ..Default::default()
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once ]",
        ),
        (
            "a continue whose route a function decides",
            |a, _| {
                vec![
                    loop_entry("once"),
                    AltSpec {
                        r_fn: Some(std::sync::Arc::new(|_, _| None)),
                        ..back(a)
                    },
                    AltSpec::new(),
                ]
            },
            "once = [ once / A once ]\n\nA = %s\"a\"",
        ),
    ];
    for (what, opens, want) in cases {
        let out = rule_of_opens(opens);
        assert_eq!(out, want, "{what}:\n{out}");
        assert!(!out.contains('*'), "{what}, read as a repetition:\n{out}");
        assert_rfc5234_shape(&out);
    }
    let whole = rule_of_opens(|a, _| vec![loop_entry("once"), back(a), AltSpec::new()]);
    assert_loop_abnf(&whole, "once = *A\n\nA = %s\"a\"");
}

/// A rule item's loop comes back through its helpers: the continue
/// replaces with `H$alt0`, which pushes the item and on close replaces
/// with `H$alt0$step1`, which replaces with `H`. With the step replacing
/// with nothing, the iteration ends after one item, and the rule is no
/// loop. It renders as debug's main emits it, with no repetition.
#[test]
fn abnf_does_not_read_a_loop_whose_helpers_never_come_back_as_one() {
    let mut parser = Tabnas::new();
    let x = parser.token_with_source("#X", "x");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "doc",
        AltSpec {
            p: Some("_gen1_star_item".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![x]],
            ..Default::default()
        },
        None,
    );
    ref_loop(&mut parser, "_gen1_star_item", &[x], "item", end);
    // The step, which replaced with the loop, now ends the iteration.
    parser.define_rule("_gen1_star_item$alt0$step1", |spec| {
        spec.clear();
        spec.add_open(AltSpec::new());
    });
    wrap_start(&mut parser, "doc");

    let out = abnf(&parser);
    assert_eq!(
        out,
        "doc = r-gen1-star-item\nitem = X\n\
         r-gen1-star-item = [ r-gen1-star-item / r-gen1-star-item-alt0 ]\n\
         r-gen1-star-item-alt0 = item r-gen1-star-item-alt0-step1\n\
         r-gen1-star-item-alt0-step1 = \"\"\n\nX = %s\"x\"",
        "helpers that never come back:\n{out}"
    );
    assert!(!out.contains('*'), "read as a repetition:\n{out}");
    assert_rfc5234_shape(&out);
}

/// A rule item's loop whose way back is guarded is no loop either: the
/// step replaces with the loop only under a condition, `n.never == 1`,
/// which nothing sets, so the iteration can end after one item. The
/// compiler puts conditions on a loop's own continues, never on its
/// helpers; a helper's way back is read only when it is taken whatever
/// the state. It renders as debug's main emits it, with no repetition.
#[test]
fn abnf_does_not_read_a_loop_whose_way_back_is_guarded_as_one() {
    let mut parser = Tabnas::new();
    let x = parser.token_with_source("#X", "x");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "doc",
        AltSpec {
            p: Some("_gen1_star_item".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![x]],
            ..Default::default()
        },
        None,
    );
    ref_loop(&mut parser, "_gen1_star_item", &[x], "item", end);
    parser.define_rule("_gen1_star_item$alt0$step1", |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            r: Some("_gen1_star_item".into()),
            c: vec![Condition {
                path: vec!["n".into(), "never".into()],
                op: CompareOp::Eq,
                value: Value::Number(1.0),
            }],
            ..Default::default()
        });
    });
    wrap_start(&mut parser, "doc");

    let out = abnf(&parser);
    assert_eq!(
        out,
        "doc = r-gen1-star-item\nitem = X\n\
         r-gen1-star-item = [ r-gen1-star-item / r-gen1-star-item-alt0 ]\n\
         r-gen1-star-item-alt0 = item r-gen1-star-item-alt0-step1\n\
         r-gen1-star-item-alt0-step1 = r-gen1-star-item\n\nX = %s\"x\"",
        "a guarded way back:\n{out}"
    );
    assert!(!out.contains('*'), "read as a repetition:\n{out}");
    assert_rfc5234_shape(&out);
}

/// A `_plus` helper that repeats by a cycle of its own, not through a
/// loop, keeps its production: here it re-enters itself on `A` and exits
/// on anything else, which takes any number of `A`. Folded, as a helper
/// that reaches no kept repetition was, its back edge rendered as
/// nothing and the rule came out as one `A`. It renders as debug's main
/// emits it.
#[test]
fn abnf_keeps_a_plus_helper_that_repeats_by_its_own_cycle() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    simple_rule(
        &mut parser,
        "rep",
        AltSpec {
            p: Some("_gen1_plus_term".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_plus_term", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("_gen1_plus_term".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
    });
    wrap_start(&mut parser, "rep");

    let out = abnf(&parser);
    assert_eq!(
        out, "rep = r-gen1-plus-term\nr-gen1-plus-term = [ A r-gen1-plus-term ]\n\nA = %s\"a\"",
        "a plus helper's own cycle:\n{out}"
    );
    assert_rfc5234_shape(&out);
}

/// A grammar whose start rule is a synthetic loop, named directly or
/// through the `__start__` wrapper. A synthetic loop is rendered where
/// it is referenced, and nothing references the start: it came out with
/// no production at all. The start is always a production.
#[test]
fn abnf_keeps_a_synthetic_loop_that_is_the_start_as_a_production() {
    for wrapped in [false, true] {
        let mut parser = Tabnas::new();
        let a = parser.token_with_source("#A", "a");
        let end = token(&parser, "#ZZ");
        terminal_loop(&mut parser, "_gen1_star_A", a, end);
        if wrapped {
            wrap_start(&mut parser, "_gen1_star_A");
        } else {
            parser.options.rule.start = "_gen1_star_A".into();
        }
        assert_eq!(
            abnf(&parser),
            "r-gen1-star-A = *A\n\nA = %s\"a\"",
            "wrapped: {wrapped}"
        );
    }
}

/// A synthetic rule with the loop's whole open scaffold whose close
/// replaces with a synthetic helper, and that helper's route a function
/// decides: it may come back to the rule by a way the spec does not
/// show. The rule is no loop, and renders as debug's main emits it.
#[test]
fn abnf_does_not_read_a_synthetic_loop_whose_close_helper_is_dynamic_as_one() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen2_group", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![b]],
            r_fn: Some(std::sync::Arc::new(|_, _| None)),
            ..Default::default()
        });
    });
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(loop_entry("_gen1_star_A"));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            r: Some("_gen2_group".into()),
            ..Default::default()
        });
    });
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = r-gen1-star-A\nr-gen1-star-A = [ r-gen1-star-A / A r-gen1-star-A ] B\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// A synthetic rule with the loop's whole open scaffold whose close
/// replaces with a synthetic helper that takes a `B` and whose own close
/// pushes a user rule: the helper runs its closes again each time the
/// pushed rule ends, pushing `item` over and over. The rule is no loop,
/// and renders as debug's main emits it.
#[test]
fn abnf_does_not_read_a_synthetic_loop_whose_close_helper_pushes_as_one() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![c]],
            ..Default::default()
        },
        None,
    );
    simple_rule(
        &mut parser,
        "_gen2_group",
        AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        },
        Some(AltSpec {
            p: Some("item".into()),
            ..Default::default()
        }),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(loop_entry("_gen1_star_A"));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            r: Some("_gen2_group".into()),
            ..Default::default()
        });
    });
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = r-gen1-star-A\nitem = C\nr-gen1-star-A = [ r-gen1-star-A / A r-gen1-star-A ] B item\n\nC = %s\"c\"\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// A loop whose iteration pushes `_gen2_group$alt0`, a synthetic rule
/// that repeats by a cycle of its own, `A _gen2_group$alt0 / B`, and
/// comes back to the loop. The cycle is no iteration of the loop's:
/// read as a helper of the loop, the rule was inlined with its way back
/// to itself rendered as nothing, `*( A / B )` for a loop that takes
/// `*( *A B )`. It stays a production of its own, referenced by name.
#[test]
fn abnf_keeps_a_cyclic_helper_a_loop_pushes_as_a_production() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_star__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen2_group$alt0", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            p: Some("_gen2_group$alt0".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_group",
        &[a, b],
        "_gen2_group$alt0",
        end,
    );
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = *r-gen2-group-alt0\nr-gen2-group-alt0 = A r-gen2-group-alt0 / B\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// A synthetic rule with the loop's whole open scaffold and a close
/// that pushes a user rule. A push in a close comes back to the close
/// phase when the pushed rule ends and runs the closes again, so the
/// rule pushes `item` over and over, where the loop inlined as a
/// repetition rendered `*A item`, one `item`. It is no loop, and renders
/// as debug's main emits it.
#[test]
fn abnf_does_not_read_a_synthetic_loop_whose_close_pushes_as_one() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        },
        None,
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(loop_entry("_gen1_star_A"));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            p: Some("item".into()),
            ..Default::default()
        });
    });
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = r-gen1-star-A\nitem = B\nr-gen1-star-A = [ r-gen1-star-A / A r-gen1-star-A ] item\n\nB = %s\"b\"\nA = %s\"a\""
    );
}

/// A `_plus` over `( B *A C )`, its `*A` in the old push-chain shape,
/// whose own trailing star is a loop over the same group, as the
/// compiler builds `1*X`. The old star is the item's, a production
/// referenced by name, and the plus folds round it as it would round any
/// rule the item names, written back as the `1*X` it was compiled from.
#[test]
fn abnf_folds_a_plus_round_an_old_shape_star_inside_its_item() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen6_plus__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
    simple_rule(
        &mut parser,
        "_gen2_group",
        AltSpec {
            s: vec![vec![b]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("_gen2_group$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "_gen2_group$step1",
        AltSpec {
            s: vec![vec![c]],
            ..Default::default()
        },
        None,
    );
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_group",
        &[b],
        "_gen2_group",
        end,
    );
    plus_chain(
        &mut parser,
        "_gen6_plus__gen2_group",
        "_gen2_group",
        "_gen3_star__gen2_group",
    );
    wrap_start(&mut parser, "top");

    assert_eq!(
        abnf(&parser),
        "top = 1*( B r-gen1-star-A C )\nr-gen1-star-A = [ A r-gen1-star-A ]\n\nB = %s\"b\"\nC = %s\"c\"\nA = %s\"a\""
    );
}

/// A `_plus` helper whose chain pushes `_gen5_group` and ends in a loop
/// over `_gen2_group`, a different rule that renders the same. The
/// compiler's `1*X` pushes the very item its loop repeats; this chain
/// merely reads `X *X`, and `X *X` and `1*X` compile to different
/// recognisers, so writing it back as `1*X` would claim a construction
/// it is not. It keeps its production, and its step, as they are.
#[test]
fn abnf_keeps_a_plus_over_a_different_item_as_a_production() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen6_plus__gen5_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
    for group in ["_gen2_group", "_gen5_group"] {
        let step = format!("{group}$step1");
        simple_rule(
            &mut parser,
            group,
            AltSpec {
                s: vec![vec![b]],
                p: Some("_gen1_star_A".into()),
                ..Default::default()
            },
            Some(AltSpec {
                r: Some(step.clone()),
                ..Default::default()
            }),
        );
        simple_rule(
            &mut parser,
            &step,
            AltSpec {
                s: vec![vec![c]],
                ..Default::default()
            },
            None,
        );
    }
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_group",
        &[b],
        "_gen2_group",
        end,
    );
    plus_chain(
        &mut parser,
        "_gen6_plus__gen5_group",
        "_gen5_group",
        "_gen3_star__gen2_group",
    );
    wrap_start(&mut parser, "top");

    assert_eq!(
        abnf(&parser),
        "top = r-gen6-plus--gen5-group\nr-gen1-star-A = [ A r-gen1-star-A ]\nr-gen6-plus--gen5-group = B r-gen1-star-A C r-gen6-plus--gen5-group-step1\nr-gen6-plus--gen5-group-step1 = *( B r-gen1-star-A C )\n\nA = %s\"a\"\nB = %s\"b\"\nC = %s\"c\""
    );
}

/// A `_plus` whose chain pushes `item` and ends in a loop whose
/// iteration pushes `item` and then takes a `B` on its way back. Read as
/// the plus over a loop it was written `1*( item B )`, which requires
/// the `B`, where the live chain takes `item` alone. A way back that
/// takes a token is no iteration helper the compiler writes, so the loop
/// is no loop, and it and the plus render as debug's main emits them.
#[test]
fn abnf_keeps_a_plus_whose_loop_takes_more_than_its_item_as_a_production() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen4_plus_item".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    simple_rule(
        &mut parser,
        "item",
        AltSpec {
            s: vec![vec![a]],
            ..Default::default()
        },
        None,
    );
    let rule = "_gen3_star_item".to_string();
    parser.define_rule(rule.clone(), move |spec| {
        spec.clear();
        spec.add_open(loop_entry(&rule));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            b: 1,
            r: Some(format!("{rule}$alt0")),
            ..Default::default()
        });
        loop_exits(spec, end);
    });
    parser.define_rule("_gen3_star_item$alt0", |spec| {
        spec.clear();
        spec.add_open(counted(
            AltSpec {
                p: Some("item".into()),
                ..Default::default()
            },
            0,
        ));
        spec.add_close(counted(
            AltSpec {
                r: Some("_gen3_star_item$alt0$step1".into()),
                ..Default::default()
            },
            1,
        ));
    });
    parser.define_rule("_gen3_star_item$alt0$step1", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![b]],
            r: Some("_gen3_star_item".into()),
            ..Default::default()
        });
    });
    plus_chain(&mut parser, "_gen4_plus_item", "item", "_gen3_star_item");
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = r-gen4-plus-item\nitem = A\nr-gen3-star-item = [ r-gen3-star-item / r-gen3-star-item-alt0 ]\nr-gen3-star-item-alt0 = item r-gen3-star-item-alt0-step1\nr-gen3-star-item-alt0-step1 = B r-gen3-star-item\nr-gen4-plus-item = item r-gen4-plus-item-step1\nr-gen4-plus-item-step1 = r-gen3-star-item\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// A loop whose continue replaces with a helper of a shape the compiler
/// never writes: one that pushes the loop itself, and one with an empty
/// way through beside a consuming one. The first rendered the pushed
/// loop as the iteration's back edge, nothing at all; the second dropped
/// the empty way, `*( A B )` for a rule that also takes `A` alone.
/// Neither is a loop, and each renders as debug's main emits it.
#[test]
fn abnf_does_not_read_a_loop_through_a_helper_of_another_shape_as_one() {
    type Helper = fn(Tin) -> Vec<AltSpec>;
    let helpers: [(&str, Helper, &str); 2] = [
        (
            "pushes the loop",
            |_| {
                vec![AltSpec {
                    p: Some("_gen1_star_x".into()),
                    ..Default::default()
                }]
            },
            "top = r-gen1-star-x\nr-gen1-star-x = [ r-gen1-star-x / A r-gen1-star-x-alt0 ]\nr-gen1-star-x-alt0 = r-gen1-star-x r-gen1-star-x-alt0-step1\nr-gen1-star-x-alt0-step1 = r-gen1-star-x\n\nA = %s\"a\"",
        ),
        (
            "an empty way beside a consuming one",
            |b| {
                vec![
                    AltSpec::new(),
                    AltSpec {
                        s: vec![vec![b]],
                        ..Default::default()
                    },
                ]
            },
            "top = r-gen1-star-x\nr-gen1-star-x = [ r-gen1-star-x / A r-gen1-star-x-alt0 ]\nr-gen1-star-x-alt0 = [ B ] r-gen1-star-x-alt0-step1\nr-gen1-star-x-alt0-step1 = r-gen1-star-x\n\nA = %s\"a\"\nB = %s\"b\"",
        ),
    ];
    for (what, opens, want) in helpers {
        let mut parser = Tabnas::new();
        let a = parser.token_with_source("#A", "a");
        let b = parser.token_with_source("#B", "b");
        let end = token(&parser, "#ZZ");
        simple_rule(
            &mut parser,
            "top",
            AltSpec {
                p: Some("_gen1_star_x".into()),
                ..Default::default()
            },
            Some(AltSpec::new()),
        );
        parser.define_rule("_gen1_star_x", move |spec| {
            spec.clear();
            spec.add_open(loop_entry("_gen1_star_x"));
            spec.add_open(AltSpec {
                s: vec![vec![a]],
                r: Some("_gen1_star_x$alt0".into()),
                ..Default::default()
            });
            loop_exits(spec, end);
        });
        parser.define_rule("_gen1_star_x$alt0", move |spec| {
            spec.clear();
            for alt in opens(b) {
                spec.add_open(alt);
            }
            spec.add_close(AltSpec {
                r: Some("_gen1_star_x$alt0$step1".into()),
                ..Default::default()
            });
        });
        simple_rule(
            &mut parser,
            "_gen1_star_x$alt0$step1",
            AltSpec {
                r: Some("_gen1_star_x".into()),
                ..Default::default()
            },
            None,
        );
        wrap_start(&mut parser, "top");
        assert_eq!(abnf(&parser), want, "{what}");
    }
}

/// A loop whose item is `_gen2_group$alt0`, a `$alt` rule that takes an
/// `A` or nothing and then a `B`: the iteration takes `A B` or `B`.
/// Inlined as a helper of the loop its empty way was dropped, `*( A B )`;
/// nothing but a loop's inlining would inline a `$alt` rule, and one
/// with an empty way stays a production of its own, as it always was.
#[test]
fn abnf_keeps_a_nullable_helper_inside_a_loop_as_a_production() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_star_x".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen2_group$alt0", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        });
    });
    ref_loop(
        &mut parser,
        "_gen3_star_x",
        &[a, b],
        "_gen2_group$alt0",
        end,
    );
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = *r-gen2-group-alt0\nr-gen2-group-alt0 = [ A ] B\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// A user loop over `*A` whose close phase takes a `B` and replaces the
/// rule with itself, or ends: `H = *A [ B H ]`. The iteration's own back
/// edges render as nothing, but the close's `r: H` is the rule again,
/// and dropping it rendered `H = *A [ B ]`, which stops after one `B`.
#[test]
fn abnf_keeps_a_loops_close_that_re_enters_it() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "once".into();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    parser.define_rule("once", move |spec| {
        spec.clear();
        spec.add_open(loop_entry("once"));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("once".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            s: vec![vec![b]],
            r: Some("once".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });
    assert_eq!(
        abnf(&parser),
        "once = *A [ B once ]\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// The same scaffold on a synthetic rule, which is inlined where it is
/// referenced and has no production of its own to name from its close:
/// it is no loop, and renders as debug's main emits it, a production.
#[test]
fn abnf_does_not_read_a_synthetic_loop_whose_close_re_enters_it_as_one() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        spec.add_open(loop_entry("_gen1_star_A"));
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            r: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec {
            s: vec![vec![b]],
            r: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_close(AltSpec::new());
    });
    wrap_start(&mut parser, "top");
    assert_eq!(
        abnf(&parser),
        "top = r-gen1-star-A\nr-gen1-star-A = [ r-gen1-star-A / A r-gen1-star-A ] [ B r-gen1-star-A ]\n\nA = %s\"a\"\nB = %s\"b\""
    );
}

/// `top = *( "b" *"a" "c" )` with the outer star in the loop shape and
/// the inner star in the OLD push-chain shape, a mix a hand-built grammar
/// can carry. A loop's helpers are the synthetic rules its iteration
/// reaches short of a kept production, and the old star is a kept
/// production: it stays a bareword reference inside the repetition, with
/// its production and its epsilon branch. Finding the helpers by
/// reachability alone added the old star to them, suppressed its
/// production and inlined it without its epsilon branch and back edge:
/// `*( B A C )`, exactly one `A` where the original takes any number.
#[test]
fn abnf_keeps_an_old_shape_star_inside_a_loop_group() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    let end = token(&parser, "#ZZ");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_star__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec::new()),
    );
    parser.define_rule("_gen1_star_A", move |spec| {
        spec.clear();
        // The push chain: each item pushes the rule again.
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        });
        spec.add_open(AltSpec::new());
        spec.add_close(AltSpec::new());
    });
    simple_rule(
        &mut parser,
        "_gen2_group",
        AltSpec {
            s: vec![vec![b]],
            p: Some("_gen1_star_A".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("_gen2_group$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "_gen2_group$step1",
        AltSpec {
            s: vec![vec![c]],
            ..Default::default()
        },
        None,
    );
    ref_loop(
        &mut parser,
        "_gen3_star__gen2_group",
        &[b],
        "_gen2_group",
        end,
    );
    wrap_start(&mut parser, "top");

    let out = abnf(&parser);
    assert_eq!(
        out,
        "top = *( B r-gen1-star-A C )\nr-gen1-star-A = [ A r-gen1-star-A ]\n\nB = %s\"b\"\nC = %s\"c\"\nA = %s\"a\"",
        "old-shape star inside a loop mismatch:\n{out}"
    );
    for leak in ["_gen", "$", "-alt", "step1"] {
        assert!(!out.contains(leak), "a synthetic {leak:?} leaked:\n{out}");
    }
    assert_rfc5234_shape(&out);
}

/// `( *"a" "b" / "c" )` as the compiler builds it under a repetition:
/// a group whose first alternative starts with a rule gets a `$alt` /
/// `$step` chain of its own — `_gen2_group$alt0` pushes the inner star
/// and closes into `_gen2_group$alt0$step1`, which takes the `"b"`;
/// `_gen2_group$alt1` takes the `"c"`; the group peeks each FIRST token
/// and pushes the chain that starts with it. The inner star is a terminal
/// loop whose FOLLOW is the `"b"`; the outer star, `_gen3_star__gen2_group`,
/// is a ref loop over the group with one continue per FIRST token and the
/// `"d"` after it as its FOLLOW. Installed in the compiler's order, from
/// the specs it emits for `top = *( *%s"a" %s"b" / %s"c" ) %s"d"`.
fn star_of_a_group_with_a_star_alternative(parser: &mut Tabnas, a: Tin, b: Tin, c: Tin, d: Tin) {
    terminal_loop(parser, "_gen1_star_term", a, b);
    simple_rule(
        parser,
        "_gen2_group$alt0",
        AltSpec {
            p: Some("_gen1_star_term".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("_gen2_group$alt0$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        parser,
        "_gen2_group$alt0$step1",
        AltSpec {
            s: vec![vec![b]],
            ..Default::default()
        },
        None,
    );
    simple_rule(
        parser,
        "_gen2_group$alt1",
        AltSpec {
            s: vec![vec![c]],
            ..Default::default()
        },
        None,
    );
    parser.define_rule("_gen2_group", move |spec| {
        spec.clear();
        for (first, chain) in [
            (a, "_gen2_group$alt0"),
            (b, "_gen2_group$alt0"),
            (c, "_gen2_group$alt1"),
        ] {
            spec.add_open(AltSpec {
                s: vec![vec![first]],
                b: 1,
                p: Some(chain.into()),
                ..Default::default()
            });
        }
        spec.add_close(AltSpec::new());
    });
    ref_loop(
        parser,
        "_gen3_star__gen2_group",
        &[a, b, c],
        "_gen2_group",
        d,
    );
}

/// `top = *( *"a" "b" / "c" ) "d"`: a loop over a group that has a
/// `$alt` / `$step` chain of its own, because one of its alternatives
/// starts with a rule. That chain is the loop's to inline, like the
/// group and the loop's own `H$alt0` and `H$alt0$step1`: the helpers of
/// a loop are everything its iteration reaches short of a kept
/// production. Finding them by name (`H$…`) missed the group's chain,
/// which `is_foldable` refuses for its `$alt`, and it surfaced as three
/// kept productions, `top = *( r-gen2-group-alt0 / r-gen2-group-alt1 ) D`
/// with `r-gen2-group-alt0 = *A r-gen2-group-alt0-step1`. The inner loop
/// renders as `*A` inside the alternative.
#[test]
fn abnf_renders_a_loop_over_a_group_with_a_star_alternative() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    let d = parser.token_with_source("#D", "d");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_star__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("top$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "top$step1",
        AltSpec {
            s: vec![vec![d]],
            ..Default::default()
        },
        None,
    );
    star_of_a_group_with_a_star_alternative(&mut parser, a, b, c, d);
    wrap_start(&mut parser, "top");

    assert_loop_abnf(
        &abnf(&parser),
        "top = *( *A B / C ) D\n\nA = %s\"a\"\nB = %s\"b\"\nC = %s\"c\"\nD = %s\"d\"",
    );
}

/// `top = 1*( *"a" "b" / "c" ) "d"`: the `_plus` helper over the same
/// group pushes it directly and, on close, steps into the loop. The
/// group's chain folds, so the helper folds too, and is written back as
/// the `1*( … )` it was compiled from. With the chain refused as kept
/// productions the helper was refused as well and came out as
/// `top = r-gen3-plus--gen2-group D` over a body of `X *X`, the spelling
/// that does not round-trip on a nullable item — and this item is
/// nullable: `*A B` can start with the `B`.
#[test]
fn abnf_renders_a_plus_over_a_group_with_a_star_alternative() {
    let mut parser = Tabnas::new();
    let a = parser.token_with_source("#A", "a");
    let b = parser.token_with_source("#B", "b");
    let c = parser.token_with_source("#C", "c");
    let d = parser.token_with_source("#D", "d");
    simple_rule(
        &mut parser,
        "top",
        AltSpec {
            p: Some("_gen3_plus__gen2_group".into()),
            ..Default::default()
        },
        Some(AltSpec {
            r: Some("top$step1".into()),
            ..Default::default()
        }),
    );
    simple_rule(
        &mut parser,
        "top$step1",
        AltSpec {
            s: vec![vec![d]],
            ..Default::default()
        },
        None,
    );
    star_of_a_group_with_a_star_alternative(&mut parser, a, b, c, d);
    plus_chain(
        &mut parser,
        "_gen3_plus__gen2_group",
        "_gen2_group",
        "_gen3_star__gen2_group",
    );
    wrap_start(&mut parser, "top");

    assert_loop_abnf(
        &abnf(&parser),
        "top = 1*( *A B / C ) D\n\nA = %s\"a\"\nB = %s\"b\"\nC = %s\"c\"\nD = %s\"d\"",
    );
}

/// `odd = A [ odd ]`, hand-built with the close continuation carrying the
/// loop entry's whole shape: `{ c: [n.rep == 0], n: {rep: 1}, s: A,
/// b: 1, r: odd }`, then `{ }`. A loop is decided by its OPEN
/// alternatives, and `odd` has no entry among them, so it is no loop, and
/// a rule that is not a loop has no entry to skip: every alternative is
/// content. Skipping the entry's shape wherever it appeared emitted
/// `odd = A`, exactly one where the rule takes one or more. origin/main
/// emits the pinned text.
#[test]
fn abnf_keeps_an_entry_shaped_close_continuation_of_a_rule_that_is_no_loop() {
    let mut parser = Tabnas::new();
    parser.options.rule.start = "odd".into();
    let a = parser.token_with_source("#A", "a");
    parser.define_rule("odd", move |spec| {
        spec.clear();
        spec.add_open(AltSpec {
            s: vec![vec![a]],
            ..Default::default()
        });
        spec.add_close(AltSpec {
            s: vec![vec![a]],
            b: 1,
            ..loop_entry("odd")
        });
        spec.add_close(AltSpec::new());
    });

    let out = abnf(&parser);
    assert_eq!(
        out, "odd = A [ odd ]\n\nA = %s\"a\"",
        "entry-shaped continuation of a non-loop mismatch:\n{out}"
    );
    assert!(!out.contains('*'), "read as a repetition:\n{out}");
    assert_rfc5234_shape(&out);
}