neotoma 0.1.1

A flexible, cached parser combinator framework for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
//! # Grammar Syntax
//! - `"terminal"` - matches literal string (with `\"` for escaped quotes)
//! - `digits` - matches one or more decimal digits (0-9)
//! - `alpha` - matches one or more alphabetic characters (ASCII)
//! - `alphanumeric` - matches one or more alphanumeric characters (ASCII)
//! - `whitespace` - matches one or more whitespace characters (ASCII)
//! - `udigits` - matches one or more decimal digits (unicode)
//! - `ualpha` - matches one or more alphabetic characters (unicode)
//! - `ualphanumeric` - matches one or more alphanumeric characters (unicode)
//! - `uwhitespace` - matches one or more whitespace characters (unicode)
//! - `hexdigits` - matches one or more hexadecimal digits (0-9, a-f, A-F)
//! - `eof` - matches end of file (ensures complete input consumption)
//! - `[abc]` - matches any character in the set (custom character class)
//! - `[^abc]` - matches any character NOT in the set (negated character class)
//! - `(A B C)` - matches A followed by B followed by C (sequence)
//! - `(| A B C)` - matches either A or B or C (alternatives)
//! - `(* A)` - matches zero or more instances of A
//! - `(+ A)` - matches one or more instances of A
//! - `(? A)` - matches zero or one instances of A
//! - `(* A / B)` - matches zero or more A's separated by B (trailing B allowed but not required)
//! - `(+ A / B)` - matches one or more A's separated by B (trailing B allowed but not required)
//! - `name = rule` - Names a parsing rule, for use in other rules and/or recursive rule definitions
//! - `name` - References a named rule. The `digits`, `alpha` and so on are not valid rule names
//! - `@start name` - Identifies the starting rule for the grammar. If not provided, defaults to the last rule defined

use crate::{
    either::Either, eof::EndOfFile, literal::Literal, parser::Parser, repeat::Repeat,
    result::Error, sequence::Sequence, until::Utf8Until, utf8class::Utf8Class,
    utf8util::read_utf8_char,
};

// Const literal parsers for grammar punctuation - avoiding runtime allocations
const OPEN_PAREN: Literal = Literal::from_str_const("(");
const CLOSE_PAREN: Literal = Literal::from_str_const(")");
const PIPE: Literal = Literal::from_str_const("|");
const ASTERISK: Literal = Literal::from_str_const("*");
const PLUS: Literal = Literal::from_str_const("+");
const QUESTION: Literal = Literal::from_str_const("?");
const LESS_THAN: Literal = Literal::from_str_const("<");
const SLASH: Literal = Literal::from_str_const("/");
const OPEN_BRACKET: Literal = Literal::from_str_const("[");
//const CLOSE_BRACKET: Literal = Literal::from_str_const("]");
const CARET: Literal = Literal::from_str_const("^");
const QUOTE: Literal = Literal::from_str_const("\"");
const AT_SYMBOL: Literal = Literal::from_str_const("@");
const EQUALS: Literal = Literal::from_str_const("=");

// Const literal parsers for new grammar keywords
const START_KEYWORD: Literal = Literal::from_str_const("start");

// Const literal parsers for grammar keywords - avoiding runtime allocations
const DIGITS_KEYWORD: Literal = Literal::from_str_const("digits");
const ALPHA_KEYWORD: Literal = Literal::from_str_const("alpha");
const ALPHANUMERIC_KEYWORD: Literal = Literal::from_str_const("alphanumeric");
const WHITESPACE_KEYWORD: Literal = Literal::from_str_const("whitespace");
const HEXDIGITS_KEYWORD: Literal = Literal::from_str_const("hexdigits");
const UDIGITS_KEYWORD: Literal = Literal::from_str_const("udigits");
const UALPHA_KEYWORD: Literal = Literal::from_str_const("ualpha");
const UALPHANUMERIC_KEYWORD: Literal = Literal::from_str_const("ualphanumeric");
const UWHITESPACE_KEYWORD: Literal = Literal::from_str_const("uwhitespace");
const EOF_KEYWORD: Literal = Literal::from_str_const("eof");

/// Context type used internally by grammar parsers.
///
/// This context allows grammar parsers to maintain state during parsing,
/// such as tracking recursion depth, variable bindings, or other grammar-specific information.
#[derive(Debug, Clone, Default)]
struct GrammarContext {
    /// Map of rule names to their grammar definitions
    rules: std::collections::HashMap<String, GrammarNode>,
    /// Starting rule name for parsing
    start_rule: Option<String>,
}

/// Parser for grammar expressions
///
/// This type is responsible for parsing grammar syntax and producing
/// a Grammar which implements a parser for the described language.
#[derive(Clone)]
pub struct GrammarParser;

impl Default for GrammarParser {
    fn default() -> Self {
        Self::new()
    }
}

impl GrammarParser {
    /// Create a new GrammarParser instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use neotoma::grammar::GrammarParser;
    /// let parser = GrammarParser::new();
    /// ```
    pub fn new() -> Self {
        Self
    }
}

// Implementation for external calls (no context)
impl Parser<()> for GrammarParser {
    type Output = Grammar;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        _context: &mut (),
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Create a new GrammarContext for accumulating rules and directives
        let mut grammar_context = GrammarContext::default();
        let mut last_node = None;

        let ws = crate::utf8class::Utf8Class::whitespace();

        // Parse multiple grammar constructs until end of input
        loop {
            // Skip any whitespace between constructs
            let _ = ws.parse(source, cache, &mut grammar_context);

            // Try to parse another grammar construct
            match self.read(source, cache, &mut grammar_context) {
                Ok(node) => {
                    last_node = Some(node);
                    // Continue parsing more constructs
                }
                Err(Error::NoMatch) => {
                    // No more constructs to parse, we're done
                    break;
                }
                Err(other_error) => {
                    // Actual parsing error, propagate it
                    return Err(other_error);
                }
            }
        }

        // After parsing all constructs, validate and build the final grammar
        if let Some(start) = grammar_context.start_rule.as_deref() {
            if let Some(rule) = grammar_context.rules.get(start).cloned() {
                Ok(Grammar::new(rule, grammar_context))
            } else {
                // The grammar syntax is invalid, due to referencing a
                // nonexistent start rule
                Err(Error::NoMatch)
            }
        } else if let Some(last_node) = last_node {
            // Use the last parsed node if no start rule specified
            Ok(Grammar::new(last_node, grammar_context))
        } else {
            // No constructs parsed at all
            Err(Error::NoMatch)
        }
    }
}

// Implementation for internal recursive calls (with GrammarContext)
impl Parser<GrammarContext> for GrammarParser {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Try each possible expression type in order

        // First, try meta-constructs that update context
        // Try @start directive
        if let Ok(start_rule) = StartDirective.parse(source, cache, context) {
            context.start_rule = Some(start_rule);
            return Ok(GrammarNode::Empty);
        }

        // Try rule definition
        if let Ok((name, node)) = RuleDefinition.parse(source, cache, context) {
            context.rules.insert(name, node);
            return Ok(GrammarNode::Empty);
        }

        // Then try terminals (quoted strings)
        if let Ok(literal) = Terminal.parse(source, cache, context) {
            return Ok(GrammarNode::Terminal(literal));
        }

        // Try built-in keyword types
        if let Ok(digits) = Digits.parse(source, cache, context) {
            return Ok(GrammarNode::Digits(digits));
        }

        if let Ok(alphanumeric) = Alphanumeric.parse(source, cache, context) {
            return Ok(GrammarNode::Alphanumeric(alphanumeric));
        }

        if let Ok(alpha) = Alpha.parse(source, cache, context) {
            return Ok(GrammarNode::Alpha(alpha));
        }

        if let Ok(whitespace) = Whitespace.parse(source, cache, context) {
            return Ok(GrammarNode::Whitespace(whitespace));
        }

        if let Ok(udigits) = UDigits.parse(source, cache, context) {
            return Ok(GrammarNode::UDigits(udigits));
        }

        if let Ok(ualphanumeric) = UAlphanumeric.parse(source, cache, context) {
            return Ok(GrammarNode::UAlphanumeric(ualphanumeric));
        }

        if let Ok(ualpha) = UAlpha.parse(source, cache, context) {
            return Ok(GrammarNode::UAlpha(ualpha));
        }

        if let Ok(uwhitespace) = UWhitespace.parse(source, cache, context) {
            return Ok(GrammarNode::UWhitespace(uwhitespace));
        }

        if let Ok(hexdigits) = HexDigits.parse(source, cache, context) {
            return Ok(GrammarNode::HexDigits(hexdigits));
        }

        if let Ok(eof) = EndOfFileParser.parse(source, cache, context) {
            return Ok(GrammarNode::EndOfFile(eof));
        }

        // Try character classes [abc] and [^abc]
        if let Ok(inclass) = InClass.parse(source, cache, context) {
            return Ok(GrammarNode::InClass(inclass));
        }

        if let Ok(notinclass) = NotInClass.parse(source, cache, context) {
            return Ok(GrammarNode::NotInClass(notinclass));
        }

        // Try alternatives syntax: (| A B C)
        if let Ok(expr) = Alternatives.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try separated repetitions first (longer patterns)
        // Try zero-or-more separated syntax: (* A / B)
        if let Ok(expr) = ZeroOrMoreSeparated.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try one-or-more separated syntax: (+ A / B)
        if let Ok(expr) = OneOrMoreSeparated.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try non-separated repetitions (shorter patterns)
        // Try zero-or-more syntax: (* A)
        if let Ok(expr) = ZeroOrMore.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try one-or-more syntax: (+ A)
        if let Ok(expr) = OneOrMore.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try zero-or-one syntax: (? A)
        if let Ok(expr) = ZeroOrOne.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try read-until-parse syntax: (< A B)
        if let Ok(expr) = ReadUntilAndParse.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try read-until syntax: (< A)
        if let Ok(expr) = ReadUntil.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try rule reference: identifier
        if let Ok(expr) = RuleReferenceParser.parse(source, cache, context) {
            return Ok(expr);
        }

        // Try sequential syntax last: (A B C)
        // This must be last because it's the most general case
        if let Ok(expr) = Sequential.parse(source, cache, context) {
            return Ok(expr);
        }

        Err(Error::NoMatch)
    }
}

