tsv_ts 0.8.0

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

use crate::Goal;
use crate::ast::*;
use crate::lexer::escapes::{LegacyEscape, find_legacy_escape};
use crate::lexer::{KeywordKind, Lexer, LexerCheckpoint, Token, TokenKind, is_es_line_terminator};
use crate::printer::ParenContext;
use bumpalo::Bump;
use bumpalo::collections::Vec as BumpVec;
use std::collections::BTreeSet;
use std::ops::ControlFlow;
use tsv_lang::{DepthBudget, DepthLimit, Error, Span, SpineCount};

// Import parsing implementations
mod expression;
mod expression_arrow; // Arrow function predicate scans and builders
mod expression_assignable; // Cover-grammar expression→pattern conversion (`refine_assignable`)
mod expression_braced_operand; // Braced-operand byte-scan lookahead (`{} / 2` vs `if (c) {}⏎/re/`)
mod expression_literals; // Object and array literal parsing
mod expression_lookahead; // Arrow function and type argument disambiguation
mod expression_template; // Template literal parsing (`\`...${expr}...\``)
mod expression_type_args; // Type-argument byte-scan lookahead (`<Type, ...>` vs `<`)
mod parameters; // Function/method parameter and destructuring-pattern parsing
mod scan; // Low-level byte scanning utilities
mod statement; // Statement parsing (refactored into submodules)
mod type_members; // Type-literal / interface-body member grammar (property/method/signature elements)
mod types; // TypeScript type-syntax parsing (annotations, type expressions, type parameters)

pub(crate) use expression::is_jsdoc_type_cast_comment;
pub(crate) use expression_braced_operand::closes_braced_operand;
pub(crate) use expression_type_args::{closes_statement_header, closes_type_arguments};

/// Who owns a top-level `as` in a partial expression parse — TypeScript, or the host
/// grammar the expression is embedded in.
///
/// Svelte's block heads are the only callers, and they split on whether the head's own
/// binding separator is spelled `as`:
///
/// - [`TopLevelAs::Assertion`] — `{#await p as T then v}`. `then` / `catch` are not type
///   syntax, so an `as` in an await head is always TypeScript's; the parse ends on its
///   own at the clause keyword.
/// - [`TopLevelAs::HostSeparator`] — `{#each xs as item}`, where the separator *is* `as`.
///   The parse must leave the keyword for the block reader, which then walks the
///   assertion run itself (`tsv_svelte`'s `each_binding_separator`).
///
/// ⚠️ The axis is `as` **alone**, which is why the name says so. `satisfies` is a type
/// assertion too, but no host separator is spelled `satisfies`, so it is never in
/// question and stays consumable under both variants — the wider "type assertions"
/// framing this replaced denied it in `{#each}` for no reason, rejecting
/// `{#each xs satisfies T as item}`, which canonical Svelte accepts.
///
/// The policy applies only at [`Parser::grouping_depth`] `0` — inside grouping,
/// `(x as T)` is unambiguously an assertion under both.
// Reached only through a `#[doc(hidden)]` re-export, so it renders nowhere public and its
// links to private items are maintainer navigation (see the hidden modules in `lib.rs`).
#[expect(rustdoc::private_intra_doc_links)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TopLevelAs {
    /// Consume `as` wherever it is grammatical.
    Assertion,
    /// Stop at a top-level `as`, leaving the keyword to the host grammar.
    HostSeparator,
}

/// Build a detached [`Comment`] from a lexed comment token's positions.
///
/// `content_start` / `token_*` are local (pre-`base_offset`) byte offsets; the
/// stored spans are shifted into host coordinates by `base_offset` so embedded
/// `<script>` / `{expr}` comments slice the host source. The content end is the
/// token end minus the closing `*/` for block comments (`//` and `#!` run to the
/// token end). Returns the comment plus whether its content holds a line
/// terminator — block comments only — which callers fold into
/// `had_line_terminator` for ASI (a multi-line comment counts as one terminator).
fn comment_from_token(
    source: &str,
    token_start: usize,
    token_end: usize,
    content_start: usize,
    is_block: bool,
    base_offset: usize,
) -> (Comment, bool) {
    let content_end = if is_block { token_end - 2 } else { token_end };
    let content = &source[content_start..content_end];
    // Ask the `\n` question first — `Comment::content_is_multiline`, which is also the
    // `is_block` gate (a `//` comment's content can hold no terminator at all). It is a
    // single-`char` pattern, so it lowers to a `memchr`, whereas the full `LineTerminator`
    // predicate is a char-at-a-time searcher over the whole comment body (a long JSDoc block
    // pays that in full). And a `\n` *is* a line terminator, so on the common multi-line block
    // comment it answers the wider question for free; only a block comment with no `\n` at all
    // — a one-liner like `/* x */` — reaches the rare-terminator scan, which is spelled as the
    // shared production minus the character already ruled out rather than as its own list, so
    // widening the class cannot leave this behind.
    let multiline = Comment::content_is_multiline(is_block, content);
    let has_line_terminator =
        is_block && (multiline || content.contains(|c| is_es_line_terminator(c) && c != '\n'));
    let comment = Comment {
        content_span: Span::new(
            (content_start + base_offset) as u32,
            (content_end + base_offset) as u32,
        ),
        is_block,
        multiline,
        span: Span::new(
            (token_start + base_offset) as u32,
            (token_end + base_offset) as u32,
        ),
        from_template_reader: false,
        // Set later by the parser: a `(` glued to this comment makes it a cast's.
        owned_by_node: false,
    };
    comment.debug_assert_span_len();
    (comment, has_line_terminator)
}

/// A `<` region: what tsc's type-argument parse may still be consuming.
///
/// It opens at a binary `<` (a `<<` opens two — tsc re-scans it to a `<` and reads the
/// second as a nested list's), and a `>` reduced while it is open may be the token that
/// recovering parse stops at — which the printer must then never let end a line, nor put
/// a pair of its own behind (`BinaryExpression::may_close_type_arguments`). A `>>` closes
/// two nested lists and a `>>>` three, so each is such a token behind that many open
/// regions ([`LtRegions`]). It is a deliberate SUPERSET — no model of which tokens the
/// recovery takes — and it ends only where the printed form provably ends it, all of them
/// tokens the type grammar cannot take at list level:
///
/// - the closer of the delimiter the `<` was written in ([`Parser::exit_grouping`], read
///   against [`LtRegion::floor`] as `no_in_depth` reads its baseline) — call arguments,
///   a parameter list, `[…]`, `{…}`, each `${…}` of a template. **A grouping paren is
///   not one**: the printer may strip it, so the region re-anchors one level out
///   instead. A comma-list owner may retain an authored comparison pair when a later
///   sibling holds a flagged closer; retention leaves this region verdict unchanged
///   ([`Parser::exit_stripped_grouping`]);
/// - a statement, module-item or class-member boundary
///   ([`Parser::lt_regions_statement_base`]), and the two places a statement's own parts
///   stand past one: a do-while's test, past its body, and a `switch` clause's test, past
///   the discriminant and past the statements of the clause before it. Two `case` tests
///   with no statement between them are NOT parted: only a `:` and a keyword stand there,
///   and tsv's own type-argument scan reads through both.
///
/// A **body** is no boundary of the region it was written in — an arrow's, a function's,
/// a class's, an object literal method's: its statements start from the open regions,
/// and the regions are still open past its `}` ([`Parser::with_lt_region_inherited`]).
///
/// Ending it EARLY is the unsound direction (a `>` the printer may then end a line on,
/// or put a pair behind); ending it late costs one operator-leading line break, or one
/// withheld clarity pair, on a shape real code does not hold.
///
/// Regions die in the reverse of the order they opened: a later one opens at the same depth
/// or deeper, so it dies no later than every one before it ([`LtRegions`]).
// TODO: a region still outlives the part of a statement it was written in at these
// places, each the late (sound) direction: a `for` head's parts across their `;`
// (`for (let i = 0; i < n; i += c > d % e + f ? 1 : 2) {}`), a class heritage's or a
// decorator's paren into the class body or the member it heads
// (`class K extends (a < b ? B : C) { q = c > d % e + f; }`), and an object literal's
// computed key into a later property (`x = { [a < b]: 1, q: c > await d };`).
#[derive(Clone, Copy, Default)]
struct LtRegion {
    /// The [`Parser::grouping_depth`] the region lives at: it is dead once the depth drops
    /// below this.
    floor: u32,
    /// Where its `<` stands (a span coordinate, as [`Parser::current_pos`] gives). A `>`
    /// whose own LEFT operand holds the `<` is not this rule's — `(x < q) > c` and
    /// `x < 1 + 2 > c` are the chain the pair rule answers
    /// (`BinaryExpression::relexes_as_type_arguments`), which either ends the region on a
    /// `)` or has graded it no type-argument list — so the reader asks for a `<` standing
    /// AHEAD of that operand ([`Parser::lt_regions_open_before`]).
    lt_pos: usize,
}

/// The `<` regions open at one point of the parse, in opening order — the earliest
/// [`LtRegions::CAP`] of them, which is every count a reader asks for: a `>` closes one
/// list, a `>>` two, a `>>>` three.
///
/// Dropping the rest loses nothing. Floors never decrease along the order regions opened
/// in (a later `<` stands at the same depth or deeper, and re-anchoring a stripped paren's
/// regions lowers them only to the depth every earlier one already lives at), so the
/// regions that die at a closer are always a suffix, and an untracked one is dead before
/// any tracked one it followed.
#[derive(Clone, Copy, Default)]
struct LtRegions {
    len: u8,
    open: [LtRegion; Self::CAP],
}

impl LtRegions {
    /// The most lists one token closes (`>>>`).
    const CAP: usize = 3;

    /// Record a region that just opened; past [`Self::CAP`] it is not tracked.
    #[inline]
    fn open(&mut self, region: LtRegion) {
        if let Some(slot) = self.open.get_mut(usize::from(self.len)) {
            *slot = region;
            self.len += 1;
        }
    }

    /// Drop the regions that lived deeper than `depth` — the delimiter they opened in
    /// has closed.
    #[inline]
    fn close_above(&mut self, depth: u32) {
        while self.len > 0 && self.open[usize::from(self.len) - 1].floor > depth {
            self.len -= 1;
        }
    }

    /// Re-anchor the regions that lived deeper than `depth` AT `depth` — the grouping
    /// paren they opened in is one the printer may strip.
    #[inline]
    fn reanchor_above(&mut self, depth: u32) {
        for region in &mut self.open[..usize::from(self.len)] {
            region.floor = region.floor.min(depth);
        }
    }

    /// How many open regions have their `<` ahead of `operand_start`.
    #[inline]
    fn open_before(&self, operand_start: usize) -> usize {
        self.open[..usize::from(self.len)]
            .iter()
            .take_while(|region| region.lt_pos < operand_start)
            .count()
    }
}

/// One discarded grouping paren pair, recorded while a binding pattern is read
/// ([`Parser::record_grouping_parens`]): the span of the expression it wrapped, and
/// where its `(` stands, which is where the binding-pattern error points.
#[derive(Clone, Copy)]
pub(super) struct GroupingParen {
    pub(super) inner: Span,
    pub(super) open: u32,
}

/// The counts a statement list ([`Parser::statement_list`]) keeps across its statements:
/// the enclosing frame's spine count and deepest nesting, restored when the list closes,
/// and the greatest of the statements' own so far.
/// How a pair-free root's expression ends ([`Parser::pair_free_root`]) — what tells the
/// node at its start that it is the whole of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RootEnd {
    /// Anywhere: an assignment's right side, which no comma continues.
    Anywhere,
    /// At anything but a comma, which would make the expression a sequence: a statement's
    /// expression.
    BeforeAnyButComma,
    /// [`RootEnd::BeforeAnyButComma`] in a `for` header's init or update clause — the one
    /// position a bare sequence prints bare too (`for (a, b; ; c, d)`), where everywhere
    /// else it takes a pair ([`Parser::sequence_pair`]).
    ForClause,
    /// At the `)` of a grouping paren, whose pair the author wrote.
    AtParenClose,
}

pub(super) struct StatementFrame {
    outer: SpineCount,
    statements: SpineCount,
    /// The statements closed so far.
    closed: usize,
    outer_peak: u32,
    peak: u32,
}

impl StatementFrame {
    /// Close the statement just parsed and open the next: once the count has run long
    /// ([`SpineCount::runs_long`]) or the list has passed its first
    /// [`ListFrame::SUMMED`] statements, it joins the list's greatest and the parser's
    /// restarts; until then the statements count together, which costs a body of short
    /// statements nothing and overcounts it by a few dozen units, or a few printer pairs,
    /// at most. Neither test reads the printer pairs, so a format's output, whose pairs are
    /// grouping parens, is framed exactly as its input was. The deepest nesting restarts at
    /// every statement ([`DepthBudget::take_peak`]), so a chain is charged its own
    /// statement's, whatever came before it.
    #[inline]
    pub(super) fn next(&mut self, parser: &mut Parser<'_, '_>) {
        self.closed += 1;
        if self.closed > ListFrame::SUMMED || parser.spine.runs_long() {
            self.statements = self.statements.max(parser.spine.take());
        }
        if parser.depth.is_deep() {
            self.peak = self.peak.max(parser.depth.take_peak(parser.grouping_depth));
        }
    }
}

/// The spine frames of a list whose elements are siblings — an array's or object's
/// elements, a call's arguments, a sequence, a declarator list, a class or type body's
/// members, a union's constituents, a switch's cases, an enum's members
/// ([`Parser::list_frame`]). The first [`ListFrame::SUMMED`] elements count in the
/// enclosing frame, which costs a short list nothing and overcounts it by at most their
/// sum; past them each element counts in a frame of its own, the first of which takes what
/// came before, and the list hands up the greatest — so a long list of short chains (a
/// data table, a minified sequence) is charged one element's chains, not their total.
pub(super) struct ListFrame {
    greatest: SpineCount,
    peak: u32,
}

impl ListFrame {
    /// The elements counted together before each takes a frame of its own.
    const SUMMED: usize = 8;

    /// Open the frame of element `index` (0-based), closing the one before it — its spine
    /// count and its deepest nesting ([`DepthBudget::take_peak`]) alike.
    #[inline]
    pub(super) fn element(&mut self, parser: &mut Parser<'_, '_>, index: usize) {
        if index >= Self::SUMMED {
            self.greatest = self.greatest.max(parser.spine.take());
            self.peak = self.peak.max(parser.depth.take_peak(parser.grouping_depth));
        }
    }

    /// Close the list: the enclosing frame takes the greatest of the elements' frames —
    /// the first of them holding what the frame counted before the list.
    #[inline]
    pub(super) fn close(self, parser: &mut Parser<'_, '_>) {
        if !self.greatest.is_empty() {
            parser.spine.fold(self.greatest);
        }
        if self.peak > 0 {
            parser.depth.fold_peak(self.peak);
        }
    }
}

// The spine units a link counts ([`Parser::spine_link`]): one for a binary or logical
// operator and for a member access, call or instantiation the member-chain printer
// flattens — the cheapest links to walk, since every walk over an operator chain iterates
// it, and every walk over a member and call chain iterates it too, but for the member-chain
// linearizer and the type strip, each of which recurses through only its first few links — and, for
// the dearer ones, the stack their walks spend per link over an operator's, rounded up over every
// build the contract covers: the native optimized and debug builds, and the WASM engine's two
// stacks (its shadow stack in linear memory, and the host engine's own, cold and tiered up). The
// re-entering links', an assertion's and a type suffix's weights keep about a quarter over the
// smallest at which every leg of the gates holds its nine-tenths margin, so a printer change that
// grows one of those walks fails the gate before it eats the contract's own margin, and the WASM
// engine sets them: the re-entering links' by its shadow stack once V8 has tiered the walks up, an
// assertion's by that shadow stack in either tier, and a type suffix's by the engine's own stack
// once tiered up (the native builds hold at lower ones). A non-null's is the smallest a debug
// build's frames hold, which price it above a subscript's (a run of `!` with a comment in each gap
// nests a doc level per link).
// Whether a link re-enters is the printer's answer (`printer::binary_left_operand_reenters`,
// `printer::call_may_print_whole`); the units themselves are graded over every pair of link kinds,
// a sample of triples and the links with comments in their gaps, natively by
// `tests/depth_limit.rs` and in the WASM engine by `scripts/depth_wasm.ts`.

/// The spine units of a binary or logical operator, a postfix `++` / `--`, or a qualified
/// name's `.`.
pub(super) const LINK_OPERATOR: u32 = 1;
/// The spine units of a member access, a call or an instantiation that the member-chain
/// printer flattens into its chain.
pub(super) const LINK_SUBSCRIPT: u32 = 1;
/// The spine units of a non-null assertion the member-chain printer flattens: a run of
/// `!` with a comment in each gap is printed as a doc that nests a level per `!`
/// (`Printer::build_commented_non_null_operand_doc`), whose walks a debug build's frames
/// price above a subscript's.
pub(super) const LINK_NON_NULL: u32 = 2;
/// The spine units of a link whose walk re-enters the expression printer for its operand:
/// a call or a `!` the member-chain printer does not flatten, one on a call (a curried call,
/// `f()!()`) or on a tagged template ([`Parser::call_link_units`]); a member over a tagged
/// template; a member or `!` over a call the printer prints
/// whole, and that call itself ([`Parser::member_link_units`], [`Parser::settle_call_link`]);
/// and a binary operator whose left operand the binary-chain printer does not flatten into
/// its chain ([`Parser::binary_link_units`]).
pub(super) const LINK_REENTRY: u32 = 10;
/// The spine units of a tagged template, whose tag the printer prints by re-entering the
/// expression printer; a link over a tagged template counts as a re-entry of its own
/// ([`Parser::member_link_units`], [`Parser::call_link_units`]).
pub(super) const LINK_TAG: u32 = 14;
/// The spine units of an `as` / `satisfies` link.
pub(super) const LINK_ASSERTION: u32 = 8;
/// The spine units of a type's `[]` / `[K]` suffix link.
pub(super) const LINK_TYPE_SUFFIX: u32 = 5;

/// The links a link's spine walk takes before it consults [`SpineMemo`]
/// ([`Parser::member_link_units`], [`Parser::call_link_units`]): a spine the walk ends
/// within — most of them — pays only the walk, which a bound this small keeps compact where
/// it is inlined.
const SPINE_WALK_LINKS: u32 = 4;

/// What the last walk past [`SPINE_WALK_LINKS`] found, keyed by the address of the node its
/// bounded walk stopped at (`0`: none yet). The link over a chain's operand stops one link
/// above where the link before it stopped, so its walk past the bound takes one step to a
/// key: a chain of `n` links walks `n` times the bound, not `n²` steps. Sound because an
/// arena node is never mutated or freed while the parser lives, so a node's answer is fixed
/// once it is built; a walk that meets no key (another chain's walk took the memo) walks to
/// the end of its spine — slower, never wrong.
///
/// Deliberately left out of [`Checkpoint`]: a rewind need not restore it, since an abandoned
/// branch's nodes stay allocated in the arena and their addresses are never reused, so a key
/// one of them left names that node alone and its answer stays true.
#[derive(Clone, Copy, Default)]
struct SpineMemo {
    /// The node [`Parser::spine_whole_past`] last stopped at.
    whole_at: usize,
    /// Whether the first call down that node's spine may be one the printer prints whole.
    whole: bool,
    /// The node [`Parser::call_units_past`] last stopped at.
    call_at: usize,
    /// [`Parser::call_link_units`] of that node.
    call_units: u32,
}

/// One step of [`Parser::call_link_units`]' walk down a call link's operand: through a `!`'s
/// operand or an instantiation's expression, or the walk's end — [`LINK_REENTRY`] at a call
/// or a tagged template, else [`LINK_SUBSCRIPT`]. The one statement of the call rule, which
/// both the bounded walk and its continuation past the bound ([`Parser::call_units_past`])
/// take.
#[expect(clippy::inline_always)]
#[inline(always)]
fn call_spine_step<'e>(inner: &'e Expression<'e>) -> ControlFlow<u32, &'e Expression<'e>> {
    tsv_lang::fanout_probe::predicate();
    match &inner.kind {
        ExpressionKind::TSNonNullExpression(n) => ControlFlow::Continue(n.expression),
        ExpressionKind::TSInstantiationExpression(i) => ControlFlow::Continue(i.expression),
        ExpressionKind::CallExpression(_) | ExpressionKind::TaggedTemplateExpression(_) => {
            ControlFlow::Break(LINK_REENTRY)
        }
        _ => ControlFlow::Break(LINK_SUBSCRIPT),
    }
}

/// The parser state [`Parser::rewind`] restores after one of the grammar's
/// speculative parses ([`Parser::parse_arrow_or_rewind`],
/// [`Parser::parse_type_arguments_or_rewind`], [`Parser::type_arguments_follower_settled`]
/// the `export default` value's decorator-list read in `parse_export_declaration`, and a
/// parameter's in `parse_parameter`):
/// the lexer cursor, the
/// one-token window with its decoded values and line-terminator flags, `prev_end`,
/// a peek's stored lexer error, the comment ledger's length, the grouping depth, the
/// depth-limit counts ([`Parser::depth`] — whose nesting is restored on every path anyway,
/// but whose deepest level an abandoned parse may have raised — and [`Parser::spine`]), the
/// open `<` regions that are read against it ([`Parser::lt_regions`]) and the error
/// kept from an abandoned type-argument list
/// ([`Parser::abandoned_type_arguments_error`]).
/// Context flags (`allow_in`, `in_await`, …) are not carried — their combinators
/// restore them on every path — and neither are arena nodes, which an abandoned
/// parse simply leaves unreachable.
///
/// ⚠️ That first exemption is a **standing obligation**, not an observation: a
/// context flag whose save/restore is hand-rolled around a `?` leaks its value
/// out of an abandoned parse, and nothing here can see that it did. Every one
/// goes through [`Parser::with_context_flag`] (or a combinator built on it) for
/// exactly this reason. Nothing likewise forces a NEW `Parser` field into this
/// struct — the destructuring in [`Parser::rewind`] guards only the other
/// direction — so a field added below `grouping_depth` must be classified here
/// by hand: carried, combinator-restored, or provably immutable for the parse.
/// `record_grouping_parens`, `in_for_header` and `pair_free_root` are combinator-restored. `grouping_parens`
/// is deliberately not carried: an entry an abandoned parse leaves names a `(`…`)` pair
/// that is in the source however the rest is read, so it can only ever mark a target the
/// real parse also sees wrapped. These are deliberately not carried either, each a fact about the
/// source that outlives the reading that found it:
///
/// - `abandoned_type_argument_lists` and `type_argument_lists_kept` — which `<` open no
///   type-argument list, and which open one whatever follows it, in which context.
///   Surviving the rewind is their whole purpose
///   ([`Parser::abandoned_type_argument_lists`]).
/// - `await_name_operand` — where a name `await` stood at this goal. It is read once,
///   against the position of the error the whole parse ends on, and the tokens an
///   abandoned parse read are the ones its re-read reads.
/// - `preserved_a_paren` — set by a pair an abandoned parse wrapped; it may over-report,
///   which costs its one reader a second parse.
/// - `decorated_parameter_properties` — which decorator runs belong to a parameter
///   property, whose re-read it keeps to one ([`Parser::decorated_parameter_properties`]).
///
/// A comment's `owned_by_node` is written through the ledger rather than appended to it,
/// so truncating the ledger does not undo a claim on a comment drained AHEAD of the
/// checkpoint — one glued to the token the parser had peeked.
/// [`Parser::parse_type_arguments_or_rewind`] cannot leave such a claim from the list it
/// tries: that token opens the list's first argument, which is read as a type, and the
/// type grammar claims no comment. The comparison reading it then may try
/// (`Parser::type_arguments_follower_settled`) reads that token as an expression, which
/// can claim one, so that speculation puts back the claims it made on the comments
/// drained ahead of its checkpoint. The `export default` and parameter sites keep any
/// claim their decorator-list read makes across the rewind, and that is safe: the re-read
/// parses the same decorator list the same way, so every surviving claim is one it makes
/// again.
#[derive(Clone)]
pub(super) struct Checkpoint<'arena> {
    lexer: LexerCheckpoint,
    current: Token,
    current_decoded: Option<&'arena str>,
    peek: Option<Token>,
    peek_decoded: Option<&'arena str>,
    had_line_terminator: bool,
    peek_had_line_terminator: bool,
    prev_end: usize,
    lexer_error: Option<Error>,
    comments_len: usize,
    grouping_depth: u32,
    depth: DepthBudget,
    spine: SpineCount,
    lt_regions: LtRegions,
    abandoned_type_arguments_error: Option<Error>,
}

