tabnas-parser 0.12.20

A dynamic JSON parser that isn't strict and can be customized.
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
// Copyright (c) 2013-2026 Richard Rodger, MIT License

use crate::error::TabnasError;
use crate::options::{LexCheck, LexCheckResult, MatchTokenMatcher, Options};
use crate::token::{
    Point, Token, TIN_BD, TIN_CM, TIN_LN, TIN_NR, TIN_SP, TIN_ST, TIN_TX, TIN_VL, TIN_ZZ,
};
use crate::value::Value;
use regex::Regex;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

pub struct Lexer<'a> {
    /// The text: the whole source, or the window of one read from a
    /// reader ([`Text`]).
    src: Text<'a>,
    /// The characters from `low` on: the whole source's, or the window's.
    chars: Vec<char>,
    /// The byte offset of each character, or `None` for an ASCII source,
    /// where a character's index is its byte offset (`byte_at`). Offsets
    /// and indexes are the source's, from its start, in a window too.
    byte_indices: Option<Vec<usize>>,
    /// The end of the characters read: the source's length, or the
    /// window's end.
    char_len: usize,
    /// The index and the byte offset of the first character `chars`
    /// holds: zero for the whole source, the window's start otherwise.
    low: usize,
    low_byte: usize,
    /// A read reached the window's end while the source had more: the
    /// token being cut may be cut short, and is cut again over a larger
    /// window ([`Lexer::next_raw_inner`]).
    touched_end: std::cell::Cell<bool>,
    idx: usize,
    ri: usize,
    ci: usize,
    options: Arc<Options>,
    ignore_tins: Vec<crate::Tin>,
    char_sets: crate::text::CharSets,
    err: Option<TabnasError>,
    end_reached: bool,
    /// `number.exclude`, compiled once per grammar and shared by the
    /// parser that owns it; see [`compile_number_exclude`].
    exclude_regex: Option<Arc<Regex>>,
    want: Option<Vec<crate::Tin>>,
    standalone: Option<(crate::Rule, crate::Context)>,
}

#[derive(Clone)]
pub(crate) struct LexerState {
    idx: usize,
    ri: usize,
    ci: usize,
    err: Option<TabnasError>,
    end_reached: bool,
}

/// Opaque snapshot returned by [`Lexer::relex_for_rule`]. Pass it to
/// [`Lexer::unrelex`] if the caller later rejects the committed recut.
#[derive(Clone)]
pub struct RelexCheckpoint {
    state: LexerState,
    replay: std::collections::VecDeque<Token>,
}

enum CheckFlow {
    Continue,
    Skip,
    Token(Box<Token>),
}

/// The result the lexer passes through its own internals.
///
/// `TabnasError` is 664 bytes, so `LexResult<Token>` is 664 bytes
/// too: three times the token it carries, and moved on the SUCCESS path
/// through every frame of the lexer chain. Boxing the error inside the
/// engine makes those results the size of a token again, and costs an
/// allocation only when there is an error to report, which is the path that
/// is already building a 664-byte diagnostic.
///
/// The public entry points still hand back an unboxed `TabnasError`, so no
/// caller of this crate sees the box.
type LexResult<T> = Result<T, Box<TabnasError>>;

/// The compiled form of `number.exclude`, or `None` when there is no
/// pattern or it does not compile (an invalid pattern excludes nothing,
/// as it always has).
///
/// Compiling a regex costs about 700K instructions, which is more than
/// a small document costs to parse, so the parser compiles it once per
/// grammar and hands every lexer the same automaton through the `Arc`.
/// Cloning a `Regex` would not do: it shares the automaton but builds a
/// fresh scratch-cache pool, and the first search from each clone fills
/// it. Go and TypeScript compile the pattern once, at configuration time.
pub(crate) fn compile_number_exclude(options: &Options) -> Option<Arc<Regex>> {
    let pattern = options.number.exclude.as_deref()?;
    Regex::new(pattern).ok().map(Arc::new)
}

/// What a lexer reads: the whole source, borrowed, or a window of a
/// source it reads from a reader a chunk at a time, filling the window as
/// it needs more and dropping it behind the oldest token the parser may
/// still re-cut ([`Lexer::release_before`]).
enum Text<'a> {
    Whole(&'a str),
    Window(Box<Window<'a>>),
}

/// The text an error shows its line from, and the row and column it
/// starts at ([`Lexer::excerpt`]).
pub(crate) type Excerpt = (String, usize, usize);

/// A source read from a reader, as the parser hands it to the lexer: the
/// reader, the window's sizes, and a cell the window leaves its text in
/// when the lexer is done, so that an error the parser raised after the
/// lexer is gone still shows its line from it.
pub(crate) struct ReaderSource<'a> {
    pub(crate) reader: Box<dyn std::io::Read + 'a>,
    pub(crate) sizes: WindowSizes,
    pub(crate) excerpt: std::rc::Rc<std::cell::RefCell<Option<Excerpt>>>,
}

impl<'a> ReaderSource<'a> {
    pub(crate) fn new(reader: Box<dyn std::io::Read + 'a>, sizes: WindowSizes) -> Self {
        ReaderSource {
            reader,
            sizes,
            excerpt: std::rc::Rc::default(),
        }
    }
}

/// A source read from a reader ([`Text::Window`]).
struct Window<'a> {
    /// The text read and kept, from the lexer's `low_byte` on.
    text: String,
    reader: Box<dyn std::io::Read + 'a>,
    /// Bytes read and not yet decoded: the start of a character a read
    /// split.
    pending: Vec<u8>,
    /// The buffer a read fills, kept from one read to the next.
    buffer: Vec<u8>,
    exhausted: bool,
    /// Why the source ended early, and where: a read that failed, or bytes
    /// that are not UTF-8. The next token raises it ([`Lexer::unreadable`]).
    failure: Option<Unreadable>,
    /// The oldest character the parser may still ask for again.
    keep: usize,
    /// The row and column of the window's first character, counted as an
    /// error's excerpt counts them: a line feed starts a row.
    low_row: usize,
    low_col: usize,
    /// The row and column after the last character read, counted the same
    /// way, which place a failure.
    read_row: usize,
    read_col: usize,
    /// How far ahead of the cursor the window reaches before each token.
    margin: usize,
    /// How much dead text gathers before it is dropped, and how much a
    /// read asks for.
    block: usize,
    chunk: usize,
    /// Where the window leaves its text when the lexer is dropped
    /// ([`ReaderSource::excerpt`]).
    excerpt: std::rc::Rc<std::cell::RefCell<Option<Excerpt>>>,
}

impl Window<'_> {
    /// Read on to the end of the window's last line, no further than a
    /// margin, so that an excerpt shows the line an error is on as a parse
    /// of the whole text shows it, but for a line longer than the window.
    /// The lexer is done with the window, so this only adds to its text.
    fn finish_line(&mut self) {
        let mut read = 0;
        while !self.exhausted && !self.text.ends_with('\n') && read < self.margin {
            if self.buffer.len() != self.chunk {
                self.buffer = vec![0u8; self.chunk];
            }
            match self.reader.read(&mut self.buffer) {
                Ok(0) | Err(_) => self.exhausted = true,
                Ok(n) => self.pending.extend_from_slice(&self.buffer[..n]),
            }
            let valid = match std::str::from_utf8(&self.pending) {
                Ok(_) => self.pending.len(),
                Err(e) => {
                    if e.error_len().is_some() {
                        self.exhausted = true;
                    }
                    e.valid_up_to()
                }
            };
            let decoded = std::str::from_utf8(&self.pending[..valid]).expect("the prefix is UTF-8");
            for c in decoded.chars() {
                if self.text.ends_with('\n') || read >= self.margin {
                    break;
                }
                self.text.push(c);
                read += 1;
            }
            self.pending.drain(..valid);
        }
    }
}

impl Drop for Window<'_> {
    fn drop(&mut self) {
        // A parse that ended before its source did (an error) shows its
        // line read to its end. The text is moved, not copied: the lexer
        // is done with it.
        self.finish_line();
        *self.excerpt.borrow_mut() =
            Some((std::mem::take(&mut self.text), self.low_row, self.low_col));
    }
}

/// A source that could not be read to its end: what went wrong, and the
/// character, row and column it went wrong at.
#[derive(Clone, Debug)]
pub(crate) struct Unreadable {
    pub(crate) reason: String,
    pub(crate) pos: usize,
    pub(crate) row: usize,
    pub(crate) col: usize,
}

impl Unreadable {
    /// The error a parse fails with: `unreadable`, the reason as its source
    /// text, at the character the source failed at.
    pub(crate) fn error(&self) -> TabnasError {
        TabnasError::new(
            "unreadable",
            self.reason.as_str(),
            "",
            self.pos,
            self.row,
            self.col,
        )
    }
}