/// Result type for Grammar parsing
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GrammarResult {
    /// Literal string result (from terminals)
    Literal(Vec<u8>),
    /// UTF-8 string result (from unicode character classes)
    Unicode(String),
    /// Byte sequence result (from ASCII character classes)
    Bytes(Vec<u8>),
    /// Sequence result containing multiple sub-results
    Sequence(Vec<GrammarResult>),
    /// Alternative result - exactly one of the options matched
    Alternative(Box<GrammarResult>),
    /// Repetition result - zero or more matches
    Repetition(Vec<GrammarResult>),
    /// Optional result - zero or one match
    Optional(Option<Box<GrammarResult>>),
    /// Empty result (for () or empty matches)
    Empty,
}

impl GrammarResult {
    /// Convert this result to bytes for situations where byte representation is needed
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            GrammarResult::Literal(bytes) => bytes.clone(),
            GrammarResult::Unicode(string) => string.as_bytes().to_vec(),
            GrammarResult::Bytes(bytes) => bytes.clone(),
            GrammarResult::Sequence(results) => {
                let mut combined = Vec::new();
                for result in results {
                    combined.extend(result.to_bytes());
                }
                combined
            }
            GrammarResult::Alternative(result) => result.to_bytes(),
            GrammarResult::Repetition(results) => {
                let mut combined = Vec::new();
                for result in results {
                    combined.extend(result.to_bytes());
                }
                combined
            }
            GrammarResult::Optional(Some(result)) => result.to_bytes(),
            GrammarResult::Optional(None) | GrammarResult::Empty => Vec::new(),
        }
    }

    /// Check if this result represents an empty match
    pub fn is_empty(&self) -> bool {
        matches!(self, GrammarResult::Empty | GrammarResult::Optional(None))
    }
}

/// Internal AST node for grammar parsing (private)
#[derive(Debug, Clone, PartialEq, Eq)]
enum GrammarNode {
    RuleReference(String),
    Empty,
    Terminal(Literal),
    Digits(Utf8Class),
    Alpha(Utf8Class),
    Alphanumeric(Utf8Class),
    Whitespace(Utf8Class),
    UDigits(Utf8Class),
    UAlpha(Utf8Class),
    UAlphanumeric(Utf8Class),
    UWhitespace(Utf8Class),
    HexDigits(Utf8Class),
    EndOfFile(EndOfFile),
    InClass(Utf8Class),
    NotInClass(Utf8Class),
    Sequential(Sequence<Box<GrammarNode>, Box<GrammarNode>>),
    SequentialEnd(Sequence<Box<GrammarNode>, ()>),
    Alternatives(Either<Box<GrammarNode>, Box<GrammarNode>>),
    ZeroOrMore(Repeat<Box<GrammarNode>, ()>),
    OneOrMore(Repeat<Box<GrammarNode>, ()>),
    ZeroOrOne(Repeat<Box<GrammarNode>>),
    ZeroOrMoreSeparated(Repeat<Box<GrammarNode>, Box<GrammarNode>>),
    OneOrMoreSeparated(Repeat<Box<GrammarNode>, Box<GrammarNode>>),
    ReadUntil(Utf8Until<Box<GrammarNode>>),
    ReadUntilParse(Utf8Until<Box<GrammarNode>>, Box<GrammarNode>),
}

/// Grammar parser with context for named rules and recursion
#[derive(Debug, Clone)]
pub struct Grammar {
    node: GrammarNode,
    context: GrammarContext,
}

impl Grammar {
    /// Create a new Grammar with the given node and context (private)
    fn new(node: GrammarNode, context: GrammarContext) -> Self {
        Self { node, context }
    }

    /// Check if a rule exists in this grammar's context
    pub fn rule_exists(&self, name: &str) -> bool {
        self.context.rules.contains_key(name)
    }

    /// Get the start rule name, if any
    pub fn start_rule(&self) -> Option<&str> {
        self.context.start_rule.as_deref()
    }
}

// Implementation for Grammar struct for external API (uses embedded context)
impl Parser<()> for Grammar {
    type Output = GrammarResult;

    fn id(&self) -> u64 {
        use std::any::TypeId;
        use std::hash::{DefaultHasher, Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        TypeId::of::<Self>().hash(&mut hasher);

        // Hash the node
        self.node.id().hash(&mut hasher);

        // Hash the context fields
        self.context.rules.len().hash(&mut hasher);
        if let Some(ref start_rule) = self.context.start_rule {
            start_rule.hash(&mut hasher);
        }

        hasher.finish()
    }

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        _context: &mut (),
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Use our embedded context for parsing
        let mut grammar_context = self.context.clone();

        // Delegate to the internal node with our context
        self.node.read(source, cache, &mut grammar_context)
    }
}

// Implementation for Grammar struct with GrammarContext - delegates to internal node
impl Parser<GrammarContext> for Grammar {
    type Output = GrammarResult;

    fn id(&self) -> u64 {
        use std::any::TypeId;
        use std::hash::{DefaultHasher, Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        TypeId::of::<Self>().hash(&mut hasher);

        // Hash the node
        self.node.id().hash(&mut hasher);

        // Hash the context fields
        self.context.rules.len().hash(&mut hasher);
        if let Some(ref start_rule) = self.context.start_rule {
            start_rule.hash(&mut hasher);
        }

        hasher.finish()
    }

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Delegate to the internal node
        self.node.read(source, cache, context)
    }
}

// Implementation for GrammarNode enum - handles the actual parsing logic
impl Parser<GrammarContext> for GrammarNode {
    type Output = GrammarResult;

    fn id(&self) -> u64 {
        use std::any::TypeId;
        use std::hash::{DefaultHasher, Hash, Hasher};
        use std::mem;

        let mut hasher = DefaultHasher::new();
        TypeId::of::<Self>().hash(&mut hasher);

        // Hash the enum discriminant
        mem::discriminant(self).hash(&mut hasher);

        // Hash the contents based on variant
        match self {
            GrammarNode::RuleReference(name) => {
                name.hash(&mut hasher);
            }
            GrammarNode::Empty => {
                // Nothing to hash for empty
            }
            GrammarNode::Terminal(literal) => {
                <Literal as Parser<GrammarContext>>::id(literal).hash(&mut hasher);
            }
            GrammarNode::Digits(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::Alpha(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::Alphanumeric(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::Whitespace(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::UDigits(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::UAlpha(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::UAlphanumeric(utf8_class) => {
                <Utf8Class<fn(char) -> bool> as Parser<GrammarContext>>::id(utf8_class)
                    .hash(&mut hasher);
            }
            GrammarNode::UWhitespace(utf8_class) => {
                <Utf8Class<fn(char) -> bool> as Parser<GrammarContext>>::id(utf8_class)
                    .hash(&mut hasher);
            }
            GrammarNode::HexDigits(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::EndOfFile(eof) => {
                <EndOfFile as Parser<GrammarContext>>::id(eof).hash(&mut hasher);
            }
            GrammarNode::InClass(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::NotInClass(utf8_class) => {
                <Utf8Class as Parser<GrammarContext>>::id(utf8_class).hash(&mut hasher);
            }
            GrammarNode::Sequential(sequence) => {
                <Sequence<Box<GrammarNode>, Box<GrammarNode>> as Parser<GrammarContext>>::id(
                    sequence,
                )
                .hash(&mut hasher);
            }
            GrammarNode::SequentialEnd(sequence) => {
                <Sequence<Box<GrammarNode>, ()> as Parser<GrammarContext>>::id(sequence)
                    .hash(&mut hasher);
            }
            GrammarNode::Alternatives(either) => {
                <Either<Box<GrammarNode>, Box<GrammarNode>> as Parser<GrammarContext>>::id(either)
                    .hash(&mut hasher);
            }
            GrammarNode::ZeroOrMore(repeat) => {
                <Repeat<Box<GrammarNode>, ()> as Parser<GrammarContext>>::id(repeat)
                    .hash(&mut hasher);
            }
            GrammarNode::OneOrMore(repeat) => {
                <Repeat<Box<GrammarNode>, ()> as Parser<GrammarContext>>::id(repeat)
                    .hash(&mut hasher);
            }
            GrammarNode::ZeroOrOne(repeat) => {
                <Repeat<Box<GrammarNode>> as Parser<GrammarContext>>::id(repeat).hash(&mut hasher);
            }
            GrammarNode::ZeroOrMoreSeparated(repeat) => {
                <Repeat<Box<GrammarNode>, Box<GrammarNode>> as Parser<GrammarContext>>::id(repeat)
                    .hash(&mut hasher);
            }
            GrammarNode::OneOrMoreSeparated(repeat) => {
                <Repeat<Box<GrammarNode>, Box<GrammarNode>> as Parser<GrammarContext>>::id(repeat)
                    .hash(&mut hasher);
            }
            GrammarNode::ReadUntil(until) => {
                <Utf8Until<Box<GrammarNode>> as Parser<GrammarContext>>::id(until)
                    .hash(&mut hasher);
            }
            GrammarNode::ReadUntilParse(until, content_parser) => {
                <Utf8Until<Box<GrammarNode>> as Parser<GrammarContext>>::id(until)
                    .hash(&mut hasher);
                <Box<GrammarNode> as Parser<GrammarContext>>::id(content_parser).hash(&mut hasher);
            }
        }

        hasher.finish()
    }

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        match self {
            GrammarNode::RuleReference(name) => {
                // Look up the rule in the context
                if let Some(rule_node) = context.rules.get(name).cloned() {
                    // Recursive call to parse the referenced rule
                    rule_node.parse(source, cache, context)
                } else {
                    Err(Error::NoMatch)
                }
            }
            GrammarNode::Empty => {
                // Empty variant returns empty result
                Ok(GrammarResult::Empty)
            }
            GrammarNode::Terminal(literal) => {
                let result = literal.parse(source, cache, context)?;
                Ok(GrammarResult::Literal(result.into()))
            }
            GrammarNode::Digits(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::Alpha(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::Alphanumeric(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::Whitespace(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::UDigits(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::UAlpha(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::UAlphanumeric(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::UWhitespace(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::HexDigits(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::EndOfFile(eof) => {
                eof.parse(source, cache, context)?;
                Ok(GrammarResult::Empty)
            }
            GrammarNode::InClass(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::NotInClass(utf8_class) => {
                let result = utf8_class.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::Sequential(sequence) => {
                let result = sequence.parse(source, cache, context)?;
                // Create a sequence result containing both sub-results
                Ok(GrammarResult::Sequence(vec![result.0, result.1]))
            }
            GrammarNode::SequentialEnd(sequence) => {
                let result = sequence.parse(source, cache, context)?;
                // Only return the result from the expression side (ignore the () side)
                Ok(result.0)
            }
            GrammarNode::Alternatives(either) => {
                let result = either.parse(source, cache, context)?;
                // Return whichever alternative matched
                match result {
                    (Some(left), None) => Ok(GrammarResult::Alternative(Box::new(left))),
                    (None, Some(right)) => Ok(GrammarResult::Alternative(Box::new(right))),
                    _ => unreachable!("Either should return exactly one result"),
                }
            }
            GrammarNode::ZeroOrMore(repeat) => {
                let results = repeat.parse(source, cache, context)?;
                // Convert all results to GrammarResult
                Ok(GrammarResult::Repetition(results))
            }
            GrammarNode::OneOrMore(repeat) => {
                let results = repeat.parse(source, cache, context)?;
                // Convert all results to GrammarResult
                Ok(GrammarResult::Repetition(results))
            }
            GrammarNode::ZeroOrOne(option) => {
                let result = option.parse(source, cache, context)?;
                if result.is_empty() {
                    Ok(GrammarResult::Optional(None))
                } else {
                    Ok(GrammarResult::Optional(
                        result.into_iter().next().map(Box::new),
                    ))
                }
            }
            GrammarNode::ZeroOrMoreSeparated(repeat) => {
                let results = repeat.parse(source, cache, context)?;
                // Convert all results to GrammarResult
                Ok(GrammarResult::Repetition(results))
            }
            GrammarNode::OneOrMoreSeparated(repeat) => {
                let results = repeat.parse(source, cache, context)?;
                // Convert all results to GrammarResult
                Ok(GrammarResult::Repetition(results))
            }
            GrammarNode::ReadUntil(until) => {
                let result = until.parse(source, cache, context)?;
                Ok(GrammarResult::Unicode(result))
            }
            GrammarNode::ReadUntilParse(until, content_parser) => {
                let captured = until.parse(source, cache, context)?;
                // Parse the captured content with the content parser
                let mut captured_input = std::io::Cursor::new(captured.as_bytes());
                let mut captured_source = crate::parser::Source::new(&mut captured_input);
                let content_result = content_parser.parse(&mut captured_source, cache, context)?;
                Ok(content_result)
            }
        }
    }
}

struct Terminal;

impl Parser<GrammarContext> for Terminal {
    type Output = Literal;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        QUOTE.parse(source, cache, context)?;

        let mut bytes = Vec::new();
        let mut escaped = false;
        let mut reading = true;

        while reading {
            let byte = source.peek1()?;

            if escaped {
                bytes.push(byte);
                escaped = false;
                source.advance(1);
            } else if byte == b'\\' {
                escaped = true;
                source.advance(1);
            } else if byte == b'"' {
                reading = false;
            } else {
                bytes.push(byte);
                source.advance(1);
            }
        }

        QUOTE.parse(source, cache, context)?;

        Ok(Literal::from_bytes(&bytes))
    }
}

struct Digits;

impl Parser<GrammarContext> for Digits {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        DIGITS_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::digits())
    }
}

struct Alpha;

impl Parser<GrammarContext> for Alpha {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        ALPHA_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::alpha())
    }
}

struct Alphanumeric;

impl Parser<GrammarContext> for Alphanumeric {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        ALPHANUMERIC_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::alphanumeric())
    }
}

struct Whitespace;

impl Parser<GrammarContext> for Whitespace {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        WHITESPACE_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::whitespace())
    }
}

struct HexDigits;

impl Parser<GrammarContext> for HexDigits {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        HEXDIGITS_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::hex_digits())
    }
}

struct UDigits;

impl Parser<GrammarContext> for UDigits {
    type Output = Utf8Class<fn(char) -> bool>;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        UDIGITS_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::unicode_digits())
    }
}

struct UAlpha;

impl Parser<GrammarContext> for UAlpha {
    type Output = Utf8Class<fn(char) -> bool>;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        UALPHA_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::unicode_alpha())
    }
}

struct UAlphanumeric;

impl Parser<GrammarContext> for UAlphanumeric {
    type Output = Utf8Class<fn(char) -> bool>;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        UALPHANUMERIC_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::from_predicate_min(|c| c.is_alphanumeric(), 1))
    }
}

struct UWhitespace;

impl Parser<GrammarContext> for UWhitespace {
    type Output = Utf8Class<fn(char) -> bool>;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        UWHITESPACE_KEYWORD.parse(source, cache, context)?;
        Ok(Utf8Class::unicode_whitespace())
    }
}