#[expect(clippy::struct_excessive_bools)]
pub(crate) struct Parser<'a, 'arena> {
    /// Bump arena that owns every AST node this parser allocates. Supplied by
    /// the caller (caller-owns-`Bump`); the returned `Program<'arena>` borrows
    /// from it. `&'arena Bump` is `Copy`, so `self.alloc(owned)` and
    /// `self.arena.alloc(self.parse_x()?)` (even while `&mut self` is held — the
    /// field read borrows the `Bump`, not `self`) both work directly; lift it into a
    /// local (`let arena = self.arena;`) only when several allocations in one method
    /// share it.
    arena: &'arena Bump,
    source: &'a str,
    lexer: Lexer<'a>,
    /// The current token's classification + span as the lexer's 16-byte POD,
    /// stored in place so `advance()` has the lexer write it directly
    /// (`self.lexer.next_token_into(&mut self.current)`) with no intermediate
    /// `Token` scattered into separate scalar fields. Every other writer assigns a
    /// whole token, except the `>>` / `>>>` / `<<` splits, which narrow it in place
    /// (`start` + `kind`).
    /// The rare decoded value rides out-of-band in `current_decoded` (escape paths
    /// only), mirroring the lexer's split.
    current: Token,
    /// Decoded string/identifier value for the current token (escape paths only),
    /// copied into the AST arena at receipt so it is a `Copy` `&'arena str` rather
    /// than an owned `String` — the lexer decodes into a reused scratch buffer and
    /// the parser arena-copies it immediately, so no per-literal `String` survives.
    current_decoded: Option<&'arena str>,
    /// Single-token lookahead slot, stored as the 16-byte `Token` POD with its
    /// decoded value out-of-band in `peek_decoded` (mirroring the `current` /
    /// `current_decoded` split). Consuming the peek is then a direct `Token` copy
    /// into `current` with no intermediate lookahead struct to reassemble.
    peek: Option<Token>,
    peek_decoded: Option<&'arena str>,
    base_offset: usize, // Offset in full source (for embedded expressions)
    /// Comments collected during parsing, gathered directly in the AST arena
    /// (`Comment` is a `Copy` POD, so bumpalo's no-`Drop` rule holds). Handed to
    /// consumers as an `&'arena [Comment]` slice via `take_comments`, so the
    /// warm binding loops (`reset()`-reused arenas) never malloc for comments.
    comments: BumpVec<'arena, Comment>,
    /// True if a line terminator occurred between the previous token and current token.
    /// Used for ASI (Automatic Semicolon Insertion).
    had_line_terminator: bool,
    /// End position of the previous token (before current). Used for span calculation
    /// when ASI inserts a semicolon.
    prev_end: usize,
    /// Whether a top-level `as` is TypeScript's assertion operator. Set per partial
    /// parse from a [`TopLevelAs`] policy — false only where the host grammar spells its
    /// own separator `as` (`{#each items as pattern}`), never as a blanket
    /// "Svelte template" rule (`{#await p as T then v}` keeps it) — and only at the
    /// head's own level: a grouping delimiter (`grouping_depth`) or a body
    /// ([`Parser::with_body_frame`]) is where the separator cannot sit.
    ///
    /// `satisfies` is deliberately NOT gated by this: no host separator collides with it,
    /// so it is an assertion in every context.
    top_level_as_is_assertion: bool,
    /// Nesting depth inside grouping delimiters (`(...)`, `[...]`, `{...}`, `${...}`),
    /// maintained by [`Parser::enter_grouping`] / [`Parser::exit_grouping`].
    /// Used to disambiguate context-sensitive keywords inside nested expressions:
    /// - `as`: always a type assertion when depth > 0, even when
    ///   `top_level_as_is_assertion` is false (Svelte `#each` partial parsing)
    /// - `in`: a binary operator once the depth rises above [`Parser::no_in_depth`],
    ///   even when `allow_in` is false (for-loop header parsing)
    ///
    /// ⚠️ A reading of this counter is meaningless without a **baseline**, and the
    /// two consumers above use different ones — a literal `0` for `as` (that region
    /// opens at the parse root, where a fresh `Parser` starts at 0) and
    /// `no_in_depth` for `in` (that region opens mid-parse, at whatever depth the
    /// enclosing expression had reached). Copying one gate's baseline to the other
    /// is the bug this split exists to prevent.
    grouping_depth: u32,
    /// The parse's nesting against `tsv_lang`'s nesting limit, in wire levels, and the
    /// deepest level reached ([`DepthBudget`]) — every level but the grouping delimiters',
    /// which [`Parser::grouping_depth`] counts and the limit is tested beside. Seeded by an
    /// embedded parse with the host markup's nesting, so a Svelte document's budget is
    /// document-wide. Every level entered is left on every path out ([`Parser::nested`]).
    pub(crate) depth: DepthBudget,
    /// The open frame's spine count against `tsv_lang`'s spine limit ([`SpineCount`]):
    /// added to by every link ([`Parser::spine_link`]), framed where siblings can run long
    /// ([`Parser::chain`], [`Parser::statement_list`]). A [`Checkpoint`] carries it, so a
    /// rewind cannot leave what an abandoned branch counted.
    spine: SpineCount,
    /// What the link pricing's spine walks found past their bound, carried from link to link
    /// ([`SpineMemo`]).
    spine_memo: SpineMemo,
    /// When `true`, grouping parens `(expr)` are preserved as an internal
    /// `ParenthesizedExpression` node instead of being discarded. Off by default
    /// (matching acorn/Svelte, whose public AST is paren-free); enabled only for
    /// the `{#snippet}`-parameter sub-parse, where Svelte parses with acorn's
    /// `preserveParens: true` and skips `remove_parens`. Set via
    /// `crate::__private::parse_embedded_preserve_parens`.
    pub(crate) preserve_parens: bool,
    /// Set when [`Parser::preserve_parens`] wrapped at least one grouping pair in a
    /// `ParenthesizedExpression` — read by `crate::__private::parse_embedded_preserve_parens`,
    /// whose caller then owes the paren-free tree a parse of its own. Never cleared, so a pair a
    /// speculative parse built and a rewind abandoned leaves it set: an over-report costs that
    /// caller one redundant parse and is never a wrong answer.
    pub(crate) preserved_a_paren: bool,
    /// When `true`, every discarded grouping paren is recorded in
    /// [`Parser::grouping_parens`]. Set only while [`Parser::parse_binding_pattern`] reads
    /// its pattern as an array/object literal, the one place a paren the internal AST
    /// drops still decides the verdict: a binding pattern admits no parenthesized target.
    /// A function, class or arrow block body inside the pattern clears it
    /// ([`Parser::with_body_frame`]), since no paren there can wrap one of the pattern's
    /// targets; the rest of the pattern's nesting records too — an arrow's concise body,
    /// a default's own grouping — harmlessly, as an entry matches only a target whose own
    /// span it wraps.
    record_grouping_parens: bool,
    /// The grouping parens discarded while [`Parser::record_grouping_parens`] was set,
    /// in parse order — acorn's `parenthesizedBind`, kept as a list because tsv refines
    /// the literal after the parse instead of threading a record through it. Read and
    /// truncated by [`Parser::parse_binding_pattern`]; never reaches the wire.
    grouping_parens: Vec<GroupingParen>,
    /// True when parsing inside `declare namespace`/`declare module` (acorn/babel
    /// `inAmbientContext`). Relaxes a few ambient-only grammar rules — notably a
    /// single trailing comma after a rest parameter is tolerated throughout the
    /// subtree (see the rest-comma checks in `parameters.rs`/`types.rs`). It does NOT
    /// force functions bodiless — a plain `function f() {}` inside a `declare
    /// namespace` is an ordinary function declaration (its ambient implementation
    /// error is deferred to diagnostics).
    in_ambient_context: bool,
    /// Stored lexer error from peek_kind(). Returned on next advance() call.
    /// This ensures lexer errors propagate even when peek swallows them.
    lexer_error: Option<Error>,
    /// Whether a line terminator (including before/inside comments drained
    /// during the peek) precedes the cached peek token. Only meaningful while
    /// `peek` is `Some`; consumed by `advance_inner()`.
    peek_had_line_terminator: bool,
    /// Whether to allow `in` as a binary operator.
    /// Set to false when parsing for-loop headers to distinguish `for (x in y)` from expressions.
    allow_in: bool,
    /// The [`Parser::grouping_depth`] at which the current `[~In]` region began —
    /// the baseline the `in`-is-a-binary-operator gate compares against, so the
    /// question it asks is "has a grouping opened **since this region
    /// began**?" rather than "is any grouping open anywhere?". Only meaningful
    /// while `allow_in` is false; set (save/restore) by [`Parser::with_no_in`],
    /// which opens a region at a for header's expression head and at each of its
    /// declaration's initializers. A plain `== 0` test would read the
    /// enclosing expression's delimiters — `fn(function () { for (k in o) {} })`
    /// parses its header at depth 1 — and take the for-in separator for a
    /// relational `in`.
    no_in_depth: u32,
    /// Whether the parse is inside a `for` header's expression head or declaration
    /// initializer, nested functions included — the region over which the printer
    /// parenthesizes every `in` binary (`Printer::in_for_init`), so that each `in` link
    /// there is walked by re-entering the expression printer
    /// ([`Parser::binary_link_units`]). Set (save/restore) by [`Parser::with_no_in`].
    in_for_header: bool,
    /// The innermost open position whose bare assignment prints without the pair the
    /// printer gives an assignment elsewhere ([`Parser::pair_free_root`], save/restore):
    /// where it starts, and how its expression ends.
    pair_free_root: Option<(usize, RootEnd)>,
    /// The [`Parser::grouping_depth`] at which the innermost open conditional
    /// **consequent** began, or `None` outside one — tsc's
    /// `allowReturnTypeInArrowFunction` flag, `Some` where tsc passes `false`.
    ///
    /// In a consequent a `:` after a parenthesized arrow head may be the
    /// conditional's own (`a ? (b) : c => d` is `a ? b : (c => d)`), so a
    /// parenthesized arrow there may keep a return-type annotation only when a
    /// second `:` follows the whole arrow; [`Parser::parse_arrow_or_rewind`]
    /// asks. Set by [`Parser::with_arrow_return_type_barred`] at the `?`, read
    /// through [`Parser::arrow_return_type_barred`] against the same baseline
    /// rule as `no_in_depth` — a grouping opened *since* the `?` is a fresh
    /// expression frame where tsc passes `true` again, so only the consequent's
    /// own depth is barred — and lifted by every body ([`Parser::with_body_frame`])
    /// and every `yield` argument, the two places tsc resets the flag without
    /// opening a delimiter, plus the head it commits to a signature outright
    /// (`Parser::parse_arrow_or_rewind`). It survives into an arrow's concise
    /// body, the conditional's alternate and an assignment's right side, which
    /// inherit it exactly as tsc threads the parameter through those three.
    arrow_return_type_barred_at: Option<u32>,
    /// The OPEN `<` regions — the one input of
    /// `BinaryExpression::may_close_type_arguments`, where the hazard, tsc's recovering
    /// list parse, is stated. What a region is, and where one ends: [`LtRegion`].
    ///
    /// Carried by [`Checkpoint`], since a speculative parse may open one.
    lt_regions: LtRegions,
    /// What [`Parser::lt_regions`] is reset to where a statement (or a class member)
    /// begins: the regions a **body** inherited. A statement's own regions die with it — a
    /// head's `<` says nothing about the body (`if (x < q) a > b`) — but a body written
    /// inside an open region is still inside it, tsc reading an arrow's block as a type
    /// literal and its `return (` as a method signature
    /// (`x < (() => { return (a > b); })`). [`Parser::with_lt_region_inherited`] hands the
    /// open regions down and restores both on the way out.
    lt_regions_statement_base: LtRegions,
    /// The `<` tokens (their offsets in [`Parser::source`]) that
    /// [`Parser::parse_type_arguments_or_rewind`] tried as a type-argument list and
    /// abandoned, each with the context it was read in — asked again at one of them in
    /// that context, it hands the `<` back at once.
    ///
    /// **Why it exists.** An expression inside a type inside a tried list is read by
    /// the abandoned list and again by the operator reading that replaces it (a type
    /// literal's computed key, an import type's options). A list tried inside such an
    /// expression would then be tried once per reading of every list around it, which
    /// doubles the work at each level of nesting; remembered, it is tried once.
    ///
    /// **Its contract.** An entry says *the list at this `<` fails past its first
    /// separator when read in this context*. The tokens from a `<` on are the same on
    /// every read, so the context is all a second read can differ in — and it does
    /// differ, because the reading that replaces an abandoned one may open or close a
    /// function scope over the same tokens: an arrow head is tried under the arrow's
    /// own function context and re-read as a grouped expression under the enclosing
    /// one, and a function type's parameter annotation, read under the enclosing
    /// context, is re-read as an arrow function's. So the key holds every flag the
    /// expressions in a list inherit ([`Parser::type_arguments_context_key`]), and a
    /// read in another context tries the list again.
    ///
    /// A list is abandoned a second way, whole: where the token after its `>` is one
    /// tsc's `canFollowTypeArgumentsInExpression` refuses and acorn-typescript does not,
    /// and tsc's comparison reading parses (`Parser::type_arguments_follower_settled`).
    /// That entry says the same thing — the `<` is the operator in this context — and is
    /// a fact about the same tokens.
    abandoned_type_argument_lists: BTreeSet<(u32, u8)>,
    /// The `<` tokens whose type-argument list was read whole, followed by a token only
    /// tsc refuses, and KEPT because tsc's comparison reading does not parse
    /// (`Parser::type_arguments_follower_settled`), each with the context it was read in
    /// — read again at one of them in that context, the list is kept without asking. The
    /// twin of [`Parser::abandoned_type_argument_lists`]'s whole-list entries, and for the
    /// same reason: the comparison reading is a parse of everything after the `<`, which
    /// holds any list nested there, so unremembered each answer would be asked once per
    /// reading of every list around it.
    type_argument_lists_kept: BTreeSet<(u32, u8)>,
    /// Whether a whole type-argument list followed by a token only tsc refuses is put to
    /// tsc's comparison reading at all (`Parser::parse_type_arguments_or_rewind`). Off only
    /// in the re-parse [`parse_retrying_acorn_followers`] runs where tsc rejects the text,
    /// which reads every such list as acorn-typescript does.
    tsc_followers: bool,
    /// Whether this parse gave a whole list up to tsc's comparison reading
    /// ([`Parser::abandoned_type_argument_lists`]'s whole-list entries) — the reading the
    /// acorn re-parse would undo, so without one there is nothing to re-parse for.
    gave_up_list_to_tsc_follower: bool,
    /// Whether this parse KEPT a whole list past a follower only tsc refuses
    /// ([`Parser::type_argument_lists_kept`]) — tsc's comparison does not parse there, so
    /// tsc rejects the text, which earns a parse that also gave a list up the acorn
    /// re-parse even where it succeeded.
    ///
    /// Neither flag is rewound: they are facts about the tokens, as the sets are, and one
    /// set inside an abandoned speculation can only over-report.
    kept_list_past_tsc_follower: bool,
    /// The error of the abandoned type-argument list that reached furthest into the
    /// source, kept for the case where the operator reading fails too: the parse then
    /// reports whichever error reached further
    /// ([`Parser::prefer_abandoned_type_arguments_error`]). Carried by [`Checkpoint`],
    /// so a list abandoned inside a parse that is itself abandoned leaves nothing
    /// behind.
    abandoned_type_arguments_error: Option<Error>,
    /// Where each decorated parameter property's decorator run begins (its first `@`),
    /// once read. A parameter property's decorators sit one wire level deeper than a plain
    /// parameter's — on the binding inside the `TSParameterProperty` — and a run is parsed
    /// before the modifier that says which one it is, so the first read of a run that turns
    /// out to belong to a property is rewound and read again with that level charged
    /// ([`Parser::nested`]); read again at an offset here, the run is charged up front. A
    /// fact about the tokens, so it survives every rewind, and it keeps the re-reads to one
    /// per run however deep such parameters nest. Sorted, so a lookup is a binary search over
    /// contiguous memory; a run is first read in source order, so an insert is a push except
    /// past a rewind.
    decorated_parameter_properties: Vec<u32>,
    /// The syntactic goal symbol (`Script` vs `Module`) this parse runs against.
    /// Fixed for the whole parse — embedders (Svelte) and the standalone
    /// `parse`/`format` default to `Module`; `parse_with_goal` overrides it.
    goal: Goal,
    /// The `[Await]` grammar context. `true` (`[+Await]`) inside an async
    /// function/arrow/method/generator's params or body, a class static
    /// initialization block, a `for await` head, and — by default — module top
    /// level; reset to `false` (`[~Await]`) on entering a non-async
    /// function-like scope, and at Script top level. When `false`, `await` is
    /// not an await-expression: under `Goal::Script` it is an ordinary
    /// identifier (`await_is_identifier`), under `Goal::Module` it is reserved.
    in_await: bool,
    /// The `[Await]` context this position would have under `Goal::Module`: `true` at
    /// top level, the enclosing function's own `is_async` inside one — replaced and
    /// restored beside `in_await` by [`Parser::with_fn_context`]. At `Goal::Script`,
    /// where `in_await` is `false` at top level, it is what says a name `await` stands
    /// where a module would read an await expression, and a `for await` where a module
    /// would take the loop (`parse_for_statement`'s goal gate).
    in_await_if_module: bool,
    /// Where the same-line token after the latest such name `await` starts — the
    /// operand a module would have read. A Script error reported exactly there died
    /// only because `await` is a name at this goal, so [`Parser::parse`] marks it a
    /// goal gate for the format fallback (`Error::is_goal_gated`).
    await_name_operand: Option<usize>,
    /// Whether the code being parsed is **strict**. Seeded from the goal — Module
    /// code is always strict, Script code starts sloppy — and turned on (never off)
    /// by a `"use strict"` directive prologue, by entering a class, and by
    /// inheritance into every nested scope. It is a property of the source text,
    /// not of the goal: unlike `[Await]`/`[Yield]` it is never *cleared* going
    /// inward, so its scopes save-and-restore rather than replace
    /// ([`Parser::with_strict_scope`]).
    ///
    /// It gates the strict-mode rules the parser enforces, and this is where that list
    /// is kept — every other mention names this field rather than re-spelling it. The
    /// spec words each as a Static Semantics early error (*IsStrict(this production)*;
    /// only the informative Annex C restates the two literal rules as disallowed
    /// productions), which the reject-vs-defer line would defer; they reject because
    /// tsc reports all of them wherever it reads the file: its parser rejects the two
    /// literal rules (TS1121 / TS1489, TS1487 / TS1488), and its binder reports a strict
    /// `with` (TS1101) among the grammar errors it raises even in an unchecked
    /// JavaScript file (acorn rejects all of them too):
    ///
    /// - the **leading-zero numeric literals** (`010`, `08`), read by
    ///   `parse_number_or_bigint_literal` at the moment the token becomes a node;
    /// - the **legacy string escapes** (`'\7'`, `'\08'`, `'\8'`), read by
    ///   `Parser::extract_string_cooked` — the one seam every string literal is
    ///   consumed through — and re-read over a body's earlier prologue literals when a
    ///   `"use strict"` directive turns it strict (`Parser::note_directive`);
    /// - the **`with` statement**, read at its keyword by the statement dispatch.
    ///   `with` stays a `ReservedWord` in every mode, so only the statement moves.
    ///
    /// Each is read at consumption, so the lexer stays mode-free and a peeked token is
    /// never graded under the wrong mode. The other strict-mode **early errors**
    /// (duplicate parameters, reserved words as binding names, an assignment to `eval`)
    /// are a separate, deferred question: they parse under every mode and belong to the
    /// diagnostics layer.
    strict: bool,
    /// The `[Yield]` grammar context. `true` (`[+Yield]`) inside a generator
    /// function's params **and** body; reset to `false` (`[~Yield]`) on entering
    /// any non-generator function-like scope (a plain function, an arrow, a class
    /// static block or field initializer) and at top level. Unlike `[Await]` it
    /// is never goal-driven — a generator is marked by `*`, not by module vs
    /// script. It gates the bare-`yield`-operand guard (`is_bare_assignment_head`):
    /// a `yield` expression can only be a complete `AssignmentExpression` that no
    /// operator extends where `yield` is actually a `YieldExpression`, i.e. in
    /// `[+Yield]`. Outside a generator `yield` is a (deferred) reserved-word
    /// identifier, so the guard must not fire — see the guard in `expression.rs`.
    in_yield: bool,
    /// Whether the type grammar disallows function/constructor types at the
    /// current position: a union/intersection constituent (after `|`/`&`,
    /// including the leading-operator forms) or a type-operator operand
    /// (`keyof`/`unique`/`readonly`). TS (and acorn-typescript) admit
    /// `FunctionType`/`ConstructorType` only at full-type positions, so at these
    /// operand positions a `(` is always a parenthesized type — a following `=>`
    /// belongs to an enclosing construct (e.g. the enclosing arrow function's own
    /// `=>` in `(): A & (B) => x`) — and `new () => T` / `<T>() => U` are syntax
    /// errors (`A & () => x` must be written `A & (() => x)`). Set by the
    /// constituent/operand parses in `types.rs`; cleared at every full-type
    /// descent (`parse_type`), so nested positions (type arguments, tuple
    /// members, object-type members, conditional branches, parenthesized inners)
    /// parse function types greedily again.
    fn_type_disallowed: bool,
    /// Whether the type grammar disallows conditional types at the current
    /// position: the extends clause of a conditional type and the constraint of
    /// a constrained `infer` (acorn-typescript's
    /// `inDisallowConditionalTypesContext`). Read by the constrained-infer
    /// parse: at a disallow position `infer U extends C ? …` keeps `C` as the
    /// constraint (the `?` belongs to the enclosing conditional); at an allow
    /// position the same tokens are a conditional whose check is the bare
    /// `infer U` (see `pending_conditional_extends`). Cleared at every
    /// full-type descent (`parse_type`), matching acorn's allow-context resets
    /// (parenthesized inners, tuple/object members, type arguments, and — via
    /// its explicit signature wrapper — function/constructor-type params and
    /// returns).
    conditional_type_disallowed: bool,
    /// Hand-off from the constrained-infer parse to `parse_type`: when
    /// `infer U extends C` at an allow-conditional position is directly
    /// followed by `?`, the already-parsed `C` re-binds as the extends clause
    /// of a conditional whose check is the bare `infer U` (acorn rolls back
    /// its constraint tryParse and re-parses `extends C` at the conditional
    /// level; this hand-off reproduces that without re-lexing). Set only when
    /// the current token is `?`; consumed by the innermost enclosing
    /// `parse_type`, which nothing can precede (every intermediate
    /// union/intersection/array/operand loop breaks on `?`).
    pending_conditional_extends: Option<&'arena TSType<'arena>>,
}

