bun_js_parser 0.1.1

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
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
#![allow(clippy::single_match)]
#![warn(unused_must_use)]
use bun_collections::VecExt;
use bun_core::{self, err};

use crate::lexer as js_lexer;
use crate::p::P;
use bun_ast as js_ast;

use js_ast::op::Level;
use js_ast::{Expr, G, LocRef, S, Stmt};
use js_lexer::T;

use crate::parser::fs;
use crate::parser::{
    AwaitOrYield, DeferredTsDecorators, LexicalDecl, ParseStatementOptions, ParsedPath, Ref,
    StmtList,
};
use crate::typescript;
use bun_ast::{ImportKind, ImportRecordFlags, ImportRecordTag};
use js_ast::expr::EFlags;

// TODO(port): narrow error set
type Result<T> = core::result::Result<T, bun_core::Error>;

// Zig: `pub fn ParseStmt(comptime ts, comptime jsx, comptime scan_only) type { return struct {...} }`
// — file-split mixin pattern. Round-C lowered `const JSX: JSXTransformType` → `J: JsxT`, so this is
// a direct `impl P` block. The 25+ per-token `t_*` helpers are private; only `parse_stmt` is
// surfaced. Round-G un-gated the simpler `t_*` bodies; phase-d ported the remaining
// `t_export`/`t_import`/fallthrough bodies inline (the `_draft_heavy` staging mod is gone).

impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_ONLY> {
    // PORT NOTE on `#[inline]` / `#[inline(never)]` / `#[cold]` annotations across the `t_*` arms:
    // `parse_stmt` is invoked once per leading statement token; profiling showed its
    // stack-adjust prologue/epilogue dominating because LLVM was hoisting the larger
    // (and rarely-taken) `t_*` bodies inline, ballooning `parse_stmt`'s frame. Keep the
    // rare / heavy arms out-of-line so `parse_stmt` stays a thin dispatcher, and fold the
    // trivial forwarders in so the `parse_stmts_up_to → parse_stmt → t_* → parse_*` chain
    // loses a hop on the hot statements (`;`, `function`, `var`, `const`, `return`, …).
    //
    // `P` is monomorphized over `(TYPESCRIPT, SCAN_ONLY)` (JSX is a runtime field, not a
    // type parameter — see `parser.rs`), so every `#[inline(never)]`
    // `t_*` becomes 2-3 sibling symbols that the linker would otherwise interleave with the
    // hot ones. Anything that can't fire on a plain `bun run` of a `.js`/`.ts` script — the
    // TS-only keyword forms (`enum`, `@decorator`, `type`/`namespace`/`module`/`declare`),
    // `with` (illegal in strict/module code), `do … while`, `debugger`, and `label:` — is
    // additionally `#[cold]` so LLVM parks all of those instantiations together in
    // `.text.unlikely`, leaving the bytes that actually execute on startup dense instead of
    // spread across sibling monomorphizations that fault-around drags in.

    #[inline]
    fn t_semicolon(p: &mut Self) -> Result<Stmt> {
        p.lexer.next()?;
        Ok(Stmt::empty())
    }

    #[inline]
    fn t_function(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        p.lexer.next()?;
        p.parse_fn_stmt(loc, opts, None)
    }

    #[cold]
    #[inline(never)]
    fn t_enum(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        if !Self::IS_TYPESCRIPT_ENABLED {
            p.lexer.unexpected()?;
            return Err(err!("SyntaxError"));
        }
        p.parse_typescript_enum_stmt(loc, opts)
    }

    #[cold]
    #[inline(never)]
    fn t_at(p: &mut Self, opts: &mut ParseStatementOptions<'a>) -> Result<Stmt> {
        // Parse decorators before class statements, which are potentially exported
        if Self::IS_TYPESCRIPT_ENABLED || p.options.features.standard_decorators {
            let scope_index = p.scopes_in_order.len();
            let ts_decorators = p.parse_type_script_decorators()?;

            // If this turns out to be a "declare class" statement, we need to undo the
            // scopes that were potentially pushed while parsing the decorator arguments.
            // That can look like any one of the following:
            //
            //   "@decorator declare class Foo {}"
            //   "@decorator declare abstract class Foo {}"
            //   "@decorator export declare class Foo {}"
            //   "@decorator export declare abstract class Foo {}"
            //
            // PORT NOTE: spec stores the Vec<Expr> directly into `opts.ts_decorators.values`.
            // `DeferredTsDecorators::values` is currently typed `&'a [Expr]` (parser.rs), so until
            // that field is widened to `ExprNodeList` we copy into the arena (Expr is `Copy`) and
            // let `ts_decorators` drop normally — no `mem::forget` / `from_raw_parts` lifetime
            // laundering (forbidden per PORTING.md §Forbidden patterns).
            let ts_decorators_slice: &'a [Expr] = p.arena.alloc_slice_copy(ts_decorators.slice());
            opts.ts_decorators = Some(DeferredTsDecorators {
                values: ts_decorators_slice,
                scope_index,
            });

            // "@decorator class Foo {}"
            // "@decorator abstract class Foo {}"
            // "@decorator declare class Foo {}"
            // "@decorator declare abstract class Foo {}"
            // "@decorator export class Foo {}"
            // "@decorator export abstract class Foo {}"
            // "@decorator export declare class Foo {}"
            // "@decorator export declare abstract class Foo {}"
            // "@decorator export default class Foo {}"
            // "@decorator export default abstract class Foo {}"
            if p.lexer.token != T::TClass
                && p.lexer.token != T::TExport
                && !(Self::IS_TYPESCRIPT_ENABLED && p.lexer.is_contextual_keyword(b"abstract"))
                && !(Self::IS_TYPESCRIPT_ENABLED && p.lexer.is_contextual_keyword(b"declare"))
            {
                p.lexer.expected(T::TClass)?;
            }

            return p.parse_stmt(opts);
        }
        // notimpl();

        p.lexer.unexpected()?;
        Err(err!("SyntaxError"))
    }

    #[inline(never)]
    fn t_class(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        if opts.lexical_decl != LexicalDecl::AllowAll {
            p.forbid_lexical_decl(loc)?;
        }

        p.parse_class_stmt(loc, opts)
    }

    #[inline]
    fn t_var(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        p.lexer.next()?;
        let decls = p.parse_and_declare_decls(js_ast::symbol::Kind::Hoisted, opts)?;
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(
            S::Local {
                kind: js_ast::s::Kind::KVar,
                decls,
                is_export: opts.is_export,
                ..Default::default()
            },
            loc,
        ))
    }

    #[inline]
    fn t_const(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        if opts.lexical_decl != LexicalDecl::AllowAll {
            p.forbid_lexical_decl(loc)?;
        }
        // p.markSyntaxFeature(compat.Const, p.lexer.Range())

        p.lexer.next()?;

        if Self::IS_TYPESCRIPT_ENABLED && p.lexer.token == T::TEnum {
            return p.parse_typescript_enum_stmt(loc, opts);
        }

        let decls = p.parse_and_declare_decls(js_ast::symbol::Kind::Constant, opts)?;
        p.lexer.expect_or_insert_semicolon()?;

        if !opts.is_typescript_declare {
            p.require_initializers(js_ast::s::Kind::KConst, decls.slice())?;
        }

        Ok(p.s(
            S::Local {
                kind: js_ast::s::Kind::KConst,
                decls,
                is_export: opts.is_export,
                ..Default::default()
            },
            loc,
        ))
    }

    #[inline(never)]
    fn t_if(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        let mut current_loc = loc;
        let mut root_if: Option<Stmt> = None;
        // PORT NOTE: `StoreRef` (arena back-pointer with safe `Deref`/`DerefMut`)
        // into the previous iteration's `S::If` allocation — borrowck cannot
        // express the cross-iteration back-reference, but the arena keeps every
        // node alive for `'a`.
        let mut current_if: Option<js_ast::StoreRef<S::If>> = None;

        loop {
            p.lexer.next()?;
            p.lexer.expect(T::TOpenParen)?;
            let test_ = p.parse_expr(Level::Lowest)?;
            p.lexer.expect(T::TCloseParen)?;
            let mut stmt_opts = ParseStatementOptions {
                lexical_decl: LexicalDecl::AllowFnInsideIf,
                ..Default::default()
            };
            let yes = p.parse_stmt(&mut stmt_opts)?;

            // Create the if node
            let if_stmt = p.s(
                S::If {
                    test_,
                    yes,
                    no: None,
                },
                current_loc,
            );

            // First if statement becomes root
            if root_if.is_none() {
                root_if = Some(if_stmt);
            }

            // Link to previous if statement's else branch
            if let Some(mut prev_if) = current_if {
                // `StoreRef` `DerefMut` — arena-allocated S::If from prior iteration.
                prev_if.no = Some(if_stmt);
            }

            // Set current if for next iteration. The S::If was just allocated via Stmt::alloc;
            // recover its arena handle through the StmtData payload.
            current_if = match if_stmt.data {
                js_ast::StmtData::SIf(s_if) => Some(s_if),
                _ => unreachable!(),
            };

            if p.lexer.token != T::TElse {
                return Ok(root_if.unwrap());
            }

            p.lexer.next()?;

            // Handle final else
            if p.lexer.token != T::TIf {
                stmt_opts = ParseStatementOptions {
                    lexical_decl: LexicalDecl::AllowFnInsideIf,
                    ..Default::default()
                };
                // current_if was set just above in this iteration; `StoreRef` `DerefMut`.
                let no = p.parse_stmt(&mut stmt_opts)?;
                let mut cur = current_if.unwrap();
                cur.no = Some(no);
                return Ok(root_if.unwrap());
            }

            // Continue with else if
            current_loc = p.lexer.loc();
        }
    }

    #[cold]
    #[inline(never)]
    fn t_do(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        let mut stmt_opts = ParseStatementOptions::default();
        let body = p.parse_stmt(&mut stmt_opts)?;
        p.lexer.expect(T::TWhile)?;
        p.lexer.expect(T::TOpenParen)?;
        let test_ = p.parse_expr(Level::Lowest)?;
        p.lexer.expect(T::TCloseParen)?;

        // This is a weird corner case where automatic semicolon insertion applies
        // even without a newline present
        if p.lexer.token == T::TSemicolon {
            p.lexer.next()?;
        }
        Ok(p.s(S::DoWhile { body, test_ }, loc))
    }

    #[inline(never)]
    fn t_while(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;

        p.lexer.expect(T::TOpenParen)?;
        let test_ = p.parse_expr(Level::Lowest)?;
        p.lexer.expect(T::TCloseParen)?;

        let mut stmt_opts = ParseStatementOptions::default();
        let body = p.parse_stmt(&mut stmt_opts)?;

        Ok(p.s(S::While { body, test_ }, loc))
    }

    #[cold]
    #[inline(never)]
    fn t_with(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        p.lexer.expect(T::TOpenParen)?;
        let test_ = p.parse_expr(Level::Lowest)?;
        let body_loc = p.lexer.loc();
        p.lexer.expect(T::TCloseParen)?;

        // Push a scope so we make sure to prevent any bare identifiers referenced
        // within the body from being renamed. Renaming them might change the
        // semantics of the code.
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::With, body_loc)?;
        let mut stmt_opts = ParseStatementOptions::default();
        let body = p.parse_stmt(&mut stmt_opts)?;
        p.pop_scope();

        Ok(p.s(
            S::With {
                body,
                body_loc,
                value: test_,
            },
            loc,
        ))
    }

    #[inline(never)]
    fn t_switch(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;

        p.lexer.expect(T::TOpenParen)?;
        let test_ = p.parse_expr(Level::Lowest)?;
        p.lexer.expect(T::TCloseParen)?;

        let body_loc = p.lexer.loc();
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, body_loc)?;
        // Zig: `defer p.popScope()`. Wrap the body in an inner closure so `pop_scope` runs once on
        // its `Result`, covering every `?` early-exit as well as explicit returns.
        let result: Result<Stmt> = (|| {
            p.lexer.expect(T::TOpenBrace)?;
            let mut cases = bun_alloc::ArenaVec::<js_ast::Case>::new_in(p.arena);
            let mut found_default = false;
            while p.lexer.token != T::TCloseBrace {
                let mut body = StmtList::new_in(p.arena);
                // PORT NOTE: Zig hoisted `value`/`stmt_opts` above the loop;
                // both are reinitialized every iteration before any read, so
                // declare per-iteration.
                let mut value: Option<js_ast::Expr> = None;
                if p.lexer.token == T::TDefault {
                    if found_default {
                        p.log().add_range_error(
                            Some(p.source),
                            p.lexer.range(),
                            b"Multiple default clauses are not allowed",
                        );
                        return Err(err!("SyntaxError"));
                    }

                    found_default = true;
                    p.lexer.next()?;
                    p.lexer.expect(T::TColon)?;
                } else {
                    p.lexer.expect(T::TCase)?;
                    value = Some(p.parse_expr(Level::Lowest)?);
                    p.lexer.expect(T::TColon)?;
                }

                'case_body: loop {
                    match p.lexer.token {
                        T::TCloseBrace | T::TCase | T::TDefault => {
                            break 'case_body;
                        }
                        _ => {
                            let mut stmt_opts = ParseStatementOptions {
                                lexical_decl: LexicalDecl::AllowAll,
                                ..Default::default()
                            };
                            body.push(p.parse_stmt(&mut stmt_opts)?);
                        }
                    }
                }
                cases.push(js_ast::Case {
                    value,
                    body: bun_ast::StoreSlice::from_bump(body),
                    loc: bun_ast::Loc::EMPTY,
                });
            }
            p.lexer.expect(T::TCloseBrace)?;
            Ok(p.s(
                S::Switch {
                    test_,
                    body_loc,
                    cases: bun_ast::StoreSlice::from_bump(cases),
                },
                loc,
            ))
        })();
        p.pop_scope();
        result
    }

    #[inline(never)]
    fn t_try(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        let body_loc = p.lexer.loc();
        p.lexer.expect(T::TOpenBrace)?;
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, loc)?;
        let mut stmt_opts = ParseStatementOptions::default();
        let body = p.parse_stmts_up_to(T::TCloseBrace, &mut stmt_opts)?;
        p.pop_scope();
        p.lexer.next()?;

        let mut catch_: Option<js_ast::Catch> = None;
        let mut finally: Option<js_ast::Finally> = None;

        if p.lexer.token == T::TCatch {
            let catch_loc = p.lexer.loc();
            let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::CatchBinding, catch_loc)?;
            p.lexer.next()?;
            let mut binding: Option<js_ast::Binding> = None;

            // The catch binding is optional, and can be omitted
            if p.lexer.token != T::TOpenBrace {
                p.lexer.expect(T::TOpenParen)?;
                let mut value = p.parse_binding(Default::default())?;

                // Skip over types
                if Self::IS_TYPESCRIPT_ENABLED && p.lexer.token == T::TColon {
                    p.lexer.expect(T::TColon)?;
                    p.skip_type_script_type(Level::Lowest)?;
                }

                p.lexer.expect(T::TCloseParen)?;

                // Bare identifiers are a special case
                let kind = match value.data {
                    js_ast::b::B::BIdentifier(_) => js_ast::symbol::Kind::CatchIdentifier,
                    _ => js_ast::symbol::Kind::Other,
                };
                p.declare_binding(kind, &mut value, &stmt_opts)?;
                binding = Some(value);
            }

            let catch_body_loc = p.lexer.loc();
            p.lexer.expect(T::TOpenBrace)?;

            let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, catch_body_loc)?;
            let stmts = p.parse_stmts_up_to(T::TCloseBrace, &mut stmt_opts)?;
            p.pop_scope();
            p.lexer.next()?;
            catch_ = Some(js_ast::Catch {
                loc: catch_loc,
                binding,
                body: bun_ast::StoreSlice::from_bump(stmts),
                body_loc: catch_body_loc,
            });
            p.pop_scope();
        }

        if p.lexer.token == T::TFinally || catch_.is_none() {
            let finally_loc = p.lexer.loc();
            let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, finally_loc)?;
            p.lexer.expect(T::TFinally)?;
            p.lexer.expect(T::TOpenBrace)?;
            let stmts = p.parse_stmts_up_to(T::TCloseBrace, &mut stmt_opts)?;
            p.lexer.next()?;
            finally = Some(js_ast::Finally {
                loc: finally_loc,
                stmts: bun_ast::StoreSlice::from_bump(stmts),
            });
            p.pop_scope();
        }

        Ok(p.s(
            S::Try {
                body_loc,
                body: bun_ast::StoreSlice::from_bump(body),
                catch_,
                finally,
            },
            loc,
        ))
    }

    #[inline(never)]
    fn t_for(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, loc)?;
        // Zig: `defer p.popScope()`. Wrap the body in an inner closure so `pop_scope` runs once on
        // its `Result`, covering every `?` early-exit as well as explicit returns.
        let result: Result<Stmt> = (|| {
            p.lexer.next()?;

            // "for await (let x of y) {}"
            let mut is_for_await = p.lexer.is_contextual_keyword(b"await");
            if is_for_await {
                let await_range = p.lexer.range();
                if p.fn_or_arrow_data_parse.allow_await != AwaitOrYield::AllowExpr {
                    p.log().add_range_error(
                        Some(p.source),
                        await_range,
                        b"Cannot use \"await\" outside an async function",
                    );
                    is_for_await = false;
                } else {
                    // TODO: improve error handling here
                    //                 didGenerateError := p.markSyntaxFeature(compat.ForAwait, awaitRange)
                    if p.fn_or_arrow_data_parse.is_top_level {
                        p.top_level_await_keyword = await_range;
                        // p.markSyntaxFeature(compat.TopLevelAwait, awaitRange)
                    }
                }
                p.lexer.next()?;
            }

            p.lexer.expect(T::TOpenParen)?;

            let mut init_: Option<Stmt> = None;
            let mut test_: Option<Expr> = None;
            let mut update: Option<Expr> = None;

            // "in" expressions aren't allowed here
            p.allow_in = false;

            let mut bad_let_range: Option<bun_ast::Range> = None;
            if p.lexer.is_contextual_keyword(b"let") {
                bad_let_range = Some(p.lexer.range());
            }

            // Track the decl slice separately so we can reference it after `decls` is moved into
            // an arena-backed S::Local. The Vec's heap buffer stays put across the move; the
            // arena outlives this fn, so the lifetime-erased view remains valid.
            let mut decls_ptr: bun_ast::StoreSlice<G::Decl> = bun_ast::StoreSlice::EMPTY;
            let init_loc = p.lexer.loc();
            let mut is_var = false;
            match p.lexer.token {
                // for (var )
                T::TVar => {
                    is_var = true;
                    p.lexer.next()?;
                    let mut stmt_opts = ParseStatementOptions::default();
                    let decls =
                        p.parse_and_declare_decls(js_ast::symbol::Kind::Hoisted, &mut stmt_opts)?;
                    decls_ptr = bun_ast::StoreSlice::new(decls.slice());
                    init_ = Some(p.s(
                        S::Local {
                            kind: js_ast::s::Kind::KVar,
                            decls,
                            ..Default::default()
                        },
                        init_loc,
                    ));
                }
                // for (const )
                T::TConst => {
                    p.lexer.next()?;
                    let mut stmt_opts = ParseStatementOptions::default();
                    let decls =
                        p.parse_and_declare_decls(js_ast::symbol::Kind::Constant, &mut stmt_opts)?;
                    decls_ptr = bun_ast::StoreSlice::new(decls.slice());
                    init_ = Some(p.s(
                        S::Local {
                            kind: js_ast::s::Kind::KConst,
                            decls,
                            ..Default::default()
                        },
                        init_loc,
                    ));
                }
                // for (;)
                T::TSemicolon => {}
                _ => {
                    let mut stmt_opts = ParseStatementOptions {
                        lexical_decl: LexicalDecl::AllowAll,
                        is_for_loop_init: true,
                        ..Default::default()
                    };

                    let res = p.parse_expr_or_let_stmt(&mut stmt_opts)?;
                    match res.stmt_or_expr {
                        js_ast::StmtOrExpr::Stmt(stmt) => {
                            bad_let_range = None;
                            // Keep the "let"/"using" declarations visible to the for-in/for-of
                            // checks below ("forbid_initializers"), like the "var"/"const" arms.
                            decls_ptr = bun_ast::StoreSlice::new(res.decls.slice());
                            init_ = Some(stmt);
                        }
                        js_ast::StmtOrExpr::Expr(expr) => {
                            init_ = Some(p.s(
                                S::SExpr {
                                    value: expr,
                                    ..Default::default()
                                },
                                init_loc,
                            ));
                        }
                    }
                }
            }

            // "in" expressions are allowed again
            p.allow_in = true;

            // Detect for-of loops
            if p.lexer.is_contextual_keyword(b"of") || is_for_await {
                if let Some(r) = bad_let_range {
                    p.log().add_range_error(
                        Some(p.source),
                        r,
                        b"\"let\" must be wrapped in parentheses to be used as an expression here",
                    );
                    return Err(err!("SyntaxError"));
                }

                if is_for_await && !p.lexer.is_contextual_keyword(b"of") {
                    if init_.is_some() {
                        p.lexer.expected_string(b"\"of\"")?;
                    } else {
                        p.lexer.unexpected()?;
                        return Err(err!("SyntaxError"));
                    }
                }

                p.forbid_initializers(decls_ptr.slice(), "of", false)?;
                p.lexer.next()?;
                let value = p.parse_expr(Level::Comma)?;
                p.lexer.expect(T::TCloseParen)?;
                let mut stmt_opts = ParseStatementOptions::default();
                let body = p.parse_stmt(&mut stmt_opts)?;
                return Ok(p.s(
                    S::ForOf {
                        is_await: is_for_await,
                        init: init_.unwrap(),
                        value,
                        body,
                    },
                    loc,
                ));
            }

            // Detect for-in loops
            if p.lexer.token == T::TIn {
                p.forbid_initializers(decls_ptr.slice(), "in", is_var)?;
                p.lexer.next()?;
                let value = p.parse_expr(Level::Lowest)?;
                p.lexer.expect(T::TCloseParen)?;
                let mut stmt_opts = ParseStatementOptions::default();
                let body = p.parse_stmt(&mut stmt_opts)?;
                return Ok(p.s(
                    S::ForIn {
                        init: init_.unwrap(),
                        value,
                        body,
                    },
                    loc,
                ));
            }

            // Only require "const" statement initializers when we know we're a normal for loop
            if let Some(init_stmt) = &init_ {
                match &init_stmt.data {
                    js_ast::StmtData::SLocal(local) => {
                        if local.kind == js_ast::s::Kind::KConst {
                            p.require_initializers(js_ast::s::Kind::KConst, decls_ptr.slice())?;
                        }
                    }
                    _ => {}
                }
            }

            p.lexer.expect(T::TSemicolon)?;
            if p.lexer.token != T::TSemicolon {
                test_ = Some(p.parse_expr(Level::Lowest)?);
            }

            p.lexer.expect(T::TSemicolon)?;

            if p.lexer.token != T::TCloseParen {
                update = Some(p.parse_expr(Level::Lowest)?);
            }

            p.lexer.expect(T::TCloseParen)?;
            let mut stmt_opts = ParseStatementOptions::default();
            let body = p.parse_stmt(&mut stmt_opts)?;
            Ok(p.s(
                S::For {
                    init: init_,
                    test_,
                    update,
                    body,
                },
                loc,
            ))
        })();
        p.pop_scope();
        result
    }

    #[inline]
    fn t_break(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        let name = p.parse_label_name()?;
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(S::Break { label: name }, loc))
    }

    #[inline]
    fn t_continue(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        let name = p.parse_label_name()?;
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(S::Continue { label: name }, loc))
    }

    #[inline]
    fn t_return(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        if p.fn_or_arrow_data_parse.is_return_disallowed {
            p.log().add_range_error(
                Some(p.source),
                p.lexer.range(),
                b"A return statement cannot be used here",
            );
        }
        p.lexer.next()?;
        let mut value: Option<Expr> = None;
        if p.lexer.token != T::TSemicolon
            && !p.lexer.has_newline_before
            && p.lexer.token != T::TCloseBrace
            && p.lexer.token != T::TEndOfFile
        {
            value = Some(p.parse_expr(Level::Lowest)?);
        }
        p.latest_return_had_semicolon = p.lexer.token == T::TSemicolon;
        p.lexer.expect_or_insert_semicolon()?;

        Ok(p.s(S::Return { value }, loc))
    }

    #[inline]
    fn t_throw(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        if p.lexer.has_newline_before {
            p.log().add_error(
                Some(p.source),
                bun_ast::Loc {
                    start: loc.start + 5,
                },
                b"Unexpected newline after \"throw\"",
            );
            return Err(err!("SyntaxError"));
        }
        let expr = p.parse_expr(Level::Lowest)?;
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(S::Throw { value: expr }, loc))
    }

    #[cold]
    #[inline(never)]
    fn t_debugger(p: &mut Self, _: &mut ParseStatementOptions, loc: bun_ast::Loc) -> Result<Stmt> {
        p.lexer.next()?;
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(S::Debugger {}, loc))
    }

    #[inline(never)]
    fn t_open_brace(
        p: &mut Self,
        _: &mut ParseStatementOptions,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Block, loc)?;
        // Zig: `defer p.popScope()`. Wrap the body in an inner closure so `pop_scope` runs once on
        // its `Result`, covering every `?` early-exit.
        let result: Result<Stmt> = (|| {
            p.lexer.next()?;
            let mut stmt_opts = ParseStatementOptions::default();
            let stmts = p.parse_stmts_up_to(T::TCloseBrace, &mut stmt_opts)?;
            let close_brace_loc = p.lexer.loc();
            p.lexer.next()?;
            Ok(p.s(
                S::Block {
                    stmts: bun_ast::StoreSlice::from_bump(stmts),
                    close_brace_loc,
                },
                loc,
            ))
        })();
        p.pop_scope();
        result
    }

    // ─── heavy bodies still blocked ──────────────────────────────────────────
    #[inline(never)]
    fn t_export(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        let previous_export_keyword = p.esm_export_keyword;
        if opts.is_module_scope {
            p.esm_export_keyword = p.lexer.range();
        } else if !opts.is_namespace_scope {
            p.lexer.unexpected()?;
            return Err(err!("SyntaxError"));
        }
        p.lexer.next()?;

        // TypeScript decorators only work on class declarations
        // "@decorator export class Foo {}"
        // "@decorator export abstract class Foo {}"
        // "@decorator export default class Foo {}"
        // "@decorator export default abstract class Foo {}"
        // "@decorator export declare class Foo {}"
        // "@decorator export declare abstract class Foo {}"
        if opts.ts_decorators.is_some()
            && p.lexer.token != T::TClass
            && p.lexer.token != T::TDefault
            && !p.lexer.is_contextual_keyword(b"abstract")
            && !p.lexer.is_contextual_keyword(b"declare")
        {
            p.lexer.expected(T::TClass)?;
        }

        match p.lexer.token {
            T::TClass | T::TConst | T::TFunction | T::TVar => {
                opts.is_export = true;
                p.parse_stmt(opts)
            }

            T::TImport => {
                // "export import foo = bar"
                if Self::IS_TYPESCRIPT_ENABLED && (opts.is_module_scope || opts.is_namespace_scope)
                {
                    opts.is_export = true;
                    return p.parse_stmt(opts);
                }

                p.lexer.unexpected()?;
                Err(err!("SyntaxError"))
            }

            T::TEnum => {
                if !Self::IS_TYPESCRIPT_ENABLED {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                opts.is_export = true;
                p.parse_stmt(opts)
            }

            T::TIdentifier => {
                if p.lexer.is_contextual_keyword(b"let") {
                    opts.is_export = true;
                    return p.parse_stmt(opts);
                }

                if Self::IS_TYPESCRIPT_ENABLED {
                    if opts.is_typescript_declare && p.lexer.is_contextual_keyword(b"as") {
                        // "export as namespace ns;"
                        p.lexer.next()?;
                        p.lexer.expect_contextual_keyword(b"namespace")?;
                        p.lexer.expect(T::TIdentifier)?;
                        p.lexer.expect_or_insert_semicolon()?;

                        return Ok(p.s(S::TypeScript {}, loc));
                    }
                }

                if p.lexer.is_contextual_keyword(b"async") {
                    let async_range = p.lexer.range();
                    p.lexer.next()?;
                    if p.lexer.has_newline_before {
                        p.log().add_range_error(
                            Some(p.source),
                            async_range,
                            b"Unexpected newline after \"async\"",
                        );
                    }

                    p.lexer.expect(T::TFunction)?;
                    opts.is_export = true;
                    return p.parse_fn_stmt(loc, opts, Some(async_range));
                }

                if Self::IS_TYPESCRIPT_ENABLED {
                    use typescript::identifier::StmtIdentifier;
                    if let Some(ident) = typescript::identifier::for_str(p.lexer.identifier) {
                        match ident {
                            StmtIdentifier::SType => {
                                // "export type foo = ..."
                                let type_range = p.lexer.range();
                                p.lexer.next()?;
                                if p.lexer.has_newline_before {
                                    p.log().add_error_fmt(
                                        Some(p.source),
                                        type_range.end(),
                                        format_args!("Unexpected newline after \"type\""),
                                    );
                                    return Err(err!("SyntaxError"));
                                }
                                let mut skipper = ParseStatementOptions {
                                    is_module_scope: opts.is_module_scope,
                                    is_export: true,
                                    ..Default::default()
                                };
                                p.skip_type_script_type_stmt(&mut skipper)?;
                                return Ok(p.s(S::TypeScript {}, loc));
                            }
                            StmtIdentifier::SNamespace
                            | StmtIdentifier::SAbstract
                            | StmtIdentifier::SModule
                            | StmtIdentifier::SInterface => {
                                // "export namespace Foo {}"
                                // "export abstract class Foo {}"
                                // "export module Foo {}"
                                // "export interface Foo {}"
                                opts.is_export = true;
                                return p.parse_stmt(opts);
                            }
                            StmtIdentifier::SDeclare => {
                                // "export declare class Foo {}"
                                opts.is_export = true;
                                opts.lexical_decl = LexicalDecl::AllowAll;
                                opts.is_typescript_declare = true;
                                return p.parse_stmt(opts);
                            }
                        }
                    }
                }

                p.lexer.unexpected()?;
                Err(err!("SyntaxError"))
            }

            T::TDefault => {
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                let default_loc = p.lexer.loc();
                p.lexer.next()?;

                // TypeScript decorators only work on class declarations
                // "@decorator export default class Foo {}"
                // "@decorator export default abstract class Foo {}"
                if opts.ts_decorators.is_some()
                    && p.lexer.token != T::TClass
                    && !p.lexer.is_contextual_keyword(b"abstract")
                {
                    p.lexer.expected(T::TClass)?;
                }

                if p.lexer.is_contextual_keyword(b"async") {
                    let async_range = p.lexer.range();
                    p.lexer.next()?;
                    if p.lexer.token == T::TFunction && !p.lexer.has_newline_before {
                        p.lexer.next()?;
                        let mut stmt_opts = ParseStatementOptions {
                            is_name_optional: true,
                            lexical_decl: LexicalDecl::AllowAll,
                            ..Default::default()
                        };
                        let stmt = p.parse_fn_stmt(loc, &mut stmt_opts, Some(async_range))?;
                        if matches!(stmt.data, js_ast::StmtData::STypeScript(_)) {
                            // This was just a type annotation
                            return Ok(stmt);
                        }

                        let default_name = if let Some(func) = stmt.data.s_function() {
                            if let Some(name) = func.func.name {
                                LocRef {
                                    loc: name.loc,
                                    ref_: name.ref_,
                                }
                            } else {
                                p.create_default_name(default_loc)?
                            }
                        } else {
                            p.create_default_name(default_loc)?
                        };

                        let value = js_ast::StmtOrExpr::Stmt(stmt);
                        return Ok(p.s(
                            S::ExportDefault {
                                default_name,
                                value,
                            },
                            loc,
                        ));
                    }

                    let default_name = p.create_default_name(loc)?;

                    let mut expr = p.parse_async_prefix_expr(async_range, Level::Comma)?;
                    p.parse_suffix(&mut expr, Level::Comma, None, EFlags::None)?;
                    p.lexer.expect_or_insert_semicolon()?;
                    let value = js_ast::StmtOrExpr::Expr(expr);
                    p.has_export_default = true;
                    return Ok(p.s(
                        S::ExportDefault {
                            default_name,
                            value,
                        },
                        loc,
                    ));
                }

                if p.lexer.token == T::TFunction
                    || p.lexer.token == T::TClass
                    || p.lexer.is_contextual_keyword(b"interface")
                {
                    let mut _opts = ParseStatementOptions {
                        ts_decorators: opts.ts_decorators.take(),
                        is_name_optional: true,
                        lexical_decl: LexicalDecl::AllowAll,
                        ..Default::default()
                    };
                    let stmt = p.parse_stmt(&mut _opts)?;

                    let default_name: LocRef = 'default_name_getter: {
                        match &stmt.data {
                            // This was just a type annotation
                            js_ast::StmtData::STypeScript(_) => {
                                return Ok(stmt);
                            }

                            js_ast::StmtData::SFunction(func_container) => {
                                if let Some(name) = func_container.func.name {
                                    break 'default_name_getter LocRef {
                                        loc: name.loc,
                                        ref_: name.ref_,
                                    };
                                }
                            }
                            js_ast::StmtData::SClass(class) => {
                                if let Some(name) = class.class.class_name {
                                    break 'default_name_getter LocRef {
                                        loc: name.loc,
                                        ref_: name.ref_,
                                    };
                                }
                            }
                            // "interface" turned out not to start an interface
                            // declaration: the nested statement came back as an
                            // expression statement ("export default interface = 2",
                            // "export default interface => 1") or a labeled statement
                            // ("export default interface: 0"). None of these can be a
                            // default export value, so report a syntax error instead of
                            // building an S.ExportDefault that the visit and print
                            // passes don't support.
                            _ => {
                                let r = js_lexer::range_of_identifier(p.source, stmt.loc);
                                p.log().add_range_error_fmt(
                                    Some(p.source),
                                    r,
                                    format_args!(
                                        "Unexpected \"{}\"",
                                        bstr::BStr::new(p.source.text_for_range(r))
                                    ),
                                );
                                return Err(err!("SyntaxError"));
                            }
                        }

                        p.create_default_name(default_loc).expect("unreachable")
                    };
                    p.has_export_default = true;
                    p.has_es_module_syntax = true;
                    return Ok(p.s(
                        S::ExportDefault {
                            default_name,
                            value: js_ast::StmtOrExpr::Stmt(stmt),
                        },
                        loc,
                    ));
                }

                let is_identifier = p.lexer.token == T::TIdentifier;
                let name = p.lexer.identifier;
                let expr = p.parse_expr(Level::Comma)?;

                // Handle the default export of an abstract class in TypeScript
                if Self::IS_TYPESCRIPT_ENABLED
                    && is_identifier
                    && (p.lexer.token == T::TClass || opts.ts_decorators.is_some())
                    && name == b"abstract"
                    && matches!(expr.data, js_ast::ExprData::EIdentifier(_))
                {
                    let mut stmt_opts = ParseStatementOptions {
                        ts_decorators: opts.ts_decorators.take(),
                        is_name_optional: true,
                        ..Default::default()
                    };
                    let stmt: Stmt = p.parse_class_stmt(loc, &mut stmt_opts)?;

                    // Use the statement name if present, since it's a better name
                    let default_name: LocRef = 'default_name_getter: {
                        match &stmt.data {
                            // This was just a type annotation
                            js_ast::StmtData::STypeScript(_) => {
                                return Ok(stmt);
                            }

                            js_ast::StmtData::SFunction(func_container) => {
                                if let Some(_name) = func_container.func.name {
                                    break 'default_name_getter LocRef {
                                        loc: default_loc,
                                        ref_: _name.ref_,
                                    };
                                }
                            }
                            js_ast::StmtData::SClass(class) => {
                                if let Some(_name) = class.class.class_name {
                                    break 'default_name_getter LocRef {
                                        loc: default_loc,
                                        ref_: _name.ref_,
                                    };
                                }
                            }
                            _ => {}
                        }

                        p.create_default_name(default_loc).expect("unreachable")
                    };
                    p.has_export_default = true;
                    return Ok(p.s(
                        S::ExportDefault {
                            default_name,
                            value: js_ast::StmtOrExpr::Stmt(stmt),
                        },
                        loc,
                    ));
                }

                // "@decorator export default abstract = 1"
                if opts.ts_decorators.is_some() {
                    p.lexer.expected(T::TClass)?;
                }

                p.lexer.expect_or_insert_semicolon()?;

                // Use the expression name if present, since it's a better name
                p.has_export_default = true;
                let default_name = p.default_name_for_expr(expr, default_loc);
                Ok(p.s(
                    S::ExportDefault {
                        default_name,
                        value: js_ast::StmtOrExpr::Expr(expr),
                    },
                    loc,
                ))
            }
            T::TAsterisk => {
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                p.lexer.next()?;
                // Both arms below assign exactly once before any read.
                let namespace_ref: Ref;
                let mut alias: Option<G::ExportStarAlias> = None;
                let path: ParsedPath;

                if p.lexer.is_contextual_keyword(b"as") {
                    // "export * as ns from 'path'"
                    p.lexer.next()?;
                    let name = p.parse_clause_alias(b"export")?;
                    namespace_ref = p.store_name_in_ref(name)?;
                    alias = Some(G::ExportStarAlias {
                        loc: p.lexer.loc(),
                        original_name: bun_ast::StoreStr::new(name),
                    });
                    p.lexer.next()?;
                    p.lexer.expect_contextual_keyword(b"from")?;
                    path = p.parse_path()?;
                } else {
                    // "export * from 'path'"
                    p.lexer.expect_contextual_keyword(b"from")?;
                    path = p.parse_path()?;
                    // Zig: `fs.PathName.init(path.text).nonUniqueNameString(arena)` —
                    // sanitize the basename into an identifier and copy into the arena.
                    let name: &'a [u8] = {
                        use std::io::Write as _;
                        let base = fs::PathName::init(path.text).non_unique_name_string_base();
                        let mut buf: Vec<u8> = Vec::new();
                        write!(&mut buf, "{}", bun_core::fmt::fmt_identifier(base))
                            .expect("unreachable");
                        p.arena.alloc_slice_copy(&buf)
                    };
                    namespace_ref = p.store_name_in_ref(name)?;
                }

                let import_record_index = p.add_import_record(
                    ImportKind::Stmt,
                    path.loc,
                    path.text,
                    // TODO: import assertions
                    // path.assertions
                );

                if path.is_macro {
                    p.log().add_error(
                        Some(p.source),
                        path.loc,
                        b"cannot use macro in export statement",
                    );
                } else if path.import_tag != ImportRecordTag::None {
                    p.log().add_error(
                        Some(p.source),
                        loc,
                        b"cannot use export statement with \"type\" attribute",
                    );
                }

                if Self::TRACK_SYMBOL_USAGE_DURING_PARSE_PASS {
                    // In the scan pass, we need _some_ way of knowing *not* to mark as unused
                    p.import_records.items_mut()[import_record_index as usize]
                        .flags
                        .insert(ImportRecordFlags::CALLS_RUNTIME_RE_EXPORT_FN);
                }

                p.lexer.expect_or_insert_semicolon()?;
                p.has_es_module_syntax = true;
                Ok(p.s(
                    S::ExportStar {
                        namespace_ref,
                        alias,
                        import_record_index,
                    },
                    loc,
                ))
            }
            T::TOpenBrace => {
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                let export_clause = p.parse_export_clause()?;
                if p.lexer.is_contextual_keyword(b"from") {
                    p.lexer.expect_contextual_keyword(b"from")?;
                    let parsed_path = p.parse_path()?;

                    p.lexer.expect_or_insert_semicolon()?;

                    if Self::IS_TYPESCRIPT_ENABLED {
                        // export {type Foo} from 'bar';
                        // ->
                        // nothing
                        // https://www.typescriptlang.org/play?useDefineForClassFields=true&esModuleInterop=false&declaration=false&target=99&isolatedModules=false&ts=4.5.4#code/KYDwDg9gTgLgBDAnmYcDeAxCEC+cBmUEAtnAOQBGAhlGQNwBQQA
                        if export_clause.clauses.is_empty() && export_clause.had_type_only_exports {
                            return Ok(p.s(S::TypeScript {}, loc));
                        }
                    }

                    if parsed_path.is_macro {
                        p.log().add_error(
                            Some(p.source),
                            loc,
                            b"export from cannot be used with \"type\": \"macro\"",
                        );
                    } else if parsed_path.import_tag != ImportRecordTag::None {
                        p.log().add_error(
                            Some(p.source),
                            loc,
                            b"export from cannot be used with \"type\" attribute",
                        );
                    }

                    let import_record_index =
                        p.add_import_record(ImportKind::Stmt, parsed_path.loc, parsed_path.text);
                    let path_name = fs::PathName::init(parsed_path.text);
                    // PERF(port): was arena allocPrint — profile if hot.
                    let namespace_ref = {
                        use std::io::Write as _;
                        let mut buf: Vec<u8> = Vec::new();
                        write!(
                            &mut buf,
                            "import_{}",
                            bun_core::fmt::fmt_identifier(path_name.non_unique_name_string_base())
                        )
                        .expect("unreachable");
                        // TODO(port): store_name_in_ref expects arena-owned slice; verify lifetime
                        p.store_name_in_ref(p.arena.alloc_slice_copy(&buf))?
                    };

                    if Self::TRACK_SYMBOL_USAGE_DURING_PARSE_PASS {
                        // In the scan pass, we need _some_ way of knowing *not* to mark as unused
                        p.import_records.items_mut()[import_record_index as usize]
                            .flags
                            .insert(ImportRecordFlags::CALLS_RUNTIME_RE_EXPORT_FN);
                    }
                    p.current_scope_mut().is_after_const_local_prefix = true;
                    p.has_es_module_syntax = true;
                    return Ok(p.s(
                        S::ExportFrom {
                            // SAFETY: sole owner — fresh arena slice from parse_export_clause,
                            // moved into the AST node here; no other &mut alias exists.
                            items: export_clause.clauses.into(),
                            is_single_line: export_clause.is_single_line,
                            namespace_ref,
                            import_record_index,
                        },
                        loc,
                    ));
                }
                p.lexer.expect_or_insert_semicolon()?;

                if Self::IS_TYPESCRIPT_ENABLED {
                    // export {type Foo};
                    // ->
                    // nothing
                    // https://www.typescriptlang.org/play?useDefineForClassFields=true&esModuleInterop=false&declaration=false&target=99&isolatedModules=false&ts=4.5.4#code/KYDwDg9gTgLgBDAnmYcDeAxCEC+cBmUEAtnAOQBGAhlGQNwBQQA
                    if export_clause.clauses.is_empty() && export_clause.had_type_only_exports {
                        return Ok(p.s(S::TypeScript {}, loc));
                    }
                }
                p.has_es_module_syntax = true;
                Ok(p.s(
                    S::ExportClause {
                        // SAFETY: sole owner — fresh arena slice from parse_export_clause,
                        // moved into the AST node here; no other &mut alias exists.
                        items: export_clause.clauses.into(),
                        is_single_line: export_clause.is_single_line,
                    },
                    loc,
                ))
            }
            T::TEquals => {
                // "export = value;"

                p.esm_export_keyword = previous_export_keyword; // This wasn't an ESM export statement after all
                if Self::IS_TYPESCRIPT_ENABLED {
                    p.lexer.next()?;
                    let value = p.parse_expr(Level::Lowest)?;
                    p.lexer.expect_or_insert_semicolon()?;
                    return Ok(p.s(S::ExportEquals { value }, loc));
                }
                p.lexer.unexpected()?;
                Err(err!("SyntaxError"))
            }
            _ => {
                p.lexer.unexpected()?;
                Err(err!("SyntaxError"))
            }
        }
    }

    #[inline(never)]
    fn t_import(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        let previous_import_keyword = p.esm_import_keyword;
        p.esm_import_keyword = p.lexer.range();
        p.lexer.next()?;
        let mut stmt: S::Import = S::Import {
            namespace_ref: Ref::NONE,
            import_record_index: u32::MAX,
            ..Default::default()
        };
        let mut was_originally_bare_import = false;

        // "export import foo = bar"
        if (opts.is_export || (opts.is_namespace_scope && !opts.is_typescript_declare))
            && p.lexer.token != T::TIdentifier
        {
            p.lexer.expected(T::TIdentifier)?;
        }

        match p.lexer.token {
            // "import('path')"
            // "import.meta"
            T::TOpenParen | T::TDot => {
                p.esm_import_keyword = previous_import_keyword; // this wasn't an esm import statement after all
                let mut expr = p.parse_import_expr(loc, Level::Lowest)?;
                p.parse_suffix(&mut expr, Level::Lowest, None, EFlags::None)?;
                p.lexer.expect_or_insert_semicolon()?;
                return Ok(p.s(
                    S::SExpr {
                        value: expr,
                        ..Default::default()
                    },
                    loc,
                ));
            }
            T::TStringLiteral | T::TNoSubstitutionTemplateLiteral => {
                // "import 'path'"
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }
                was_originally_bare_import = true;
            }
            T::TAsterisk => {
                // "import * as ns from 'path'"
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                p.lexer.next()?;
                p.lexer.expect_contextual_keyword(b"as")?;
                stmt = S::Import {
                    namespace_ref: p.store_name_in_ref(p.lexer.identifier)?,
                    star_name_loc: Some(p.lexer.loc()),
                    import_record_index: u32::MAX,
                    ..Default::default()
                };
                p.lexer.expect(T::TIdentifier)?;
                p.lexer.expect_contextual_keyword(b"from")?;
            }
            T::TOpenBrace => {
                // "import {item1, item2} from 'path'"
                if !opts.is_module_scope
                    && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }
                let import_clause = p.parse_import_clause()?;
                if Self::IS_TYPESCRIPT_ENABLED {
                    if import_clause.had_type_only_imports && import_clause.items.is_empty() {
                        p.lexer.expect_contextual_keyword(b"from")?;
                        let _ = p.parse_path()?;
                        p.lexer.expect_or_insert_semicolon()?;
                        return Ok(p.s(S::TypeScript {}, loc));
                    }
                }

                stmt = S::Import {
                    namespace_ref: Ref::NONE,
                    import_record_index: u32::MAX,
                    // SAFETY: sole owner — fresh arena slice from parse_import_clause,
                    // moved into the AST node here; no other &mut alias exists.
                    items: import_clause.items.into(),
                    is_single_line: import_clause.is_single_line,
                    ..Default::default()
                };
                p.lexer.expect_contextual_keyword(b"from")?;
            }
            T::TIdentifier => {
                // "import defaultItem from 'path'"
                // "import foo = bar"
                if !opts.is_module_scope && !opts.is_namespace_scope {
                    p.lexer.unexpected()?;
                    return Err(err!("SyntaxError"));
                }

                let mut default_name = p.lexer.identifier;
                let default_name_raw = p.lexer.raw();
                stmt = S::Import {
                    namespace_ref: Ref::NONE,
                    import_record_index: u32::MAX,
                    default_name: Some(LocRef {
                        loc: p.lexer.loc(),
                        ref_: Some(p.store_name_in_ref(default_name)?),
                    }),
                    ..Default::default()
                };
                p.lexer.next()?;

                // "import defer * as ns from 'path'"
                //
                // https://tc39.es/proposal-defer-import-eval/
                //
                // `defer` is only a phase keyword when followed by `*`; in
                // every other position (`import defer from 'x'`,
                // `import defer, {x} from 'y'`) it is an ordinary default
                // binding named `defer`. Compare the raw token so
                // `def\u0065r` is not treated as the phase keyword.
                //
                // `opts.is_export` rules out `export import defer * as ...`
                // (only reachable via the TypeScript `export import foo = bar`
                // re-entry) so it falls through to the import-equals handler
                // and errors there.
                if default_name_raw == b"defer" && p.lexer.token == T::TAsterisk && !opts.is_export
                {
                    // Same scope restriction as `import * as ns from 'path'`:
                    // ESM import declarations are only valid at module scope
                    // (or inside a TypeScript `declare namespace`).
                    if !opts.is_module_scope
                        && (!opts.is_namespace_scope || !opts.is_typescript_declare)
                    {
                        p.lexer.unexpected()?;
                        return Err(err!("SyntaxError"));
                    }
                    p.lexer.next()?;
                    p.lexer.expect_contextual_keyword(b"as")?;
                    stmt = S::Import {
                        namespace_ref: p.store_name_in_ref(p.lexer.identifier)?,
                        star_name_loc: Some(p.lexer.loc()),
                        import_record_index: u32::MAX,
                        phase_defer: true,
                        ..Default::default()
                    };
                    p.lexer.expect(T::TIdentifier)?;
                    p.lexer.expect_contextual_keyword(b"from")?;

                    let path = p.parse_path()?;
                    p.lexer.expect_or_insert_semicolon()?;
                    return p.process_import_statement(stmt, path, loc, false);
                }

                if Self::IS_TYPESCRIPT_ENABLED {
                    // Skip over type-only imports
                    if default_name == b"type" {
                        match p.lexer.token {
                            T::TIdentifier => {
                                if p.lexer.identifier != b"from" {
                                    default_name = p.lexer.identifier;
                                    stmt.default_name.as_mut().unwrap().loc = p.lexer.loc();
                                    p.lexer.next()?;

                                    if p.lexer.token == T::TEquals {
                                        // "import type foo = require('bar');"
                                        // "import type foo = bar.baz;"
                                        opts.is_typescript_declare = true;
                                        return p.parse_type_script_import_equals_stmt(
                                            loc,
                                            opts,
                                            stmt.default_name.unwrap().loc,
                                            default_name,
                                        );
                                    } else {
                                        // "import type foo from 'bar';"
                                        p.lexer.expect_contextual_keyword(b"from")?;
                                        let _ = p.parse_path()?;
                                        p.lexer.expect_or_insert_semicolon()?;
                                        return Ok(p.s(S::TypeScript {}, loc));
                                    }
                                }
                            }
                            T::TAsterisk => {
                                // "import type * as foo from 'bar';"
                                p.lexer.next()?;
                                p.lexer.expect_contextual_keyword(b"as")?;
                                p.lexer.expect(T::TIdentifier)?;
                                p.lexer.expect_contextual_keyword(b"from")?;
                                let _ = p.parse_path()?;
                                p.lexer.expect_or_insert_semicolon()?;
                                return Ok(p.s(S::TypeScript {}, loc));
                            }

                            T::TOpenBrace => {
                                // "import type {foo} from 'bar';"
                                let _ = p.parse_import_clause()?;
                                p.lexer.expect_contextual_keyword(b"from")?;
                                let _ = p.parse_path()?;
                                p.lexer.expect_or_insert_semicolon()?;
                                return Ok(p.s(S::TypeScript {}, loc));
                            }
                            _ => {}
                        }
                    }

                    // Parse TypeScript import assignment statements
                    if p.lexer.token == T::TEquals
                        || opts.is_export
                        || (opts.is_namespace_scope && !opts.is_typescript_declare)
                    {
                        p.esm_import_keyword = previous_import_keyword; // This wasn't an ESM import statement after all;
                        return p.parse_type_script_import_equals_stmt(
                            loc,
                            opts,
                            bun_ast::Loc::EMPTY,
                            default_name,
                        );
                    }
                }

                if p.lexer.token == T::TComma {
                    p.lexer.next()?;

                    match p.lexer.token {
                        // "import defaultItem, * as ns from 'path'"
                        T::TAsterisk => {
                            p.lexer.next()?;
                            p.lexer.expect_contextual_keyword(b"as")?;
                            stmt.namespace_ref = p.store_name_in_ref(p.lexer.identifier)?;
                            stmt.star_name_loc = Some(p.lexer.loc());
                            p.lexer.expect(T::TIdentifier)?;
                        }
                        // "import defaultItem, {item1, item2} from 'path'"
                        T::TOpenBrace => {
                            let import_clause = p.parse_import_clause()?;

                            // SAFETY: sole owner — fresh arena slice from parse_import_clause,
                            // moved into the AST node here; no other &mut alias exists.
                            stmt.items = import_clause.items.into();
                            stmt.is_single_line = import_clause.is_single_line;
                        }
                        _ => {
                            p.lexer.unexpected()?;
                            return Err(err!("SyntaxError"));
                        }
                    }
                }

                p.lexer.expect_contextual_keyword(b"from")?;
            }
            _ => {
                p.lexer.unexpected()?;
                return Err(err!("SyntaxError"));
            }
        }

        let path = p.parse_path()?;
        p.lexer.expect_or_insert_semicolon()?;

        p.process_import_statement(stmt, path, loc, was_originally_bare_import)
    }

    /// Out-of-line tail for the (uncommon) `label: stmt` form reached from
    /// `parse_stmt_fallthrough`. Keeping the nested `ParseStatementOptions` and the
    /// recursive `parse_stmt` call here keeps `parse_stmt_fallthrough`'s frame small.
    #[cold]
    #[inline(never)]
    fn parse_labeled_stmt(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
        label_loc: bun_ast::Loc,
        label_ref: Ref,
    ) -> Result<Stmt> {
        let _ = p.push_scope_for_parse_pass(js_ast::scope::Kind::Label, loc)?;
        // Zig: `defer p.popScope();` — pop after parsing the labeled body.
        // Hand-roll the defer so we can keep `p` exclusively borrowed.

        // Parse a labeled statement
        p.lexer.next()?;

        let _name = LocRef {
            loc: label_loc,
            ref_: Some(label_ref),
        };
        let mut nested_opts = ParseStatementOptions::default();

        match opts.lexical_decl {
            LexicalDecl::AllowAll | LexicalDecl::AllowFnInsideLabel => {
                nested_opts.lexical_decl = LexicalDecl::AllowFnInsideLabel;
            }
            _ => {}
        }
        let stmt_result = p.parse_stmt(&mut nested_opts);
        p.pop_scope();
        let stmt = stmt_result?;
        Ok(p.s(S::Label { name: _name, stmt }, loc))
    }

    fn parse_stmt_fallthrough(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
    ) -> Result<Stmt> {
        let is_identifier = p.lexer.token == T::TIdentifier;
        let name = p.lexer.identifier;
        // Parse either an async function, an async expression, or a normal expression.
        // Every branch below either assigns `expr` or `return`s.
        let mut expr: Expr;
        if is_identifier && p.lexer.raw() == b"async" {
            let async_range = p.lexer.range();
            p.lexer.next()?;
            if p.lexer.token == T::TFunction && !p.lexer.has_newline_before {
                p.lexer.next()?;

                return p.parse_fn_stmt(async_range.loc, opts, Some(async_range));
            }

            expr = p.parse_async_prefix_expr(async_range, Level::Lowest)?;
            p.parse_suffix(&mut expr, Level::Lowest, None, EFlags::None)?;
        } else {
            let expr_or_let = p.parse_expr_or_let_stmt(opts)?;
            match expr_or_let.stmt_or_expr {
                js_ast::StmtOrExpr::Stmt(stmt) => {
                    p.lexer.expect_or_insert_semicolon()?;
                    return Ok(stmt);
                }
                js_ast::StmtOrExpr::Expr(_expr) => {
                    expr = _expr;
                }
            }
        }
        if is_identifier {
            if let js_ast::ExprData::EIdentifier(ident) = &expr.data {
                if p.lexer.token == T::TColon && !opts.has_decorators() {
                    return Self::parse_labeled_stmt(p, opts, loc, expr.loc, ident.ref_);
                }

                if Self::IS_TYPESCRIPT_ENABLED {
                    if let Some(ts_stmt) = js_lexer::TypescriptStmtKeyword::from_bytes(name) {
                        // Hand the cold TS-keyword statement forms (`type`/`interface`/`namespace`/
                        // `module`/`abstract`/`global`/`declare`) to an out-of-line helper so the
                        // common `SExpr` fall-through keeps a small stack frame.
                        if let Some(stmt) =
                            Self::parse_stmt_fallthrough_ts_keyword(p, opts, loc, ts_stmt)?
                        {
                            return Ok(stmt);
                        }
                    }
                }
            }
        }
        // Output.print("\n\nmVALUE {s}:{s}\n", .{ expr, name });
        p.lexer.expect_or_insert_semicolon()?;
        Ok(p.s(
            S::SExpr {
                value: expr,
                ..Default::default()
            },
            loc,
        ))
    }

    /// Cold TS-only statement keywords reached from `parse_stmt_fallthrough` once the
    /// leading identifier has been recognised as one of the contextual statement keywords.
    /// Returns `Some(stmt)` when the keyword form was consumed; `None` means the caller
    /// should fall through to treating the already-parsed expression as an `SExpr`.
    #[cold]
    #[inline(never)]
    fn parse_stmt_fallthrough_ts_keyword(
        p: &mut Self,
        opts: &mut ParseStatementOptions<'a>,
        loc: bun_ast::Loc,
        ts_stmt: js_lexer::TypescriptStmtKeyword,
    ) -> Result<Option<Stmt>> {
        match ts_stmt {
            js_lexer::TypescriptStmtKeyword::TsStmtType => {
                if p.lexer.token == T::TIdentifier && !p.lexer.has_newline_before {
                    // "type Foo = any"
                    let mut stmt_opts = ParseStatementOptions {
                        is_module_scope: opts.is_module_scope,
                        ..Default::default()
                    };
                    p.skip_type_script_type_stmt(&mut stmt_opts)?;
                    return Ok(Some(p.s(S::TypeScript {}, loc)));
                }
            }
            js_lexer::TypescriptStmtKeyword::TsStmtNamespace
            | js_lexer::TypescriptStmtKeyword::TsStmtModule => {
                // "namespace Foo {}"
                // "module Foo {}"
                // "declare module 'fs' {}"
                // "declare module 'fs';"
                if !p.lexer.has_newline_before
                    && (opts.is_module_scope || opts.is_namespace_scope)
                    && (p.lexer.token == T::TIdentifier
                        || (p.lexer.token == T::TStringLiteral && opts.is_typescript_declare))
                {
                    return Ok(Some(p.parse_type_script_namespace_stmt(loc, opts)?));
                }
            }
            js_lexer::TypescriptStmtKeyword::TsStmtInterface => {
                // "interface Foo {}"
                let mut stmt_opts = ParseStatementOptions {
                    is_module_scope: opts.is_module_scope,
                    ..Default::default()
                };

                p.skip_type_script_interface_stmt(&mut stmt_opts)?;
                return Ok(Some(p.s(S::TypeScript {}, loc)));
            }
            js_lexer::TypescriptStmtKeyword::TsStmtAbstract => {
                if p.lexer.token == T::TClass || opts.ts_decorators.is_some() {
                    return Ok(Some(p.parse_class_stmt(loc, opts)?));
                }
            }
            js_lexer::TypescriptStmtKeyword::TsStmtGlobal => {
                // "declare module 'fs' { global { namespace NodeJS {} } }"
                if opts.is_namespace_scope
                    && opts.is_typescript_declare
                    && p.lexer.token == T::TOpenBrace
                {
                    p.lexer.next()?;
                    let _ = p.parse_stmts_up_to(T::TCloseBrace, opts)?;
                    p.lexer.next()?;
                    return Ok(Some(p.s(S::TypeScript {}, loc)));
                }
            }
            js_lexer::TypescriptStmtKeyword::TsStmtDeclare => {
                opts.lexical_decl = LexicalDecl::AllowAll;
                opts.is_typescript_declare = true;

                // "@decorator declare class Foo {}"
                // "@decorator declare abstract class Foo {}"
                if opts.ts_decorators.is_some()
                    && p.lexer.token != T::TClass
                    && !p.lexer.is_contextual_keyword(b"abstract")
                {
                    p.lexer.expected(T::TClass)?;
                }

                // "declare global { ... }"
                if p.lexer.is_contextual_keyword(b"global") {
                    p.lexer.next()?;
                    p.lexer.expect(T::TOpenBrace)?;
                    let scope_index = p.scopes_in_order.len();
                    let _ = p.parse_stmts_up_to(T::TCloseBrace, opts)?;
                    p.lexer.next()?;
                    // The statements inside are dropped, so discard any scopes they
                    // recorded or the visit pass will hit a scope order mismatch.
                    p.discard_scopes_up_to(scope_index);
                    return Ok(Some(p.s(S::TypeScript {}, loc)));
                }

                // "declare const x: any"
                let scope_index = p.scopes_in_order.len();
                let stmt = p.parse_stmt(opts)?;
                if let Some(decs) = &opts.ts_decorators {
                    p.discard_scopes_up_to(decs.scope_index);
                } else {
                    // The statement is dropped below (or reduced to just its bindings
                    // for "export declare var" inside a namespace), so discard any
                    // scopes it recorded or the visit pass will hit a scope order
                    // mismatch (e.g. "declare foo: bar" parses a labeled statement
                    // that records a Label scope).
                    p.discard_scopes_up_to(scope_index);
                }

                // Unlike almost all uses of "declare", statements that use
                // "export declare" with "var/let/const" inside a namespace affect
                // code generation. They cause any declared bindings to be
                // considered exports of the namespace. Identifier references to
                // those names must be converted into property accesses off the
                // namespace object:
                //
                //   namespace ns {
                //     export declare const x
                //     export function y() { return x }
                //   }
                //
                //   (ns as any).x = 1
                //   console.log(ns.y())
                //
                // In this example, "return x" must be replaced with "return ns.x".
                // This is handled by replacing each "export declare" statement
                // inside a namespace with an "export var" statement containing all
                // of the declared bindings. That "export var" statement will later
                // cause identifiers to be transformed into property accesses.
                if opts.is_namespace_scope && opts.is_export {
                    let mut decls: G::DeclList = bun_alloc::AstAlloc::vec();
                    match &stmt.data {
                        js_ast::StmtData::SLocal(local) => {
                            let mut _decls = bun_alloc::ArenaVec::<G::Decl>::with_capacity_in(
                                local.decls.len_u32() as usize,
                                p.arena,
                            );
                            for decl in local.decls.slice() {
                                Self::extract_decls_for_binding(decl.binding, &mut _decls)?;
                            }
                            decls = G::DeclList::from_bump_vec(_decls);
                        }
                        _ => {}
                    }

                    if decls.len_u32() > 0 {
                        return Ok(Some(p.s(
                            S::Local {
                                kind: js_ast::LocalKind::KVar,
                                is_export: true,
                                decls,
                                ..Default::default()
                            },
                            loc,
                        )));
                    }
                }

                return Ok(Some(p.s(S::TypeScript {}, loc)));
            }
        }
        Ok(None)
    }

    pub fn parse_stmt(&mut self, opts: &mut ParseStatementOptions<'a>) -> Result<Stmt> {
        if !self.stack_check.is_safe_to_recurse() {
            // TODO(port): bun_core::throw_stack_overflow() not yet exported; map to a SyntaxError
            // until the StackOverflow error variant lands.
            return Err(err!("StackOverflow"));
        }

        // Zig used `inline ... => |function| @field(@This(), @tagName(function))(...)` to dispatch
        // by token name via comptime reflection. Rust has no `@field`/`@tagName`; expand the arms.
        let loc = self.lexer.loc();
        match self.lexer.token {
            T::TSemicolon => Self::t_semicolon(self),
            T::TAt => Self::t_at(self, opts),

            T::TExport => Self::t_export(self, opts, loc),
            T::TFunction => Self::t_function(self, opts, loc),
            T::TEnum => Self::t_enum(self, opts, loc),
            T::TClass => Self::t_class(self, opts, loc),
            T::TVar => Self::t_var(self, opts, loc),
            T::TConst => Self::t_const(self, opts, loc),
            T::TIf => Self::t_if(self, opts, loc),
            T::TDo => Self::t_do(self, opts, loc),
            T::TWhile => Self::t_while(self, opts, loc),
            T::TWith => Self::t_with(self, opts, loc),
            T::TSwitch => Self::t_switch(self, opts, loc),
            T::TTry => Self::t_try(self, opts, loc),
            T::TFor => Self::t_for(self, opts, loc),
            T::TImport => Self::t_import(self, opts, loc),
            T::TBreak => Self::t_break(self, opts, loc),
            T::TContinue => Self::t_continue(self, opts, loc),
            T::TReturn => Self::t_return(self, opts, loc),
            T::TThrow => Self::t_throw(self, opts, loc),
            T::TDebugger => Self::t_debugger(self, opts, loc),
            T::TOpenBrace => Self::t_open_brace(self, opts, loc),

            _ => Self::parse_stmt_fallthrough(self, opts, loc),
        }
    }
}