struct EndOfFileParser;

impl Parser<GrammarContext> for EndOfFileParser {
    type Output = EndOfFile;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        EOF_KEYWORD.parse(source, cache, context)?;
        Ok(EndOfFile::new())
    }
}

struct Identifier;

impl Parser<GrammarContext> for Identifier {
    type Output = String;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse identifier: letter followed by letters/digits/underscores
        let first_char = Utf8Class::alpha().parse(source, cache, context)?;
        let rest_chars = Utf8Class::from_predicate_min(|c| c.is_alphanumeric() || c == '_', 0)
            .parse(source, cache, context)
            .unwrap_or_default();
        Ok(format!("{first_char}{rest_chars}"))
    }
}

struct InClass;

impl Parser<GrammarContext> for InClass {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Match opening bracket '['
        OPEN_BRACKET.parse(source, cache, context)?;

        if source.peek1()? == b'^' {
            return Err(Error::NoMatch);
        }

        let mut chars = String::new();
        let mut escaped = false;

        loop {
            // Read a UTF-8 character
            let ch = read_utf8_char(source)?;

            if escaped {
                // Add escaped character
                chars.push(ch);
                escaped = false;
            } else if ch == '\\' {
                // Next character is escaped
                escaped = true;
            } else if ch == ']' {
                // End of character class
                break;
            } else {
                // Regular character - add to class
                chars.push(ch);
            }
        }

        // We don't actually call this, because read_utf8_char has
        // already consumed it from the source

        //CLOSE_BRACKET.parse(source, cache, context)?;

        // Create UTF-8 character class from the collected characters
        // Use with_min(1) to require at least one character match
        Ok(Utf8Class::with_min(&chars, 1))
    }
}

struct NotInClass;

impl Parser<GrammarContext> for NotInClass {
    type Output = Utf8Class;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Match opening bracket '['
        OPEN_BRACKET.parse(source, cache, context)?;

        // Must have '^' as the next character for negated class
        CARET.parse(source, cache, context)?;

        let mut chars = String::new();
        let mut escaped = false;

        loop {
            // Read a UTF-8 character
            let ch = read_utf8_char(source)?;

            if escaped {
                // Add escaped character
                chars.push(ch);
                escaped = false;
            } else if ch == '\\' {
                // Next character is escaped
                escaped = true;
            } else if ch == ']' {
                // End of character class
                break;
            } else {
                // Regular character - add to class
                chars.push(ch);
            }
        }

        // We don't actually call this, because read_utf8_char has
        // already consumed it from the source

        //CLOSE_BRACKET.parse(source, cache, context)?;

        // Create negated UTF-8 character class from the collected characters
        // Use not_in_with_min(1) to require at least one character match and negate the set
        Ok(Utf8Class::not_in_with_min(&chars, 1))
    }
}

struct Sequential;

impl Parser<GrammarContext> for Sequential {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Skip optional whitespace after (
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse sequence of expressions
        let mut expressions: Vec<GrammarNode> = Vec::new();

        // Parse expressions until closing paren
        while source.peek1().unwrap_or(0) != b')' {
            // Skip whitespace before expression
            let _ = Utf8Class::whitespace().parse(source, cache, context);

            // Check if we've reached the closing paren after skipping whitespace
            if source.peek1().unwrap_or(0) == b')' {
                break;
            }

            // Try to parse a sub-expression
            match <GrammarParser as Parser<GrammarContext>>::read(
                &GrammarParser,
                source,
                cache,
                context,
            ) {
                Ok(expr) => {
                    expressions.push(expr);
                }
                Err(_) => {
                    // If we can't parse a sub-expression, return NoMatch
                    return Err(Error::NoMatch);
                }
            }

            // Skip whitespace after expression
            let _ = Utf8Class::whitespace().parse(source, cache, context);
        }

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the sequence from parsed expressions
        if expressions.is_empty() {
            return Err(Error::NoMatch);
        }

        if expressions.len() == 1 {
            return Ok(expressions.into_iter().next().unwrap());
        }

        // Build right-associative sequence ending with ()
        let mut expressions = expressions;
        expressions.reverse(); // Process from right to left: [C, B, A]

        // Start with the rightmost element and wrap it as Sequence<C, ()>
        let last_expr = expressions.remove(0); // Remove C
        let mut result = GrammarNode::SequentialEnd(Sequence::new(Box::new(last_expr), ()));

        // Build the chain: Sequence<B, Sequence<C, ()>> -> Sequence<A, Sequence<B, Sequence<C, ()>>>
        for expr in expressions {
            let sequence = Sequence::new(Box::new(expr), Box::new(result));
            result = GrammarNode::Sequential(sequence);
        }

        Ok(result)
    }
}

struct Alternatives;

impl Parser<GrammarContext> for Alternatives {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse pipe symbol
        PIPE.parse(source, cache, context)?;

        // Skip optional whitespace after |
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse alternative expressions
        let mut alternatives: Vec<GrammarNode> = Vec::new();

        // Parse expressions until closing paren
        while source.peek1().unwrap_or(0) != b')' {
            // Skip whitespace before expression
            let _ = Utf8Class::whitespace().parse(source, cache, context);

            // Check if we've reached the closing paren after skipping whitespace
            if source.peek1().unwrap_or(0) == b')' {
                break;
            }

            // Try to parse a sub-expression
            match <GrammarParser as Parser<GrammarContext>>::read(
                &GrammarParser,
                source,
                cache,
                context,
            ) {
                Ok(expr) => {
                    alternatives.push(expr);
                }
                Err(_) => {
                    // If we can't parse a sub-expression, return NoMatch
                    return Err(Error::NoMatch);
                }
            }

            // Skip whitespace after expression
            let _ = Utf8Class::whitespace().parse(source, cache, context);
        }

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the alternatives from parsed expressions
        if alternatives.is_empty() {
            return Err(Error::NoMatch);
        }

        if alternatives.len() == 1 {
            return Ok(alternatives.into_iter().next().unwrap());
        }

        // Build right-associative alternatives without () termination
        let mut alternatives = alternatives;
        alternatives.reverse(); // Process from right to left: [C, B, A]

        // Start with the rightmost element
        let mut result = alternatives.remove(0); // Remove C