impl<'a, 'arena> Parser<'a, 'arena> {
    /// Allocate a single AST node in the arena, returning a shared `&'arena`
    /// reference (replaces `Box::new`). Zero-copy: `Bump::alloc` moves the value
    /// into arena memory; the mut→shared reborrow is implicit.
    #[inline]
    fn alloc<T>(&self, val: T) -> &'arena T {
        self.arena.alloc(val)
    }

    /// A growable vector that builds AST-node collections **directly in the
    /// arena** — the preferred way to gather children. Build it in the parse
    /// loop, then `.into_bump_slice()` to store the field (zero-copy: the buffer
    /// is already arena-owned; `into_bump_slice` just hands it back). Carries its
    /// own `Copy` `&'arena Bump`, so pushing `self.parse_x()?` inside the loop
    /// does NOT borrow `self` — no `&mut self` conflict.
    #[inline]
    fn bvec<T>(&self) -> BumpVec<'arena, T> {
        BumpVec::new_in(self.arena)
    }

    /// Copy the lexer's just-produced decoded value (escape paths only) into the
    /// AST arena, yielding a `Copy` `&'arena str`. The lexer decodes into a reused
    /// scratch that the next lex overwrites, so this runs immediately after each
    /// lex; `None` for the common escape-free token. One copy into the arena — the
    /// same copy the old owned-`String` path made when it stored the value, now the
    /// only allocation on the escape path.
    ///
    /// Only the test inlines; the copy is [`Parser::copy_decoded_to_arena`]'s. Inlined,
    /// the bump allocation and its `memcpy` call kept two callee-saved registers live in
    /// [`Parser::advance_inner`], which then saved and restored them on every token.
    #[inline]
    fn decoded_to_arena(&self) -> Option<&'arena str> {
        if self.lexer.decoded_str().is_some() {
            self.copy_decoded_to_arena()
        } else {
            None
        }
    }

    /// [`Parser::decoded_to_arena`]'s copy, for the rare token that decoded an escape.
    #[cold]
    #[inline(never)]
    fn copy_decoded_to_arena(&self) -> Option<&'arena str> {
        self.lexer
            .decoded_str()
            .map(|s| -> &'arena str { self.arena.alloc_str(s) })
    }

    /// Allocate the binding `extra` for a typed identifier carrying `ta`: a type
    /// annotation and no decorators. Callers thread the optionality
    /// (`type_annotation.map(|ta| self.typed_extra(ta))`); decorators, when
    /// present, are folded in separately by the parameter-list caller
    /// (`attach_param_decorators`).
    #[inline]
    fn typed_extra(&self, ta: TSTypeAnnotation<'arena>) -> &'arena IdentifierParamExtra<'arena> {
        self.alloc(IdentifierParamExtra {
            type_annotation: Some(ta),
            decorators: None,
        })
    }

    /// Create a parser of `source` at `base_offset` against `goal`, not yet
    /// [primed](Parser::prime) — the one constructor, which every parse reaches through
    /// [`parse_retrying_acorn_followers`]. `base_offset` is where `source` sits in the
    /// document it was cut from (a Svelte `<script>` or template expression; `0`
    /// standalone), added to every span. Embedded parses are always `Goal::Module` (a
    /// Svelte `<script>` is a module); only the standalone entry points name `Script`.
    ///
    /// Infallible, and the first token is not lexed here: `current` holds an empty `Eof`
    /// placeholder until [`Parser::prime`] replaces it. The split is what lets the state be
    /// built where it lives. A constructor that lexes has to return `Result<Self, _>`, which
    /// comes back through a temporary its caller then copies whole into its own local, and
    /// the lexer it advances is built in a stack temporary of its own and copied in once the
    /// token is read. Returned as a plain `Self`, every field is written straight into the
    /// caller's local, and `prime` lexes into the parser's own lexer and `current`, as
    /// [`Parser::advance`] does.
    ///
    /// `#[inline(never)]`: out of line it is a run of stores through the caller's pointer
    /// and no frame of its own, where each monomorphized copy of the driver it would inline
    /// into — one per parse entry point, each calling it twice — carries its own copy of
    /// those stores.
    #[inline(never)]
    fn new(source: &'a str, base_offset: usize, goal: Goal, arena: &'arena Bump) -> Self {
        Self {
            arena,
            source,
            // The lexer scans `source` (the island) but reports errors against the document
            // it sits in, so it carries the same `base_offset` the spans are shifted by.
            lexer: Lexer::at_offset(source, base_offset),
            current: Token {
                kind: TokenKind::Eof,
                start: 0,
                end: 0,
            },
            current_decoded: None,
            peek: None,
            peek_decoded: None,
            base_offset,
            comments: BumpVec::new_in(arena),
            had_line_terminator: false, // No line terminator before first token
            prev_end: 0,
            top_level_as_is_assertion: true, // Enable by default (TypeScript context)
            grouping_depth: 0,               // Not inside any grouping delimiters
            depth: DepthBudget::at(0),       // An embedded parse seeds the host's nesting
            spine: SpineCount::default(),    // No link counted yet
            spine_memo: SpineMemo::default(), // No long walk taken yet
            preserve_parens: false,          // Discard grouping parens (paren-free public AST)
            preserved_a_paren: false,        // No pair wrapped yet
            record_grouping_parens: false,   // Only while a binding pattern is read
            grouping_parens: Vec::new(),     // Filled only while that flag is set
            in_ambient_context: false,       // Not in declare namespace/module
            lexer_error: None,               // No stored lexer error
            peek_had_line_terminator: false, // No peek cached yet
            allow_in: true,                  // Allow `in` binary operator by default
            in_for_header: false,
            pair_free_root: None,
            no_in_depth: 0,                    // Only read while `allow_in` is false
            arrow_return_type_barred_at: None, // Not inside a conditional consequent
            lt_regions: LtRegions::default(),  // No `<` region open
            lt_regions_statement_base: LtRegions::default(), // The top level inherits none
            abandoned_type_argument_lists: BTreeSet::new(), // No list tried yet
            type_argument_lists_kept: BTreeSet::new(), // Nor kept past a follower
            tsc_followers: true,               // tsc's reading, until a failure retries
            gave_up_list_to_tsc_follower: false, // Nothing given up yet
            kept_list_past_tsc_follower: false, // Nor kept
            abandoned_type_arguments_error: None,
            decorated_parameter_properties: Vec::new(), // No property read yet
            goal,
            // Module top level is `[+Await]` (`ModuleItem[+Await]`); Script top
            // level is `[~Await]` (`ScriptBody[~Await]`).
            in_await: matches!(goal, Goal::Module),
            // what `in_await` would be under `Goal::Module`, whose top level is `[+Await]`
            in_await_if_module: true,
            await_name_operand: None,
            // Module code is strict by definition (ecma262 sec-strict-mode-code);
            // Script code is strict only once a `"use strict"` prologue says so.
            strict: matches!(goal, Goal::Module),
            // Top level is `[~Yield]` in both goals — a generator scope is entered
            // only via `*` on a function/method (see `with_fn_context`).
            in_yield: false,
            fn_type_disallowed: false, // Top level is a full-type position
            conditional_type_disallowed: false, // Top level allows conditional types
            pending_conditional_extends: None,
        }
    }

    /// Lex the first token into `current`, collecting the comments ahead of it — the step
    /// the constructor leaves to its caller ([`Parser::new`] says why), owed exactly once
    /// before anything reads a token.
    ///
    /// The comment drain records a line terminator it crosses, as it does between two
    /// tokens; ahead of the first token there is no previous token for one to separate
    /// it from, so the flag is cleared again.
    pub(crate) fn prime(&mut self) -> Result<(), Error> {
        self.lexer.next_token_into(&mut self.current)?;
        self.current_decoded = self.decoded_to_arena();
        self.collect_comments()?;
        self.had_line_terminator = false;
        Ok(())
    }

    pub(super) fn advance(&mut self) -> Result<(), Error> {
        // Check for stored lexer error from peek_kind() - propagate it now
        if let Some(err) = self.lexer_error.take() {
            return Err(err);
        }
        self.advance_inner()
    }

    /// The token step of [`Parser::advance`], once no lexer error is held back.
    fn advance_inner(&mut self) -> Result<(), Error> {
        // Save previous token's end position for ASI span calculation
        self.prev_end = self.current.end as usize;

        // Get next token (from peek cache or lexer)
        if let Some(peek) = self.peek.take() {
            // Direct 16-byte copy of the cached token POD — no field-by-field
            // reassembly or `usize`→`u32` conversion.
            self.current = peek;
            self.current_decoded = self.peek_decoded.take();
            // Recorded while populating the peek cache — includes line
            // terminators before/inside comments drained during the peek.
            self.had_line_terminator = self.peek_had_line_terminator;
        } else {
            // Write the lexed token straight into the current slot — `next_token_into`
            // writes through `&mut self.current` (disjoint from `&mut self.lexer`), so no
            // intermediate `Token` is returned through a stack slot, reloaded and
            // re-scattered here.
            self.lexer.next_token_into(&mut self.current)?;
            self.current_decoded = self.decoded_to_arena();
            self.had_line_terminator = self.lexer.had_line_terminator();
        }

        self.collect_comments()
    }

    /// Drain any `Comment` tokens at the current position into `self.comments`, leaving the current
    /// token at the first non-comment token. Shared by `advance_inner` and the regex relex path
    /// (`parse_primary_expression`), both of which land on a fresh token and must absorb any
    /// comments before the next consumer reads the current token.
    ///
    /// The common case — the current token is *not* a comment — is a single discriminant check that
    /// inlines into the hot `advance` pump; the drain loop itself is cold-outlined into
    /// `drain_comments` so it never bloats the inlined fast path.
    #[inline]
    pub(super) fn collect_comments(&mut self) -> Result<(), Error> {
        if matches!(self.current.kind, TokenKind::Comment { .. }) {
            self.drain_comments()
        } else {
            Ok(())
        }
    }

    /// The cold half of `collect_comments`: the current token is known to be a `Comment` on entry;
    /// drain it and any consecutive comments. `#[cold]` + `#[inline(never)]` keep it off the hot pump.
    #[cold]
    #[inline(never)]
    fn drain_comments(&mut self) -> Result<(), Error> {
        while let TokenKind::Comment {
            is_block,
            content_start,
        } = &self.current.kind
        {
            // ECMAScript spec: if a MultiLineComment contains one or more line terminators,
            // then it is replaced by a single line terminator for ASI purposes.
            // So block comments with newlines should set had_line_terminator.
            let (comment, has_line_terminator) = comment_from_token(
                self.source,
                self.current.start as usize,
                self.current.end as usize,
                *content_start as usize,
                *is_block,
                self.base_offset,
            );
            if has_line_terminator {
                self.had_line_terminator = true;
            }
            self.comments.push(comment);
            let token = self.lexer.next_token()?;
            self.update_current(token);
            // Also check line terminator in whitespace after comment
            if self.lexer.had_line_terminator() {
                self.had_line_terminator = true;
            }
        }

        Ok(())
    }

    // Helper methods for extract-then-advance pattern

    #[inline]
    pub(super) fn current_kind(&self) -> &TokenKind {
        &self.current.kind
    }

    /// Overwrite the current token's kind/start/end/decoded from a freshly lexed token, without
    /// the surrounding bookkeeping (`prev_end`, the line-terminator flag, comment collection).
    /// Used by `collect_comments` and by callers that resync the lexer themselves before reading —
    /// template continuation and the regex relex.
    #[inline]
    pub(super) fn update_current(&mut self, token: Token) {
        self.current = token;
        // `decoded` rides out-of-band on the lexer; the caller lexed `token` from
        // `self.lexer` immediately before this call, so drain it here.
        self.current_decoded = self.decoded_to_arena();
    }

    #[inline]
    pub(super) fn current_pos(&self) -> (usize, usize) {
        (
            self.current.start as usize + self.base_offset,
            self.current.end as usize + self.base_offset,
        )
    }

    /// Run `f` `units` wire levels deeper — the nesting half of the depth limit
    /// ([`DepthBudget`]), refused at the current token where it would pass
    /// `tsv_lang::NESTING_LIMIT`. `units` is at least the number of wire nodes the step puts
    /// on the path from the root, which is what the walks over the tree pay stack for. The levels
    /// are left on every path out, the error path included, since a speculative parse that
    /// fails is rewound and the parse goes on.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn nested<T>(
        &mut self,
        units: u32,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        if !self.depth.try_enter_beside(units, self.grouping_depth) {
            return Err(self.too_deep(DepthLimit::Nesting));
        }
        let result = f(self);
        self.depth.leave(units);
        result
    }

    /// Run `f` in a frame of the spine count ([`SpineCount::take`]): the links it adds
    /// ([`Parser::spine_link`]) count from zero, and the frame's count is handed up as the
    /// greater of it and its siblings'. Opened where siblings can run long — each element of
    /// a list after the first, each operand of an operator chain, a qualified name, a
    /// decorator, a class heritage — so their chains bound one path each rather than adding
    /// up; within a frame, every link adds up.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn chain<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let outer = self.spine.take();
        let result = f(self);
        self.spine.fold(outer);
        result
    }

    /// Run `f` — a loop over a list of statements — as the list: `levels` wire levels of
    /// nesting for its statements ([`Parser::nested`]; a statement in a list is counted
    /// here, once, rather than at each, with any levels its container would enter just
    /// for it), and a spine frame per statement, `f` handing each finished one
    /// to [`StatementFrame::next`], the list handing the greatest up. Sibling statements are
    /// so measured apart, which keeps one long chain from being charged to the statements
    /// around it.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn statement_list<T>(
        &mut self,
        levels: u32,
        f: impl FnOnce(&mut Self, &mut StatementFrame) -> Result<T, Error>,
    ) -> Result<T, Error> {
        self.nested(levels, |p| {
            let mut frame = StatementFrame {
                outer: p.spine.take(),
                statements: SpineCount::default(),
                closed: 0,
                outer_peak: p.depth.take_peak(p.grouping_depth),
                peak: 0,
            };
            let result = f(p, &mut frame);
            frame.next(p);
            p.spine.fold(frame.outer.max(frame.statements));
            p.depth.fold_peak(frame.outer_peak.max(frame.peak));
            result
        })
    }

    /// Open a list's spine frames ([`ListFrame`]): the list calls [`ListFrame::element`] as
    /// each element starts and [`ListFrame::close`] when it ends — on its success path; a
    /// failed parse is abandoned or rewound with the count restored from a checkpoint. A
    /// list of a few elements touches no count at all.
    #[inline]
    #[expect(clippy::unused_self)]
    pub(super) fn list_frame(&self) -> ListFrame {
        ListFrame {
            greatest: SpineCount::default(),
            peak: 0,
        }
    }

    /// Count one link of a left-nested chain — a binary operator, a member access, a call,
    /// an assertion, a type's `[]` — as `units` spine units, refused at the current token
    /// where the frame's count would pass `tsv_lang::SPINE_LIMIT`
    /// ([`SpineCount::try_link`]). A link costs [`LINK_OPERATOR`] units unless its walks
    /// spend more stack than an operator's: [`LINK_NON_NULL`], [`LINK_REENTRY`], [`LINK_TAG`],
    /// [`LINK_ASSERTION`], [`LINK_TYPE_SUFFIX`].
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn spine_link(&mut self, units: u32) -> Result<(), Error> {
        if self.spine.try_link(units, &self.depth) {
            Ok(())
        } else {
            Err(self.too_deep(DepthLimit::Spine))
        }
    }

    /// Count a pair the printer will add around a node the parse just built — a level of
    /// nesting in the format's output ([`SpineCount::try_pair`]), refused at the current
    /// token where that output would pass `tsv_lang::NESTING_LIMIT`, or its links
    /// `tsv_lang::SPINE_LIMIT` with the pair charged. Asked of the printer's own
    /// predicate wherever one can stack along a path
    /// ([`Parser::count_operand_pairs`], [`Parser::self_pair`]).
    #[inline]
    pub(super) fn printer_pair(&mut self) -> Result<(), Error> {
        self.spine
            .try_pair(&self.depth)
            .map_err(|limit| self.too_deep(limit))
    }

    /// Count a wire level the parse finds only above an operand it has already read — an
    /// assignment over its target — which no top-down [`Parser::nested`] charge can reach:
    /// the operand's deepest node sits a level lower than it was counted, so the frame's
    /// deepest nesting is raised to `operand_peak` — the frame's [`DepthBudget::peak`] once
    /// the operand was read, which holds the operand's own — plus one
    /// ([`DepthBudget::try_raise_peak`]). The right side parsed after
    /// the operand is not under the level, so a right-nested assignment chain is charged
    /// its own depth, not a level per assignment on top of it.
    #[inline]
    pub(super) fn level_above_operand(&mut self, operand_peak: u32) -> Result<(), Error> {
        self.depth
            .try_raise_peak(operand_peak + 1, &self.spine)
            .map_err(|limit| self.too_deep(limit))
    }

    /// Run `f` — the parse of an expression starting at the current token — as a pair-free
    /// root: a position where the printer writes a bare assignment without the pair it gives
    /// an assignment as a value nearly everywhere else (`f((a = b))`, `x = (a = b)`,
    /// `() => (a = b)`) — a statement's expression and a `for` header's own clause
    /// (`end`: [`RootEnd::BeforeAnyButComma`], [`RootEnd::ForClause`]), an assignment's right side
    /// ([`RootEnd::Anywhere`]) — or one where the author wrote the pair, a grouping paren
    /// ([`RootEnd::AtParenClose`]), counted as a level of nesting already.
    #[inline]
    pub(super) fn pair_free_root<T>(
        &mut self,
        end: RootEnd,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let outer = self.pair_free_root.replace((self.current_pos().0, end));
        let result = f(self);
        self.pair_free_root = outer;
        result
    }

    /// Count the pair the printer writes around a node that takes one wherever it stands
    /// as a value — an assignment, and an `in` binary inside a `for` header — unless the
    /// node, starting at `start` and ending at the current token, is the whole of the
    /// innermost pair-free root ([`Parser::pair_free_root`]). Decided as the node is built,
    /// with no pair counted and withdrawn: a pair counted at the bottom of a deep path and
    /// withdrawn above it would refuse a depth the printer's output never reaches.
    #[inline]
    pub(super) fn self_pair(&mut self, start: usize) -> Result<(), Error> {
        let whole_root = self.pair_free_root.is_some_and(|(root, end)| {
            root == start
                && match end {
                    RootEnd::Anywhere => true,
                    RootEnd::BeforeAnyButComma | RootEnd::ForClause => {
                        self.current.kind != TokenKind::Comma
                    }
                    RootEnd::AtParenClose => self.current.kind == TokenKind::ParenClose,
                }
        });
        if whole_root {
            Ok(())
        } else {
            self.printer_pair()
        }
    }

    /// Count the pairs the printer adds around a node's operands, each in its position — a
    /// binary's, an assertion's, a heritage, a `new` callee — where the source wrote none:
    /// the caller passes an operand only when it is bare, no grouping paren of the author's
    /// around it. Asked of the printer's own predicate (`printer::printer_adds_operand_pair`);
    /// an operand that counts a pair for itself ([`Parser::self_pair`]) is not counted again.
    ///
    /// Forced inline: it is asked at every operator, and almost every operand is answered by
    /// its kind alone, so the call site keeps that test and the rule stays out of line.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn count_operand_pairs(
        &mut self,
        left: Option<(&Expression<'_>, ParenContext)>,
        right: Option<(&Expression<'_>, ParenContext)>,
    ) -> Result<(), Error> {
        for (operand, ctx) in [left, right].into_iter().flatten() {
            if crate::printer::printer_adds_operand_pair(operand, ctx, self.in_for_header) {
                self.printer_pair()?;
            }
        }
        Ok(())
    }

    /// Count the pairs the printer adds around a binary's operands where the source wrote
    /// none ([`Parser::count_operand_pairs`]): a left operand is bare where it starts the
    /// binary's own extent (`expr_start`), a right one where it ends at the last token
    /// read. Out of line: most operands take no pair by kind, which the caller asks first
    /// (`printer::operator_operand_takes_no_pair`).
    #[inline(never)]
    pub(super) fn binary_operand_pairs(
        &mut self,
        operator: BinaryOperator,
        left: &Expression<'_>,
        right: &Expression<'_>,
        expr_start: usize,
    ) -> Result<(), Error> {
        let left_bare = expr_start == left.span().start as usize;
        let right_bare = right.span().end as usize == self.prev_token_end();
        self.count_operand_pairs(
            left_bare.then_some((
                left,
                ParenContext::BinaryLeft {
                    parent_op: operator,
                },
            )),
            right_bare.then_some((
                right,
                ParenContext::BinaryRight {
                    parent_op: operator,
                },
            )),
        )
    }

    /// Count the pair the printer writes around a sequence (`(a, b);`, `return (a, b);`,
    /// `` `${(a, b)}` ``, `a[(b, c)]`) — every sequence takes one but the whole of a `for`
    /// header's init or update clause and the whole of a grouping paren the author wrote
    /// (counted as a level already). `start` is where the sequence starts, the current
    /// token the one after it.
    #[inline]
    pub(super) fn sequence_pair(&mut self, start: usize) -> Result<(), Error> {
        let whole_root = self.pair_free_root.is_some_and(|(root, end)| {
            root == start
                && match end {
                    RootEnd::ForClause => true,
                    RootEnd::AtParenClose => self.current.kind == TokenKind::ParenClose,
                    RootEnd::Anywhere | RootEnd::BeforeAnyButComma => false,
                }
        });
        if whole_root {
            Ok(())
        } else {
            self.printer_pair()
        }
    }

    /// Count the pairs the printer adds around a prefix operator's `operand` — a unary's,
    /// a prefix update's, an `await`'s, an angle-bracket assertion's, a spread's — in its
    /// position `ctx`, each a level of the output's nesting. `operand_token` is the start of
    /// the operand's first token, an author's `(` included.
    ///
    /// The count is the pairs the printer may write there, less the pairs the author wrote:
    /// what it writes is a function of the tree (and its comments), which formatting keeps,
    /// so on a format's output — whose authored pairs are the ones it wrote — the count is
    /// none, and the output's reparse counts no more than the input's parse did. The pairs
    /// it may write:
    ///
    /// - the one the operand's position takes, asked of the printer's predicate
    ///   (`printer::printer_adds_operand_pair`; `-(-x)`, `<T>(<U>x)`, `...(a || b)`) —
    ///   for an operand the author parenthesized, an assignment's or a sequence's too, which
    ///   count their own only where bare ([`Parser::self_pair`], [`Parser::sequence_pair`]);
    /// - `holder`, the unary operator's comment holder (the operator ending at `holder.0`,
    ///   the node at `holder.1`): a comment between the operator and the operand, or
    ///   between the operand and the node's end inside an author's pair, makes the printer
    ///   wrap the operand in a pair of its own (`!(/* c */ x)`), read over every comment
    ///   there, owned or not;
    /// - `shell`, the pair an angle-bracket assertion breaks its operand into
    ///   (`<T>(⏎\tx⏎)`), counted whether or not the cast breaks.
    ///
    /// Inline, it answers the commonest operand: one no operator position pairs by kind
    /// (`printer::operator_operand_takes_no_pair`), bare or in the author's pairs — less an
    /// assignment or a sequence, which take one there — with no shell to count and no
    /// comment past the operator to make a holder.
    #[inline]
    pub(super) fn count_prefix_operand_pairs(
        &mut self,
        operand: &Expression<'_>,
        ctx: ParenContext,
        operand_token: usize,
        holder: Option<(usize, usize)>,
        shell: bool,
    ) -> Result<(), Error> {
        if !shell
            && ctx.is_operator_position()
            && !matches!(
                operand.kind,
                ExpressionKind::AssignmentExpression(_)
                    | ExpressionKind::SequenceExpression(_)
                    | ExpressionKind::ParenthesizedExpression(_)
            )
            && crate::printer::operator_operand_takes_no_pair(operand)
            && holder.is_none_or(|(operator_end, _)| {
                self.comments
                    .last()
                    .is_none_or(|c| (c.span.start as usize) < operator_end)
            })
        {
            return Ok(());
        }
        self.count_prefix_operand_pairs_by_rule(operand, ctx, operand_token, holder, shell)
    }

    /// [`Parser::count_prefix_operand_pairs`] past its inline answer.
    #[inline(never)]
    fn count_prefix_operand_pairs_by_rule(
        &mut self,
        operand: &Expression<'_>,
        ctx: ParenContext,
        operand_token: usize,
        holder: Option<(usize, usize)>,
        shell: bool,
    ) -> Result<(), Error> {
        // a wire-only parse keeps the author's pairs as nodes (`parse_preserve_parens`): they
        // are counted as the pairs they are, so it charges what the parse the printer reads
        // charges
        let mut operand = operand;
        while let ExpressionKind::ParenthesizedExpression(paren) = &operand.kind {
            operand = paren.expression;
        }
        let span = operand.span();
        let bare = span.start as usize == operand_token;
        let commented = holder.is_some_and(|(operator_end, node_end)| {
            self.has_comment_between(operator_end, span.start as usize)
                || self.has_comment_between(span.end as usize, node_end)
        });
        let position_pair = (!bare
            && matches!(
                operand.kind,
                ExpressionKind::AssignmentExpression(_) | ExpressionKind::SequenceExpression(_)
            ))
            || crate::printer::printer_adds_operand_pair(operand, ctx, self.in_for_header);
        let written = u32::from(position_pair) + u32::from(commented) + u32::from(shell);
        if written == 0 {
            return Ok(());
        }
        let authored = if bare {
            0
        } else {
            self.authored_pairs(operand_token, span.start as usize)
        };
        for _ in authored..written {
            self.printer_pair()?;
        }
        Ok(())
    }

    /// The grouping parens the author wrote in `[from, to)` (host offsets) — the run of
    /// `(` ahead of an operand the parser stripped them from, comments between them aside.
    pub(super) fn authored_pairs(&self, from: usize, to: usize) -> u32 {
        let bytes = self.source.as_bytes();
        let mut comment = self
            .comments
            .partition_point(|c| (c.span.start as usize) < from);
        let mut pos = from;
        let mut pairs = 0;
        while pos < to {
            if let Some(c) = self.comments.get(comment)
                && c.span.start as usize == pos
            {
                pos = c.span.end as usize;
                comment += 1;
                continue;
            }
            pairs += u32::from(bytes[pos - self.base_offset] == b'(');
            pos += 1;
        }
        pairs
    }

    /// Count the pair the printer writes around a `return` / `throw` argument that is a
    /// bare binary chain, once the chain breaks (`return (⏎\ta &&⏎\tb⏎);`, prettier's
    /// `printReturnOrThrowArgument`) — a level of the output's nesting. `argument_token` is
    /// the start of the argument's first token.
    #[inline]
    pub(super) fn restricted_argument_pair(
        &mut self,
        argument: &Expression<'_>,
        argument_token: usize,
    ) -> Result<(), Error> {
        if matches!(argument.kind, ExpressionKind::BinaryExpression(_))
            && argument.span().start as usize == argument_token
        {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// Count the pairs the printer adds around a conditional's `test` (the conditional
    /// starting at `expr_start`) and its `consequent` (its first token at
    /// `consequent_start`), each a level of the output's nesting: a bare conditional
    /// consequent's (`a ? (b ? c : d) : e`), and the clarity pairs around a bare test and
    /// branch (`(a ?? b) ? (c as T) : d`, [`Parser::ternary_branch_pair`]). Out of line,
    /// off the expression loop.
    #[inline(never)]
    pub(super) fn conditional_head_pairs(
        &mut self,
        test: &Expression<'_>,
        expr_start: usize,
        consequent: &Expression<'_>,
        consequent_start: usize,
    ) -> Result<(), Error> {
        if matches!(consequent.kind, ExpressionKind::ConditionalExpression(_))
            && consequent.span().start as usize == consequent_start
        {
            self.printer_pair()?;
        }
        if test.span().start as usize == expr_start && crate::printer::ternary_test_takes_pair(test)
        {
            self.printer_pair()?;
        }
        self.ternary_branch_pair(consequent, consequent_start)
    }

    /// Count the pair the printer adds around a conditional's bare branch for clarity
    /// (`a ? (b as T) : (c ?? d)`, `printer::ternary_branch_takes_pair`) — a level of the
    /// output's nesting. An assignment branch counts its own ([`Parser::self_pair`]).
    #[inline]
    pub(super) fn ternary_branch_pair(
        &mut self,
        branch: &Expression<'_>,
        branch_token: usize,
    ) -> Result<(), Error> {
        if branch.span().start as usize == branch_token
            && crate::printer::ternary_branch_takes_pair(branch)
        {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// Count the pair the printer writes around a function expression a chain starting at
    /// `start` calls or tags bare (`(function () {})()`, `` (function () {})`t` ``) — a level
    /// of the output's nesting, asked of the printer's predicate in `ctx`
    /// (`printer::printer_adds_operand_pair`). Only a chain's head can be one.
    #[inline]
    pub(super) fn function_head_pair(
        &mut self,
        head: &Expression<'_>,
        start: u32,
        ctx: ParenContext,
    ) -> Result<(), Error> {
        if matches!(
            head.kind,
            ExpressionKind::FunctionExpression(_) | ExpressionKind::ClassExpression(_)
        ) && head.span().start == start
            && crate::printer::printer_adds_operand_pair(head, ctx, self.in_for_header)
        {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// Count the pair the printer writes around an arrow's bare function return type
    /// (`(x): ((y) => T) =>`, whose second `=>` would read as the arrow's own) — a level of
    /// the output's nesting.
    #[inline]
    pub(super) fn arrow_return_pair(
        &mut self,
        return_type: Option<&TSTypeAnnotation<'_>>,
    ) -> Result<(), Error> {
        if return_type.is_some_and(|r| matches!(r.type_annotation, TSType::Function(_))) {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// Whether `operand`, read by a chain starting at `start`, is an instantiation the
    /// author wrote no pair around — one the printer parenthesizes where another type
    /// argument list follows it (`(f<T>)<U>`, `printer::instantiation_keeps_pair_before_type_args`,
    /// whose optional-chain exception this reads past: a pair counted the output lacks).
    #[inline]
    pub(super) fn is_bare_instantiation(operand: &Expression<'_>, start: u32) -> bool {
        matches!(operand.kind, ExpressionKind::TSInstantiationExpression(_))
            && operand.span().start == start
    }

    /// Count the pair the printer writes around a numeric literal a member access reads
    /// (`(1).toString()`, `printer::needs_parens`'s chain-base rule), where `object` —
    /// a chain's head starting at `start` — is one the author wrote bare.
    #[inline]
    pub(super) fn chain_base_pair(
        &mut self,
        object: &Expression<'_>,
        start: u32,
    ) -> Result<(), Error> {
        if matches!(object.kind, ExpressionKind::Literal(_))
            && object.span().start == start
            && crate::printer::printer_parenthesizes_chain_base(object)
        {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// Whether a comment starts in `[from, to)` (host offsets). The comments are collected
    /// in source order.
    ///
    /// A comment wholly inside a gap between two tokens is what the callers ask about, so a
    /// gap too narrow to hold one, or one past the last comment collected, holds none
    /// without a search.
    #[inline]
    fn has_comment_between(&self, from: usize, to: usize) -> bool {
        if to.saturating_sub(from) < Comment::MIN_SPAN_LEN as usize
            || self
                .comments
                .last()
                .is_none_or(|c| (c.span.start as usize) < from)
        {
            return false;
        }
        let i = self
            .comments
            .partition_point(|c| (c.span.start as usize) < from);
        self.comments
            .get(i)
            .is_some_and(|c| (c.span.start as usize) < to)
    }

    /// The spine units of a call or an instantiation on `operand`, and the call rule a `!`
    /// on it meets ([`Parser::non_null_link_units`]):
    /// [`LINK_REENTRY`] on a call, seen through any run of `!` and instantiations (`f()()`,
    /// `f()!()`, `f()!!!()`, `f()<T>()`) — the curried shapes the member-chain printer prints
    /// apart from the chain below them — or on a tagged template, which the member-chain
    /// printer takes for its chain's base and prints by re-entering the expression printer
    /// (`` a`t`() ``) — else [`LINK_SUBSCRIPT`].
    ///
    /// A run longer than [`SPINE_WALK_LINKS`] is walked past the bound by
    /// [`Parser::call_units_past`], so a run of `n` `!` costs `n` steps, not `n²`.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn call_link_units(&mut self, operand: &Expression<'_>) -> u32 {
        let mut inner = operand;
        let mut links = SPINE_WALK_LINKS;
        loop {
            match call_spine_step(inner) {
                ControlFlow::Continue(next) => inner = next,
                ControlFlow::Break(units) => return units,
            }
            links -= 1;
            if links == 0 {
                return self.call_units_past(inner);
            }
        }
    }

    /// [`Parser::call_link_units`]'s walk from `cut`, the node its bounded walk stopped at,
    /// answered by [`SpineMemo`] where the walk reaches the node the last such walk stopped
    /// at — one link below `cut` when the link before this one was a `!` or instantiation
    /// over it.
    #[inline(never)]
    fn call_units_past(&mut self, cut: &Expression<'_>) -> u32 {
        let mut inner = cut;
        let units = loop {
            if std::ptr::from_ref(inner).addr() == self.spine_memo.call_at {
                break self.spine_memo.call_units;
            }
            match call_spine_step(inner) {
                ControlFlow::Continue(next) => inner = next,
                ControlFlow::Break(units) => break units,
            }
        };
        self.spine_memo.call_at = std::ptr::from_ref(cut).addr();
        self.spine_memo.call_units = units;
        units
    }

    /// The spine units of a member access over `object`: [`LINK_REENTRY`] where `object` is
    /// a tagged template, the chain base the member-chain printer re-enters the expression
    /// printer for (`` a`t`.b ``), or where the first call down `object`'s spine may be one
    /// the printer prints whole, which a member over it prints over whole, re-entering too
    /// (`printer::call_may_print_whole`) — else [`LINK_SUBSCRIPT`].
    ///
    /// A spine longer than [`SPINE_WALK_LINKS`] is walked past the bound by
    /// [`Parser::spine_whole_past`], so a chain of `n` members costs `n` steps, not `n²`.
    ///
    /// Forced inline: it is asked of every member link, and the walk past the bound is
    /// outlined, so a call site keeps only the bounded walk.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn member_link_units(&mut self, object: &Expression<'_>) -> u32 {
        let whole = matches!(object.kind, ExpressionKind::TaggedTemplateExpression(_))
            || match crate::printer::spine_first_call_within(object, SPINE_WALK_LINKS) {
                Ok(call) => call.is_some_and(crate::printer::call_may_print_whole),
                Err(cut) => self.spine_whole_past(cut),
            };
        if whole { LINK_REENTRY } else { LINK_SUBSCRIPT }
    }

    /// Whether the first call down the spine from `cut`, the node
    /// [`Parser::member_link_units`]'s bounded walk stopped at, may be one the printer prints
    /// whole — answered by [`SpineMemo`] where the walk reaches the node the last such walk
    /// stopped at, one link below `cut` when the link before this one was a member or `!`
    /// over it.
    #[inline(never)]
    fn spine_whole_past(&mut self, cut: &Expression<'_>) -> bool {
        let mut node = cut;
        let whole = loop {
            if std::ptr::from_ref(node).addr() == self.spine_memo.whole_at {
                break self.spine_memo.whole;
            }
            match crate::printer::spine_first_call_within(node, 1) {
                Ok(call) => break call.is_some_and(crate::printer::call_may_print_whole),
                Err(next) => node = next,
            }
        };
        self.spine_memo.whole_at = std::ptr::from_ref(cut).addr();
        self.spine_memo.whole = whole;
        whole
    }

    /// Whether `call` is one the printer may print whole (`printer::call_may_print_whole`),
    /// answered inline for the commonest call — a callee that is no call (nor a `!` over
    /// one) and no sole template argument, which no rule there admits.
    #[inline]
    fn call_prints_whole(call: &Expression<'_>) -> bool {
        match &call.kind {
            ExpressionKind::CallExpression(c) => {
                (matches!(
                    c.callee.kind,
                    ExpressionKind::CallExpression(_) | ExpressionKind::TSNonNullExpression(_)
                ) || matches!(
                    c.arguments,
                    [argument] if matches!(
                        argument.kind,
                        ExpressionKind::TemplateLiteral(_)
                            | ExpressionKind::TaggedTemplateExpression(_)
                    )
                )) && crate::printer::call_may_print_whole(c)
            }
            _ => false,
        }
    }

    /// The spine units of a `!` over `operand`: the greatest of the rules a `!` meets —
    /// a curried call's ([`Parser::call_link_units`]), a member's
    /// ([`Parser::member_link_units`]) and its own ([`LINK_NON_NULL`]).
    #[inline]
    pub(super) fn non_null_link_units(&mut self, operand: &Expression<'_>) -> u32 {
        self.call_link_units(operand)
            .max(self.member_link_units(operand))
            .max(LINK_NON_NULL)
    }

    /// Top a call link up to [`LINK_REENTRY`] once its arguments are read, where they make
    /// `call` one the printer may print whole, re-entering the expression printer for its
    /// callee (a sole multi-line template argument — `printer::call_may_print_whole`). The
    /// link was charged [`Parser::call_link_units`] of the callee, read again here from the
    /// call (an instantiation the call lifted its list from is seen through there too)
    /// rather than carried across the argument list's parse.
    ///
    /// Forced inline: it is asked of every call, and almost every one fails the
    /// [`Parser::call_prints_whole`] test, so the call site keeps only that test.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn settle_call_link(&mut self, call: &Expression<'_>) -> Result<(), Error> {
        if Self::call_prints_whole(call)
            && let ExpressionKind::CallExpression(c) = &call.kind
        {
            let charged = self.call_link_units(c.callee);
            if charged < LINK_REENTRY {
                self.spine_link(LINK_REENTRY - charged)?;
            }
        }
        Ok(())
    }

    /// The spine units of a binary or logical `operator` over `left`: [`LINK_REENTRY`]
    /// where the binary-chain printer builds `left` as an operand of its own rather than
    /// flattening it into the chain (`a == b == c`, `a * b / c`, `a + b as T + c`) — asked
    /// of the printer's own predicate (`printer::binary_left_operand_reenters`), so the
    /// price follows the walk it prices — else [`LINK_OPERATOR`].
    #[inline]
    pub(super) fn binary_link_units(&self, operator: BinaryOperator, left: &Expression<'_>) -> u32 {
        // the predicate's own first test, inline: every other operand ends the spine
        if !matches!(
            left.kind,
            ExpressionKind::BinaryExpression(_)
                | ExpressionKind::TSAsExpression(_)
                | ExpressionKind::TSSatisfiesExpression(_)
        ) {
            return LINK_OPERATOR;
        }
        if crate::printer::binary_left_operand_reenters(operator, left, self.in_for_header) {
            LINK_REENTRY
        } else {
            LINK_OPERATOR
        }
    }

    /// The depth-limit error at the current token.
    #[cold]
    #[inline(never)]
    fn too_deep(&self, limit: DepthLimit) -> Error {
        Error::too_deep(limit, self.current_pos().0)
    }

    /// Convert a raw `source`-relative offset into an absolute `Span` coordinate:
    /// `base_offset`-shifted and narrowed to `u32`. Raw offsets index `self.source`
    /// (e.g. `self.current.start as usize`, a captured scan position); `Span` fields
    /// store the shifted `u32`. Centralizes the `(base_offset + pos) as u32` boundary
    /// cast — the `u32` sibling of `current_pos` (which stays `usize` for indexing).
    #[inline]
    pub(super) fn span_pos(&self, raw: usize) -> u32 {
        (self.base_offset + raw) as u32
    }

    /// The inverse of [`Parser::span_pos`]: an absolute `Span` coordinate back to a raw
    /// offset into `self.source`.
    ///
    /// Stored spans are **host** coordinates while `self.source` is the local (possibly
    /// embedded) slice, so a span read back as an index has to shift — indexing with one
    /// directly reads the wrong bytes under Svelte embedding, or past the slice end. The
    /// same hazard [`Parser::resolve_cooked`] names, and the reason a byte scan keyed on a
    /// node's span goes through here.
    ///
    /// A position BELOW the base is the wrong base, not a clamp: the saturation would hand
    /// back offset 0, where a byte scan simply finds nothing and reports no verdict —
    /// exactly the silent miss this function exists to prevent. Asserted rather than
    /// returned, since every caller holds a span this parser itself produced.
    #[inline]
    pub(super) fn local_pos(&self, span_pos: u32) -> usize {
        debug_assert!(
            span_pos as usize >= self.base_offset,
            "span position {span_pos} is below the parser's base offset {} — a host \
             coordinate from another parse, or a base that moved",
            self.base_offset,
        );
        (span_pos as usize).saturating_sub(self.base_offset)
    }

    /// Get the end position of the previously consumed token (with base_offset).
    ///
    /// Useful for determining where statements end after consuming optional tokens
    /// like semicolons (via ASI or explicit).
    #[inline]
    pub(super) fn prev_token_end(&self) -> usize {
        self.prev_end + self.base_offset
    }

    /// Consume an optional `?` marker, extending a binding's end to cover it.
    /// Returns `(present, end)`: when the `?` is eaten, `end` advances to
    /// `prev_token_end` (so a `?` with no following type annotation still
    /// extends the identifier span); otherwise `end` passes through unchanged.
    #[inline]
    pub(super) fn eat_optional_marker(&mut self, end: usize) -> Result<(bool, usize), Error> {
        Ok(if self.eat(TokenKind::Question)? {
            (true, self.prev_token_end())
        } else {
            (false, end)
        })
    }

    /// Get the raw end position (without base_offset) for lexer operations
    pub(super) fn current_raw_end(&self) -> usize {
        self.current.end as usize
    }

    /// Resolve a `StringCooked` during parse. Stored spans are in **host**
    /// coordinates (`base_offset` added), but `self.source` is the local
    /// (possibly embedded) slice — so the span shifts back before slicing.
    /// Resolving a host span directly against `self.source` reads the wrong
    /// bytes under Svelte embedding, or panics past the slice end.
    pub(super) fn resolve_cooked<'s>(
        &'s self,
        cooked: &'s StringCooked<'arena>,
        span: Span,
    ) -> &'s str {
        let local = Span::new(
            span.start - self.base_offset as u32,
            span.end - self.base_offset as u32,
        );
        cooked.resolve(local, self.source)
    }

    /// The source text a host `span` covers (the parser's own slice, `base_offset` taken
    /// off).
    pub(super) fn source_slice(&self, span: Span) -> &'a str {
        &self.source[span.start as usize - self.base_offset..span.end as usize - self.base_offset]
    }

    /// The current token's verbatim source text. Returns `&'a str` (borrowing the
    /// immutable source), not `&self` — so callers can hold it across `advance()`
    /// without a borrow-escape `.to_string()`.
    #[inline]
    pub(super) fn current_value(&self) -> &'a str {
        &self.source[self.current.start as usize..self.current.end as usize]
    }

    /// Get the decoded string value for the current token (for strings with escapes)
    ///
    /// Used for:
    /// - Identifiers with unicode escapes (\u0066oo → "foo")
    /// - Expression evaluation (computing const values)
    /// - Type analysis (analyzing string literal types)
    /// - Linting (analyzing string content for patterns)
    pub(super) fn current_decoded(&self) -> Option<&str> {
        self.current_decoded
    }

    /// Whether the current token's raw bytes are plain one-column ASCII. Asked of the
    /// lexer by the token's start offset: the lexer keeps the starts of the last two
    /// NON-plain identifier tokens, which is enough because it is never more than the
    /// one `peek` token ahead of `current` — so nothing is snapshotted at `advance` and
    /// nothing is saved when the peek is filled (see `Lexer::nonplain_ident_starts`).
    #[inline]
    fn current_name_plain_ascii(&self) -> bool {
        self.lexer.ident_is_plain_ascii(self.current.start)
    }

    /// The current identifier token's name channel — the canonical identifier
    /// name constructor. Span-identity (`escaped: None`, name = the raw token
    /// bytes) unless the token carries a decoded unicode escape
    /// (`\u0066oo` → `foo`) or is too long for `raw_len` — only those rare
    /// cases carry the arena-`&str` escape hatch.
    pub(super) fn current_ident_name(&self) -> IdentName<'arena> {
        if let Some(decoded) = self.current_decoded {
            IdentName {
                escaped: Some(decoded),
                raw_len: 0,
                plain_ascii: false,
            }
        } else {
            self.current_raw_ident_name()
        }
    }

    /// The current token's name channel from its RAW source text, ignoring any
    /// decoded escape value. For keyword tokens, which are never escaped — the
    /// lexer re-classifies an escaped keyword as an `Identifier`, so its decoded
    /// value flows through `current_ident_name` instead (property/member and
    /// class/interface/type-member keys decode via that path — acorn parity).
    ///
    /// The oversized-name arm's arena copy is out of line
    /// ([`Parser::oversized_raw_name`]): inline, every call here would save and
    /// restore the registers the copy needs, on a path no real identifier
    /// takes.
    pub(super) fn current_raw_ident_name(&self) -> IdentName<'arena> {
        let len = self.current.end - self.current.start;
        if len > u16::MAX as u32 {
            return IdentName {
                escaped: Some(self.oversized_raw_name()),
                raw_len: 0,
                plain_ascii: false,
            };
        }
        IdentName {
            escaped: None,
            raw_len: len as u16,
            plain_ascii: self.current_name_plain_ascii(),
        }
    }

    /// The current token's raw text, arena-copied — the escape hatch
    /// [`Parser::current_raw_ident_name`] carries for an absurdly long name
    /// (> 64 KiB), which `raw_len` can't hold (essentially unreachable — no
    /// real identifier is this long).
    ///
    /// It hands back the string alone, which returns in registers, rather than
    /// the whole `IdentName`, which would return through a stack slot each
    /// caller this inlines into had to reserve — in parse functions that
    /// recurse.
    #[cold]
    #[inline(never)]
    fn oversized_raw_name(&self) -> &'arena str {
        self.arena.alloc_str(self.current_value())
    }

    /// Name channel for the current token, which the caller has already verified
    /// is a plain `Identifier` or a keyword-lexed word valid as a name here — the
    /// [`Parser::at_binding_name`] set, so a contextual keyword or `await` at Script
    /// `[~Await]` (e.g. a class name, single-param arrow param, or `break`/`continue`
    /// label). A plain identifier decodes unicode escapes; a keyword token is never
    /// escaped (the lexer re-classifies an escaped keyword as an `Identifier`), so it
    /// is taken verbatim.
    pub(super) fn current_ident_name_or_await(&self) -> IdentName<'arena> {
        if matches!(self.current_kind(), TokenKind::Identifier) {
            self.current_ident_name()
        } else {
            self.current_raw_ident_name()
        }
    }

    /// Whether a private identifier's name (the part after `#`) equals `expected` (an
    /// ASCII name like `"constructor"`). An escaped name compares its arena string; a
    /// span-identity name compares its raw source bytes, which begin one byte past the
    /// node span's start — the `#` — in host coordinates, shifted back to the local
    /// slice. Used to reject the reserved `#constructor` class-element name.
    pub(super) fn private_name_is(
        &self,
        pid: &PrivateIdentifier<'_>,
        span: Span,
        expected: &str,
    ) -> bool {
        match pid.name.escaped {
            Some(s) => s == expected,
            None => {
                let start = span.start as usize + 1 - self.base_offset;
                let raw = start..start + pid.name.raw_len as usize;
                self.source.as_bytes().get(raw) == Some(expected.as_bytes())
            }
        }
    }

    /// Name channel for the current token as an identifier — the set
    /// `KeywordKind::can_be_identifier` admits (`from`, `as`, `satisfies`, the type
    /// keywords, … plus `let` / `yield` / `await`). Used at positions where an
    /// unconditionally-reserved word would be read as a keyword instead (a
    /// specifier local name, a label, a qualified type name's right side).
    ///
    /// ⚠️ This is a **name-building** channel, not a gate: it is deliberately wider
    /// than [`Parser::at_binding_name`] / [`Parser::at_reference_name`] and applies
    /// neither the goal axis to `await` nor the `[~Yield]` guard to `yield`. Every
    /// caller must already have decided the word is legal here — a label site, for
    /// instance, is admitted by `at_reference_name` at the statement dispatcher, and
    /// calling this without that gate would accept `yield:` inside a generator.
    ///
    /// Handles `TokenKind::Identifier` with unicode escape decoding. Returns `None`
    /// if the current token is not identifier-like.
    ///
    /// ⚠️ For a position the grammar spells `IdentifierName` — where every reserved
    /// word is valid — use [`Parser::try_identifier_name`] instead.
    pub(super) fn try_ident_or_contextual_name(&self) -> Option<IdentName<'arena>> {
        match self.current_kind() {
            TokenKind::Identifier => Some(self.current_ident_name()),
            TokenKind::Keyword(kw) if kw.can_be_identifier() => Some(self.current_raw_ident_name()),
            _ => None,
        }
    }

    /// Name channel for the current token as a function declaration name — a
    /// `BindingIdentifier`, so it asks [`Parser::await_is_binding_name`]: `await`
    /// names a function at `Goal::Script` (whatever the `[Await]` context, that bar
    /// being a deferred early error) and is reserved at `Module`, so `function
    /// await(){}` / `export function await(){}` reject there, matching
    /// acorn-as-module. Other keyword-lexed names (`async`, `from`, `let`, `yield`,
    /// the type keywords) stay valid.
    pub(super) fn try_function_name(&self) -> Option<IdentName<'arena>> {
        if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::Await))
            && !self.await_is_binding_name()
        {
            return None;
        }
        self.try_ident_or_contextual_name()
    }

    /// Whether the current token is binding-name-eligible — the allocation-free
    /// classification behind `try_binding_name().is_some()`, without building the
    /// name. Pure `&self` (no allocation), so it is safe inside a `debug_assert!`
    /// (the name-building path `try_binding_name` takes may arena-allocate an
    /// escaped name).
    ///
    /// The set is [`KeywordKind::can_be_binding_name`] plus `await` where the goal
    /// axis makes it an identifier — so `let` and `yield` are in, their only bar
    /// being a strict-mode early error tsv defers.
    ///
    /// This also guards the two **`IdentifierReference` heads** that tsv checks
    /// before committing — a heritage element's `TypeName` (`interface A extends X`,
    /// `class C implements X`) and an import-equals module reference (`import x =
    /// A.B`) — which want the same set for the same reason: in strict mode the bar
    /// on `let`/`yield` is an early error in the reference and binding spellings
    /// alike, while a genuine `ReservedWord` (`void`) is excluded by the
    /// `Identifier` production in both. tsc and prettier accept `let`/`yield` at
    /// both heads; acorn accepts them at the heritage head and rejects them at the
    /// module reference, but it is the shape oracle, not the validity one. The
    /// heritage head once needed a wider predicate of its own purely because this
    /// set was missing `let`.
    ///
    /// ⚠️ An *expression*-position reader wants
    /// [`Parser::keyword_is_expression_identifier`] instead — inside a generator
    /// `yield` is the operator there, which is a production guard rather than a
    /// deferrable early error.
    pub(super) fn at_binding_name(&self) -> bool {
        match self.current_kind() {
            TokenKind::Identifier => true,
            TokenKind::Keyword(kw) if kw.can_be_binding_name() => true,
            TokenKind::Keyword(KeywordKind::Await) => self.await_is_binding_name(),
            _ => false,
        }
    }

    pub(super) fn try_binding_name(&self) -> Option<IdentName<'arena>> {
        match self.current_kind() {
            TokenKind::Identifier => Some(self.current_ident_name()),
            TokenKind::Keyword(kw) if kw.can_be_binding_name() => {
                Some(self.current_raw_ident_name())
            }
            // `await` is a valid `BindingIdentifier` at Script goal, whatever the
            // `[Await]` context: the goal bullet is enforced, the `[Await]` one is a
            // deferred early error like the `[Yield]` twin (`await_is_binding_name`).
            TokenKind::Keyword(KeywordKind::Await) if self.await_is_binding_name() => {
                Some(self.current_raw_ident_name())
            }
            _ => None,
        }
    }

    /// Take the current token as a declaration-name `BindingIdentifier` — an
    /// identifier or a contextual keyword valid as a binding name (`enum string {}`,
    /// `type any = …`, `namespace number {}`) — advancing past it. Returns `Ok(None)`
    /// *without advancing* when the current token can't be a binding name, so the
    /// caller emits its own position-specific error. The single home for the
    /// "a declaration name is a `BindingIdentifier`" policy shared by the interface /
    /// namespace-segment / declare-module / enum / type-alias name parsers. The class
    /// paths capture inline instead (they additionally exclude the heritage-starting
    /// `implements`), and the import path captures the name across a following branch.
    pub(super) fn take_binding_identifier(&mut self) -> Result<Option<Identifier<'arena>>, Error> {
        let Some(name) = self.try_binding_name() else {
            return Ok(None);
        };
        let (id_start, id_end) = self.current_pos();
        self.advance()?;
        Ok(Some(Identifier::simple(
            name,
            Span::new(id_start as u32, id_end as u32),
        )))
    }

    /// Whether `await` reads as a plain identifier at an **expression or label**
    /// position: only at `Goal::Script` and outside any `[+Await]` context.
    ///
    /// Both halves are real here, for different reasons. The goal half is the early
    /// error tsv enforces (`IdentifierReference : await` is a Syntax Error when the
    /// goal is `Module`). The `!in_await` half is not a deferral question at all —
    /// `IdentifierReference[Await] : [~Await] await` and `LabelIdentifier[Await] :
    /// [~Await] await` carry the guard **in their productions**, and inside a
    /// `[+Await]` context `await` is the operator, so the identifier reading is
    /// unreachable rather than merely invalid. Exactly parallel to
    /// [`Parser::yield_is_identifier`].
    ///
    /// ⚠️ A **binding** position wants [`Parser::await_is_binding_name`] instead —
    /// there the `[Await]` bar is a deferrable early error, not a production guard.
    pub(super) fn await_is_identifier(&self) -> bool {
        self.goal == Goal::Script && !self.in_await
    }

    /// Whether `await` may name a `BindingIdentifier` here: at `Goal::Script`,
    /// whatever the `[Await]` context.
    ///
    /// [`Parser::await_is_identifier`] minus the `!in_await` half, and the
    /// difference is the same one that lets `yield` be a binding name inside a
    /// generator. §sec-identifiers gives `BindingIdentifier[Yield, Await] :
    /// Identifier | `yield` | `await`` with **no** guard on either word, and writes
    /// both context bars as early errors instead (so ASI cannot split `let ⏎ await
    /// 0;`):
    ///
    /// ```text
    /// BindingIdentifier[Yield, Await] : `await`
    ///   It is a Syntax Error if this production has an [Await] parameter.
    /// ```
    ///
    /// tsv defers that one, exactly as it defers the `[Yield]` twin — so `async
    /// function h() { var await = 1; }` and `async function h(await) {}` parse at
    /// Script goal. Deferring is what the reject-vs-defer line prescribes: the bar
    /// is a Static Semantics early error ("…if this production has an `[Await]`
    /// parameter"), not a production. tsc's parser agrees — its
    /// `isBindingIdentifier` deliberately admits `await`/`yield` and leaves the bar
    /// to the grammar checker (TS1359), the same bucket as TS1212 `let`. acorn
    /// rejects, but it is the shape oracle, not the validity one.
    ///
    /// The **goal** bullet is a different early error and stays enforced: `await` is
    /// a Syntax Error as a name when the goal is `Module`, which is what makes the
    /// goal axis observable at all.
    pub(super) fn await_is_binding_name(&self) -> bool {
        self.goal == Goal::Script
    }

    /// Whether `yield` reads as a plain identifier here rather than as the operator:
    /// outside a generator only.
    ///
    /// This is the `[~Yield]` guard that `IdentifierReference` and `LabelIdentifier`
    /// carry **in their productions** — and that `BindingIdentifier` deliberately does
    /// NOT (ecma262 §sec-identifiers gives it `Identifier | `yield` | `await`` with no
    /// guard and writes the `[Yield]` bar as an early error instead, so ASI cannot
    /// split `let ⏎ await 0;`). That asymmetry is the whole reason the three channels
    /// differ: `function* g() { var yield = 1; }` parses (binding, deferred early
    /// error) while `function* g() { o = { yield }; }` and `function* g() { yield: ; }`
    /// reject (reference / label, production guard). Real tsc and test262 both draw the
    /// line there. The `await` counterpart is [`Parser::await_is_identifier`].
    pub(super) fn yield_is_identifier(&self) -> bool {
        !self.in_yield
    }

    /// Whether `kw` reads as a plain identifier at an **expression** position —
    /// [`KeywordKind::can_be_binding_name`] narrowed by the one word whose
    /// expression reading differs from its binding reading (see
    /// [`Parser::yield_is_identifier`]).
    ///
    /// `await` is outside this set entirely: its callers ask
    /// [`Parser::await_is_identifier`] on arms of their own, ordered after the arm
    /// that calls this.
    pub(super) fn keyword_is_expression_identifier(&self, kw: KeywordKind) -> bool {
        kw.can_be_binding_name()
            && (!matches!(kw, KeywordKind::Yield) || self.yield_is_identifier())
    }

    /// Whether the current token may name an `IdentifierReference` **or** a
    /// `LabelIdentifier` — one predicate because ecma262 gives the two productions
    /// character-for-character identical guards:
    ///
    /// ```text
    /// IdentifierReference[Yield, Await] : Identifier | [~Yield] `yield` | [~Await] `await`
    /// LabelIdentifier[Yield, Await]     : Identifier | [~Yield] `yield` | [~Await] `await`
    /// ```
    ///
    /// [`Parser::at_binding_name`] with both context guards *applied* rather than
    /// deferred, and that is the whole difference between the two channels:
    /// `BindingIdentifier` carries no guard and puts the same bars in the early
    /// errors, which tsv defers. So inside a generator or async function the binding
    /// channel admits `yield` / `await` (`function* g() { var yield = 1; }`) while
    /// this one does not (`function* g() { yield: ; }`, `async function h() { await:
    /// ; }`). A guard is not a deferrable early error: in a `[+Yield]` / `[+Await]`
    /// context the word is the **operator**, so the name reading is unreachable, not
    /// merely invalid.
    ///
    /// The two non-label callers are the `IdentifierReference` heads tsv checks
    /// before committing — a heritage element's `TypeName` (`interface A extends X`,
    /// `class C implements X`) and an import-equals module reference (`import x =
    /// A.B`). tsc draws the same line by parsing heritage with its *expression*
    /// parser, so `function* g() { interface A extends yield {} }` and `async
    /// function h() { interface A extends await {} }` are TS1109 there — while a
    /// plain type annotation (`function* g() { let x: yield; }`) is fine, since that
    /// one never reaches an expression parser in either implementation.
    pub(super) fn at_reference_name(&self) -> bool {
        self.at_binding_name()
            && match self.current_kind() {
                TokenKind::Keyword(KeywordKind::Yield) => self.yield_is_identifier(),
                TokenKind::Keyword(KeywordKind::Await) => self.await_is_identifier(),
                _ => true,
            }
    }

    /// Enter a grouping delimiter — `(…)`, `[…]`, `{…}`, `${…}` — having just
    /// consumed its opener. Pairs with [`Parser::exit_grouping`] on the closer.
    ///
    /// The two calls are what maintain [`Parser::grouping_depth`], and every
    /// consumer of that counter is documented on the field: a *baseline* decides
    /// what a reading means, and the two questions it answers use different ones
    /// ([`Parser::no_in_depth`] vs the parse root's literal 0). The pairs across
    /// `expression.rs` / `expression_literals.rs` / `expression_template.rs` /
    /// `parameters.rs` are hand-balanced across early returns and are deliberately
    /// NOT unwound on the error path — a rejected parse propagates straight out, and
    /// the one place that abandons a parse and continues, [`Parser::rewind`],
    /// restores the depth itself. Wrapping them in a combinator (so the pair is balanced
    /// by construction) wants body extraction at several sites and is its own change.
    ///
    /// The grouping depth is also part of the depth limit's nesting count: a grouping
    /// delimiter is where most of the expression grammar's recursion passes (a paren, an
    /// array, an object, a call's arguments, a template's `${`, a computed member), so its
    /// level is the one this increment already pays for, and the limit is tested against
    /// it beside [`Parser::depth`] (`DepthBudget::check_beside`) — refused at the current
    /// token where the two together would pass `tsv_lang::NESTING_LIMIT`.
    #[inline]
    pub(super) fn enter_grouping(&mut self) -> Result<(), Error> {
        self.grouping_depth += 1;
        if !self.depth.check_beside(self.grouping_depth) {
            return Err(self.too_deep(DepthLimit::Nesting));
        }
        Ok(())
    }

    /// Leave a grouping delimiter, having just consumed its closer. See
    /// [`Parser::enter_grouping`].
    #[inline]
    pub(super) fn exit_grouping(&mut self) {
        debug_assert!(
            self.grouping_depth > 0,
            "exit_grouping without a matching enter_grouping"
        );
        self.grouping_depth -= 1;
        // The delimiter a `<` region opened in has closed, and its closer is a token the
        // printed form always holds ([`LtRegion`]).
        self.lt_regions.close_above(self.grouping_depth);
    }

    /// [`Parser::exit_grouping`] for a GROUPING paren, the one delimiter the printer may
    /// strip: a `<` region opened inside it survives the `)`, re-anchored at the depth the
    /// paren sat in ([`LtRegion`]).
    #[inline]
    pub(super) fn exit_stripped_grouping(&mut self) {
        self.lt_regions
            .reanchor_above(self.grouping_depth.saturating_sub(1));
        self.exit_grouping();
    }

    /// Record a binary `<` / `<<` just consumed, at `lt_pos`: a `<` opens one region and a
    /// `<<` two, the second `<` being a nested list's to the parse that re-scans it
    /// ([`LtRegion`]).
    #[inline]
    pub(super) fn open_lt_regions(&mut self, lt_pos: usize, count: usize) {
        for _ in 0..count {
            self.lt_regions.open(LtRegion {
                floor: self.grouping_depth,
                lt_pos,
            });
        }
    }

    /// How many `<` regions are open at the current token with their `<` ahead of
    /// `operand_start` — the start of the left operand of the `>` / `>>` / `>>>` being
    /// reduced ([`LtRegion::lt_pos`]).
    #[inline]
    pub(super) fn lt_regions_open_before(&self, operand_start: usize) -> usize {
        self.lt_regions.open_before(operand_start)
    }

    /// A statement or class member begins: the regions of whatever came before it in this
    /// body are dead ([`Parser::lt_regions_statement_base`]).
    #[inline]
    pub(super) fn reset_lt_region_for_statement(&mut self) {
        self.lt_regions = self.lt_regions_statement_base;
    }

    /// Run `f` as a **body** written inside whatever `<` regions are open: its statements
    /// start from those regions rather than from none
    /// ([`Parser::lt_regions_statement_base`]), and both are restored afterward (on
    /// success and error alike), where the body's own regions are dead.
    pub(super) fn with_lt_region_inherited<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved = self.lt_regions;
        let saved_base = std::mem::replace(&mut self.lt_regions_statement_base, saved);
        let result = f(self);
        self.lt_regions_statement_base = saved_base;
        self.lt_regions = saved;
        result
    }

    /// Shared body of the `with_*` context combinators: run `f` with the
    /// boolean context flag selected by `flag` set to `value`, restoring the
    /// prior value afterward (on success and error alike).
    pub(super) fn with_context_flag<T>(
        &mut self,
        flag: fn(&mut Self) -> &mut bool,
        value: bool,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved = std::mem::replace(flag(self), value);
        let result = f(self);
        *flag(self) = saved;
        result
    }

    /// Run `f` as a conditional's **consequent**: a parenthesized arrow at this
    /// grouping depth may keep a return-type annotation only when a second `:`
    /// follows it (see [`Parser::arrow_return_type_barred_at`]). Restored
    /// afterward, on success and error alike, so the alternate parses under the
    /// enclosing rule — inheriting an outer consequent's bar, as tsc's alternate
    /// inherits the outer flag.
    pub(super) fn with_arrow_return_type_barred<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved = self
            .arrow_return_type_barred_at
            .replace(self.grouping_depth);
        let result = f(self);
        self.arrow_return_type_barred_at = saved;
        result
    }

    /// Run `f` as a fresh expression frame where a parenthesized arrow's return
    /// type is always allowed — where tsc passes `allowReturnTypeInArrowFunction =
    /// true`: a body ([`Parser::with_body_frame`], which pairs this with `[+In]`),
    /// a `yield` argument, and the arrow head tsc commits to a signature outright
    /// (`Parser::parse_arrow_or_rewind`, whose commit exists FOR this lift —
    /// tsc's `true` reaches the arrow's body). Restored afterward, on success and
    /// error alike.
    pub(super) fn with_arrow_return_type_allowed<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved = self.arrow_return_type_barred_at.take();
        let result = f(self);
        self.arrow_return_type_barred_at = saved;
        result
    }

    /// Whether a parenthesized arrow parsed at the current token must be followed
    /// by `:` to keep a return-type annotation — the current token sits directly in
    /// a conditional's consequent, with no grouping opened since its `?`. The
    /// baseline compare is the `no_in_depth` rule: the consequent may itself sit
    /// at any depth, and only a delimiter opened *inside* it lifts the bar.
    #[inline]
    pub(super) fn arrow_return_type_barred(&self) -> bool {
        self.arrow_return_type_barred_at == Some(self.grouping_depth)
    }

    /// Take the state [`Parser::rewind`] returns to. Each of the grammar's speculative
    /// parses takes it at the token it may have to un-read and hands it back if what
    /// it read turns out not to be there: [`Parser::parse_arrow_or_rewind`] at an
    /// arrow head in a conditional's consequent,
    /// [`Parser::parse_type_arguments_or_rewind`] at the `<` of a type-argument list
    /// the lookahead admitted, and again at a whole list whose follower only tsc
    /// refuses, where [`Parser::type_arguments_follower_settled`] tries the comparison from
    /// a checkpoint of its own; and the `export default` value at the `@` of a decorated
    /// class, whose decorator list is read ahead to see whether an `abstract` class
    /// follows (`parse_export_declaration`).
    #[must_use]
    pub(super) fn checkpoint(&self) -> Checkpoint<'arena> {
        // An expression head is never between the constrained-infer handoff's set
        // and its take (both sit inside one `parse_type` call), so the handoff is
        // not carried — `rewind` clears it instead.
        debug_assert!(self.pending_conditional_extends.is_none());
        Checkpoint {
            lexer: self.lexer.checkpoint(),
            current: self.current.clone(),
            current_decoded: self.current_decoded,
            peek: self.peek.clone(),
            peek_decoded: self.peek_decoded,
            had_line_terminator: self.had_line_terminator,
            peek_had_line_terminator: self.peek_had_line_terminator,
            prev_end: self.prev_end,
            lexer_error: self.lexer_error.clone(),
            comments_len: self.comments.len(),
            grouping_depth: self.grouping_depth,
            depth: self.depth,
            spine: self.spine,
            lt_regions: self.lt_regions,
            abandoned_type_arguments_error: self.abandoned_type_arguments_error.clone(),
        }
    }

    /// Return to `checkpoint`, abandoning everything parsed since: the token window
    /// and lexer cursor go back, the comments drained since are dropped (the
    /// re-parse drains them again), and the grouping depth is reset — the one
    /// place the hand-balanced `enter_grouping` / `exit_grouping` pairs are
    /// unwound, since the abandoned parse may have failed inside one. Arena nodes
    /// the abandoned parse built are unreachable garbage; every context flag was
    /// restored by its own combinator on the way out.
    pub(super) fn rewind(&mut self, checkpoint: Checkpoint<'arena>) {
        let Checkpoint {
            lexer,
            current,
            current_decoded,
            peek,
            peek_decoded,
            had_line_terminator,
            peek_had_line_terminator,
            prev_end,
            lexer_error,
            comments_len,
            grouping_depth,
            depth,
            spine,
            lt_regions,
            abandoned_type_arguments_error,
        } = checkpoint;
        self.lexer.rewind(lexer);
        self.current = current;
        self.current_decoded = current_decoded;
        self.peek = peek;
        self.peek_decoded = peek_decoded;
        self.had_line_terminator = had_line_terminator;
        self.peek_had_line_terminator = peek_had_line_terminator;
        self.prev_end = prev_end;
        self.lexer_error = lexer_error;
        self.comments.truncate(comments_len);
        self.grouping_depth = grouping_depth;
        self.depth = depth;
        self.spine = spine;
        self.lt_regions = lt_regions;
        self.abandoned_type_arguments_error = abandoned_type_arguments_error;
        // Whatever the abandoned parse's type grammar was handing to itself is not
        // for the re-parse to receive (`checkpoint` asserts it was empty).
        self.pending_conditional_extends = None;
    }

    /// Whether the `<` at `lt` (an offset in [`Parser::source`]) is one a type-argument
    /// list was tried at and abandoned ([`Parser::abandoned_type_argument_lists`]).
    #[inline]
    pub(super) fn type_arguments_abandoned_at(&self, lt: u32) -> bool {
        // empty for every document that abandons no list, which is nearly all of them
        !self.abandoned_type_argument_lists.is_empty()
            && self
                .abandoned_type_argument_lists
                .contains(&(lt, self.type_arguments_context_key()))
    }

    /// The context a type-argument list is read in, as one key: every flag that the
    /// expressions inside its types inherit — a type literal's computed key, an import
    /// type's options, a default or a key in a signature's binding pattern — and that
    /// decides whether they parse
    /// ([`Parser::abandoned_type_argument_lists`]). That is the scope the list stands
    /// in: `[Await]`, `[Yield]`, strictness, and whether the code is ambient.
    ///
    /// The flags left out decide nothing for a list. The gates read against
    /// [`Parser::grouping_depth`] — `in` as an operator, `as` as an assertion, an
    /// arrow function's barred return type — are not inherited by anything tsc or
    /// acorn-typescript reads as a type: a computed key opens a grouping of its own,
    /// an import type's options are an object literal in its own braces, and a
    /// default or a key in a signature's binding pattern stands in the pattern's
    /// delimiters. (Options that are no object literal make no import type to either;
    /// a tail that holds them and fails on a gate is read as the comparisons both
    /// read.) The type-context pair is reset at every argument
    /// ([`Parser::with_full_type_context`]), and `record_grouping_parens` and
    /// `in_await_if_module` only record. A context flag added to the parser belongs
    /// here if an expression's parse reads it.
    fn type_arguments_context_key(&self) -> u8 {
        [
            self.in_await,
            self.in_yield,
            self.strict,
            self.in_ambient_context,
        ]
        .iter()
        .fold(0, |key, &flag| (key << 1) | u8::from(flag))
    }

    /// Whether the `<` at `lt` is one whose type-argument list was read whole and kept
    /// past a follower only tsc refuses ([`Parser::type_argument_lists_kept`]).
    #[inline]
    pub(super) fn type_arguments_kept_at(&self, lt: u32) -> bool {
        !self.type_argument_lists_kept.is_empty()
            && self
                .type_argument_lists_kept
                .contains(&(lt, self.type_arguments_context_key()))
    }

    /// Record the verdict on the type-argument list at `lt` that a follower only tsc
    /// refuses asked for: abandoned to the comparison reading (`abandoned`), or kept.
    /// Called after the rewind, as [`Parser::abandon_type_arguments`] is. No error is
    /// kept for an abandoned list: the list parsed, so the comparison reading that
    /// replaces it is the one the error will be about.
    pub(super) fn settle_type_arguments_follower(&mut self, lt: u32, abandoned: bool) {
        let key = (lt, self.type_arguments_context_key());
        if abandoned {
            self.abandoned_type_argument_lists.insert(key);
        } else {
            self.type_argument_lists_kept.insert(key);
        }
    }

    /// Record the type-argument list at `lt` as abandoned, with the error it failed
    /// on. Called AFTER the rewind that abandons it. That rewind restores the error
    /// kept before the list was tried, so the error of a list abandoned inside this one
    /// is dropped with it; it is kept again only where the reading that replaces this
    /// list tries that `<` again, which a remembered answer does not.
    pub(super) fn abandon_type_arguments(&mut self, lt: u32, error: Error) {
        // the rewind has run: every context flag is back to what the list was tried in
        self.abandoned_type_argument_lists
            .insert((lt, self.type_arguments_context_key()));
        // (a positionless error orders below every position, so it never displaces one)
        let reaches_further = match &self.abandoned_type_arguments_error {
            Some(kept) => error.position() > kept.position(),
            None => true,
        };
        if reaches_further {
            self.abandoned_type_arguments_error = Some(error);
        }
    }

    /// The error a failed parse reports: `error`, unless an abandoned type-argument
    /// list's own error reached at least as far into the source
    /// ([`Parser::abandoned_type_arguments_error`]).
    ///
    /// A list that is abandoned was a guess, and the `<` is then read as the operator
    /// it may equally be. Where that reading fails as well, the error that reached
    /// further is the one about the text the author more plausibly wrote — a missing
    /// `)` at the end of two comparisons, rather than a `:` no type takes at their
    /// start — and on a tie the list's, the first reading tried. A **goal gate** is
    /// reported as it stands: the format fallback reads its mark, not its position
    /// ([`Error::is_goal_gated`]).
    pub(crate) fn prefer_abandoned_type_arguments_error(&mut self, error: Error) -> Error {
        match (self.abandoned_type_arguments_error.take(), error.position()) {
            (Some(kept), Some(reached))
                if !error.is_goal_gated() && kept.position().is_some_and(|k| k >= reached) =>
            {
                kept
            }
            _ => error,
        }
    }

    /// Run `f` with the function-like scope's `[Await]` and `[Yield]` contexts
    /// set to `is_async` / `is_generator`, restoring both afterward (on success
    /// and error alike). Wrap a function-like scope's params+body so a nested
    /// scope establishes its own `await`/`yield` context without leaking to (or
    /// inheriting from) the enclosing one: an async generator's body is
    /// `[+Await, +Yield]`, a plain function or an arrow inside a generator is
    /// `[~Yield]`, etc. Both flags reset together because they share the same
    /// boundary — every function-like scope — so threading them as one call makes
    /// it impossible to set one and forget the other.
    pub(super) fn with_fn_context<T>(
        &mut self,
        is_async: bool,
        is_generator: bool,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved_await = std::mem::replace(&mut self.in_await, is_async);
        let saved_await_if_module = std::mem::replace(&mut self.in_await_if_module, is_async);
        let saved_yield = std::mem::replace(&mut self.in_yield, is_generator);
        let result = f(self);
        self.in_await = saved_await;
        self.in_await_if_module = saved_await_if_module;
        self.in_yield = saved_yield;
        result
    }

    /// Run `f` in a fresh **strictness scope**: `f` may turn strict mode on (a
    /// `"use strict"` directive prologue at its head), and the flag is restored on
    /// the way out, on success and error alike. Wraps the two bodies that carry a
    /// directive prologue — a `Program` ([`Parser::parse`]) and a function body
    /// (`parse_function_body`).
    ///
    /// Strictness is *inherited*, never cleared, so this saves and restores rather
    /// than replacing (the shape `with_fn_context` takes for `[Await]`/`[Yield]`,
    /// which a nested scope does reset). It is a combinator and not a bare
    /// assignment for the reason [`Parser::checkpoint`] states: the checkpoint
    /// carries no context flags, on the promise that every one of them is restored
    /// by its own combinator — a hand-rolled save/restore pair would leak past a
    /// speculative parse.
    pub(super) fn with_strict_scope<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let saved = self.strict;
        let result = f(self);
        self.strict = saved;
        result
    }

    /// Run `f` with strict mode **on**, restoring the flag afterward (on success and
    /// error alike). This is the one region that is strict by construction rather
    /// than by directive: a class's id, heritage clause and body (ecma262
    /// sec-class-definitions: *all parts of a ClassDeclaration or ClassExpression
    /// are strict mode code*), which is why `class C extends (010) {}` is an error
    /// even in a sloppy script. Takes no value because strictness only ever turns
    /// on — see [`Parser::with_strict_scope`] for the directive-driven case.
    pub(super) fn with_strict_class_scope<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        self.with_context_flag(|p| &mut p.strict, true, f)
    }

    /// Run `f` with the function-type-disallowed context set to `value`,
    /// restoring it afterward (on success and error alike). A single-flag
    /// `with_context_flag` wrapper. Set `true` around union/intersection constituent and
    /// type-operator operand parses; set `false` at full-type entry
    /// (`parse_type`) so nested positions parse function types greedily again.
    pub(super) fn with_fn_type_disallowed<T>(
        &mut self,
        value: bool,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        self.with_context_flag(|p| &mut p.fn_type_disallowed, value, f)
    }

    /// Run `f` with the conditional-type-disallowed context set to `value`,
    /// restoring it afterward (on success and error alike). Mirrors
    /// `with_fn_type_disallowed`. Set `true` around a conditional's extends
    /// clause and a constrained infer's constraint; set `false` at full-type
    /// entry (`parse_type`) so nested positions parse conditionals greedily
    /// again.
    pub(super) fn with_conditional_type_disallowed<T>(
        &mut self,
        value: bool,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        self.with_context_flag(|p| &mut p.conditional_type_disallowed, value, f)
    }

    /// Run `f` at a full-type position — both type-context restrictions
    /// (`fn_type_disallowed`, `conditional_type_disallowed`) cleared, each
    /// restored afterward — so nested full-type positions parse function and
    /// conditional types greedily even when reached from a constituent/operand
    /// parse. Wraps the full-type entry (`parse_type`).
    pub(super) fn with_full_type_context<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, Error>,
    ) -> Result<T, Error> {
        self.with_fn_type_disallowed(false, |p| p.with_conditional_type_disallowed(false, f))
    }

    /// Like `try_binding_name`, but also accepts the `this` keyword as the
    /// TypeScript `this` parameter (`function f(this: T)`, `(this: T) => U`).
    pub(super) fn try_param_name(&self) -> Option<IdentName<'arena>> {
        match self.try_binding_name() {
            Some(name) => Some(name),
            None => self.this_as_name(),
        }
    }

    /// The `this` keyword used as a name channel — the TypeScript `this`
    /// parameter (`function f(this: T)`) and the subject of a `this` type
    /// predicate (`this is T`, `asserts this`). `None` when the current token is
    /// not `this`; its raw text is verbatim (`this` is never escaped).
    pub(super) fn this_as_name(&self) -> Option<IdentName<'arena>> {
        if matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::This)) {
            Some(self.current_raw_ident_name())
        } else {
            None
        }
    }

    /// Name channel for the current token as an `IdentifierName`, accepting ANY
    /// keyword — `ReservedWord` is a subset of `IdentifierName`, so a position
    /// spelled `IdentifierName` in the grammar takes `if` / `default` / `class`
    /// as freely as `a`.
    ///
    /// Two such positions, both single-token productions where the reserved word
    /// cannot be misread as a keyword:
    ///
    /// - `ModuleExportName : IdentifierName | StringLiteral` (`export { x as if }`)
    ///   — this handles only the `IdentifierName` arm; callers test for
    ///   `TokenKind::String` first and build a `ModuleExportName::Literal`.
    /// - `PrivateIdentifier :: # IdentifierName` (`#default`).
    ///
    /// ⚠️ Not to be confused with [`Parser::try_ident_or_contextual_name`], which is
    /// *narrower* despite the broader-sounding name: it admits only the contextual
    /// keywords. Reaching for that one at an `IdentifierName` position is what made
    /// `#default` an over-rejection.
    pub(super) fn try_identifier_name(&self) -> Option<IdentName<'arena>> {
        match self.current_kind() {
            TokenKind::Identifier => Some(self.current_ident_name()),
            TokenKind::Keyword(_) => Some(self.current_raw_ident_name()),
            _ => None,
        }
    }

    /// Extract string literal content and quote character from current token.
    ///
    /// Assumes current token is `TokenKind::String`. Returns `(content, quote)` where:
    /// Decoded form of the current string-literal token, as a [`StringCooked`].
    ///
    /// `Verbatim` (no escapes) carries no allocation — the decoded value equals
    /// the inner source slice (recovered later via `StringCooked::resolve(span,
    /// source)`). `Decoded` (escapes present) arena-copies the lexer's decoded
    /// value (one copy). The quote char is no longer stored — recover it via
    /// `Literal::string_quote(source)`.
    ///
    /// Every string literal in the grammar is consumed here — an expression, an object or
    /// class key, a type-literal member key, a literal type, an import type's specifier,
    /// a module specifier — which is why the strict-mode legacy-escape gate
    /// ([`Parser::legacy_escape_error`]) rides here for every literal as its token
    /// becomes a node; the gate's one other asker is the retroactive prologue walk
    /// (`Parser::note_directive`), over literals whose tokens are already gone.
    pub(super) fn extract_string_cooked(&self) -> Result<StringCooked<'arena>, Error> {
        match self.current_decoded {
            Some(decoded) => {
                if self.strict
                    && let Some(err) = self.legacy_escape_error_in_current_string()
                {
                    return Err(err);
                }
                Ok(StringCooked::Decoded(decoded))
            }
            None => Ok(StringCooked::Verbatim),
        }
    }

    /// The strict-mode legacy-escape check over the current `TokenKind::String` token,
    /// reached from [`Parser::extract_string_cooked`] only on the escape arm — a literal
    /// the lexer decoded. A literal with no escapes carries no backslash and so cannot
    /// hold one of these forms, which is what keeps the walk off the common path.
    fn legacy_escape_error_in_current_string(&self) -> Option<Error> {
        let start = self.current.start as usize;
        let end = self.current.end as usize;
        // Quotes excluded. `get` rather than an index: the token is a well-formed string
        // literal at every caller, and a malformed one should read as "no legacy escape"
        // rather than panic (the `fuzz` gate reaches this seam).
        let inner = self.source.get(start + 1..end.saturating_sub(1))?;
        self.legacy_escape_error(inner, start + 1 + self.base_offset)
    }

    /// The one gate on the **legacy string escapes** — `LegacyOctalEscapeSequence` (`\7`,
    /// `\101`, `\0` followed by a decimal digit) and `NonOctalDecimalEscapeSequence`
    /// (`\8`, `\9`). Strict code disallows both by early error over the *production*
    /// (ecma262 sec-literals-string-literals, restated in Annex C), so the lexer decodes
    /// them under every mode and the rejection belongs here, where the token becomes a
    /// node and the enclosing code's strictness is settled — the same shape as the
    /// leading-zero numeric gate in [`Parser::parse_number_or_bigint_literal`].
    ///
    /// `raw` is a string literal's inner source with its quotes excluded, and `raw_start`
    /// that slice's position in the document the error is rendered against.
    fn legacy_escape_error(&self, raw: &str, raw_start: usize) -> Option<Error> {
        let (offset, form) = find_legacy_escape(raw)?;
        let message = match form {
            LegacyEscape::NonOctalDecimal => {
                "The '\\8' and '\\9' escape sequences are not allowed in strict mode."
            }
            LegacyEscape::LegacyOctal => {
                "Octal escape sequences are not allowed in strict mode. Use '\\x' or '\\u'."
            }
        };
        Some(self.error_msg_at(message, raw_start + offset))
    }

    // Error construction helpers - reduce boilerplate for common error patterns

    /// Create an error with custom message at current position
    pub(super) fn error_msg(&self, message: &str) -> Error {
        Error::invalid_syntax(message.to_string(), self.current_pos().0)
    }

    /// Create an error with custom message at custom position
    pub(super) fn error_msg_at(&self, message: &str, position: usize) -> Error {
        Error::invalid_syntax(message.to_string(), position)
    }

    /// Create a **goal-gate** error at `position`: the construct is one only a module
    /// holds (`import` / `export` / `import.meta`, a top-level `for await`) met at
    /// `Goal::Script`. Marked so the format
    /// fallback can read the script attempt's death here as proof the source is a
    /// module rather than as one more position to compare
    /// (`Error::is_goal_gated`; `parse_with_goal_or_fallback`).
    pub(super) fn error_goal_gate_at(&self, message: &str, position: usize) -> Error {
        Error::goal_gate(message.to_string(), position)
    }

    /// [`Parser::error_goal_gate_at`] at the current position.
    pub(super) fn error_goal_gate(&self, message: &str) -> Error {
        self.error_goal_gate_at(message, self.current_pos().0)
    }

    /// Create an error: "Expected X"
    pub(super) fn error_expected(&self, what: &str) -> Error {
        Error::invalid_syntax(format!("Expected {what}"), self.current_pos().0)
    }

    /// Create an error: "Expected X, found Y"
    pub(super) fn error_expected_found(&self, what: &str) -> Error {
        let kind = &self.current.kind;
        Error::invalid_syntax(
            format!("Expected {what}, found {kind}"),
            self.current_pos().0,
        )
    }

    /// Create an error: "Expected X, found Y" at custom position
    pub(super) fn error_expected_found_at(&self, what: &str, position: usize) -> Error {
        let kind = &self.current.kind;
        Error::invalid_syntax(format!("Expected {what}, found {kind}"), position)
    }

    /// Create an error: "Expected X after Y, found Z"
    pub(super) fn error_expected_after(&self, what: &str, after: &str) -> Error {
        let kind = &self.current.kind;
        Error::invalid_syntax(
            format!("Expected {what} after '{after}', found {kind}"),
            self.current_pos().0,
        )
    }

    /// Create an error: "Unexpected keyword 'X'"
    pub(super) fn error_unexpected_keyword(&self, kw: KeywordKind) -> Error {
        Error::invalid_syntax(format!("Unexpected keyword '{kw}'"), self.current_pos().0)
    }

    /// Create an error for the `with` statement in strict code. Named rather than folded
    /// into `error_unexpected_keyword` so the message says *why* the word is refused; a
    /// bare "unexpected keyword" reads like a parser gap for a construct that sloppy
    /// Script code accepts.
    pub(super) fn error_with_statement(&self) -> Error {
        Error::invalid_syntax(
            "The 'with' statement is not allowed in strict mode".to_owned(),
            self.current_pos().0,
        )
    }

    /// Create an error: `Expected ',' or '}' after list element, found …` — the quotes
    /// come from the punctuators' own `Display`, not from this template.
    pub(super) fn error_list_separator(
        &self,
        separator: &TokenKind,
        terminator: &TokenKind,
    ) -> Error {
        let kind = &self.current.kind;
        Error::invalid_syntax(
            // `TokenKind`'s `Display` already quotes a punctuator, so no quotes here.
            format!("Expected {separator} or {terminator} after list element, found {kind}"),
            self.current_pos().0,
        )
    }

    pub(super) fn check(&self, kind: &TokenKind) -> bool {
        &self.current.kind == kind
    }

    /// Check if current token is an assignment operator and return it.
    ///
    /// Returns `Some(operator)` for: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `**=`,
    /// `<<=`, `>>=`, `>>>=`, `&=`, `|=`, `^=`, `&&=`, `||=`, `??=`
    ///
    /// `inline(always)` because each `inline(always)` copy of
    /// [`Parser::parse_expression_operators`] holds a call site, and with two the hot one in
    /// [`Parser::parse_expression_bp`] stops inlining it.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub(super) fn try_assignment_operator(&self) -> Option<AssignmentOperator> {
        match &self.current.kind {
            TokenKind::Equals => Some(AssignmentOperator::Assign),
            TokenKind::PlusEquals => Some(AssignmentOperator::AddAssign),
            TokenKind::MinusEquals => Some(AssignmentOperator::SubtractAssign),
            TokenKind::StarEquals => Some(AssignmentOperator::MultiplyAssign),
            TokenKind::SlashEquals => Some(AssignmentOperator::DivideAssign),
            TokenKind::PercentEquals => Some(AssignmentOperator::RemainderAssign),
            TokenKind::StarStarEquals => Some(AssignmentOperator::ExponentiateAssign),
            TokenKind::LeftShiftEquals => Some(AssignmentOperator::LeftShiftAssign),
            TokenKind::RightShiftEquals => Some(AssignmentOperator::RightShiftAssign),
            TokenKind::UnsignedRightShiftEquals => {
                Some(AssignmentOperator::UnsignedRightShiftAssign)
            }
            TokenKind::AmpersandEquals => Some(AssignmentOperator::BitwiseAndAssign),
            TokenKind::PipeEquals => Some(AssignmentOperator::BitwiseOrAssign),
            TokenKind::CaretEquals => Some(AssignmentOperator::BitwiseXorAssign),
            TokenKind::AmpersandAmpersandEquals => Some(AssignmentOperator::LogicalAndAssign),
            TokenKind::PipePipeEquals => Some(AssignmentOperator::LogicalOrAssign),
            TokenKind::QuestionQuestionEquals => Some(AssignmentOperator::NullishAssign),
            _ => None,
        }
    }

    // Peek helpers for lookahead (needed for type annotations, operators, etc.)
    // Lazily computes peek token on first access.
    // Stores lexer errors to be returned on next advance() call.
    //
    // Comment tokens are drained into `self.comments` (mirroring
    // `collect_comments()`) so the cached token — and every peek-based
    // decision — is the next CODE token. Line terminators seen while
    // draining are recorded in `peek_had_line_terminator` for the
    // advance() that later consumes the cached token.
    pub(super) fn peek_kind(&mut self) -> TokenKind {
        if self.peek.is_none() && self.lexer_error.is_none() {
            self.peek_had_line_terminator = false;
            loop {
                match self.lexer.next_token() {
                    Ok(token) => {
                        if self.lexer.had_line_terminator() {
                            self.peek_had_line_terminator = true;
                        }
                        if let TokenKind::Comment {
                            is_block,
                            content_start,
                        } = &token.kind
                        {
                            // ECMAScript spec: a MultiLineComment containing a line
                            // terminator counts as one for ASI purposes.
                            let (comment, has_line_terminator) = comment_from_token(
                                self.source,
                                token.start as usize,
                                token.end as usize,
                                *content_start as usize,
                                *is_block,
                                self.base_offset,
                            );
                            if has_line_terminator {
                                self.peek_had_line_terminator = true;
                            }
                            self.comments.push(comment);
                            continue;
                        }
                        self.peek = Some(token);
                        self.peek_decoded = self.decoded_to_arena();
                    }
                    Err(err) => {
                        // Store error to be returned on next advance().
                        self.lexer_error = Some(err);
                    }
                }
                break;
            }
        }
        self.peek
            .as_ref()
            .map_or(TokenKind::Eof, |t| t.kind.clone())
    }

    /// Get the value of the peek token as a string slice
    pub(super) fn peek_value(&self) -> &str {
        self.peek
            .as_ref()
            .map_or("", |t| &self.source[t.start as usize..t.end as usize])
    }

    /// Check if peek token is an identifier (used for contextual keyword disambiguation)
    pub(super) fn peek_is_identifier(&mut self) -> bool {
        matches!(self.peek_kind(), TokenKind::Identifier)
    }

    /// Check if peek token is a specific kind
    pub(super) fn peek_is(&mut self, kind: &TokenKind) -> bool {
        self.peek_kind() == *kind
    }

    /// Whether the peek token can begin a function parameter binding: an
    /// identifier, a destructuring pattern (`[`/`{`), a rest element (`...`),
    /// `this`, or a contextual keyword usable as a binding name (e.g. another
    /// modifier like `readonly`). Used to disambiguate a contextual modifier
    /// keyword (`override`, `readonly`) from a parameter that happens to be
    /// named the same.
    pub(super) fn peek_starts_parameter_binding(&mut self) -> bool {
        let kind = self.peek_kind();
        kind.is_binding_name_word()
            || matches!(
                kind,
                TokenKind::BracketOpen
                    | TokenKind::BraceOpen
                    | TokenKind::DotDotDot
                    | TokenKind::Keyword(KeywordKind::This)
            )
    }

    /// Get the start position of the peek token (cache must be populated via peek_kind() first)
    pub(super) fn peek_start(&self) -> usize {
        self.peek.as_ref().map_or(0, |t| t.start as usize)
    }

    /// Whether a line terminator separates the current token from the peeked one.
    ///
    /// Scans the raw inter-token slice, so a comment containing a newline counts
    /// as a line terminator (per ASI rules). Used for `[no LineTerminator here]`
    /// restrictions like `using [no LineTerminator here] BindingIdentifier`.
    pub(super) fn peek_preceded_by_line_terminator(&mut self) -> bool {
        self.peek_kind(); // populate the cache
        let to = self.peek_start();
        let from = (self.current.end as usize).min(to);
        self.source[from..to].contains(is_es_line_terminator)
    }

    /// Whether the peeked token is an identifier on the same line as the current
    /// token (tsc's `nextTokenIsIdentifierOnSameLine`).
    ///
    /// The shared shape behind the contextual-keyword declaration starters
    /// (`type`/`interface`/`namespace`/`module`): a line break before the
    /// name demotes the keyword to a plain identifier and ASI splits the statement.
    pub(super) fn peek_is_same_line_identifier(&mut self) -> bool {
        self.peek_is_identifier() && !self.peek_preceded_by_line_terminator()
    }

    /// Whether the peeked token is a same-line *declaration name word* — a plain
    /// identifier or a keyword-lexed word valid as a binding name (`string`,
    /// `number`, `any`, … plus `let` / `yield`; the set
    /// `KeywordKind::can_be_binding_name` accepts). Used by the
    /// `interface`/`namespace`/`module` dispatch, which commits to a declaration
    /// only when a name follows on the same line (tsc
    /// `nextTokenIsIdentifier…OnSameLine`, whose `isBindingIdentifier` is likewise
    /// true for the contextual keywords *and* for the strict-mode-reserved words it
    /// defers). So `interface let {}` / `namespace let {}` commit, matching tsc; a
    /// word barred by a *production* rather than an early error (`void`, `enum`)
    /// fails the gate, leaving the contextual keyword an ordinary identifier.
    /// Mirrors the `try_binding_name` name-capture predicate the declaration
    /// parsers use for the name itself.
    pub(super) fn peek_is_same_line_name_word(&mut self) -> bool {
        self.peek_kind().is_binding_name_word() && !self.peek_preceded_by_line_terminator()
    }

    /// Demand a same-line name for a contextual declaration head already committed to
    /// — `interface` / `type` / `namespace` / `module` behind `declare` or `export`.
    ///
    /// The statement path asks [`Self::peek_is_same_line_name_word`] one token earlier,
    /// where failing it DEMOTES the head to a plain identifier and ASI splits the
    /// statement. Behind a modifier there is no demotion to fall back on — the modifier
    /// would be left with nothing to attach to — so the same question becomes an error
    /// rather than a fork, and every oracle agrees there is no reading: tsc rejects
    /// (TS1434, or TS1142 "Line break not permitted here" for `declare type`), as do
    /// acorn and prettier. Without it the two lines welded into ONE declaration and the
    /// line terminator simply vanished, tsv alone.
    ///
    /// `head` names the construct for the message ONLY — the string-name allowance is
    /// read off the token, never off this word, so a reworded message cannot change
    /// what parses. One helper for all four heads so they cannot drift apart — they
    /// had, which is how `declare interface` and `declare type` kept welding while
    /// `declare namespace` did not.
    pub(super) fn require_same_line_declaration_name(&mut self, head: &str) -> Result<(), Error> {
        if self.peek_is_same_line_declaration_name() {
            Ok(())
        } else {
            Err(self.same_line_declaration_name_error(head))
        }
    }

    /// The question [`Self::require_same_line_declaration_name`] asks, split out for the
    /// one caller that must ask it *before* consuming the head keyword: `export type`
    /// decides between the alias and the `{`/`*` re-export forms only after the advance,
    /// and those two forms take the break in every oracle (tsc's
    /// `canFollowExportModifier` exempts exactly `*` and `{`).
    ///
    /// Asked while `current` is still the head keyword, which is what lets it read the
    /// string-name allowance from the token: only `module` takes one
    /// (`declare module 'x' {}`).
    pub(super) fn peek_is_same_line_declaration_name(&mut self) -> bool {
        self.peek_is_same_line_name_word()
            || (self.current_value() == "module"
                && self.peek_kind() == TokenKind::String
                && !self.peek_preceded_by_line_terminator())
    }

    /// The error [`Self::require_same_line_declaration_name`] raises, so the split
    /// caller above reports it in the same words.
    pub(super) fn same_line_declaration_name_error(&self, head: &str) -> Error {
        self.error_msg(&format!("{head} name must be on the same line"))
    }

    /// Whether a `let` in a `StatementListItem` or a for-head heads a
    /// `LexicalDeclaration` rather than an expression — acorn's `isLet` with no
    /// context: a binding name, `{`, or `[` follows.
    ///
    /// `let` is the one word that is neither a `ReservedWord` nor purely contextual:
    /// `Identifier : IdentifierName but not ReservedWord` admits it, so `let` is a
    /// perfectly good `IdentifierReference` (`let;`, `x = let`, `let.x = 1`,
    /// `typeof let`), barred only by the strict-mode early error tsv defers. What
    /// keeps the two readings apart is a *lookahead*, and ecma262 spells one half of
    /// it out — `ExpressionStatement` carries `[lookahead ∉ { …, `let` `[` }]`, so
    /// `let [` can never begin an expression statement. That is why `let[0] = 1` is
    /// **not** an indexed assignment but a declaration with an invalid array binding
    /// pattern, and stays a syntax error (tsc TS1181) even though `let.x = 1` parses.
    ///
    /// A **for-head** asks the same question, and each head reads it off its own
    /// production: `ForStatement`'s init carries that same `[lookahead ∉ { let [ }]`,
    /// so `for (let; ;)` and `for (let = 3; ;)` are expression inits, and the for-in
    /// production carries `[lookahead ≠ let []` on its `LeftHandSideExpression`, so
    /// `for (let in o)` and `for (let.x in o)` are expression lefts. (tsc instead
    /// commits `for (let` to a declaration on the keyword alone,
    /// `parseForOrForInOrForOfStatement` testing `token() === LetKeyword` with no
    /// lookahead; the drop-in oracle and the grammar agree against it.) A for-of head's
    /// own `[lookahead ∉ { let }]` is a separate, wider bar, enforced where the head is
    /// read — see `Parser::parse_for_statement`.
    ///
    /// ⚠️ A **single-statement position** (an `if` arm, a loop or `with` body, a
    /// labelled item) does NOT ask this: no declaration is admissible there at all, so
    /// only `let [` — barred from the expression reading by the lookahead above — is a
    /// declaration, and it is a syntax error rather than a second reading. That fork is
    /// `Parser::parse_nested_statement`.
    ///
    /// Two of acorn's `isLet` arms are absent here because tokenization already
    /// answers them: `in` / `instanceof` never reach the binding-name set (acorn
    /// re-reads the raw word to exclude them), and an identifier written with a
    /// unicode escape (`let \u0061 = 1`) is an ordinary `Identifier` token, so this
    /// reads the declaration acorn reads. acorn's raw scan cannot decode an escape,
    /// so it takes a following `\` as a declaration in **every** position — the
    /// single-statement one included, where no declaration is admissible — and
    /// over-rejects the escaped spelling alone: `L: let ⏎ \u0061 = 1;` is a syntax
    /// error there while the unescaped `L: let ⏎ a = 1;` parses, as it does here.
    /// ASI licenses this reading for both spellings — `let a` is underivable in a
    /// `LabelledItem : Statement` position, so the identifier is an offending token
    /// preceded by a `LineTerminator` and rule 1 of
    /// §sec-rules-of-automatic-semicolon-insertion inserts the semicolon.
    pub(super) fn at_let_declaration(&mut self) -> bool {
        let kind = self.peek_kind();
        kind.is_binding_name_word()
            || matches!(kind, TokenKind::BraceOpen | TokenKind::BracketOpen)
            || (matches!(kind, TokenKind::Keyword(KeywordKind::Await))
                && self.await_is_binding_name())
    }

    /// Whether the peeked token is a same-line *binding word* for a `using`
    /// declaration: any identifier-shaped word — a plain identifier or a
    /// keyword-lexed contextual name (`async`, `undefined`, …) — except the
    /// words that continue the *expression* reading of `using` instead:
    /// the word-shaped binary operators (`using in b`, `using instanceof C`)
    /// and the cast keywords (`using as T`, `using satisfies T` — acorn at the
    /// canonical parsers' ES2025, where `using` is no keyword, reads these as
    /// casts of the identifier `using`; tsc and acorn at ES2026 commit to a
    /// declaration binding `as`/`satisfies`. The drop-in oracle wins, and the
    /// printer keeps a pair around the word so every edition reads its output
    /// as the cast — `head_parens.rs`'s statement-head set).
    /// Reserved words (`function`, `let`, …) pass the gate and are rejected by
    /// the binding parser, matching acorn's rejection of both readings. The
    /// one-past-peek sibling is `peek_followed_by_same_line_binding_word`.
    pub(super) fn peek_is_same_line_binding_word(&mut self) -> bool {
        self.peek_is_identifier_or_keyword()
            && !self.peek_preceded_by_line_terminator()
            && !matches!(self.peek_value(), "in" | "instanceof" | "as" | "satisfies")
    }

    /// Whether the token after a `declare` modifier begins an ambient declaration
    /// on the same line.
    ///
    /// `declare` is a contextual keyword: a following line terminator (ASI) or a
    /// non-declaration token demotes it to a plain identifier (`declare;`,
    /// `declare = x`). Mirrors tsc's `isDeclaration` modifier handling
    /// (`nextToken(); if (hasPrecedingLineBreak()) return false; continue;`): the
    /// next token must be a declaration starter on the same line. The contextual
    /// starters (`abstract`/`namespace`/`module`/`interface`/`type`/`global`) are
    /// matched by source value since they lex as plain identifiers.
    pub(super) fn peek_starts_ambient_declaration(&mut self) -> bool {
        if self.peek_preceded_by_line_terminator() {
            return false;
        }
        match self.peek_kind() {
            TokenKind::Keyword(
                KeywordKind::Const
                | KeywordKind::Let
                | KeywordKind::Var
                | KeywordKind::Function
                | KeywordKind::Class
                | KeywordKind::Enum,
            ) => true,
            // `declare async function` — the one starter carrying a `[no
            // LineTerminator here]` of its OWN, so the ambient reading is refused
            // here when `function` does not sit on the `async`'s line. Asking a
            // token later is what keeps this out of the `declare abstract⏎class`
            // trap (see `parse_declare_statement_kind`), where the ambient reading
            // is already committed and can no longer split into statements.
            TokenKind::Keyword(KeywordKind::Async) => {
                self.peek_followed_by_same_line_function_keyword()
            }
            TokenKind::Identifier => matches!(
                self.peek_value(),
                "abstract" | "namespace" | "module" | "interface" | "type" | "global"
            ),
            _ => false,
        }
    }

    /// The byte scan the one-past-peek predicates share: where the next token
    /// begins past the peeked one (skipping whitespace and comments), and whether
    /// that gap holds no line terminator — the answer a `[no LineTerminator here]`
    /// predicate needs. A comment spanning a line counts as one (per ASI rules).
    fn scan_past_peek(&mut self) -> (usize, bool) {
        self.peek_kind(); // populate the cache
        let after_peek = self.peek.as_ref().map_or(0, |t| t.end as usize);
        let pos = scan::skip_whitespace_and_comments(self.source.as_bytes(), after_peek);
        (
            pos,
            !self.source[after_peek..pos].contains(is_es_line_terminator),
        )
    }

    /// Whether the peeked token is followed on the same line by an identifier.
    ///
    /// Used for `await using [no LineTerminator here] BindingIdentifier`, where
    /// the binding sits one token past the peek horizon.
    pub(super) fn peek_followed_by_same_line_binding_word(&mut self) -> bool {
        let (pos, same_line) = self.scan_past_peek();
        let bytes = self.source.as_bytes();
        same_line && scan::identifier_starts_at(bytes, pos) && {
            // A word continuing the *expression* reading instead of binding:
            // `await using in b` / `await using instanceof C` are await
            // expressions (`in`/`instanceof` are the word-shaped binary
            // operators), and `await using as T` / `await using satisfies T`
            // are casts of `await using` (acorn's reading at the canonical
            // ES2025; tsc would commit to a declaration binding
            // `as`/`satisfies`, but the drop-in oracle wins). Every other word
            // is a binding attempt — including
            // contextual keywords that are valid binding names (`async`,
            // `undefined`, `of`). Mirrors `peek_is_same_line_binding_word`.
            let end = scan::skip_identifier(bytes, pos);
            let word = &bytes[pos..end];
            word != b"in" && word != b"instanceof" && word != b"as" && word != b"satisfies"
        }
    }

    /// Whether the peeked token is followed by `=`, `;` or `:` — the tokens that
    /// continue a declarator whose binding is the peek (an initializer, the end
    /// of a C-style head's init, a type annotation).
    ///
    /// Used where `using of` reads two ways in a `for` head: a declaration of
    /// `of` (`for (using of = a; ;)`), or — the proposal's `[lookahead ≠ using
    /// of]`, which restricts the for-of `ForDeclaration` alone — a for-of over
    /// the identifier `using` (`for (using of items)`). tsc's
    /// `nextTokenIsEqualsOrSemicolonOrColonToken` draws the line at the same
    /// three tokens; an `=` opening `==` / `===` / `=>` is no initializer. A
    /// break before the token is fine: nothing past the binding carries `[no
    /// LineTerminator here]`.
    pub(super) fn peek_followed_by_declarator_continuation(&mut self) -> bool {
        let (pos, _) = self.scan_past_peek();
        let bytes = self.source.as_bytes();
        match bytes.get(pos) {
            Some(b';' | b':') => true,
            Some(b'=') => !matches!(bytes.get(pos + 1), Some(b'=' | b'>')),
            _ => false,
        }
    }

    /// Whether the peeked token is followed on the same line by the `function`
    /// keyword.
    ///
    /// Used for `declare async [no LineTerminator here] function`, where the
    /// keyword sits one token past the peek horizon. tsc's modifier lookahead
    /// bails on a break before `function`, so `declare async⏎function f(): void;`
    /// is not one ambient async signature there — and asking a token ahead is what
    /// lets that reading be declined *before* the `declare` dispatch commits to one
    /// it could no longer undo, the trap `declare abstract⏎class` sits in.
    ///
    /// What becomes of the residue is the ordinary expression-statement path's ASI
    /// question, which this predicate does not touch: tsc recovers into three
    /// statements, tsv rejects — as it did before `declare async` was accepted at all.
    pub(super) fn peek_followed_by_same_line_function_keyword(&mut self) -> bool {
        let (pos, same_line) = self.scan_past_peek();
        let bytes = self.source.as_bytes();
        same_line
            && pos < bytes.len()
            && &bytes[pos..scan::skip_identifier(bytes, pos)] == b"function"
    }

    /// Whether the cursor sits at a `using` declaration head — the contextual
    /// keyword followed on the same line by a binding word (`using [no
    /// LineTerminator here] BindingIdentifier`; a break, or an
    /// expression-continuation word, demotes `using` to a plain identifier —
    /// `peek_is_same_line_binding_word` spells both).
    ///
    /// One question, one predicate: every dispatch site asks exactly this, and a
    /// for head then adds only the for-of form's `[lookahead ≠ using of]`, which
    /// a C-style init's declaration of `of` escapes.
    pub(super) fn at_using_declaration(&mut self) -> bool {
        *self.current_kind() == TokenKind::Identifier
            && self.current_value() == "using"
            && self.peek_is_same_line_binding_word()
    }

    /// Whether the cursor sits at an `await using` declaration head. **Both** gaps
    /// carry `[no LineTerminator here]` — `await [no LT] using [no LT]
    /// BindingIdentifier` — so a break at either leaves an `await using`
    /// *expression* behind; a statement then splits under ASI, while a for head,
    /// having no ASI, is a syntax error. Splitting this question across the two
    /// dispatch sites is what let the for head lose both restrictions.
    ///
    /// Whether `await` may be an ordinary identifier here (`Goal::Script`) is the
    /// caller's question, not this one's — statement dispatch settles it first
    /// via `await_is_identifier`.
    pub(super) fn at_await_using_declaration(&mut self) -> bool {
        *self.current_kind() == TokenKind::Keyword(KeywordKind::Await)
            && self.peek_is_same_line_identifier()
            && self.peek_value() == "using"
            && self.peek_followed_by_same_line_binding_word()
    }

    /// Check if peek token could be a property name (identifier, keyword, string, or computed key)
    ///
    /// Used to detect getter/setter syntax where `get` and `set` are contextual keywords:
    /// - `{ get x() {} }` - getter (peek is `x` = identifier)
    /// - `{ get [expr]() {} }` - computed getter (peek is `[`)
    /// - `{ get }` - shorthand property (peek is `}`, not a property name, so NOT a getter)
    pub(super) fn peek_is_property_name(&mut self) -> bool {
        matches!(
            self.peek_kind(),
            TokenKind::Identifier
                | TokenKind::BracketOpen
                | TokenKind::String
                | TokenKind::Number
                | TokenKind::Keyword(_)
        )
    }

    /// Check if current token is an identifier or keyword.
    ///
    /// In JS/TypeScript, reserved words (keywords) can be used as property names
    /// in member expressions: `obj.class`, `obj.if`, `obj.default()`.
    ///
    /// This is distinct from `peek_is_property_name` which also allows `[` and strings.
    /// After `.` or `?.`, we expect just an identifier or keyword (not computed/string).
    pub(super) fn current_is_identifier_or_keyword(&self) -> bool {
        matches!(
            self.current.kind,
            TokenKind::Identifier | TokenKind::Keyword(_)
        )
    }

    /// Peek sibling of `current_is_identifier_or_keyword`: whether the next token
    /// is an identifier or any keyword (acorn/tsc `tokenIsIdentifierOrKeyword`).
    pub(super) fn peek_is_identifier_or_keyword(&mut self) -> bool {
        matches!(
            self.peek_kind(),
            TokenKind::Identifier | TokenKind::Keyword(_)
        )
    }

    /// Get the property name string from current token (identifier or keyword).
    ///
    /// Returns the string representation for property name contexts where both
    /// identifiers and keywords are valid (e.g., after `.` in member access).
    ///
    /// # Precondition
    /// Current token must be an identifier or keyword. Call `current_is_identifier_or_keyword()`
    /// to verify before calling this method.
    pub(super) fn current_property_name(&self) -> &'a str {
        match &self.current.kind {
            TokenKind::Identifier => self.current_value(),
            TokenKind::Keyword(kw) => kw.as_str(),
            _ => {
                debug_assert!(
                    false,
                    "current_property_name called on non-identifier/keyword token"
                );
                // Return empty string as fallback in release builds
                ""
            }
        }
    }

    /// Consume the current `IdentifierName` token — an identifier or any keyword —
    /// as an [`Identifier`] node spanning exactly that token.
    ///
    /// The consuming counterpart of [`Parser::current_is_identifier_or_keyword`],
    /// shared by the *key* positions that take an `IdentifierName`: the property
    /// after `.` / `?.` (`obj.class`, including a `new` callee's chain), a class
    /// member key, and a type-member key. `\u` escapes decode (`x.a` → name
    /// `a`; ecma262 `IdentifierName` StringValue) — acorn parity.
    ///
    /// # Precondition
    /// Current token must satisfy [`Parser::current_is_identifier_or_keyword`], so
    /// callers own the "not a name here" error and its wording.
    pub(super) fn parse_identifier_name_node(&mut self) -> Result<Identifier<'arena>, Error> {
        debug_assert!(self.current_is_identifier_or_keyword());
        let (start, end) = self.current_pos();
        let name = self.current_ident_name();
        self.advance()?;
        Ok(Identifier::simple(
            name,
            Span::new(start as u32, end as u32),
        ))
    }

    /// Check if peek token could be a class member name (identifier, keyword, computed key, or private identifier)
    ///
    /// Used to detect accessor syntax in class bodies:
    /// - `get x() {}` - getter (peek is `x` = identifier)
    /// - `get #x() {}` - private getter (peek is `#`)
    /// - `get [expr]() {}` - computed getter (peek is `[`)
    pub(super) fn peek_is_class_member_name(&mut self) -> bool {
        matches!(
            self.peek_kind(),
            TokenKind::Identifier
                | TokenKind::BracketOpen
                | TokenKind::String
                | TokenKind::Number
                | TokenKind::Keyword(_)
                | TokenKind::Hash
        )
    }

    /// Parse a private identifier: `#name`
    ///
    /// Current token must be `#`. ecma262 `PrivateIdentifier :: # IdentifierName`
    /// is a single *lexical* token, which pins both halves of what may follow:
    ///
    /// - the name is an `IdentifierName`, so **every** reserved word is a valid
    ///   private name (`#default`, `#class`, `#true`) — not just the contextual
    ///   keywords a `BindingIdentifier` admits. The one reserved private name,
    ///   `#constructor`, is rejected by the `ClassElementName` early error at the
    ///   class-member key site, on decoded StringValue.
    /// - the name is *glued* to the `#`: `# a`, `#/*c*/a` and `#⏎a` are two tokens,
    ///   not a private name (acorn rejects them in the lexer). Without the check
    ///   tsv accepted them and reprinted `#a` — rewriting invalid code as valid.
    ///
    /// Returns the PrivateIdentifier beside its span, which includes the `#`.
    pub(super) fn parse_private_identifier(
        &mut self,
    ) -> Result<(PrivateIdentifier<'arena>, Span), Error> {
        debug_assert!(matches!(self.current_kind(), TokenKind::Hash));
        let (start, hash_end) = self.current_pos();
        self.advance()?; // consume '#'

        // The `IdentifierName` name channel decodes `\u` escapes, so an escaped
        // spelling names the same private name (`#\u0061` is `#a`) — acorn parity.
        let (name_start, end) = self.current_pos();
        let Some(name) = self.try_identifier_name() else {
            return Err(self.error_expected_after("identifier", "#"));
        };
        if name_start != hash_end {
            return Err(self.error_msg_at("A private name must follow '#' immediately", hash_end));
        }
        self.advance()?;

        Ok((
            PrivateIdentifier { name },
            Span::new(start as u32, end as u32),
        ))
    }

    pub(super) fn expect(&mut self, kind: &TokenKind) -> Result<(), Error> {
        if self.check(kind) {
            self.advance()
        } else {
            Err(self.unexpected_token_err(kind))
        }
    }

    /// Construct the `UnexpectedToken` error for a failed `expect`. Cold-outlined
    /// out of the hot `expect` body: valid input never takes this branch, so the
    /// two `to_string` allocations + struct build shouldn't inflate the caller.
    #[cold]
    #[inline(never)]
    fn unexpected_token_err(&self, kind: &TokenKind) -> Error {
        Error::unexpected_token(
            kind.to_string(),
            self.current.kind.to_string(),
            self.current_pos().0,
        )
    }

    /// Expect `>` in type context, handling compound token splitting
    ///
    /// In TypeScript, compound tokens starting with `>` can appear in type contexts where
    /// they need to be split (e.g., `Array<Map<K, V>>`, `const k: <T>() => T = ...`).
    ///
    /// This method:
    /// - Consumes `>` normally if current token is `>`
    /// - Splits `>>` into `>` + `>`, consuming the first
    /// - Splits `>>>` into `>` + `>>`, consuming the first
    /// - Splits `>=` into `>` + re-lex (may become `=>`)
    /// - Splits `>>=` into `>` + re-lex (may become `>=` or `>` + `=`)
    /// - Splits `>>>=` into `>` + re-lex (may become `>>=`)
    ///   Consume a `>` in type context and return the end position of the consumed `>`.
    ///   Handles `>>`, `>>>`, `>=`, etc. by splitting the token.
    pub(super) fn greater_than_end_in_type(&mut self) -> Result<u32, Error> {
        let end = (self.current_pos().0 + 1) as u32;
        self.expect_greater_than_in_type()?;
        Ok(end)
    }

    pub(super) fn expect_greater_than_in_type(&mut self) -> Result<(), Error> {
        match self.current.kind {
            TokenKind::GreaterThan => {
                // Normal case: single `>`
                self.advance()
            }
            TokenKind::RightShift => {
                // `>>` - split into `>` + `>`
                // Consume first `>` by advancing start position. The split
                // only narrows the current token — `current.end` and every
                // later token boundary are unchanged — so a cached peek (lexed
                // from `current.end`) stays valid and MUST be kept: clearing
                // it would desync the cache from the lexer's cursor (the next
                // fill would silently skip the peeked token). `prev_end` moves to
                // the consumed `>`'s end, as `advance` would have set it.
                self.current.start += 1;
                self.prev_end = self.current.start as usize;
                self.current.kind = TokenKind::GreaterThan;
                Ok(())
            }
            TokenKind::UnsignedRightShift => {
                // `>>>` - split into `>` + `>>`
                // Consume first `>` by advancing start position; the cached
                // peek stays valid (see the `>>` arm).
                self.current.start += 1;
                self.prev_end = self.current.start as usize;
                self.current.kind = TokenKind::RightShift;
                Ok(())
            }
            TokenKind::GreaterThanEquals
            | TokenKind::RightShiftEquals
            | TokenKind::UnsignedRightShiftEquals => {
                // `>=`, `>>=`, `>>>=` - consume `>`, re-lex from next position
                // The remainder might combine with subsequent chars (e.g., `>=` -> `=>`)
                let new_start = self.current.start as usize + 1;
                self.prev_end = new_start;
                // Drop comments drained by a discarded peek — the seek below
                // re-lexes that region, and they'd be collected twice.
                let relex_from = self.span_pos(new_start);
                while self
                    .comments
                    .last()
                    .is_some_and(|c| c.span.start >= relex_from)
                {
                    self.comments.pop();
                }
                let token = self.lexer.seek_and_next_token(new_start)?;
                self.current = token;
                self.current_decoded = self.decoded_to_arena();
                // Clear peek cache since token changed
                self.peek = None;
                self.peek_decoded = None;
                Ok(())
            }
            _ => Err(Error::unexpected_token(
                "'>'".to_string(),
                self.current.kind.to_string(),
                self.current_pos().0,
            )),
        }
    }

    /// Whether the current token is `<` or the `<<` shift token, whose first
    /// `<` can open a type-argument list (`f<<T>(v: T) => void>()`) — the
    /// opening mirror of `check_greater_than_in_type`. `<<=` never splits: the
    /// `<=` remainder cannot continue a type-argument list (matches acorn).
    pub(super) fn check_less_than_in_type(&self) -> bool {
        matches!(
            self.current.kind,
            TokenKind::LessThan | TokenKind::LeftShift
        )
    }

    /// Expect `<` opening a type-argument list, splitting `<<` into `<` + `<`
    /// — the opening mirror of `expect_greater_than_in_type`.
    pub(super) fn expect_less_than_in_type(&mut self) -> Result<(), Error> {
        match self.current.kind {
            TokenKind::LessThan => self.advance(),
            TokenKind::LeftShift => {
                // Consume the first `<` by advancing the token start; the
                // remainder is the inner `<`. The cached peek stays valid
                // (see `expect_greater_than_in_type`'s `>>` arm), and `prev_end`
                // moves to the consumed `<`'s end, as `advance` would have set it.
                self.current.start += 1;
                self.prev_end = self.current.start as usize;
                self.current.kind = TokenKind::LessThan;
                Ok(())
            }
            _ => Err(Error::unexpected_token(
                "'<'".to_string(),
                self.current.kind.to_string(),
                self.current_pos().0,
            )),
        }
    }

    /// Check if current token is `>` or can be split to produce `>` (for type contexts)
    pub(super) fn check_greater_than_in_type(&self) -> bool {
        matches!(
            self.current.kind,
            TokenKind::GreaterThan
                | TokenKind::RightShift
                | TokenKind::UnsignedRightShift
                | TokenKind::GreaterThanEquals
                | TokenKind::RightShiftEquals
                | TokenKind::UnsignedRightShiftEquals
        )
    }

    /// Consume a token if it matches the given kind (optional token consumption)
    ///
    /// Returns `true` if the token was consumed, `false` otherwise. Consuming it lexes
    /// the token after it, and a lexer error there is returned at once — acorn's timing,
    /// where consuming a token reads the next. Held back instead, the error would read as
    /// the optional token's absence — a stray `=` in `function f(a = '\x4') {}`.
    ///
    /// Useful for optional syntax elements like:
    /// - Trailing commas: `[1, 2, 3,]` - eat(Comma) at end
    /// - Optional semicolons in some contexts
    /// - Optional type annotations: eat(Colon) to check presence
    ///
    /// # Example
    /// ```ignore
    /// let has_init = if self.eat(TokenKind::Equals)? {
    ///     Some(self.parse_expression()?)
    /// } else {
    ///     None
    /// };
    /// ```
    pub(super) fn eat(&mut self, kind: TokenKind) -> Result<bool, Error> {
        if self.check(&kind) {
            self.advance()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Consume a contextual keyword if present (identifier with specific value).
    /// Returns true if consumed, false otherwise; a lexer error on the token after it is
    /// returned, as [`Parser::eat`] returns one.
    #[inline]
    pub(super) fn eat_contextual_keyword(&mut self, keyword: &str) -> Result<bool, Error> {
        if matches!(self.current_kind(), TokenKind::Identifier) && self.current_value() == keyword {
            self.advance()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Check if the next (peek) token is a contextual keyword.
    /// Does not consume any tokens (only peeks).
    #[inline]
    pub(super) fn peek_is_contextual_keyword(&mut self, keyword: &str) -> bool {
        matches!(self.peek_kind(), TokenKind::Identifier) && self.peek_value() == keyword
    }

    /// Whether a type-predicate `is` follows the current subject token — the
    /// `parameterName [no LineTerminator here] is Type` rule (a newline before
    /// `is` makes it a stray token, matching acorn-typescript's
    /// `hasPrecedingLineBreak` guard, like the arrow `=>` / conditional
    /// `extends`). Assumes the current token is the predicate subject
    /// (`x` / `this`). Shared by the return-position predicate parser and the
    /// `this is T` primary-type sites. Does not consume any tokens (only peeks).
    #[inline]
    pub(super) fn peek_predicate_is_ahead(&mut self) -> bool {
        self.peek_is_contextual_keyword("is") && !self.peek_preceded_by_line_terminator()
    }

    /// Eat a leading `asserts` type-predicate keyword, committing only when an
    /// identifier or keyword follows it. Mirrors tsc's `parseNonArrayType`
    /// dispatch (`parser.ts`): `asserts` is a type-predicate prefix iff
    /// `nextTokenIsIdentifierOrKeyword` — otherwise (punctuation/literal: `{`,
    /// `[`, `<`, `.`, `|`, `&`, `;`, …) it stays an ordinary type name
    /// (`: asserts`, `: asserts[]`, `: asserts<T>`, `: asserts.Foo`), left
    /// unconsumed for the caller to parse as a regular type. When a *reserved*
    /// keyword follows (`asserts extends …`), the prefix commits and the caller
    /// then rejects it as a missing parameter name — matching tsc, which parses
    /// the keyword as the asserted identifier and errors.
    /// The asserted name must also be on the SAME line: tsc gates the whole reading on
    /// `lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine)`, so across a break `asserts`
    /// is the ordinary type reference of that name and what follows begins nothing valid
    /// (TS1434; prettier rejects with it). acorn instead welds into the very
    /// `TSTypePredicate` it builds for the same-line spelling, discarding the line
    /// terminator — the shape target is not the validity oracle, so tsv follows tsc.
    /// Per ecma262 §sec-comments a block comment holding a line terminator IS one, so
    /// `asserts /*⏎*/ a` declines on the same rule.
    pub(super) fn eat_type_predicate_asserts(&mut self) -> Result<bool, Error> {
        if matches!(self.current_kind(), TokenKind::Identifier)
            && self.current_value() == "asserts"
            && self.peek_is_identifier_or_keyword()
            && !self.peek_preceded_by_line_terminator()
        {
            self.advance()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Check if a semicolon can be inserted at the current position (ASI).
    ///
    /// Returns true if:
    /// - Current token is EOF, OR
    /// - Current token is `}`, OR
    /// - A line terminator occurred between the previous token and current token
    ///
    /// This is the core ASI detection per ECMAScript spec section 12.9.
    pub(super) fn can_insert_semicolon(&self) -> bool {
        matches!(self.current.kind, TokenKind::Eof | TokenKind::BraceClose)
            || self.had_line_terminator
    }

    /// Consume a semicolon, or accept if ASI allows one.
    ///
    /// This is the main ASI entry point for statement termination.
    /// Use this instead of `expect(&TokenKind::Semicolon)` for statement-ending semicolons.
    ///
    /// Returns Ok(()) if:
    /// - A semicolon token was consumed, OR
    /// - ASI conditions allow implicit semicolon insertion
    ///
    /// Returns Err if neither explicit semicolon nor ASI conditions are met.
    /// Consume a semicolon and return the end position (including the semicolon).
    /// Use this for statement spans that include the trailing semicolon.
    pub(super) fn semicolon_end(&mut self) -> Result<u32, Error> {
        self.semicolon()?;
        Ok(self.prev_token_end() as u32)
    }

    pub(super) fn semicolon(&mut self) -> Result<(), Error> {
        if self.eat(TokenKind::Semicolon)? {
            return Ok(());
        }
        if self.can_insert_semicolon() {
            return Ok(());
        }
        Err(self.error_expected("';'"))
    }

    /// Handle list separator (comma) and terminator in list parsing
    ///
    /// Consolidates comma/terminator handling across:
    /// - Object properties: `{ a: 1, b: 2 }`
    /// - Array elements: `[1, 2, 3]`
    /// - Function parameters: `fn(a, b, c)`
    /// - Type parameters: `Array<T, U>`
    ///
    /// Returns:
    /// - `Ok(true)` if more elements expected (found separator, not at terminator)
    /// - `Ok(false)` if list ended (found terminator or trailing separator)
    /// - `Err(Error)` if neither separator nor terminator found
    ///
    /// Handles trailing separators uniformly: `[1, 2,]` is valid
    ///
    /// # Example
    /// ```ignore
    /// loop {
    ///     properties.push(self.parse_property()?);
    ///     if !self.expect_list_separator(&TokenKind::Comma, &TokenKind::BraceClose)? {
    ///         break;
    ///     }
    /// }
    /// ```
    pub(super) fn expect_list_separator(
        &mut self,
        separator: &TokenKind,
        terminator: &TokenKind,
    ) -> Result<bool, Error> {
        if self.check(separator) {
            self.advance()?;
            if self.check(terminator) {
                Ok(false) // Trailing separator, end of list
            } else {
                Ok(true) // More elements expected
            }
        } else if self.check(terminator) {
            Ok(false) // End of list
        } else {
            Err(self.error_list_separator(separator, terminator))
        }
    }

    pub(crate) fn parse(&mut self) -> Result<Program<'arena>, Error> {
        self.parse_program()
            .map_err(|error| self.mark_await_operand_gate(error))
    }

    /// Mark a Script error sitting exactly at the operand a module would have read after
    /// a name `await` (`await_name_operand`, noted by `parse_await_name_reference`) as a
    /// goal gate: the parse died there only because `await` is a name at this goal, so
    /// the source was written as a module and the format fallback reports the module
    /// attempt's error (`parse_with_goal_or_fallback`). Applied once, here, rather than
    /// where the error is raised, because any kind of error can land on that token.
    fn mark_await_operand_gate(&self, error: Error) -> Error {
        if self.await_name_operand.is_some() && error.position() == self.await_name_operand {
            error.into_goal_gate()
        } else {
            error
        }
    }

    fn parse_program(&mut self) -> Result<Program<'arena>, Error> {
        let start = self.base_offset; // Start at base_offset for embedded contexts

        // The outermost strictness scope: a Script's `"use strict"` prologue turns
        // strict mode on for everything after it, and the flag is restored on the way
        // out so a re-used parser starts from the goal's own seed again.
        let body = self.with_strict_scope(|p| {
            p.statement_list(1, |p, frame| {
                let mut body = p.bvec();
                let mut in_prologue = true;
                while p.current.kind != TokenKind::Eof {
                    let mut item = p.parse_module_item(statement::ModuleItemContext::TopLevel)?;
                    frame.next(p);
                    if in_prologue {
                        in_prologue = p.note_directive(&mut item, &body)?;
                    }
                    body.push(item);
                }
                Ok(body)
            })
        })?;

        // Use current_pos() to get global position (includes base_offset)
        let (_, end) = self.current_pos();

        Ok(Program {
            body: body.into_bump_slice(),
            comments: self.take_comments(),
            span: Span::new(start as u32, end as u32),
            goal: self.goal,
        })
    }

    /// Parse a single expression, WITHOUT requiring it to fill the input slice — the raw
    /// parse the pattern path builds on: `parse_pattern_with_comments` parses here, converts
    /// the result to a Svelte pattern, then enforces end-of-input itself. (Expression tags
    /// use `parse_expression_with_comments`, which requires full consumption via
    /// `expect_end_of_input`.)
    pub(crate) fn parse_expression_unbounded(&mut self) -> Result<Expression<'arena>, Error> {
        self.parse_expression()
    }

    /// Require that parsing has consumed the whole input slice — the current token must
    /// be `Eof`. Trailing trivia (comments, whitespace) is consumed by the lexer, so only
    /// a stray *token* trips this.
    ///
    /// The Svelte embedders parse an expression or pattern from a slice bounded by `}`
    /// (`{@html expr}`, `{@const id = init}`, `{:then pattern}`, …) and require it to fill
    /// the slice exactly — Svelte's `eat('}', true)`. Without this check a trailing token
    /// is silently dropped (`{@html a b}` → `{@html a}`), which loses content rather than
    /// diverging visibly.
    ///
    /// `end` is what the message says was expected in the stray token's place: the slice's
    /// end as the caller knows it. For an island that is the host's delimiter (`'}'`,
    /// `')'`), since the document goes on past it and the delimiter is what is missing.
    /// The island's parser knows nothing else of its host, and the name is handed to this
    /// check alone rather than stored on the parser.
    pub(crate) fn expect_end_of_input(&self, end: &str) -> Result<(), Error> {
        if self.current.kind == TokenKind::Eof {
            Ok(())
        } else {
            Err(self.error_expected_found(end))
        }
    }

    /// Parse a single expression and return it with any collected comments.
    /// Used for expressions in Svelte templates where comments need to be preserved.
    /// The expression must fill the whole slice, whose end `end` names (see
    /// `expect_end_of_input`).
    pub(crate) fn parse_expression_with_comments(
        &mut self,
        end: &str,
    ) -> Result<(&'arena Expression<'arena>, &'arena [Comment]), Error> {
        let expr = self.parse_expression_ref()?;
        self.expect_end_of_input(end)?;
        let comments = self.take_comments();
        Ok((expr, comments))
    }

    /// Hand the collected comments to the caller as an arena slice.
    /// Used when parsing expressions that need to return comments to the caller.
    pub(crate) fn take_comments(&mut self) -> &'arena [Comment] {
        std::mem::replace(&mut self.comments, BumpVec::new_in(self.arena)).into_bump_slice()
    }

    /// Parse a single assignment expression and return position where parsing stopped.
    ///
    /// Unlike `parse_expression_unbounded()`, this stops at top-level commas.
    /// This is useful for parsing expressions embedded in contexts where commas
    /// have other meanings (like `{#each items as pattern, index}`).
    ///
    /// `top_level_as` decides whether a top-level `as` belongs to this parse or to the
    /// host's own grammar — see [`TopLevelAs`], which states the rule and names both
    /// callers. `satisfies` is unaffected either way.
    ///
    /// Returns (expression, end_position) where end_position is where the next
    /// unparsed content begins (in absolute source coordinates with base_offset).
    pub(crate) fn parse_assignment_expression_partial(
        &mut self,
        top_level_as: TopLevelAs,
    ) -> Result<(&'arena Expression<'arena>, usize), Error> {
        let saved = std::mem::replace(
            &mut self.top_level_as_is_assertion,
            top_level_as == TopLevelAs::Assertion,
        );
        let result = self.parse_assignment_expression_ref();
        self.top_level_as_is_assertion = saved;

        let expr = result?;
        // Return the start of the current (unconsumed) token
        let next_pos = self.current.start as usize + self.base_offset;
        Ok((expr, next_pos))
    }

    /// Convert an expression to a Svelte block or tag pattern — an `{#each}` context, a
    /// `{:then}` / `{:catch}` value, a `{@const}` id
    /// (`crate::__private::parse_pattern_with_comments`).
    ///
    /// This converts ObjectExpression to ObjectPattern, ArrayExpression to ArrayPattern,
    /// etc., under Svelte's reading of the pattern as an assignment target. A
    /// declaration's or parameter's binding pattern never comes through here; it is read
    /// by `parse_binding_pattern`.
    ///
    /// # Arguments
    ///
    /// * `expr` - The expression to convert (typically an ObjectExpression or ArrayExpression)
    ///
    /// # Returns
    ///
    /// * `Ok(Expression)` - The converted pattern (ObjectPattern, ArrayPattern, etc.)
    /// * `Err(Error)` - If the expression cannot be converted to a valid pattern
    pub(crate) fn expression_to_svelte_pattern(
        &mut self,
        expr: Expression<'arena>,
    ) -> Result<Expression<'arena>, Error> {
        // Svelte block and `{@const}` patterns, which Svelte reads as assignment
        // targets: a member or parenthesized target is accepted, a type-assertion
        // target still rejects (see `AssignableContext::SveltePattern`).
        self.refine_assignable(
            expr,
            expression_assignable::AssignableContext::SveltePattern,
        )
    }

    /// Parse a string literal into a Literal node.
    ///
    /// Most callers first confirm a `String` token, but the module `from`/source
    /// paths (`export * from …`, `export { … } from …`) reach here directly on
    /// arbitrary input, so a non-`String` token is returned as a clean parse error
    /// rather than panicking (debug) or mis-extracting a "string" from the wrong
    /// token (release, where a bare `debug_assert!` would be elided). Surfaced by
    /// the `fuzz` gate (`tsv_debug fuzz`).
    pub(super) fn parse_string_literal(&mut self) -> Result<Literal<'arena>, Error> {
        if !matches!(self.current_kind(), TokenKind::String) {
            return Err(self.error_expected("string literal"));
        }

        let (start, end) = self.current_pos();
        let cooked = self.extract_string_cooked()?;
        self.advance()?;

        Ok(Literal {
            value: LiteralValue::String(cooked),
            span: Span::new(start as u32, end as u32),
        })
    }
}

