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
// Expression parsing using Pratt parser for operator precedence
use crate::ast::{
AssignmentExpression, AssignmentOperator, AwaitExpression, BinaryExpression, BinaryOperator,
BlockStatement, CallExpression, CommentBoundPair, CommentBoundPairKind, ConditionalExpression,
Expression, ExpressionKind, IdentName, Identifier, ImportExpression, ImportPhase, Literal,
LiteralValue, MemberExpression, MetaProperty, NewExpression, ParenthesizedExpression,
RegexLiteral, SequenceExpression, SpreadElement, Statement, Super, TSAsExpression,
TSInstantiationExpression, TSNonNullExpression, TSSatisfiesExpression, TSTypeAssertion,
TSTypeParameterInstantiation, TaggedTemplateExpression, TemplateLiteral, ThisExpression,
UnaryExpression, UnaryOperator, UpdateExpression, UpdateOperator, YieldExpression,
};
use crate::lexer::{KeywordKind, TokenKind};
use crate::parser::expression_assignable::AssignableContext;
use crate::printer::ParenContext;
use tsv_lang::printing::visual_width;
use tsv_lang::source_scan;
use tsv_lang::{Error, Span, TAB_WIDTH};
use super::expression_lookahead::{
ArrowHead, has_line_terminator_between, matching_angle_close,
type_args_follower_refused_by_tsc_alone, type_args_follower_refuses,
};
use super::expression_type_args::TypeArgScan;
use super::scan::{
LeadingZeroLiteral, classify_leading_zero, parse_number_literal, skip_whitespace,
skip_whitespace_and_comments,
};
use super::{
Checkpoint, GroupingParen, LINK_ASSERTION, LINK_NON_NULL, LINK_OPERATOR, LINK_REENTRY,
LINK_SUBSCRIPT, LINK_TAG, Parser, RootEnd,
};
//
// Binding Power Constants for Pratt Parser
//
// Higher values = tighter binding (evaluated first)
// Left-associative: left_bp < right_bp
// Right-associative: left_bp > right_bp
/// Comma operator (sequence expression) - lowest precedence
const BP_COMMA: u8 = 0;
/// Assignment operators (=, +=, etc.) and ternary conditional
const BP_ASSIGNMENT: u8 = 1;
/// TypeScript `as` / `satisfies` bind at RELATIONAL precedence — tsc's
/// `getBinaryOperatorPrecedence` returns `OperatorPrecedence.Relational` for both
/// (the same tier as `<` / `>` / `instanceof` / `in`), and acorn-typescript gates
/// them on `tt._in.binop` (relational) in its `parseExprOp` override. This equals
/// the relational `left_bp` in `infix_operator_info`, so `x === y as T` parses
/// `x === (y as T)` (tighter than equality / logical / bitwise / `??`) while
/// `a + b as T` stays `(a + b) as T` (looser than additive / shift /
/// multiplicative). Left-associative — `a as T as U` is `(a as T) as U`, and
/// `a < b as T` is `(a < b) as T` (breaks as the right operand of a same-tier
/// relational operator) — with the right-hand side consumed as a *type* by
/// `parse_type`, not an expression.
const BP_AS: u8 = 19;
/// Yield expression (same as assignment — yield takes AssignmentExpression per spec)
const BP_YIELD: u8 = 1;
/// Unary operators (!, -, +, ~, typeof, void, delete, await, ++, --, new)
const BP_UNARY: u8 = 29;
// ## The expression ladder's return currency
//
// Every `parse_*` on the expression cycle returns `Result<&'arena Expression, Error>`:
// the node is built in the arena at the tail of its own builder (`alloc_expr`) and the
// recursion moves a reference. That `Result` is two words — the reference plus the
// pointer-sized `Error`'s discriminant — which x86-64 returns in two registers. A
// wider success value does not: `{&Expression, u32, u32}` is the same 16 B once the error
// niche-packs into it, but a three-field aggregate is no two-scalar pair, so it came back
// through an sret stack slot at every outlined call. (wasm32 returns every `Result` through
// a slot either way.)
//
// **An expression's paren-inclusive extent is the tokens its parse consumed**, so it
// travels with no field at all: it starts at the token current when the parse begins and
// ends at `Parser::prev_token_end` when the parse returns. That extent is wider than the
// node's own semantic `span` exactly when the parse stripped a grouping paren shell —
// `(a && b) || c`'s left operand spans `a && b`, while the `||` node starts at the `(`,
// and `(a ? b : c)()`'s call starts at the `(` rather than the ternary. So a caller that
// needs the extent reads it where it is exact: the start before the call (most already
// hold it — `parse_expression_bp`'s `expr_start`, `parse_prefix_expression`'s
// `head_start`), the end immediately after the call returns, before anything else is
// consumed. A caller that asks "was this operand parenthesized?" compares the extent's
// start with the node's own `span().start`.
//
// ⚠️ The frame is what the reference buys as much as the return. LLVM gives each sret call
// site its own stack slot and does not merge them across match arms, and a frame is sized
// once for its widest arm — so a dispatcher with N arms that each call a `parse_*` returning
// a bare `Expression` (72 B) reserves N × 72 B at **every** recursion level, whichever arm
// it takes. `Parser::parse_prefix_expression` and `Parser::parse_primary_expression` are
// those dispatchers, and both sit on the paren / call / member / object-literal cycle, so
// their slots set the stack every nesting level costs, which the depth limits' margin is
// made of — see `docs/cli.md` §Recursion Depth. The rule
// that follows: **no `parse_*` reached from a dispatcher returns the bare `Expression`
// enum.** A builder returns either the arena reference (boxing at its own tail) or its own
// concrete node struct — an `ObjectExpression` / `ArrayExpression` / `TemplateLiteral` is
// 32–40 B and niche-packs into its `Result`, so the arm that wraps one in `Expression::…`
// inline builds a temporary LLVM *does* merge with its sibling arms'. The type parser keeps
// the same rule for `TSType` (`Parser::parse_type`).
//
// The assert is width-relative (a reference and an `Error` are each one `usize`), so it
// would hold on the 32-bit `wasm32` build too, where the return is a slot regardless. The
// `Result`'s two words are rustc's layout, not a guarantee, so it is pinned in the test build.
#[cfg(test)]
const _: () = assert!(size_of::<Result<&Expression<'static>, Error>>() == 2 * size_of::<usize>());
/// Box a freshly built expression node into the arena — the tail of every node builder
/// on the expression ladder (see §The expression ladder's return currency above).
///
/// Called at the **tail of the node builder**, never by its caller: a `parse_*` that
/// hands back a bare `Expression` makes its caller hold a 72 B value across the boxing
/// call, and a caller with N such arms pays N slots in **every** frame.
#[inline]
pub(in crate::parser) fn alloc_expr<'arena>(
arena: &'arena bumpalo::Bump,
expr: Expression<'arena>,
) -> &'arena Expression<'arena> {
arena.alloc(expr)
}
/// Debug-check a node extent derived from the parser's cursor against the operands it
/// covers: the span `start..end` must enclose `first`'s start and `last`'s end. A
/// derived end is read as `Parser::prev_token_end` after an operand parse returns, so an
/// arm that consumes a token without moving that cursor (a split `>` closing type
/// arguments) would silently shorten the node below its own child. Compiled out of
/// release builds — the operands are read only inside the `debug_assert!`.
#[inline]
pub(in crate::parser) fn debug_assert_encloses(
start: u32,
end: u32,
first: &Expression<'_>,
last: &Expression<'_>,
) {
debug_assert!(
start <= first.span().start && last.span().end <= end,
"derived extent {start}..{end} must enclose its operands {}..{}",
first.span().start,
last.span().end
);
}
/// Whether `expr`, whose parse began at `start`, is a leading *unparenthesized*
/// expression that is itself a complete `AssignmentExpression` no subscript or operator
/// may extend — a bare arrow function (always), or a bare `yield` expression when
/// parsing inside a generator (`in_yield`). Both are top-level `AssignmentExpression`
/// alternatives (ecma262 §13.15 — `ArrowFunction` / `YieldExpression`), not a
/// `ConditionalExpression`, binary operand, or `LeftHandSideExpression`, so both
/// `parse_prefix_expression` (call / member / postfix) and `parse_expression_bp`
/// (binary / `as` / assignment / ternary) must stop when this holds. The check is
/// span-anchored: a bare head's own span starts exactly where its parse began, but
/// parenthesizing (`(() => {})` / `(yield)`) begins the parse at the outer `(` while the
/// inner span starts later, so the two diverge — a parenthesized arrow/yield is a primary
/// that CAN be an operand and is (correctly) not flagged.
///
/// `yield` is only a `YieldExpression` in `[+Yield]`; outside a generator it is a
/// (deferred) reserved-word identifier that prettier accepts as an operand, so the guard
/// must not fire there — hence the `in_yield` gate. See the parser's `in_yield` field.
fn is_bare_assignment_head(expr: &Expression<'_>, start: usize, in_yield: bool) -> bool {
let is_head = matches!(expr.kind, ExpressionKind::ArrowFunctionExpression(_))
|| (in_yield && matches!(expr.kind, ExpressionKind::YieldExpression(_)));
is_head && start == expr.span().start as usize
}
/// How `parse_postfix_expression` should treat the subscript chain.
///
/// `ClassHeritage` is the `extends <expr>` clause — a `LeftHandSideExpression` that
/// deviates from a normal subscript chain in two ways: a bare `<T>` (type args the
/// expression does not go on past — `Parser::heritage_type_args_continue_expression`)
/// stops the chain so the class can split it into
/// `super_type_parameters`, and a postfix `++`/`--` is left UNCONSUMED (the arm is
/// `Normal`-only), so `class C extends a++ {}` parses the heritage as `a` and the
/// stray `++` is rejected. In `Normal` mode a postfix `++`/`--` IS consumed as an
/// `UpdateExpression`, which then ends the chain — an update expression is not a
/// `LeftHandSideExpression`, so no further subscript can apply.
#[derive(Clone, Copy, PartialEq, Eq)]
enum SubscriptMode {
Normal,
ClassHeritage,
}
// ## Forward-binding comments
//
// A comment glued to the token after it is **bound to that token** — read by some other
// tool (or by tsv's own layout) as modifying the *next* thing, so anything printed between
// the two changes what it modifies. **Every glued block comment is owned** (`owned_by_node`,
// set by `bind_leading_comment`): ownership is keyed on *position* (glued-ness), not content.
// The one content classifier below, `is_jsdoc_type_cast_comment`, is no longer an ownership
// membership test — it decides a **cast's paren-retention** (whether `(expr)` becomes a
// `CommentBoundPair` node). It retains a residual ownership role only because a cast's comment may
// sit a newline *above* its `(` (`CommentGlue::AnyLine`), which the general `SameLine`-glued
// rule doesn't reach; a same-line cast comment's ownership is already subsumed by that rule.
// A glued block keeps its pair as well when the pair's interior opens with a line comment
// (`CommentBoundPairKind::GluedComment`, `glued_comment_pair_index`) — position again, not
// content.
//
// An owned comment must be printed by some node — an owned comment nothing prints is a
// *dropped* comment. See `printer/comments/owned.rs`.
/// Mirror of prettier's `isTypeCastComment` (`is-type-cast-comment.js`): the
/// comment text (between `/*` and `*/`) starts with `*` — i.e. the `/**` form —
/// and contains `@type` or `@satisfies` followed by a word boundary.
///
/// Binds forward to the `(` it glues to: the comment plus those parens **are** the cast.
///
/// Re-exported as [`crate::__private::is_jsdoc_type_cast_comment`] for the binding audit.
pub(crate) fn is_jsdoc_type_cast_comment(value: &str) -> bool {
value.starts_with('*') && contains_type_or_satisfies_tag(value)
}
/// Whether `value` contains `@type` or `@satisfies` with a trailing word
/// boundary (so `@types` / `@typedef` don't match), matching prettier's
/// `/@(?:type|satisfies)\b/`. The boundary is **ASCII** (`[A-Za-z0-9_]`) to
/// mirror that regex exactly — JS `\b` has no `u` flag here, so `@typeñ` ends
/// the tag at the non-ASCII `ñ` and counts as a cast.
fn contains_type_or_satisfies_tag(value: &str) -> bool {
for tag in ["@type", "@satisfies"] {
let mut from = 0;
while let Some(rel) = value[from..].find(tag) {
let abs = from + rel;
let after = abs + tag.len();
let boundary = value[after..]
.chars()
.next()
.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_'));
if boundary {
return true;
}
from = abs + 1;
}
}
false
}
/// The byte offset of the infix operator that joins an ALREADY-BUILT binary node's two
/// operands, located forward from the left operand's `span.end` — the first significant
/// byte past it that is not a `)`, since a paren shell around an operand is outside that
/// operand's own span (`(a) < b`, `((a)) < b`). `None` when the byte found is not
/// `expected`, which is the whole verification: a caller that cannot place its own
/// operator asks nothing further of it.
///
/// A binary node records no operator offset of its own — 4 bytes on every one, to serve
/// the one reader below — so the bytes answer instead, and the reader is a cold path.
fn infix_operator_offset(bytes: &[u8], left_end: usize, expected: u8) -> Option<usize> {
let mut pos = skip_whitespace_and_comments(bytes, left_end);
while bytes.get(pos) == Some(&b')') {
pos = skip_whitespace_and_comments(bytes, pos + 1);
}
(bytes.get(pos) == Some(&expected)).then_some(pos)
}
/// Infix operator info: binding powers and the corresponding binary operator.
///
/// Returns `(left_bp, right_bp, operator)` if the token is a binary operator.
/// - `left_bp < right_bp` for left-associative operators
/// - `left_bp > right_bp` for right-associative operators (e.g., `**`)
///
/// Uses standard JS operator precedence.
fn infix_operator_info(kind: &TokenKind) -> Option<(u8, u8, BinaryOperator)> {
match kind {
// Nullish coalescing: same precedence as `||` (tsc's `Coalesce = LogicalOR`),
// left-associative — so the (ungrammatical) `a ?? b || c` mix groups as
// `(a ?? b) || c` like tsc/prettier, not `a ?? (b || c)`. Valid code never
// mixes `??` with `||`/`&&` unparenthesized (the grammar forbids it), so this
// shared level only decides error-recovery grouping.
TokenKind::QuestionQuestion => Some((7, 8, BinaryOperator::QuestionQuestion)),
// Logical OR
TokenKind::PipePipe => Some((7, 8, BinaryOperator::PipePipe)),
// Logical AND
TokenKind::AmpersandAmpersand => Some((9, 10, BinaryOperator::AmpersandAmpersand)),
// Bitwise OR
TokenKind::Pipe => Some((11, 12, BinaryOperator::Pipe)),
// Bitwise XOR
TokenKind::Caret => Some((13, 14, BinaryOperator::Caret)),
// Bitwise AND
TokenKind::Ampersand => Some((15, 16, BinaryOperator::Ampersand)),
// Equality
TokenKind::EqualsEquals => Some((17, 18, BinaryOperator::EqualsEquals)),
TokenKind::BangEquals => Some((17, 18, BinaryOperator::BangEquals)),
TokenKind::EqualsEqualsEquals => Some((17, 18, BinaryOperator::EqualsEqualsEquals)),
TokenKind::BangEqualsEquals => Some((17, 18, BinaryOperator::BangEqualsEquals)),
// Relational (including in, instanceof)
TokenKind::LessThan => Some((19, 20, BinaryOperator::LessThan)),
TokenKind::GreaterThan => Some((19, 20, BinaryOperator::GreaterThan)),
TokenKind::LessThanEquals => Some((19, 20, BinaryOperator::LessThanEquals)),
TokenKind::GreaterThanEquals => Some((19, 20, BinaryOperator::GreaterThanEquals)),
TokenKind::Keyword(KeywordKind::Instanceof) => Some((19, 20, BinaryOperator::Instanceof)),
TokenKind::Keyword(KeywordKind::In) => Some((19, 20, BinaryOperator::In)),
// Bitshift
TokenKind::LeftShift => Some((21, 22, BinaryOperator::LeftShift)),
TokenKind::RightShift => Some((21, 22, BinaryOperator::RightShift)),
TokenKind::UnsignedRightShift => Some((21, 22, BinaryOperator::UnsignedRightShift)),
// Additive
TokenKind::Plus => Some((23, 24, BinaryOperator::Plus)),
TokenKind::Minus => Some((23, 24, BinaryOperator::Minus)),
// Multiplicative
TokenKind::Star => Some((25, 26, BinaryOperator::Star)),
TokenKind::Slash => Some((25, 26, BinaryOperator::Slash)),
TokenKind::Percent => Some((25, 26, BinaryOperator::Percent)),
// Exponentiation (right-associative: left_bp > right_bp)
TokenKind::StarStar => Some((28, 27, BinaryOperator::StarStar)),
_ => None,
}
}
/// Whether a `{ … }` body opens with a directive prologue (ecma262
/// sec-directive-prologues-and-the-use-strict-directive). A function body does — a
/// `"use strict"` heading it turns the body strict — while a plain nested block does not,
/// so the same string statement there is an ordinary expression. The axis
/// `Parser::parse_block_body` is keyed on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum DirectivePrologue {
Present,
Absent,
}
impl<'a, 'arena> Parser<'a, 'arena> {
/// Parse an expression using Pratt parsing for operator precedence
///
/// This is the top-level entry point that handles ALL expression forms including
/// the comma operator (sequence expression). Use `parse_assignment_expression()`
/// for contexts where comma is a separator (function args, array elements, etc.)
pub(super) fn parse_expression(&mut self) -> Result<Expression<'arena>, Error> {
// The spine returns an arena ref; this owned form (shallow clone — children are
// refs) serves the callers that store the value: the by-value `export =` /
// `export default` fields, and the pattern path (`parse_expression_unbounded`),
// which converts it to a binding pattern.
Ok(self.parse_expression_bp(BP_COMMA)?.clone())
}
/// Parse an assignment expression (excludes comma operator)
///
/// Use this for contexts where comma is a separator rather than an operator:
/// - Function call arguments: `foo(a, b)` - commas separate args
/// - Array elements: `[a, b, c]` - commas separate elements
/// - Object property values: `{x: a, y: b}` - commas separate properties
/// - Variable initializers: `const x = expr` - comma would be ambiguous with declarators
///
/// To use the comma operator in these contexts, wrap in parens: `foo((a, b))`
///
/// This owned form (a shallow clone of the spine's arena node) serves the callers that
/// store the value by value — a computed member key, an enum member initializer; a
/// slot or list element that holds `&'arena Expression` (call arguments, array
/// elements, property values, initializers) takes `parse_assignment_expression_ref`.
pub(super) fn parse_assignment_expression(&mut self) -> Result<Expression<'arena>, Error> {
// Use BP_ASSIGNMENT to skip comma handling (which only triggers at BP_COMMA)
Ok(self.parse_expression_bp(BP_ASSIGNMENT)?.clone())
}
/// Parse a computed property/member name `[ AssignmentExpression ]`, assuming the
/// opening `[` has already been consumed and consuming the closing `]`.
///
/// A computed key is a single `AssignmentExpression` (ecma262 `ComputedPropertyName`
/// / `ClassElementName`), so a comma `SequenceExpression` (`[a, b]`, TS1171) and a
/// spread (`[...a]`) are grammar violations acorn rejects at parse — tsv rejects too
/// for drop-in parity. The comma falls out of `parse_assignment_expression` (which
/// stops before `,`, then `expect(']')` fails on it); the spread parses as a primary
/// expression tsv accepts in array/object/call positions, so it needs an explicit
/// guard. A member-access *subscript* (`obj[a, b]`) is a full `Expression` and uses
/// `parse_expression_ref` directly — not this helper.
pub(super) fn parse_computed_member_key(&mut self) -> Result<Expression<'arena>, Error> {
if matches!(self.current_kind(), TokenKind::DotDotDot) {
return Err(self.error_msg("A computed property name cannot be a spread element"));
}
let key = self.parse_assignment_expression()?;
self.expect(&TokenKind::BracketClose)?;
Ok(key)
}
/// `parse_expression`'s ref-returning sibling: hands back the spine's arena
/// ref directly, for consumers whose AST field is `&'arena Expression` —
/// skipping the owned boundary's shallow clone + re-alloc round trip.
pub(super) fn parse_expression_ref(&mut self) -> Result<&'arena Expression<'arena>, Error> {
self.parse_expression_bp(BP_COMMA)
}
/// `parse_assignment_expression`'s ref-returning sibling (see
/// `parse_expression_ref`).
pub(super) fn parse_assignment_expression_ref(
&mut self,
) -> Result<&'arena Expression<'arena>, Error> {
self.parse_expression_bp(BP_ASSIGNMENT)
}
/// Parse an expression without allowing `in` as a binary operator.
///
/// Used in for-loop headers to distinguish `for (x in y)` from expressions.
/// The `in` keyword is recognized as the for-in separator, not as a binary operator.
pub(super) fn parse_expression_no_in(&mut self) -> Result<Expression<'arena>, Error> {
self.with_no_in(Self::parse_expression)
}
/// Run `f` as a `[~In]` region — a for header's expression head or a
/// declaration's initializer there — restoring the prior state afterward.
///
/// Opening the region also pins `no_in_depth` to the CURRENT grouping
/// depth, which is the baseline the gate in `parse_expression_bp` measures
/// against. The depth a header starts at is not zero in general — the loop may
/// sit anywhere inside an enclosing expression's delimiters
/// (`fn(function () { for (k in o) {} })`, an object-literal method, an array
/// element, a template hole) — and only a grouping opened *inside* the header
/// restores `[+In]`. Setting `allow_in` alone, without the pin, leaves that
/// gate measuring against an outer region's baseline: inside any enclosing
/// delimiter the `in` then reads as the binary operator again.
pub(super) fn with_no_in<T>(
&mut self,
f: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
let saved_depth = std::mem::replace(&mut self.no_in_depth, self.grouping_depth);
let result = self.with_context_flag(
|p| &mut p.allow_in,
false,
|p| p.with_context_flag(|p| &mut p.in_for_header, true, f),
);
// Every delimiter the header opened is closed again by the time it ends, so
// the gate's `==` can never be reached from below. The `enter_grouping` /
// `exit_grouping` pairs are hand-balanced across several early returns, and
// an unbalanced one would not error here — it would silently re-read a later
// `in` as the binary operator. (Not asserted on the error path: those
// propagate straight out of the parse without unwinding the depth.)
debug_assert!(
result.is_err() || self.grouping_depth == self.no_in_depth,
"grouping delimiters must balance across a for-header init"
);
self.no_in_depth = saved_depth;
result
}
/// Run `f` with the `[In]` grammar parameter forced to `[+In]` (`allow_in =
/// true`), restoring the prior value afterward (even on error). Used at the
/// grammar productions that reset `[+In]` within a for-header init without
/// opening a delimiter — the ternary consequent and function/class bodies —
/// where a bare `in` is the binary operator, not the for-in separator (a
/// delimiter, a parameter list's included, restores it through `no_in_depth`).
/// A no-op outside a for-header init (where `allow_in` is already `true`); a
/// nested for-header re-disables it via [`Parser::with_no_in`]'s own
/// save/restore.
///
/// The `[In]` parameter ALONE — a body also lifts the conditional consequent's
/// return-type bar, and takes [`Parser::with_body_frame`] for both.
pub(super) fn with_allow_in<T>(
&mut self,
f: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
self.with_context_flag(|p| &mut p.allow_in, true, f)
}
/// Run `f` as a **body** — an arrow's block body, a function's params + body,
/// or a class body: `[+In]` ([`Parser::with_allow_in`]), a conditional
/// consequent's return-type bar lifted
/// ([`Parser::with_arrow_return_type_allowed`]), a top-level `as` read as the
/// assertion, and the open `<` region handed down to the body's statements
/// ([`Parser::with_lt_region_inherited`]), all restored afterward (even on error).
/// The first three share this boundary — a body is where tsc's
/// `allowReturnTypeInArrowFunction` goes back to `true` without a delimiter
/// opening, it is `[+In]` for the same reason, and a host's `as` separator
/// (`{#each xs as item}`) cannot sit inside one — so each of the three body sites
/// makes this one call rather than nesting all four combinators. A body also ends an
/// enclosing binding pattern's paren record ([`Parser::record_grouping_parens`]): no
/// paren inside one can wrap a target of the pattern around it.
///
/// The ternary consequent is the one `[+In]` production that instead BARS the
/// return type, so it takes `with_allow_in` and
/// [`Parser::with_arrow_return_type_barred`] directly: routing it through here
/// would lift the bar only to re-set it.
pub(super) fn with_body_frame<T>(
&mut self,
f: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
self.with_allow_in(|p| {
p.with_context_flag(
|p| &mut p.top_level_as_is_assertion,
true,
|p| {
p.with_context_flag(
|p| &mut p.record_grouping_parens,
false,
|p| p.with_arrow_return_type_allowed(|p| p.with_lt_region_inherited(f)),
)
},
)
})
}
/// Fold a trailing TypeScript `as` / `satisfies` type assertion at the current
/// token into `left`, returning `true` if one was consumed (the infix loop should
/// `continue`) or `false` if the current token isn't a type assertion to take here
/// (the loop should stop).
///
/// `as` / `satisfies` bind at the RELATIONAL tier (`BP_AS`), left-associative, with
/// a *type* (via `parse_type`) on the right — so `x === y as T` is `x === (y as T)`
/// while `a + b as T` stays `(a + b) as T`. Three conditions leave the keyword
/// unconsumed (each returns `false`) — ASI on a preceding line break, the Svelte
/// `#each` binding-separator gate, and relational precedence; see the guards.
///
/// `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)]
fn try_parse_type_assertion(
&mut self,
min_bp: u8,
expr_start: usize,
left: &mut &'arena Expression<'arena>,
) -> Result<bool, Error> {
let is_as = match self.current_kind() {
TokenKind::Keyword(KeywordKind::As) => true,
TokenKind::Keyword(KeywordKind::Satisfies) => false,
_ => return Ok(false),
};
// ASI: a preceding line terminator ends the expression, so the keyword starts a
// fresh statement (tsc's `parseBinaryExpressionRest` / acorn-typescript both
// break on `hasPrecedingLineBreak`). Unconditional — it holds inside grouping
// too (`(a⏎as B)` can't close), so it precedes the `#each` gate.
if self.had_line_terminator {
return Ok(false);
}
// `as` is the Svelte `#each … as pattern` binding separator when the host claims
// it and we're outside grouping — leave it for the `#each` parser. Inside
// grouping (`(x as T)`) it is always a type assertion.
//
// ⚠️ `is_as` is part of the gate, not decoration: the question is which keyword
// the HOST spells, and no host separator is spelled `satisfies`. Gating both
// together rejected `{#each xs satisfies T as item}` — valid, and accepted by
// canonical Svelte — for a collision that only `as` can have.
//
// The literal `0` here is the baseline, and it differs from the `in` gate's
// (`no_in_depth`) on purpose: this region opens at the PARSE ROOT — a partial
// parse builds a fresh `Parser`, so `grouping_depth` starts at 0 and every
// delimiter counted is one the `#each` expression itself opened. The `[~In]`
// region opens MID-parse instead, at whatever depth the enclosing expression
// had reached, so it must carry its own baseline. Same field, two questions.
if is_as && !self.top_level_as_is_assertion && self.grouping_depth == 0 {
return Ok(false);
}
// Relational binding power: looser than the caller's minimum (e.g. as the right
// operand of a same-tier relational operator — `a < b as T` is `(a < b) as T`).
if BP_AS < min_bp {
return Ok(false);
}
let arena = self.arena;
// one link of the operator chain: an assertion nests its operand to the left
self.spine_link(LINK_ASSERTION)?;
// and the pair the printer adds around a bare operand that binds looser
// (`(a + b) as T`), a level of the output's nesting
if expr_start == left.span().start as usize {
self.count_operand_pairs(Some((left, ParenContext::TypeAssertion)), None)?;
// a bare `async` keeps a pair at every position (`(async) as T`), which acorn
// would read as an async arrow head
if matches!(left.kind, ExpressionKind::Identifier(_))
&& self.source_slice(left.span()) == "async"
{
self.printer_pair()?;
}
}
self.advance()?; // consume `as` / `satisfies`
let type_annotation = self.parse_type()?;
let span = Span::new(expr_start as u32, type_annotation.span().end);
let expr = if is_as {
Expression {
span,
kind: ExpressionKind::TSAsExpression(TSAsExpression {
expression: left,
type_annotation,
}),
}
} else {
Expression {
span,
kind: ExpressionKind::TSSatisfiesExpression(TSSatisfiesExpression {
expression: left,
type_annotation,
}),
}
};
*left = arena.alloc(expr);
Ok(true)
}
/// Pratt parser: parse expression with minimum binding power
///
/// The result's paren-inclusive extent is `expr_start` to the `prev_token_end` at
/// return — see §The expression ladder's return currency.
///
/// It counts no depth of its own: an expression's nesting is counted where its grammar
/// recurses — a grouping delimiter ([`Parser::enter_grouping`]), an operator's
/// operand, an arrow's body — so a plain operand pays nothing.
fn parse_expression_bp(&mut self, min_bp: u8) -> Result<&'arena Expression<'arena>, Error> {
// Track the true start position (before any parentheses)
// This is needed because grouped expressions like (a && b) should have their
// containing binary expression span include the opening paren
let expr_start = self.current_pos().0;
// Parse prefix expression (primary or unary)
let left = self.parse_prefix_expression()?;
self.parse_expression_operators(min_bp, expr_start, left)
}
/// The operator half of [`Parser::parse_expression_bp`]: everything that extends an
/// already-parsed `left` operand whose parse began at `expr_start` — binary operators
/// and `as` / `satisfies`, then an assignment, a conditional and a sequence, as
/// `min_bp` admits them.
///
/// Its own function for the one other caller,
/// [`Parser::type_arguments_follower_settled`], which asks whether a `<` the
/// subscript loop has just read a type-argument list from reads as the comparison
/// operator instead — exactly as this loop would read it from that `left`.
/// `inline(always)` keeps [`Parser::parse_expression_bp`], the expression ladder's
/// hot path, one frame as it was before the split.
#[expect(clippy::inline_always)]
#[inline(always)]
fn parse_expression_operators(
&mut self,
min_bp: u8,
expr_start: usize,
mut left: &'arena Expression<'arena>,
) -> Result<&'arena Expression<'arena>, Error> {
let arena = self.arena;
// A leading *unparenthesized* arrow function — or a bare `yield` inside a
// generator — is a complete `AssignmentExpression` (see
// `is_bare_assignment_head`), so no operator may extend it: a trailing
// binary/logical operator, `as` / `satisfies` assertion, assignment target,
// or ternary `?` is a syntax error (tsc TS1005 / prettier reject; acorn's
// `parseExprOps` and `parseMaybeAssign`-above-`parseMaybeConditional`
// enforce the same). Only a sequence `,` or a statement terminator may
// follow. An operator that can *start* an expression is absorbed first — a
// concise arrow body (`() => x || a`) or the yield argument
// (`yield a || b`, `yield +c`) — so this fires only for a truly complete
// head with no argument/body to absorb it.
let leading_bare_head = is_bare_assignment_head(left, expr_start, self.in_yield);
// The same head is no OPERAND either. Above the assignment tier this parse is a
// unary operator's argument or a binary operator's right side — a
// `UnaryExpression` at the loosest — and `ArrowFunction` / `YieldExpression` are
// alternatives of `AssignmentExpression` alone (ecma262 §13.15), so `x + a => b`,
// `!a => b` and `x < async (a) => b` are syntax errors; parenthesized, the same
// head is a primary any operator takes.
if leading_bare_head && min_bp > BP_ASSIGNMENT {
return Err(Error::invalid_syntax(
"An arrow function or `yield` expression cannot be an operand without parentheses"
.to_string(),
left.span().start as usize,
));
}
// Parse infix binary operators and TypeScript `as` / `satisfies` type
// assertions in one precedence-climbing loop. `as` / `satisfies` bind at
// the RELATIONAL tier (`BP_AS`), left-associative, consuming a *type* on the
// right — so `x === y as T` is `x === (y as T)` while `a + b as T` stays
// `(a + b) as T`. (A second phase below every binary operator would
// mis-group it as `(x === y) as T`.)
loop {
// A leading bare arrow / bare yield takes no infix operator or `as` /
// `satisfies` assertion — it is already a complete assignment expression.
if leading_bare_head {
break;
}
let kind = self.current_kind();
let Some((left_bp, right_bp, operator)) = infix_operator_info(kind) else {
// Not a binary operator — the only remaining infix forms are the
// TypeScript `as` / `satisfies` type assertions.
if self.try_parse_type_assertion(min_bp, expr_start, &mut left)? {
continue;
}
break;
};
// Skip `in` operator when allow_in is false (parsing for-loop headers),
// unless a grouping delimiter opened SINCE the header began — inside one
// `in` is always a binary operator. The baseline is `no_in_depth`, not 0:
// the header itself may be nested in an outer expression's delimiters,
// whose depth says nothing about this header.
if matches!(operator, BinaryOperator::In)
&& !self.allow_in
&& self.grouping_depth == self.no_in_depth
{
break;
}
// Check if operator binds tighter than minimum
if left_bp < min_bp {
break;
}
// ES2016+: Unary expression as left operand of ** without parens is a syntax error
// `-2 ** 3` is ambiguous - must be `(-2) ** 3` or `-(2 ** 3)`. An `await`
// operand is a UnaryExpression per the grammar (`await UnaryExpression`), so
// `await b ** 2` is the same error — must be `(await b) ** 2` or `await (b ** 2)`.
// Detect unparenthesized unary: the operand's parse began at its own span start
if operator == BinaryOperator::StarStar
&& matches!(
left.kind,
ExpressionKind::UnaryExpression(_) | ExpressionKind::AwaitExpression(_)
)
&& expr_start == left.span().start as usize
{
return Err(Error::invalid_syntax(
"Unary expression cannot be the left operand of ** without parentheses. Use (-x) ** y or -(x ** y).".to_string(),
left.span().start as usize,
));
}
// An angle-bracket assertion is the same error in tsc (`A type assertion
// expression is not allowed in the left-hand side of an exponentiation
// expression`), and prettier, a tsc front end, throws on it. acorn-typescript
// reads `<T>x ** y` as `<T>(x ** y)` instead — its assertion operand is a
// `parseMaybeUnary`, which consumes the `**` — so tsv rejects rather than build
// tsc's `(<T>x) ** y` beside a wire that says otherwise.
if operator == BinaryOperator::StarStar
&& matches!(left.kind, ExpressionKind::TSTypeAssertion(_))
&& expr_start == left.span().start as usize
{
return Err(Error::invalid_syntax(
"Type assertion cannot be the left operand of ** without parentheses. Use (<T>x) ** y or <T>(x ** y).".to_string(),
left.span().start as usize,
));
}
// Ask the RELAXED reading of the same type-argument lookahead that declined
// the `<` below — the one component that has already read these bytes, and the
// last moment they are still in reach (the printer holds a tree). It answers
// whether this chain's PRINTED form re-lexes as a type-argument list, which is
// what decides a paren pair at the enclosing `>`
// (`Printer::needs_parens_binary_operand`).
//
// Asked HERE, at the `>` that would close the region, rather than at the `<`
// that opens it: the verdict is a fact about the JOIN of the two tokens, and
// this is the first point both exist. A `<` with no `>` over it — `check(a < b)`
// and every other ordinary comparison — then pays nothing, where a question asked
// at the `<` would walk each one to the statement's end looking for a close that
// is not there. The bit rides the `<` node, already in the arena, so setting it
// re-allocates that one node; only a chain that takes the pair pays for it.
if operator == BinaryOperator::GreaterThan
&& let ExpressionKind::BinaryExpression(child) = &left.kind
&& child.operator == BinaryOperator::LessThan
&& let Some(lt) = infix_operator_offset(
self.source.as_bytes(),
self.local_pos(child.left.span().end),
b'<',
)
&& self.chain_owes_type_argument_pair(lt, expr_start != left.span().start as usize)
{
left = arena.alloc(Expression {
span: left.span,
kind: ExpressionKind::BinaryExpression(BinaryExpression {
relexes_as_type_arguments: true,
..child.clone()
}),
});
}
left = self.parse_binary_step(left, expr_start, operator, right_bp)?;
}
// Handle assignment operator (after binary ops, before ternary)
// Assignment is right-associative and has low precedence
// Check for simple `=` and compound assignment operators (+=, -=, etc.)
// A leading bare arrow / bare yield is not a `LeftHandSideExpression`, so it
// cannot be an assignment target (`() => {} = a` / `yield = a` are syntax
// errors).
if !leading_bare_head
&& min_bp <= BP_ASSIGNMENT
&& let Some(operator) = self.try_assignment_operator()
{
left = self.parse_assignment_step(left, expr_start, operator)?;
}
// Handle ternary operator (lowest precedence among binary-like ops, above comma)
// Handle at BP_ASSIGNMENT to include in assignment expressions but not in binary ops
// A leading bare arrow / bare yield cannot be a `ConditionalExpression`
// test — the ternary's test is a `ShortCircuitExpression`, which never
// derives `ArrowFunction` / `YieldExpression`, so `() => {} ? b : c` and
// `yield ? b : c` are syntax errors. (Both parsers reject the yield form;
// for the arrow form acorn over-leniently accepts it — a cataloged
// `tsv_rejects` divergence, see conformance_svelte.md.)
if !leading_bare_head && min_bp <= BP_ASSIGNMENT && self.eat(TokenKind::Question)? {
left = self.parse_conditional_step(left, expr_start)?;
}
// Handle comma operator (lowest precedence, after ternary)
// Only handle at top level (BP_COMMA) to avoid conflicts with comma in
// function calls, array literals, and object literals
if min_bp == BP_COMMA && self.check(&TokenKind::Comma) {
left = self.parse_sequence_step(left, expr_start)?;
}
Ok(left)
}
/// Parse a prefix expression (a primary or unary head plus its subscript chain)
fn parse_prefix_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
// The head token — the leftmost token of the expression being parsed, and the
// only one a leading comment can be glued to. Taken before the match, which
// produces exactly the node that token begins (postfix subscripts wrap it after).
let (head_start, _) = self.current_pos();
// Whether the head is a prefix operator — a unary operator, a prefix update,
// `await`, or an angle-bracket type assertion (a generic arrow, the `<` arm's
// other reading, is a bare head that returns below either way). What it builds is
// a `UnaryExpression` in ecma262's grammar, never a `LeftHandSideExpression`, and
// a call, member access, tagged template or type argument list continues only a
// `LeftHandSideExpression`. Its operand has already taken every subscript it can,
// so a subscript token still standing behind one is one the operand refused: the
// one its postfix `++` / `--` ends on (`!b++` before `(z)`, `[0]`, `` `t` `` or
// `.c`), which the operator does not take either.
let prefix_operator_head = match self.current_kind() {
TokenKind::Minus
| TokenKind::Plus
| TokenKind::Bang
| TokenKind::Tilde
| TokenKind::PlusPlus
| TokenKind::MinusMinus
| TokenKind::LessThan
| TokenKind::LeftShift
| TokenKind::Keyword(KeywordKind::Typeof | KeywordKind::Void | KeywordKind::Delete) => {
true
}
TokenKind::Keyword(KeywordKind::Await) => self.in_await,
_ => false,
};
let parsed = match self.current_kind() {
TokenKind::Minus | TokenKind::Plus | TokenKind::Bang | TokenKind::Tilde => {
self.parse_unary_expression()?
}
TokenKind::PlusPlus | TokenKind::MinusMinus => self.parse_prefix_update_expression()?,
TokenKind::Keyword(KeywordKind::New) => self.parse_new_expression()?,
TokenKind::Keyword(KeywordKind::Import) => {
// Could be: import('module') or import.meta
self.parse_import_or_meta_property()?
}
TokenKind::Keyword(KeywordKind::Typeof | KeywordKind::Void | KeywordKind::Delete) => {
self.parse_unary_keyword_expression()?
}
// A single unparenthesized arrow parameter may be a contextual keyword
// that is a valid `BindingIdentifier` (`any => x`, `async => x`,
// `from => x`, `let => x`). The byte scan requires `=>` *immediately*
// after the word, so `async x => …` / `async () => …` (a real async arrow)
// fall through to the `async` arm, and a reserved word (`void =>`) is
// excluded by `can_be_binding_name` and rejects downstream. This mirrors
// the plain-`Identifier` arrow check below; `await` at Script `[~Await]`
// keeps its dedicated handling in the `Await` arm, and `yield =>` is an
// arrow only outside a generator — inside one `yield` is the operator,
// which is what `keyword_is_expression_identifier` subtracts.
TokenKind::Keyword(kw)
if self.keyword_is_expression_identifier(*kw)
&& self.is_single_param_arrow_start() =>
{
self.parse_single_param_arrow_function()?
}
TokenKind::Keyword(KeywordKind::Await) => {
if self.in_await {
// `[+Await]` context: a real await expression.
self.parse_await_expression()?
} else if self.await_is_identifier() {
if self.is_single_param_arrow_start() {
// Script `[~Await]`: `await => …` is an arrow whose single
// `BindingIdentifier` parameter is `await`.
self.parse_single_param_arrow_function()?
} else {
// Script `[~Await]`: `await` is an ordinary `IdentifierReference`.
self.parse_await_name_reference()?
}
} else {
// Module `[~Await]`: `await` is reserved and there is no
// `[+Await]` to make it an await expression.
return Err(self.error_msg(
"'await' is only allowed inside an async function or at the top level of a module",
));
}
}
// `let` is not a `ReservedWord`, so it is an ordinary
// `IdentifierReference` wherever an expression is expected — the
// statement dispatcher has already decided this is not a declaration
// (`Parser::at_let_declaration`). Unlike `yield`/`await` it has no
// operator reading to lose, so the arm is unconditional.
TokenKind::Keyword(KeywordKind::Let) => self.parse_keyword_identifier_reference()?,
TokenKind::Keyword(KeywordKind::Yield) => {
if self.yield_is_identifier() {
// `[~Yield]`: `yield` is an ordinary `IdentifierReference`, exactly
// like `await` at Script goal above — `IdentifierReference[Yield] :
// [~Yield] yield`. Its remaining bar is the strict-mode early error
// tsv defers, so `yield()`, `yield++`, `yield.foo` and `x = yield`
// are all plain identifier expressions, as tsc and prettier parse
// them. Building a `YieldExpression` here instead was a wrong wire
// SHAPE, not just leniency: `yield.foo` came out as a
// `MemberExpression` over a `YieldExpression`, a node the enclosing
// function could not legally contain.
self.parse_keyword_identifier_reference()?
} else {
// `[+Yield]`: the operator.
self.parse_yield_expression()?
}
}
TokenKind::Keyword(KeywordKind::Async) => {
// Could be async arrow function, async function expression, or just identifier
// Look ahead to determine what follows 'async'
let peek = self.peek_kind();
// Every `async`-headed refinement is a `[no LineTerminator here]` production:
// `async [no LT] function` and `AsyncArrowFunction : async [no LT]
// ArrowFormalParameters` (ecma262). So the break is ONE gate rather than a
// condition repeated per shape — it rules out every refinement at once, and
// each arm below is then left reading as its own grammar question.
//
// A line break demotes `async` to an ordinary identifier expression, and
// what that leaves is a syntax error in every shape but one —
// `const x = async⏎function () {}` is a bodiless function declaration,
// `const f = async⏎() => {}` a call to `async` with a stray `=>`,
// `const f = async⏎<T>(a: T) => a` a comparison chain — matching
// acorn/tsc/prettier, never a silently-accepted async function or arrow. The
// exception is a SINGLE parameter (`const f = async⏎a => a`), where ASI
// splits the statement and both halves are valid; declining the refinement
// is what produces that reading too.
if self.peek_preceded_by_line_terminator() {
// `async` used as an identifier reference, demoted by the line break.
self.parse_primary_expression()?
} else if peek == TokenKind::Keyword(KeywordKind::Function) {
// Async function expression: `async function() {}`.
let (start, _) = self.current_pos();
self.advance()?; // consume 'async'
self.parse_async_function_expression(start)?
} else if peek == TokenKind::ParenOpen {
// `async(...)` — could be async arrow or call to function named `async`
// Scan ahead: if `(...)` is followed by `=>`, it's an async arrow function
let paren_start = self.peek_start();
if let Some(head) = ArrowHead::at_paren(self.source.as_bytes(), paren_start)
&& let Some(arrow) = self.parse_arrow_or_rewind(head, |p| {
let (start, _) = p.current_pos();
p.advance()?; // consume 'async'
p.parse_async_arrow_function_after_async(start)
})?
{
arrow
} else {
// `async(2)` — call to function named `async`; also the
// reading an async arrow handed back in a conditional's
// consequent takes (`a ? async (b): c => d` calls `async`)
self.parse_primary_expression()?
}
} else if matches!(peek, TokenKind::Identifier | TokenKind::LessThan) {
// Async arrow function: `async x => ...` or `async <T>() => ...`
let (start, _) = self.current_pos();
self.advance()?; // consume 'async'
self.parse_async_arrow_function_after_async(start)?
} else {
// `async` used as identifier (e.g., `[async]`, `async = 1`)
self.parse_primary_expression()?
}
}
TokenKind::At => {
// Decorated class expression: `@dec class {}`. Decorators are
// otherwise statement-only; in expression position the only thing
// that may follow a decorator list is a class expression.
self.parse_decorated_class_expression()?
}
TokenKind::Keyword(KeywordKind::Class) => {
// Class expression: `class { }` or `class Foo<T> { }`
self.parse_class_expression()?
}
TokenKind::Keyword(KeywordKind::Function) => {
// Function expression: `function() {}` or `function name() {}`
self.parse_function_expression()?
}
TokenKind::LessThan | TokenKind::LeftShift => {
// Generic arrow function: `<T>() => ...` — never begins with a
// `<<` shift token (its type-parameter list opens with a single
// `<`), so a shift here can only open a type assertion whose
// type is a generic function type: `<<T>() => R>x`.
if self.current.kind == TokenKind::LessThan
&& let Some(head) = self.generic_arrow_function_start()
&& let Some(arrow) =
self.parse_arrow_or_rewind(head, Self::parse_generic_arrow_function)?
{
arrow
} else {
// TypeScript type assertion: `<T>expr` — the reading a generic
// arrow handed back in a conditional's consequent takes too
// (`a ? <T>(b): c => d` asserts `<T>` on the consequent `(b)`)
self.parse_type_assertion()?
}
}
TokenKind::Identifier => {
// Check for single-param arrow function: `x => expr`
if self.is_single_param_arrow_start() {
self.parse_single_param_arrow_function()?
} else {
// Regular identifier
self.parse_primary_expression()?
}
}
_ => self.parse_primary_expression()?,
};
self.bind_leading_comment(head_start, parsed);
// An unparenthesized arrow function — or a bare `yield` inside a generator
// — is a complete AssignmentExpression, so no `.`-member subscript can
// follow (`() => {}()` is invalid JS; `yield.a` is too — the `.` doesn't
// extend the head). A parenthesized head (`(() => {})()` / `(yield).a`,
// detected by the span gap) is a callable primary. A subscript token that
// *starts* an expression is instead absorbed earlier as the yield argument
// (`yield [x]` is `yield` of an array; `yield (e)` its parenthesized arg),
// so only the no-argument bare head reaches here.
if is_bare_assignment_head(parsed, head_start, self.in_yield) {
return Ok(parsed);
}
// A prefix operator's expression takes no subscript (see `prefix_operator_head`):
// past a line break the statement ends before one (`a = !b++⏎(z) => z` is two
// statements), and on the same line, or where no statement can end, the token is
// a syntax error (`!b++(z)`, `g(!b++⏎(z))`).
if prefix_operator_head {
return Ok(parsed);
}
// Parse any postfix operations (member access, call expressions)
self.parse_postfix_expression(parsed, head_start as u32, SubscriptMode::Normal)
}
/// Parse call arguments: `(arg1, arg2, ...)`
///
/// Assumes the opening `(` has already been consumed.
/// Returns the arguments and the end position of the closing `)`.
pub(super) fn parse_call_arguments(
&mut self,
) -> Result<
(
bumpalo::collections::Vec<'arena, &'arena Expression<'arena>>,
usize,
),
Error,
> {
self.enter_grouping()?;
let mut arguments = self.bvec();
if !self.check(&TokenKind::ParenClose) {
// the arguments are siblings (`ListFrame`)
let mut frame = self.list_frame();
loop {
frame.element(self, arguments.len());
// A leading `...` is a SpreadElement (ecma262 ArgumentList); everywhere
// else falls through to a plain AssignmentExpression.
let arg = self.parse_spread_or_assignment_element()?;
arguments.push(arg);
if !self.expect_list_separator(&TokenKind::Comma, &TokenKind::ParenClose)? {
break;
}
}
frame.close(self);
}
let (_, paren_end) = self.current_pos();
self.expect(&TokenKind::ParenClose)?;
self.exit_grouping();
Ok((arguments, paren_end))
}
/// Parse the expression part of a decorator (the `expr` in `@expr`), per the
/// TC39 decorators grammar (a proposal, not yet standard, which `tsv` supports):
///
/// - `@(Expression)` — a parenthesized **full** expression, or
/// - `@Ident(.Ident | .#private)*` — a `DecoratorMemberExpression`: an
/// identifier reference followed by a `.`-member chain whose properties
/// are identifier names or private names (`DecoratorMemberExpression .
/// PrivateIdentifier` in the TC39 grammar),
///
/// each optionally followed by a **single** trailing call `(...)`, which may carry
/// explicit type arguments (`@g<number>()`), and with a postfix `!` permitted
/// anywhere in the chain (`@x!`, `@x.y!`, `@x!.y`).
///
/// Deliberately narrower than a full `AssignmentExpression`: binary
/// operators, computed/optional member access (`[…]`, `?.`), tagged
/// templates, and `++`/`--` are not part of the grammar. Leaving them
/// unconsumed is what lets the construct *after* the decorator parse — e.g.
/// the `*` of a decorated generator method (`@fn *a() {}`), which a
/// full-expression parse would otherwise swallow as multiplication. A full
/// expression must be parenthesized (`@(a + b)`).
///
/// Mirrors `@sveltejs/acorn-typescript`'s `parseDecorator`, except the
/// `.#private` chain step, which acorn-typescript rejects (a lag behind the
/// TC39 grammar).
///
/// **The postfix `!` is accepted where acorn rejects it, and type arguments are
/// accepted with or without a trailing call**, because that narrowing argument does
/// not reach either: a decorator is followed by `class`, a class member, or a
/// parameter, so neither a `!` nor a `<` opening a type-argument list can be the
/// *next construct's* token. tsc accepts all of it with no diagnostic — TypeScript's
/// grammar admits it — and prettier formats all of it, printing `@(x!)` and a bare
/// `@g<number>()`, which the printer already reproduces for free. With no call the
/// expression is a `TSInstantiationExpression` (acorn's
/// `parseMaybeDecoratorArguments`), which prettier parenthesizes like the `!` — it
/// is no decorator member expression.
/// See `docs/conformance_svelte.md` §TypeScript Corrections. A member's own
/// definite-assignment `!` is unaffected (`@dec x!: number` binds the `!` to `x`,
/// since the decorator expression ends at `dec`).
pub(in crate::parser) fn parse_decorator_expression(
&mut self,
) -> Result<Expression<'arena>, Error> {
// a decorator's member chain is a chain of its own (`Parser::chain`)
self.chain(Self::parse_decorator_expression_chain)
}
/// [`Parser::parse_decorator_expression`] inside its chain frame.
fn parse_decorator_expression_chain(&mut self) -> Result<Expression<'arena>, Error> {
let head_start = self.current_pos().0;
let is_parenthesized = *self.current_kind() == TokenKind::ParenOpen;
// `@(Expression)` rides the full expression grammar inside the parens:
// `parse_primary_expression` handles the `(` via `parse_paren_expression`
// (sequence, arrow, paren-stripping) exactly as a standalone `(expr)`.
// Otherwise the head must be an identifier reference — the same set
// `parse_primary_expression` already accepts as an `Identifier` (plain
// names plus value-position contextual keywords like `async`/`as`, and
// `await` at `Script` goal), never `this`/`super`/a literal/`new`.
let mut expr = self.parse_primary_expression()?;
if !is_parenthesized {
if !matches!(expr.kind, ExpressionKind::Identifier(_)) {
// `parse_primary_expression` has already consumed the head, so
// anchor the error at its start, not the now-current token.
return Err(Error::invalid_syntax(
"Expected an identifier or '(' as the decorator expression".to_string(),
head_start,
));
}
// `DecoratorMemberExpression`: a `.`-member chain. Property names are
// liberal (keywords allowed: `@a.class`) and private names are part
// of the grammar (`@C.#p`); computed `[…]` and optional `?.` access
// are not.
//
// A postfix `!` INTERLEAVES with the chain rather than only closing it,
// which is why it shares this loop: `@x!`, `@x.y!` and `@x!.y` are all
// tsc shapes. (Why it is accepted at all: see the fn doc.)
loop {
match self.current_kind() {
TokenKind::Dot => {
self.spine_link(LINK_SUBSCRIPT)?;
self.advance()?; // consume '.'
let (property, prop_end) = self.parse_dot_property()?;
let span = Span::new(head_start as u32, prop_end as u32);
expr = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: expr,
property: self.arena.alloc(property),
computed: false,
optional: false,
}),
},
);
}
// same ASI gate as every other `wrap_non_null_assertion` caller:
// a line terminator before `!` makes it a prefix `!`, not ours
TokenKind::Bang if !self.had_line_terminator => {
self.spine_link(LINK_NON_NULL)?;
expr = self.wrap_non_null_assertion(expr, head_start as u32)?;
}
_ => break,
}
}
}
// Explicit type arguments, on the trailing call (`@g<number>()`, `@a.b<T>()`) or
// standing alone (`@a.b<number>` with no call, which becomes a
// `TSInstantiationExpression` below). `LeftShift` is matched for the
// nested-generic spelling (`@g<<T>() => U>()`), whose leading `<<` the lexer
// emits as one token. (Why any of it is accepted: see the fn doc.)
let type_arguments = if matches!(
self.current_kind(),
TokenKind::LessThan | TokenKind::LeftShift
) && self.is_type_arguments_start(TypeArgScan::Parse)
{
Some(self.parse_type_parameter_instantiation()?)
} else {
None
};
// A single optional trailing call (`@foo()`, `@a.b.c()`, `@(expr)()`).
// Only one: `parseMaybeDecoratorArguments` runs once, so `@foo()()` and
// `@foo().bar` are not decorators — a parenthesized form covers them.
if *self.current_kind() == TokenKind::ParenOpen {
self.advance()?; // consume '('
let (arguments, paren_end) = self.parse_call_arguments()?;
let arguments = arguments.into_bump_slice();
// The call node starts at the callee's own start (acorn's
// `startNodeAtNode(expr)`), not at any stripped wrapping paren.
let start = expr.span().start;
let span = Span::new(start, paren_end as u32);
expr = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::CallExpression(CallExpression {
callee: expr,
type_arguments,
arguments,
optional: false,
}),
},
);
} else if let Some(type_arguments) = type_arguments {
// Type arguments with no call — `@a.b<number>` ahead of the class. The
// decorator expression is a `TSInstantiationExpression`, anchored at the
// callee's own start like the call form above.
let start = expr.span().start;
let end = type_arguments.span.end;
expr = alloc_expr(
self.arena,
Expression {
span: Span::new(start, end),
kind: ExpressionKind::TSInstantiationExpression(TSInstantiationExpression {
expression: expr,
type_arguments,
}),
},
);
}
// Hand back an owned `Expression` (shallow clone — children are arena
// refs), matching `parse_assignment_expression`'s by-value boundary.
Ok(expr.clone())
}
/// Parse an optional call's type-argument list, which a call **must** follow, and
/// leave the `(` unconsumed for the caller.
///
/// `a?.<T>` alone is a syntax error: the `?.` commits to a member or call, and the
/// `<` would otherwise read as a relational operator against whatever comes next.
/// The optional call is the only position that takes type arguments this way. A
/// decorator's look identical (`@g<T>()`) but DO stand alone — `@a.b<T>` is a
/// `TSInstantiationExpression` — so the decorator reads them through
/// `parse_type_parameter_instantiation` directly. Both read the list committed: a
/// `<` behind `?.` or a decorator has no operator reading to fall back to, which
/// the other standalone positions have (`parse_instantiation_expression`, the
/// `new` callee arm — [`Parser::parse_type_arguments_or_rewind`]).
fn parse_type_arguments_before_call(
&mut self,
) -> Result<TSTypeParameterInstantiation<'arena>, Error> {
let type_args = self.parse_type_parameter_instantiation()?;
if *self.current_kind() != TokenKind::ParenOpen {
return Err(self.error_expected_after("'('", "type arguments in optional call"));
}
Ok(type_args)
}
/// Wrap `expr` in a `TSNonNullExpression`, consuming the current `!` token. The
/// span starts at `start`, where `expr`'s parse began, so it covers any grouping
/// parens (`(a?.b)!`), which `TSNonNullExpression::seals_optional_chain` relies
/// on. Callers gate on
/// `Bang` + `!had_line_terminator` (ASI: a line terminator before `!` makes it a
/// prefix `!` on the next statement instead).
fn wrap_non_null_assertion(
&mut self,
expr: &'arena Expression<'arena>,
start: u32,
) -> Result<&'arena Expression<'arena>, Error> {
let (_, op_end) = self.current_pos();
self.advance()?; // consume '!'
let span = Span::new(start, op_end as u32);
Ok(alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::TSNonNullExpression(TSNonNullExpression { expression: expr }),
},
))
}
/// Parse the property after a consumed `.` or `?.`: a private name
/// (`obj.#p`) or an identifier/keyword name — keywords are valid property
/// names (`obj.class`, `obj.if`, `obj.default()`). Returns the property
/// expression and its end position; errors when neither follows.
fn parse_dot_property(&mut self) -> Result<(Expression<'arena>, usize), Error> {
if *self.current_kind() == TokenKind::Hash {
let (private_id, span) = self.parse_private_identifier()?;
Ok((
Expression {
span,
kind: ExpressionKind::PrivateIdentifier(private_id),
},
span.end_usize(),
))
} else if self.current_is_identifier_or_keyword() {
let property = self.parse_identifier_name_node()?;
let prop_end = property.span.end_usize();
Ok((Expression::from_identifier(property), prop_end))
} else {
Err(self.error_expected_after("property name", "."))
}
}
/// The assignment step of [`Parser::parse_expression_bp`]: `operator`, the current
/// token, over the target `left` (starting at `expr_start`), and its right side. Out of
/// line, off the expression ladder's common path.
#[inline(never)]
fn parse_assignment_step(
&mut self,
left: &'arena Expression<'arena>,
expr_start: usize,
operator: AssignmentOperator,
) -> Result<&'arena Expression<'arena>, Error> {
// A bare operator expression is no `LeftHandSideExpression` — a grammar
// error, read before the operator is consumed while `prev_token_end` still
// closes the left side.
self.check_bare_assignment_left(left, expr_start)?;
// the deepest nesting the frame has reached by the end of the target, the target's
// own among it, which the assignment's level sits above
let target_peak = self.depth.peak();
self.advance()?; // consume assignment operator
// Parse right-hand side (assignment is right-associative, so same precedence):
// one wire level (the depth limit's count)
// a bare assignment on the right of another prints bare (`a = b = c`)
let right = self.nested(1, |p| {
p.pair_free_root(RootEnd::Anywhere, |p| p.parse_expression_bp(BP_ASSIGNMENT))
})?;
let end = self.prev_token_end() as u32;
// Convert left side to pattern if needed (cover grammar). Assignment is the
// one context that accepts a type-assertion target (`(x as T) = …`); as the
// WHOLE target it may not be an `AssignmentPattern` (`(a = b) = 1`).
// `refine_assignable` consumes by value; clone the arena ref (shallow — children
// are refs) on this cold assignment-target path.
//
// Only `=` reparses an object or array literal as a destructuring pattern
// (ecma262 §13.15.1): a compound operator's literal left (`({ a } += x)`)
// stays the literal, as acorn keeps it — an invalid target, the deferred
// early error. Every other compound left converts as an `=` left does, so a
// parenthesized assignment there (`(a = b) += 1`) still has no wire shape.
let left_pattern = if operator != AssignmentOperator::Assign
&& matches!(
left.kind,
ExpressionKind::ObjectExpression(_) | ExpressionKind::ArrayExpression(_)
) {
left.clone()
} else {
self.refine_whole_assignable(left.clone(), AssignableContext::Assignment)?
};
// one wire level: the assignment over its target, read before the operator said it
// was one (the depth limit's count), raising the deepest nesting to the frame's at the
// end of the target, plus one — none over a bare name, which nests nothing, the
// wire-only tree's grouping pairs looked through so it counts no more than the
// paren-free parse
let mut target = &left_pattern;
while let ExpressionKind::ParenthesizedExpression(paren) = &target.kind {
target = paren.expression;
}
if !matches!(target.kind, ExpressionKind::Identifier(_)) {
self.level_above_operand(target_peak)?;
}
let span = Span::new(expr_start as u32, end);
debug_assert_encloses(span.start, span.end, left, right);
let assignment = self.arena.alloc(Expression {
span,
kind: ExpressionKind::AssignmentExpression(AssignmentExpression {
left: self.arena.alloc(left_pattern),
operator,
right,
}),
});
// the pair the printer adds around an assignment as a value ([`Parser::self_pair`])
self.self_pair(expr_start)?;
Ok(assignment)
}
/// The conditional step of [`Parser::parse_expression_bp`], the `?` consumed: the
/// branches over the test `left` (starting at `expr_start`). Out of line, off the
/// expression ladder's common path.
#[inline(never)]
fn parse_conditional_step(
&mut self,
left: &'arena Expression<'arena>,
expr_start: usize,
) -> Result<&'arena Expression<'arena>, Error> {
// the test, parsed before the `?` said it was one, is the conditional's left
// operand: a spine link, which every walk takes by re-entering its printer
// (`((a ? b : c) ? d : e)` nests a conditional per grouping paren)
self.spine_link(LINK_REENTRY)?;
// Parse consequent (then branch) - use BP_ASSIGNMENT to exclude comma operator
// This ensures (a ? b : c, d) parses as ((a ? b : c), d) not (a ? b : (c, d))
// The consequent is `AssignmentExpression[+In]` — `in` is always the
// binary operator here, even inside a for-header init. The alternate
// is `[?In]` and inherits the outer context (so `for (a ? b : x in y;;)`
// still rejects).
//
// It is also where a parenthesized arrow's return type is BARRED: the
// `:` that would open one may be this conditional's own, so
// `parse_arrow_or_rewind` keeps such an annotation only when a second
// `:` follows the arrow (tsc's `allowReturnTypeInArrowFunction`). The
// alternate inherits the enclosing rule, as it does in tsc.
// each branch one wire level (the depth limit's count)
let consequent_start = self.current_pos().0;
let consequent = self.nested(1, |p| {
p.with_allow_in(|p| {
p.with_arrow_return_type_barred(|p| p.parse_expression_bp(BP_ASSIGNMENT))
})
})?;
self.conditional_head_pairs(left, expr_start, consequent, consequent_start)?;
// Expect ':'
self.expect(&TokenKind::Colon)?;
// Parse alternate (else branch) - use BP_ASSIGNMENT to exclude comma operator
let alternate_start = self.current_pos().0;
let alternate = self.nested(1, |p| p.parse_expression_bp(BP_ASSIGNMENT))?;
self.ternary_branch_pair(alternate, alternate_start)?;
let span = Span::new(expr_start as u32, self.prev_token_end() as u32);
debug_assert_encloses(span.start, span.end, left, alternate);
Ok(self.arena.alloc(Expression {
span,
kind: ExpressionKind::ConditionalExpression(ConditionalExpression {
test: left,
consequent,
alternate,
}),
}))
}
/// The sequence step of [`Parser::parse_expression_bp`], at the first `,`: the
/// elements after `left` (starting at `expr_start`). Out of line, off the expression
/// ladder's common path.
#[inline(never)]
fn parse_sequence_step(
&mut self,
left: &'arena Expression<'arena>,
expr_start: usize,
) -> Result<&'arena Expression<'arena>, Error> {
let mut expressions = self.bvec();
expressions.push(left);
// the first element, parsed before the comma said it was one, is the sequence's
// left operand: a spine link, which every walk takes by re-entering its printer
// (`((a, b), c)` nests a sequence per grouping paren)
self.spine_link(LINK_REENTRY)?;
// the elements are siblings (`ListFrame`); the first is already counted
let mut frame = self.list_frame();
while self.eat(TokenKind::Comma)? {
frame.element(self, expressions.len());
// Parse next expression - use BP_ASSIGNMENT to stop before next comma; one
// wire level: the element under its `SequenceExpression`
let next = self.nested(1, |p| p.parse_expression_bp(BP_ASSIGNMENT))?;
expressions.push(next);
}
frame.close(self);
// the pair the printer writes around it (`(a, b);`), a level of the output's
// nesting
self.sequence_pair(expr_start)?;
// the last element's last consumed token (a trailing grouping paren included)
let span = Span::new(expr_start as u32, self.prev_token_end() as u32);
if let (Some(first), Some(last)) = (expressions.first(), expressions.last()) {
debug_assert_encloses(span.start, span.end, first, last);
}
Ok(self.arena.alloc(Expression {
span,
kind: ExpressionKind::SequenceExpression(SequenceExpression {
expressions: expressions.into_bump_slice(),
}),
}))
}
/// One binary operator step of [`Parser::parse_expression_bp`]'s precedence loop,
/// the current token being `operator` (binding `right_bp` on its right) over `left`,
/// which starts the chain's extent at `expr_start`: the operator, its right operand,
/// and the node over the two, with the depth limit's link and the printer's pairs.
/// Out of line, so the expression ladder's common path — an operand and no operator —
/// carries none of its state.
#[inline(never)]
fn parse_binary_step(
&mut self,
left: &'arena Expression<'arena>,
expr_start: usize,
operator: BinaryOperator,
right_bp: u8,
) -> Result<&'arena Expression<'arena>, Error> {
// Read BEFORE the operator is consumed and the right operand parsed: the
// question is whether enough `<` stand AHEAD of this token for it to close
// every list they open — one for a `>`, two for a `>>`, three for a `>>>` —
// and a `<` inside its own right operand does not
// (`BinaryExpression::may_close_type_arguments`).
let lists_closed = match operator {
BinaryOperator::GreaterThan => 1,
BinaryOperator::RightShift => 2,
BinaryOperator::UnsignedRightShift => 3,
_ => 0,
};
let may_close_type_arguments =
lists_closed > 0 && self.lt_regions_open_before(expr_start) >= lists_closed;
// Span coordinates, as `expr_start` is — the two are only ever compared.
let operator_pos = self.current_pos().0;
// one link of the operator chain, which nests to the left
self.spine_link(self.binary_link_units(operator, left))?;
self.advance()?; // consume operator
// A `<<` opens regions as a `<` does — tsc re-scans it to one where it looks
// for type arguments (`reScanLessThanToken`), and the `<` left behind is the
// next list's.
match operator {
BinaryOperator::LessThan => self.open_lt_regions(operator_pos, 1),
BinaryOperator::LeftShift => self.open_lt_regions(operator_pos, 2),
_ => {}
}
// Parse right-hand side with right binding power: one wire level. Once the
// frame's count runs long, each operand takes a spine frame of its own, the
// chain's operands being siblings; the chain's own links stay in this frame.
let chain = self.spine.runs_long().then(|| self.spine.take());
let right = self.nested(1, |p| p.parse_expression_bp(right_bp))?;
if let Some(chain) = chain {
self.spine.fold(chain);
}
// The pairs the printer adds around the operands where the source wrote none
// (`(a == b) == c`, `a ** (b ** c)`), each a level of the output's nesting —
// a left operand is bare where it starts the chain's own extent, a right one
// where it ends at the last token read — and an `in` binary's own inside a
// `for` header ([`Parser::self_pair`])
if !(crate::printer::operator_operand_takes_no_pair(left)
&& crate::printer::operator_operand_takes_no_pair(right))
{
self.binary_operand_pairs(operator, left, right, expr_start)?;
}
if operator == BinaryOperator::In && self.in_for_header {
self.self_pair(expr_start)?;
}
// Create binary expression
// `expr_start` (which includes any opening paren) to the right operand's last
// consumed token (which includes any closing paren)
let span = Span::new(expr_start as u32, self.prev_token_end() as u32);
debug_assert_encloses(span.start, span.end, left, right);
Ok(self.arena.alloc(Expression {
span,
kind: ExpressionKind::BinaryExpression(BinaryExpression {
left,
operator,
right,
// Set only by the lazy `>` reading in the loop, which re-allocates the node.
relexes_as_type_arguments: false,
may_close_type_arguments,
}),
}))
}
/// One `?.` link of [`Parser::parse_postfix_expression`]'s chain over `left` (the chain
/// starting at `start`, the current token the `?.`). Out of line, off the chain's common
/// links.
#[inline(never)]
fn parse_optional_link(
&mut self,
mut left: &'arena Expression<'arena>,
start: u32,
) -> Result<&'arena Expression<'arena>, Error> {
let arena = self.arena;
self.chain_base_pair(left, start)?;
self.advance()?; // consume '?.'
// counted once the token past the `?.` tells a call from a member
let call = matches!(
self.current_kind(),
TokenKind::ParenOpen | TokenKind::LessThan | TokenKind::LeftShift
);
let charged = if call {
self.call_link_units(left)
} else {
self.member_link_units(left)
};
self.spine_link(charged)?;
match self.current_kind() {
TokenKind::Hash | TokenKind::Identifier | TokenKind::Keyword(_) => {
// obj?.prop or obj?.#private - optional property access
let (property, prop_end) = self.parse_dot_property()?;
let span = Span::new(start, prop_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: left,
property: arena.alloc(property),
computed: false,
optional: true,
}),
},
);
}
TokenKind::BracketOpen => {
// obj?.[expr] - optional computed access
self.advance()?; // consume '['
self.enter_grouping()?;
let index = self.parse_expression_ref()?;
let (_, bracket_end) = self.current_pos();
self.expect(&TokenKind::BracketClose)?; // consume ']'
self.exit_grouping();
let span = Span::new(start, bracket_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: left,
property: index,
computed: true,
optional: true,
}),
},
);
}
TokenKind::ParenOpen => {
// obj?.() - optional call
self.advance()?; // consume '('
let (arguments, paren_end) = self.parse_call_arguments()?;
let arguments = arguments.into_bump_slice();
let span = Span::new(start, paren_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::CallExpression(CallExpression {
callee: left,
type_arguments: None,
arguments,
optional: true,
}),
},
);
self.settle_call_link(left)?;
}
TokenKind::LessThan | TokenKind::LeftShift
if self.is_type_arguments_start(TypeArgScan::Parse) =>
{
// obj?.<T>(args) - optional call with explicit type arguments;
// only a call may follow (`a?.<T>` without `(` is a syntax error)
let type_args = self.parse_type_arguments_before_call()?;
self.advance()?; // consume '('
let (arguments, paren_end) = self.parse_call_arguments()?;
let arguments = arguments.into_bump_slice();
let span = Span::new(start, paren_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::CallExpression(CallExpression {
callee: left,
type_arguments: Some(type_args),
arguments,
optional: true,
}),
},
);
self.settle_call_link(left)?;
}
_ => {
return Err(self.error_expected_after("property name, '[', or '('", "?."));
}
}
Ok(left)
}
/// The tagged template link of [`Parser::parse_postfix_expression`]'s chain over `left`
/// (the chain starting at `start`, the current token the template; `optional_chained`
/// where a `?.` came before it, which a tag may not hold). Out of line, off the
/// chain's common links.
#[inline(never)]
fn parse_tag_link(
&mut self,
left: &'arena Expression<'arena>,
start: u32,
optional_chained: bool,
) -> Result<&'arena Expression<'arena>, Error> {
self.spine_link(LINK_TAG)?;
self.function_head_pair(left, start, ParenContext::TaggedTemplateTag)?;
// one wire level: the quasi's `TemplateLiteral` under its tag node, whose
// own level is its `${`'s
let template = self.nested(1, |p| p.parse_template_literal(true))?;
// An optional chain can't be a template tag (per spec): `a?.b`x``
// is a syntax error. A parenthesized chain (`(a?.b)`x``) seals the
// chain (consumed as its own primary, so `optional_chained` is
// false here) and is valid.
if optional_chained {
return Err(self.error_msg(
"Optional chaining cannot appear in the tag of tagged template expressions",
));
}
// A `` tag<T>`x` `` tagged template lifts the tag's `<T>`
// into the tag's `typeArguments` (see `flatten_instantiation`).
let (tag, type_arguments) = self.flatten_instantiation(left);
Ok(self.build_tagged_template(tag, start, type_arguments, template))
}
/// Parse postfix expressions: member access (`.`, `[`), call expressions (`()`)
///
/// Handles chained expressions like `obj.prop`, `arr[0]`, `foo()`, `obj.method().prop`
fn parse_postfix_expression(
&mut self,
mut left: &'arena Expression<'arena>,
start: u32,
mode: SubscriptMode,
) -> Result<&'arena Expression<'arena>, Error> {
let arena = self.arena;
// Tracks whether an optional `?.` was consumed in THIS subscript chain (not
// inside a parenthesized sub-expression — those are parsed as their own
// primary with a fresh flag). An optional chain may not be the tag of a
// tagged template (`a?.b`x`` is a syntax error); a parenthesized chain
// (`(a?.b)`x``) seals it and is valid. Mirrors acorn's `optionalChained`.
let mut optional_chained = false;
loop {
match self.current_kind() {
TokenKind::Dot => {
// Member access: obj.prop or obj.#private
let units = self.member_link_units(left);
self.spine_link(units)?;
self.chain_base_pair(left, start)?;
self.advance()?; // consume '.'
let (property, prop_end) = self.parse_dot_property()?;
let span = Span::new(start, prop_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: left,
property: arena.alloc(property),
computed: false,
optional: false,
}),
},
);
}
TokenKind::QuestionDot => {
// Optional chaining: obj?.prop, obj?.#private, obj?.[expr], obj?.()
optional_chained = true;
left = self.parse_optional_link(left, start)?;
}
TokenKind::BracketOpen => {
// Computed member access: arr[0]
let units = self.member_link_units(left);
self.spine_link(units)?;
self.advance()?; // consume '['
self.enter_grouping()?;
let index = self.parse_expression_ref()?;
let (_, bracket_end) = self.current_pos();
self.expect(&TokenKind::BracketClose)?; // consume ']'
self.exit_grouping();
let span = Span::new(start, bracket_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: left,
property: index,
computed: true,
optional: false,
}),
},
);
}
TokenKind::ParenOpen => {
// Call expression: foo()
let units = self.call_link_units(left);
self.spine_link(units)?;
self.function_head_pair(left, start, ParenContext::Callee)?;
self.advance()?; // consume '('
let (arguments, paren_end) = self.parse_call_arguments()?;
let arguments = arguments.into_bump_slice();
let span = Span::new(start, paren_end as u32);
// A `foo<T>(...)` generic call lifts the callee's `<T>` into
// the call's `typeArguments` (see `flatten_instantiation`).
let (callee, type_arguments) = self.flatten_instantiation(left);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::CallExpression(CallExpression {
callee,
type_arguments,
arguments,
optional: false,
}),
},
);
self.settle_call_link(left)?;
}
TokenKind::NoSubstitutionTemplate | TokenKind::TemplateHead => {
// Tagged template expression: tag`content`
left = self.parse_tag_link(left, start, optional_chained)?;
}
kind @ TokenKind::PlusPlus | kind @ TokenKind::MinusMinus
if mode == SubscriptMode::Normal && !self.had_line_terminator =>
{
// Postfix update expression: x++, x--
// ASI Rule: If there's a line terminator before ++/--, ASI fires
// and the ++/-- becomes a prefix operator on the next statement.
// So we only parse postfix if NO line terminator preceded this token.
let operator = if *kind == TokenKind::PlusPlus {
UpdateOperator::Increment
} else {
UpdateOperator::Decrement
};
let (_, op_end) = self.current_pos();
self.spine_link(LINK_OPERATOR)?;
self.advance()?;
let span = Span::new(start, op_end as u32);
left = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::UpdateExpression(UpdateExpression {
operator,
argument: left,
prefix: false,
}),
},
);
// A postfix `++`/`--` yields an UpdateExpression, which is not a
// `LeftHandSideExpression` — no further member/call subscript can
// apply (`a++[b]` / `a++.c` / `a++()` are grammar errors; acorn
// stops here). Break so a following `[`/`.`/`(` starts a new
// construct (e.g. the next member in a class body, across ASI).
break;
}
TokenKind::LessThan | TokenKind::LeftShift => {
// Might be TSInstantiationExpression: f<T>, expr<Type>
// (a `<<` shift token splits when its tail opens a generic
// function type: `f<<T>(v: T) => void>()`).
// If it parses as type arguments it's instantiation; otherwise
// let binary expression handle it as comparison/shift.
//
// In ClassHeritage mode a bare `<T>` belongs to the class's
// `super_type_parameters` split, so we leave it for the caller; only a
// list the expression goes on past is consumed here — a call's
// (`Base<T>(...)`, flattened into the call), a tag's (`` f<T>`t` ``) or
// a member's object past a line break (`f<T>⏎[0]`). A `<` that isn't
// type args stops the chain either way.
let consume = self.is_type_arguments_start(TypeArgScan::Parse)
&& (mode == SubscriptMode::Normal
|| self.heritage_type_args_continue_expression());
if !consume {
break;
}
// The lookahead admitted a list; where its tail turns out to be
// none, the `<` is handed back and the binary loop reads it.
let Some(instantiation) = self.parse_instantiation_expression(left, start)?
else {
break;
};
let units = self.call_link_units(left);
self.spine_link(units)?;
// the pair the printer keeps around an instantiation instantiated
// again (`(f<T>)<U>`, a call's or tag's list included, which flatten
// this one), a level of the output's nesting
if Self::is_bare_instantiation(left, start) {
self.printer_pair()?;
}
left = instantiation;
// An instantiation expression can't be followed by a property
// access (`f<T>.x`); a call or tagged template, which the loop
// below flattens into the expression, stays valid.
self.reject_instantiation_follower()?;
}
TokenKind::Bang if !self.had_line_terminator => {
// TypeScript non-null assertion: `expr!`.
let units = self.non_null_link_units(left);
self.spine_link(units)?;
left = self.wrap_non_null_assertion(left, start)?;
}
_ => break,
}
}
Ok(left)
}
/// Parse the superclass expression of an `extends` clause.
///
/// Per ecma262 §15.7 `ClassHeritage : extends LeftHandSideExpression`. Matches
/// acorn's `parseExprSubscripts` with `canBeArrow = false`: a primary atom
/// (identifier, literal, parenthesized expression, array/object, template,
/// `class`/`function` expression, `new`, `import()`) followed by member/call/
/// non-null/tagged-template subscripts. Non-LHS forms (ternary, binary, unary,
/// `await`, assignment, and a top-level `=>` arrow) are excluded — the class body
/// then errors when it fails to find `{`. A bare `<T>` is left for the class's
/// `super_type_parameters` split via `SubscriptMode::ClassHeritage`.
pub(in crate::parser) fn parse_heritage_expression(
&mut self,
) -> Result<&'arena Expression<'arena>, Error> {
self.chain(|p| {
let start = p.current_pos().0 as u32;
let atom = p.parse_heritage_atom()?;
p.parse_postfix_expression(atom, start, SubscriptMode::ClassHeritage)
})
}
/// Whether the current `async` heads an async function expression: `function` follows
/// on the same line. `async [no LineTerminator here] function` (ecma262), so across a
/// line break `async` is a plain identifier — `new async⏎function f() {}` is
/// `new async;` and a declaration, `class A extends async⏎function () {} {}` a syntax
/// error — as the primary path reads it, whose one gate ahead of every `async`
/// refinement this restates for the two callers that ask about the function shape
/// alone (the `new` callee, the heritage atom).
fn at_async_function_expression(&mut self) -> bool {
*self.current_kind() == TokenKind::Keyword(KeywordKind::Async)
&& self.peek_kind() == TokenKind::Keyword(KeywordKind::Function)
&& !self.peek_preceded_by_line_terminator()
}
/// Parse the primary atom of an `extends` clause (acorn's `parseExprAtom` with
/// `canBeArrow = false`). `parse_primary_expression` covers identifiers,
/// literals, parens, arrays, objects, templates, `this`/`super`, and regex; the
/// keyword-led expression atoms (`new`, `class`, `function`, `async function`,
/// `import`) sit above the primary layer and are dispatched here.
fn parse_heritage_atom(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
// `async function () {}` is the only `async`-led heritage atom. A bare `async`
// (or an `async`-arrow, which isn't a valid heritage atom) falls through to the
// primary path, where `async` parses as a plain identifier. Peeking needs
// `&mut self`, so this can't be a match guard over the borrowing `current_kind`.
if self.at_async_function_expression() {
self.advance()?; // consume 'async'
return self.parse_async_function_expression(start);
}
match self.current_kind() {
TokenKind::Keyword(KeywordKind::New) => self.parse_new_expression_in(true),
// a class expression's own heritage recurses here (`class extends class extends
// …`), its level the heritage clause's (`parse_optional_extends_clause`)
TokenKind::Keyword(KeywordKind::Class) => self.parse_class_expression(),
TokenKind::Keyword(KeywordKind::Function) => self.parse_function_expression(),
TokenKind::Keyword(KeywordKind::Import) => self.parse_import_or_meta_property(),
_ => {
let parsed = self.parse_primary_expression()?;
// Reject a top-level (unparenthesized) arrow: `class C extends (a) => b {}`.
// acorn parses the heritage atom with `canBeArrow = false`, so an outer
// arrow isn't a valid superclass. A *parenthesized* arrow
// (`extends (a => b) {}`) is fine — there the arrow's own span starts
// past the `(`, so it differs from where the atom's parse began
// (`is_bare_assignment_head`, the one spelling of that test).
if is_bare_assignment_head(parsed, start, false) {
return Err(self.error_msg(
"Arrow functions cannot be used as a class heritage expression",
));
}
Ok(parsed)
}
}
}
/// Whether the type-argument list at the current `<` (or `<<`) is the heritage
/// EXPRESSION's rather than the class's `super_type_parameters`: the expression goes on
/// past its close. Used by the `ClassHeritage` subscript mode to tell
/// `extends Base<T>` (the split) from a list the superclass expression owns —
///
/// - a call's (`getMixin<T>(Base)`);
/// - a tag's (`` extends f<T>`t` ``, on any line, as a template continues a tag on any
/// line), the class's own list then following the template (`` f<T>`t`<U> ``);
/// - a computed member's object past a line break (`extends f<T>⏎[0]`). On the list's
/// own line a `[` refuses an instantiation (tsc's `canFollowTypeArgumentsInExpression`,
/// acorn-typescript's `startsExpr` bail), so `f<T>[0]` stays rejected.
///
/// tsc reads the clause through `parseExpressionWithTypeArguments`, acorn-typescript
/// through its subscript loop; both take every one of these as the expression's.
/// `matching_angle_close` handles an `=>` arrow's `>` (`getMixin<() => void>(Base)`),
/// comments, and strings; for a `<<` token, the second `<` re-raises the depth so the
/// scan finds the outer close.
fn heritage_type_args_continue_expression(&self) -> bool {
let bytes = self.source.as_bytes();
let start = self.current.start as usize;
// Must start with '<'
if start >= bytes.len() || bytes[start] != b'<' {
return false;
}
let Some(close) = matching_angle_close(bytes, start + 1, TypeArgScan::Parse) else {
return false;
};
let after = skip_whitespace_and_comments(bytes, close + 1);
match bytes.get(after) {
Some(b'(' | b'`') => true,
Some(b'[') => has_line_terminator_between(bytes, close + 1, after),
_ => false,
}
}
/// Parse a Number token into a Literal, handling BigInt suffix.
///
/// The one gate on the **leading-zero** literals — `LegacyOctalIntegerLiteral`
/// (`010`) and `NonOctalDecimalIntegerLiteral` (`08`). The lexer reads both under
/// every mode; strict code makes them a Syntax Error, a Static Semantics early error
/// the parser enforces (ecma262 sec-numeric-literals-early-errors; `Parser::strict`
/// says why it rejects), so the rejection belongs here, where the token
/// becomes a node and the enclosing code's strictness is settled. Every position a
/// numeric literal can occupy routes through this — an expression, an object or
/// class key, a literal type, a `TSLiteralType`'s negated operand, and a type
/// member's key — so the gate is stated once.
pub(crate) fn parse_number_or_bigint_literal(&self) -> Result<Literal<'arena>, Error> {
let (start, end) = self.current_pos();
let raw = self.current_value();
if self.strict
&& let Some(form) = classify_leading_zero(raw)
{
let message = match form {
LeadingZeroLiteral::LegacyOctal => {
"Legacy octal literals are not allowed in strict mode. Use '0o' for octal."
}
LeadingZeroLiteral::NonOctalDecimal => {
"Decimals with leading zeros are not allowed in strict mode."
}
};
return Err(self.error_msg_at(message, start));
}
if raw.ends_with('n') {
// BigInt — no stored payload; digits via `Literal::bigint_digits(source)`.
Ok(Literal {
value: LiteralValue::BigInt,
span: Span::new(start as u32, end as u32),
})
} else {
let number = parse_number_literal(raw)
.map_err(|_| self.error_msg_at(&format!("Invalid number: {raw}"), start))?;
Ok(Literal {
value: LiteralValue::Number(number),
span: Span::new(start as u32, end as u32),
})
}
}
/// Parse a primary expression
fn parse_primary_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
match self.current_kind() {
TokenKind::Number => {
let literal = self.parse_number_or_bigint_literal()?;
self.advance()?;
Ok(alloc_expr(self.arena, Expression::from_literal(literal)))
}
TokenKind::String => {
let literal = self.parse_string_literal()?;
Ok(alloc_expr(self.arena, Expression::from_literal(literal)))
}
TokenKind::Identifier => {
let (start, end) = self.current_pos();
let name = self.current_ident_name();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_identifier(Identifier::simple(
name,
Span::new(start as u32, end as u32),
)),
))
}
// `await` / `yield` as an ordinary `IdentifierReference` (Script
// `[~Await]` / `[~Yield]`) — e.g. a `new` callee (`new await()`,
// `new yield()`) or any primary reference.
TokenKind::Keyword(KeywordKind::Await) if self.await_is_identifier() => {
self.parse_await_name_reference()
}
TokenKind::Keyword(KeywordKind::Yield) if self.yield_is_identifier() => {
self.parse_keyword_identifier_reference()
}
TokenKind::Keyword(KeywordKind::Let) => self.parse_keyword_identifier_reference(),
TokenKind::BraceOpen => {
// one wire level beyond the expression's own: the `Property` its values
// sit under (the depth limit's count, `Parser::nested`)
let (object, span) = self.nested(1, Self::parse_object_expression)?;
Ok(alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::ObjectExpression(object),
},
))
}
TokenKind::BracketOpen => {
let (array, span) = self.parse_array_expression()?;
Ok(alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::ArrayExpression(array),
},
))
}
TokenKind::Keyword(KeywordKind::True) => {
let (start, end) = self.current_pos();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_literal(Literal {
value: LiteralValue::Boolean(true),
span: Span::new(start as u32, end as u32),
}),
))
}
TokenKind::Keyword(KeywordKind::False) => {
let (start, end) = self.current_pos();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_literal(Literal {
value: LiteralValue::Boolean(false),
span: Span::new(start as u32, end as u32),
}),
))
}
TokenKind::Keyword(KeywordKind::Null) => {
let (start, end) = self.current_pos();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_literal(Literal {
value: LiteralValue::Null,
span: Span::new(start as u32, end as u32),
}),
))
}
TokenKind::Keyword(KeywordKind::This) => {
let (start, end) = self.current_pos();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression { span: Span::new(start as u32, end as u32), kind: ExpressionKind::ThisExpression(ThisExpression {
}) },
))
}
TokenKind::Keyword(KeywordKind::Super) => {
let (start, end) = self.current_pos();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression { span: Span::new(start as u32, end as u32), kind: ExpressionKind::Super(Super {
}) },
))
}
TokenKind::ParenOpen => {
// Could be: arrow function `() => ...` or parenthesized expression `(expr)`
self.parse_paren_expression()
}
TokenKind::NoSubstitutionTemplate | TokenKind::TemplateHead => {
// Untagged template literal (a primary expression): invalid escapes
// are a syntax error (only tagged templates tolerate them).
Ok(alloc_expr(
self.arena,
Expression::from_template_literal(self.parse_template_literal(false)?),
))
}
TokenKind::Slash | TokenKind::SlashEquals => {
// In expression context, `/` or `/=` starts a regex literal, not division
// Division is only possible after a value (identifier, number, closing bracket)
// but we're in parse_primary_expression which is called when expecting a value.
//
// When lexer sees `/=`, it returns SlashEquals (division assignment), but in
// expression-start context this is actually a regex starting with `=` like /=\s*/.
//
// Use current_start directly (not current_pos) because the lexer expects positions
// relative to its source slice, not the full document offset.
//
// The relex re-reads source from the `/`: a populated peek cache here
// would leave a stale token behind, and comments drained by that peek
// would be re-read as regex pattern chars.
debug_assert!(
self.peek.is_none(),
"regex relex with populated peek cache"
);
let lexer_start = self.current.start as usize;
let (regex_token, pattern_end) = self.lexer.read_regex_literal(lexer_start)?;
let lexer_end = regex_token.end as usize;
// Pattern and flags are verbatim source slices (escapes preserved),
// recovered from spans rather than owned strings. `pattern_end` is the
// closing `/` (local): pattern is [slash+1, close), flags are
// [close+1, token end). Spans are stored in host coordinates
// (`span_pos` applies the `base_offset` shift).
let pattern_span =
Span::new(self.span_pos(lexer_start + 1), self.span_pos(pattern_end));
let flags_span =
Span::new(self.span_pos(pattern_end + 1), self.span_pos(lexer_end));
// Precompute the pattern's visual width so the "simple call argument"
// width check stays source-free; saturate to the field's u16 range.
let pattern_width = visual_width(&self.source[lexer_start + 1..pattern_end], TAB_WIDTH)
.min(u16::MAX as usize) as u16;
// Advance past the regex token by reading the next token. The regex relex
// bypasses advance_inner() (the lexer was resynced by read_regex_literal), so
// mirror the bookkeeping we need by hand: record the regex token's end as
// prev_end (so prev_token_end() covers the regex — object Property/SpreadElement
// spans read it), set the current token, refresh the ASI line-terminator flag,
// and absorb any comments that land right after the regex (`{a: /re/ /*c*/}`) the
// same way advance_inner() does — without this the comment stays as the current
// token and the next consumer rejects it.
self.prev_end = lexer_end;
let next_token = self.lexer.next_token()?;
self.update_current(next_token);
// Update ASI state - line terminators after regex enable semicolon insertion
self.had_line_terminator = self.lexer.had_line_terminator();
self.collect_comments()?;
Ok(alloc_expr(
self.arena,
Expression { kind: ExpressionKind::RegexLiteral(RegexLiteral {
pattern_span,
flags_span,
pattern_width,
}), span: Span::new(self.span_pos(lexer_start), self.span_pos(lexer_end)) },
))
}
TokenKind::Hash => {
// ecma262 `RelationalExpression : PrivateIdentifier in ShiftExpression` — a
// private name is an expression ONLY as the left side of a brand check
// (`#field in obj`). Anywhere else (`const x = #a`) it is a syntax error,
// and the canonical parser rejects it, so require the `in` here rather than
// handing a bare `#a` to the binary-expression machinery. Without the guard
// tsv over-accepted; in a Svelte attribute value that surfaced as `{#a}`
// parsing as an expression the canonical parser refuses.
let (private_id, span) = self.parse_private_identifier()?;
if !matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::In)) {
return Err(self.error_expected_after("'in'", "private name"));
}
Ok(alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::PrivateIdentifier(private_id),
},
))
}
// TypeScript type keywords and contextual keywords are valid identifiers in expression context.
// `void` is not one: it is an ECMAScript ReservedWord, the unary operator, so a bare
// `void` reaching a primary (a `new` callee, a decorator head, a heritage atom) is a
// syntax error, as `typeof` is.
TokenKind::Keyword(KeywordKind::Number)
| TokenKind::Keyword(KeywordKind::String)
| TokenKind::Keyword(KeywordKind::Boolean)
| TokenKind::Keyword(KeywordKind::Any)
| TokenKind::Keyword(KeywordKind::Never)
| TokenKind::Keyword(KeywordKind::Unknown)
| TokenKind::Keyword(KeywordKind::Object)
| TokenKind::Keyword(KeywordKind::Symbol)
| TokenKind::Keyword(KeywordKind::Bigint)
// `undefined` is a global identifier (not a ReservedWord), so in value
// position it is an `Identifier` named "undefined" — never a literal.
// This makes it a valid assignment target (`undefined = 12`). acorn
// models it the same way.
| TokenKind::Keyword(KeywordKind::Undefined)
// Contextual keywords that can be identifiers
| TokenKind::Keyword(KeywordKind::Async)
| TokenKind::Keyword(KeywordKind::From)
| TokenKind::Keyword(KeywordKind::As)
| TokenKind::Keyword(KeywordKind::Satisfies) => {
let (start, end) = self.current_pos();
let name = self.current_raw_ident_name();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_identifier(Identifier::simple(
name,
Span::new(start as u32, end as u32),
)),
))
}
_ => Err(Error::invalid_expression(
self.current_kind().to_string(),
self.current_pos().0,
)),
}
}
/// Parse parenthesized expression or arrow function
///
/// Distinguishes between:
/// - Arrow function: `() => ...`, `(x) => ...`, `(x, y) => ...`
/// - Grouped expression: `(expr)`
///
/// Uses lookahead to detect arrow functions by scanning for `=>` after `)`.
fn parse_paren_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
// Check if this looks like an arrow function by scanning ahead. In a
// conditional's consequent the arrow may be handed back (`None`): its
// return-type `:` was the conditional's, and the head is the grouped
// expression below (`a ? (b) : c => d`).
if let Some(head) = self.paren_arrow_function_start()
&& let Some(arrow) = self.parse_arrow_or_rewind(head, Self::parse_arrow_function)?
{
return Ok(arrow);
}
// Parse as grouped expression: (expr)
// The discarded parens stay part of this parse's extent — it began at the `(` and
// ends at the `)` — so a containing node still spans them: (a ? b : c)() has its
// CallExpression starting at '(', not at 'a'
let (paren_start, _) = self.current_pos();
let cast_comment_idx = self.jsdoc_cast_comment_index(paren_start);
// The cheap half of the glued-comment pair's test, read while the comment is the
// last one drained: a block glued to this `(`. The interior half waits for the
// pair's comments ([`Self::glued_comment_pair_index`]).
let glued_idx = if cast_comment_idx.is_none() && !self.preserve_parens {
self.glued_block_comment_index(paren_start)
} else {
None
};
self.expect(&TokenKind::ParenOpen)?; // consume '('
self.enter_grouping()?;
// the author's pair: a node that would count one for itself counts none
let parsed =
self.pair_free_root(RootEnd::AtParenClose, |p| p.parse_expression_bp(BP_COMMA))?;
// Capture the end position of ')' before consuming it
let (_, paren_end) = self.current_pos();
self.expect(&TokenKind::ParenClose)?; // consume ')'
// The one delimiter the printer may strip, so a `<` region opened inside it is
// not closed by this `)`.
self.exit_stripped_grouping();
debug_assert_encloses(paren_start as u32, paren_end as u32, parsed, parsed);
// A binding pattern is read as a literal and refined after the parse, so the
// pair it would reject has to outlive the discard (`let [(a)] = x`).
if self.record_grouping_parens {
self.grouping_parens.push(GroupingParen {
inner: parsed.span(),
open: paren_start as u32,
});
}
// Grouping parens are normally discarded (the inner's own allocation flows
// through, paren-free like acorn/Svelte). Two positions preserve them as an
// explicit wrapper node spanning `(`…`)` — the same bounds as the extent a
// containing expression reads for a discarded pair:
// - **JSDoc type cast** (`/** @type {T} */ (expr)`) — the parens are
// semantically required (dropping them drops the cast), so a preceding
// `@type`/`@satisfies` block comment wraps the inner in a `CommentBoundPair`. The cast
// also takes **ownership** of that comment: the comment and this `(` are one
// unit, so the cast prints it and the flat-`Vec<Comment>` lookups skip it
// (`Comment::owned_by_node`) — printed from an enclosing gap instead, a
// paren synthesized around an enclosing expression lands between the two
// and the cast silently re-binds to the wider node on reparse. This owning
// is not fully subsumed by the general "every glued block comment is owned"
// rule (`bind_leading_comment`), which binds only a **same-line** glued
// comment (`CommentGlue::SameLine`); a cast comment may sit a newline
// **above** its `(` (`AnyLine`) and still be the cast, so the cast owns it
// here regardless (a same-line cast comment is owned by both, harmlessly).
// - **Wire-only sub-parse** (`preserve_parens`: a `{#snippet}` head, the binding
// audit) — acorn's `preserveParens` without Svelte's `remove_parens`; wraps in a
// `ParenthesizedExpression` for the wire alone — the printer and the compiler
// read a second, paren-free parse of the same source. This is tested FIRST: a
// cast's pair is a grouping pair to acorn like any other, so under
// `preserveParens` it is a `ParenthesizedExpression` too (the cast comment
// attaches to it as a leading comment — Svelte's `{#snippet}` wire), and the
// `CommentBoundPair` belongs to the paren-free tree, the one that prints. The comment's
// ownership is still claimed here, so the two parses agree on it (the binding
// audit buckets a cast's re-binding HARD by it).
// - **Glued-comment pair** (`/* c */ (⏎// d⏎expr)`) — a block glued to the `(` of a
// pair whose interior opens with a line comment keeps the pair in the same node,
// owning the block, so it prints exactly as a cast does
// ([`Self::glued_comment_pair_index`]). Not under `preserve_parens`: that tree
// keeps every pair already.
// Every other comment stays located positionally at print time.
let paren_span = Span::new(paren_start as u32, paren_end as u32);
let expr = if self.preserve_parens {
if let Some(idx) = cast_comment_idx {
self.comments[idx].owned_by_node = true;
}
self.preserved_a_paren = true;
self.alloc(Expression {
span: paren_span,
kind: ExpressionKind::ParenthesizedExpression(ParenthesizedExpression {
expression: parsed,
}),
})
} else if let Some((idx, kind)) = cast_comment_idx
.map(|idx| (idx, CommentBoundPairKind::Cast))
.or_else(|| {
let idx = self.glued_comment_pair_index(glued_idx?, paren_start)?;
Some((idx, CommentBoundPairKind::GluedComment))
})
{
self.comments[idx].owned_by_node = true;
let comment = self.comments[idx];
self.alloc(Expression {
span: paren_span,
kind: ExpressionKind::CommentBoundPair(CommentBoundPair {
inner: parsed,
comment,
kind,
}),
})
} else {
parsed
};
Ok(expr)
}
/// The index in `self.comments` of the JSDoc type-cast block comment
/// (`/** @type {T} */` / `/** @satisfies {T} */`) immediately preceding a `(` at
/// `paren_start` — which is what makes those parens a cast that must be preserved.
/// `None` when the `(` is an ordinary grouping/call paren.
///
/// Mirrors prettier's predicate (`is-type-cast-comment.js` +
/// `postprocess/index.js`): a **block** comment whose text starts with `*`
/// (the `/**` form) and contains `@type`/`@satisfies` (word boundary), with
/// only whitespace between the comment's `*/` and the `(`.
///
/// The caller hands the index to the `CommentBoundPair`, which takes ownership of the
/// comment — so this must identify it *exactly*, never merely "a cast-shaped
/// comment somewhere before here" (an owned comment nothing prints is a dropped
/// comment).
fn jsdoc_cast_comment_index(&self, paren_start: usize) -> Option<usize> {
// `paren_start` is a full-file offset (`current_pos` adds `base_offset`);
// `self.source` is the local slice, so translate back to a local index.
//
// `AnyLine`: the cast's comment may sit on its own line above the `(`
// (`const a =⏎ /** @type {T} */⏎ (v);`) and still be the cast — unlike a bundler
// annotation, which binds only when glued to its token (`SameLine`, see
// `glued_block_comment_index`).
let i = source_scan::block_comment_end_before(
self.source.as_bytes(),
paren_start - self.base_offset,
source_scan::CommentGlue::AnyLine,
)?;
// Resolve the comment through the lexer's spans rather than re-scanning the
// source (see `block_comment_end_before` — byte scanning cannot find the real
// `/*`). The comment ending here was just drained into `self.comments`; match it
// by its host-coordinate end and test its exact (delimiter-excluded) content.
let token_end = (i + self.base_offset) as u32;
let idx = self
.comments
.iter()
.rposition(|c| c.span.end == token_end)?;
let c = &self.comments[idx];
if !c.is_block {
return None;
}
// The text tested is the run's, not this comment's: two byte-adjacent indentable
// blocks are ONE comment, and prettier merges them (`mergeNestledJsdocComments`,
// run from `postprocess/index.js`) *ahead of* its `isTypeCastComment` scan — so
// `/** @type {T}⏎ *//** c⏎ */ (x)` is a cast whose marker sits in the head. The
// merged content is a plain source slice from the run's first `/*` to this
// comment's `*/` (`merge_nestled_block_comments`, which keeps the trailing
// entry's flags), so `idx` remains the comment the cast owns and prints.
let run_start =
tsv_lang::nestled_run_start(&self.comments, idx, |c| self.comment_content(c));
let start = self.comments[run_start].content_span.start as usize - self.base_offset;
let end = c.content_span.end as usize - self.base_offset;
is_jsdoc_type_cast_comment(&self.source[start..end]).then_some(idx)
}
/// `glued_idx` — the block glued to the `(` at `paren_start`
/// ([`Self::glued_block_comment_index`]) — when the pair's interior opens with a line
/// comment, which makes the pair a [`CommentBoundPairKind::GluedComment`]; `None`
/// otherwise. Called once the pair is parsed, so its comments are all drained.
///
/// "Opens with" means between the `(` and the first token of the content that is not
/// itself a `(`: a stripped inner pair (`/* c */ ((⏎// d⏎x).m)`) and blocks ahead of the
/// line comment (`/* c */ (/* e */ // d⏎x)`) are part of the opening. A line comment
/// after that token (`/* c */ (a + // d⏎b)`, `/* c */ (x // d⏎)`) never separates the
/// block from the value, so it does not count; nor does an interior holding only
/// blocks, which strips with the block still glued through to the value.
///
/// The walk is bounded by that opening run: it steps the source and the comments drained
/// after `glued_idx` in lockstep, skipping whitespace, `(` and comments, and stops at
/// the first other byte — so a pair costs nothing past its leading trivia. The
/// whitespace class is the lexer's ([`skip_whitespace`]): a narrower one would read a
/// non-ASCII space as content and strip a pair whose printed form, its space now
/// ASCII, the next pass keeps.
fn glued_comment_pair_index(&self, glued_idx: usize, paren_start: usize) -> Option<usize> {
let src = self.source.as_bytes();
let mut pos = paren_start - self.base_offset + 1;
let mut next = glued_idx + 1;
loop {
pos = skip_whitespace(src, pos);
match self.comments.get(next) {
Some(c) if c.span.start as usize == pos + self.base_offset => {
if !c.is_block {
return Some(glued_idx);
}
pos = c.span.end as usize - self.base_offset;
next += 1;
}
_ if src.get(pos) == Some(&b'(') => pos += 1,
_ => return None,
}
}
}
/// A collected comment's content (delimiters excluded) as a slice of `self.source`.
///
/// [`Comment::content`](tsv_lang::Comment::content) itself cannot serve: a comment's
/// spans are host coordinates while `self.source` is the island's local slice, so the
/// `base_offset` translation lives here rather than at each caller.
fn comment_content(&self, comment: &tsv_lang::Comment) -> &'a str {
let start = comment.content_span.start as usize - self.base_offset;
let end = comment.content_span.end as usize - self.base_offset;
&self.source[start..end]
}
/// Give the node beginning at `head_start` **ownership** of a leading comment glued
/// to that token, so the printer emits the two together and no paren it synthesizes
/// around an enclosing expression can land between them.
///
/// **Every** glued block comment is owned — the position is an authoring choice that
/// binds the comment to the operand it leads, so a paren the printer synthesizes
/// around an enclosing expression must not land between them, and the leading-comment
/// hoist out of stripped grouping parens (`(/* c */ x ?? y)` → `/* c */ (x ?? y)`)
/// must not fire. There is no content sniff: a bundler annotation
/// (`/* @__PURE__ */`) and a plain comment bind their token identically; only the
/// JSDoc cast is special, and only for *paren retention* (`jsdoc_cast_comment_index`
/// builds the `CommentBoundPair`), never for ownership — that flows through here too.
///
/// `expr` is the node the head token begins — the leftmost leaf of whatever
/// expression is being parsed, before any postfix subscript or infix operator wraps
/// it. The `span().start == head_start` guard is what makes the binding safe: an
/// owned comment nothing prints is a *dropped* comment, so the flag is set only when
/// a node genuinely starts at the token, never when the head was a grouping `(` the
/// parser discards (`/* c */ (a + b)` — there the comment leads a paren, no node
/// begins at it, and it stays an ordinary positional comment).
pub(in crate::parser) fn bind_leading_comment(
&mut self,
head_start: usize,
expr: &Expression<'arena>,
) {
if expr.span().start as usize != head_start {
return;
}
let Some(idx) = self.glued_block_comment_index(head_start) else {
return;
};
self.comments[idx].owned_by_node = true;
}
/// The index in `self.comments` of a **block** comment glued to the token at
/// `head_start` — nothing but spaces/tabs between its `*/` and the token, and no
/// newline (a comment the author put on its own line leads the *line*, not the
/// token, so it keeps its ordinary positional handling).
///
/// Resolves the comment through the lexer's spans rather than re-scanning, for the
/// same reason [`Self::jsdoc_cast_comment_index`] does: a `/*` inside this comment's
/// own body, a preceding line comment, or a string literal are indistinguishable
/// from the real opener by byte scanning.
fn glued_block_comment_index(&self, head_start: usize) -> Option<usize> {
// `head_start` is a full-file offset (`current_pos` adds `base_offset`);
// `self.source` is the local slice, so translate back to a local index.
//
// `SameLine`: a comment the author put on its own line leads the *line*, not the
// token, so it keeps its ordinary positional handling. This is the one axis on
// which this differs from `jsdoc_cast_comment_index` (`AnyLine`), and it is
// load-bearing — an annotation binds only when glued.
let i = source_scan::block_comment_end_before(
self.source.as_bytes(),
head_start.checked_sub(self.base_offset)?,
source_scan::CommentGlue::SameLine,
)?;
let token_end = (i + self.base_offset) as u32;
let idx = self
.comments
.iter()
.rposition(|c| c.span.end == token_end)?;
self.comments[idx].is_block.then_some(idx)
}
/// Parse a TypeScript angle-bracket type assertion: `<Type>expr`
///
/// This is the old-style type assertion syntax. It's equivalent to `expr as Type`
/// but doesn't work in JSX because it looks like an element.
///
/// Example: `<string>value`, `<T>a`
fn parse_type_assertion(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let arena = self.arena;
let (start, _) = self.current_pos();
// Parse <Type> (`<<` splits when the assertion type is a generic
// function type: `<<T>() => R>x`)
self.expect_less_than_in_type()?; // consume '<'
let type_annotation = self.parse_type()?;
self.expect(&TokenKind::GreaterThan)?; // consume '>'
let operand_token = self.current_pos().0;
// The operand is a UnaryExpression, parsed above the assignment tier — which is what
// rejects an unparenthesized arrow (`<T>x => x`), as TypeScript does.
// acorn-typescript instead backtracks and reads `<T>` as the arrow's type
// parameters (a deliberate, cataloged divergence — conformance_svelte.md §Type
// assertion vs. generic arrow). A *parenthesized* arrow (`<T>(() => {})`) stays a
// valid operand.
// one wire level: the operand (the depth limit's count)
let parsed = self.nested(1, |p| p.parse_expression_bp(BP_UNARY))?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
// the pairs the printer adds around the operand, each a level of the output's
// nesting: the one its position takes (`<T>(<U>x)`), and the shell a broken cast
// breaks the operand into (`<T>(⏎\tx⏎)`, prettier's `shouldBreakAfterCast`) around
// any operand but an array or object literal, which expand themselves
let shell = !matches!(
parsed.kind,
ExpressionKind::ArrayExpression(_) | ExpressionKind::ObjectExpression(_)
);
self.count_prefix_operand_pairs(
parsed,
ParenContext::AngleBracketAssertion,
operand_token,
None,
shell,
)?;
Ok(alloc_expr(
arena,
Expression {
span: Span::new(start as u32, end),
kind: ExpressionKind::TSTypeAssertion(TSTypeAssertion {
type_annotation,
expression: parsed,
}),
},
))
}
/// Parse a TypeScript instantiation expression `expr<Type>` from an
/// already-parsed `left` operand whose parse began at `start`, or hand the `<`
/// back (`None`) where it opens no list after all.
///
/// The caller gates this on `is_type_arguments_start(TypeArgScan::Parse)`: when `<`
/// follows an expression it could be type arguments (`f<number>`, `arr<T, U>`) or a
/// comparison (`a < b`), and that lookahead disambiguates before the list is read —
/// for the list's first argument, which is as far as it grades
/// ([`Parser::parse_type_arguments_or_rewind`]).
fn parse_instantiation_expression(
&mut self,
left: &'arena Expression<'arena>,
start: u32,
) -> Result<Option<&'arena Expression<'arena>>, Error> {
// Parse type parameter instantiation: <T, U>
let Some(type_args) = self.parse_type_arguments_or_rewind(Some((left, start)))? else {
return Ok(None);
};
let end = type_args.span.end;
Ok(Some(alloc_expr(
self.arena,
Expression {
span: Span::new(start, end),
kind: ExpressionKind::TSInstantiationExpression(TSInstantiationExpression {
expression: left,
type_arguments: type_args,
}),
},
)))
}
/// Parse the type-argument list at the current `<`, which the lookahead admitted
/// ([`Parser::is_type_arguments_start`]) — or, where the tokens behind its first
/// argument turn out to spell no list, rewind and hand the `<` back (`None`) for
/// the caller to leave to the binary loop as the comparison operator.
///
/// **Why the list is tried rather than committed.** The lookahead grades a list's
/// FIRST argument and matches delimiters behind its first `,`, so what stands past
/// that separator is a question nobody has asked: `<b, c + d>(e)`,
/// `<400, q: c>(d - e)` and `<b, hi = c>(d + 1)` all pass it, and each is the tail
/// of two comparisons in comma siblings — call arguments, array elements, object
/// properties, a declarator list, parameter defaults, enum members. tsc and
/// acorn-typescript read those as comparisons because both parse the list for real
/// and back off it (`parseTypeArgumentsInExpression` under `tryParse`,
/// `tsTryParseAndCatch`); so does this.
///
/// **What is tried is the tail alone.** The `<` and the first argument are parsed
/// committed ([`Parser::parse_type_argument_list_head`]), as is a list with no
/// separator at all: that is the part the lookahead DID grade, and several of its
/// answers are deliberate claims — regions it keeps for the type parse to reject
/// loudly, because the chain they would otherwise be has no printed form every
/// parser reads back as the input (`docs/conformance_svelte.md` §TypeScript
/// Corrections). Rewinding on any failure would hand those back as chains. An
/// error in the head therefore stays the list's own.
///
/// **Where the fallback is refused.** A tail that fails is abandoned only where the
/// operator reading is one tsv can print back: the printer rewrites some of the
/// tokens the list stopped on, and a rewrite that completes the list turns two
/// comparisons into a generic call. Those failures stay hard errors
/// ([`Parser::printed_tail_could_complete_type_arguments`]), as does a **goal
/// gate**, whose mark the format fallback reads off the error the parse ends on
/// ([`Error::is_goal_gated`]): the operator reading may fail short of the
/// `import.meta` the gate fired on, and the rewind of a speculation around this
/// one drops the error kept here.
///
/// A `<` abandoned once is remembered with the context it was read in, and asked
/// again in that context answers at once
/// (`Parser::abandoned_type_argument_lists`). Its error is kept for the case where
/// the operator reading fails as well
/// (`Parser::prefer_abandoned_type_arguments_error`).
///
/// **Where the follower refuses a whole list.** A list read whole is still no list
/// where the token after its `>` is one tsc refuses there and acorn-typescript does
/// not — a `<`, or a `+` / `-` past a line break
/// ([`type_args_follower_refused_by_tsc_alone`]): tsc reads the comparison
/// (`f<T><U>(z)` is `(f < T) > <U>(z)`, `f<T>⏎+c` is `(f < T) > +c`), and so does
/// this, where that reading parses ([`Parser::type_arguments_follower_settled`]). Where
/// it does not (`f<T><U>;`, `f<string[]><U>(x)`), tsc rejects the text, and the list
/// acorn-typescript reads is kept. Either way the text is then acorn's to read
/// throughout, so the driver reads it again with no list given up
/// (`parse_retrying_acorn_followers`): where this parse kept a list and gave another
/// up (`f<() => A><U><V>(x)` calls `f<() => A><U>` with `<V>`, never
/// `(f<() => A> < U) > <V>(x)`), and where the comparison parsed but its context then
/// refused it, failing the parse (`const a = f<T, U><V>(x)`, whose `,` ends the
/// declarator).
///
/// Only the positions with an operator reading come here — the subscript loop and
/// the `new` callee, each handing over the operand the `<` follows with where its
/// parse began (`operand`), which the comparison reading compares. A class heritage's
/// `new` callee hands over none: the heritage is a `LeftHandSideExpression`, which no
/// comparison is, so there a follower only tsc refuses leaves the list standing as
/// acorn-typescript reads it (`extends new f<T><() => U> {}`, whose second list is the
/// heritage's). Behind `?.` and in a decorator a `<` is a list or nothing, so those
/// read theirs committed.
pub(super) fn parse_type_arguments_or_rewind(
&mut self,
operand: Option<(&'arena Expression<'arena>, u32)>,
) -> Result<Option<TSTypeParameterInstantiation<'arena>>, Error> {
let lt = self.current.start;
if self.type_arguments_abandoned_at(lt) {
return Ok(None);
}
let checkpoint = self.checkpoint();
let Some(type_arguments) = self.parse_type_arguments_tried(lt, &checkpoint)? else {
return Ok(None);
};
let Some((left, start)) = operand else {
return Ok(Some(type_arguments));
};
if !self.tsc_followers
|| !type_args_follower_refused_by_tsc_alone(
self.source.as_bytes(),
self.prev_end,
self.current.start as usize,
)
|| self.type_arguments_kept_at(lt)
{
return Ok(Some(type_arguments));
}
let close_end = self.prev_end;
self.rewind(checkpoint.clone());
if self.type_arguments_follower_settled(left, start, close_end) {
self.settle_type_arguments_follower(lt, true);
self.gave_up_list_to_tsc_follower = true;
return Ok(None);
}
self.settle_type_arguments_follower(lt, false);
self.kept_list_past_tsc_follower = true;
// read the list again, which the verdict now keeps
self.parse_type_arguments_tried(lt, &checkpoint)
}
/// The list half of [`Parser::parse_type_arguments_or_rewind`]: the list at the
/// current `<` (the offset `lt`), its tail tried past the first separator and
/// rewound to `checkpoint` (taken at the `<`) where it spells none.
fn parse_type_arguments_tried(
&mut self,
lt: u32,
checkpoint: &Checkpoint<'arena>,
) -> Result<Option<TSTypeParameterInstantiation<'arena>>, Error> {
let (start, first) = self.parse_type_argument_list_head()?;
if !self.check(&TokenKind::Comma) {
// no separator: the lookahead graded everything this list holds
return self.parse_type_argument_list_tail(start, first).map(Some);
}
match self.parse_type_argument_list_tail(start, first) {
Ok(type_arguments) => Ok(Some(type_arguments)),
Err(error)
if error.is_goal_gated()
|| error.kind() == tsv_lang::ErrorKind::TooDeep
|| self.printed_tail_could_complete_type_arguments(lt) =>
{
Err(error)
}
Err(error) => {
self.rewind(checkpoint.clone());
self.abandon_type_arguments(lt, error);
Ok(None)
}
}
}
/// Whether the `<` at the current token, behind the operand `left` (whose parse
/// began at `start`), reads as tsc's comparison: the operator loop run from `left` as
/// [`Parser::parse_expression_operators`] runs it, which must parse and must consume
/// the token holding the list's closing `>` (ending at `close_end`) — so the
/// comparison has the operand after that `>` too. Speculative: the parser is put
/// back at the `<` whatever the answer.
///
/// The reading fails where tsc's parser rejects the text and acorn-typescript reads
/// a list: the operand after the `>` missing (`f<T><U>;`, `new a.b<T><U>()`,
/// `f<T><U>(...x)`), or a list that reads as no expression (`f<string[]><U>(x)`,
/// `f<void><U>(x)`, `f<A extends B ? C : D><U>(x)`, where the loop stops short of the
/// `>`). It is run at the loosest binding power, so a list holding a `,`
/// (`g(f<T, U><V>(x))`) reads as the comparison whose `,` the context then takes —
/// tsc's reading. Where the context takes none (`const a = f<T, U><V>(x)`) tsc rejects
/// the text, which this cannot see: the parse fails there instead, and the driver reads
/// the text again as acorn-typescript does (`parse_retrying_acorn_followers`).
///
/// The comparison reads the first argument as an expression, which can claim a block
/// comment glued to it ([`Checkpoint`]); a claim on a comment drained ahead of the
/// checkpoint survives the rewind, so it is put back here.
pub(super) fn type_arguments_follower_settled(
&mut self,
left: &'arena Expression<'arena>,
start: u32,
close_end: usize,
) -> bool {
let lt_pos = self.current_pos().0;
// the comments drained ahead of the checkpoint that a reading may still claim:
// the ones at or past the `<`, at the ledger's end
let unclaimed = self
.comments
.iter()
.rposition(|comment| (comment.span.start as usize) < lt_pos)
.map_or(0, |i| i + 1);
let unclaimed: Vec<usize> = (unclaimed..self.comments.len())
.filter(|&i| !self.comments[i].owned_by_node)
.collect();
let checkpoint = self.checkpoint();
let reads = self
.parse_expression_operators(BP_COMMA, start as usize, left)
.is_ok()
&& self.prev_end >= close_end;
self.rewind(checkpoint);
for i in unclaimed {
self.comments[i].owned_by_node = false;
}
reads
}
/// Whether the PRINTED form of a type-argument list's tail could spell the list
/// that its source does not — asked where the tail has just failed, with the
/// parser still standing on the token the type grammar stopped at.
///
/// Abandoning the list reads its tokens as two comparisons, and the formatter then
/// prints them. Most tokens between the `<` and the `>` print as written, so a tail
/// that is no list in the source is none in the output. The printer's rewrites are
/// the exception, and the ones refused are those that can be read off where the
/// type grammar stopped:
///
/// - **at a `=>` past another** — an arrow function's lone parameter or conditional
/// body inside an arrow function's block body: the type grammar read the earlier
/// `=>` as a function type's and the braces as a type literal, and inside a body
/// the printer's region rules do not reach, its style pairs both (`(c) => c` is a
/// function type, `return (c)` a method signature). Any `=>` byte from the `<` on
/// refuses, which over-approximates that: an expression-body arrow earlier in the
/// tail (`fn(a < b, (c) => c, d => d > (e, f))`) and a `=>` in a string or a comment
/// refuse too;
/// - **at a `.` or a `<` right behind a `)`** — a paren shell, which the printer
/// strips where it is redundant, leaving a name that takes what the parenthesized
/// type could not: `(c).d` prints as the qualified name `c.d`, and
/// `(c) < d >> (e)` as a nested list closed with the outer one. Those two tokens
/// are all a name continues with where a parenthesized type stops, so behind a
/// `)` the fallback is taken at every other (`(c & d) !== 0 && e > (f, g)`,
/// `(c)(d) > (e, f)`);
/// - **at a `[` or a `<` past a line break** — the break ends a type, and the
/// printer folds it: `c⏎[d]` prints as the indexed access `c[d]`, `c⏎<d>` as the
/// reference `c<d>` with its own argument list.
///
/// It asks where the list stopped, and never whether the rewritten tokens would
/// reach the `>` or whether the printer strips the pair at all, so it also refuses
/// tails no rewrite completes (`fn(a < b, (c | d).e > (f, g))`). That errs toward the
/// loud answer: a rejection the author can write around, against a second program
/// printed in silence.
///
/// Two rewrites the printer leaves out between the two comparisons are not read
/// here, so the lists they would complete parse as comparisons: a shell behind a
/// PREFIX operator (`fn(a < b, typeof (c) > (d, e))`, `fn(a < b, -(1) > (d, e))`,
/// which stop AT the `(`, where only the token ahead of it would tell it from a
/// call's), and the pair around an arrow function's bare lone parameter, a function
/// type's spelling (`fn(a < b, c => c > (d, e))`, which stops at its first `=>`).
/// Inside the region the printer keeps both as the author wrote them
/// (`Printer::mark_region_source_pairs`). `lt` is the list's `<`.
fn printed_tail_could_complete_type_arguments(&self, lt: u32) -> bool {
// whether the token before the one the list stopped at is a `)`
let behind_paren = || {
self.prev_end
.checked_sub(1)
.and_then(|before| self.source.as_bytes().get(before))
== Some(&b')')
};
match self.current_kind() {
TokenKind::Arrow => self
.source
.as_bytes()
.get(lt as usize..self.current.start as usize)
.is_some_and(|tail| tail.windows(2).any(|pair| pair == b"=>")),
TokenKind::BracketOpen => self.had_line_terminator,
TokenKind::LessThan | TokenKind::LeftShift => {
self.had_line_terminator || behind_paren()
}
TokenKind::Dot => behind_paren(),
_ => false,
}
}
/// Flatten a `foo<T>` `TSInstantiationExpression` operand into its inner
/// expression plus the lifted `<T>` type arguments — the inverse of
/// `parse_instantiation_expression`. When a `(` (generic call) or template
/// tag (tagged template) follows the instantiation, the `<T>` belongs to
/// that call/tag as its `typeArguments` rather than staying a standalone
/// instantiation (acorn parity). A non-instantiation operand passes through
/// unchanged with no type arguments. Shared by the subscript loop's call and
/// tagged-template arms.
fn flatten_instantiation(
&self,
expr: &'arena Expression<'arena>,
) -> (
&'arena Expression<'arena>,
Option<TSTypeParameterInstantiation<'arena>>,
) {
match expr {
Expression {
kind: ExpressionKind::TSInstantiationExpression(inst),
..
} => (inst.expression, Some(inst.type_arguments.clone())),
other => (other, None),
}
}
/// Reject a token that may not follow a TypeScript instantiation expression — a
/// `f<T>`, or a bare `new A<T>` (type arguments with no call). Asked where the
/// *current* token is the one past the list's closing `>`; a plain call (`f<T>()`) or
/// tagged template (`` f<T>`x` ``) passes. Shared by the subscript-loop and
/// `new`-expression paths. Two classes reject:
///
/// - a **property access** — a `.`, or a `?.` whose next token is not `(` (an optional
/// *call* `f<T>?.()` stays valid): acorn rejects `f<T>.x` / `f<T>?.x` / `f<T>?.[x]`
/// ("Invalid property access after an instantiation expression").
/// - a follower that makes the list's `>` a **comparison** — a `>`-led run, or a token
/// that starts an expression on the same line (`type_args_follower_refuses`). The
/// lookahead has already asked this of every head but a function type's, whose
/// `(…) =>` has no comparison reading to fall back to, so this is where
/// `f<(a: T) => U> + 1` and `f<() => U> >> c` are the syntax errors tsc and
/// acorn-typescript call them.
fn reject_instantiation_follower(&mut self) -> Result<(), Error> {
if matches!(self.current_kind(), TokenKind::Dot)
|| (matches!(self.current_kind(), TokenKind::QuestionDot)
&& !self.peek_is(&TokenKind::ParenOpen))
{
return Err(self.error_msg("Invalid property access after an instantiation expression"));
}
if type_args_follower_refuses(
self.source.as_bytes(),
self.prev_end,
self.current.start as usize,
) {
return Err(self.error_msg("Type arguments cannot be followed by this token"));
}
Ok(())
}
/// Parse unary expression: `-x`, `+x`, `!x`, `~x`
///
/// Unary operators have higher precedence than all binary operators.
/// The binding power (29) is higher than exponentiation (27-28).
fn parse_unary_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
let operator = match self.current_kind() {
TokenKind::Minus => UnaryOperator::Minus,
TokenKind::Plus => UnaryOperator::Plus,
TokenKind::Bang => UnaryOperator::Bang,
TokenKind::Tilde => UnaryOperator::Tilde,
// Private helper; the dispatcher routes only -/+/!/~ here.
#[expect(clippy::unreachable)] // caller dispatches on the same token set
_ => unreachable!("parse_unary_expression called with non-unary operator"),
};
self.advance()?;
let (operator_end, operand_token) = (self.prev_token_end(), self.current_pos().0);
// Parse the operand with high binding power (unary is right-associative)
// This allows chained unary: --x, -+x, !!x, ~~x etc.
// and proper precedence: -a * b parses as (-a) * b
// one wire level: the operand (the depth limit's count)
let parsed = self.nested(1, |p| p.parse_expression_bp(BP_UNARY))?;
// End at the operand's last consumed token to include trailing parens in the span
// (matches Svelte's behavior): `!(a && b)` spans from `!` to `)`, not just to `b`
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
// the pairs the printer adds around the operand (`-(-x)`, `!(/* c */ x)`), levels of
// the output's nesting
self.count_prefix_operand_pairs(
parsed,
ParenContext::UnaryArgument {
parent_op: operator,
},
operand_token,
Some((operator_end, end as usize)),
false,
)?;
Ok(alloc_expr(
self.arena,
Expression::from_unary_expression(UnaryExpression {
operator,
argument: parsed,
span: Span::new(start as u32, end),
}),
))
}
/// Parse unary keyword expression: `typeof x`, `void 0`, `delete obj.x`
///
/// These keyword operators have the same precedence as other unary operators.
fn parse_unary_keyword_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
let operator = match self.current_kind() {
TokenKind::Keyword(KeywordKind::Typeof) => UnaryOperator::Typeof,
TokenKind::Keyword(KeywordKind::Void) => UnaryOperator::Void,
TokenKind::Keyword(KeywordKind::Delete) => UnaryOperator::Delete,
// Private helper; the dispatcher routes only typeof/void/delete here.
#[expect(clippy::unreachable)] // caller dispatches on the same token set
_ => unreachable!("parse_unary_keyword_expression called with non-keyword operator"),
};
self.advance()?;
let (operator_end, operand_token) = (self.prev_token_end(), self.current_pos().0);
// Parse the operand with high binding power (unary is right-associative)
// one wire level: the operand (the depth limit's count)
let parsed = self.nested(1, |p| p.parse_expression_bp(BP_UNARY))?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
// the pairs the printer adds around the operand (`typeof (<T>x)`,
// `typeof (/* c */ x)`), levels of the output's nesting
self.count_prefix_operand_pairs(
parsed,
ParenContext::UnaryArgument {
parent_op: operator,
},
operand_token,
Some((operator_end, end as usize)),
false,
)?;
Ok(alloc_expr(
self.arena,
Expression::from_unary_expression(UnaryExpression {
operator,
argument: parsed,
span: Span::new(start as u32, end),
}),
))
}
/// Parse await expression: `await promise`
///
/// Await expressions have high precedence like unary operators.
fn parse_await_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
self.advance()?; // consume 'await'
let operand_token = self.current_pos().0;
// Parse the operand with high binding power (same as unary)
// one wire level: the operand (the depth limit's count)
let parsed = self.nested(1, |p| p.parse_expression_bp(BP_UNARY))?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
// the pair the printer adds around the operand (`await (<T>x)`), a level of the
// output's nesting
self.count_prefix_operand_pairs(
parsed,
ParenContext::AwaitArgument,
operand_token,
None,
false,
)?;
Ok(alloc_expr(
self.arena,
Expression {
span: Span::new(start as u32, end),
kind: ExpressionKind::AwaitExpression(AwaitExpression { argument: parsed }),
},
))
}
/// Consume the current keyword token as an ordinary `IdentifierReference`.
///
/// Word-agnostic — the name comes from `current_raw_ident_name` — and shared by
/// the two words whose reserved-ness is contextual: `await` at Script
/// `[~Await]` and `yield` at `[~Yield]`. The caller must have verified the
/// matching predicate (`await_is_identifier` / `yield_is_identifier`); reaching
/// here in a `[+Await]` / `[+Yield]` context would silently turn an operator
/// into a name. Used for a primary reference and a `new` callee (`new await()`,
/// `new yield()`).
fn parse_keyword_identifier_reference(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, end) = self.current_pos();
let name = self.current_raw_ident_name();
self.advance()?;
Ok(alloc_expr(
self.arena,
Expression::from_identifier(Identifier::simple(
name,
Span::new(start as u32, end as u32),
)),
))
}
/// [`Parser::parse_keyword_identifier_reference`] for `await` read as a name, noting
/// where a module would have read its operand: the same-line token after it, where
/// the position is `[+Await]` under `Goal::Module` (`in_await_if_module`). A Script
/// parse that then dies exactly there died because `await` is a name at this goal —
/// tsc's parser reads that same shape as an await expression in any file
/// (`isAwaitExpression`) — so `Parser::parse` marks that error a goal gate. A line
/// break after the name closes the statement by ASI, so a token past one is no
/// operand.
fn parse_await_name_reference(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let reference = self.parse_keyword_identifier_reference()?;
if self.in_await_if_module && !self.had_line_terminator {
self.await_name_operand = Some(self.current_pos().0);
}
Ok(reference)
}
/// Parse yield expression: `yield`, `yield value`, or `yield* iterable`
///
/// Yield expressions have low precedence (lowest in expressions).
/// - `yield` with no argument yields undefined
/// - `yield value` yields the given value
/// - `yield* iterable` delegates to another generator/iterable
fn parse_yield_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, yield_end) = self.current_pos();
self.advance()?; // consume 'yield'
// Check for delegate: `yield*`. The `*` binds only on `yield`'s own line —
// `YieldExpression : yield [no LineTerminator here] * AssignmentExpression`
// (ecma262 §15.5), the same restriction the argument-bearing production carries
// and which `can_insert_semicolon` below already enforces for it. Without this
// guard the two lines welded into ONE delegating yield, which no oracle endorses:
// a bare `*` cannot start a statement, so tsc (TS1109 `Expression expected`),
// acorn and prettier all reject `yield⏎* x`, while tsv silently deleted the line
// terminator and reprinted `yield* x`.
//
// A break falls through to the argument-less reading, so `yield` ends here and
// the stray `*` fails at statement level — tsc's own recovery, and the graceful
// demotion the non-delegate half already performs (`yield⏎x` is `yield;` then
// `x;`). Per ecma262 §sec-comments a block comment holding a line terminator IS
// one, so `yield /*⏎*/ * x` rejects on the same rule.
let delegate =
if matches!(self.current_kind(), TokenKind::Star) && !self.had_line_terminator {
self.advance()?; // consume '*'
true
} else {
false
};
// Check if there's an argument
// yield has very low precedence, so we need to be careful about what follows
// If the next token can start an expression and isn't a statement terminator, parse it
//
// The argument is a fresh expression frame for a parenthesized arrow's return
// type (tsc's `parseYieldExpression` passes `allowReturnTypeInArrowFunction:
// true`), so a consequent's bar does not reach `a ? yield (b): c => d : e`.
let (argument, end) = if delegate {
// yield* requires an argument
let parsed = self.nested(1, |p| {
p.with_arrow_return_type_allowed(|p| p.parse_expression_bp(BP_YIELD))
})?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
(Some(parsed), end)
} else if self.can_insert_semicolon() || matches!(self.current_kind(), TokenKind::Eof) {
// No argument - yield with no value
(None, yield_end as u32)
} else if self.is_expression_start() {
// Parse the argument
let parsed = self.nested(1, |p| {
p.with_arrow_return_type_allowed(|p| p.parse_expression_bp(BP_YIELD))
})?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
(Some(parsed), end)
} else {
// No argument
(None, yield_end as u32)
};
Ok(alloc_expr(
self.arena,
Expression {
span: Span::new(start as u32, end),
kind: ExpressionKind::YieldExpression(YieldExpression { argument, delegate }),
},
))
}
/// Check if the current token can start an expression
fn is_expression_start(&self) -> bool {
match self.current_kind() {
TokenKind::Identifier
| TokenKind::Number
| TokenKind::String
| TokenKind::BraceOpen
| TokenKind::BracketOpen
| TokenKind::ParenOpen
| TokenKind::Bang
| TokenKind::Minus
| TokenKind::Plus
| TokenKind::Tilde
| TokenKind::PlusPlus
| TokenKind::MinusMinus
| TokenKind::NoSubstitutionTemplate
| TokenKind::TemplateHead
| TokenKind::RegexLiteral
// `/` / `/=` after `yield` is a regex-literal argument, not division:
// the lexer emits `Slash`/`SlashEquals` by default (the parser re-lexes
// it as a regex only in primary position), and a bare `yield` can't be
// the left operand of division without parens, so `yield /a/g` is
// `yield (/a/g)` (matching acorn). The primary parser resyncs the regex.
| TokenKind::Slash
| TokenKind::SlashEquals
| TokenKind::LessThan
| TokenKind::Hash => true,
// Most keywords can start expressions (as primaries, unary ops, or contextual
// identifiers); the statement, clause and binary-operator keywords cannot. The set
// is shared with the type-argument follower lookahead.
TokenKind::Keyword(kw) => kw.starts_expression(),
_ => false,
}
}
/// Parse prefix update expression: `++x`, `--x`
///
/// Prefix increment/decrement has the same precedence as unary operators.
fn parse_prefix_update_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
let operator = match self.current_kind() {
TokenKind::PlusPlus => UpdateOperator::Increment,
TokenKind::MinusMinus => UpdateOperator::Decrement,
// Private helper; the dispatcher routes only ++/-- here.
#[expect(clippy::unreachable)] // caller dispatches on the same token set
_ => unreachable!("parse_prefix_update_expression called with non-update operator"),
};
self.advance()?;
let operand_token = self.current_pos().0;
// Parse the operand - update expressions apply to member expressions or identifiers
// Use high binding power so ++x.y parses correctly
// one wire level: the operand (the depth limit's count)
let parsed = self.nested(1, |p| p.parse_expression_bp(BP_UNARY))?;
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, parsed, parsed);
// the pair the printer adds around the operand (`++(-x)`), a level of the output's
// nesting
self.count_prefix_operand_pairs(
parsed,
ParenContext::UpdateArgument { postfix: false },
operand_token,
None,
false,
)?;
Ok(alloc_expr(
self.arena,
Expression {
span: Span::new(start as u32, end),
kind: ExpressionKind::UpdateExpression(UpdateExpression {
operator,
argument: parsed,
prefix: true,
}),
},
))
}
/// Parse new expression: `new Date()`, `new Map()`, `new Foo.Bar()`
/// Also handles `new.target` meta property.
///
/// The `new` keyword has the same precedence as unary operators.
/// It takes a callee (identifier or member expression) and optional arguments.
fn parse_new_expression(&mut self) -> Result<&'arena Expression<'arena>, Error> {
self.parse_new_expression_in(false)
}
/// The callee of a `new` with its member chain ([`Parser::parse_new_expression_in`]),
/// up to the argument list: the callee and the `new`'s own type argument list, if the
/// chain ended on one.
fn parse_new_callee_chain(
&mut self,
heritage: bool,
is_async_function: bool,
callee_start: u32,
) -> Result<
(
&'arena Expression<'arena>,
Option<TSTypeParameterInstantiation<'arena>>,
),
Error,
> {
let arena = self.arena;
let callee_parsed = self.parse_new_callee(is_async_function)?;
// A bare arrow is an `AssignmentExpression`, never the `MemberExpression` a `new`
// callee is: `new () => a` is a syntax error where `new (() => a)` constructs.
if is_bare_assignment_head(callee_parsed, callee_start as usize, false) {
return Err(Error::invalid_syntax(
"An arrow function cannot be a `new` callee without parentheses".to_string(),
callee_start as usize,
));
}
// Parse member access chains: new Foo.Bar.Baz()
let mut callee = callee_parsed;
// `<T>` in the callee chain belongs to a trailing tagged template
// (`new Foo<T>`x``, part of the callee) when a template follows — consumed
// in the loop — otherwise it is the `new`'s own (`new Foo<T>()`) and this
// holds it for the argument parse below.
let mut type_arguments: Option<TSTypeParameterInstantiation<'arena>> = None;
loop {
match self.current_kind() {
TokenKind::Dot => {
let units = self.member_link_units(callee);
self.spine_link(units)?;
self.advance()?; // consume '.'
// The same seam the ordinary `.` / `?.` chains use, so a `new`
// callee takes every property name they do — keywords
// (`new Foo.class()`) and PRIVATE names (`new this.#f()`),
// which only `parse_dot_property` knows about.
let (property, prop_end) = self.parse_dot_property()?;
let span = Span::new(callee_start, prop_end as u32);
callee = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: callee,
property: arena.alloc(property),
computed: false,
optional: false,
}),
},
);
}
TokenKind::BracketOpen => {
let units = self.member_link_units(callee);
self.spine_link(units)?;
self.advance()?; // consume '['
self.enter_grouping()?;
let index = self.parse_expression_ref()?;
let (_, bracket_end) = self.current_pos();
self.expect(&TokenKind::BracketClose)?;
self.exit_grouping();
let span = Span::new(callee_start, bracket_end as u32);
callee = alloc_expr(
self.arena,
Expression {
span,
kind: ExpressionKind::MemberExpression(MemberExpression {
object: callee,
property: index,
computed: true,
optional: false,
}),
},
);
}
TokenKind::QuestionDot => {
// An optional chain can't be a `new` callee (per spec): `new a?.b()`
// is a syntax error. A parenthesized chain (`new (a?.b)()`) seals it
// and is valid — its `?.` is consumed inside the primary, never here.
return Err(self.error_msg(
"Optional chaining cannot appear in the callee of new expressions",
));
}
TokenKind::Bang if !self.had_line_terminator => {
// Non-null assertion on the callee: `new (a?.b)!()`. The trailing `(`
// then binds as the `new` argument list, not a call on the callee.
let units = self.non_null_link_units(callee);
self.spine_link(units)?;
callee = self.wrap_non_null_assertion(callee, callee_start)?;
}
TokenKind::NoSubstitutionTemplate | TokenKind::TemplateHead => {
// A tagged template extends the callee itself: `new Foo`x`` is
// `new (Foo`x`)()`, not `(new Foo())`x``. Per the grammar, a
// `new` callee is an ordinary MemberExpression, whose production
// includes `MemberExpression TemplateLiteral` — so a trailing tag
// before any explicit `(...)` binds to the callee, not the `new`.
self.spine_link(LINK_TAG)?;
callee = self.attach_new_callee_tag(callee, callee_start, None)?;
}
// `<T>` here is either the tag's type arguments (`new Foo<T>`x``,
// where they flatten onto a TaggedTemplateExpression callee — acorn
// parity) or the `new`'s own (`new Foo<T>()`). A following template
// disambiguates: it consumes them into the tag and the callee chain
// continues (`new Foo<T>`x`.bar`); otherwise they are the `new`'s and
// the chain ends here.
_ if self.check_less_than_in_type()
&& self.is_type_arguments_start(TypeArgScan::Parse) =>
{
// A tail that is no list leaves the `<` to compare the
// argument-less `new` with what follows (`new A < b`).
let operand = (!heritage).then_some((callee, callee_start));
let Some(ta) = self.parse_type_arguments_or_rewind(operand)? else {
break;
};
// a tag's weight: the list may go on to one
self.spine_link(LINK_TAG)?;
// the pair the printer keeps around an instantiation that takes a
// second list (`new (a.b<T>)<U>()`), a level of the output's nesting
if Self::is_bare_instantiation(callee, callee_start) {
self.printer_pair()?;
}
if matches!(
self.current_kind(),
TokenKind::NoSubstitutionTemplate | TokenKind::TemplateHead
) {
callee = self.attach_new_callee_tag(callee, callee_start, Some(ta))?;
} else if self.new_callee_continues_past_type_args() {
// The list stays on the callee as an instantiation and the chain
// goes on: a second list tsc's comparison could not take
// (`new a.b<T><U>()` constructs `a.b<T>` with `<U>`,
// acorn-typescript's tree) or a member past a line break
// (`new f<T>⏎[x](y)` constructs `f<T>[x]`, tsc's and acorn's).
callee = alloc_expr(
arena,
Expression {
span: Span::new(callee_start, ta.span.end),
kind: ExpressionKind::TSInstantiationExpression(
TSInstantiationExpression {
expression: callee,
type_arguments: ta,
},
),
},
);
} else {
type_arguments = Some(ta);
break;
}
}
_ => break,
}
}
Ok((callee, type_arguments))
}
/// The callee of a `new` ([`Parser::parse_new_expression_in`]) up to its member chain:
/// an `async function` (`is_async_function`, asked by the caller), another `new`, a
/// function or class expression, `import.meta`, or a primary.
fn parse_new_callee(
&mut self,
is_async_function: bool,
) -> Result<&'arena Expression<'arena>, Error> {
if is_async_function {
// Async function expression: `new async function() {}`
let (start, _) = self.current_pos();
self.advance()?; // consume 'async'
return self.parse_async_function_expression(start);
}
match self.current_kind() {
TokenKind::Keyword(KeywordKind::New) => self.parse_new_expression(),
// Function expression: `new function() {}`
TokenKind::Keyword(KeywordKind::Function) => self.parse_function_expression(),
// Class expression: `new class {}`
TokenKind::Keyword(KeywordKind::Class) => self.parse_class_expression(),
TokenKind::Keyword(KeywordKind::Import) => {
// `new import.meta()` — `import.meta` is a MetaProperty (a
// MemberExpression), a valid `new` callee. `new import(...)`
// is not: an `import(...)` ImportCall is a CallExpression, not
// a MemberExpression — acorn agrees ("Cannot use new with
// import()").
let (import_start, _) = self.current_pos();
let parsed = self.parse_import_or_meta_property()?;
if matches!(parsed.kind, ExpressionKind::ImportExpression(_)) {
return Err(self.error_msg_at("Cannot use new with import()", import_start));
}
Ok(parsed)
}
// We use primary + postfix parsing but stop before call expressions
_ => self.parse_primary_expression(),
}
}
/// [`Parser::parse_new_expression`], told whether the `new` is a class heritage's
/// superclass (`heritage`), where its callee's type-argument lists have no comparison
/// reading to fall back to ([`Parser::parse_type_arguments_or_rewind`]).
fn parse_new_expression_in(
&mut self,
heritage: bool,
) -> Result<&'arena Expression<'arena>, Error> {
let arena = self.arena;
let (start, new_end) = self.current_pos();
self.advance()?; // consume 'new'
// Check for new.target meta property
if *self.current_kind() == TokenKind::Dot {
self.advance()?; // consume '.'
if *self.current_kind() == TokenKind::Identifier && self.current_value() == "target" {
let (prop_start, prop_end) = self.current_pos();
self.advance()?; // consume 'target'
// Both tokens are already consumed; their spans cover exactly
// `new` / `target`, so the names are the verbatim spans.
let meta_span = Span::new(start as u32, new_end as u32);
let prop_span = Span::new(prop_start as u32, prop_end as u32);
return Ok(alloc_expr(
arena,
Expression {
span: Span::new(start as u32, prop_end as u32),
kind: ExpressionKind::MetaProperty(arena.alloc(MetaProperty {
meta: Identifier::simple(IdentName::from_span(meta_span), meta_span),
property: Identifier::simple(
IdentName::from_span(prop_span),
prop_span,
),
})),
},
));
}
return Err(self.error_expected_after("'target'", "new."));
}
// Parse the callee - identifier, member expr, function/class expression, or nested `new`
// Check async function first (peek borrows self, can't be inside match)
let is_async_function = self.at_async_function_expression();
// where the callee's parse begins — a parenthesized callee's `(` (`new (a()).b`),
// which every member the chain below wraps it in starts at
let callee_start = self.current_pos().0 as u32;
// one wire level: the callee with its member chain (the depth limit's count,
// `Parser::nested`) — a `new` callee may be another `new` (`new new A()()`), a
// recursion that does not pass `parse_expression_bp`. The argument list below counts
// its own, as a grouping.
let (callee, type_arguments) = self.nested(1, |p| {
p.parse_new_callee_chain(heritage, is_async_function, callee_start)
})?;
// Parse optional arguments: new Date() vs new Date. `new`'s argument list is an
// `Arguments` grouping delimiter, so it shares `parse_call_arguments` (which
// bumps `grouping_depth`) — `in` is a binary operator inside the arguments even
// in a for-header init, matching call arguments (ecma262 `ArgumentList[+In]`).
let (arguments, end): (&'arena [&'arena Expression<'arena>], u32) =
if self.eat(TokenKind::ParenOpen)? {
let (args, paren_end) = self.parse_call_arguments()?;
(args.into_bump_slice(), paren_end as u32)
} else {
// new Date without parens - valid JS; bare instantiation type args
// (`new A<T>`) extend the span past the callee. A bare `new A<T>`
// (type args, no call arguments) is instantiation-style: like `f<T>`
// it can't be followed by a property access (`new A<T>.x` rejects);
// `new A<T>()` took the `(` branch above, so its later `.prop` is an
// ordinary member access.
if type_arguments.is_some() {
// An argument-less `new` cannot head an optional call, and the list
// cannot extend its callee into one (tsc TS1209): no argument list is
// inferred ahead of the `?.` for the chain to start from. A `?.` that
// opens a property access is refused below, as after any list.
if matches!(self.current_kind(), TokenKind::QuestionDot)
&& self.peek_is(&TokenKind::ParenOpen)
{
return Err(self.error_msg(
"Optional chaining cannot appear in the callee of new expressions",
));
}
self.reject_instantiation_follower()?;
}
let end = type_arguments
.as_ref()
.map_or_else(|| self.prev_token_end() as u32, |ta| ta.span.end);
// the argument list the printer writes (`new A()`), a grouping delimiter
// and so a level of the output's nesting
self.printer_pair()?;
(&[], end)
};
// the pair the printer adds around a bare callee it parenthesizes (`new (class {})()`),
// a level of the output's nesting
if callee.span().start == callee_start {
self.count_operand_pairs(Some((callee, ParenContext::NewCallee)), None)?;
}
Ok(alloc_expr(
arena,
Expression {
span: Span::new(start as u32, end),
kind: ExpressionKind::NewExpression(NewExpression {
callee,
type_arguments,
arguments,
}),
},
))
}
/// Whether a `new` callee's type argument list, just parsed and followed by no
/// template, stays on the callee as an instantiation with the callee chain going on,
/// rather than ending the callee as the `new`'s own list (`new f<T>()`).
///
/// acorn-typescript parses the callee with its subscripts first and hands the list to
/// the `new` only when it is the callee's LAST subscript; two followers keep the chain
/// going:
///
/// - **a second type argument list** — `new a.b<T><U>()` is `new (a.b<T>)<U>()`, the
/// second list the `new`'s. It stands only where tsc's comparison does not parse:
/// tsc takes no list ahead of a `<`, and where its comparison parses
/// (`new f<T><U>(x)` is `(new f < T) > <U>(x)`) the first list was abandoned to it
/// already ([`Parser::parse_type_arguments_or_rewind`]). The printer adds the pair
/// both parsers read alike.
/// - **a `[` past a line break** — `new f<T>⏎[x](y)` constructs the member `f<T>[x]`,
/// to tsc as to acorn: the break commits the list, and the member is the callee's.
/// On the list's own line the `[` refuses it, which the lookahead that admitted the
/// list has already decided.
///
/// A second list whose own follower refuses it stays unparsed (`extends new f<T><U> {}`,
/// where acorn-typescript reads `<U>` as the heritage's list): acorn tries the list,
/// finds the token after it starting an expression, and leaves the `new` at the first.
/// The lookahead has asked that of every head already but a function type's
/// (`<() => U> {`), so it is asked here.
fn new_callee_continues_past_type_args(&self) -> bool {
match self.current_kind() {
TokenKind::BracketOpen => self.had_line_terminator,
_ => {
self.check_less_than_in_type()
&& self.is_type_arguments_start(TypeArgScan::Parse)
&& {
let bytes = self.source.as_bytes();
let lt = self.current.start as usize;
matching_angle_close(bytes, lt + 1, TypeArgScan::Parse).is_none_or(
|close| {
let after = skip_whitespace_and_comments(bytes, close + 1);
!type_args_follower_refuses(bytes, close + 1, after)
},
)
}
}
}
}
/// Extend a `new` callee with the tagged template at the current token,
/// carrying the tag's `<T>` in `type_arguments` when present (`new Foo<T>`x``).
/// The `new`-callee member loop's two tag sites — with and without a preceding
/// instantiation — share this. Returns `tag` unchanged if the parsed quasi is
/// not a `TemplateLiteral` (unreachable: `parse_template_literal` yields only
/// that).
fn attach_new_callee_tag(
&mut self,
tag: &'arena Expression<'arena>,
tag_start: u32,
type_arguments: Option<TSTypeParameterInstantiation<'arena>>,
) -> Result<&'arena Expression<'arena>, Error> {
// one wire level: the quasi's `TemplateLiteral` under its tag node
let template = self.nested(1, |p| p.parse_template_literal(true))?;
Ok(self.build_tagged_template(tag, tag_start, type_arguments, template))
}
/// Build a `TaggedTemplateExpression` from an already-parsed tag, its optional
/// `<T>` type arguments, and the parsed quasi. Shared by `attach_new_callee_tag`
/// (the `new`-callee sites) and the ordinary postfix tagged-template arm so the
/// node's span math — `tag_start..quasi.span.end` — lives in one place. `tag` is
/// the resolved tag expression and `tag_start` its paren-inclusive start (where
/// the tag's parse began); the postfix arm flattens a `tag<T>`
/// `TSInstantiationExpression` off the tag first (via `flatten_instantiation`),
/// lifting `<T>` into `type_arguments`.
fn build_tagged_template(
&self,
tag: &'arena Expression<'arena>,
tag_start: u32,
type_arguments: Option<TSTypeParameterInstantiation<'arena>>,
quasi: TemplateLiteral<'arena>,
) -> &'arena Expression<'arena> {
let end = quasi.span.end;
alloc_expr(
self.arena,
Expression {
span: Span::new(tag_start, end),
kind: ExpressionKind::TaggedTemplateExpression(self.arena.alloc(
TaggedTemplateExpression {
tag,
type_arguments,
quasi,
},
)),
},
)
}
/// Reject a spread element where an `ImportCall` argument (an
/// `AssignmentExpression`) is expected — `import(...x)` / `import.source(...x)`
/// are syntax errors (acorn agrees). An `import(...)` argument is a bare
/// `AssignmentExpression`, not an `ArgumentList`, so a leading `...` is invalid;
/// this guard reports it precisely (guarding both argument positions) rather than
/// letting it fall through to the generic primary-expression error.
fn reject_import_call_spread(&self) -> Result<(), Error> {
if matches!(self.current_kind(), TokenKind::DotDotDot) {
return Err(self.error_msg("Cannot use spread element in import() argument"));
}
Ok(())
}
/// Parse import expression or import.meta meta property
///
/// Handles:
/// - `import('module')` - dynamic import expression
/// - `import.source('module')` / `import.defer('module')` - phased dynamic
/// import (the source-phase-imports / import-defer proposals)
/// - `import.meta` - meta property
fn parse_import_or_meta_property(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, import_end) = self.current_pos();
self.advance()?; // consume 'import'
// Check for `import.meta` / `import.source(…)` / `import.defer(…)`.
let mut phase = ImportPhase::None;
if *self.current_kind() == TokenKind::Dot {
self.advance()?; // consume '.'
if *self.current_kind() == TokenKind::Identifier && self.current_value() == "meta" {
// `import.meta` is a Module-goal-only construct (early error:
// "Syntax Error if the syntactic goal symbol is not Module").
if self.goal != crate::Goal::Module {
return Err(self.error_goal_gate("'import.meta' is only allowed in a module"));
}
let (prop_start, prop_end) = self.current_pos();
self.advance()?; // consume 'meta'
// Both tokens are already consumed; their spans cover exactly
// `import` / `meta`, so the names are the verbatim spans.
let meta_span = Span::new(start as u32, import_end as u32);
let prop_span = Span::new(prop_start as u32, prop_end as u32);
return Ok(alloc_expr(
self.arena,
Expression {
span: Span::new(start as u32, prop_end as u32),
kind: ExpressionKind::MetaProperty(self.arena.alloc(MetaProperty {
meta: Identifier::simple(IdentName::from_span(meta_span), meta_span),
property: Identifier::simple(
IdentName::from_span(prop_span),
prop_span,
),
})),
},
));
}
// `import.source(…)` / `import.defer(…)` — the import-phase proposals.
// The phase keyword must be immediately followed by the `(` call: a bare
// `import.source` or a member access `import.source.x` is a syntax error
// (enforced by the `ParenOpen` expect below).
if *self.current_kind() == TokenKind::Identifier {
match self.current_value() {
"source" => phase = ImportPhase::Source,
"defer" => phase = ImportPhase::Defer,
_ => return Err(self.error_expected_after("'meta'", "import.")),
}
self.advance()?; // consume 'source' / 'defer'
} else {
return Err(self.error_expected_after("'meta'", "import."));
}
}
// Dynamic import: import('module') or import('module', options), possibly
// phased as import.source(...) / import.defer(...).
self.expect(&TokenKind::ParenOpen)?;
// The argument list is a grouping delimiter — `in` is always the binary
// operator inside it, even within a for-header init (the args are
// `AssignmentExpression[+In]`). Mirrors `parse_call_arguments`.
self.enter_grouping()?;
self.reject_import_call_spread()?;
// Parse the source expression (usually a string literal)
let source = self.parse_assignment_expression_ref()?;
// The `ImportCall` grammar allows an optional trailing comma after the
// source (1-arg form) and after the options (2-arg form):
// import ( AssignmentExpression ,opt )
// import ( AssignmentExpression , AssignmentExpression ,opt )
// A bare trailing comma after the source leaves no options arg; a comma
// followed by an expression is the options arg. 3+ args are not in the
// grammar and still error at the `)` below — a deliberate divergence
// from acorn-typescript, which accepts 3+ args and rejects the trailing
// comma. See docs/conformance_svelte.md.
let mut options: Option<&'arena Expression<'arena>> = None;
if self.eat(TokenKind::Comma)? && !self.check(&TokenKind::ParenClose) {
self.reject_import_call_spread()?; // the options arg is likewise no spread
options = Some(self.parse_assignment_expression_ref()?);
self.eat(TokenKind::Comma)?; // optional trailing comma after the options
}
// Capture end position before consuming ')'
let (_, paren_end) = self.current_pos();
self.expect(&TokenKind::ParenClose)?;
self.exit_grouping();
Ok(alloc_expr(
self.arena,
Expression {
span: Span::new(start as u32, paren_end as u32),
kind: ExpressionKind::ImportExpression(ImportExpression {
source,
options,
phase,
}),
},
))
}
/// Parse a block statement: `{ stmt1; stmt2; }`
///
/// Parse a function/arrow block body, marking its directive prologue.
///
/// Function bodies (unlike arbitrary blocks) carry a directive prologue per
/// acorn — see `note_directive` — so this is also a strictness scope: a
/// `"use strict"` at the head makes the body and everything nested in it strict,
/// and the mode is restored for the code that follows. The parameters were
/// parsed by the caller under the *outer* mode, which is correct — acorn does
/// the same, and the rule against a directive in a non-simple-parameter function
/// is a deferred early error.
pub(super) fn parse_function_body(&mut self) -> Result<BlockStatement<'arena>, Error> {
// two wire levels: the body's `BlockStatement` and its statements
self.parse_function_body_levels(2)
}
/// [`Parser::parse_function_body`], its statements `levels` wire levels deep (the
/// depth limit's count, entered once for the body: [`Parser::statement_list`]) — two
/// for a body, three for an arrow function's, whose own level comes with it.
pub(super) fn parse_function_body_levels(
&mut self,
levels: u32,
) -> Result<BlockStatement<'arena>, Error> {
self.with_strict_scope(|p| {
let (body, span) = p.parse_block_body(DirectivePrologue::Present, levels)?;
Ok(BlockStatement {
body: body.into_bump_slice(),
span,
})
})
}
/// A block that is a wire level of its own below the statement holding it — a `try`'s
/// block, a `catch` or `finally` clause's ([`Parser::nested`]). A block STATEMENT is
/// counted as the statement it is ([`Parser::parse_bare_block_statement`]).
pub(super) fn parse_block_statement(&mut self) -> Result<BlockStatement<'arena>, Error> {
self.nested(1, Self::parse_bare_block_statement)
}
/// A `{ … }` block, with no depth level of its own: a block statement, whose level
/// is the statement's.
pub(super) fn parse_bare_block_statement(&mut self) -> Result<BlockStatement<'arena>, Error> {
let (body, span) = self.parse_block_body(DirectivePrologue::Absent, 1)?;
Ok(BlockStatement {
body: body.into_bump_slice(),
span,
})
}
/// Parse a `{ … }` block's statements into an arena buffer plus the block's
/// span. Shared by `parse_block_statement` and `parse_function_body`;
/// `prologue` is what tells the two apart — only a function body carries a
/// directive prologue, so a `"use strict"` heading a plain nested block is an
/// ordinary expression statement that turns nothing on.
fn parse_block_body(
&mut self,
prologue: DirectivePrologue,
levels: u32,
) -> Result<(bumpalo::collections::Vec<'arena, Statement<'arena>>, Span), Error> {
let (start, _) = self.current_pos();
self.expect(&TokenKind::BraceOpen)?; // consume '{'
// Parse statements until we hit '}', `levels` wire levels deep
let mut body = self.bvec();
self.statement_list(levels, |p, frame| {
let mut in_prologue = prologue == DirectivePrologue::Present;
while !p.check(&TokenKind::BraceClose) {
if p.check(&TokenKind::Eof) {
return Err(p.error_msg("Unexpected end of input in block"));
}
let mut stmt = p.parse_statement()?;
frame.next(p);
if in_prologue {
in_prologue = p.note_directive(&mut stmt, &body)?;
}
body.push(stmt);
}
Ok(())
})?;
let (_, end) = self.current_pos();
self.expect(&TokenKind::BraceClose)?; // consume '}'
Ok((body, Span::new(start as u32, end as u32)))
}
/// Parse an array-element / argument that permits a leading spread
/// (`...AssignmentExpression`) — the array-literal, call-argument, and
/// new-argument positions where a `SpreadElement` is grammatical (ecma262
/// `ElementList` / `ArgumentList`). Everywhere else a bare `...` is a syntax
/// error: `parse_primary_expression` does not accept it, so spread stays
/// confined to exactly these list contexts (object literals and parameter
/// lists build their own spread/rest nodes inline).
pub(super) fn parse_spread_or_assignment_element(
&mut self,
) -> Result<&'arena Expression<'arena>, Error> {
if matches!(self.current_kind(), TokenKind::DotDotDot) {
self.parse_spread_element()
} else {
self.parse_assignment_expression_ref()
}
}
/// Parse spread element: `...expr`
fn parse_spread_element(&mut self) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
self.expect(&TokenKind::DotDotDot)?; // consume '...'
let operand_token = self.current_pos().0;
// Use assignment_expression because comma separates array elements/object properties;
// one wire level: the `SpreadElement` over its argument (the depth limit's count)
let argument = self.nested(1, Self::parse_assignment_expression_ref)?;
// Use prev_token_end() to include closing paren when argument is parenthesized
let end = self.prev_token_end() as u32;
debug_assert_encloses(start as u32, end, argument, argument);
// the pair the printer adds around the argument (`...(a || b)`), a level of the
// output's nesting
self.count_prefix_operand_pairs(
argument,
ParenContext::SpreadArgument,
operand_token,
None,
false,
)?;
Ok(self
.arena
.alloc(Expression::from_spread_element(SpreadElement {
argument,
span: Span::new(start as u32, end),
})))
}
}