        // Build the chain: Either<B, C> -> Either<A, Either<B, C>>
        for expr in alternatives {
            let either = Either::new(Box::new(expr), Box::new(result));
            result = GrammarNode::Alternatives(either);
        }

        Ok(result)
    }
}

struct ZeroOrMore;

impl Parser<GrammarContext> for ZeroOrMore {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse asterisk symbol
        ASTERISK.parse(source, cache, context)?;

        // Skip optional whitespace after *
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the inner expression
        let inner_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the zero-or-more expression
        let repeat = Repeat::new(Box::new(inner_expr));
        Ok(GrammarNode::ZeroOrMore(repeat))
    }
}

struct OneOrMore;

impl Parser<GrammarContext> for OneOrMore {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse plus symbol
        PLUS.parse(source, cache, context)?;

        // Skip optional whitespace after +
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the inner expression
        let inner_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the one-or-more expression
        let repeat = Repeat::with_min(Box::new(inner_expr), 1);
        Ok(GrammarNode::OneOrMore(repeat))
    }
}

struct ZeroOrMoreSeparated;

impl Parser<GrammarContext> for ZeroOrMoreSeparated {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse asterisk symbol
        ASTERISK.parse(source, cache, context)?;

        // Skip optional whitespace after *
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the inner expression
        let inner_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the separator: /
        SLASH.parse(source, cache, context)?;

        // Skip optional whitespace after /
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the separator expression
        let separator_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the zero-or-more separated expression
        let repeat = Repeat::with_joint(Box::new(inner_expr), Box::new(separator_expr));
        Ok(GrammarNode::ZeroOrMoreSeparated(repeat))
    }
}

struct OneOrMoreSeparated;

impl Parser<GrammarContext> for OneOrMoreSeparated {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse plus symbol
        PLUS.parse(source, cache, context)?;

        // Skip optional whitespace after +
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the inner expression
        let inner_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the separator: /
        SLASH.parse(source, cache, context)?;

        // Skip optional whitespace after /
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the separator expression
        let separator_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the one-or-more separated expression
        let repeat = Repeat::with_joint_min(Box::new(inner_expr), Box::new(separator_expr), 1);
        Ok(GrammarNode::OneOrMoreSeparated(repeat))
    }
}

struct ZeroOrOne;

impl Parser<GrammarContext> for ZeroOrOne {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse question mark symbol
        QUESTION.parse(source, cache, context)?;

        // Skip optional whitespace after ?
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the inner expression
        let inner_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the zero-or-one expression
        let repeat = Repeat::with_max(Box::new(inner_expr), 1);
        Ok(GrammarNode::ZeroOrOne(repeat))
    }
}

struct ReadUntil;

impl Parser<GrammarContext> for ReadUntil {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse less-than symbol
        LESS_THAN.parse(source, cache, context)?;

        // Skip optional whitespace after <
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the end condition expression
        let end_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the read-until expression
        let utf8_until = Utf8Until::new(Box::new(end_expr));
        Ok(GrammarNode::ReadUntil(utf8_until))
    }
}

struct ReadUntilAndParse;

impl Parser<GrammarContext> for ReadUntilAndParse {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse opening parenthesis
        OPEN_PAREN.parse(source, cache, context)?;

        // Parse less-than symbol
        LESS_THAN.parse(source, cache, context)?;

        // Skip optional whitespace after <
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the end condition expression
        let end_expr = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse the content parser expression
        let content_parser = GrammarParser.parse(source, cache, context)?;

        // Skip optional whitespace before closing paren
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse closing parenthesis
        CLOSE_PAREN.parse(source, cache, context)?;

        // Build the read-until-parse expression
        let utf8_until = Utf8Until::new(Box::new(end_expr));
        Ok(GrammarNode::ReadUntilParse(
            utf8_until,
            Box::new(content_parser),
        ))
    }
}

// Parser for @start directive
struct StartDirective;

impl Parser<GrammarContext> for StartDirective {
    type Output = String;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse @start keyword
        AT_SYMBOL.parse(source, cache, context)?;
        START_KEYWORD.parse(source, cache, context)?;

        // Skip whitespace (including newlines)
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse rule name (identifier: letters, digits, underscores)
        let name = Identifier.parse(source, cache, context)?;

        Ok(name)
    }
}

// Parser for rule definition: name = expression
struct RuleDefinition;

impl Parser<GrammarContext> for RuleDefinition {
    type Output = (String, GrammarNode);

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse rule name (identifier: letters, digits, underscores)
        let name = Identifier.parse(source, cache, context)?;

        // Skip whitespace (including newlines)
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse equals sign
        EQUALS.parse(source, cache, context)?;

        // Skip whitespace (including newlines)
        let _ = Utf8Class::whitespace().parse(source, cache, context);

        // Parse expression
        let expression = <GrammarParser as Parser<GrammarContext>>::read(
            &GrammarParser,
            source,
            cache,
            context,
        )?;

        Ok((name, expression))
    }
}

// Parser for rule reference: just an identifier
struct RuleReferenceParser;

impl Parser<GrammarContext> for RuleReferenceParser {
    type Output = GrammarNode;