/// Parse TypeScript source code into an AST allocated in `arena`.
pub(crate) fn parse_typescript<'arena>(
    source: &str,
    arena: &'arena Bump,
) -> Result<Program<'arena>, Error> {
    parse_typescript_with_goal(source, Goal::Module, arena)
}

/// Build a parser of `source` at `base_offset` against `goal`, prime it and run `f` — the
/// driver every parse entry point runs through, standalone ([`parse_typescript_with_goal`])
/// and embedded (`crate::with_embedding_parser`, which Svelte's entry points take). What
/// `f` returns borrows only `arena`. Error context (`with_context`) is applied by the
/// public `crate::parse*` wrappers, not here.
///
/// **The acorn re-parse.** A whole type-argument list followed by a token only tsc refuses
/// (a `<`, or a `+` / `-` past a line break) is given up to tsc's comparison wherever that
/// comparison parses as an expression, and kept where it does not
/// ([`Parser::type_arguments_follower_settled`]). That reading is tsc's only where tsc
/// accepts the text, and where tsc rejects a text acorn-typescript accepts, tsv keeps
/// acorn's reading — of the whole text, every list read as acorn reads it. So a parse
/// that gave a list up is run once more with none given up ([`Parser::tsc_followers`]
/// off) when tsc rejects the text, which it does in two ways:
///
/// - **The parse kept a list too.** tsc's comparison does not parse there, so tsc
///   rejects the text, and every list given up elsewhere in it is acorn's —
///   `f<() => A><U><V>(x)` calls `f<() => A><U>` with `<V>`, never
///   `(f<() => A> < U) > <V>(x)`, and in `f<string[]><U>(g<T><V>(y))` the argument is
///   acorn's call too. The re-parse's result is taken; should it fail, the first one is.
/// - **The parse failed.** The speculation cannot see the context around the expression,
///   which may refuse what it read: in `const a = f<T, U><V>(x)` the comparison's `,`
///   ends the declarator ahead of a second one that is no binding, and in an arrow body,
///   a conditional branch or a property value the `,` ends the expression where none may
///   follow. tsc rejects those texts and acorn parses them. The re-parse's result is
///   taken if it parses.
///
/// A text tsc accepts gives lists up and keeps none, so it never pays for the second
/// parse, and neither does a failed parse that gave nothing up.
///
/// **The host's refusals are part of the parse.** An embedder whose grammar refuses what
/// the parse returned — a Svelte head whose `as` / `then` boundary is missing, a
/// `{@const}` init that reads as a second declarator, a `{@render}` that is no call — is
/// the context around the expression in the same sense, so it hands that refusal in as
/// `host_check`, which runs on each parse's result; a refusal fails that parse, and the
/// failed tsc-reading parse is retried like any other. Run after the parse rather than
/// inside `f`, a refusal never trades places with an abandoned type-argument list's error
/// (`Parser::prefer_abandoned_type_arguments_error`), which is the parse's own.
///
/// **Which error a text both readings fail reports** follows who reads the text.
/// `embedded` says a host document holds it — a Svelte `<script>` or template island,
/// every embedding entry point's text. Svelte reads each of those with acorn-typescript,
/// so the re-parse's error, acorn's reading's, is the one reported, whether a refusal
/// of the host's or the parse's own failure: it lands where Svelte's does —
/// `{const a = f<T, U><V>(x) /* c */}` reports the content after the declaration and
/// `{a ? f<T, U><V>(x) : }` the missing alternate, not tsc's stop at the `,` or the
/// `<V>`. A standalone text has no host to read it as acorn does, and tsc's reading is the
/// one it is given, so where each failed inside the parse itself the first parse's error
/// is reported (`a ? f<T, U><V>(x) : ;` stops at tsc's `,`).
///
/// `host_nesting` is the nesting the host document has spent where the text sits (`0`
/// standalone): both parses start their depth count there ([`DepthBudget::at`]), so an
/// island deep in Svelte markup has only what the markup left of the document's budget.
// Every argument is a distinct input of the one driver both parses share; bundling two of
// them into a struct would only move the count.
#[expect(clippy::too_many_arguments)]
pub(crate) fn parse_retrying_acorn_followers<'arena, T>(
    source: &str,
    base_offset: usize,
    host_nesting: u32,
    goal: Goal,
    arena: &'arena Bump,
    embedded: bool,
    f: impl Fn(&mut Parser<'_, 'arena>) -> Result<T, Error>,
    host_check: impl Fn(&T) -> Result<(), Error>,
) -> Result<T, Error> {
    // Each failure carries whether the host refused it (`true`) or the parse itself did.
    let checked = |parsed: T| {
        host_check(&parsed)
            .map(|()| parsed)
            .map_err(|error| (error, true))
    };
    let mut parser = Parser::new(source, base_offset, goal, arena);
    parser.depth = DepthBudget::at(host_nesting);
    parser.prime()?;
    let first = f(&mut parser)
        .map_err(|error| (parser.prefer_abandoned_type_arguments_error(error), false))
        .and_then(checked);
    if !parser.gave_up_list_to_tsc_follower
        || (first.is_ok() && !parser.kept_list_past_tsc_follower)
    {
        return first.map_err(|(error, _)| error);
    }
    let mut retry = Parser::new(source, base_offset, goal, arena);
    retry.depth = DepthBudget::at(host_nesting);
    retry.tsc_followers = false;
    let second = retry
        .prime()
        .and_then(|()| f(&mut retry))
        .map_err(|error| (error, false))
        .and_then(checked);
    match (second, first) {
        (Ok(parsed), _) | (Err(_), Ok(parsed)) => Ok(parsed),
        (Err((_, false)), Err((error, false))) if !embedded => Err(error),
        (Err((error, _)), Err(_)) => Err(error),
    }
}

