node-js 0.1.16

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

use crate::ast::*;
use crate::lexer::{lex, Legacy, Tok, Token};

const KEYWORDS: &[&str] = &[
    "var",
    "let",
    "const",
    "function",
    "return",
    "if",
    "else",
    "while",
    "do",
    "for",
    "in",
    "switch",
    "case",
    "default",
    "break",
    "continue",
    "true",
    "false",
    "null",
    "this",
    "new",
    "typeof",
    "void",
    "delete",
    "instanceof",
    "throw",
    "try",
    "catch",
    "finally",
];

fn is_keyword(s: &str) -> bool {
    KEYWORDS.contains(&s)
}

/// The private names one class body declares and the ones its code refers to.
#[derive(Default)]
struct PrivateScope {
    declared: Vec<String>,
    used: Vec<String>,
}

/// The names a binding pattern introduces.
fn pattern_idents(e: &Expr, out: &mut Vec<String>) {
    match e {
        Expr::Ident(n) => out.push(n.clone()),
        Expr::Array(items) => items.iter().for_each(|i| pattern_idents(i, out)),
        Expr::Spread(inner) => pattern_idents(inner, out),
        Expr::Assign { target, .. } => pattern_idents(target, out),
        Expr::Object(props) => {
            for pr in props {
                match pr {
                    Prop::KeyValue { value, .. } => pattern_idents(value, out),
                    Prop::Spread(inner) => pattern_idents(inner, out),
                    _ => {}
                }
            }
        }
        _ => {}
    }
}

/// 15.4.1: a getter takes no parameters and a setter exactly one, which is not
/// a rest parameter.
fn check_accessor_arity(kind: MemberKind, params: &[Param]) -> Result<(), String> {
    match kind {
        MemberKind::Get if !params.is_empty() => {
            Err("SyntaxError: Getter must not have any formal parameters.".to_string())
        }
        MemberKind::Set if params.len() != 1 => {
            Err("SyntaxError: Setter must have exactly one formal parameter.".to_string())
        }
        MemberKind::Set if params[0].rest => {
            Err("SyntaxError: Setter function argument must not be a rest parameter".to_string())
        }
        _ => Ok(()),
    }
}

fn private_not_declared(name: &str) -> String {
    format!("SyntaxError: Private field '{name}' must be declared in an enclosing class")
}

struct Parser {
    toks: Vec<Token>,
    pos: usize,
    /// True while parsing a generator body — enables `yield` as an operator.
    in_generator: bool,
    /// True while parsing an async body — enables `await` as an operator.
    in_async: bool,
    /// True while parsing a `for` init in LHS position — suppresses `in` as a
    /// relational operator so `for (x in obj)` (no declaration keyword) parses
    /// the `in` as the loop separator, not a binary expression. Cleared inside
    /// any parenthesised/bracketed sub-expression, where `in` is legal again.
    no_in: bool,
    /// One frame per enclosing class body, each holding the private names that
    /// body DECLARES and the ones its code USES. A private name is only in
    /// scope inside a class that declares it, so an undeclared use is an EARLY
    /// error (`SyntaxError`) rather than a runtime `TypeError` if the read ever
    /// happens — a typo in a dead branch used to ship silently.
    class_scopes: Vec<PrivateScope>,
    /// Whether token offsets point into the script text, so a function's
    /// [`Span`] can be recorded. Off for a re-parsed template field.
    spans: bool,
    /// The labels of the statements enclosing the current one, innermost last,
    /// reset at each function boundary: a label may not be declared twice in
    /// one nest (14.13.1).
    labels: Vec<String>,
    /// Whether the code being parsed is strict (a `'use strict'` directive
    /// prologue, or a class body). Decides the early errors that only strict
    /// code has: legacy octal forms, `let`/`yield`/… as names, a function
    /// declaration as an `if`/loop body.
    strict: bool,
    /// Whether `super` may appear here: a method, an accessor, a class field
    /// initialiser or a static block, and an arrow inside one. An `eval`'s
    /// source starts out true, since it may be running inside a method.
    super_ok: bool,
    /// Whether a `return` is legal here: inside a function body, or at the top
    /// of a file (which Node wraps in one). An `eval`'s top level is not.
    in_function: bool,
    /// The `{ a = 1 }` shorthand initialisers seen in an expression: the `=`
    /// token and the source span of `a = 1`. They are legal only if the object turns out to be a pattern
    /// (an assignment target, a `for` head); anything left when the statement
    /// ends is the `Invalid shorthand property initializer` early error.
    cover_init: Vec<(usize, Pos, Pos)>,
    /// Set while parsing a binding pattern, where `{ a = 1 }` is simply a
    /// default and never a cover grammar. Cleared again inside a default
    /// value or a computed key, which are expressions.
    in_binding: bool,
    /// The names a binding pattern being parsed binds, with where each is
    /// written; drained by [`Parser::parse_binding_target_at`].
    bound_at: Vec<(String, Pos)>,
    /// Whether the source is parsed with the Module goal (16.2): strict,
    /// top-level `await`, `import`/`export` declarations and `import.meta`.
    module: bool,
}

/// Parse a complete JS program into a statement list. Inline `rust { ... }` FFI
/// blocks are desugared to `__rust_compile(...)` calls before lexing.
pub fn parse(src: &str) -> Result<Vec<Stmt>, String> {
    parse_source(src, false, false, false)
}

/// Parse the source text of an `eval` / `vm` script. Identical to [`parse`]
/// except that `super` is accepted at the top level when `allow_super` says the
/// code runs inside a method (a direct `eval` there may use it).
pub fn parse_eval(src: &str, allow_super: bool, caller_strict: bool) -> Result<Vec<Stmt>, String> {
    parse_source(src, allow_super, true, caller_strict)
}

fn parse_source(
    src: &str,
    allow_super: bool,
    in_eval: bool,
    caller_strict: bool,
) -> Result<Vec<Stmt>, String> {
    note_error_span(0, 0);
    let desugared = crate::rust_ffi::desugar(src);
    // A `rust { … }` block is rewritten before lexing, so offsets would point
    // into text the caller never sees; record spans only when nothing moved.
    let spans = desugared == src;
    let toks = lex_noting(&desugared, spans)?;
    let mut p = Parser {
        toks,
        pos: 0,
        in_generator: false,
        in_async: false,
        no_in: false,
        class_scopes: Vec::new(),
        labels: Vec::new(),
        strict: false,
        super_ok: allow_super,
        in_function: !in_eval,
        cover_init: Vec::new(),
        in_binding: false,
        bound_at: Vec::new(),
        spans,
        module: false,
    };
    p.strict = caller_strict || p.leading_use_strict(0);
    let mut out = Vec::new();
    while !p.at_eof() {
        out.push(p.note_error_pos(Parser::parse_stmt)?);
    }
    Ok(out)
}

thread_local! {
    /// Where the last parse that failed stopped — see [`take_error_pos`].
    static ERROR_POS: std::cell::Cell<Pos> = const { std::cell::Cell::new(0) };
    /// The end of the span it underlines — see [`take_error_end`].
    static ERROR_END: std::cell::Cell<Pos> = const { std::cell::Cell::new(0) };
}

/// The [`Pos`] of the token the last failed [`parse`] / [`parse_module`]
/// stopped at (`0`: none, or none since the last call), which is where V8 puts
/// a SyntaxError's caret.
pub fn take_error_pos() -> Pos {
    ERROR_POS.with(|p| p.replace(0))
}

/// One past the last character V8 underlines for that SyntaxError — the end
/// of the offending token (`0`: underline the one character at the position).
/// Taken by `host::note_syntax_error` alongside [`take_error_pos`].
pub fn take_error_end() -> Pos {
    ERROR_END.with(|p| p.replace(0))
}

/// Record a SyntaxError found after parsing — an early error such as a
/// redeclaration — at the source span `[pos, end)`, for [`take_error_pos`].
pub fn note_error_span(pos: Pos, end: Pos) {
    ERROR_POS.with(|p| p.set(pos));
    ERROR_END.with(|p| p.set(end));
}

/// [`lex`], recording the span of the token an error stopped in when `spans`
/// says positions refer to the caller's text.
fn lex_noting(src: &str, spans: bool) -> Result<Vec<Token>, String> {
    lex(src).inspect_err(|_| {
        let (start, end) = crate::lexer::take_error_span();
        if spans {
            note_error_span(start + 1, end + 1);
        }
    })
}

/// Parse `src` with the Module goal (ECMA-262 16.2.1): the code is strict,
/// `await` is an operator at the top level, `return` there is an error, and the
/// top level may hold `import`/`export` declarations. A hashbang line is a
/// comment only at the very start of the text.
pub fn parse_module(src: &str) -> Result<Vec<Stmt>, String> {
    note_error_span(0, 0);
    let toks = lex_noting(src, true)?;
    let mut p = Parser {
        toks,
        pos: 0,
        in_generator: false,
        in_async: true,
        no_in: false,
        class_scopes: Vec::new(),
        labels: Vec::new(),
        strict: true,
        super_ok: false,
        in_function: false,
        cover_init: Vec::new(),
        in_binding: false,
        bound_at: Vec::new(),
        spans: true,
        module: true,
    };
    let mut out = Vec::new();
    while !p.at_eof() {
        let line = p.line();
        let item = if p.is_kw("export") {
            p.parse_export()?
        } else if p.is_kw("import")
            && !matches!(
                p.toks.get(p.pos + 1).map(|t| &t.tok),
                Some(Tok::Punct(s)) if s == "(" || s == "."
            )
        {
            p.parse_import()?
        } else {
            out.push(p.note_error_pos(Parser::parse_stmt)?);
            continue;
        };
        out.push(Stmt::new(item, line));
    }
    Ok(out)
}

impl Parser {
    // ── token helpers ────────────────────────────────────────────────────
    fn cur(&self) -> &Token {
        &self.toks[self.pos]
    }
    /// Parse one `${…}` field of a template token, keeping its spans in this
    /// script's coordinates. The field is part of the enclosing code, so it
    /// parses in the same context: `await` and `yield` stay operators inside
    /// an async or generator body, and a private name it uses is checked
    /// against the enclosing class body like any other use. A field used to be
    /// parsed as if at the top level, so `` `${await x}` `` was a
    /// `ReferenceError` and `` `${this.#c}` `` a `SyntaxError`.
    fn parse_field(&mut self, src: &str, at: u32) -> Result<Expr, String> {
        // `${}`: the field is empty, so the first thing wrong is its `}`.
        if src.trim().is_empty() {
            return Err("SyntaxError: Unexpected token '}'".to_string());
        }
        let mut p = field_parser(src, self.spans.then_some(at))?;
        p.in_generator = self.in_generator;
        p.in_async = self.in_async;
        p.strict = self.strict;
        p.super_ok = self.super_ok;
        p.in_function = self.in_function;
        p.module = self.module;
        if !self.class_scopes.is_empty() {
            p.class_scopes.push(PrivateScope::default());
        }
        let e = p.parse_expr()?;
        if let (Some(scope), Some(inner)) = (self.class_scopes.last_mut(), p.class_scopes.pop()) {
            scope.used.extend(inner.used);
        }
        Ok(e)
    }

    /// The [`Pos`] of the current token: one past its byte offset, or `0`
    /// when this parser's offsets do not index the caller's text.
    fn pos_here(&self) -> Pos {
        if self.spans {
            self.toks[self.pos].start + 1
        } else {
            0
        }
    }