    fn read<S>(
        &self,
        source: &mut crate::parser::Source<S>,
        cache: &mut impl crate::cache::ParsingCache,
        context: &mut GrammarContext,
    ) -> crate::result::ParseResult<Self::Output>
    where
        S: crate::parser::Parsable,
    {
        // Parse identifier (letters, digits, underscores)
        let name = Identifier.parse(source, cache, context)?;

        // Check if this is a reserved keyword
        if matches!(
            name.as_str(),
            "digits"
                | "alpha"
                | "alphanumeric"
                | "whitespace"
                | "hexdigits"
                | "udigits"
                | "ualpha"
                | "ualphanumeric"
                | "uwhitespace"
                | "eof"
        ) {
            return Err(Error::NoMatch);
        }

        // Always create a rule reference - we'll resolve it later
        Ok(GrammarNode::RuleReference(name))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{parse, parse_with_context};
    use std::io::Cursor;

    #[test]
    fn test_inclass_basic() {
        let parser = InClass;

        let mut input = Cursor::new(b"[abc]");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();

        // Test that the character class was created correctly
        // We can't easily test the internal structure, but we can verify it was created
        let _utf8_class = result;
    }

    #[test]
    fn test_inclass_with_utf8() {
        let parser = InClass;

        // Test with UTF-8 characters
        let mut input = Cursor::new("[αβγ世界]".as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_inclass_with_escapes() {
        let parser = InClass;

        // Test with escaped brackets
        let mut input = Cursor::new(b"[\\[\\]]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_inclass_empty() {
        let parser = InClass;

        // Test empty character class
        let mut input = Cursor::new(b"[]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_inclass_missing_closing_bracket() {
        let parser = InClass;

        // Test malformed input - should fail
        let mut input = Cursor::new(b"[abc");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err());
    }

    #[test]
    fn test_inclass_functional() {
        // Test that the created character class actually works for parsing
        let parser = InClass;

        // Parse the character class definition
        let mut input = Cursor::new(b"[abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let char_class = parse_with_context(parser, &mut source, &mut context).unwrap();

        // Test the character class against actual input
        let mut test_input1 = Cursor::new(b"a");
        let mut test_source1 = crate::parser::Source::new(&mut test_input1);

        let result1 = parse(char_class.clone(), &mut test_source1);
        assert!(result1.is_ok()); // Should match 'a'
        if let Ok(matched) = result1 {
            assert_eq!(matched, "a"); // Should match exactly 'a'
        }

        let mut test_input2 = Cursor::new(b"d");
        let mut test_source2 = crate::parser::Source::new(&mut test_input2);

        let result2 = parse(char_class, &mut test_source2);
        // With min_length 1, it should fail to match 'd' since it's not in [abc]
        assert!(result2.is_err()); // Should NOT match 'd'
    }

    #[test]
    fn test_not_inclass_basic() {
        let parser = NotInClass;

        let mut input = Cursor::new(b"[^abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_not_inclass_with_utf8() {
        let parser = NotInClass;

        // Test with UTF-8 characters
        let mut input = Cursor::new("[^αβγ世界]".as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_not_inclass_with_escapes() {
        let parser = NotInClass;

        // Test with escaped brackets
        let mut input = Cursor::new(b"[^\\[\\]]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_not_inclass_empty() {
        let parser = NotInClass;

        // Test empty negated character class - should match any character
        let mut input = Cursor::new(b"[^]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        let _utf8_class = result;
    }

    #[test]
    fn test_not_inclass_missing_closing_bracket() {
        let parser = NotInClass;

        // Test malformed input - should fail
        let mut input = Cursor::new(b"[^abc");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err());
    }

    #[test]
    fn test_not_inclass_missing_caret() {
        let parser = NotInClass;

        // Test input without caret - should fail
        let mut input = Cursor::new(b"[abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err());
    }

    #[test]
    fn test_not_inclass_functional() {
        // Test that the created negated character class actually works for parsing
        let parser = NotInClass;

        // Parse the negated character class definition
        let mut input = Cursor::new(b"[^abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let char_class = parse_with_context(parser, &mut source, &mut context).unwrap();

        // Test the character class against actual input
        // Should match 'd' (not in [abc])
        let mut test_input1 = Cursor::new(b"d");
        let mut test_source1 = crate::parser::Source::new(&mut test_input1);

        let result1 = parse(char_class.clone(), &mut test_source1);
        assert!(result1.is_ok()); // Should match 'd'
        if let Ok(matched) = result1 {
            assert_eq!(matched, "d"); // Should match exactly 'd'
        }

        // Should NOT match 'a' (in [abc])
        let mut test_input2 = Cursor::new(b"a");
        let mut test_source2 = crate::parser::Source::new(&mut test_input2);

        let result2 = parse(char_class, &mut test_source2);
        assert!(result2.is_err()); // Should NOT match 'a'
    }

    #[test]
    fn test_grammar_expression_terminal() {
        // Test that GrammarParser::new() can parse a terminal
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"\"hello\"");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        match parse_with_context(parser, &mut source, &mut context) {
            Ok(GrammarNode::Terminal(literal)) => {
                // Verify we got a literal
                assert_eq!(literal, b"hello".as_slice().into());
            }
            _ => panic!("Expected Terminal expression"),
        }
    }

    #[test]
    fn test_grammar_expression_digits() {
        // Test that GrammarParser::new() can parse digits keyword
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"digits");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        match parse_with_context(parser, &mut source, &mut context) {
            Ok(GrammarNode::Digits(_)) => {
                // Success - we got a digits expression
            }
            _ => panic!("Expected Digits expression"),
        }
    }

    #[test]
    fn test_grammar_expression_alpha() {
        // Test that GrammarParser::new() can parse alpha keyword
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"alpha");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        match parse_with_context(parser, &mut source, &mut context) {
            Ok(GrammarNode::Alpha(_)) => {
                // Success - we got an alpha expression
            }
            _ => panic!("Expected Alpha expression"),
        }
    }

    #[test]
    fn test_grammar_expression_inclass() {
        // Test that GrammarParser::new() can parse character class
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"[abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        match parse_with_context(parser, &mut source, &mut context) {
            Ok(GrammarNode::InClass(_)) => {
                // Success - we got an InClass expression
            }
            _ => panic!("Expected InClass expression"),
        }
    }

    #[test]
    fn test_grammar_expression_not_inclass() {
        // Test that GrammarParser::new() can parse negated character class
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"[^abc]");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        match parse_with_context(parser, &mut source, &mut context) {
            Ok(GrammarNode::NotInClass(_)) => {
                // Success - we got a NotInClass expression
            }
            _ => panic!("Expected NotInClass expression"),
        }
    }

    #[test]
    fn test_grammar_expression_no_match() {
        // Test that GrammarParser::new() fails on invalid input
        let parser = GrammarParser::new();

        // This should not match since it's not a valid grammar expression
        // Use something that can't be parsed as any grammar construct
        let mut input = Cursor::new(b"@#$%");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err());
    }

    #[test]
    fn test_grammar_expression_parenthesized_sequence() {
        // Test that GrammarParser::new() can parse parenthesized sequences
        let parser = GrammarParser::new();

        // Test a simple sequence - should be successfully parsed
        let mut input = Cursor::new(b"(\"hello\" \"world\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        // Should succeed because parenthesized expressions are now implemented
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_alternatives() {
        // Test that GrammarParser::new() can parse alternatives syntax
        let parser = GrammarParser::new();

        // Test alternatives - should be successfully parsed
        let mut input = Cursor::new(b"(| \"hello\" \"world\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        // Should succeed because alternatives are now implemented
        assert!(result.is_ok());
    }

    #[test]
    fn test_alternatives_parser_direct() {
        // Test the Alternatives parser directly
        let mut input = Cursor::new(b"(| \"hello\" \"world\")");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(Alternatives, &mut source, &mut GrammarContext::default());
        println!("Direct Alternatives parser result: {result:?}");
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_repetition() {
        // Test that GrammarParser::new() can parse repetition syntax
        let parser = GrammarParser::new();

        // Test zero or more - should be successfully parsed
        let mut input = Cursor::new(b"(* \"hello\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        // Should succeed because repetitions are now implemented
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_one_or_more() {
        // Test one-or-more repetition
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(+ \"hello\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_zero_or_one() {
        // Test zero-or-one repetition
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(? \"hello\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_nested_sequences() {
        // Test nested parenthesized expressions
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(\"hello\" digits \"world\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());
    }

    #[test]
    fn test_grammar_expression_sequence_structure() {
        // Test that sequences actually create the proper recursive structure
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(\"hello\" \"world\" \"test\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());

        // Verify we got a Sequential expression
        if let Ok(GrammarNode::Sequential(_sequence)) = result {
            // The sequence should be: Sequence<"hello", Sequence<"world", "test">>
            // This demonstrates that our recursive structure building works
        } else {
            panic!("Expected Sequential expression");
        }
    }

    #[test]
    fn test_grammar_expression_alternatives_structure() {
        // Test that alternatives create the proper recursive structure
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(| \"hello\" \"world\" \"test\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());

        // Verify we got an Alternatives expression
        if let Ok(GrammarNode::Alternatives(_either)) = result {
            // The alternatives should be: Either<"hello", Either<"world", "test">>
            // This demonstrates that our recursive structure building works
        } else {
            panic!("Expected Alternatives expression");
        }
    }

    #[test]
    fn test_grammar_expression_repetition_structure() {
        // Test that repetitions create the proper structure
        let parser = GrammarParser::new();

        let mut input = Cursor::new(b"(* \"hello\")");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());

        // Verify we got a ZeroOrMore expression
        if let Ok(GrammarNode::ZeroOrMore(_repeat)) = result {
            // The repetition properly wraps the inner expression
        } else {
            panic!("Expected ZeroOrMore expression");
        }
    }

    // Tests for parsing functionality
    #[test]
    fn test_sequence_parsing_basic() {
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"("hello" "world")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "Sequence parsing should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::Sequential(_) => {
                    // Expected: this is the correct structure for sequences
                }
                _ => panic!("Expected Sequential expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_alternatives_parsing_basic() {
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(| "hello" "world")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "Alternatives parsing should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::Alternatives(_) => {
                    // Expected: this is the correct structure for alternatives
                }
                _ => panic!("Expected Alternatives expression, got {expr:?}"),
            }
        }
    }

    // Tests for all character class keywords
    #[test]
    #[allow(clippy::type_complexity)]
    fn test_all_character_class_keywords() {
        let test_cases: Vec<(&'static str, Box<dyn Fn(&GrammarNode) -> bool>)> = vec![
            (
                "digits",
                Box::new(|expr| matches!(expr, GrammarNode::Digits(_))),
            ),
            (
                "alpha",
                Box::new(|expr| matches!(expr, GrammarNode::Alpha(_))),
            ),
            (
                "alphanumeric",
                Box::new(|expr| matches!(expr, GrammarNode::Alphanumeric(_))),
            ),
            (
                "whitespace",
                Box::new(|expr| matches!(expr, GrammarNode::Whitespace(_))),
            ),
            (
                "hexdigits",
                Box::new(|expr| matches!(expr, GrammarNode::HexDigits(_))),
            ),
            (
                "udigits",
                Box::new(|expr| matches!(expr, GrammarNode::UDigits(_))),
            ),
            (
                "ualpha",
                Box::new(|expr| matches!(expr, GrammarNode::UAlpha(_))),
            ),
            (
                "ualphanumeric",
                Box::new(|expr| matches!(expr, GrammarNode::UAlphanumeric(_))),
            ),
            (
                "uwhitespace",
                Box::new(|expr| matches!(expr, GrammarNode::UWhitespace(_))),
            ),
        ];

        for (keyword, matcher) in test_cases {
            let parser = GrammarParser::new();
            let mut input = Cursor::new(keyword.as_bytes());
            let mut source = crate::parser::Source::new(&mut input);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(result.is_ok(), "Failed to parse keyword: {keyword}");

            if let Ok(expr) = result {
                assert!(
                    matcher(&expr),
                    "Wrong expression type for keyword {keyword}: {expr:?}",
                );
            }
        }
    }

    // Tests for terminal parsing with various escape sequences
    #[test]
    fn test_terminal_with_escape_sequences() {
        let test_cases = vec![
            (r#""hello""#, "hello"),
            (r#""hello world""#, "hello world"),
            (r#""line\nbreak""#, "linenbreak"), // \n becomes literal n
            (r#""quote\"inside""#, r#"quote"inside"#), // \" becomes literal "
            (r#""backslash\\here""#, r#"backslash\here"#), // \\ becomes literal \
            (r#""tab\there""#, "tabthere"),     // \t becomes literal t
        ];

        for (input, expected) in test_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(result.is_ok(), "Failed to parse terminal: {input}");

            if let Ok(GrammarNode::Terminal(literal)) = result {
                assert_eq!(
                    literal,
                    expected.as_bytes().into(),
                    "Wrong literal value for: {input}",
                );
            } else {
                panic!("Expected Terminal expression for: {input}");
            }
        }
    }

    // Tests for character class parsing
    #[test]
    fn test_character_class_parsing() {
        let test_cases = vec![
            ("[abc]", true),  // basic character class
            ("[^abc]", true), // negated character class
            ("[a-z]", true),  // range (should be parsed as individual chars for now)
            ("[αβγ]", true),  // unicode characters
            ("[]", true),     // empty character class
            ("[^]", true),    // empty negated character class
        ];

        for (input, should_succeed) in test_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);

            if should_succeed {
                assert!(result.is_ok(), "Failed to parse character class: {input}");
                match result {
                    Ok(GrammarNode::InClass(_)) | Ok(GrammarNode::NotInClass(_)) => {
                        // Success - got the expected character class type
                    }
                    _ => panic!("Expected character class expression for: {input}"),
                }
            } else {
                assert!(result.is_err(), "Should have failed to parse: {input}");
            }
        }
    }

    // Tests for repetition operators
    #[test]
    #[allow(clippy::type_complexity)]
    fn test_repetition_operators() {
        let test_cases: Vec<(&'static str, Box<dyn Fn(&GrammarNode) -> bool>)> = vec![
            (
                "(* \"hello\")",
                Box::new(|expr| matches!(expr, GrammarNode::ZeroOrMore(_))),
            ),
            (
                "(+ \"hello\")",
                Box::new(|expr| matches!(expr, GrammarNode::OneOrMore(_))),
            ),
            (
                "(? \"hello\")",
                Box::new(|expr| matches!(expr, GrammarNode::ZeroOrOne(_))),
            ),
        ];

        for (input, matcher) in test_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(result.is_ok(), "Failed to parse repetition: {input}");

            if let Ok(expr) = result {
                assert!(
                    matcher(&expr),
                    "Wrong expression type for repetition: {input}",
                );
            }
        }
    }

    // Tests for separated repetitions
    #[test]
    #[allow(clippy::type_complexity)]
    fn test_separated_repetitions() {
        let test_cases: Vec<(&'static str, Box<dyn Fn(&GrammarNode) -> bool>)> = vec![
            (
                "(*\"item\" / \",\")",
                Box::new(|expr| matches!(expr, GrammarNode::ZeroOrMoreSeparated(_))),
            ),
            (
                "(+\"item\" / \",\")",
                Box::new(|expr| matches!(expr, GrammarNode::OneOrMoreSeparated(_))),
            ),
        ];

        for (input, matcher) in test_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(
                result.is_ok(),
                "Failed to parse separated repetition: {input}",
            );

            if let Ok(expr) = result {
                assert!(
                    matcher(&expr),
                    "Wrong expression type for separated repetition: {input}",
                );
            }
        }
    }

    // Tests for deeply nested expressions
    #[test]
    fn test_deeply_nested_sequences() {
        let input = "(\"a\" \"b\" \"c\" \"d\" \"e\" \"f\")";
        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(input.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok(), "Failed to parse deeply nested sequence");

        if let Ok(GrammarNode::Sequential(_)) = result {
            // Success - deeply nested sequences should work
        } else {
            panic!("Expected Sequential expression for deeply nested sequence");
        }
    }

    #[test]
    fn test_deeply_nested_alternatives() {
        let input = "(| \"a\" \"b\" \"c\" \"d\" \"e\" \"f\")";
        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(input.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok(), "Failed to parse deeply nested alternatives");

        if let Ok(GrammarNode::Alternatives(_)) = result {
            // Success - deeply nested alternatives should work
        } else {
            panic!("Expected Alternatives expression for deeply nested alternatives");
        }
    }

    // Tests for mixed sequences and alternatives
    #[test]
    fn test_nested_mixed_expressions() {
        let input = "(\"start\" (| \"option1\" \"option2\") \"end\")";
        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(input.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok(), "Failed to parse nested mixed expressions");

        if let Ok(GrammarNode::Sequential(_)) = result {
            // Success - nested mixed expressions should work
        } else {
            panic!("Expected Sequential expression for nested mixed expressions");
        }
    }

    // Tests for error cases
    #[test]
    fn test_malformed_parentheses() {
        // Test cases that should fail with NoMatch
        let error_cases = vec!["(\"unclosed", "(\"missing_close\""];

        for input in error_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(matches!(result, Err(crate::result::Error::NoMatch)));
        }

        // Test cases that should succeed (parser ignores trailing characters)
        let success_cases = vec!["\"unopened\")", "\"missing_open\")"];

        for input in success_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(result.is_ok());
        }

        // Test case that should succeed with nested parentheses
        let nested_case = "((\"double\"))";
        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(nested_case.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());
    }

    #[test]
    fn test_malformed_character_classes() {
        let error_cases = vec!["[unclosed", "[^unclosed"];

        for input in error_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(
                result.is_err(),
                "Should have failed for malformed character class: {input}",
            );
        }
    }

    #[test]
    fn test_malformed_terminals() {
        let error_cases = vec!["\"unclosed", "\"unterminated\\"];

        for input in error_cases {
            let parser = GrammarParser::new();
            let mut input_cursor = Cursor::new(input.as_bytes());
            let mut source = crate::parser::Source::new(&mut input_cursor);

            let mut context = GrammarContext::default();
            let result = parse_with_context(parser, &mut source, &mut context);
            assert!(
                dbg!(result).is_err(),
                "Should have failed for malformed terminal: {input}",
            );
        }
    }

    // Performance and edge case tests
    #[test]
    fn test_empty_input() {
        let parser = GrammarParser::new();
        let mut input = Cursor::new(b"");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err(), "Should fail on empty input");
    }

    #[test]
    fn test_whitespace_only() {
        let parser = GrammarParser::new();
        let mut input = Cursor::new(b"   \t\n  ");
        let mut source = crate::parser::Source::new(&mut input);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err(), "Should fail on whitespace-only input");
    }

    #[test]
    fn test_very_long_terminal() {
        let long_content = "a".repeat(1000);
        let input = format!("\"{long_content}\"");

        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(input.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok(), "Should handle very long terminals");

        if let Ok(GrammarNode::Terminal(literal)) = result {
            assert_eq!(literal, long_content.as_bytes().into());
        } else {
            panic!("Expected Terminal expression for very long terminal");
        }
    }

    #[test]
    fn test_very_long_character_class() {
        let long_chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".repeat(10);
        let input = format!("[{long_chars}]");

        let parser = GrammarParser::new();
        let mut input_cursor = Cursor::new(input.as_bytes());
        let mut source = crate::parser::Source::new(&mut input_cursor);

        let mut context = GrammarContext::default();
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok(), "Should handle very long character classes");

        if let Ok(GrammarNode::InClass(_)) = result {
            // Success - very long character class handled
        } else {
            panic!("Expected InClass expression for very long character class");
        }
    }

    // Tests for Expression Parser implementation
    #[test]
    fn test_expression_parser_terminal() {
        let expr = GrammarNode::Terminal(Literal::from_str("hello"));

        let mut input = Cursor::new(b"hello");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(result.is_ok(), "Expression parser should work for Terminal");

        if let Ok(GrammarResult::Literal(bytes)) = result {
            assert_eq!(bytes, b"hello".to_vec());
        } else {
            panic!("Expected Literal result");
        }
    }

    #[test]
    fn test_expression_parser_digits() {
        let expr = GrammarNode::Digits(Utf8Class::digits());

        let mut input = Cursor::new(b"12345");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(result.is_ok(), "Expression parser should work for Digits");

        if let Ok(GrammarResult::Unicode(chars)) = result {
            assert_eq!(chars, "12345");
        } else {
            panic!("Expected Bytes result");
        }
    }

    #[test]
    fn test_expression_parser_sequence() {
        // Create a sequence: "hello" followed by "world"
        let hello_expr = GrammarNode::Terminal(Literal::from_str("hello"));
        let world_expr = GrammarNode::Terminal(Literal::from_str("world"));
        let sequence = Sequence::new(Box::new(hello_expr), Box::new(world_expr));
        let expr = GrammarNode::Sequential(sequence);

        let mut input = Cursor::new(b"helloworld");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(
            result.is_ok(),
            "Expression parser should work for Sequential"
        );

        if let Ok(GrammarResult::Sequence(results)) = result {
            assert_eq!(results.len(), 2);
            // Convert to bytes to check the combined result
            let combined_bytes = GrammarResult::Sequence(results).to_bytes();
            assert_eq!(combined_bytes, b"helloworld".to_vec());
        } else {
            panic!("Expected Sequence result");
        }
    }

    #[test]
    fn test_expression_parser_alternatives() {
        // Create alternatives: "hello" OR "world"
        let hello_expr = GrammarNode::Terminal(Literal::from_str("hello"));
        let world_expr = GrammarNode::Terminal(Literal::from_str("world"));
        let either = Either::new(Box::new(hello_expr), Box::new(world_expr));
        let expr = GrammarNode::Alternatives(either);

        // Test first alternative
        let mut input1 = Cursor::new(b"hello");
        let mut source1 = crate::parser::Source::new(&mut input1);

        let result1 =
            parse_with_context(expr.clone(), &mut source1, &mut GrammarContext::default());
        assert!(
            result1.is_ok(),
            "Expression parser should work for first alternative"
        );

        if let Ok(GrammarResult::Alternative(boxed_result)) = result1 {
            assert_eq!(boxed_result.to_bytes(), b"hello".to_vec());
        } else {
            panic!("Expected Alternative result");
        }

        // Test second alternative
        let mut input2 = Cursor::new(b"world");
        let mut source2 = crate::parser::Source::new(&mut input2);

        let result2 = parse_with_context(expr, &mut source2, &mut GrammarContext::default());
        assert!(
            result2.is_ok(),
            "Expression parser should work for second alternative"
        );

        if let Ok(GrammarResult::Alternative(boxed_result)) = result2 {
            assert_eq!(boxed_result.to_bytes(), b"world".to_vec());
        } else {
            panic!("Expected Alternative result");
        }
    }

    #[test]
    fn test_expression_parser_zero_or_more() {
        // Create zero-or-more: (* "a")
        let a_expr = GrammarNode::Terminal(Literal::from_str("a"));
        let repeat = Repeat::new(Box::new(a_expr));
        let expr = GrammarNode::ZeroOrMore(repeat);

        let mut input = Cursor::new(b"aaab");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(
            result.is_ok(),
            "Expression parser should work for ZeroOrMore"
        );

        if let Ok(GrammarResult::Repetition(results)) = result {
            let combined_bytes = GrammarResult::Repetition(results).to_bytes();
            assert_eq!(combined_bytes, b"aaa".to_vec());
        } else {
            panic!("Expected Repetition result");
        }
    }

    #[test]
    fn test_expression_parser_zero_or_one() {
        // Create zero-or-one: (? "maybe")
        let maybe_expr = GrammarNode::Terminal(Literal::from_str("maybe"));
        let option = Repeat::with_max(Box::new(maybe_expr), 1);
        let expr = GrammarNode::ZeroOrOne(option);

        let mut input = Cursor::new(b"maybe");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(
            result.is_ok(),
            "Expression parser should work for ZeroOrOne"
        );

        if let Ok(GrammarResult::Optional(Some(boxed_result))) = result {
            assert_eq!(boxed_result.to_bytes(), b"maybe".to_vec());
        } else {
            panic!("Expected Optional(Some) result");
        }
    }

    #[test]
    fn test_expression_parser_sequential_end() {
        // Create sequence ending: Sequence<"hello", ()>
        let hello_expr = GrammarNode::Terminal(Literal::from_str("hello"));
        let sequence = Sequence::new(Box::new(hello_expr), ());
        let expr = GrammarNode::SequentialEnd(sequence);

        let mut input = Cursor::new(b"hello");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(
            result.is_ok(),
            "Expression parser should work for SequentialEnd"
        );

        if let Ok(GrammarResult::Literal(bytes)) = result {
            assert_eq!(bytes, b"hello".to_vec());
        } else {
            panic!("Expected Literal result from SequentialEnd");
        }
    }

    #[test]
    fn test_expression_parser_complex_nested() {
        // Test a complex nested expression with the actual Expression Parser
        // This verifies that the delegation works correctly for complex structures

        // Build manually: Sequence<"start", Sequence<Digits, ()>>
        let start_expr = GrammarNode::Terminal(Literal::from_str("start"));
        let digits_expr = GrammarNode::Digits(Utf8Class::digits());

        let inner_seq = Sequence::new(Box::new(digits_expr), ());
        let inner_expr = GrammarNode::SequentialEnd(inner_seq);

        let outer_seq = Sequence::new(Box::new(start_expr), Box::new(inner_expr));
        let expr = GrammarNode::Sequential(outer_seq);

        let mut input = Cursor::new(b"start123");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse_with_context(expr, &mut source, &mut GrammarContext::default());
        assert!(
            result.is_ok(),
            "Expression parser should work for complex nested structures"
        );

        if let Ok(GrammarResult::Sequence(results)) = result {
            let combined_bytes = GrammarResult::Sequence(results).to_bytes();
            assert_eq!(combined_bytes, b"start123".to_vec());
        } else {
            panic!("Expected Sequence result from complex nested structure");
        }
    }

    #[test]
    fn test_expression_result_to_bytes() {
        // Test the to_bytes() method on various GrammarResult types

        // Test Literal
        let literal_result = GrammarResult::Literal(b"hello".to_vec());
        assert_eq!(literal_result.to_bytes(), b"hello".to_vec());

        // Test Unicode
        let unicode_result = GrammarResult::Unicode("world".to_string());
        assert_eq!(unicode_result.to_bytes(), b"world".to_vec());

        // Test Bytes
        let bytes_result = GrammarResult::Bytes(b"test".to_vec());
        assert_eq!(bytes_result.to_bytes(), b"test".to_vec());

        // Test Sequence
        let seq_result = GrammarResult::Sequence(vec![
            GrammarResult::Literal(b"hello".to_vec()),
            GrammarResult::Literal(b"world".to_vec()),
        ]);
        assert_eq!(seq_result.to_bytes(), b"helloworld".to_vec());

        // Test Alternative
        let alt_result =
            GrammarResult::Alternative(Box::new(GrammarResult::Literal(b"choice".to_vec())));
        assert_eq!(alt_result.to_bytes(), b"choice".to_vec());

        // Test Repetition
        let rep_result = GrammarResult::Repetition(vec![
            GrammarResult::Literal(b"a".to_vec()),
            GrammarResult::Literal(b"b".to_vec()),
            GrammarResult::Literal(b"c".to_vec()),
        ]);
        assert_eq!(rep_result.to_bytes(), b"abc".to_vec());

        // Test Optional (Some)
        let opt_some_result =
            GrammarResult::Optional(Some(Box::new(GrammarResult::Literal(b"maybe".to_vec()))));
        assert_eq!(opt_some_result.to_bytes(), b"maybe".to_vec());

        // Test Optional (None)
        let opt_none_result = GrammarResult::Optional(None);
        assert_eq!(opt_none_result.to_bytes(), Vec::<u8>::new());

        // Test Empty
        let empty_result = GrammarResult::Empty;
        assert_eq!(empty_result.to_bytes(), Vec::<u8>::new());
    }

    #[test]
    fn test_expression_result_is_empty() {
        // Test the is_empty() method

        assert!(!GrammarResult::Literal(b"hello".to_vec()).is_empty());
        assert!(!GrammarResult::Unicode("world".to_string()).is_empty());
        assert!(!GrammarResult::Bytes(b"test".to_vec()).is_empty());
        assert!(!GrammarResult::Sequence(vec![]).is_empty()); // Empty sequence is not considered "empty"
        assert!(
            !GrammarResult::Alternative(Box::new(GrammarResult::Literal(b"a".to_vec()))).is_empty()
        );
        assert!(!GrammarResult::Repetition(vec![]).is_empty()); // Empty repetition is not considered "empty"
        assert!(
            !GrammarResult::Optional(Some(Box::new(GrammarResult::Literal(b"a".to_vec()))))
                .is_empty()
        );

        assert!(GrammarResult::Optional(None).is_empty());
        assert!(GrammarResult::Empty.is_empty());
    }

    #[test]
    fn test_id_implementation_grammar_expression() {
        // GrammarParser::new() is a unit struct with no parameters, so default id() is correct
        let grammar1 = GrammarParser::new();
        let grammar2 = GrammarParser::new();

        // These should have the same ID since GrammarParser::new() has no parameters
        assert_eq!(
            <GrammarParser as crate::parser::Parser<()>>::id(&grammar1),
            <GrammarParser as crate::parser::Parser<()>>::id(&grammar2),
            "GrammarParser::new() instances should have same ID since they have no parameters"
        );
    }

    #[test]
    fn test_id_implementation_different_expressions() {
        // This test checks that Expression enum implements proper id() method
        // Different Expression variants with different data should have different IDs

        let expr1 = GrammarNode::Terminal(Literal::from_str("hello"));
        let expr2 = GrammarNode::Terminal(Literal::from_str("world"));
        let expr3 = GrammarNode::Digits(Utf8Class::digits());

        // These should have different IDs because they represent different parsing behavior
        // This test will FAIL if Expression uses default id() implementation
        assert_ne!(
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr1),
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr2),
            "Different Expression instances should have different IDs to avoid cache collisions"
        );
        assert_ne!(
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr1),
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr3),
            "Different Expression variants should have different IDs to avoid cache collisions"
        );
        assert_ne!(
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr2),
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr3),
            "Different Expression variants should have different IDs to avoid cache collisions"
        );
    }

    #[test]
    fn test_id_implementation_same_expressions() {
        // Test that identical expressions have the same ID
        let expr1 = GrammarNode::Terminal(Literal::from_str("hello"));
        let expr2 = GrammarNode::Terminal(Literal::from_str("hello"));

        assert_eq!(
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr1),
            <GrammarNode as crate::parser::Parser<GrammarContext>>::id(&expr2),
            "Identical Expression instances should have the same ID for cache efficiency"
        );
    }

    #[test]
    fn test_id_implementation_expression_cache_correctness() {
        use std::io::Cursor;

        // This test verifies that cache works correctly without collisions
        // when Expression implements proper id() method

        let expr1 = GrammarNode::Terminal(Literal::from_str("hello"));
        let expr2 = GrammarNode::Terminal(Literal::from_str("world"));

        // Test parsing "hello" with expr1
        let mut input1 = Cursor::new(b"hello");
        let mut source1 = crate::parser::Source::new(&mut input1);

        let result1 = parse_with_context(expr1, &mut source1, &mut GrammarContext::default());
        assert!(result1.is_ok(), "First parse should succeed");

        // Parse "world" with expr2 - this should succeed and not use cached result from expr1
        let mut input2 = Cursor::new(b"world");
        let mut source2 = crate::parser::Source::new(&mut input2);

        let result2 = parse_with_context(expr2, &mut source2, &mut GrammarContext::default());
        assert!(result2.is_ok(), "Second parse should succeed");

        // Verify the results are different
        if let (Ok(GrammarResult::Literal(bytes1)), Ok(GrammarResult::Literal(bytes2))) =
            (result1, result2)
        {
            assert_ne!(
                bytes1, bytes2,
                "Results should be different - no cache collision should occur"
            );
            assert_eq!(bytes1, b"hello".to_vec());
            assert_eq!(bytes2, b"world".to_vec());
        } else {
            panic!("Expected literal results");
        }
    }

    #[test]
    fn test_id_implementation_box_expression() {
        // Test that Box<Grammar> properly implements id() method
        let boxed_expr1 = Box::new(GrammarNode::Terminal(Literal::from_str("test1")));
        let boxed_expr2 = Box::new(GrammarNode::Terminal(Literal::from_str("test2")));

        // These should have different IDs since they contain different expressions
        // This test will FAIL if Box<Grammar> uses default id() implementation
        let id1 = <Box<GrammarNode> as crate::parser::Parser<GrammarContext>>::id(&boxed_expr1);
        let id2 = <Box<GrammarNode> as crate::parser::Parser<GrammarContext>>::id(&boxed_expr2);

        assert_ne!(
            id1, id2,
            "Different Box<Grammar> instances should have different IDs to avoid cache collisions"
        );
    }

    #[test]
    fn test_id_implementation_same_box_expression() {
        // Test that identical boxed expressions have the same ID
        let boxed_expr1 = Box::new(GrammarNode::Terminal(Literal::from_str("test")));
        let boxed_expr2 = Box::new(GrammarNode::Terminal(Literal::from_str("test")));

        assert_eq!(
            <Box<GrammarNode> as crate::parser::Parser<GrammarContext>>::id(&boxed_expr1),
            <Box<GrammarNode> as crate::parser::Parser<GrammarContext>>::id(&boxed_expr2),
            "Identical Box<GrammarNode> instances should have the same ID for cache efficiency"
        );
    }

    #[test]
    fn test_id_implementation_different_keyword_parsers() {
        // Test that different keyword parsers have different IDs
        // These parsers are unit structs so default id() implementation is correct
        let digits_parser = Digits;
        let alpha_parser = Alpha;
        let whitespace_parser = Whitespace;

        // These should have different IDs since they're different types
        assert_ne!(
            <Digits as crate::parser::Parser<GrammarContext>>::id(&digits_parser),
            <Alpha as crate::parser::Parser<GrammarContext>>::id(&alpha_parser),
            "Different parser types should have different IDs"
        );
        assert_ne!(
            <Alpha as crate::parser::Parser<GrammarContext>>::id(&alpha_parser),
            <Whitespace as crate::parser::Parser<GrammarContext>>::id(&whitespace_parser),
            "Different parser types should have different IDs"
        );
        assert_ne!(
            <Digits as crate::parser::Parser<GrammarContext>>::id(&digits_parser),
            <Whitespace as crate::parser::Parser<GrammarContext>>::id(&whitespace_parser),
            "Different parser types should have different IDs"
        );

        // Same type instances should have same ID
        let digits_parser2 = Digits;
        assert_eq!(
            <Digits as crate::parser::Parser<GrammarContext>>::id(&digits_parser),
            <Digits as crate::parser::Parser<GrammarContext>>::id(&digits_parser2),
            "Same parser type instances should have same ID"
        );
    }

    #[test]
    fn test_read_until_parse_functionality() {
        // Test that ReadUntilParse actually parses captured content
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" "captured")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "ReadUntilParse parsing should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: this should create a ReadUntilParse expression
                    // The actual functionality will be tested when the expression is executed
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    // Comprehensive tests for ReadUntil and ReadUntilParse
    #[test]
    fn test_read_until_basic_parsing() {
        // Test basic ReadUntil syntax parsing
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "ReadUntil parsing should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: this should create a ReadUntil expression
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_complex_end_condition() {
        // Test ReadUntil with complex end condition
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< (| "end" "stop"))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntil with complex end condition should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: should handle complex end conditions
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_complex_parser() {
        // Test ReadUntilParse with complex content parser
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" (| "hello" "world"))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse with complex parser should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: should handle complex content parsers
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_with_whitespace() {
        // Test ReadUntil parsing with whitespace in syntax
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(<  "end"  )"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "ReadUntil with whitespace should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: whitespace should be handled properly
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_with_whitespace() {
        // Test ReadUntilParse parsing with whitespace in syntax
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(<  "end"  "content"  )"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse with whitespace should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: whitespace should be handled properly
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_nested() {
        // Test ReadUntil nested inside other expressions
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(* (< "end"))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "Nested ReadUntil should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ZeroOrMore(_) => {
                    // Expected: should create a repetition of ReadUntil
                }
                _ => panic!("Expected ZeroOrMore expression containing ReadUntil, got {expr:?}",),
            }
        }
    }

    #[test]
    fn test_read_until_parse_nested() {
        // Test ReadUntilParse nested inside other expressions
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(+ (< "end" "content"))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "Nested ReadUntilParse should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::OneOrMore(_) => {
                    // Expected: should create a repetition of ReadUntilParse
                }
                _ => {
                    panic!("Expected OneOrMore expression containing ReadUntilParse, got {expr:?}",)
                }
            }
        }
    }