/// [`parse_typescript`] against an explicit goal symbol. `parse_typescript` is
/// the `Goal::Module` form.
// `Parser::parse` (clippy's method-path suggestion) fails the higher-ranked
// lifetime check on `parse_retrying_acorn_followers`'s `f` bound; the closure infers it.
#[expect(clippy::redundant_closure_for_method_calls)]
pub(crate) fn parse_typescript_with_goal<'arena>(
    source: &str,
    goal: Goal,
    arena: &'arena Bump,
) -> Result<Program<'arena>, Error> {
    parse_retrying_acorn_followers(
        source,
        0,
        0,
        goal,
        arena,
        false,
        |parser| parser.parse(),
        |_| Ok(()),
    )
}

/// [`parse_typescript`] with grouping parens preserved as `ParenthesizedExpression`
/// nodes (acorn's `preserveParens: true`). Standalone analog of
/// `crate::__private::parse_embedded_preserve_parens` — the binding audit
/// (`tsv_debug binding_audit`) reparses formatted output this way so the paren
/// structure a glued comment binds to is visible in the wire JSON.
pub(crate) fn parse_typescript_preserve_parens<'arena>(
    source: &str,
    arena: &'arena Bump,
) -> Result<Program<'arena>, Error> {
    parse_retrying_acorn_followers(
        source,
        0,
        0,
        Goal::Module,
        arena,
        false,
        |parser| {
            parser.preserve_parens = true;
            parser.parse()
        },
        |_| Ok(()),
    )
}