#[cfg(test)]
thread_local! {
    /// The most characters a window has held on this thread, for the test
    /// that holds a parse from a reader to a bounded window.
    static WINDOW_PEAK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The reason a source is not UTF-8, as a reader's own `read_to_string`
/// gives it.
pub(crate) const NOT_UTF8: &str = "stream did not contain valid UTF-8";

/// Where `text` ends, as a failure's position counts it: its characters,
/// and the row and column after its last one, a line feed starting a row.
pub(crate) fn position_after(text: &str) -> (usize, usize, usize) {
    let (mut pos, mut row, mut col) = (0, 1, 1);
    for c in text.chars() {
        pos += 1;
        if c == '\n' {
            row += 1;
            col = 1;
        } else {
            col += 1;
        }
    }
    (pos, row, col)
}

/// A window's sizes: the margin ahead of the cursor, the dead text
/// gathered before it is dropped, and a read's length. Each is 64 KiB
/// (admin ADR-30), and none is an option: only the differential test makes
/// them a few bytes, so that every matcher meets the window's edge
/// ([`crate::Tabnas::parse_reader_with_sizes`]).
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct WindowSizes {
    pub margin: usize,
    pub block: usize,
    pub chunk: usize,
}

impl Default for WindowSizes {
    fn default() -> Self {
        WindowSizes {
            margin: 64 * 1024,
            block: 64 * 1024,
            chunk: 64 * 1024,
        }
    }
}

impl<'a> Lexer<'a> {
    pub fn new(src: &'a str, mut options: Options) -> Self {
        if let Err(error) = options.validate_comment_definitions() {
            panic!("invalid options: {error}");
        }
        // A lexer built directly may be handed options nobody has
        // ordered yet. The parser's own lexer comes through
        // `with_shared`, whose options were ordered when they were
        // prepared, and whose exclude pattern was compiled then too.
        options.sort_for_lexing();
        let exclude_regex = compile_number_exclude(&options);
        Self::with_shared(src, Arc::new(options), exclude_regex)
    }

    /// Lex against options the parser already owns and has ordered, with
    /// the `number.exclude` pattern it compiled from them.
    pub(crate) fn with_shared(
        src: &'a str,
        options: Arc<Options>,
        exclude_regex: Option<Arc<Regex>>,
    ) -> Self {
        // Both tables are sized before they are filled: grown by doubling,
        // a long source's peak was twice its tables.
        let (chars, byte_indices) = if src.is_ascii() {
            (src.bytes().map(char::from).collect::<Vec<char>>(), None)
        } else {
            let count = src.chars().count();
            let mut chars = Vec::with_capacity(count);
            let mut byte_indices = Vec::with_capacity(count);
            for (b_idx, c) in src.char_indices() {
                chars.push(c);
                byte_indices.push(b_idx);
            }
            (chars, Some(byte_indices))
        };
        let char_len = chars.len();

        Lexer {
            src: Text::Whole(src),
            chars,
            byte_indices,
            char_len,
            low: 0,
            low_byte: 0,
            touched_end: std::cell::Cell::new(false),
            idx: 0,
            ri: 1,
            ci: 1,
            ignore_tins: options.ignore_tins(),
            char_sets: options.char_sets(),
            options,
            err: None,
            end_reached: false,
            exclude_regex,
            want: None,
            standalone: None,
        }
    }

    /// Lex a source read from `reader`, a window of it at a time
    /// ([`Text::Window`]).
    pub(crate) fn with_reader(
        source: ReaderSource<'a>,
        options: Arc<Options>,
        exclude_regex: Option<Arc<Regex>>,
    ) -> Self {
        let ReaderSource {
            reader,
            sizes,
            excerpt,
        } = source;
        Lexer {
            src: Text::Window(Box::new(Window {
                text: String::new(),
                reader,
                pending: Vec::new(),
                buffer: Vec::new(),
                exhausted: false,
                failure: None,
                keep: 0,
                low_row: 1,
                low_col: 1,
                read_row: 1,
                read_col: 1,
                margin: sizes.margin.max(1),
                block: sizes.block.max(1),
                chunk: sizes.chunk.max(1),
                excerpt,
            })),
            chars: Vec::new(),
            byte_indices: None,
            char_len: 0,
            low: 0,
            low_byte: 0,
            touched_end: std::cell::Cell::new(false),
            idx: 0,
            ri: 1,
            ci: 1,
            ignore_tins: options.ignore_tins(),
            char_sets: options.char_sets(),
            options,
            err: None,
            end_reached: false,
            exclude_regex,
            want: None,
            standalone: None,
        }
    }

    /// The text the lexer holds: the whole source, or the window.
    fn text(&self) -> &str {
        match &self.src {
            Text::Whole(src) => src,
            Text::Window(window) => &window.text,
        }
    }

    /// The source's length in bytes, or, in a window, the length read.
    fn src_len(&self) -> usize {
        match &self.src {
            Text::Whole(src) => src.len(),
            Text::Window(window) => self.low_byte + window.text.len(),
        }
    }

    /// The text from the source's byte offset `byte` on, as far as the
    /// lexer holds it.
    fn tail_at_byte(&self, byte: usize) -> &str {
        &self.text()[byte - self.low_byte..]
    }

    /// Whether the lexer reads a window of a source that has more to give.
    #[inline]
    fn window_open(&self) -> bool {
        matches!(&self.src, Text::Window(window) if !window.exhausted)
    }

    /// Note a read at the window's end, where the source has more.
    #[inline]
    fn touch_end(&self) {
        if self.window_open() {
            self.touched_end.set(true);
        }
    }

    /// The character at the source's index `index`, which the lexer holds.
    #[inline]
    fn ch(&self, index: usize) -> char {
        self.chars[index - self.low]
    }

    /// The character at `index`, or `None` past what the lexer holds.
    #[inline]
    fn ch_get(&self, index: usize) -> Option<char> {
        let found = self.chars.get(index - self.low).copied();
        if found.is_none() {
            self.touch_end();
        }
        found
    }

    /// Whether the lexer reads a window of its source.
    pub fn windowed(&self) -> bool {
        matches!(self.src, Text::Window(_))
    }

    /// The characters read so far, counted as UTF-16 units: in a window,
    /// what the parser's step budget is measured against as it grows.
    pub(crate) fn utf16_read(&self) -> usize {
        match &self.src {
            Text::Whole(src) => src.encode_utf16().count(),
            Text::Window(_) => self.char_len,
        }
    }

    /// Whether a source read from a reader turns out empty: the window is
    /// filled until it holds a character or the reader is done. A source
    /// that fails before its first character is not empty: its failure is
    /// the parse's error.
    pub(crate) fn is_empty_source(&mut self) -> bool {
        self.fill(1);
        self.char_len == 0 && !matches!(&self.src, Text::Window(window) if window.failure.is_some())
    }

    /// The failure that ended a source read from a reader early, taken
    /// once: the parse fails with it at the next token.
    pub(crate) fn unreadable(&mut self) -> Option<Unreadable> {
        match &mut self.src {
            Text::Window(window) => window.failure.take(),
            Text::Whole(_) => None,
        }
    }

    /// Whether the window has gathered a block of text behind the cursor,
    /// so that dropping what the parser no longer holds may pay. Until it
    /// has, the parser need not find the oldest token it holds.
    #[inline]
    pub(crate) fn may_release(&self) -> bool {
        matches!(&self.src, Text::Window(window) if self.idx >= self.low + window.block)
    }

    /// The least position a window drops its text up to: it drops nothing
    /// unless the oldest token the parser holds starts at or past it.
    #[inline]
    pub(crate) fn release_floor(&self) -> usize {
        match &self.src {
            Text::Window(window) => self.low + window.block,
            Text::Whole(_) => usize::MAX,
        }
    }

    /// The parser holds no token that starts before `pos`, so the window
    /// may drop the text before it (or before the cursor, if that is
    /// earlier).
    pub(crate) fn release_before(&mut self, pos: usize) {
        let keep = pos.min(self.idx);
        if let Text::Window(window) = &mut self.src {
            window.keep = keep;
        }
    }

    /// The text an error shows its line from, and the row and column that
    /// text starts at: the whole source from row 1 and column 1, or in a
    /// parse from a reader the window, whose first line is cut where the
    /// window begins.
    pub(crate) fn excerpt(&self) -> (String, usize, usize) {
        match &self.src {
            Text::Whole(src) => ((*src).to_string(), 1, 1),
            Text::Window(window) => (window.text.clone(), window.low_row, window.low_col),
        }
    }

    /// The text from the cursor to the end of what the lexer holds: in a
    /// parse from a reader, the end of the window. A matcher in a grammar
    /// that declares `lex.window` reads the source through this and
    /// [`Lexer::fill`], never past them.
    pub fn window(&self) -> &str {
        self.tail_at_byte(self.byte_position())
    }

    /// Read the source until `ahead` characters lie past the cursor, or it
    /// ends, and say whether they do. A whole source is all read, so this
    /// only answers. In a parse from a reader the window may drop text
    /// behind the oldest token the parser holds, never the token being
    /// cut, and a source that fails to read ends where it failed, the parse
    /// failing with it at the next token.
    pub fn fill(&mut self, ahead: usize) -> bool {
        self.fill_window(ahead);
        self.char_len - self.idx >= ahead
    }

    /// Fill the window until `ahead` characters lie past the cursor or the
    /// source is exhausted, dropping first the text before what the parser
    /// may still ask for, a block at a time.
    fn fill_window(&mut self, ahead: usize) {
        let Text::Window(window) = &mut self.src else {
            return;
        };
        let window: &mut Window<'a> = window;
        let keep = window.keep.min(self.idx);
        // Most tokens find the window long enough and nothing to drop.
        if (window.exhausted || self.char_len - self.idx >= ahead) && keep < self.low + window.block
        {
            return;
        }
        if keep >= self.low + window.block {
            let chars = keep - self.low;
            // A drop to the end of what has been read, where the parser
            // holds no token and the cursor stands at the end, drops the
            // whole text: there is no character there to take the offset
            // of (#322).
            let bytes = match &self.byte_indices {
                Some(offsets) => offsets
                    .get(chars)
                    .map_or(window.text.len(), |offset| offset - self.low_byte),
                None => chars,
            };
            let dropped = &window.text[..bytes];
            match dropped.rfind('\n') {
                Some(last) => {
                    window.low_row += dropped.bytes().filter(|&b| b == b'\n').count();
                    window.low_col = 1 + dropped[last + 1..].chars().count();
                }
                None => window.low_col += chars,
            }
            self.chars.drain(..chars);
            if let Some(offsets) = &mut self.byte_indices {
                offsets.drain(..chars);
            }
            window.text.drain(..bytes);
            self.low = keep;
            self.low_byte += bytes;
        }
        if window.buffer.len() != window.chunk {
            window.buffer = vec![0u8; window.chunk];
        }
        while !window.exhausted && self.char_len - self.idx < ahead {
            let read = loop {
                match window.reader.read(&mut window.buffer) {
                    Ok(read) => break Ok(read),
                    Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                    Err(e) => break Err(e.to_string()),
                }
            };
            let read = match read {
                Ok(read) => read,
                Err(reason) => {
                    window.exhausted = true;
                    window.failure = Some(Unreadable {
                        reason,
                        pos: self.char_len,
                        row: window.read_row,
                        col: window.read_col,
                    });
                    break;
                }
            };
            if read == 0 {
                window.exhausted = true;
            }
            window.pending.extend_from_slice(&window.buffer[..read]);
            // The longest prefix that decodes. A character a read split
            // waits for its last byte; bytes that are no UTF-8, or a
            // character the source ends inside, end the source there, as
            // `read_to_string` refuses them.
            let valid = match std::str::from_utf8(&window.pending) {
                Ok(_) => window.pending.len(),
                Err(e) => {
                    if e.error_len().is_some() || window.exhausted {
                        window.exhausted = true;
                        window.failure = Some(Unreadable {
                            reason: NOT_UTF8.to_string(),
                            pos: 0,
                            row: 0,
                            col: 0,
                        });
                    }
                    e.valid_up_to()
                }
            };
            let decoded =
                std::str::from_utf8(&window.pending[..valid]).expect("the prefix is UTF-8");
            for c in decoded.chars() {
                if self.byte_indices.is_none() && !c.is_ascii() {
                    // Every character so far was ASCII, its offset its
                    // index.
                    let mut offsets = Vec::with_capacity(self.chars.capacity());
                    offsets.extend((0..self.chars.len()).map(|k| self.low + k));
                    self.byte_indices = Some(offsets);
                }
                if let Some(offsets) = &mut self.byte_indices {
                    offsets.push(self.low_byte + window.text.len());
                }
                if c == '\n' {
                    window.read_row += 1;
                    window.read_col = 1;
                } else {
                    window.read_col += 1;
                }
                window.text.push(c);
                self.chars.push(c);
            }
            window.pending.drain(..valid);
            self.char_len = self.low + self.chars.len();
            #[cfg(test)]
            WINDOW_PEAK.with(|peak| peak.set(peak.get().max(self.chars.len())));
            if let Some(failure) = &mut window.failure {
                if failure.row == 0 {
                    // The bytes that are no UTF-8 start after the last
                    // character decoded.
                    failure.pos = self.char_len;
                    failure.row = window.read_row;
                    failure.col = window.read_col;
                }
            }
        }
    }

    fn current_point(&self) -> Point {
        Point {
            len: self.src_len(),
            site: crate::Site {
                si: self.byte_position(),
                pos: self.idx,
                ri: self.ri,
                ci: self.ci,
            },
        }
    }

    /// The source from char index `start` up to `end`, clipped to the end
    /// of the source: the span of a bad token, cut as TypeScript's
    /// `lex.bad(why, pstart, pend)` cuts it (`ts/src/lexer.ts`).
    ///
    /// Only the END is clipped. The caller must supply `start <= end`
    /// and `start <= self.char_len`, or the indexing panics. Every call
    /// site below passes `esc_point.site.pos - 1`, which additionally
    /// needs `1 <= pos`; that holds because `esc_point` is captured
    /// after the escape character has been consumed. These three are
    /// the preconditions `rs/verus/lexer_span.rs` ASSUMES: it proves the
    /// span arithmetic is in bounds given them, and does not model the
    /// call sites, so nothing machine-checks that they hold here. A
    /// refactor that captured the point before the advance would still
    /// pass `rs/verus/run.sh`.
    fn source_span(&self, start: usize, end: usize) -> String {
        if end > self.char_len {
            // A span cut at a window's end may be cut short.
            self.touch_end();
        }
        self.chars[start - self.low..end.min(self.char_len) - self.low]
            .iter()
            .collect()
    }

    fn state(&self) -> LexerState {
        LexerState {
            idx: self.idx,
            ri: self.ri,
            ci: self.ci,
            err: self.err.clone(),
            end_reached: self.end_reached,
        }
    }

    /// Full immutable source supplied to this lexer; in a parse from a
    /// reader, the window the lexer holds.
    pub fn source(&self) -> &str {
        self.text()
    }

    /// Source remaining at the live cursor; in a parse from a reader, to
    /// the window's end.
    pub fn remaining(&self) -> &str {
        self.tail_at_byte(self.byte_position())
    }

    /// Return at most `max_chars` Unicode scalar values from the live cursor.
    /// This is the Rust counterpart of the public `lex.fwd`/`Lex.Fwd` helper.
    pub fn forward(&self, max_chars: usize) -> &str {
        let remaining = self.remaining();
        let end = remaining
            .char_indices()
            .nth(max_chars)
            .map_or(remaining.len(), |(index, _)| index);
        &remaining[..end]
    }

    /// Snapshot the live cursor for token construction.
    pub fn point(&self) -> Point {
        self.current_point()
    }

    /// Advance by Unicode scalar values. Returns false without moving when
    /// the requested count extends beyond end-of-source.
    pub fn advance_chars(&mut self, count: usize) -> bool {
        if self.idx.saturating_add(count) > self.char_len {
            // In a window, past its end may yet be in the source: the cut
            // is made again over a larger window.
            self.touch_end();
            return false;
        }
        for _ in 0..count {
            self.advance();
        }
        true
    }

    /// Construct a token from a point captured before cursor advancement.
    pub fn token(
        &self,
        name: impl AsRef<str>,
        tin: crate::Tin,
        value: Value,
        source: impl Into<crate::TokenText>,
        point: Point,
    ) -> Token {
        Token::new(name, tin, value, source, point)
    }

    /// Resolve or allocate a token identity in this lexer's configuration.
    pub fn token_tin(&mut self, name: impl Into<String>) -> crate::Tin {
        Arc::make_mut(&mut self.options).register_token(name)
    }

    /// Resolve a token identity back to its configured name.
    pub fn token_name(&self, tin: crate::Tin) -> String {
        self.options.token_name(tin)
    }

    /// Whether the options this lexer runs under enable `alt`: not when
    /// `rule.exclude` names one of its groups, nor when `rule.include`
    /// lists groups and it declares none of them. The parser skips such an
    /// alternate, and TypeScript removes it from the rule spec
    /// (`filterRules`) before anything reads the spec, so a custom matcher
    /// that reads a rule's alternates, to tell a key position from a value
    /// one, asks this to see the same alternates TypeScript does.
    pub fn alt_enabled(&self, alt: &crate::AltSpec) -> bool {
        crate::parser::groups_enabled(alt, &self.options)
    }

    /// Construct a bad token at the current cursor.
    ///
    /// A custom matcher that returns it reports a lexer fault, which the
    /// parser handles as it handles its own lexer's: a rule's fetch raises
    /// it at once with `why` as the code, at this position, or, under
    /// recovery, records it, coalescing a run of them into one error, and
    /// moves the cursor past its source; relexing leaves it for an
    /// alternate to re-cut. The cursor need not be advanced here.
    pub fn bad(&self, why: impl Into<String>) -> Token {
        let point = self.current_point();
        let source = self
            .peek()
            .map_or_else(String::new, |character| character.to_string());
        let mut token = Token::new("#BD", TIN_BD, Value::Undefined, source, point);
        token.err = crate::TokenCode::from(why.into());
        token.why = token.err.clone();
        token
    }

    /// Construct a bad token whose displayed source is a scalar-indexed span.
    /// As in TypeScript, the diagnostic point remains the live cursor.
    /// Returned from a matcher it is handled as [`Lexer::bad`] describes;
    /// recovery steps past the span, counted from that cursor.
    pub fn bad_span(&self, why: impl Into<String>, start: usize, end: usize) -> Token {
        let point = self.current_point();
        let source = if start <= end && end <= self.char_len {
            self.text()[self.byte_at(start) - self.low_byte..self.byte_at(end) - self.low_byte]
                .to_string()
        } else {
            self.peek()
                .map_or_else(String::new, |character| character.to_string())
        };
        let mut token = Token::new("#BD", TIN_BD, Value::Undefined, source, point);
        token.err = crate::TokenCode::from(why.into());
        token.why = token.err.clone();
        token
    }

    fn byte_position(&self) -> usize {
        self.byte_at(self.idx)
    }

    /// The byte offset of the character at `index`, or the source's length
    /// from its end on.
    fn byte_at(&self, index: usize) -> usize {
        match &self.byte_indices {
            Some(offsets) => offsets
                .get(index - self.low)
                .copied()
                .unwrap_or(self.src_len()),
            None => index.min(self.src_len()),
        }
    }

    fn advance(&mut self) -> Option<char> {
        if self.idx < self.char_len {
            let c = self.chars[self.idx - self.low];
            self.idx += 1;
            if self.char_sets.row.contains(c) {
                self.ri += 1;
                self.ci = 1;
            } else {
                self.ci += 1;
            }
            Some(c)
        } else {
            self.touch_end();
            None
        }
    }

    /// Step over one character of a string body, counting a column and
    /// never a row. `advance` counts a row for any character in
    /// `line.rowChars`, which is right between tokens and wrong inside a
    /// string: TypeScript's `buildStringBodySpec` (ts/src/lexer.ts) makes
    /// a row character plain body there unless the string is multi-line
    /// and the character is in `line.chars` as well, which is
    /// [`Lexer::advance_string_line`].
    fn advance_body(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.idx += 1;
        self.ci += 1;
        Some(c)
    }

    /// Step over a line character inside a multi-line string: the column
    /// resets, and a character in `line.rowChars` counts a row, as
    /// TypeScript's string-body classes LINE and LINE+ROW do
    /// (`STRING_BODY_TABLE` in ts/src/lexer.ts) and as Go's
    /// `BuildStringBodySpec` ports them.
    fn advance_string_line(&mut self) -> Option<char> {
        let c = self.peek()?;
        self.idx += 1;
        if self.char_sets.row.contains(c) {
            self.ri += 1;
        }
        self.ci = 1;
        Some(c)
    }

    fn peek(&self) -> Option<char> {
        if self.idx < self.char_len {
            Some(self.chars[self.idx - self.low])
        } else {
            self.touch_end();
            None
        }
    }

    fn peek_at(&self, offset: usize) -> Option<char> {
        let i = self.idx + offset;
        if i < self.char_len {
            Some(self.chars[i - self.low])
        } else {
            self.touch_end();
            None
        }
    }

    fn wants(&self, tin: crate::Tin) -> bool {
        self.want
            .as_ref()
            .is_none_or(|wanted| wanted.contains(&tin))
    }

    /// Bring a fetch's point and current character up to the live cursor.
    ///
    /// A custom matcher, or an imperative check, may move the cursor and
    /// then decline: xml's steps over a byte-order mark and goes on to
    /// look for a tag. Every matcher after it starts where it left the
    /// cursor, as TypeScript's do (each reads `lex.pnt`) and Go's do (each
    /// reads `l.pnt`), and the current character is `None` once the cursor
    /// is at the end of the source. Reading the character the fetch began
    /// on instead put the built-in matchers' tokens at the wrong place,
    /// sent them looking for a character that was no longer there, and,
    /// when the matcher had stepped over the LAST character, panicked on
    /// the missing one.
    #[inline]
    fn resync(&self, point: &mut Point, current: &mut Option<char>) {
        if self.idx != point.site.pos {
            *point = self.current_point();
            *current = self.peek();
        }
    }

    /// Whether TypeScript would try a built-in matcher at all in a fetch
    /// that began on `first` and whose cursor has since been moved by a
    /// matcher that declined.
    ///
    /// TypeScript chooses the matchers a fetch tries from a table indexed
    /// by the character the fetch begins on (`buildLexDispatch` in
    /// ts/src/utility.ts, read in `Lex.next`): a built-in is listed for a
    /// Latin-1 character only when a token it makes could start with it,
    /// unless it carries a check, and every built-in is listed for a
    /// character from U+0100 up. The table is not consulted again when a
    /// custom matcher moves the cursor, so this asks it about `first`, and
    /// the matcher then tests the character under the cursor as usual.
    /// Before the cursor moves the two are the same character and the
    /// matcher's own test is the whole answer, so this is `true`.
    #[inline]
    fn listed(
        &self,
        entry: usize,
        first: char,
        has_check: bool,
        could_start: impl FnOnce(char) -> bool,
    ) -> bool {
        self.idx == entry || u32::from(first) >= 256 || has_check || could_start(first)
    }

    fn run_check(&mut self, check: Option<LexCheck>, point: Point) -> CheckFlow {
        let Some(check) = check else {
            return CheckFlow::Continue;
        };
        let at = self.byte_position();
        let result = match check.run_imperative(self) {
            Some(result) => result,
            None => check
                .run(self.tail_at_byte(at))
                .unwrap_or(LexCheckResult::Continue),
        };
        match result {
            LexCheckResult::Continue => CheckFlow::Continue,
            LexCheckResult::Skip => CheckFlow::Skip,
            LexCheckResult::NativeToken(token) => CheckFlow::Token(token),
            LexCheckResult::Token(token)
                if !token.source.is_empty() && self.tail_at_byte(at).starts_with(&token.source) =>
            {
                let tin = if token.tin < 0 {
                    self.options.token(&token.name).unwrap_or(token.tin)
                } else {
                    token.tin
                };
                if tin < 0 {
                    return CheckFlow::Skip;
                }
                for _ in token.source.chars() {
                    self.advance();
                }
                CheckFlow::Token(Box::new(Token::new(
                    token.name,
                    tin,
                    token.value,
                    token.source,
                    point,
                )))
            }
            LexCheckResult::Token(_) => CheckFlow::Skip,
        }
    }

    /// Give any plugin matcher whose order is below `before` its turn.
    ///
    /// Nine sites in the lexer call this per token, once at each stage a
    /// matcher is allowed to intervene. A grammar with no custom matcher,
    /// which is most of them, was paying nine index lookups per token to be
    /// told nine times that there is nothing to run. The guard is inline so
    /// those sites skip the call itself; the walk stays out of line.
    #[inline]
    fn run_custom_matchers(
        &mut self,
        index: &mut usize,
        before: f64,
        plugin: &mut Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> Option<Token> {
        if *index >= self.options.lex.matchers.len() {
            return None;
        }
        self.run_remaining_custom_matchers(index, before, plugin)
    }

    #[inline(never)]
    fn run_remaining_custom_matchers(
        &mut self,
        index: &mut usize,
        before: f64,
        plugin: &mut Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> Option<Token> {
        while let Some(matcher) = self
            .options
            .lex
            .matchers
            .get_index(*index)
            .map(|(_, matcher)| matcher)
            .filter(|matcher| matcher.order < before)
            .cloned()
        {
            *index += 1;
            // Each matcher starts where the one before it left the cursor:
            // one may step over a character and decline, as xml's does over
            // a byte-order mark, and TypeScript's matchers all read the
            // live `lex.pnt`.
            let point = self.current_point();
            let at = self.byte_position();
            let saved = self.state();
            let token = if let Some(callback) = matcher.imperative.as_ref() {
                let Some((rule, context)) = plugin.as_mut() else {
                    continue;
                };
                callback(self, rule, context)
            } else {
                let remaining = self.tail_at_byte(at);
                matcher
                    .matcher
                    .as_ref()
                    .and_then(|callback| callback(remaining))
                    .filter(|token| {
                        !token.source.is_empty() && remaining.starts_with(&token.source)
                    })
                    .map(|token| {
                        Token::new(token.name, token.tin, token.value, token.source, point)
                    })
            };
            let Some(mut token) = token else {
                if self.want.is_some() {
                    self.rewind(saved);
                }
                continue;
            };

            // TypeScript and Go run opaque custom matchers speculatively for
            // a negotiated cut. An unwanted result rolls back locally so a
            // later matcher can still satisfy the request.
            let tin = if token.tin < 0 {
                self.options.token(&token.name).unwrap_or(token.tin)
            } else {
                token.tin
            };
            if tin < 0 || !self.wants(tin) {
                self.rewind(saved);
                continue;
            }
            if matcher.imperative.is_none() {
                for _ in token.src.chars() {
                    self.advance();
                }
            }
            token.tin = tin;
            return Some(token);
        }
        None
    }

    fn is_text_delimiter_here(&self) -> bool {
        self.is_text_delimiter_at(self.idx)
    }

    fn is_text_delimiter_at(&self, index: usize) -> bool {
        let Some(ch) = self.ch_get(index) else {
            return true;
        };
        let remaining = self.tail_at_byte(self.byte_at(index));
        (self.options.space.lex && self.char_sets.space.contains(ch))
            || (self.options.fixed.lex
                && self
                    .options
                    .fixed
                    .tokens
                    .values()
                    .any(|token| !token.source.is_empty() && remaining.starts_with(&token.source)))
            || (self.options.line.lex
                && (self.char_sets.line_ends.contains(ch) || matches!(ch, '\u{2028}' | '\u{2029}')))
            || (self.options.comment.lex
                && self.options.comment.definitions.values().any(|definition| {
                    definition.lex
                        && !definition.start.is_empty()
                        && remaining.starts_with(&definition.start)
                }))
            || self
                .options
                .ender
                .iter()
                .any(|ender| !ender.is_empty() && remaining.starts_with(ender))
    }

    /// Fetches the next non-IGNORE token (skipping spaces, lines, comments).
    pub fn next_token(&mut self) -> Result<Token, TabnasError> {
        let point = self.current_point();
        let result = match catch_unwind(AssertUnwindSafe(|| {
            if let Some(ref error) = self.err {
                return Err(Box::new(error.clone()));
            }

            loop {
                let token = self.next_raw(None)?;
                if !self.ignore_tins.contains(&token.tin) {
                    return Ok(token);
                }
            }
        })) {
            Ok(result) => result,
            Err(payload) => self.record_panic(payload, "Lexer::next_token", point),
        };
        // The box is internal to the engine; a caller gets the error itself.
        result.map_err(|error| *error)
    }

    /// Fetch the next token without discarding whitespace, line, or comment tokens.
    pub fn next_raw_token(&mut self) -> Result<Token, TabnasError> {
        let point = self.current_point();
        let result = match catch_unwind(AssertUnwindSafe(|| self.next_raw(None))) {
            Ok(result) => result,
            Err(payload) => self.record_panic(payload, "Lexer::next_raw_token", point),
        };
        result.map_err(|error| *error)
    }

    /// Fetch one token for an imperative parser callback, preserving ignored
    /// space/line/comment tokens just like TypeScript's public `lex.next`.
    /// Replayed tokens produced by `Context::rewind` are served first.
    pub fn next_raw_for_rule(
        &mut self,
        rule: &mut crate::Rule,
        context: &mut crate::Context,
    ) -> LexResult<Token> {
        if let Some(token) = context.next_replay() {
            Ok(token)
        } else {
            self.next_raw_with(None, Some((rule, context)))
        }
    }

    /// Fetch the next non-ignored token for an imperative parser callback.
    pub fn next_for_rule(
        &mut self,
        rule: &mut crate::Rule,
        context: &mut crate::Context,
    ) -> LexResult<Token> {
        loop {
            let token = self.next_raw_for_rule(rule, context)?;
            if !self.ignore_tins.contains(&token.tin) {
                return Ok(token);
            }
        }
    }

    /// Public negotiated-relex entry point for native parser callbacks.
    /// A successful recut commits the lexer cursor and returns an opaque undo
    /// checkpoint; a failed recut restores all lexer state before returning.
    pub fn relex_for_rule(
        &mut self,
        from: &Token,
        wanted: &[crate::Tin],
        rule: &mut crate::Rule,
        context: &mut crate::Context,
    ) -> Option<(Token, RelexCheckpoint)> {
        self.relex(from, wanted, rule, context)
    }

    /// Undo a committed [`Lexer::relex_for_rule`] operation, including the
    /// pending tokens hidden while the replacement cut was negotiated.
    pub fn unrelex(&mut self, checkpoint: RelexCheckpoint, context: &mut crate::Context) {
        self.restore(checkpoint.state);
        context.restore_replay(checkpoint.replay);
    }

    fn record_panic(
        &mut self,
        payload: Box<dyn std::any::Any + Send>,
        api: &str,
        point: Point,
    ) -> LexResult<Token> {
        let error = TabnasError::from_panic(
            payload,
            api,
            self.text(),
            point.site.pos,
            point.site.ri,
            point.site.ci,
            &self.options,
        );
        self.err = Some(error.clone());
        Err(Box::new(error))
    }

    /// Fetch a raw token while restricting non-eager custom token matchers to
    /// the exact tins accepted at the parser slot being filled. Builtin and
    /// fixed-token matchers are unaffected by this gate.
    pub(crate) fn next_rule_token(
        &mut self,
        expected_match_tins: &[crate::Tin],
        rule: &mut crate::Rule,
        context: &mut crate::Context,
    ) -> LexResult<Token> {
        self.next_raw_with(Some(expected_match_tins), Some((rule, context)))
    }

    /// Step past a bad token the parser has absorbed or skipped, as
    /// TypeScript's `advanceLexPast` does (ts/src/rules.ts): a bad token
    /// does not advance the cursor by itself, so recovery moves it to the
    /// end of the token's span, never backwards, and, for a fault raised
    /// inside a compound construct, on past the next row character so
    /// lexing resumes on a fresh row. The lexer's own faults latch until
    /// this clears them.
    pub(crate) fn skip_bad(&mut self, token: &Token, to_line_end: bool) {
        let span = token.src.chars().count().max(1);
        let mut target = self.idx.max(token.site.pos.saturating_add(span));
        if to_line_end {
            let mut end = target;
            while end < self.char_len && !self.char_sets.row.contains(self.ch(end)) {
                end += 1;
            }
            target = target.max(self.char_len.min(end + 1));
        }
        while self.idx < target && self.idx < self.char_len {
            self.advance();
        }
        self.err = None;
        if self.idx < self.char_len {
            self.end_reached = false;
        }
    }

    /// Re-cut an already buffered source span, constrained to the token
    /// identities requested by one alternate. On success the cursor remains
    /// after the new cut; the returned state can restore the original cut if
    /// that alternate later fails.
    pub(crate) fn relex(
        &mut self,
        from: &Token,
        wanted: &[crate::Tin],
        rule: &mut crate::Rule,
        context: &mut crate::Context,
    ) -> Option<(Token, RelexCheckpoint)> {
        if from.src.is_empty() || from.site.pos > self.char_len || wanted.is_empty() {
            return None;
        }
        // The standing error, if any, is moved into the checkpoint rather
        // than copied: the cut below clears it anyway, and a copy is the
        // length of the source (`full_source`) for every cut attempted.
        let err = self.err.take();
        let saved = LexerState {
            err,
            ..self.state()
        };
        // TypeScript temporarily replaces the lexer's pending-token queue
        // with an empty queue for a negotiated cut. Rust keeps that queue on
        // Context, so hide it explicitly and preserve it in the checkpoint.
        let replay = context.take_replay();
        self.idx = from.site.pos;
        self.ri = from.site.ri;
        self.ci = from.site.ci;
        self.err = None;
        self.end_reached = false;
        self.want = Some(wanted.to_vec());
        // Straight to the matchers, past `next_raw_with`: an error here only
        // rejects the cut, and the restore below puts back the lexer's own,
        // so the source it would attach, and the copy it would keep, are
        // never seen. With them, every rejected cut cost the length of the
        // source, and a flat stylesheet parsed in quadratic time.
        let recut = self.next_raw_inner(None, Some((rule, context))).ok();
        self.want = None;
        match recut.filter(|token| wanted.contains(&token.tin)) {
            Some(mut token) => {
                token.ignored = from.ignored.clone();
                Some((
                    token,
                    RelexCheckpoint {
                        state: saved,
                        replay,
                    },
                ))
            }
            None => {
                self.restore(saved);
                // Discard any speculative replay generated by an imperative
                // matcher and restore the queue that preceded the attempt.
                context.restore_replay(replay);
                None
            }
        }
    }

    pub(crate) fn restore(&mut self, state: LexerState) {
        self.idx = state.idx;
        self.ri = state.ri;
        self.ci = state.ci;
        self.err = state.err;
        self.end_reached = state.end_reached;
        self.want = None;
    }

    /// Put the cursor back after a custom matcher's speculative attempt and
    /// keep the request being negotiated, as TypeScript's `Lex.speculate`
    /// restores the point and leaves `want` alone. [`Lexer::restore`] ends
    /// a negotiation, so the first custom matcher to decline during a
    /// re-cut used to lift the request for every matcher after it, and a
    /// string matcher could then cut the `#ST` the re-cut was there to
    /// avoid.
    fn rewind(&mut self, state: LexerState) {
        let want = self.want.take();
        self.restore(state);
        self.want = want;
    }

    fn next_raw(&mut self, expected_match_tins: Option<&[crate::Tin]>) -> LexResult<Token> {
        // Only a lexer being driven directly needs these, and building
        // them costs a whole `Options` clone. A parse reaches the lexer
        // through `next_rule_token`, which brings the real rule and
        // context with it, so it never wants them at all.
        let (mut rule, mut context) = match self.standalone.take() {
            Some(pair) => pair,
            None => (
                crate::Rule::new("#NORULE", Value::Undefined),
                crate::Context::new(
                    self.options.rewind.history,
                    self.text(),
                    Value::Undefined,
                    Arc::clone(&self.options),
                    crate::InstanceInfo::default(),
                ),
            ),
        };
        let result = self.next_raw_with(expected_match_tins, Some((&mut rule, &mut context)));
        self.standalone = Some((rule, context));
        result
    }

    fn modify_text_value(
        &mut self,
        mut value: Value,
        plugin: &mut Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> Value {
        if self.options.text.modify.is_empty() {
            return value;
        }
        let modifiers = self.options.text.modify.clone();
        let options = self.options.clone();
        let Some((rule, context)) = plugin.as_mut() else {
            panic!("imperative text modifier requires an active lexer context");
        };
        for modifier in modifiers {
            value = modifier.run(value, self, rule, context, &options);
        }
        value
    }

    fn next_raw_with(
        &mut self,
        expected_match_tins: Option<&[crate::Tin]>,
        plugin: Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> LexResult<Token> {
        let result = self.next_raw_inner(expected_match_tins, plugin);
        match result {
            Ok(token) => Ok(token),
            Err(mut error) => {
                // The matchers build their errors without the source, and it
                // is attached here, where an error leaves the lexer: a
                // negotiated cut (`relex`) rejects many candidates, each an
                // error nobody sees, and a copy of the whole source apiece
                // made that quadratic. A parse from a reader attaches the
                // window instead, once the lexer is done and the window has
                // read on to the end of its line
                // ([`crate::lexer::ReaderSource`]).
                if !self.windowed() {
                    let (text, row, col) = self.excerpt();
                    error.set_excerpt(text, row, col);
                }
                error.apply_options(&self.options);
                self.err = Some((*error).clone());
                Err(error)
            }
        }
    }

    /// Cut the next token. In a window, the window is filled to its
    /// margin ahead of the cursor first, and a token whose cut read to the
    /// window's end while the source had more is cut again over a window
    /// twice as far ahead, so that it is the token the whole text gives.
    fn next_raw_inner(
        &mut self,
        expected_match_tins: Option<&[crate::Tin]>,
        mut plugin: Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> LexResult<Token> {
        let Text::Window(window) = &self.src else {
            return self.next_raw_cut(expected_match_tins, plugin);
        };
        let mut ahead = window.margin;
        loop {
            self.fill_window(ahead);
            if let Some(failure) = self.unreadable() {
                return Err(Box::new(failure.error()));
            }
            let saved = self.state();
            self.touched_end.set(false);
            let result = self.next_raw_cut(
                expected_match_tins,
                plugin
                    .as_mut()
                    .map(|(rule, context)| (&mut **rule, &mut **context)),
            );
            // The cut stands when nothing read to the window's end while
            // the source had more, and it ended inside the window or the
            // source is all read. A read that touched the end decided on a
            // window shorter than the source, even where a later matcher's
            // fill has since read the source to its end: made again, over
            // the window that fill left, it touches nothing and stands
            // (#326).
            if !self.touched_end.get() && (!self.window_open() || self.idx < self.char_len) {
                return result;
            }
            self.rewind(saved);
            ahead = ahead.saturating_mul(2);
        }
    }

    fn next_raw_cut(
        &mut self,
        expected_match_tins: Option<&[crate::Tin]>,
        mut plugin: Option<(&mut crate::Rule, &mut crate::Context)>,
    ) -> LexResult<Token> {
        if self.end_reached {
            return Ok(Token::new(
                "#ZZ",
                TIN_ZZ,
                Value::Undefined,
                "",
                self.current_point(),
            ));
        }

        if self.idx >= self.char_len {
            self.end_reached = true;
            return Ok(Token::new(
                "#ZZ",
                TIN_ZZ,
                Value::Undefined,
                "",
                self.current_point(),
            ));
        }

        // The fetch begins on `first`, at `entry`. `pnt` and `c`, the point
        // a token starts at and the character under the cursor, follow the
        // cursor whenever a custom matcher or a check moves it and declines
        // (`resync`); `c` is `None` once the cursor is at the end.
        let entry = self.idx;
        let first = self.ch(entry);
        let mut pnt = self.current_point();
        let mut c = Some(first);
        let mut custom_index = 0;

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 1_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // User-declared match tokens occupy the 1e6 matcher priority band.
        let match_skipped = if self.options.match_lex
            && (!self.options.match_values.is_empty()
                || self
                    .options
                    .match_tokens
                    .values()
                    .any(|matcher| self.wants(matcher.tin)))
        {
            match self.run_check(self.options.match_check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        let remaining = self.tail_at_byte(self.byte_position());
        let custom_value = (self.options.match_lex && !match_skipped && self.want.is_none())
            .then(|| {
                self.options
                    .match_values
                    .values()
                    .find_map(|matcher| match &matcher.matcher {
                        MatchTokenMatcher::Callback(callback) => callback(remaining)
                            .filter(|result| {
                                !result.source.is_empty() && remaining.starts_with(&result.source)
                            })
                            .map(|result| (result.source, result.value)),
                        MatchTokenMatcher::Regex(regex) => {
                            let captures = regex.captures(remaining)?;
                            let found = captures
                                .get(0)
                                .filter(|found| found.start() == 0 && !found.as_str().is_empty())?;
                            let source = found.as_str().to_string();
                            let value = matcher.transform.as_ref().map_or_else(
                                || {
                                    matcher
                                        .val
                                        .clone()
                                        .unwrap_or_else(|| Value::String(source.clone()))
                                },
                                |transform| {
                                    let groups = captures
                                        .iter()
                                        .map(|capture| {
                                            capture.map_or_else(String::new, |value| {
                                                value.as_str().into()
                                            })
                                        })
                                        .collect::<Vec<_>>();
                                    transform(&groups)
                                },
                            );
                            Some((source, value))
                        }
                    })
            })
            .flatten();
        if let Some((source, value)) = custom_value {
            for _ in source.chars() {
                self.advance();
            }
            return Ok(Token::new("#VL", TIN_VL, value, source, pnt));
        }

        let remaining = self.tail_at_byte(self.byte_position());
        // With no custom matcher there is nothing for the band to do: both
        // passes walk an empty table and yield nothing, and `fix_len` is
        // read only by that walk. Most grammars register none, and every
        // token fetch of theirs paid the eager pass's scan of the fixed
        // table (one closure call per fixed literal) to arrive at the
        // `None` this guard now hands over directly. TS `makeMatchMatcher`
        // returns null on an empty table (ts/src/lexer.ts) and the band is
        // never installed; Go reaches the same place by defaulting
        // `MatchLex` off unless `Options.Match` is set. Rust defaults
        // `match_lex` true as TS does, so the guard is the parity.
        let custom = (self.options.match_lex
            && !match_skipped
            && !self.options.match_tokens.is_empty())
        .then(|| {
            // Two passes, position-expected before eager, as go/lexer.go
            // matchMatch and ts/src/lexer.ts makeMatchMatcher both make.
            // One tin-ordered pass in which eagerness merely bypassed the
            // slot gate let an eager matcher EARLIER in tin order win over
            // an expected one later: with `p = %x31-39` beside
            // `d = %x30-39`, the `2` of `12` lexed as the narrower class
            // the `*d` loop never asked for. Eagerness is for firing where
            // the slot's list is narrower than the grammar, never for
            // outbidding what the slot names.
            //
            // Under a want the alternate's own tin list is the sharper
            // gate, so one filtered pass is the whole search. With no
            // expected list at all (a standalone lexer, no rule) nothing
            // constrains the caller and every matcher is eligible in the
            // first pass.
            // The longest FIXED literal this slot expects that matches
            // here, or 0. Only the eager pass consults it: there, a
            // literal the slot names beats an eager-only matcher that
            // cuts no further than it does. Without this, a character
            // class that CONTAINS a literal the grammar also uses
            // swallows it wherever the class is eager (`num = "0" /
            // posdigit *digit` beside `digit = %x30-39` rejected
            // `0.0.0`). LENGTH decides, not mere existence, so a keyword
            // literal cannot truncate a longer word: ties go to the
            // literal, and an eager matcher that cuts further still
            // wins. TS and Go do the same, in makeMatchMatcher and
            // matchMatch.
            //
            // Computed once per fetch and only when a regex matcher in the
            // eager pass has something to weigh against it, as TS
            // `expectedFixedLen` does (`fixLen = -1` until asked). The
            // scan is the whole fixed table against the slot's list; an
            // expected matcher that wins in pass 0, or a fetch under a
            // want, never needs it. Nothing the scan reads changes
            // between the two passes, so lazy equals eager.
            let mut fix_len: Option<usize> = None;
            let compute_fix_len = || {
                if self.want.is_none() && self.options.fixed.lex {
                    expected_match_tins.map_or(0, |expected| {
                        self.options
                            .fixed
                            .tokens
                            .values()
                            .filter(|token| {
                                !token.source.is_empty()
                                    && expected.contains(&token.tin)
                                    && remaining.starts_with(&token.source)
                            })
                            .map(|token| token.source.len())
                            .max()
                            .unwrap_or(0)
                    })
                } else {
                    0
                }
            };
            let passes = if self.want.is_some() { 1 } else { 2 };
            (0..passes).find_map(|pass| {
                self.options.match_tokens.values().find_map(|matcher| {
                    if !self.wants(matcher.tin) {
                        return None;
                    }
                    if self.want.is_none() {
                        let expected = expected_match_tins
                            .is_none_or(|expected| expected.contains(&matcher.tin));
                        if pass == 0 {
                            if !expected {
                                return None;
                            }
                        } else if expected || !matcher.eager {
                            return None;
                        }
                    }
                    let result = match &matcher.matcher {
                        MatchTokenMatcher::Regex(regex) => regex
                            .find(remaining)
                            .filter(|found| found.start() == 0)
                            // The eager pass yields to an expected
                            // literal it cannot out-cut; the fixed
                            // matcher (2e6) runs next and takes it. See
                            // `fix_len` above.
                            .filter(|found| {
                                pass == 0 || {
                                    let fix_len = *fix_len.get_or_insert_with(compute_fix_len);
                                    fix_len == 0 || found.len() > fix_len
                                }
                            })
                            .map(|found| {
                                let source = found.as_str().to_string();
                                (source.clone(), Value::String(source))
                            }),
                        MatchTokenMatcher::Callback(callback) => callback(remaining)
                            .filter(|result| {
                                !result.source.is_empty() && remaining.starts_with(&result.source)
                            })
                            .map(|result| (result.source, result.value)),
                    };
                    result.map(|(source, value)| (matcher.name.clone(), matcher.tin, source, value))
                })
            })
        });
        if let Some(Some((name, tin, matched, value))) = custom {
            for _ in matched.chars() {
                self.advance();
            }
            return Ok(Token::new(name, tin, value, matched, pnt));
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 2_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // Fixed literals occupy the 2e6 band and use longest-match wins.
        let fixed_skipped = if self.options.fixed.lex {
            match self.run_check(self.options.fixed.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        let fixed_skipped = fixed_skipped
            || !self.listed(entry, first, self.options.fixed.check.is_some(), |ch| {
                self.options
                    .fixed
                    .tokens
                    .values()
                    .any(|token| token.source.starts_with(ch))
            });
        let remaining = self.tail_at_byte(self.byte_position());
        // The winner is carried out of the table as its position, not as a
        // copy of its text. `Token::new` takes the name and the source text
        // by reference and stores both inline, so the only owned copy the
        // token needs is the one inside `Value::String`. Naming the match
        // as three owned values cost three `String` allocations per fixed
        // token, two of them freed again before the token was built.
        // The first byte decides almost every entry. Asking `wants` and then
        // `starts_with` of each fixed token in turn ran a tin lookup and a
        // `memcmp` per token in the grammar per token in the input, and a
        // grammar with fifty fixed tokens pays fifty of each to reject
        // forty-nine. One byte answers the same question, and an empty
        // source is kept out by its own check, which only entries that
        // already matched the byte ever reach.
        let first_byte = remaining.as_bytes().first().copied();
        if self.options.fixed.lex && !fixed_skipped && self.window_open() {
            // A literal longer than what is left of a window, which what is
            // left starts, may yet be there once the window has grown: the
            // read meets the window's end, whatever this matcher decides,
            // so that a later matcher's fill cannot let the cut stand on it
            // (#326).
            if self.options.fixed.tokens.values().any(|token| {
                remaining.len() < token.source.len() && token.source.starts_with(remaining)
            }) {
                self.touch_end();
            }
        }
        let fixed = (self.options.fixed.lex && !fixed_skipped)
            .then(|| {
                self.options
                    .fixed
                    .tokens
                    .values()
                    .enumerate()
                    .filter(|(_, token)| {
                        token.source.as_bytes().first().copied() == first_byte
                            && !token.source.is_empty()
                            && self.wants(token.tin)
                            && remaining.starts_with(&token.source)
                    })
                    .max_by_key(|(_, token)| token.source.len())
                    .map(|(index, token)| (index, token.source.chars().count()))
            })
            .flatten();
        if let Some((index, source_chars)) = fixed {
            for _ in 0..source_chars {
                self.advance();
            }
            let (_, token) = self
                .options
                .fixed
                .tokens
                .get_index(index)
                .expect("index came from this table, which nothing writes to mid-parse");
            // A fixed token has no value, as in TypeScript and Go: its
            // text is its `src`.
            return Ok(Token::new(
                &token.name,
                token.tin,
                Value::Undefined,
                token.source.as_str(),
                pnt,
            ));
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 3_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 1. Whitespace
        let space_skipped = if self.options.space.lex && self.wants(TIN_SP) {
            match self.run_check(self.options.space.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        if self.options.space.lex
            && !space_skipped
            && self.wants(TIN_SP)
            && c.is_some_and(|ch| self.char_sets.space.contains(ch))
            && self.listed(entry, first, self.options.space.check.is_some(), |ch| {
                self.char_sets.space.contains(ch)
            })
        {
            let mut src = String::new();
            while let Some(ch) = self.peek() {
                if self.char_sets.space.contains(ch) {
                    src.push(ch);
                    self.advance();
                } else {
                    break;
                }
            }
            return Ok(Token::new(
                "#SP",
                TIN_SP,
                Value::String(src.clone()),
                src,
                pnt,
            ));
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 4_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 2. Line ending
        let line_skipped = if self.options.line.lex && self.wants(TIN_LN) {
            match self.run_check(self.options.line.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        let line_skipped = line_skipped
            || !self.listed(entry, first, self.options.line.check.is_some(), |ch| {
                self.char_sets.line_ends.contains(ch)
            });
        if self.options.line.lex
            && !line_skipped
            && self.wants(TIN_LN)
            && c.is_some_and(|ch| self.char_sets.line_ends.contains(ch))
        {
            let mut src = String::new();
            let mut seen = std::collections::HashSet::new();
            while let Some(ch) = self.peek() {
                if !self.char_sets.line_ends.contains(ch) {
                    break;
                }
                if self.options.line.single && !seen.insert(ch) {
                    break;
                }
                src.push(self.advance().expect("peeked character must advance"));
            }
            self.ci = 1;
            return Ok(Token::new(
                "#LN",
                TIN_LN,
                Value::String(src.clone()),
                src,
                pnt,
            ));
        }

        if let Some(bad_char @ ('\u{2028}' | '\u{2029}')) = c {
            if self.options.line.lex && !line_skipped && self.wants(TIN_LN) {
                self.advance();
                let err = TabnasError::new(
                    "unexpected",
                    bad_char.to_string(),
                    "",
                    pnt.site.pos,
                    pnt.site.ri,
                    pnt.site.ci,
                );
                self.err = Some(err.clone());
                return Err(Box::new(err));
            }
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 5_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 3. Quoted strings. These precede comments in the canonical matcher
        // order, so an overlapping quote/comment opener is a string unless
        // string matching explicitly abandons the malformed candidate.
        let string_skipped = if self.options.string.lex && self.wants(TIN_ST) {
            match self.run_check(self.options.string.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        let quote = c.filter(|ch| self.char_sets.string.contains(*ch));
        if let Some(quote) = quote.filter(|_| {
            self.options.string.lex
                && !string_skipped
                && self.wants(TIN_ST)
                && self.listed(entry, first, self.options.string.check.is_some(), |ch| {
                    self.char_sets.string.contains(ch)
                })
        }) {
            let start = (self.idx, self.ri, self.ci);
            match self.match_string(quote, pnt) {
                result @ Ok(_) => return result,
                Err(error) if !self.options.string.abandon => return Err(error),
                Err(_) => {
                    (self.idx, self.ri, self.ci) = start;
                    self.err = None;
                }
            }
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 6_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 4. Comments (longest opening marker wins; ties sort by name).
        let comment_skipped = if self.options.comment.lex && self.wants(TIN_CM) {
            match self.run_check(self.options.comment.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        if self.options.comment.lex
            && !comment_skipped
            && self.wants(TIN_CM)
            && self.listed(entry, first, self.options.comment.check.is_some(), |ch| {
                self.options
                    .comment
                    .definitions
                    .values()
                    .any(|definition| definition.start.starts_with(ch))
            })
        {
            if let Some(token) = self.match_comment(pnt)? {
                return Ok(token);
            }
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 7_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 5. Numbers
        let number_skipped = if self.options.number.lex && self.wants(TIN_NR) {
            match self.run_check(self.options.number.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        let could_start_number =
            |ch: char| ch == '-' || ch == '+' || ch == '.' || ch.is_ascii_digit();
        if self.options.number.lex
            && !number_skipped
            && self.wants(TIN_NR)
            && c.is_some_and(could_start_number)
            && self.listed(
                entry,
                first,
                self.options.number.check.is_some(),
                could_start_number,
            )
        {
            if let Some(tkn) = self.match_number(pnt)? {
                return Ok(tkn);
            }
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, 8_000_000.0, &mut plugin) {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 6. Text and named/regex values share the same delimited run.
        // Negotiated lexing gates this combined family by its primary token
        // identity (#TX), matching the TypeScript and Go dispatchers. Once
        // entered, an exact or regexp value definition may still produce
        // #VL; the caller rejects and rolls that cut back when #VL was not
        // requested.
        let text_matcher_wanted = self.wants(TIN_TX);
        let value_lex = self.options.value.lex && text_matcher_wanted;
        let text_lex = self.options.text.lex && text_matcher_wanted;
        let text_skipped = if text_lex || value_lex {
            match self.run_check(self.options.text.check.clone(), pnt) {
                CheckFlow::Continue => false,
                CheckFlow::Skip => true,
                CheckFlow::Token(token) => return Ok(*token),
            }
        } else {
            false
        };
        self.resync(&mut pnt, &mut c);
        if (text_lex || value_lex) && !text_skipped && !self.is_text_delimiter_here() {
            let start = (self.idx, self.ri, self.ci);
            // Only a `value` definition declaring `consume` looks at the
            // rest of the document, and the JSON grammar has none: the
            // tail is sliced where one asks for it, from the offset the
            // token started at, never copied.
            let start_byte = self.byte_position();
            let mut src = String::new();
            while let Some(ch) = self.peek() {
                if self.is_text_delimiter_here() {
                    break;
                }
                src.push(ch);
                self.advance();
            }

            let mut output = None;
            if value_lex {
                if let Some(definition) = self
                    .options
                    .value
                    .definitions
                    .get(&src)
                    .filter(|definition| definition.matcher.is_none())
                    .cloned()
                {
                    output = Some(Token::new(
                        "#VL",
                        TIN_VL,
                        definition
                            .val
                            .clone()
                            .unwrap_or_else(|| Value::String(src.clone())),
                        src.clone(),
                        pnt,
                    ));
                }

                if output.is_none() {
                    let mut definitions: Vec<_> = self
                        .options
                        .value
                        .definitions
                        .iter()
                        .filter(|(_, definition)| definition.matcher.is_some())
                        .map(|(name, definition)| (name.clone(), definition.clone()))
                        .collect();
                    definitions.sort_by(|(name_a, _), (name_b, _)| name_a.cmp(name_b));
                    for (_, definition) in definitions {
                        let regex = definition.matcher.as_ref().expect("filtered matcher");
                        let target: &str = if definition.consume {
                            self.tail_at_byte(start_byte)
                        } else {
                            &src
                        };
                        let Some(captures) = regex.captures(target) else {
                            continue;
                        };
                        let Some(found) = captures.get(0).filter(|found| found.start() == 0) else {
                            continue;
                        };
                        if !definition.consume && found.end() != target.len() {
                            continue;
                        }
                        let matched = found.as_str().to_string();
                        let value = definition.transform.as_ref().map_or_else(
                            || {
                                definition
                                    .val
                                    .clone()
                                    .unwrap_or_else(|| Value::String(matched.clone()))
                            },
                            |transform| {
                                let groups = captures
                                    .iter()
                                    .map(|capture| {
                                        capture
                                            .map_or_else(String::new, |value| value.as_str().into())
                                    })
                                    .collect::<Vec<_>>();
                                transform(&groups)
                            },
                        );
                        if definition.consume {
                            (self.idx, self.ri, self.ci) = start;
                            for _ in matched.chars() {
                                self.advance();
                            }
                        }
                        output = Some(Token::new("#VL", TIN_VL, value, matched, pnt));
                        break;
                    }
                }
            }

            if output.is_none() && (!text_lex || text_skipped) {
                (self.idx, self.ri, self.ci) = start;
            } else if output.is_none() {
                output = Some(Token::new(
                    "#TX",
                    TIN_TX,
                    Value::String(src.clone()),
                    src,
                    pnt,
                ));
            }

            if let Some(mut token) = output {
                let value = std::mem::replace(&mut token.val, Value::Undefined);
                token.val = self.modify_text_value(value, &mut plugin);
                return Ok(token);
            }
        }

        if let Some(token) = self.run_custom_matchers(&mut custom_index, f64::INFINITY, &mut plugin)
        {
            return Ok(token);
        }
        self.resync(&mut pnt, &mut c);

        // 7. Unclaimed character -> Error: unexpected, raised where the
        // cursor stands, as TypeScript's `Lex.next` builds its #BD at the
        // live `pnt` and Go's `nextUnfiltered2` at `l.pnt`. A matcher that
        // stepped over the last character and declined leaves no character
        // to name: the error then names none, at the end of the source, as
        // it does in both. This took a character unconditionally, and so
        // panicked on a lone byte-order mark under the xml plugin, whose
        // matcher steps over a mark at the start of the source.
        let bad_source = self.advance().map_or_else(String::new, String::from);
        let err = TabnasError::new(
            "unexpected",
            bad_source,
            "",
            pnt.site.pos,
            pnt.site.ri,
            pnt.site.ci,
        );
        self.err = Some(err.clone());
        Err(Box::new(err))
    }

    fn match_comment(&mut self, pnt: Point) -> LexResult<Option<Token>> {
        let remaining = self.tail_at_byte(self.byte_position());
        if self.window_open()
            && self.options.comment.definitions.values().any(|definition| {
                definition.lex
                    && remaining.len() < definition.start.len()
                    && definition.start.starts_with(remaining)
            })
        {
            // A marker longer than what is left of a window, which what is
            // left starts, may yet start a comment once the window has
            // grown (#326).
            self.touch_end();
        }
        let mut definitions: Vec<_> = self
            .options
            .comment
            .definitions
            .iter()
            .filter(|(_, definition)| {
                // Same first-byte test as the fixed-token scan above.
                definition.start.as_bytes().first().copied()
                    == remaining.as_bytes().first().copied()
                    && !definition.start.is_empty()
                    && definition.lex
                    && remaining.starts_with(&definition.start)
            })
            .collect();
        definitions.sort_by(|(name_a, a), (name_b, b)| {
            b.start
                .len()
                .cmp(&a.start.len())
                .then_with(|| name_a.cmp(name_b))
        });
        let Some((_, definition)) = definitions.first() else {
            return Ok(None);
        };
        let definition = (*definition).clone();
        let mut src = String::new();
        for _ in definition.start.chars() {
            src.push(self.advance().expect("comment marker must advance"));
        }

        let mut terminated_by_suffix = false;
        let mut closed = definition.line;
        loop {
            let at = self.byte_position();
            let remainder = self.tail_at_byte(at);
            let suffix = definition
                .suffixes
                .iter()
                .filter(|suffix| !suffix.is_empty() && remainder.starts_with(*suffix))
                .max_by_key(|suffix| suffix.len())
                .cloned();
            let suffix = match (suffix, definition.suffix_matcher.as_ref()) {
                (Some(suffix), _) => Some(suffix),
                (None, None) => None,
                (None, Some(matcher)) => match matcher.run(self.tail_at_byte(at)) {
                    Some(effect) => Some(effect),
                    None => {
                        let saved = self.state();
                        let wanted = self.want.clone();
                        let token = matcher.run_imperative(self);
                        self.restore(saved);
                        self.want = wanted;
                        token.map(|token| token.src.to_string())
                    }
                },
            };
            let remainder = self.tail_at_byte(self.byte_position());
            let suffix =
                suffix.filter(|suffix| !suffix.is_empty() && remainder.starts_with(suffix));
            if let Some(suffix) = suffix {
                for _ in suffix.chars() {
                    src.push(self.advance().expect("comment suffix must advance"));
                }
                terminated_by_suffix = true;
                closed = true;
                break;
            }
            if !definition.line
                && !definition.end.is_empty()
                && remainder.starts_with(&definition.end)
            {
                for _ in definition.end.chars() {
                    src.push(self.advance().expect("comment end must advance"));
                }
                closed = true;
                break;
            }
            let Some(ch) = self.peek() else {
                break;
            };
            if definition.line && (self.char_sets.line_ends.contains(ch)) {
                break;
            }
            src.push(self.advance().expect("comment body must advance"));
        }

        if !closed {
            let err = TabnasError::new(
                "unterminated_comment",
                src,
                "",
                pnt.site.pos,
                pnt.site.ri,
                pnt.site.ci,
            );
            self.err = Some(err.clone());
            return Err(Box::new(err));
        }

        if definition.eat_line && !terminated_by_suffix {
            while let Some(ch) = self.peek() {
                if !self.char_sets.line_ends.contains(ch) {
                    break;
                }
                src.push(self.advance().expect("comment line tail must advance"));
            }
        }

        Ok(Some(Token::new(
            "#CM",
            TIN_CM,
            Value::String(src.clone()),
            src,
            pnt,
        )))
    }

    fn match_number(&mut self, pnt: Point) -> LexResult<Option<Token>> {
        let start_idx = self.idx;
        let mut src = String::new();

        // Optional sign.
        if matches!(self.peek(), Some('-' | '+')) {
            src.push(self.advance().unwrap());
        }

        // Base-prefixed integers are complete at the final valid digit.
        if self.peek() == Some('0') {
            if let Some(prefix) = self.peek_at(1) {
                let radix = match prefix {
                    'x' | 'X' if self.options.number.hex => Some(16),
                    'o' | 'O' if self.options.number.oct => Some(8),
                    'b' | 'B' if self.options.number.bin => Some(2),
                    _ => None,
                };
                if let Some(radix) = radix {
                    src.push(self.advance().expect("peeked zero"));
                    src.push(self.advance().expect("peeked base prefix"));
                    let mut saw_digit = false;
                    while let Some(ch) = self.peek() {
                        if ch.is_digit(radix) {
                            saw_digit = true;
                            src.push(self.advance().expect("peeked base digit"));
                        } else if self
                            .options
                            .number
                            .sep
                            .as_ref()
                            .is_some_and(|separator| separator.contains(ch))
                        {
                            src.push(self.advance().expect("peeked base digit"));
                        } else {
                            break;
                        }
                    }
                    if saw_digit && self.is_text_delimiter_here() {
                        if self
                            .exclude_regex
                            .as_ref()
                            .is_some_and(|regex| regex.is_match(&src))
                        {
                            self.reset_number(start_idx, pnt);
                            return Ok(None);
                        }
                        if self.options.value.lex {
                            if let Some(definition) = self
                                .options
                                .value
                                .definitions
                                .get(&src)
                                .filter(|definition| definition.matcher.is_none())
                            {
                                return Ok(Some(Token::new(
                                    "#VL",
                                    TIN_VL,
                                    definition
                                        .val
                                        .clone()
                                        .unwrap_or_else(|| Value::String(src.clone())),
                                    src,
                                    pnt,
                                )));
                            }
                        }
                        // The digits of the literal, prefix, sign and any
                        // separators removed, folded as they are read. The
                        // fold keeps a bounded head, a digit count and a
                        // sticky bit, so a literal of any length costs the
                        // same handful of bytes: buffering the digits
                        // instead would let one long token multiply the
                        // memory the source already holds.
                        let mut fold = DigitFold::new(radix.trailing_zeros());
                        for ch in src.chars().skip_while(|ch| matches!(ch, '-' | '+')).skip(2) {
                            if self
                                .options
                                .number
                                .sep
                                .as_ref()
                                .is_some_and(|separator| separator.contains(ch))
                            {
                                continue;
                            }
                            fold.push(ch.to_digit(radix).expect("validated base digit"));
                        }
                        let mut value = fold.finish();
                        if src.starts_with('-') {
                            value = -value;
                        }
                        return Ok(Some(Token::new(
                            "#NR",
                            TIN_NR,
                            Value::Number(value),
                            src,
                            pnt,
                        )));
                    }
                    self.reset_number(start_idx, pnt);
                    return Ok(None);
                }
            }
        }

        let Some(ch) = self.peek() else {
            self.reset_number(start_idx, pnt);
            return Ok(None);
        };
        if ch == '.' {
            if !self.peek_at(1).is_some_and(|next| next.is_ascii_digit()) {
                self.reset_number(start_idx, pnt);
                return Ok(None);
            }
            src.push(self.advance().expect("peeked leading decimal point"));
        } else if !ch.is_ascii_digit() {
            self.reset_number(start_idx, pnt);
            return Ok(None);
        }

        let (has_digits, edge_separator) = self.scan_number_digits(&mut src);
        if !has_digits || edge_separator {
            self.reset_number(start_idx, pnt);
            return Ok(None);
        }

        // The canonical regexp admits a trailing decimal point and an
        // exponent after it (`2.e3`), but declines `0.a` as one text run.
        if self.peek() == Some('.') {
            let next = self.peek_at(1);
            let exponent_after_dot = matches!(next, Some('e' | 'E'))
                && match self.peek_at(2) {
                    Some('+' | '-') => self.peek_at(3).is_some_and(|ch| ch.is_ascii_digit()),
                    Some(ch) => ch.is_ascii_digit(),
                    None => false,
                };
            if next.is_some_and(|ch| ch.is_ascii_digit()) {
                src.push(self.advance().expect("peeked decimal point"));
                let (_, edge_separator) = self.scan_number_digits(&mut src);
                if edge_separator {
                    self.reset_number(start_idx, pnt);
                    return Ok(None);
                }
            } else if next.is_some()
                && !self.is_text_delimiter_at(self.idx + 1)
                && next != Some('.')
                && !exponent_after_dot
            {
                self.reset_number(start_idx, pnt);
                return Ok(None);
            } else {
                src.push(self.advance().expect("peeked trailing decimal point"));
            }
        }

        if matches!(self.peek(), Some('e' | 'E')) {
            let exponent_start = self.idx;
            let source_len = src.len();
            src.push(self.advance().expect("peeked exponent marker"));
            if matches!(self.peek(), Some('+' | '-')) {
                src.push(self.advance().expect("peeked exponent sign"));
            }
            let (has_exponent_digits, edge_separator) = self.scan_number_digits(&mut src);
            if edge_separator {
                self.reset_number(start_idx, pnt);
                return Ok(None);
            }
            if !has_exponent_digits {
                self.idx = exponent_start;
                src.truncate(source_len);
            }
        }

        if !self.is_text_delimiter_here() {
            self.reset_number(start_idx, pnt);
            return Ok(None);
        }

        // Check exclusion regex (e.g. ^00+)
        if let Some(ref re) = self.exclude_regex {
            if re.is_match(&src) {
                // Number is excluded, backtrack
                self.reset_number(start_idx, pnt);
                return Ok(None);
            }
        }

        if self.options.value.lex {
            if let Some(definition) = self
                .options
                .value
                .definitions
                .get(&src)
                .filter(|definition| definition.matcher.is_none())
            {
                return Ok(Some(Token::new(
                    "#VL",
                    TIN_VL,
                    definition
                        .val
                        .clone()
                        .unwrap_or_else(|| Value::String(src.clone())),
                    src,
                    pnt,
                )));
            }
        }

        // Parse float
        let parse_src = self.options.number.sep.as_ref().map_or_else(
            || src.clone(),
            |separator| src.chars().filter(|ch| !separator.contains(*ch)).collect(),
        );
        match parse_src.parse::<f64>() {
            Ok(num) => Ok(Some(Token::new(
                "#NR",
                TIN_NR,
                Value::Number(num),
                src,
                pnt,
            ))),
            Err(_) => {
                self.reset_number(start_idx, pnt);
                Ok(None)
            }
        }
    }

    fn reset_number(&mut self, start_idx: usize, pnt: Point) {
        self.idx = start_idx;
        self.ri = pnt.site.ri;
        self.ci = pnt.site.ci;
    }

    /// Consume a decimal digit/separator run. Separators are legal only
    /// between digits; a leading or trailing separator makes the whole run
    /// fall through to text, matching the TypeScript regexp and Go scanner.
    fn scan_number_digits(&mut self, src: &mut String) -> (bool, bool) {
        // The run is measured before any of it is consumed. Advancing
        // as it goes would hold `&mut self` across a read of
        // `self.options.number.sep`, and the way that used to be settled
        // was to clone the separator — an allocation and a free for
        // every number in the input, for a value that cannot change
        // while one number is being scanned.
        let run_start = self.idx;
        let mut saw_digit = false;
        let mut last_was_separator = false;
        let mut end = run_start;
        {
            let separator = self.options.number.sep.as_deref();
            while let Some(ch) = self.ch_get(end) {
                if ch.is_ascii_digit() {
                    saw_digit = true;
                    last_was_separator = false;
                } else if separator.is_some_and(|separator| separator.contains(ch)) {
                    last_was_separator = true;
                } else {
                    break;
                }
                end += 1;
            }
        }
        while self.idx < end {
            src.push(self.advance().expect("scanned number character"));
        }
        let starts_with_separator = self.idx > run_start
            && self.options.number.sep.as_deref().is_some_and(|separator| {
                self.chars[run_start - self.low..self.idx - self.low]
                    .first()
                    .is_some_and(|ch| separator.contains(*ch))
            });
        (saw_digit, starts_with_separator || last_was_separator)
    }

    fn match_string(&mut self, quote: char, pnt: Point) -> LexResult<Token> {
        let quote_char = self.advance().unwrap();
        let mut out_str = String::new();
        let mut raw_src = String::new();
        raw_src.push(quote_char);

        let mut pending_high_surrogate: Option<u16> = None;

        // The body classes of TypeScript's `buildStringBodySpec`
        // (ts/src/lexer.ts), which Go's `BuildStringBodySpec` ports: a
        // line character is LINE or LINE+ROW only inside a multi-line
        // string, where it resets the column and, in `line.rowChars`,
        // counts a row; anywhere else in a body it is plain content,
        // counted as a column, unless it is a control character, which
        // stops the body as `unprintable`. This loop used to count a row
        // for any row character it stepped over, string body or not, and
        // to refuse any line character inside a single-line string: with
        // json5's U+2028 and U+2029 as row characters, `y` in
        // `"a<U+2028>b" y` sat on row 2 here and on row 1 in TypeScript
        // and Go, and with the two in `line.chars` as well the string was
        // `unprintable` (tabnas/parser#263).
        let multi_line = self.options.string.multi_chars.contains(quote);

        while let Some(c) = self.peek() {
            if c == quote {
                raw_src.push(self.advance().unwrap());
                // Rust strings cannot represent a lone UTF-16 surrogate, so
                // preserve the Go-port behavior and fold it to U+FFFD.
                self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                return Ok(Token::new(
                    "#ST",
                    TIN_ST,
                    Value::String(out_str),
                    raw_src,
                    pnt,
                ));
            }

            if let Some(replacement) = self.options.string.replace.get(&c).cloned() {
                raw_src.push(self.advance().expect("peeked character must advance"));
                self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                out_str.push_str(&replacement);
                continue;
            }

            if multi_line && self.char_sets.line.contains(c) {
                raw_src.push(
                    self.advance_string_line()
                        .expect("peeked character must advance"),
                );
                out_str.push(c);
                continue;
            }

            // A control character stops the body: a line character
            // always, since a single-line string cannot hold one, and any
            // other unless `string.allowControl` admits it. Sited ON the
            // character, as TypeScript does (`pnt.sI = sI; pnt.cI = cI`
            // before its `bad()` call, ts/src/lexer.ts). `pnt` is the
            // opening quote, and reporting that put every embedded
            // newline at the start of its string.
            if (c as u32) < 32
                && (self.char_sets.line.contains(c) || !self.options.string.allow_control)
            {
                let site = self.current_point().site;
                let err =
                    TabnasError::new("unprintable", c.to_string(), "", site.pos, site.ri, site.ci);
                self.err = Some(err.clone());
                return Err(Box::new(err));
            }

            if c == self.options.string.escape_char {
                raw_src.push(self.advance().unwrap());
                let esc_point = self.current_point();
                if let Some(esc) = self.advance() {
                    raw_src.push(esc);
                    if let Some(replacement) = self.options.string.escape.get(&esc).cloned() {
                        self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                        out_str.push_str(&replacement);
                        continue;
                    }
                    match esc {
                        'u' => {
                            // Unicode escape: \uXXXX or \u{X...}. An
                            // invalid one is reported on the backslash
                            // with the span TypeScript cuts: six source
                            // characters for the fixed-width form, four
                            // for `\x`, and through the closing brace
                            // (or to the end of the source) for the
                            // braced form -- clipped, never padded, so a
                            // truncated escape at end of input reports
                            // exactly the characters that are there.
                            if self.peek() == Some('{') && !self.options.string.escape_strict {
                                raw_src.push(self.advance().unwrap()); // '{'
                                let mut hex = String::new();
                                let mut closed = false;
                                while let Some(h) = self.peek() {
                                    if h == '}' {
                                        raw_src.push(self.advance().unwrap());
                                        closed = true;
                                        break;
                                    }
                                    raw_src.push(self.advance().unwrap());
                                    hex.push(h);
                                }

                                if !closed
                                    || hex.is_empty()
                                    || hex.len() > 6
                                    || !hex.chars().all(|ch| ch.is_ascii_hexdigit())
                                {
                                    let err = TabnasError::new(
                                        "invalid_unicode",
                                        self.source_span(esc_point.site.pos - 1, self.idx),
                                        "",
                                        esc_point.site.pos - 1,
                                        esc_point.site.ri,
                                        esc_point.site.ci - 1,
                                    );
                                    self.err = Some(err.clone());
                                    return Err(Box::new(err));
                                }

                                let cp = match u32::from_str_radix(&hex, 16) {
                                    Ok(val) if val <= 0x10FFFF => val,
                                    _ => {
                                        let err = TabnasError::new(
                                            "invalid_unicode",
                                            self.source_span(esc_point.site.pos - 1, self.idx),
                                            "",
                                            esc_point.site.pos - 1,
                                            esc_point.site.ri,
                                            esc_point.site.ci - 1,
                                        );
                                        self.err = Some(err.clone());
                                        return Err(Box::new(err));
                                    }
                                };

                                self.emit_unicode_escape(
                                    cp,
                                    &mut pending_high_surrogate,
                                    &mut out_str,
                                );
                            } else {
                                // Exactly 4 hex digits: \uXXXX
                                let mut hex = String::new();
                                for _ in 0..4 {
                                    if let Some(h) = self.peek() {
                                        if h.is_ascii_hexdigit() {
                                            raw_src.push(self.advance().unwrap());
                                            hex.push(h);
                                        } else {
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                }

                                if hex.len() != 4 {
                                    let err = TabnasError::new(
                                        "invalid_unicode",
                                        self.source_span(
                                            esc_point.site.pos - 1,
                                            esc_point.site.pos + 5,
                                        ),
                                        "",
                                        esc_point.site.pos - 1,
                                        esc_point.site.ri,
                                        esc_point.site.ci - 1,
                                    );
                                    self.err = Some(err.clone());
                                    return Err(Box::new(err));
                                }

                                let cp = u16::from_str_radix(&hex, 16).map_err(|_| {
                                    let err = TabnasError::new(
                                        "invalid_unicode",
                                        self.source_span(
                                            esc_point.site.pos - 1,
                                            esc_point.site.pos + 5,
                                        ),
                                        "",
                                        esc_point.site.pos - 1,
                                        esc_point.site.ri,
                                        esc_point.site.ci - 1,
                                    );
                                    self.err = Some(err.clone());
                                    err
                                })?;

                                self.emit_unicode_escape(
                                    u32::from(cp),
                                    &mut pending_high_surrogate,
                                    &mut out_str,
                                );
                            }
                        }
                        'x' if !self.options.string.escape_strict => {
                            let mut hex = String::new();
                            for _ in 0..2 {
                                if let Some(h) = self.peek() {
                                    if h.is_ascii_hexdigit() {
                                        raw_src.push(
                                            self.advance().expect("peeked character must advance"),
                                        );
                                        hex.push(h);
                                    }
                                }
                            }
                            if hex.len() != 2 {
                                let err = TabnasError::new(
                                    "invalid_ascii",
                                    self.source_span(
                                        esc_point.site.pos - 1,
                                        esc_point.site.pos + 3,
                                    ),
                                    "",
                                    esc_point.site.pos - 1,
                                    esc_point.site.ri,
                                    esc_point.site.ci - 1,
                                );
                                self.err = Some(err.clone());
                                return Err(Box::new(err));
                            }
                            let byte = u8::from_str_radix(&hex, 16).expect("validated ASCII hex");
                            self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                            out_str.push(char::from(byte));
                        }
                        other => {
                            if !self.options.string.allow_unknown {
                                // Sited on the escape CHARACTER with a
                                // one-character span, as TypeScript
                                // (`pnt.sI = sI; pnt.cI = cI; lex.bad(
                                // S.unexpected, sI, sI + 1)`) and Go do;
                                // the other escape errors sit on the
                                // backslash and span the construct.
                                let err = TabnasError::new(
                                    "unexpected",
                                    other.to_string(),
                                    "",
                                    esc_point.site.pos,
                                    esc_point.site.ri,
                                    esc_point.site.ci,
                                );
                                self.err = Some(err.clone());
                                return Err(Box::new(err));
                            }
                            self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                            out_str.push(other);
                        }
                    }
                } else {
                    let err = TabnasError::new(
                        "unterminated_string",
                        raw_src,
                        "",
                        pnt.site.pos,
                        pnt.site.ri,
                        pnt.site.ci,
                    );
                    self.err = Some(err.clone());
                    return Err(Box::new(err));
                }
            } else {
                self.flush_surrogate(&mut pending_high_surrogate, &mut out_str);
                raw_src.push(self.advance_body().expect("peeked character must advance"));
                out_str.push(c);
            }
        }

        let err = TabnasError::new(
            "unterminated_string",
            raw_src,
            "",
            pnt.site.pos,
            pnt.site.ri,
            pnt.site.ci,
        );
        self.err = Some(err.clone());
        Err(Box::new(err))
    }

    fn flush_surrogate(&self, pending: &mut Option<u16>, out: &mut String) {
        if pending.take().is_some() {
            out.push('\u{FFFD}');
        }
    }

    /// Emit one decoded Unicode escape while pairing UTF-16 surrogate code
    /// units across both `\\uXXXX` and `\\u{...}` spellings.
    fn emit_unicode_escape(&self, cp: u32, pending: &mut Option<u16>, out: &mut String) {
        if (0xD800..=0xDBFF).contains(&cp) {
            self.flush_surrogate(pending, out);
            *pending = Some(cp as u16);
        } else if (0xDC00..=0xDFFF).contains(&cp) {
            if let Some(high) = pending.take() {
                let scalar = 0x10000 + (((u32::from(high)) - 0xD800) << 10) + (cp - 0xDC00);
                out.push(char::from_u32(scalar).expect("paired surrogates form a Unicode scalar"));
            } else {
                out.push('\u{FFFD}');
            }
        } else {
            self.flush_surrogate(pending, out);
            out.push(char::from_u32(cp).expect("validated escape is a Unicode scalar"));
        }
    }
}

// ---------------------------------------------------------------------------
// Base-prefixed integer literals.
//
// A `0x`, `0o` or `0b` literal is read as an EXACT integer and rounded to
// a double ONCE. The obvious fold -- `value = value * radix + digit` in
// `f64` -- rounds at every digit, and past the 53-bit exact integer range
// those roundings accumulate: `0Xa6f2f78f4f9bf44` came out as
// `43a4de5ef1e9f37e` where canonical TypeScript and the Go port both
// answer `43a4de5ef1e9f37f`, one unit in the last place low. That is
// silently altered data, not a formatting difference.
//
// TypeScript coerces the literal with unary `+`, whose StringNumericValue
// is the exact mathematical value of the digits rounded once, half to
// even; Go reads it through `big.Int` and `big.Float.Float64()`, which is
// the same rule. These reproduce it. Only the VALUE is affected: which
// literals are accepted, and the token they become, are settled by
// `match_number` before any of this runs.
//
// The decimal path needs none of it -- `str::parse::<f64>` is correctly
// rounded for a digit string of any length.
// ---------------------------------------------------------------------------

/// `2^k` for a non-negative `k`, exactly, saturating to infinity above the
/// double range. A repeated multiply would round on the way up.
fn pow2(k: i64) -> f64 {
    debug_assert!(k >= 0, "only non-negative exponents arise here");
    if k > 1023 {
        f64::INFINITY
    } else {
        f64::from_bits(((k + 1023) as u64) << 52)
    }
}

/// Folds the digits of a base-prefixed literal into the NEAREST double,
/// rounding half to even, without holding the digits.
///
/// `bits` is the width of one digit, so the base is a power of two: 1 for
/// binary, 3 for octal, 4 for hexadecimal. Those are the only bases
/// `match_number` reads, which is what lets a `u128` head plus a sticky
/// bit stand in for arbitrary-precision arithmetic.
///
/// Only three things about a literal can change the answer: the top
/// `128 / bits` significant digits, how many digits follow them, and
/// whether any of those is non-zero. This keeps exactly those, so the
/// space it costs does not grow with the literal, however long an
/// untrusted document makes one.
struct DigitFold {
    bits: u32,
    /// The significant digits packed so far, at most `head_len` of them.
    head: u128,
    /// How many significant digits have been pushed, head and tail alike.
    len: usize,
    /// Whether any digit past the head was non-zero.
    sticky: bool,
    /// Whether a non-zero digit has been seen. Leading zeros carry no
    /// value, and dropping them is what makes the head wider than the 54
    /// significant bits the rounding needs.
    started: bool,
}

impl DigitFold {
    fn new(bits: u32) -> Self {
        debug_assert!(
            (1..=4).contains(&bits),
            "only the power-of-two bases the lexer reads"
        );
        DigitFold {
            bits,
            head: 0,
            len: 0,
            sticky: false,
            started: false,
        }
    }

    /// A `u128` holds exactly this many digits of the base.
    fn head_len(&self) -> usize {
        (128 / self.bits) as usize
    }

    fn push(&mut self, digit: u32) {
        if !self.started {
            if 0 == digit {
                return;
            }
            self.started = true;
        }
        if self.len < self.head_len() {
            self.head = (self.head << self.bits) | u128::from(digit);
        } else if 0 != digit {
            self.sticky = true;
        }
        self.len += 1;
    }

    fn finish(&self) -> f64 {
        if !self.started {
            return 0.0;
        }
        let head_len = self.head_len();
        if self.len <= head_len {
            // A `u128` to `f64` cast rounds to nearest, ties to even, which
            // is the rule the canonical runtime follows.
            return self.head as f64;
        }

        // Longer than a u128: the head holds the top `head_len` digits and
        // `sticky` remembers whether anything below them was set. Those two
        // are all the rounding can depend on. The leading digit is
        // non-zero, so the head is at least 121 bits wide in every base
        // here and `shift` is comfortably positive.
        let dropped = i64::from(self.bits) * (self.len - head_len) as i64;
        let shift = 128 - self.head.leading_zeros() - 53;

        let mut mantissa = (self.head >> shift) as u64;
        let half = (self.head >> (shift - 1)) & 1 == 1;
        let sticky = self.head & ((1u128 << (shift - 1)) - 1) != 0 || self.sticky;
        if half && (sticky || mantissa & 1 == 1) {
            // At most 2^53, which is still an exact double.
            mantissa += 1;
        }
        // The mantissa carries at most 53 significant bits, so the scaling
        // is exact inside the double range and overflows to infinity
        // outside it.
        mantissa as f64 * pow2(dropped + i64::from(shift))
    }
}

#[cfg(test)]
mod window_tests {
    use super::{WindowSizes, WINDOW_PEAK};

    /// A parse from a reader holds no more of the source than its window:
    /// a block behind the cursor and a margin or two ahead of it, however
    /// long the source, flat from 2,000 records to 20,000.
    #[test]
    fn a_parse_from_a_reader_holds_a_bounded_window() {
        let mut parser = crate::Tabnas::make_json();
        parser
            .set_options(|options| options.lex.window = true)
            .expect("lex.window sets");
        let sizes = WindowSizes {
            margin: 1024,
            block: 1024,
            chunk: 1024,
        };
        let mut peaks = Vec::new();
        for count in [2_000, 20_000] {
            let records: Vec<String> = (0..count)
                .map(|i| format!("{{\"id\":{i},\"name\":\"n{i}\",\"tags\":[\"a\",\"b\"]}}"))
                .collect();
            let text = format!("[{}]", records.join(","));
            WINDOW_PEAK.with(|peak| peak.set(0));
            parser
                .parse_reader_with_sizes(text.as_bytes(), sizes)
                .expect("the reader parses");
            let peak = WINDOW_PEAK.with(std::cell::Cell::get);
            assert!(peak <= 4 * 1024, "{count} records held {peak} characters");
            peaks.push(peak);
        }
        // Ten times the records hold no more than a few records' more:
        // where the blocks fall against the records moves the peak a
        // little, the length not at all.
        assert!(peaks[1] <= peaks[0] + 256, "{peaks:?}");
    }
}