    /// Run one parse step; when it fails, record the token it stopped at for
    /// [`take_error_pos`].
    fn note_error_pos<T>(
        &mut self,
        step: impl FnOnce(&mut Self) -> Result<T, String>,
    ) -> Result<T, String> {
        let r = step(self);
        // An error that placed itself (`note_error_span`) keeps its place.
        if r.is_err() && ERROR_POS.with(|p| p.get()) == 0 {
            let end = if self.spans {
                self.toks[self.pos].end + 1
            } else {
                0
            };
            note_error_span(self.pos_here(), end);
        }
        r
    }

    /// The [`Pos`] V8 gives a call whose `(` is the current token: the token
    /// before it when that is a name (`f(`, `o.m(` — "for call of an identifier
    /// we want to report position of the identifier", `ParseLeftHandSideContinuation`),
    /// else the parenthesis itself (`o[k](`, `f()(`, `f?.(`).
    fn call_pos(&self) -> Pos {
        match self.pos.checked_sub(1).map(|i| &self.toks[i]) {
            Some(t) if self.spans && matches!(t.tok, Tok::Ident(_)) => t.start + 1,
            _ => self.pos_here(),
        }
    }

    /// Byte offset where token `i` begins.
    fn start_at(&self, i: usize) -> u32 {
        self.toks[i].start
    }
    /// The source range from `start` to the end of the last consumed token.
    fn span_from(&self, start: u32) -> Span {
        if !self.spans || self.pos == 0 {
            return (0, 0);
        }
        (start, self.toks[self.pos - 1].end)
    }
    fn tok(&self) -> &Tok {
        &self.toks[self.pos].tok
    }
    fn line(&self) -> u32 {
        self.toks[self.pos].line
    }
    fn at_eof(&self) -> bool {
        matches!(self.tok(), Tok::Eof)
    }
    fn newline_before(&self) -> bool {
        self.cur().newline_before
    }
    fn advance(&mut self) -> Tok {
        let t = self.toks[self.pos].tok.clone();
        if self.pos + 1 < self.toks.len() {
            self.pos += 1;
        }
        t
    }

    /// True if the current token is the punctuation `s`.
    fn is_punct(&self, s: &str) -> bool {
        matches!(self.tok(), Tok::Punct(p) if p == s)
    }
    /// True if the current token is the identifier/keyword `s`.
    fn is_kw(&self, s: &str) -> bool {
        matches!(self.tok(), Tok::Ident(i) if i == s)
    }
    /// Consume the punctuation `s` if present.
    fn eat_punct(&mut self, s: &str) -> bool {
        if self.is_punct(s) {
            self.advance();
            true
        } else {
            false
        }
    }
    fn eat_kw(&mut self, s: &str) -> bool {
        if self.is_kw(s) {
            self.advance();
            true
        } else {
            false
        }
    }
    /// V8's message for a token the grammar has no place for. Which wording
    /// depends on the token's class — a reserved word and a punctuator are
    /// `Unexpected token 'x'`, an identifier names itself, and a literal says
    /// only what kind it is — so every "this token cannot go here" error site
    /// shares one function rather than describing the token its own way.
    fn unexpected(&self) -> String {
        /// The ReservedWords (13.1.1) V8 reports as a bare token.
        const RESERVED: &[&str] = &[
            "break",
            "case",
            "catch",
            "class",
            "const",
            "continue",
            "debugger",
            "default",
            "delete",
            "do",
            "else",
            "export",
            "extends",
            "false",
            "finally",
            "for",
            "function",
            "if",
            "import",
            "in",
            "instanceof",
            "new",
            "null",
            "return",
            "super",
            "switch",
            "this",
            "throw",
            "true",
            "try",
            "typeof",
            "var",
            "void",
            "while",
            "with",
        ];
        // V8 explains a stray `await` operand by the missing `async`, not by
        // the operand: `await 1` outside an async function reaches the `1`.
        if self.pos > 0
            && !self.in_async
            && matches!(&self.toks[self.pos - 1].tok, Tok::Ident(s) if s == "await")
            && !matches!(self.tok(), Tok::Punct(p) if p == ")" || p == ";" || p == ",")
        {
            return "SyntaxError: await is only valid in async functions and the top level bodies of modules".to_string();
        }
        let what = match self.tok() {
            Tok::Eof => "Unexpected end of input".to_string(),
            Tok::Num(_) | Tok::BigInt(_) => "Unexpected number".to_string(),
            Tok::Str(_) => "Unexpected string".to_string(),
            Tok::Template { .. } => "Unexpected template string".to_string(),
            Tok::Regex(..) => "Unexpected regular expression".to_string(),
            Tok::Ident(s) if s == "enum" => "Unexpected reserved word".to_string(),
            Tok::Ident(s) if RESERVED.contains(&s.as_str()) => {
                format!("Unexpected token '{s}'")
            }
            Tok::Ident(s) => format!("Unexpected identifier '{s}'"),
            Tok::Punct(p) => format!("Unexpected token '{p}'"),
        };
        format!("SyntaxError: {what}")
    }

    /// The parameter-list early errors that depend on how the function is
    /// written (15.2.1, 15.1.1): a repeated name is allowed only in sloppy code
    /// with a plain list of simple names, and a `'use strict'` body needs a
    /// simple list. `unique` is set for arrows, methods and accessors, which
    /// never allow a repeat; `body_strict` for a body that begins with the
    /// directive (strictness inherited from outside is `self.strict`).
    fn check_params(
        &self,
        params: &[Param],
        body_strict: bool,
        unique: bool,
    ) -> Result<(), String> {
        let simple = params
            .iter()
            .all(|p| !p.rest && p.default.is_none() && matches!(p.pattern, Expr::Ident(_)));
        if body_strict && !simple {
            return Err(
                "SyntaxError: Illegal 'use strict' directive in function with \
                        non-simple parameter list"
                    .to_string(),
            );
        }
        let strict = self.strict || body_strict;
        let mut names: Vec<String> = Vec::new();
        for p in params {
            pattern_idents(&p.pattern, &mut names);
        }
        if strict && names.iter().any(|n| n == "eval" || n == "arguments") {
            return Err("SyntaxError: Unexpected eval or arguments in strict mode".to_string());
        }
        let repeats = names
            .iter()
            .enumerate()
            .any(|(i, n)| names[..i].contains(n));
        if repeats && (strict || unique || !simple) {
            return Err(
                "SyntaxError: Duplicate parameter name not allowed in this context".to_string(),
            );
        }
        Ok(())
    }

    /// Whether the directive prologue starting at token `from` contains
    /// `'use strict'` (14.1.1): the leading run of string-literal expression
    /// statements, each ended by `;`, a newline or the end of the block.
    fn leading_use_strict(&self, from: usize) -> bool {
        let mut i = from;
        while let Some(Token {
            tok: Tok::Str(s), ..
        }) = self.toks.get(i)
        {
            let ends = match self.toks.get(i + 1) {
                Some(t) => {
                    matches!(&t.tok, Tok::Punct(p) if p == ";" || p == "}")
                        || t.newline_before
                        || matches!(t.tok, Tok::Eof)
                }
                None => true,
            };
            if !ends {
                return false;
            }
            if s == "use strict" {
                return true;
            }
            i += 1;
            if matches!(self.toks.get(i), Some(Token { tok: Tok::Punct(p), .. }) if p == ";") {
                i += 1;
            }
        }
        false
    }

    /// Run `f` with `super` allowed or not.
    fn with_super<T>(&mut self, ok: bool, f: impl FnOnce(&mut Self) -> T) -> T {
        let saved = std::mem::replace(&mut self.super_ok, ok);
        let out = f(self);
        self.super_ok = saved;
        out
    }

    /// The strict-mode-only restriction the current token trips, if the code
    /// is strict.
    fn check_legacy(&self) -> Result<(), String> {
        if !self.strict {
            return Ok(());
        }
        let msg = match self.cur().legacy {
            Legacy::None => return Ok(()),
            Legacy::OctalLiteral => "Octal literals are not allowed in strict mode.",
            Legacy::LeadingZeroDecimal => {
                "Decimals with leading zeros are not allowed in strict mode."
            }
            Legacy::OctalEscape => "Octal escape sequences are not allowed in strict mode.",
            Legacy::NonOctalEscape => "\\8 and \\9 are not allowed in strict mode.",
        };
        Err(format!("SyntaxError: {msg}"))
    }

    fn expect_punct(&mut self, s: &str) -> Result<(), String> {
        if self.eat_punct(s) {
            Ok(())
        } else {
            Err(self.unexpected())
        }
    }

    /// Consume an identifier name (any non-punct ident, including keywords used
    /// as property names when `allow_kw`).
    fn ident_name(&mut self) -> Result<String, String> {
        match self.tok().clone() {
            Tok::Ident(s) => {
                self.advance();
                Ok(s)
            }
            _ => Err(self.unexpected()),
        }
    }

    /// Apply ASI: consume an explicit `;`, or accept a newline / `}` / EOF.
    fn semicolon(&mut self) -> Result<(), String> {
        if self.eat_punct(";") {
            return Ok(());
        }
        if self.newline_before() || self.is_punct("}") || self.at_eof() {
            return Ok(());
        }
        Err(self.unexpected())
    }

    // ── statements ───────────────────────────────────────────────────────
    fn parse_stmt(&mut self) -> Result<Stmt, String> {
        let stmt = self.parse_stmt_inner()?;
        // Whatever `{ a = 1 }` is still unclaimed by a pattern is an error
        // (13.2.5.1), reported where V8 reports it: under `a = 1`.
        if let Some(&(_, pos, end)) = self.cover_init.first() {
            note_error_span(pos, end);
            return Err("SyntaxError: Invalid shorthand property initializer".to_string());
        }
        Ok(stmt)
    }