    #[test]
    fn test_read_until_in_sequence() {
        // Test ReadUntil as part of a sequence
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"("start" (< "end") "finish")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "ReadUntil in sequence should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::Sequential(_) => {
                    // Expected: should create a sequence containing ReadUntil
                }
                _ => panic!("Expected Sequential expression containing ReadUntil, got {expr:?}",),
            }
        }
    }

    #[test]
    fn test_read_until_parse_in_alternatives() {
        // Test ReadUntilParse as part of alternatives
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(| (< "end" "content") "fallback")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse in alternatives should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::Alternatives(_) => {
                    // Expected: should create alternatives containing ReadUntilParse
                }
                _ => panic!(
                    "Expected Alternatives expression containing ReadUntilParse, got {expr:?}",
                ),
            }
        }
    }

    #[test]
    fn test_read_until_with_keyword_end() {
        // Test ReadUntil with keyword end condition
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< digits)"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_ok(), "ReadUntil with keyword end should succeed");

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: should handle keyword end conditions
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_with_keyword_parser() {
        // Test ReadUntilParse with keyword content parser
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" alpha)"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse with keyword parser should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: should handle keyword content parsers
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_with_character_class() {
        // Test ReadUntil with character class end condition
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< [abc])"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntil with character class should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: should handle character class end conditions
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_with_character_class_parser() {
        // Test ReadUntilParse with character class content parser
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" [0-9])"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse with character class parser should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: should handle character class content parsers
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_malformed_missing_closing_paren() {
        // Test error handling for malformed ReadUntil syntax
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end""#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_err(), "Malformed ReadUntil should fail");
    }

    #[test]
    fn test_read_until_parse_malformed_missing_content_parser() {
        // Test error handling for ReadUntilParse missing content parser
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end")"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        // This should parse as ReadUntil, not ReadUntilParse
        assert!(
            result.is_ok(),
            "ReadUntil (not ReadUntilParse) should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: should parse as ReadUntil when only one argument
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_malformed_missing_closing_paren() {
        // Test error handling for malformed ReadUntilParse syntax
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" "content""#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(result.is_err(), "Malformed ReadUntilParse should fail");
    }

    #[test]
    fn test_read_until_deeply_nested_expressions() {
        // Test ReadUntil with deeply nested end conditions
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< ("prefix" (| "end1" "end2")))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntil with deeply nested end should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntil(_) => {
                    // Expected: should handle deeply nested expressions
                }
                _ => panic!("Expected ReadUntil expression, got {expr:?}"),
            }
        }
    }

    #[test]
    fn test_read_until_parse_deeply_nested_content_parser() {
        // Test ReadUntilParse with deeply nested content parser
        let grammar = GrammarParser::new();
        let mut input = Cursor::new(r#"(< "end" (* (| "hello" digits)))"#.as_bytes());
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar, &mut source);
        assert!(
            result.is_ok(),
            "ReadUntilParse with deeply nested content parser should succeed"
        );

        if let Ok(expr) = result {
            match expr.node {
                GrammarNode::ReadUntilParse(_, _) => {
                    // Expected: should handle deeply nested content parsers
                }
                _ => panic!("Expected ReadUntilParse expression, got {expr:?}"),
            }
        }
    }

    // Tests for new grammar features

    #[test]
    fn test_start_directive_basic() {
        let parser = StartDirective;

        let mut input = Cursor::new(b"@start expr");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        assert_eq!(result, "expr".to_string());
    }

    #[test]
    fn test_start_directive_with_whitespace() {
        let parser = StartDirective;

        let mut input = Cursor::new(b"@start   main");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        assert_eq!(result, "main".to_string());
    }

    #[test]
    fn test_start_directive_invalid() {
        let parser = StartDirective;

        let mut input = Cursor::new(b"start expr");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_err());
    }

    #[test]
    fn test_rule_definition_basic() {
        let parser = RuleDefinition;

        let mut input = Cursor::new(b"expr = digits");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        assert_eq!(result.0, "expr".to_string());
        // The result.1 should be a GrammarNode::Digits variant
        match result.1 {
            GrammarNode::Digits(_) => {}
            _ => panic!("Expected Digits node, got {:?}", result.1),
        }
    }

    #[test]
    fn test_rule_definition_with_whitespace() {
        let parser = RuleDefinition;

        let mut input = Cursor::new(b"term   =   alpha");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        assert_eq!(result.0, "term".to_string());
        match result.1 {
            GrammarNode::Alpha(_) => {}
            _ => panic!("Expected Alpha node, got {:?}", result.1),
        }
    }

    #[test]
    fn test_rule_reference_parser_with_known_rule() {
        let parser = RuleReferenceParser;

        let mut input = Cursor::new(b"expr");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        // Add a rule to the context so it's "known"
        context.rules.insert(
            "expr".to_string(),
            GrammarNode::Digits(crate::utf8class::Utf8Class::digits()),
        );

        let result = parse_with_context(parser, &mut source, &mut context).unwrap();
        match result {
            GrammarNode::RuleReference(name) => assert_eq!(name, "expr".to_string()),
            _ => panic!("Expected RuleReference, got {result:?}"),
        }
    }

    #[test]
    fn test_rule_reference_parser_with_unknown_rule() {
        let parser = RuleReferenceParser;

        let mut input = Cursor::new(b"unknown");
        let mut source = crate::parser::Source::new(&mut input);
        let mut context = GrammarContext::default();

        // RuleReferenceParser should succeed in parsing the identifier
        // but the rule reference will fail when executed (not during parsing)
        let result = parse_with_context(parser, &mut source, &mut context);
        assert!(result.is_ok());
        if let GrammarNode::RuleReference(name) = result.unwrap() {
            assert_eq!(name, "unknown");
        } else {
            panic!("Expected RuleReference");
        }
    }

    // Tests moved from tests/grammar_features.rs (unit tests only)

    #[test]
    fn test_grammar_parser_basic_expressions_still_work() {
        // Test that basic expressions still work with our new Grammar system
        let grammar_parser = GrammarParser::new();

        // Test digits keyword
        let mut input = Cursor::new(b"digits");
        let mut source = crate::parser::Source::new(&mut input);
        let grammar = parse_with_context(
            grammar_parser.clone(),
            &mut source,
            &mut GrammarContext::default(),
        )
        .expect("Should parse 'digits' keyword");

        // Test that the grammar can parse actual digits
        let mut test_input = Cursor::new(b"123");
        let mut test_source = crate::parser::Source::new(&mut test_input);
        let result = parse_with_context(grammar, &mut test_source, &mut GrammarContext::default())
            .expect("Should parse '123' with digits grammar");

        match result {
            GrammarResult::Unicode(s) => assert_eq!(s, "123"),
            _ => panic!("Expected Unicode result for digits, got {result:?}"),
        }
    }

    #[test]
    fn test_grammar_parser_terminal_strings() {
        let grammar_parser = GrammarParser::new();

        // Test terminal string
        let mut input = Cursor::new(b"\"hello\"");
        let mut source = crate::parser::Source::new(&mut input);
        let grammar =
            parse_with_context(grammar_parser, &mut source, &mut GrammarContext::default())
                .expect("Should parse terminal string");

        // Test that the grammar can parse the literal "hello"
        let mut test_input = Cursor::new(b"hello");
        let mut test_source = crate::parser::Source::new(&mut test_input);
        let result = parse_with_context(grammar, &mut test_source, &mut GrammarContext::default())
            .expect("Should parse 'hello' with terminal grammar");

        match result {
            GrammarResult::Literal(bytes) => assert_eq!(bytes, b"hello"),
            _ => panic!("Expected Literal result for terminal, got {result:?}"),
        }
    }

    #[test]
    fn test_rule_reference_succeeds_without_context() {
        // This test asserts that parsing an identifier as a rule reference succeeds
        // when no rules are defined in the context (forward reference allowed)
        let grammar_parser = GrammarParser::new();

        let mut input = Cursor::new(b"unknownrule");
        let mut source = crate::parser::Source::new(&mut input);

        // This should succeed because "unknownrule" is parsed as a rule reference
        // (failure happens at execution time, not parse time)
        let result =
            parse_with_context(grammar_parser, &mut source, &mut GrammarContext::default());

        // With our updated implementation, this succeeds as a rule reference
        // but will fail at execution time if the rule doesn't exist
        assert!(
            result.is_ok(),
            "Parsing unknown identifier should succeed as a rule reference"
        );
    }

    #[test]
    fn test_start_directive_parsed_fail_if_no_such_rule() {
        let grammar_parser = GrammarParser::new();

        let mut input = Cursor::new(b"@start expr\nother = alpha");
        let mut source = crate::parser::Source::new(&mut input);

        let result = parse(grammar_parser, &mut source);

        result.expect_err(
            "GrammarParser should fail if @start directive refers to an nonexistent rule",
        );
    }

    #[test]
    fn test_rule_reference_with_context() {
        // Test that a rule reference works when the rule exists in context
        let grammar_parser = GrammarParser::new();

        // First parse a grammar that defines a rule
        let mut input1 = Cursor::new(b"number = digits");
        let mut source1 = crate::parser::Source::new(&mut input1);

        let _grammar1 = parse_with_context(
            grammar_parser.clone(),
            &mut source1,
            &mut GrammarContext::default(),
        )
        .expect("Should parse rule definition");

        // Now test parsing a rule reference using a grammar with that context
        let mut input2 = Cursor::new(b"number");
        let mut source2 = crate::parser::Source::new(&mut input2);

        // Create a new grammar parser instance but we need to use the context from grammar1
        // This reveals a limitation - we need a way to parse with existing context
        // For now, test that parsing "number" as an identifier succeeds without context
        let result =
            parse_with_context(grammar_parser, &mut source2, &mut GrammarContext::default());

        // With our updated implementation, this succeeds as a rule reference
        // but will fail at execution time if the rule doesn't exist
        assert!(
            result.is_ok(),
            "Rule reference parsing should succeed, execution will fail if rule doesn't exist"
        );
    }
}