    fn parse_stmt_inner(&mut self) -> Result<Stmt, String> {
        let line = self.line();
        let pos = self.pos_here();
        let kind = match self.tok().clone() {
            Tok::Punct(p) if p == "{" => {
                self.advance();
                StmtKind::Block(self.parse_block_body()?)
            }
            Tok::Punct(p) if p == ";" => {
                self.advance();
                StmtKind::Empty
            }
            // A script has no `export`, and `import` is only the call form
            // `import(…)` and the meta property `import.meta`.
            Tok::Ident(kw) if kw == "export" => return Err(self.unexpected()),
            Tok::Ident(kw)
                if kw == "import"
                    && !matches!(
                        self.toks.get(self.pos + 1).map(|t| &t.tok),
                        Some(Tok::Punct(p)) if p == "(" || p == "."
                    ) =>
            {
                return Err("SyntaxError: Cannot use import statement outside a module".to_string());
            }
            Tok::Ident(kw) if kw == "var" || kw == "let" || kw == "const" => {
                let k = self.parse_decl_kind();
                let decls = self.parse_declarators()?;
                self.check_declarators(&k, &decls)?;
                self.semicolon()?;
                StmtKind::Decl { kind: k, decls }
            }
            Tok::Ident(kw) if kw == "function" => self.parse_func_decl(false)?,
            // `async function …` (declaration). `async` stays a plain identifier
            // anywhere else (contextual keyword).
            Tok::Ident(kw)
                if kw == "async" && self.peek_kw(1, "function") && !self.peek_newline(1) =>
            {
                self.advance(); // async
                self.parse_func_decl(true)?
            }
            Tok::Ident(kw) if kw == "class" => {
                // A class DECLARATION needs a binding name (15.7.1).
                if matches!(
                    self.toks.get(self.pos + 1).map(|t| &t.tok),
                    Some(Tok::Punct(p)) if p == "{"
                ) || self.peek_kw(1, "extends")
                {
                    self.advance();
                    return Err(self.unexpected());
                }
                let node = self.parse_class(true)?;
                StmtKind::ClassDecl(node)
            }
            Tok::Ident(kw) if kw == "if" => self.parse_if()?,
            Tok::Ident(kw) if kw == "while" => self.parse_while()?,
            Tok::Ident(kw) if kw == "with" => self.parse_with()?,
            Tok::Ident(kw) if kw == "do" => self.parse_do_while()?,
            Tok::Ident(kw) if kw == "for" => self.parse_for()?,
            Tok::Ident(kw) if kw == "switch" => self.parse_switch()?,
            Tok::Ident(kw) if kw == "return" => {
                if !self.in_function {
                    return Err("SyntaxError: Illegal return statement".to_string());
                }
                self.advance();
                let arg = if self.is_punct(";")
                    || self.is_punct("}")
                    || self.newline_before()
                    || self.at_eof()
                {
                    None
                } else {
                    Some(self.parse_expr()?)
                };
                self.semicolon()?;
                StmtKind::Return(arg)
            }
            Tok::Ident(kw) if kw == "break" => {
                self.advance();
                let label = self.opt_label();
                self.semicolon()?;
                StmtKind::Break(label)
            }
            Tok::Ident(kw) if kw == "continue" => {
                self.advance();
                let label = self.opt_label();
                self.semicolon()?;
                StmtKind::Continue(label)
            }
            Tok::Ident(kw) if kw == "throw" => {
                self.advance();
                // 14.14: no LineTerminator between `throw` and its operand.
                if self.newline_before() {
                    return Err("SyntaxError: Illegal newline after throw".to_string());
                }
                let e = self.parse_expr()?;
                self.semicolon()?;
                StmtKind::Throw(e)
            }
            Tok::Ident(kw) if kw == "try" => self.parse_try()?,
            // `label: stmt` — a bare identifier immediately followed by `:` at
            // statement position is a label (never an expression; the reserved
            // control keywords are all matched above, and switch `case`/`default`
            // labels are parsed inside `parse_switch`).
            Tok::Ident(name) if matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":") =>
            {
                if self.labels.contains(&name) {
                    return Err(format!(
                        "SyntaxError: Label '{name}' has already been declared"
                    ));
                }
                self.advance(); // the label identifier
                self.advance(); // the ':'
                self.labels.push(name.clone());
                // 14.13.1 / B.3.2: a labelled FunctionDeclaration is sloppy-only.
                let body = if self.strict
                    && (self.is_kw("function")
                        || self.is_kw("async") && self.peek_kw(1, "function"))
                {
                    Err("SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.".to_string())
                } else {
                    self.parse_stmt()
                };
                self.labels.pop();
                StmtKind::Labeled {
                    label: name,
                    body: Box::new(body?),
                }
            }
            _ => {
                let e = self.parse_expr()?;
                self.semicolon()?;
                StmtKind::Expr(e)
            }
        };
        Ok(Stmt::at(kind, line, pos))
    }

    /// Whether the token `n` ahead is the punctuator `p`.
    fn peek_punct_at(&self, n: usize, p: &str) -> bool {
        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Punct(s)) if s == p)
    }
    /// Whether the token `n` ahead is the identifier `kw`.
    fn peek_kw(&self, n: usize, kw: &str) -> bool {
        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Ident(s)) if s == kw)
    }
    /// Whether the token `n` ahead has a newline before it.
    fn peek_newline(&self, n: usize) -> bool {
        self.toks
            .get(self.pos + n)
            .map(|t| t.newline_before)
            .unwrap_or(false)
    }

    // ── module declarations (16.2.2, 16.2.3) ─────────────────────────────
    /// A ModuleExportName: an IdentifierName, or a string literal (`"a b"`).
    fn module_export_name(&mut self) -> Result<String, String> {
        match self.tok().clone() {
            Tok::Str(s) => {
                self.advance();
                Ok(s)
            }
            Tok::Ident(_) => self.ident_name(),
            _ => Err(self.unexpected()),
        }
    }

    /// A binding identifier an import introduces: never a reserved word.
    fn import_binding(&mut self) -> Result<String, String> {
        if matches!(self.tok(), Tok::Ident(s) if is_keyword(s) || s == "import" || s == "export") {
            return Err(self.unexpected());
        }
        let name = self.ident_name()?;
        self.check_binding_name(&name)?;
        if name == "eval" || name == "arguments" {
            return Err("SyntaxError: Unexpected eval or arguments in strict mode".to_string());
        }
        Ok(name)
    }

    /// The module specifier string after `from` (or after a bare `import`).
    fn module_specifier(&mut self) -> Result<String, String> {
        match self.tok().clone() {
            Tok::Str(s) => {
                self.advance();
                Ok(s)
            }
            _ => Err(self.unexpected()),
        }
    }

    /// An optional `with { key: "value", … }` import-attributes clause (the
    /// older `assert` spelling is accepted the same way).
    fn import_attributes(&mut self) -> Result<Vec<(String, String)>, String> {
        let mut out = Vec::new();
        if !(self.is_kw("with") || self.is_kw("assert") && !self.newline_before()) {
            return Ok(out);
        }
        self.advance();
        self.expect_punct("{")?;
        while !self.is_punct("}") {
            let key = self.module_export_name()?;
            self.expect_punct(":")?;
            let value = self.module_specifier()?;
            if out.iter().any(|(k, _)| *k == key) {
                return Err(format!(
                    "SyntaxError: Import attribute has duplicate key '{key}'"
                ));
            }
            out.push((key, value));
            if !self.eat_punct(",") {
                break;
            }
        }
        self.expect_punct("}")?;
        Ok(out)
    }

    /// `import …;` at the top level of a module (the `import` keyword is current).
    fn parse_import(&mut self) -> Result<StmtKind, String> {
        self.advance(); // import
        let mut specs = Vec::new();
        let mut clause: Span = (0, 0);
        // `import "m";` — no bindings, the module is evaluated for effect.
        if !matches!(self.tok(), Tok::Str(_)) {
            if !self.is_punct("{") && !self.is_punct("*") {
                specs.push(ImportSpec::Default(self.import_binding()?));
                if !self.eat_punct(",") {
                    return self.finish_import(specs, clause);
                }
            }
            if self.eat_punct("*") {
                if !self.eat_kw("as") {
                    return Err(self.unexpected());
                }
                specs.push(ImportSpec::Namespace(self.import_binding()?));
            } else if self.is_punct("{") {
                let start = self.start_at(self.pos);
                self.advance();
                while !self.is_punct("}") {
                    let string_name = matches!(self.tok(), Tok::Str(_));
                    let imported = self.module_export_name()?;
                    let local = if self.eat_kw("as") {
                        self.import_binding()?
                    } else if string_name || is_keyword(&imported) {
                        // `import { "a b" }` / `import { default }` have no
                        // binding name of their own.
                        return Err("SyntaxError: Unexpected reserved word".to_string());
                    } else {
                        self.check_binding_name(&imported)?;
                        imported.clone()
                    };
                    specs.push(ImportSpec::Named { imported, local });
                    if !self.eat_punct(",") {
                        break;
                    }
                }
                self.expect_punct("}")?;
                clause = self.span_from(start);
            } else {
                return Err(self.unexpected());
            }
        }
        self.finish_import(specs, clause)
    }

    /// `from "m" [with {…}];` closing an import declaration with `specs`.
    fn finish_import(&mut self, specs: Vec<ImportSpec>, clause: Span) -> Result<StmtKind, String> {
        if !specs.is_empty() && !self.eat_kw("from") {
            return Err(self.unexpected());
        }
        let specifier = self.module_specifier()?;
        let attributes = self.import_attributes()?;
        self.semicolon()?;
        Ok(StmtKind::Import(ImportDecl {
            specifier,
            specs,
            attributes,
            clause,
        }))
    }

    /// `export …` at the top level of a module (the `export` keyword is current).
    fn parse_export(&mut self) -> Result<StmtKind, String> {
        self.advance(); // export
        let line = self.line();
        if self.eat_punct("*") {
            let alias = if self.eat_kw("as") {
                Some(self.module_export_name()?)
            } else {
                None
            };
            if !self.eat_kw("from") {
                return Err(self.unexpected());
            }
            let from = self.module_specifier()?;
            let attributes = self.import_attributes()?;
            self.semicolon()?;
            return Ok(StmtKind::Export(ExportDecl::Star {
                alias,
                from,
                attributes,
            }));
        }
        if self.eat_punct("{") {
            let mut specs = Vec::new();
            let mut string_locals = false;
            while !self.is_punct("}") {
                string_locals |= matches!(self.tok(), Tok::Str(_));
                let local = self.module_export_name()?;
                let exported = if self.eat_kw("as") {
                    self.module_export_name()?
                } else {
                    local.clone()
                };
                specs.push(ExportSpec { local, exported });
                if !self.eat_punct(",") {
                    break;
                }
            }
            self.expect_punct("}")?;
            let from = if self.eat_kw("from") {
                Some(self.module_specifier()?)
            } else {
                None
            };
            // Without `from`, each local must be a binding of this module, which
            // a string literal or a reserved word can never be.
            if from.is_none() {
                if string_locals {
                    return Err("SyntaxError: Unexpected string".to_string());
                }
                if let Some(s) = specs.iter().find(|s| is_keyword(&s.local)) {
                    return Err(format!("SyntaxError: Unexpected token '{}'", s.local));
                }
            }
            let attributes = if from.is_some() {
                self.import_attributes()?
            } else {
                Vec::new()
            };
            self.semicolon()?;
            return Ok(StmtKind::Export(ExportDecl::Named {
                specs,
                from,
                attributes,
            }));
        }
        if self.eat_kw("default") {
            let is_fn = self.is_kw("function")
                || self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
            if is_fn {
                let is_async = self.eat_kw("async");
                let Expr::Function {
                    params,
                    body: FnBody::Block(body),
                    name,
                    is_generator,
                    is_async,
                    span,
                    ..
                } = self.parse_function_expr(is_async)?
                else {
                    return Err(self.unexpected());
                };
                let decl = StmtKind::FuncDecl {
                    name: name.unwrap_or_else(|| "default".to_string()),
                    params,
                    body,
                    is_generator,
                    is_async,
                    span,
                };
                return Ok(StmtKind::Export(ExportDecl::DefaultDecl(Box::new(
                    Stmt::new(decl, line),
                ))));
            }
            if self.is_kw("class") {
                let mut node = self.parse_class(true)?;
                node.name.get_or_insert_with(|| "default".to_string());
                return Ok(StmtKind::Export(ExportDecl::DefaultDecl(Box::new(
                    Stmt::new(StmtKind::ClassDecl(node), line),
                ))));
            }
            let e = self.allow_in(|p| p.parse_assign())?;
            self.semicolon()?;
            return Ok(StmtKind::Export(ExportDecl::DefaultExpr(e)));
        }
        // `export` + a declaration: var/let/const, function, async function, class.
        let is_decl = self.is_kw("var")
            || self.is_kw("let")
            || self.is_kw("const")
            || self.is_kw("function")
            || self.is_kw("class")
            || self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
        if !is_decl {
            return Err(self.unexpected());
        }
        let decl = self.parse_stmt()?;
        Ok(StmtKind::Export(ExportDecl::Decl(Box::new(decl))))
    }

    /// Parse a `function` declaration (the `function`/`async function` keyword is
    /// current). `is_async` is true when a preceding `async` was consumed.
    fn parse_func_decl(&mut self, is_async: bool) -> Result<StmtKind, String> {
        // `async` was consumed by the caller and is part of the source text.
        let start = self.start_at(if is_async { self.pos - 1 } else { self.pos });
        self.advance(); // function
        let is_generator = self.eat_punct("*");
        if self.is_punct("(") {
            return Err("SyntaxError: Function statements require a function name".to_string());
        }
        let name = self.ident_name()?;
        let params = self.parse_params()?;
        self.check_params(&params, self.leading_use_strict(self.pos + 1), false)?;
        self.expect_punct("{")?;
        let body = self.with_super(false, |p| p.parse_fn_body_block(is_generator, is_async))?;
        Ok(StmtKind::FuncDecl {
            name,
            params,
            body,
            is_generator,
            is_async,
            span: self.span_from(start),
        })
    }

    /// Parse a brace-delimited function body under the given generator/async
    /// context (so `yield`/`await` inside are operators, not identifiers).
    fn parse_fn_body_block(
        &mut self,
        is_generator: bool,
        is_async: bool,
    ) -> Result<Vec<Stmt>, String> {
        self.parse_body_block(is_generator, is_async, true)
    }

    /// [`Self::parse_fn_body_block`] with `return` admitted or not: a class
    /// static block is a body in every other respect but may not `return`.
    fn parse_body_block(
        &mut self,
        is_generator: bool,
        is_async: bool,
        returns: bool,
    ) -> Result<Vec<Stmt>, String> {
        let (pg, pa) = (self.in_generator, self.in_async);
        self.in_generator = is_generator;
        self.in_async = is_async;
        let outer_labels = std::mem::take(&mut self.labels);
        let outer_strict = self.strict;
        let outer_in_function = std::mem::replace(&mut self.in_function, returns);
        self.strict = outer_strict || self.leading_use_strict(self.pos);
        let body = self.parse_block_body();
        self.in_function = outer_in_function;
        self.strict = outer_strict;
        self.labels = outer_labels;
        self.in_generator = pg;
        self.in_async = pa;
        body
    }

    /// Parse a function *expression* (`function`/`async function`, keyword
    /// current). Supports `function*` generators.
    fn parse_function_expr(&mut self, is_async: bool) -> Result<Expr, String> {
        let start = self.start_at(if is_async { self.pos - 1 } else { self.pos });
        self.advance(); // function
        let is_generator = self.eat_punct("*");
        let name = if let Tok::Ident(n) = self.tok() {
            if !is_keyword(n) {
                let n = n.clone();
                self.advance();
                Some(n)
            } else {
                None
            }
        } else {
            None
        };
        let params = self.parse_params()?;
        self.check_params(&params, self.leading_use_strict(self.pos + 1), false)?;
        self.expect_punct("{")?;
        let body = self.with_super(false, |p| p.parse_fn_body_block(is_generator, is_async))?;
        Ok(Expr::Function {
            params,
            body: FnBody::Block(body),
            is_arrow: false,
            name,
            is_generator,
            is_async,
            is_method: false,
            span: self.span_from(start),
        })
    }

    /// Parse a `class` (the `class` keyword is current). `_decl` distinguishes a
    /// declaration (name required in strict mode, but we accept optional) from an
    /// expression.
    /// 15.7.1: a private name must be declared by an enclosing class body.
    /// Outside one, `this.#x` is a SyntaxError at parse time — it used to parse
    /// and then throw a `TypeError` only if the read ever ran, so a typo in a
    /// dead branch shipped silently.
    fn check_private_in_scope(&mut self, property: &str) -> Result<(), String> {
        if !property.starts_with('#') {
            return Ok(());
        }
        match self.class_scopes.last_mut() {
            // Recorded, not resolved: the declaration may still be ahead of the
            // use in the same body, so the check runs when the body closes.
            Some(scope) => scope.used.push(property.to_string()),
            None => return Err(private_not_declared(property)),
        }
        Ok(())
    }

    fn parse_class(&mut self, _decl: bool) -> Result<ClassNode, String> {
        self.class_scopes.push(PrivateScope::default());
        let out = self.parse_class_inner();
        let scope = self.class_scopes.pop().unwrap_or_default();
        let out = out?;
        for name in &scope.used {
            if scope.declared.contains(name) {
                continue;
            }
            // A nested class may reference a name an OUTER class declares, so an
            // unresolved use is handed outwards rather than rejected here.
            match self.class_scopes.last_mut() {
                Some(outer) => outer.used.push(name.clone()),
                None => return Err(private_not_declared(name)),
            }
        }
        Ok(out)
    }

    fn parse_class_inner(&mut self) -> Result<ClassNode, String> {
        let start = self.start_at(self.pos);
        self.advance(); // class
        let name = if let Tok::Ident(n) = self.tok() {
            if !is_keyword(n) && n != "extends" {
                let n = n.clone();
                self.advance();
                Some(n)
            } else {
                None
            }
        } else {
            None
        };
        let parent = if self.eat_kw("extends") {
            // The superclass is a left-hand-side expression (`extends Base`,
            // `extends foo.Bar`).
            Some(Box::new(self.parse_call_member()?))
        } else {
            None
        };
        self.expect_punct("{")?;
        // 11.2.2: every part of a class is strict code.
        let outer_strict = std::mem::replace(&mut self.strict, true);
        let mut members = Vec::new();
        while !self.is_punct("}") && !self.at_eof() {
            if self.eat_punct(";") {
                continue; // stray semicolons between members
            }
            let member = self.with_super(true, |p| p.parse_class_member());
            let member = match member {
                Ok(m) => m,
                Err(e) => {
                    self.strict = outer_strict;
                    return Err(e);
                }
            };
            if member.kind == MemberKind::Constructor
                && members
                    .iter()
                    .any(|m: &ClassMember| m.kind == MemberKind::Constructor)
            {
                return Err("SyntaxError: A class may only have one constructor".to_string());
            }
            if let Expr::Str(k) = &member.key {
                if k.starts_with('#') {
                    // A name is declared once — except a getter and a setter of
                    // the same staticness, which together are one accessor.
                    let pair = |a: &MemberKind, b: &MemberKind| {
                        matches!(
                            (a, b),
                            (MemberKind::Get, MemberKind::Set) | (MemberKind::Set, MemberKind::Get)
                        )
                    };
                    let clash = members.iter().any(|m: &ClassMember| {
                        matches!(&m.key, Expr::Str(n) if n == k)
                            && !(pair(&m.kind, &member.kind) && m.is_static == member.is_static)
                    });
                    if clash {
                        return Err(format!(
                            "SyntaxError: Identifier '{k}' has already been declared"
                        ));
                    }
                    if let Some(scope) = self.class_scopes.last_mut() {
                        scope.declared.push(k.clone());
                    }
                }
            }
            members.push(member);
        }
        self.strict = outer_strict;
        self.expect_punct("}")?;
        Ok(ClassNode {
            name,
            parent,
            members,
            span: self.span_from(start),
        })
    }

    /// Parse one class member: `[static] [get|set|async|*] name(params){…}` or a
    /// `[static] name [= init];` field.
    fn parse_class_member(&mut self) -> Result<ClassMember, String> {
        let is_static = self.is_kw("static") && !self.peek_is_member_punct(1) && {
            self.advance();
            true
        };
        let start = self.start_at(self.pos);
        // `static { … }` — a class static initialization block (ES2022). A brace
        // where a member key would be is unambiguous: no member name can start
        // with `{`, so this is checked before the key parse (which otherwise
        // rejects it as `bad member key Punct("{")`).
        if is_static && self.is_punct("{") {
            self.advance();
            // Its own function context: `yield`/`await` are plain identifiers
            // inside a static block, whatever encloses the class.
            let body = self.parse_body_block(false, false, false)?;
            return Ok(ClassMember {
                key: Expr::Str(String::new()),
                computed: false,
                kind: MemberKind::StaticBlock,
                is_static: true,
                is_generator: false,
                is_async: false,
                params: Vec::new(),
                body,
                field_init: None,
                span: self.span_from(start),
            });
        }
        // Accessor / async / generator prefixes (each contextual: only a prefix
        // when followed by another member name, not itself the member name).
        let mut kind = MemberKind::Method;
        let mut is_async = false;
        let mut is_generator = false;
        if self.is_kw("get") && !self.peek_is_member_punct(1) {
            self.advance();
            kind = MemberKind::Get;
        } else if self.is_kw("set") && !self.peek_is_member_punct(1) {
            self.advance();
            kind = MemberKind::Set;
        } else {
            if self.is_kw("async") && !self.peek_is_member_punct(1) && !self.peek_newline(1) {
                self.advance();
                is_async = true;
            }
            if self.eat_punct("*") {
                is_generator = true;
            }
        }
        // The member key (computed `[expr]`, string, number, or identifier).
        let (key, computed) = self.parse_property_key()?;
        // A field (no parentheses) vs a method.
        if kind == MemberKind::Method && !self.is_punct("(") {
            let field_init = if self.eat_punct("=") {
                Some(self.parse_assign()?)
            } else {
                None
            };
            self.semicolon()?;
            return Ok(ClassMember {
                key,
                computed,
                kind: MemberKind::Field,
                is_static,
                is_generator: false,
                is_async: false,
                params: Vec::new(),
                body: Vec::new(),
                field_init,
                span: (0, 0),
            });
        }
        // A method / accessor / constructor.
        let is_ctor = !is_static
            && !computed
            && matches!(&key, Expr::Str(s) if s == "constructor")
            && kind == MemberKind::Method;
        let params = self.parse_params()?;
        check_accessor_arity(kind, &params)?;
        self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
        self.expect_punct("{")?;
        let body = self.parse_fn_body_block(is_generator, is_async)?;
        Ok(ClassMember {
            key,
            computed,
            kind: if is_ctor {
                MemberKind::Constructor
            } else {
                kind
            },
            is_static,
            is_generator,
            is_async,
            params,
            body,
            field_init: None,
            span: self.span_from(start),
        })
    }

    /// Whether the token `n` ahead is `(`, `=`, `;`, `}`, or a newline-boundary —
    /// i.e. the current word is itself the member name, not a modifier prefix.
    fn peek_is_member_punct(&self, n: usize) -> bool {
        matches!(
            self.toks.get(self.pos + n).map(|t| &t.tok),
            Some(Tok::Punct(p)) if p == "(" || p == "=" || p == ";" || p == "}"
        )
    }

    /// Parse a property key for a class member / object method: `[expr]` (computed),
    /// a string, a number, or an identifier (returned as an `Expr::Str`).
    fn parse_property_key(&mut self) -> Result<(Expr, bool), String> {
        if self.is_punct("[") {
            self.advance();
            let k = self.outside_binding(Self::parse_assign)?;
            self.expect_punct("]")?;
            Ok((k, true))
        } else {
            match self.tok().clone() {
                Tok::Str(s) => {
                    self.advance();
                    Ok((Expr::Str(s), false))
                }
                Tok::Num(n) => {
                    self.advance();
                    Ok((Expr::Str(crate::host::fmt_number(n)), false))
                }
                Tok::Ident(s) => {
                    self.advance();
                    Ok((Expr::Str(s), false))
                }
                _ => Err(self.unexpected()),
            }
        }
    }

    /// An optional non-newline label after break/continue.
    fn opt_label(&mut self) -> Option<String> {
        if self.newline_before() {
            return None;
        }
        if let Tok::Ident(s) = self.tok() {
            if !is_keyword(s) {
                let s = s.clone();
                self.advance();
                return Some(s);
            }
        }
        None
    }

    /// Parse statements up to (and consuming) the closing `}`.
    fn parse_block_body(&mut self) -> Result<Vec<Stmt>, String> {
        let mut out = Vec::new();
        while !self.is_punct("}") && !self.at_eof() {
            out.push(self.parse_stmt()?);
        }
        self.expect_punct("}")?;
        Ok(out)
    }

    /// Early errors of a `var`/`let`/`const` statement's declarator list: a
    /// `const` or a destructuring pattern needs an initialiser, `let` may not
    /// be a lexically bound name, and `enum` is never a binding.
    fn check_declarators(&self, kind: &DeclKind, decls: &[Declarator]) -> Result<(), String> {
        for d in decls {
            if d.init.is_none() {
                if !matches!(d.target, Expr::Ident(_)) {
                    return Err(
                        "SyntaxError: Missing initializer in destructuring declaration".to_string(),
                    );
                }
                if matches!(kind, DeclKind::Const) {
                    return Err("SyntaxError: Missing initializer in const declaration".to_string());
                }
            }
            if !matches!(kind, DeclKind::Var) {
                if let Expr::Ident(n) = &d.target {
                    if n == "let" {
                        return Err(
                            "SyntaxError: let is disallowed as a lexically bound name".to_string()
                        );
                    }
                }
            }
        }
        Ok(())
    }

    /// A statement in a single-statement position — the body of a loop or the
    /// arm of an `if`. Declarations are not statements there (14.6, 14.7);
    /// V8 words the refusal by what the declaration was and by strictness.
    /// Sloppy code keeps B.3.3's one allowance: a plain function declaration
    /// as an `if` arm.
    fn parse_sub_stmt(&mut self, is_if_arm: bool) -> Result<Stmt, String> {
        let is_async_fn =
            self.is_kw("async") && self.peek_kw(1, "function") && !self.peek_newline(1);
        if self.is_kw("function") || is_async_fn {
            let generator = self.peek_punct_after_function();
            if is_async_fn {
                return Err("SyntaxError: Async functions can only be declared at the top level or inside a block.".to_string());
            }
            if generator {
                return Err("SyntaxError: Generators can only be declared at the top level or inside a block.".to_string());
            }
            if self.strict {
                return Err("SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.".to_string());
            }
            if !is_if_arm {
                return Err("SyntaxError: In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.".to_string());
            }
        }
        if self.is_kw("class") {
            return Err(self.unexpected());
        }
        if self.is_kw("const") {
            return Err(self.unexpected());
        }
        if self.is_kw("let")
            && matches!(
                self.toks.get(self.pos + 1).map(|t| &t.tok),
                Some(Tok::Punct(p)) if p == "[" || p == "{"
            )
        {
            return Err(
                "SyntaxError: Lexical declaration cannot appear in a single-statement context"
                    .to_string(),
            );
        }
        self.parse_stmt()
    }

    /// Whether the `function` keyword at the cursor is `function*`.
    fn peek_punct_after_function(&self) -> bool {
        let at = if self.is_kw("async") { 2 } else { 1 };
        matches!(self.toks.get(self.pos + at).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "*")
    }

    fn parse_decl_kind(&mut self) -> DeclKind {
        let k = match self.tok() {
            Tok::Ident(s) if s == "let" => DeclKind::Let,
            Tok::Ident(s) if s == "const" => DeclKind::Const,
            _ => DeclKind::Var,
        };
        self.advance();
        k
    }

    fn parse_declarators(&mut self) -> Result<Vec<Declarator>, String> {
        let mut decls = Vec::new();
        loop {
            let (target, bound) = self.parse_binding_target_at()?;
            let init = if self.eat_punct("=") {
                Some(self.parse_assign()?)
            } else {
                None
            };
            decls.push(Declarator {
                target,
                init,
                bound,
            });
            if !self.eat_punct(",") {
                break;
            }
        }
        Ok(decls)
    }

    /// A binding target: identifier or array/object destructuring pattern.
    fn parse_binding_target(&mut self) -> Result<Expr, String> {
        self.parse_binding_target_at().map(|(target, _)| target)
    }

    /// [`Parser::parse_binding_target`], with where each name it binds is
    /// written (empty without source spans).
    fn parse_binding_target_at(&mut self) -> Result<(Expr, Vec<(String, Pos)>), String> {
        let mark = self.bound_at.len();
        let pos = self.pos_here();
        let target = self.parse_binding_pattern();
        let mut bound = self.bound_at.split_off(mark);
        let target = target?;
        if let Expr::Ident(n) = &target {
            bound = vec![(n.clone(), pos)];
        }
        if !self.spans {
            bound.clear();
        }
        Ok((target, bound))
    }

    /// Run `f` on an expression nested in a binding pattern — a default value
    /// or a computed key — where names are references, not bindings.
    fn outside_binding<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
        let outer = std::mem::replace(&mut self.in_binding, false);
        let r = f(self);
        self.in_binding = outer;
        r
    }

    fn parse_binding_pattern(&mut self) -> Result<Expr, String> {
        if self.is_punct("[") || self.is_punct("{") {
            let outer = std::mem::replace(&mut self.in_binding, true);
            let pattern = if self.is_punct("[") {
                self.parse_array_literal()
            } else {
                self.parse_object_literal()
            };
            self.in_binding = outer;
            pattern
        } else {
            let name = self.ident_name()?;
            self.check_binding_name(&name)?;
            Ok(Expr::Ident(name))
        }
    }

    /// Words that may not be bound: `enum` always, and the future-reserved
    /// words (plus `let`, `static`, `yield`) in strict code (13.1.1).
    fn check_binding_name(&self, name: &str) -> Result<(), String> {
        const STRICT_RESERVED: &[&str] = &[
            "implements",
            "interface",
            "let",
            "package",
            "private",
            "protected",
            "public",
            "static",
            "yield",
        ];
        // `await` is reserved throughout module code (13.1.1).
        if name == "enum" || self.module && name == "await" {
            return Err("SyntaxError: Unexpected reserved word".to_string());
        }
        if self.strict && STRICT_RESERVED.contains(&name) {
            return Err("SyntaxError: Unexpected strict mode reserved word".to_string());
        }
        Ok(())
    }

    fn parse_if(&mut self) -> Result<StmtKind, String> {
        self.advance(); // if
        self.expect_punct("(")?;
        let test = self.parse_expr()?;
        self.expect_punct(")")?;
        let cons = Box::new(self.parse_sub_stmt(true)?);
        let alt = if self.eat_kw("else") {
            Some(Box::new(self.parse_sub_stmt(true)?))
        } else {
            None
        };
        Ok(StmtKind::If { test, cons, alt })
    }

    fn parse_while(&mut self) -> Result<StmtKind, String> {
        self.advance();
        self.expect_punct("(")?;
        let test = self.parse_expr()?;
        self.expect_punct(")")?;
        let body = Box::new(self.parse_sub_stmt(false)?);
        Ok(StmtKind::While { test, body })
    }

    fn parse_with(&mut self) -> Result<StmtKind, String> {
        if self.strict {
            return Err(
                "SyntaxError: Strict mode code may not include a with statement".to_string(),
            );
        }
        self.advance();
        self.expect_punct("(")?;
        let object = self.parse_expr()?;
        self.expect_punct(")")?;
        let body = Box::new(self.parse_sub_stmt(false)?);
        Ok(StmtKind::With { object, body })
    }

    fn parse_do_while(&mut self) -> Result<StmtKind, String> {
        self.advance();
        let body = Box::new(self.parse_sub_stmt(false)?);
        if !self.eat_kw("while") {
            return Err(self.unexpected());
        }
        self.expect_punct("(")?;
        let test = self.parse_expr()?;
        self.expect_punct(")")?;
        // 12.10.1 rule 3: a `;` is inserted after `do … while ( … )` even with no
        // line break, so `do ; while (0) 1` is two statements.
        self.eat_punct(";");
        Ok(StmtKind::DoWhile { body, test })
    }

    fn parse_for(&mut self) -> Result<StmtKind, String> {
        self.advance();
        // `for await (… of …)` — the async-iteration form (valid in an async body).
        let is_await = self.eat_kw("await");
        self.expect_punct("(")?;
        // Optional declaration or expression init.
        let decl_kind = match self.tok() {
            Tok::Ident(s) if s == "var" || s == "let" || s == "const" => {
                Some(self.parse_decl_kind())
            }
            _ => None,
        };
        // Empty init: `for (;;)`.
        if decl_kind.is_none() && self.is_punct(";") {
            return self.parse_c_for(None);
        }
        // Parse the first binding/expression, then decide of/in vs C-style.
        let mut first_bound = Vec::new();
        let first_target = if decl_kind.is_some() {
            let (target, bound) = self.parse_binding_target_at()?;
            first_bound = bound;
            target
        } else {
            self.parse_expr_no_in()?
        };
        if self.is_kw("of") || self.is_kw("in") {
            // `for ({ a = 1 } of xs)`: the head is a pattern.
            self.cover_init.clear();
        }
        if self.eat_kw("of") {
            let iter = self.parse_assign()?;
            self.expect_punct(")")?;
            let body = Box::new(self.parse_sub_stmt(false)?);
            return Ok(StmtKind::ForOf {
                decl_kind,
                target: first_target,
                iter,
                body,
                is_await,
            });
        }
        if self.eat_kw("in") {
            let object = self.parse_assign()?;
            self.expect_punct(")")?;
            let body = Box::new(self.parse_sub_stmt(false)?);
            return Ok(StmtKind::ForIn {
                decl_kind,
                target: first_target,
                object,
                body,
            });
        }
        // C-style: reconstruct the init statement.
        let init_stmt = if let Some(k) = decl_kind {
            let init = if self.eat_punct("=") {
                Some(self.parse_assign()?)
            } else {
                None
            };
            let mut decls = vec![Declarator {
                target: first_target,
                init,
                bound: first_bound,
            }];
            while self.eat_punct(",") {
                let (target, bound) = self.parse_binding_target_at()?;
                let init = if self.eat_punct("=") {
                    Some(self.parse_assign()?)
                } else {
                    None
                };
                decls.push(Declarator {
                    target,
                    init,
                    bound,
                });
            }
            // `for (let a, b of …)` / `for (let a = 1 of …)` are for-of headers
            // that carry more than a bare binding.
            if self.is_kw("of") {
                return Err(if decls.len() > 1 {
                    "SyntaxError: Invalid left-hand side in for-of loop: Must have a single binding."
                } else {
                    "SyntaxError: for-of loop variable declaration may not have an initializer."
                }
                .to_string());
            }
            StmtKind::Decl { kind: k, decls }
        } else {
            // A non-declaration C-style init may be a comma sequence
            // (`for (i = 0, n = a.length; …)`) — extend past the first assignment.
            let init = if self.is_punct(",") {
                let mut items = vec![first_target];
                while self.eat_punct(",") {
                    items.push(self.parse_expr_no_in()?);
                }
                Expr::Sequence(items)
            } else {
                first_target
            };
            StmtKind::Expr(init)
        };
        self.parse_c_for(Some(Stmt::from(init_stmt)))
    }

    fn parse_c_for(&mut self, init: Option<Stmt>) -> Result<StmtKind, String> {
        self.expect_punct(";")?;
        let test = if self.is_punct(";") {
            None
        } else {
            Some(self.parse_expr()?)
        };
        self.expect_punct(";")?;
        let update = if self.is_punct(")") {
            None
        } else {
            Some(self.parse_expr()?)
        };
        self.expect_punct(")")?;
        let body = Box::new(self.parse_sub_stmt(false)?);
        Ok(StmtKind::For {
            init: init.map(Box::new),
            test,
            update,
            body,
        })
    }

    fn parse_switch(&mut self) -> Result<StmtKind, String> {
        self.advance();
        self.expect_punct("(")?;
        let disc = self.parse_expr()?;
        self.expect_punct(")")?;
        self.expect_punct("{")?;
        let mut cases = Vec::new();
        while !self.is_punct("}") && !self.at_eof() {
            let test = if self.eat_kw("case") {
                let e = self.parse_expr()?;
                Some(e)
            } else if self.eat_kw("default") {
                None
            } else {
                return Err(self.unexpected());
            };
            self.expect_punct(":")?;
            let mut body = Vec::new();
            while !self.is_punct("}")
                && !self.is_kw("case")
                && !self.is_kw("default")
                && !self.at_eof()
            {
                body.push(self.parse_stmt()?);
            }
            cases.push(SwitchCase { test, body });
        }
        self.expect_punct("}")?;
        Ok(StmtKind::Switch { disc, cases })
    }

    fn parse_try(&mut self) -> Result<StmtKind, String> {
        self.advance();
        self.expect_punct("{")?;
        let block = self.parse_block_body()?;
        let handler = if self.eat_kw("catch") {
            let param = if self.eat_punct("(") {
                let p = self.parse_binding_target()?;
                self.expect_punct(")")?;
                Some(p)
            } else {
                None
            };
            self.expect_punct("{")?;
            let body = self.parse_block_body()?;
            Some((param, body))
        } else {
            None
        };
        let finalizer = if self.eat_kw("finally") {
            self.expect_punct("{")?;
            Some(self.parse_block_body()?)
        } else {
            None
        };
        Ok(StmtKind::Try {
            block,
            handler,
            finalizer,
        })
    }

    // ── expressions ──────────────────────────────────────────────────────
    /// Full expression, including the comma sequence operator.
    fn parse_expr(&mut self) -> Result<Expr, String> {
        let first = self.parse_assign()?;
        if self.is_punct(",") {
            let mut items = vec![first];
            while self.eat_punct(",") {
                items.push(self.parse_assign()?);
            }
            Ok(Expr::Sequence(items))
        } else {
            Ok(first)
        }
    }

    /// Like `parse_expr` but stops before `in` (used in `for` init position).
    fn parse_expr_no_in(&mut self) -> Result<Expr, String> {
        // For simplicity the no-in variant only parses an assignment/LHS chain,
        // which is sufficient for `for (x in ...)` / `for (x of ...)` heads.
        let saved = self.no_in;
        self.no_in = true;
        let r = self.parse_assign();
        self.no_in = saved;
        r
    }

    /// Whether `e` is an optional chain — i.e. its member/call SPINE carries a
    /// `?.` link. Mirrors the compiler's spine walk; used only to decide
    /// whether a set of parentheses is a chain boundary worth recording.
    fn has_optional_link(e: &Expr) -> bool {
        match e {
            Expr::Member {
                object, optional, ..
            } => *optional || Self::has_optional_link(object),
            Expr::Index {
                object, optional, ..
            } => *optional || Self::has_optional_link(object),
            Expr::Call { func, optional, .. } => *optional || Self::has_optional_link(func),
            _ => false,
        }
    }

    /// Run `f` with `in` re-enabled (inside a parenthesised/bracketed sub-
    /// expression of a `for` LHS, where the no-in restriction does not apply).
    fn allow_in<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
        let saved = self.no_in;
        self.no_in = false;
        let r = f(self);
        self.no_in = saved;
        r
    }

    /// `yield [no LineTerminator here] [*] [expr]` (15.5): a YieldExpression is
    /// an AssignmentExpression, so nothing binds to it from the right — `yield
    /// * 2` is a bare `yield` and then a stray `*`.
    fn parse_yield(&mut self) -> Result<Expr, String> {
        self.advance(); // yield
        let delegate = !self.newline_before() && self.eat_punct("*");
        // `yield` with no argument (before `)`, `]`, `}`, `,`, `;`, `:`,
        // newline, or EOF).
        let arg = if delegate
            || !(self.is_punct(")")
                || self.is_punct("]")
                || self.is_punct("}")
                || self.is_punct(",")
                || self.is_punct(";")
                || self.is_punct(":")
                || self.newline_before()
                || self.at_eof())
        {
            Some(Box::new(self.parse_assign()?))
        } else {
            None
        };
        Ok(Expr::Yield { arg, delegate })
    }

    fn parse_assign(&mut self) -> Result<Expr, String> {
        if self.in_generator && self.is_kw("yield") {
            return self.parse_yield();
        }
        // Arrow function detection.
        if let Some(arrow) = self.try_parse_arrow()? {
            return Ok(arrow);
        }
        let start = self.pos;
        let left = self.parse_conditional()?;
        // Assignment operators (right-associative).
        let op = match self.tok() {
            Tok::Punct(p) => p.clone(),
            _ => return Ok(left),
        };
        // `{ a = 1 } = v`: the shorthand initialisers just parsed belong to a
        // pattern, so they are defaults and not an error.
        if op == "=" {
            // A parenthesised literal is a value, never a pattern (13.15.1):
            // `({ a }) = 1` and `([a]) = 1` are early errors, where `(a) = 1` is
            // fine.
            if matches!(left, Expr::Object(_) | Expr::Array(_))
                && matches!(&self.toks[start].tok, Tok::Punct(p) if p == "(")
                && self.matching_paren(start) == Some(self.pos - 1)
            {
                return Err("SyntaxError: Invalid left-hand side in assignment".to_string());
            }
            self.cover_init.retain(|&(at, ..)| at < start);
        }
        let compound = match op.as_str() {
            "=" => None,
            "+=" => Some(BinOp::Add),
            "-=" => Some(BinOp::Sub),
            "*=" => Some(BinOp::Mul),
            "/=" => Some(BinOp::Div),
            "%=" => Some(BinOp::Mod),
            "**=" => Some(BinOp::Pow),
            "&=" => Some(BinOp::BitAnd),
            "|=" => Some(BinOp::BitOr),
            "^=" => Some(BinOp::BitXor),
            "<<=" => Some(BinOp::Shl),
            ">>=" => Some(BinOp::Shr),
            ">>>=" => Some(BinOp::UShr),
            "&&=" | "||=" | "??=" => {
                // Logical assignment. The operator is CARRIED, not desugared:
                // building `Logical(op, left.clone(), value)` here duplicated
                // the target, so `o[k()] ||= 1` evaluated `k` twice — once for
                // the read and once for the write — where node evaluates it
                // once and may not write at all.
                self.advance();
                let value = self.parse_assign()?;
                let lop = match op.as_str() {
                    "&&=" => LogicalOp::And,
                    "||=" => LogicalOp::Or,
                    _ => LogicalOp::Nullish,
                };
                return Ok(Expr::Assign {
                    target: Box::new(left),
                    op: Some(AssignOp::Logical(lop)),
                    value: Box::new(value),
                });
            }
            _ => return Ok(left),
        };
        self.advance();
        let value = self.outside_binding(Self::parse_assign)?;
        Ok(Expr::Assign {
            target: Box::new(left),
            op: compound.map(AssignOp::Binary),
            value: Box::new(value),
        })
    }

    fn parse_conditional(&mut self) -> Result<Expr, String> {
        let test = self.parse_binary(0)?;
        if self.eat_punct("?") {
            let cons = self.parse_assign()?;
            self.expect_punct(":")?;
            let alt = self.parse_assign()?;
            Ok(Expr::Conditional {
                test: Box::new(test),
                cons: Box::new(cons),
                alt: Box::new(alt),
            })
        } else {
            Ok(test)
        }
    }

    /// Precedence-climbing binary parser. Handles `&& || ??` as logical nodes.
    fn parse_binary(&mut self, min_prec: u8) -> Result<Expr, String> {
        let mut left = self.parse_unary()?;
        // The logical operator that built `left` in THIS loop. A parenthesised
        // operand arrives from `parse_unary` and is None, which is what makes
        // `(a || b) ?? c` legal while `a || b ?? c` is not (13.12).
        let mut left_logical: Option<LogicalOp> = None;
        while let Some((prec, right_assoc, logical, bin)) = self.bin_info() {
            if prec < min_prec {
                break;
            }
            if let Some(lop) = logical {
                let nullish = |o: LogicalOp| matches!(o, LogicalOp::Nullish);
                if left_logical.is_some_and(|l| nullish(l) != nullish(lop)) {
                    return Err(self.unexpected());
                }
            }
            self.advance();
            // `??` takes BitwiseOR-level operands (prec 4), never `||`/`&&`.
            let next_min = match logical {
                Some(LogicalOp::Nullish) => 4,
                _ if right_assoc => prec,
                _ => prec + 1,
            };
            let right = self.parse_binary(next_min)?;
            left_logical = logical;
            left = if let Some(lop) = logical {
                Expr::Logical(lop, Box::new(left), Box::new(right))
            } else {
                Expr::Binary(bin.unwrap(), Box::new(left), Box::new(right))
            };
        }
        Ok(left)
    }

    /// `(precedence, right_assoc, logical_op, bin_op)` for the current token.
    fn bin_info(&self) -> Option<(u8, bool, Option<LogicalOp>, Option<BinOp>)> {
        let p = match self.tok() {
            Tok::Punct(p) => p.as_str(),
            // In a `for` LHS (no-in) context, `in` is the loop separator, not a
            // relational operator.
            Tok::Ident(s) if s == "in" => {
                if self.no_in {
                    return None;
                }
                "in"
            }
            Tok::Ident(s) if s == "instanceof" => "instanceof",
            _ => return None,
        };
        let (prec, ra, log, bin) = match p {
            "??" => (1, false, Some(LogicalOp::Nullish), None),
            "||" => (2, false, Some(LogicalOp::Or), None),
            "&&" => (3, false, Some(LogicalOp::And), None),
            "|" => (4, false, None, Some(BinOp::BitOr)),
            "^" => (5, false, None, Some(BinOp::BitXor)),
            "&" => (6, false, None, Some(BinOp::BitAnd)),
            "==" => (7, false, None, Some(BinOp::EqEq)),
            "!=" => (7, false, None, Some(BinOp::NeEq)),
            "===" => (7, false, None, Some(BinOp::EqEqEq)),
            "!==" => (7, false, None, Some(BinOp::NeEqEq)),
            "<" => (8, false, None, Some(BinOp::Lt)),
            "<=" => (8, false, None, Some(BinOp::Le)),
            ">" => (8, false, None, Some(BinOp::Gt)),
            ">=" => (8, false, None, Some(BinOp::Ge)),
            "in" => (8, false, None, Some(BinOp::In)),
            "instanceof" => (8, false, None, Some(BinOp::InstanceOf)),
            "<<" => (9, false, None, Some(BinOp::Shl)),
            ">>" => (9, false, None, Some(BinOp::Shr)),
            ">>>" => (9, false, None, Some(BinOp::UShr)),
            "+" => (10, false, None, Some(BinOp::Add)),
            "-" => (10, false, None, Some(BinOp::Sub)),
            "*" => (11, false, None, Some(BinOp::Mul)),
            "/" => (11, false, None, Some(BinOp::Div)),
            "%" => (11, false, None, Some(BinOp::Mod)),
            "**" => (12, true, None, Some(BinOp::Pow)),
            _ => return None,
        };
        Some((prec, ra, log, bin))
    }

    /// Reject a `**` directly after a just-parsed UnaryExpression. JS only
    /// allows an UpdateExpression there (`x++ ** y` and `++x ** y` are fine),
    /// so an unparenthesized `-x ** y` / `typeof x ** y` / `await x ** y` is a
    /// SyntaxError rather than a silently-reassociated `-(x ** y)`.
    fn reject_unary_before_pow(&mut self) -> Result<(), String> {
        if self.is_punct("**") {
            return Err("SyntaxError: Unary operator used immediately before \
                 exponentiation expression. Parenthesis must be used to \
                 disambiguate operator precedence"
                .to_string());
        }
        Ok(())
    }

    fn parse_unary(&mut self) -> Result<Expr, String> {
        let op = match self.tok() {
            Tok::Punct(p) if p == "!" => Some(UnOp::Not),
            Tok::Punct(p) if p == "~" => Some(UnOp::BitNot),
            Tok::Punct(p) if p == "+" => Some(UnOp::Pos),
            Tok::Punct(p) if p == "-" => Some(UnOp::Neg),
            Tok::Ident(s) if s == "typeof" => Some(UnOp::TypeOf),
            Tok::Ident(s) if s == "void" => Some(UnOp::Void),
            Tok::Ident(s) if s == "delete" => Some(UnOp::Delete),
            _ => None,
        };
        if let Some(op) = op {
            self.advance();
            let e = self.parse_unary()?;
            // `ExponentiationExpression : UpdateExpression ** …` — a
            // UnaryExpression on the left of `**` is a SyntaxError, so
            // `-x ** y` must be written `(-x) ** y` or `-(x ** y)`.
            self.reject_unary_before_pow()?;
            return Ok(Expr::Unary(op, Box::new(e)));
        }
        // Prefix ++/--.
        if self.is_punct("++") || self.is_punct("--") {
            let op = if self.is_punct("++") {
                UpdateOp::Inc
            } else {
                UpdateOp::Dec
            };
            self.advance();
            let e = self.parse_unary()?;
            return Ok(Expr::Update {
                op,
                prefix: true,
                target: Box::new(e),
            });
        }
        self.parse_postfix()
    }

    fn parse_postfix(&mut self) -> Result<Expr, String> {
        let mut e = self.parse_call_member()?;
        // Postfix ++/-- (no line break before).
        if (self.is_punct("++") || self.is_punct("--")) && !self.newline_before() {
            let op = if self.is_punct("++") {
                UpdateOp::Inc
            } else {
                UpdateOp::Dec
            };
            self.advance();
            e = Expr::Update {
                op,
                prefix: false,
                target: Box::new(e),
            };
        }
        Ok(e)
    }

    fn parse_call_member(&mut self) -> Result<Expr, String> {
        let new_pos = self.pos_here();
        let mut e = if self.eat_kw("new") {
            // `new.target` meta-property.
            if self.is_punct(".") {
                self.advance();
                let prop = self.ident_name()?;
                if prop != "target" {
                    return Err(self.unexpected());
                }
                Expr::NewTarget
            } else {
                let callee = self.parse_call_member_no_call()?;
                // An optional chain cannot be the callee of `new` (13.3.5.1):
                // `new a?.b()` and `new C?.()` are early errors. Parenthesising
                // the chain ends it, so `new (a?.b)()` is legal — which is why
                // the check is on the callee's own spine, and the parenthesised
                // form records a chain boundary that clears `optional`.
                if Self::has_optional_link(&callee) || self.is_punct("?.") {
                    return Err(
                        "SyntaxError: Invalid optional chain from new expression".to_string()
                    );
                }
                let args = if self.is_punct("(") {
                    self.parse_args()?
                } else {
                    Vec::new()
                };
                Expr::New {
                    callee: Box::new(callee),
                    args,
                    pos: new_pos,
                }
            }
        } else {
            self.parse_primary()?
        };
        loop {
            if self.eat_punct(".") {
                let pos = self.pos_here();
                let property = self.ident_name()?;
                self.check_private_in_scope(&property)?;
                e = Expr::Member {
                    object: Box::new(e),
                    property,
                    optional: false,
                    pos,
                };
            } else if self.eat_punct("?.") {
                if matches!(self.tok(), Tok::Template { .. }) {
                    return Err(
                        "SyntaxError: Invalid tagged template on optional chain".to_string()
                    );
                }
                if self.is_punct("(") {
                    let pos = self.call_pos();
                    let args = self.parse_args()?;
                    e = Expr::Call {
                        func: Box::new(e),
                        args,
                        optional: true,
                        pos,
                    };
                } else if self.is_punct("[") {
                    let pos = self.pos_here();
                    self.advance();
                    let index = self.allow_in(|p| p.parse_expr())?;
                    self.expect_punct("]")?;
                    e = Expr::Index {
                        object: Box::new(e),
                        index: Box::new(index),
                        optional: true,
                        pos,
                    };
                } else {
                    let pos = self.pos_here();
                    let property = self.ident_name()?;
                    e = Expr::Member {
                        object: Box::new(e),
                        property,
                        optional: true,
                        pos,
                    };
                }
            } else if self.is_punct("[") {
                let pos = self.pos_here();
                self.advance();
                let index = self.allow_in(|p| p.parse_expr())?;
                self.expect_punct("]")?;
                e = Expr::Index {
                    object: Box::new(e),
                    index: Box::new(index),
                    optional: false,
                    pos,
                };
            } else if self.is_punct("(") {
                let pos = self.call_pos();
                let args = self.parse_args()?;
                e = Expr::Call {
                    func: Box::new(e),
                    args,
                    optional: false,
                    pos,
                };
            } else if matches!(self.tok(), Tok::Template { .. }) {
                // A template literal immediately after a callee is a *tagged*
                // template: `` tag`...` `` → `tag(strings, ...values)`.
                // A tagged template cannot sit on an optional chain (13.3.11.1):
                // `a?.b`t`` is an early error, because the tag would have to be
                // called even when the chain short-circuited.
                if Self::has_optional_link(&e) {
                    return Err(
                        "SyntaxError: Invalid tagged template on optional chain".to_string()
                    );
                }
                e = self.parse_tagged_template(e)?;
            } else {
                break;
            }
        }
        Ok(e)
    }

    /// Parse `` tag`a${x}b` `` into a `TaggedTemplate` node (the tag expression is
    /// already parsed as `tag`, and the current token is the template).
    fn parse_tagged_template(&mut self, tag: Expr) -> Result<Expr, String> {
        let (quasis, raws, exprs_src, expr_at) = match self.tok().clone() {
            Tok::Template {
                quasis,
                raws,
                exprs,
                expr_at,
            } => (quasis, raws, exprs, expr_at),
            _ => unreachable!(),
        };
        self.advance();
        let mut exprs = Vec::new();
        for (src, at) in exprs_src.iter().zip(expr_at) {
            exprs.push(self.parse_field(src, at)?);
        }
        Ok(Expr::TaggedTemplate {
            tag: Box::new(tag),
            quasis,
            raws,
            exprs,
        })
    }

    /// Member chain without a trailing call — the `new X.Y` callee grammar.
    fn parse_call_member_no_call(&mut self) -> Result<Expr, String> {
        let mut e = self.parse_primary()?;
        loop {
            if self.eat_punct(".") {
                let pos = self.pos_here();
                let property = self.ident_name()?;
                self.check_private_in_scope(&property)?;
                e = Expr::Member {
                    object: Box::new(e),
                    property,
                    optional: false,
                    pos,
                };
            } else if self.is_punct("[") {
                let pos = self.pos_here();
                self.advance();
                let index = self.allow_in(|p| p.parse_expr())?;
                self.expect_punct("]")?;
                e = Expr::Index {
                    object: Box::new(e),
                    index: Box::new(index),
                    optional: false,
                    pos,
                };
            } else {
                break;
            }
        }
        Ok(e)
    }

    fn parse_args(&mut self) -> Result<Vec<Expr>, String> {
        self.expect_punct("(")?;
        // Inside a call-argument list `in` is always a relational operator, even
        // in a `for` LHS.
        let args = self.allow_in(|p| {
            let mut args = Vec::new();
            while !p.is_punct(")") {
                if p.eat_punct("...") {
                    let e = p.parse_assign()?;
                    args.push(Expr::Spread(Box::new(e)));
                } else {
                    args.push(p.parse_assign()?);
                }
                if !p.eat_punct(",") {
                    break;
                }
            }
            Ok(args)
        })?;
        // V8 reserves its own wording for a call whose argument list does not
        // close, whatever token stopped it (`f(1 2)`, `f(`).
        if !self.eat_punct(")") {
            return Err("SyntaxError: missing ) after argument list".to_string());
        }
        Ok(args)
    }

    fn parse_primary(&mut self) -> Result<Expr, String> {
        match self.tok().clone() {
            Tok::Num(n) => {
                self.check_legacy()?;
                self.advance();
                Ok(Expr::Number(n))
            }
            Tok::BigInt(s) => {
                self.advance();
                Ok(Expr::BigInt(s))
            }
            Tok::Regex(pat, flags) => {
                // A regex LITERAL's flags and pattern are early errors (13.2.7.3),
                // reported before anything in the program runs.
                crate::regexp::check_literal(&pat, &flags)?;
                self.advance();
                Ok(Expr::Regex(pat, flags))
            }
            Tok::Str(s) => {
                self.check_legacy()?;
                self.advance();
                Ok(Expr::Str(s))
            }
            Tok::Template {
                quasis,
                raws: _,
                exprs,
                expr_at,
            } => {
                self.advance();
                let mut parsed = Vec::new();
                for (src, at) in exprs.iter().zip(expr_at) {
                    parsed.push(self.parse_field(src, at)?);
                }
                Ok(Expr::Template {
                    quasis,
                    exprs: parsed,
                })
            }
            Tok::Punct(p) if p == "(" => {
                self.advance();
                let e = self.parse_expr()?;
                self.expect_punct(")")?;
                // Parentheses are otherwise erased, but around an OPTIONAL CHAIN
                // they are load-bearing: they END the chain, so a `?.` inside
                // them cannot short-circuit an access written outside them.
                // `o?.a.b` is `undefined` when `o` is nullish; `(o?.a).b` reads
                // `.b` off that `undefined` and THROWS (ECMA-262 13.3.1 —
                // `ParenthesizedExpression` is not an `OptionalExpression`).
                // With the parentheses dropped the two parsed to the same tree
                // and both answered `undefined`.
                //
                // The boundary is spelled as a one-element sequence rather than
                // a new node type: `(e)` and `e,` evaluate identically, every
                // existing pass already walks `Sequence` correctly, and the
                // chain-spine walk does not descend through it — which is the
                // whole point. Only chains are wrapped, so no other expression's
                // tree shape changes.
                if Self::has_optional_link(&e) {
                    return Ok(Expr::Sequence(vec![e]));
                }
                Ok(e)
            }
            Tok::Punct(p) if p == "[" => self.parse_array_literal(),
            Tok::Punct(p) if p == "{" => self.parse_object_literal(),
            Tok::Ident(s) => {
                match s.as_str() {
                    "true" => {
                        self.advance();
                        Ok(Expr::True)
                    }
                    "false" => {
                        self.advance();
                        Ok(Expr::False)
                    }
                    "null" => {
                        self.advance();
                        Ok(Expr::Null)
                    }
                    "this" => {
                        self.advance();
                        Ok(Expr::This)
                    }
                    "super" => {
                        if !self.super_ok {
                            return Err("SyntaxError: 'super' keyword unexpected here".to_string());
                        }
                        self.advance();
                        Ok(Expr::Super)
                    }
                    "class" => Ok(Expr::Class(Box::new(self.parse_class(false)?))),
                    "function" => self.parse_function_expr(false),
                    "async" if self.peek_kw(1, "function") && !self.peek_newline(1) => {
                        self.advance(); // async
                        self.parse_function_expr(true)
                    }
                    // `yield` in a generator is an AssignmentExpression and is
                    // parsed by `parse_assign`; reaching it here means it sat
                    // where only a higher-precedence operand may (`a + yield`).
                    "yield" if self.in_generator => Err(self.unexpected()),
                    // `import(…)` (ImportCall) is left as a call of the name
                    // `import`, which the module lowering and the compiler
                    // recognise; `import.meta` is a meta property that only the
                    // Module goal has (16.2.1.1).
                    "import" if self.peek_punct_at(1, ".") => {
                        self.advance(); // import
                        self.advance(); // .
                        if !self.is_kw("meta") {
                            return Err(self.unexpected());
                        }
                        if !self.module {
                            return Err("SyntaxError: Cannot use 'import.meta' outside a module"
                                .to_string());
                        }
                        self.advance(); // meta
                        Ok(Expr::Member {
                            object: Box::new(Expr::Ident("import".into())),
                            property: "meta".into(),
                            optional: false,
                            pos: 0,
                        })
                    }
                    "import" if !self.peek_punct_at(1, "(") => Err(self.unexpected()),
                    "await" if self.in_async => {
                        let pos = self.pos_here();
                        self.advance();
                        let e = self.parse_unary()?;
                        // An AwaitExpression is a UnaryExpression, so it too
                        // cannot sit directly left of `**`.
                        self.reject_unary_before_pow()?;
                        Ok(Expr::Await(Box::new(e), pos))
                    }
                    _ if is_keyword(&s) => Err(self.unexpected()),
                    // The future-reserved words are not identifiers in strict code.
                    "implements" | "interface" | "package" | "private" | "protected" | "public"
                    | "static" | "yield"
                        if self.strict =>
                    {
                        Err("SyntaxError: Unexpected strict mode reserved word".to_string())
                    }
                    _ => {
                        if self.in_binding {
                            self.bound_at.push((s.clone(), self.pos_here()));
                        }
                        self.advance();
                        Ok(Expr::Ident(s))
                    }
                }
            }
            _ => Err(self.unexpected()),
        }
    }

    fn parse_array_literal(&mut self) -> Result<Expr, String> {
        self.expect_punct("[")?;
        let mut items = Vec::new();
        while !self.is_punct("]") {
            if self.is_punct(",") {
                // Elision: the element is a HOLE, not a stored `undefined`.
                items.push(Expr::Hole);
                self.advance();
                continue;
            }
            if self.eat_punct("...") {
                let e = self.parse_assign()?;
                items.push(Expr::Spread(Box::new(e)));
            } else {
                items.push(self.parse_assign()?);
            }
            if !self.eat_punct(",") {
                break;
            }
        }
        self.expect_punct("]")?;
        Ok(Expr::Array(items))
    }

    fn parse_object_literal(&mut self) -> Result<Expr, String> {
        self.expect_punct("{")?;
        let mut props = Vec::new();
        let mut proto_seen = false;
        while !self.is_punct("}") {
            if self.eat_punct("...") {
                let e = self.parse_assign()?;
                props.push(Prop::Spread(e));
                if !self.eat_punct(",") {
                    break;
                }
                continue;
            }
            // `get key() {}` / `set key(v) {}` accessor (contextual: `get`/`set`
            // is a modifier only when followed by another key, not `:`/`(`/`,`).
            if (self.is_kw("get") || self.is_kw("set"))
                && !self.peek_is_member_punct(1)
                && !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
            {
                let is_getter = self.is_kw("get");
                let start = self.start_at(self.pos);
                self.advance();
                let (key, computed) = self.parse_property_key()?;
                let params = self.parse_params()?;
                check_accessor_arity(
                    if is_getter {
                        MemberKind::Get
                    } else {
                        MemberKind::Set
                    },
                    &params,
                )?;
                self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
                self.expect_punct("{")?;
                let body = self.with_super(true, |p| p.parse_fn_body_block(false, false))?;
                let func = Expr::Function {
                    params,
                    body: FnBody::Block(body),
                    is_arrow: false,
                    name: None,
                    is_generator: false,
                    is_async: false,
                    is_method: true,
                    span: self.span_from(start),
                };
                props.push(Prop::Accessor {
                    key,
                    computed,
                    is_getter,
                    func,
                });
                if !self.eat_punct(",") {
                    break;
                }
                continue;
            }
            // Concise-method modifiers: `async` and/or `*` before the key.
            let mut m_async = false;
            let mut m_gen = false;
            let start = self.start_at(self.pos);
            if self.is_kw("async")
                && !self.peek_is_member_punct(1)
                && !self.peek_newline(1)
                && !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
            {
                self.advance();
                m_async = true;
            }
            if self.is_punct("*") {
                self.advance();
                m_gen = true;
            }
            let key_pos = self.pos_here();
            let (key, computed) = self.parse_property_key()?;
            // Method shorthand `key(params) { }` (incl. `*gen(){}`, `async m(){}`).
            if self.is_punct("(") {
                let params = self.parse_params()?;
                self.check_params(&params, self.leading_use_strict(self.pos + 1), true)?;
                self.expect_punct("{")?;
                let body = self.with_super(true, |p| p.parse_fn_body_block(m_gen, m_async))?;
                let f = Expr::Function {
                    params,
                    body: FnBody::Block(body),
                    is_arrow: false,
                    name: None,
                    is_generator: m_gen,
                    is_async: m_async,
                    is_method: true,
                    span: self.span_from(start),
                };
                props.push(Prop::KeyValue {
                    key,
                    value: f,
                    computed,
                });
            } else if self.eat_punct(":") {
                // 13.2.5.1: a second `__proto__: v` in one literal is an early error
                // (the shorthand and method forms do not set the prototype).
                if !computed && matches!(&key, Expr::Str(k) if k == "__proto__") {
                    if proto_seen {
                        return Err(
                            "SyntaxError: Duplicate __proto__ fields are not allowed in object literals"
                                .to_string(),
                        );
                    }
                    proto_seen = true;
                }
                let value = self.parse_assign()?;
                props.push(Prop::KeyValue {
                    key,
                    value,
                    computed,
                });
            } else {
                // Shorthand `{ x }` -> key "x", value ident x. Or with default
                // in a destructuring pattern: `{ x = 1 }`.
                let name = match &key {
                    Expr::Str(s) => s.clone(),
                    _ => return Err(format!("SyntaxError: bad shorthand (line {})", self.line())),
                };
                if self.in_binding {
                    self.bound_at.push((name.clone(), key_pos));
                }
                let value = if self.is_punct("=") {
                    let eq = self.pos;
                    self.advance();
                    // Pattern default; represent as Assign so destructuring reads it.
                    let d = self.outside_binding(Self::parse_assign)?;
                    if !self.in_binding {
                        let end = if self.spans {
                            self.toks[self.pos - 1].end + 1
                        } else {
                            0
                        };
                        self.cover_init.push((eq, key_pos, end));
                    }
                    Expr::Assign {
                        target: Box::new(Expr::Ident(name.clone())),
                        op: None,
                        value: Box::new(d),
                    }
                } else {
                    Expr::Ident(name)
                };
                props.push(Prop::KeyValue {
                    key,
                    value,
                    computed,
                });
            }
            if !self.eat_punct(",") {
                break;
            }
        }
        self.expect_punct("}")?;
        Ok(Expr::Object(props))
    }

    // ── functions / arrows ───────────────────────────────────────────────
    fn parse_params(&mut self) -> Result<Vec<Param>, String> {
        self.expect_punct("(")?;
        let mut params = Vec::new();
        while !self.is_punct(")") {
            let rest = self.eat_punct("...");
            let pattern = self.parse_binding_target()?;
            let default = if !rest && self.eat_punct("=") {
                Some(self.parse_assign()?)
            } else {
                None
            };
            params.push(Param {
                pattern,
                default,
                rest,
            });
            if !self.eat_punct(",") {
                break;
            }
        }
        self.expect_punct(")")?;
        Ok(params)
    }

    /// Try to parse an arrow function starting at the current position. Returns
    /// `None` (without consuming) if the head is not an arrow.
    fn try_parse_arrow(&mut self) -> Result<Option<Expr>, String> {
        let start = self.start_at(self.pos);
        // `async` prefix on an arrow (`async x => …` / `async (…) => …`), only
        // when `async` is not itself the parameter and no newline intervenes.
        let mut is_async = false;
        let mut base = self.pos;
        if self.is_kw("async") && !self.peek_newline(1) {
            let next = self.toks.get(self.pos + 1).map(|t| &t.tok);
            let looks_async_arrow = matches!(next, Some(Tok::Punct(p)) if p == "(")
                || matches!(next, Some(Tok::Ident(n)) if !is_keyword(n) && self.peek_is_arrow_after(2));
            if looks_async_arrow {
                is_async = true;
                base += 1;
            }
        }
        // `ident => ...`
        if let Some(Tok::Ident(name)) = self.toks.get(base).map(|t| &t.tok) {
            if !is_keyword(name)
                && matches!(self.toks.get(base + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
            {
                let name = name.clone();
                if is_async {
                    self.advance(); // async
                }
                self.advance(); // ident
                self.advance(); // =>
                let body = self.parse_arrow_body(is_async)?;
                return Ok(Some(Expr::Function {
                    params: vec![Param {
                        pattern: Expr::Ident(name),
                        default: None,
                        rest: false,
                    }],
                    body,
                    is_arrow: true,
                    name: None,
                    is_generator: false,
                    is_async,
                    is_method: false,
                    span: self.span_from(start),
                }));
            }
        }
        // `( ... ) => ...`
        if matches!(self.toks.get(base).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "(") {
            if let Some(close) = self.matching_paren(base) {
                let after = close + 1;
                if matches!(self.toks.get(after).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
                {
                    if is_async {
                        self.advance(); // async
                    }
                    let params = self.parse_params()?;
                    self.check_params(&params, false, true)?;
                    self.expect_punct("=>")?;
                    let body = self.parse_arrow_body(is_async)?;
                    return Ok(Some(Expr::Function {
                        params,
                        body,
                        is_arrow: true,
                        name: None,
                        is_generator: false,
                        is_async,
                        is_method: false,
                        span: self.span_from(start),
                    }));
                }
            }
        }
        Ok(None)
    }

    fn parse_arrow_body(&mut self, is_async: bool) -> Result<FnBody, String> {
        let (pg, pa) = (self.in_generator, self.in_async);
        self.in_generator = false;
        self.in_async = is_async;
        let outer_labels = std::mem::take(&mut self.labels);
        let outer_strict = self.strict;
        let outer_in_function = std::mem::replace(&mut self.in_function, true);
        let r = if self.is_punct("{") {
            self.advance();
            self.strict = outer_strict || self.leading_use_strict(self.pos);
            self.parse_block_body().map(FnBody::Block)
        } else {
            self.parse_assign().map(|e| FnBody::Expr(Box::new(e)))
        };
        self.in_function = outer_in_function;
        self.strict = outer_strict;
        self.labels = outer_labels;
        self.in_generator = pg;
        self.in_async = pa;
        r
    }

    /// Whether the token `n` positions ahead is `=>`.
    fn peek_is_arrow_after(&self, n: usize) -> bool {
        matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
    }

    /// Index of the `)` matching the `(` at `open`, skipping nested brackets.
    fn matching_paren(&self, open: usize) -> Option<usize> {
        let mut depth = 0i32;
        let mut i = open;
        while i < self.toks.len() {
            match &self.toks[i].tok {
                Tok::Punct(p) if p == "(" || p == "[" || p == "{" => depth += 1,
                Tok::Punct(p) if p == ")" || p == "]" || p == "}" => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(i);
                    }
                }
                Tok::Eof => return None,
                _ => {}
            }
            i += 1;
        }
        None
    }
}

/// A parser over a template-literal `${...}` field's raw source. `base` is the
/// field's byte offset in the enclosing script, so the spans recorded inside it
/// index that script; `None` records none.
fn field_parser(src: &str, base: Option<u32>) -> Result<Parser, String> {
    let mut toks = lex(src)?;
    for t in &mut toks {
        t.start += base.unwrap_or(0);
        t.end += base.unwrap_or(0);
        if let Tok::Template { expr_at, .. } = &mut t.tok {
            for at in expr_at {
                *at += base.unwrap_or(0);
            }
        }
    }
    Ok(Parser {
        toks,
        pos: 0,
        in_generator: false,
        in_async: false,
        no_in: false,
        class_scopes: Vec::new(),
        labels: Vec::new(),
        strict: false,
        super_ok: false,
        in_function: true,
        cover_init: Vec::new(),
        in_binding: false,
        bound_at: Vec::new(),
        spans: base.is_some(),
        module: false,
    })
}