tsv_ts 0.8.0

TypeScript/JS formatter, type stripper and acorn-compatible parser — part of tsv
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
// TypeScript type-syntax parsing: type annotations and type expressions
// (unions, intersections, object/mapped/tuple/template-literal types, function
// and constructor types, type queries, import types) plus type parameters. The
// type-element grammar shared by type literals and interface bodies lives in
// `parser/type_members.rs`; declarations that *introduce* types (alias,
// interface, enum, namespace, declare) live in `statement/type_declarations.rs`.

use crate::ast::*;
use crate::lexer::{KeywordKind, TokenKind};
use tsv_lang::{Error, Span};

use super::expression_lookahead::{generic_function_type_arrow_end, paren_starts_function_type};
use super::scan::{
    identifier_starts_at, is_word_at, skip_identifier, skip_whitespace_and_comments,
};
use super::{LINK_OPERATOR, LINK_TYPE_SUFFIX, Parser};

// The type ladder's return (see `Parser::parse_type`): a reference plus the pointer-sized
// `Error` needs a discriminant word, so the `Result` is two words — 16 B on 64-bit,
// which x86-64 hands back in two registers where an 80 B `TSType` needs a stack slot.
// wasm32 returns every `Result` through a slot either way; there the width is 8 B
// and the slot is 8 B rather than a whole `TSType`. rustc's layout, so a test-build pin.
#[cfg(test)]
const _: () = assert!(size_of::<Result<&TSType<'static>, Error>>() == 2 * size_of::<usize>());

impl<'a, 'arena> Parser<'a, 'arena> {
    /// Parse a `: Type` annotation when the next token is a `:`, else `None` —
    /// the optional-annotation guard shared by variable declarations, class
    /// properties, and type members. Sites whose missing `:` is an error (e.g.
    /// an index-signature parameter) keep their own inline `else`.
    pub(in crate::parser) fn parse_optional_type_annotation(
        &mut self,
    ) -> Result<Option<TSTypeAnnotation<'arena>>, Error> {
        if self.check(&TokenKind::Colon) {
            Ok(Some(self.parse_type_annotation()?))
        } else {
            Ok(None)
        }
    }

    /// Parse a type annotation (`: Type`) at the current position. Also the public entry
    /// point for embedders (`tsv_svelte`'s `{:then pattern: T}` / `{#each … as x: T}`).
    pub(crate) fn parse_type_annotation(&mut self) -> Result<TSTypeAnnotation<'arena>, Error> {
        let start = self.current_pos().0;
        self.expect(&TokenKind::Colon)?;

        // one wire level: the `TSTypeAnnotation` (the depth limit's count)
        let type_annotation = self.nested(1, Self::parse_type)?;
        let end = type_annotation.span().end;

        Ok(TSTypeAnnotation {
            type_annotation,
            span: Span::new(start as u32, end),
        })
    }

    /// How far a **bare** type (no leading `:`) reaches from the current position —
    /// the extent, not the node.
    ///
    /// The measurement behind Svelte's `{#each}` head split. `{#each xs as A[] as item}`
    /// holds two `as` tokens and only one is Svelte's binding separator; which one is a
    /// question about the *type* grammar, so it is answered by parsing a type rather than
    /// by scanning bytes for brackets — `<` / `>` are not a bracket pair, so an arrow's
    /// `>` closes a depth nothing opened. The reasoning lives with the caller that owns
    /// the decision (`tsv_svelte`'s `each_binding_separator`); this side only measures.
    ///
    /// The extent is the type node's own `span.end`, never the parser's stop position —
    /// the lexer's one-token lookahead has already skipped the trailing trivia by then,
    /// so that position is *past* a trailing comment. Same hazard, same answer, as
    /// [`Parser::parse_type_annotation`]'s embedding wrapper documents.
    pub(crate) fn type_extent(&mut self) -> Result<usize, Error> {
        Ok(self.parse_type()?.span().end as usize)
    }

    /// Parse a complete type expression (handles unions and conditional types at
    /// top level). This is the full-type entry, where function/constructor types
    /// are grammatically allowed — clear both type-context restrictions
    /// (`with_full_type_context`) so nested full-type positions (type arguments,
    /// tuple members, object-type members, conditional branches, parenthesized
    /// inners) parse them greedily even when reached from a constituent/operand
    /// parse. The postfix-`[` ASI rule (a newline before `[` ends the type — see
    /// `parse_array_type`) applies uniformly, so the `as`/`satisfies` expression
    /// context needs no separate entry.
    ///
    /// Returns the type **arena-allocated**, as does every builder on the ladder below
    /// it (`parse_union_type` → `parse_intersection_type` → `parse_array_type` →
    /// `parse_primary_type` and each leaf it dispatches to), each boxing at its own
    /// tail — the expression ladder's rule applied to types: no `parse_*` reached from a
    /// dispatcher returns the bare `TSType` enum. A by-value `TSType` (80 B) comes back
    /// through a caller stack slot at every level of this deep ladder, and a dispatcher
    /// reserves one such slot per arm in every frame; an `&'arena TSType` return is a
    /// two-scalar `Result` (see the size assert at the top of this file). Every consumer
    /// holds a type by reference and keeps that allocation — a union / intersection /
    /// tuple / type-argument / template-literal slice is a slice of these references
    /// (`&'arena [&'arena TSType]`), and the type alias's right-hand side is one — so no
    /// type is copied out of the node its builder allocated.
    pub(in crate::parser) fn parse_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        debug_assert!(self.pending_conditional_extends.is_none());
        self.with_full_type_context(|p| {
            let start = p.current_pos().0;
            let check_type = p.parse_union_type()?;

            // A constrained infer inside `check_type` hit `?` directly after its
            // constraint at this allow-conditional position: the constraint
            // re-binds as this conditional's extends clause and the current token
            // is the `?` (see `pending_conditional_extends`). Otherwise check for
            // `T extends U ? V : W`. The `extends` must not be preceded by a line
            // terminator (TS `CheckType [no LineTerminator here] extends
            // ExtendsType`): a newline before it ends the type, leaving `extends`
            // a stray token (acorn-typescript's `hasPrecedingLineBreak` guard).
            // Same restricted-production rule as the arrow `=>` (see
            // `expect_arrow`).
            let extends_type = if let Some(rebound) = p.pending_conditional_extends.take() {
                debug_assert!(p.check(&TokenKind::Question));
                Some(rebound)
            } else if p.check(&TokenKind::Keyword(KeywordKind::Extends)) && !p.had_line_terminator {
                p.advance()?; // consume 'extends'

                // The extends clause cannot itself be a conditional — a nested
                // `? T : F` binds to this conditional; parens re-enable it.
                // one wire level: the extends type under its `TSConditionalType`
                Some(p.nested(1, |p| {
                    p.with_conditional_type_disallowed(true, Self::parse_union_type)
                })?)
            } else {
                None
            };

            if let Some(extends_type) = extends_type {
                // the check type, parsed before the `extends` said it was one, is the
                // conditional's left operand: a spine link (`(A extends B ? C : D) extends …`
                // nests a conditional per grouping paren)
                p.spine_link(LINK_TYPE_SUFFIX)?;
                // Expect '?'
                p.expect(&TokenKind::Question)?;

                // Each branch is a recursion that stays inside this frame, past the
                // check type's own depth level, so it takes one of its own: one wire level,
                // the branch under the `TSConditionalType` (the depth limit's count).
                let true_type = p.nested(1, Self::parse_type)?;
                // the pair the printer adds around a bare conditional true branch while it
                // stays flat (`A extends B ? (C extends D ? E : F) : G`), a level of the
                // output's nesting — an author's pair it strips and writes back
                if matches!(true_type, TSType::Conditional(_)) {
                    p.printer_pair()?;
                }

                // Expect ':'
                p.expect(&TokenKind::Colon)?;

                let false_type = p.nested(1, Self::parse_type)?;
                let end = false_type.span().end;

                Ok(p.alloc(TSType::Conditional(TSConditionalType {
                    check_type,
                    extends_type,
                    true_type,
                    false_type,
                    span: Span::new(start as u32, end),
                })))
            } else {
                Ok(check_type)
            }
        })
    }

    /// Parse union type: `A | B | C` or `| A | B | C`
    fn parse_union_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;

        // Handle leading pipe: `| A | B`
        let has_leading_pipe = self.check(&TokenKind::Pipe);
        if has_leading_pipe {
            self.advance()?; // consume leading '|'
        }

        // A union constituent is not a full-type position: function/constructor
        // types are disallowed there (`fn_type_disallowed`), so a constituent's
        // `(` is a parenthesized type. Without a leading `|` the first parse is
        // still the full-type position itself (a function type here is greedy:
        // `([a]) => x | B` is a function type returning `x | B`).
        let first = if has_leading_pipe {
            self.with_fn_type_disallowed(true, Self::parse_intersection_type)?
        } else {
            self.parse_intersection_type()?
        };

        if !has_leading_pipe && !self.check(&TokenKind::Pipe) {
            return Ok(first);
        }

        let mut types = self.bvec();
        types.push(first);
        // the constituents are siblings (`ListFrame`); the first is already counted
        let mut frame = self.list_frame();
        while self.eat(TokenKind::Pipe)? {
            self.first_member_pair(&types)?;
            frame.element(self, types.len());
            // one wire level beyond the constituent's own: the `TSUnionType` it sits in,
            // known only once a `|` follows the first (the depth limit's count)
            let member = self.nested(1, |p| {
                p.with_fn_type_disallowed(true, Self::parse_intersection_type)
            })?;
            self.member_pair(member)?;
            types.push(member);
        }

        frame.close(self);
        let end = types.last().map_or_else(|| start as u32, |t| t.span().end);
        Ok(self.alloc(TSType::Union(TSUnionType {
            types: types.into_bump_slice(),
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse intersection type: `A & B & C` or `& A & B & C`
    fn parse_intersection_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;

        // Handle leading ampersand: `& A & B`
        let has_leading_amp = self.check(&TokenKind::Ampersand);
        if has_leading_amp {
            self.advance()?; // consume leading '&'
        }

        // An intersection constituent is not a full-type position — see the
        // union counterpart above. The no-leading-`&` first parse inherits the
        // caller's position (full-type, or a union constituent's).
        let first = if has_leading_amp {
            self.with_fn_type_disallowed(true, Self::parse_array_type)?
        } else {
            self.parse_array_type()?
        };

        if !has_leading_amp && !self.check(&TokenKind::Ampersand) {
            return Ok(first);
        }

        let mut types = self.bvec();
        types.push(first);
        // the constituents are siblings (`ListFrame`); the first is already counted
        let mut frame = self.list_frame();
        while self.eat(TokenKind::Ampersand)? {
            self.first_member_pair(&types)?;
            frame.element(self, types.len());
            // one wire level beyond the constituent's own: the `TSIntersectionType`
            let member = self.nested(1, |p| {
                p.with_fn_type_disallowed(true, Self::parse_array_type)
            })?;
            self.member_pair(member)?;
            types.push(member);
        }

        frame.close(self);

        let end = types.last().map_or_else(|| start as u32, |t| t.span().end);
        Ok(self.alloc(TSType::Intersection(TSIntersectionType {
            types: types.into_bump_slice(),
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse array type suffix `T[]` or indexed access type `T[K]`.
    ///
    /// The postfix `[` is a `[no LineTerminator here]` position (acorn's
    /// `tsParseArrayTypeOrHigher`: `while (!hasPrecedingLineBreak() && eat('['))`):
    /// a newline before `[` ends the type, so the `[` starts a new statement (ASI
    /// inserts the `;`), never an array/indexed-access suffix. `T⏎[K]` is thus `T`
    /// then a fresh `[K]`, not `T[K]`. Checked per bracket in the loop condition —
    /// every context, not just the `as`/`satisfies` expression position.
    ///
    /// tsc guards the postfix `?` of a tuple element on the same rule, in the same loop
    /// — see [`Self::error_optional_marker_after_line_break`], where acorn's port drops
    /// the guard and tsv keeps it.
    ///
    fn parse_array_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        let mut result = self.parse_primary_type()?;

        // Array type suffix [] or indexed access T[K], stopping at a newline-`[`.
        while !self.had_line_terminator && self.check(&TokenKind::BracketOpen) {
            self.spine_link(LINK_TYPE_SUFFIX)?;
            // the pair the printer adds around a bare element / object that binds looser
            // than the suffix (`(typeof a)[]`, `(infer U)[K]`, `(-1)[]`), a level of the
            // output's nesting
            if bare_type_takes_pair(result, TypePairPosition::Suffix) {
                self.printer_pair()?;
            }
            if matches!(self.peek_kind(), TokenKind::BracketClose) {
                // Array type: T[]
                self.advance()?; // consume '['
                let (_, arr_end) = self.current_pos();
                self.expect(&TokenKind::BracketClose)?;

                result = self.alloc(TSType::Array(TSArrayType {
                    element_type: result,
                    span: Span::new(start as u32, arr_end as u32),
                }));
            } else {
                // Indexed access type: T[K]
                self.advance()?; // consume '['
                // one wire level: the index (the depth limit's count)
                let index_type = self.nested(1, Self::parse_type)?;
                let (_, end) = self.current_pos();
                self.expect(&TokenKind::BracketClose)?;

                result = self.alloc(TSType::IndexedAccess(TSIndexedAccessType {
                    object_type: result,
                    index_type,
                    span: Span::new(start as u32, end as u32),
                }));
            }
        }

        Ok(result)
    }

    /// Parse primary type (highest precedence)
    fn parse_primary_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let (start, end) = self.current_pos();
        let span = Span::new(start as u32, end as u32);

        // Keyword types: string, number, boolean, true, false, etc.
        if let TokenKind::Keyword(kw) = self.current_kind()
            && let Some(ts_kind) = TSKeywordKind::from_lexer_keyword(*kw)
        {
            // A *contextual* type keyword (`string`, `number`, `any`, `undefined`, …)
            // immediately followed by `.` is the HEAD of a qualified type name
            // (`string.X`, `number.A.B`), not the primitive keyword — tsc, prettier,
            // and acorn all read it as a `TSTypeReference` / `TSQualifiedName`. Gated on
            // `can_be_binding_name` so only the non-reserved contextual keywords
            // qualify: `true`/`false`/`void`/`null` are reserved (never entity-name
            // heads for tsc/prettier), so `true.X` stays primitive and rejects the
            // trailing `.X`, matching the formatter oracle.
            if kw.can_be_binding_name() && matches!(self.peek_kind(), TokenKind::Dot) {
                return self.parse_type_reference();
            }
            self.advance()?;
            return Ok(self.alloc(TSType::Keyword(TSKeywordType::new(ts_kind, span))));
        }

        match self.current_kind() {
            // `this` type — a bare `this` type, or a `this`-type predicate
            // `this is T`. The predicate form is a primary type accepted anywhere
            // a type is expected (parameter / variable annotations, type-alias
            // RHS, type arguments), matching acorn-typescript; the identifier form
            // `x is T` stays restricted to return position (parsed in
            // `statement/type_declarations.rs`).
            TokenKind::Keyword(KeywordKind::This) => {
                let (start, end) = self.current_pos();
                if self.peek_predicate_is_ahead() {
                    let this_name = self.current_raw_ident_name();
                    self.advance()?; // past `this`
                    self.advance()?; // past `is`
                    let type_node = self.nested(1, Self::parse_type)?;
                    let type_end = type_node.span().end;
                    let predicate = TSTypePredicate {
                        parameter_name: Identifier::simple(
                            this_name,
                            Span::new(start as u32, end as u32),
                        ),
                        type_annotation: Some(type_node),
                        asserts: false,
                        span: Span::new(start as u32, type_end),
                    };
                    return Ok(self.alloc(TSType::TypePredicate(predicate)));
                }
                self.advance()?;
                Ok(self.alloc(TSType::ThisType(TSThisType {
                    span: Span::new(start as u32, end as u32),
                })))
            }
            // `const` keyword in type context (for `as const`)
            // Treated as a type reference with name "const"
            TokenKind::Keyword(KeywordKind::Const) => {
                let (start, end) = self.current_pos();
                let name = self.current_raw_ident_name();
                self.advance()?;

                Ok(self.alloc(TSType::TypeReference(TSTypeReference {
                    type_name: TSEntityName::Identifier(Identifier::simple(
                        name,
                        Span::new(start as u32, end as u32),
                    )),
                    type_arguments: None,
                    span: Span::new(start as u32, end as u32),
                })))
            }
            // Numeric literal types: `1`, `42.5`, `1n`
            TokenKind::Number => {
                let literal = self.parse_number_or_bigint_literal()?;
                let is_bigint = matches!(literal.value, LiteralValue::BigInt);
                self.advance()?;

                if is_bigint {
                    Ok(self.alloc(TSType::Literal(TSLiteralType::BigInt(literal))))
                } else {
                    Ok(self.alloc(TSType::Literal(TSLiteralType::Number(literal))))
                }
            }
            // String literal types: `"hello"`, `'world'`
            TokenKind::String => {
                let literal = self.parse_string_literal()?;
                Ok(self.alloc(TSType::Literal(TSLiteralType::String(literal))))
            }
            // Negative number literal types: `-1`, `-42n`
            TokenKind::Minus => {
                let start = self.current_pos().0;
                self.advance()?; // consume '-'

                if !matches!(self.current_kind(), TokenKind::Number) {
                    return Err(self.error_expected("number after '-' in type context"));
                }

                let argument = self.parse_number_or_bigint_literal()?;
                let num_end = self.current_pos().1;
                self.advance()?;

                let unary = UnaryExpression {
                    operator: UnaryOperator::Minus,
                    argument: self.alloc(Expression::from_literal(argument)),
                    span: Span::new(start as u32, num_end as u32),
                };
                Ok(self.alloc(TSType::Literal(TSLiteralType::UnaryExpression(unary))))
            }
            // Template literal types
            TokenKind::NoSubstitutionTemplate | TokenKind::TemplateHead => {
                let template = self.parse_template_literal_type()?;
                Ok(self.alloc(TSType::Literal(TSLiteralType::TemplateLiteral(template))))
            }
            // Parenthesized type or function type: (T) or (x: T) => U
            TokenKind::ParenOpen => self.parse_parenthesized_or_function_type(),
            // Object type: { prop: T }
            TokenKind::BraceOpen => self.parse_object_type(),
            // Tuple type: [T, U]
            TokenKind::BracketOpen => self.parse_tuple_type(),
            // Type reference or type operator (keyof, unique, readonly) or infer or abstract constructor
            TokenKind::Identifier => {
                // Check for type operators: keyof, unique, readonly, abstract
                match self.current_value() {
                    "keyof" => self.parse_type_operator(TSTypeOperatorKind::Keyof),
                    "unique" => self.parse_type_operator(TSTypeOperatorKind::Unique),
                    // Always the operator, as `keyof` and `unique` are: a `readonly`
                    // with no operand is a syntax error to tsc, acorn-typescript and
                    // prettier alike, never a type reference named `readonly`. (The
                    // mapped-type and member modifier are read by their own parsers.)
                    "readonly" => self.parse_type_operator(TSTypeOperatorKind::Readonly),
                    "abstract" => {
                        // Check if next token is 'new' for abstract constructor type
                        if matches!(self.peek_kind(), TokenKind::Keyword(KeywordKind::New)) {
                            self.parse_constructor_type(true)
                        } else {
                            // 'abstract' as a type reference (rare but valid)
                            self.parse_type_reference()
                        }
                    }
                    "infer" => self.parse_infer_type(),
                    _ => self.parse_type_reference(),
                }
            }
            // Import type: import('module') or import('module').Foo<T>
            TokenKind::Keyword(KeywordKind::Import) => self.parse_import_type(),
            // Generic function type: <T>() => U
            TokenKind::LessThan => self.parse_generic_function_type(),
            // Type query: typeof x, typeof Foo.bar, typeof import("module")
            TokenKind::Keyword(KeywordKind::Typeof) => self.parse_type_query(),
            // Constructor type: new () => T or new <T>() => T
            TokenKind::Keyword(KeywordKind::New) => self.parse_constructor_type(false),
            // Any remaining reserved keyword is a type-reference NAME: TS's type
            // space is a separate `IdentifierName` namespace, so reserved statement
            // keywords (`break`, `default`, `function`, `case`, …) are valid type
            // names — tsc, prettier and acorn-typescript all accept.
            // The primitive keywords, `this`/`const`/`import`/`typeof`/`new`, and
            // the contextual type operators (which lex as `Identifier`) all match
            // above, so only the reserved keywords reach this arm — the entity-name
            // head reads a keyword token via `current_raw_ident_name` (keywords are
            // never escaped), mirroring the `Const` arm.
            TokenKind::Keyword(_) => self.parse_type_reference(),
            _ => Err(self.error_expected_found("type")),
        }
    }

    /// Parse type operator: `keyof T`, `unique symbol`, `readonly T[]`
    ///
    /// Type operators bind looser than array `[]` and indexed access `[K]`, so:
    /// - `keyof A[B]` parses as `keyof (A[B])`, not `(keyof A)[B]`
    /// - `keyof A[]` parses as `keyof (A[])`, not `(keyof A)[]`
    /// - `readonly A[B][]` parses as `readonly ((A[B])[])`
    fn parse_type_operator(
        &mut self,
        operator: TSTypeOperatorKind,
    ) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.advance()?; // consume the operator keyword (keyof, unique, readonly)

        // Parse the type being operated on (including array/indexed access suffixes).
        // A type-operator operand is not a full-type position: function/constructor
        // types are disallowed (`keyof () => T` must be `keyof (() => T)`), so a
        // `(` here is a parenthesized type (`keyof ([a])[]` stays valid).
        // one wire level: the operand (the depth limit's count)
        let type_annotation = self.nested(1, |p| {
            p.with_fn_type_disallowed(true, Self::parse_array_type)
        })?;
        let end = type_annotation.span().end;
        // the pair the printer adds around a bare operand that is itself a prefix operator
        // (`keyof (keyof T)`, `keyof (infer U)`), a level of the output's nesting
        if matches!(type_annotation, TSType::TypeOperator(_) | TSType::Infer(_)) {
            self.printer_pair()?;
        }

        Ok(self.alloc(TSType::TypeOperator(TSTypeOperator {
            operator,
            type_annotation,
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse infer type: `infer U` (in conditional type extends clause)
    fn parse_infer_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.advance()?; // consume 'infer'

        // Parse the type parameter name. `InferType : infer TypeParameter`, and a type
        // parameter's name is a `BindingIdentifier` — so a contextual keyword names one
        // (`infer string`, `infer any`, `infer from`) exactly as it does in every other
        // binding position, and `let`/`yield` do too, their bar being the deferred
        // strict-mode early error. A bare `TokenKind::Identifier` test saw only the
        // words the lexer never made a `Keyword` and rejected the rest; acorn, tsc and
        // prettier all accept them.
        let Some(name) = self.take_binding_identifier()? else {
            return Err(self.error_expected("type parameter name after 'infer'"));
        };

        // Optional constraint: `infer U extends C`. The constraint is parsed
        // with conditionals disallowed and function types re-enabled (acorn
        // parses it as a full type in the disallow-conditional context), so a
        // nested `? T : F` binds outward rather than being swallowed as a
        // nested conditional. Parens re-enable conditionals
        // (`infer U extends (A ? B : C)`), since the parenthesized-type parser
        // recurses into the full type grammar. Mirrors how a conditional's
        // `extends_type` is parsed (`parse_type`).
        //
        // At an allow-conditional position, a `?` directly after the
        // constraint means it was never a constraint at all:
        // `infer U extends C ? T : F` is a conditional whose check is the bare
        // `infer U` and whose extends clause is `C` (acorn rolls back its
        // constraint tryParse and re-parses at the conditional level; the
        // already-parsed type is handed to `parse_type` via
        // `pending_conditional_extends` instead of re-lexing). The re-bound
        // `extends` honors the conditional's no-line-terminator rule: after a
        // newline the constraint is kept, and the enclosing context then
        // rejects the stray `?` — matching acorn, whose rolled-back re-parse
        // refuses the `extends` and rejects on the stray token.
        let name_start = name.span.start;
        let mut end = name.span.end;
        let mut constraint = None;
        if self.check(&TokenKind::Keyword(KeywordKind::Extends)) {
            let extends_preceded_by_lt = self.had_line_terminator;
            self.advance()?; // consume 'extends'
            let constraint_type = self.with_conditional_type_disallowed(true, |p| {
                p.with_fn_type_disallowed(false, Self::parse_union_type)
            })?;
            if !self.conditional_type_disallowed
                && !extends_preceded_by_lt
                && self.check(&TokenKind::Question)
            {
                self.pending_conditional_extends = Some(constraint_type);
            } else {
                end = constraint_type.span().end;
                constraint = Some(constraint_type);
            }
        }

        Ok(self.alloc(TSType::Infer(self.arena.alloc(TSInferType {
            type_parameter: TSTypeParameter {
                name,
                constraint,
                default: None,
                // `infer T` takes no modifiers.
                modifiers: TSTypeParameterModifiers::default(),
                span: Span::new(name_start, end),
            },
            span: Span::new(start as u32, end),
        }))))
    }

    /// Check if current position starts an index signature: `[key: type]: T`
    /// vs a computed property: `[expr]: T`
    ///
    /// Index signatures always have the form `[identifier: type]` where the identifier
    /// is immediately followed by `:`. Computed properties have `[expression]` where
    /// the expression can be any expression followed by `]`.
    pub(in crate::parser) fn is_index_signature_start(&self) -> bool {
        // Must start with '['
        if !matches!(self.current.kind, TokenKind::BracketOpen) {
            return false;
        }

        // Lookahead: check if pattern is `[identifier:`
        // We need to look past the '[', then the identifier, then check for ':'
        let bytes = self.source.as_bytes();
        let pos = skip_whitespace_and_comments(bytes, self.current.start as usize + 1); // skip '[' and whitespace/comments

        // Must be followed by an identifier
        if !identifier_starts_at(bytes, pos) {
            return false;
        }

        // Skip the identifier and trailing whitespace/comments
        let pos = skip_whitespace_and_comments(bytes, skip_identifier(bytes, pos));

        // Check for ':'
        pos < bytes.len() && bytes[pos] == b':'
    }

    /// Check if the current position starts a mapped type: `[K in T]`, optionally
    /// prefixed by `readonly` (`readonly [K in T]`). A mapped type is the sole
    /// member of its type literal; the `in` keyword after the single
    /// type-parameter name is what distinguishes it from an index signature
    /// (`[k: T]`) or a computed-key member (`[expr]`), both of which fall through
    /// to the general member loop. `+readonly` / `-readonly` mapped types are
    /// detected earlier by their unambiguous `+`/`-` prefix, so this only handles
    /// the bare and `readonly` forms.
    ///
    /// acorn-typescript reads `[Ident in …]` as a mapped type unconditionally
    /// (even `[a in b]`), so a computed key that wants the `in` operator must
    /// parenthesize (`[(a in b)]`) or use a non-identifier head (`[a.b in c]`) —
    /// both fail the `[Ident in` shape here and parse as computed keys, matching
    /// acorn.
    fn is_mapped_type_start(&self) -> bool {
        let bytes = self.source.as_bytes();
        let mut pos = self.current.start as usize;

        // Optional leading `readonly` modifier (bare; `+readonly` / `-readonly`
        // are handled by the caller's `+`/`-` check).
        if matches!(self.current.kind, TokenKind::Identifier) && self.current_value() == "readonly"
        {
            pos = skip_whitespace_and_comments(bytes, skip_identifier(bytes, pos));
        }

        // Must be `[`
        if pos >= bytes.len() || bytes[pos] != b'[' {
            return false;
        }
        pos = skip_whitespace_and_comments(bytes, pos + 1);

        // Followed by the type-parameter name (an identifier)
        if !identifier_starts_at(bytes, pos) {
            return false;
        }
        pos = skip_whitespace_and_comments(bytes, skip_identifier(bytes, pos));

        // Then the `in` keyword, at a word boundary so `[index]` and `[inK in K]`
        // don't false-match on a leading `in`.
        is_word_at(bytes, pos, b"in")
    }

    /// Parse type reference: `Foo` or `Foo.Bar` or `Foo<T>`
    fn parse_type_reference(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        let type_name = self.parse_type_entity_name()?;

        // Check for type arguments: <T, U>. A line break before `<` ends the type
        // at `type_name` — the `<` is not consumed as type arguments (see
        // `parse_optional_type_arguments_same_line`).
        let type_arguments = self.parse_optional_type_arguments_same_line()?;

        let end = type_arguments
            .as_ref()
            .map_or_else(|| type_name.span().end, |ta| ta.span.end);

        Ok(self.alloc(TSType::TypeReference(TSTypeReference {
            type_name,
            type_arguments,
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse import type: `import('module')` or `import('module', {with: {...}}).Foo<T>`
    fn parse_import_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.advance()?; // consume 'import'
        let import = self.parse_import_type_body(start)?;
        Ok(self.alloc(TSType::Import(self.arena.alloc(import))))
    }

    /// Parse import type body after `import` keyword has been consumed.
    /// Parses: `('module')`, `('module', {options}).Qualifier<TypeArgs>`
    fn parse_import_type_body(&mut self, start: usize) -> Result<TSImportType<'arena>, Error> {
        // Expect '('
        self.expect(&TokenKind::ParenOpen)?;

        // Parse the module specifier (string literal)
        if !matches!(self.current_kind(), TokenKind::String) {
            return Err(self.error_expected("string literal in import type"));
        }

        let argument = self.parse_string_literal()?;

        // Optional options object: `import('module', {with: {type: 'json'}})`
        let options: Option<&'arena Expression<'arena>> = if self.eat(TokenKind::Comma)? {
            Some(self.parse_expression_ref()?)
        } else {
            None
        };

        // Expect ')'
        self.expect(&TokenKind::ParenClose)?;

        // Optional qualifier: .Foo or .Foo.Bar
        let qualifier = if self.eat(TokenKind::Dot)? {
            Some(self.parse_type_entity_name()?)
        } else {
            None
        };

        // Optional type arguments: <T, U>. A line break before `<` ends the type at the
        // qualifier — an import type is one of the sites tsc's
        // `parseTypeArgumentsOfTypeReference` guard covers, so `import('./a').B` ⏎
        // `<string>` is the type `import('./a').B` followed by a separate `<string>`
        // (TS1109; prettier rejects with it). This site read its arguments directly and
        // so welded where every sibling type-argument site already split, tsv alone —
        // acorn welds too, and is the shape target rather than the validity oracle. The
        // `typeof import(…)` spelling composes through here, so it is covered by the
        // same gate rather than by `parse_type_query`'s own (which runs too late to see
        // a `<` this body already consumed).
        let type_arguments = self.parse_optional_type_arguments_same_line()?;

        let end = type_arguments
            .as_ref()
            .map(|ta| ta.span.end)
            .or_else(|| qualifier.as_ref().map(|q| q.span().end))
            .unwrap_or_else(|| self.prev_token_end() as u32);

        Ok(TSImportType {
            argument,
            options,
            qualifier,
            type_arguments,
            span: Span::new(start as u32, end),
        })
    }

    /// Parse type query: `typeof x`, `typeof Foo.bar`, `typeof import("module")`
    fn parse_type_query(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.advance()?; // consume 'typeof'

        // Check for import type: typeof import("module")
        let expr_name = if self.check(&TokenKind::Keyword(KeywordKind::Import)) {
            let import_start = self.current_pos().0;
            self.advance()?; // consume 'import'
            let import = self.parse_import_type_body(import_start)?;
            TSTypeQueryExprName::Import(self.alloc(import))
        } else {
            // Parse entity name: identifier or qualified name
            let entity_name = self.parse_type_entity_name()?;
            TSTypeQueryExprName::EntityName(entity_name)
        };

        // Parse optional type arguments: typeof Array<string>. A line break
        // before `<` ends the query — `typeof a` ⏎ `<T>(): void` in an interface
        // is two members, not an instantiation (see
        // `parse_optional_type_arguments_same_line`).
        //
        // tsc reads a query's arguments with `tryParseTypeArguments`, which takes a lone
        // `<` and never re-scans a `<<` (a type reference's list does), so after a query a
        // `<<` is the shift operator: `a as typeof b << c` is `(a as typeof b) << c`.
        // acorn-typescript splits the token and reads a list, which only a generic
        // function type can open (`typeof f<<T>() => void>`, a text tsc rejects). No text
        // reads both ways — the shift reading of a `<<T>(…) =>` tail puts an arrow in an
        // operand position — so the bytes decide: the list is read where the tail opens a
        // generic function type (`generic_function_type_arrow_end`), and the `<<` is left
        // to the shift everywhere else.
        let type_arguments = if self.check(&TokenKind::LeftShift) {
            let second_lt = self.current.start as usize + 1;
            if generic_function_type_arrow_end(self.source.as_bytes(), second_lt + 1).is_some() {
                self.parse_optional_type_arguments_same_line()?
            } else {
                None
            }
        } else {
            self.parse_optional_type_arguments_same_line()?
        };

        let end = type_arguments
            .as_ref()
            .map_or_else(|| expr_name.span().end, |ta| ta.span.end);

        Ok(self.alloc(TSType::TypeQuery(TSTypeQuery {
            expr_name,
            type_arguments,
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse an entity name (`Foo` / `Foo.Bar.Baz`) in a **type** position, where every
    /// segment after a `.` is a full `IdentifierName` — reserved words included
    /// (`ns.delete`, `A.false`, `typeof C.prototype.delete`, `typeof this.this`). tsc
    /// and acorn both accept these; tsc spells the same rule
    /// `parseEntityName(allowReservedWords: true)`.
    ///
    /// The **head** segment is not widened by this, and each caller may narrow it
    /// further, so what heads an entity name is largely the caller's question and the
    /// four callers answer it differently. The heritage clause guards with
    /// `at_binding_name` (so `extends void` / `extends null` reject); a type REFERENCE
    /// is reached only through `parse_primary_type`'s dispatch, where `void` and `null`
    /// are their own keyword types, so `void.X` / `null.X` die on the trailing `.` — see
    /// the `types/reserved_keyword_qualified_head_svelte_divergence` fixture. A type
    /// QUERY and an import-type qualifier add no guard of their own, so `typeof void.x`
    /// and `import('m').if` parse; acorn accepts both, so that leniency is parity, not a
    /// gap. ⚠️ Don't restate this as one invariant — there isn't one.
    ///
    /// What IS common to all four is the floor `parse_entity_name_inner` enforces: the
    /// head must be a word. Leaving even that to the callers is how `typeof 5` came to
    /// parse as an `Identifier` NAMED `"5"` — a fabricated node acorn rejects outright.
    pub(crate) fn parse_type_entity_name(&mut self) -> Result<TSEntityName<'arena>, Error> {
        self.parse_entity_name_inner(true)
    }

    /// Parse an entity name in an import-equals **module reference**
    /// (`import x = A.B.C`), where a reserved word after `.` is a syntax error —
    /// `import x = A.delete` is TS1359 for tsc and rejected by acorn. tsc's
    /// `parseEntityName(allowReservedWords: false)`.
    pub(crate) fn parse_module_reference_entity_name(
        &mut self,
    ) -> Result<TSEntityName<'arena>, Error> {
        self.parse_entity_name_inner(false)
    }

    fn parse_entity_name_inner(
        &mut self,
        allow_reserved_words: bool,
    ) -> Result<TSEntityName<'arena>, Error> {
        // The head is an `IdentifierName` at minimum — a word. Callers that need a
        // narrower head guard ahead of the call (see `parse_type_entity_name`); this
        // is the floor none of them may fall through, since `current_ident_name`
        // happily reads a literal's source text as a name.
        if !self.current_is_identifier_or_keyword() {
            return Err(self.error_expected("a type name"));
        }

        let (id_start, id_end) = self.current_pos();
        let name = self.current_ident_name();
        self.advance()?;

        let mut result = TSEntityName::Identifier(Identifier::simple(
            name,
            Span::new(id_start as u32, id_end as u32),
        ));

        while self.check(&TokenKind::Dot) {
            self.spine_link(LINK_OPERATOR)?;
            self.advance()?; // consume '.'
            let right_name = if allow_reserved_words {
                self.try_identifier_name()
            } else {
                self.try_ident_or_contextual_name()
            }
            .ok_or_else(|| self.error_expected_after("identifier", "."))?;

            let (right_start, right_end) = self.current_pos();
            self.advance()?;

            let right =
                Identifier::simple(right_name, Span::new(right_start as u32, right_end as u32));

            result = TSEntityName::QualifiedName(self.alloc(TSQualifiedName {
                left: result,
                right,
                span: Span::new(id_start as u32, right_end as u32),
            }));
        }

        Ok(result)
    }

    /// Parse a `<T, U>` type-argument list when the next token opens one (`<`),
    /// else `None` — the optional-type-arguments guard shared by
    /// expression-with-type-arguments and `extends`-clause heritage, which consume
    /// type arguments *across* a line break (matching acorn, and tsc, which reads
    /// them through `parseExpressionWithTypeArguments`). Callers in **type**
    /// position must instead stop at a line break — type references, `typeof`
    /// queries and `import(...)` types — and use
    /// `parse_optional_type_arguments_same_line`.
    pub(in crate::parser) fn parse_optional_type_arguments(
        &mut self,
    ) -> Result<Option<TSTypeParameterInstantiation<'arena>>, Error> {
        if self.check_less_than_in_type() {
            Ok(Some(self.parse_type_arguments()?))
        } else {
            Ok(None)
        }
    }

    /// Like `parse_optional_type_arguments`, but a preceding line terminator ends
    /// the type: a `<` after a line break is NOT consumed as type arguments
    /// (tsc's `!scanner.hasPrecedingLineBreak()` guard on
    /// `parseTypeArgumentsOfTypeReference` / `tsParseTypeQuery`). So `B` ⏎ `<T>`
    /// is the type `B` followed by a separate `<T>`, not `B<T>` — in a type-member
    /// list this ASI-splits `a: B` ⏎ `<T>(): C` into two members. This mirrors the
    /// `!had_line_terminator` guard the postfix-`[]`, tuple-optional-`?` and `extends`
    /// sites also apply. The three type-position callers are the plain type
    /// reference, the `typeof` query, and the `import(...)` type — the last of which
    /// read its arguments directly until the shared rule was extended to it.
    pub(in crate::parser) fn parse_optional_type_arguments_same_line(
        &mut self,
    ) -> Result<Option<TSTypeParameterInstantiation<'arena>>, Error> {
        if self.had_line_terminator {
            Ok(None)
        } else {
            self.parse_optional_type_arguments()
        }
    }

    /// Parse type arguments: `<T, U>` (trailing comma allowed, but cannot be empty)
    pub(in crate::parser) fn parse_type_arguments(
        &mut self,
    ) -> Result<TSTypeParameterInstantiation<'arena>, Error> {
        let start = self.current_pos().0;
        self.expect_less_than_in_type()?;

        let mut params = self.bvec();
        if !self.check_greater_than_in_type() {
            params.push(self.parse_type_argument()?);
            // the arguments are siblings (`ListFrame`); the first is already counted
            let mut frame = self.list_frame();
            while self.eat(TokenKind::Comma)? {
                // Allow trailing comma - check for closing > before parsing another type
                if self.check_greater_than_in_type() {
                    break;
                }
                frame.element(self, params.len());
                params.push(self.parse_type_argument()?);
            }
            frame.close(self);
        }

        // Type argument list cannot be empty
        if params.is_empty() {
            return Err(self.error_msg("Type argument list cannot be empty"));
        }

        let end = self.greater_than_end_in_type()?;

        Ok(TSTypeParameterInstantiation {
            params: params.into_bump_slice(),
            span: Span::new(start as u32, end),
        })
    }

    /// Parse parenthesized type `(T)` or function type `(x: T) => U`
    fn parse_parenthesized_or_function_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        // Raw `(` offset into `self.source` for the byte scan below (NOT
        // `current_pos()`, which adds `base_offset` for span coordinates and would
        // mis-index the embedded `<script>` slice).
        let paren_offset = self.current.start as usize;
        let start = self.current_pos().0;
        self.expect(&TokenKind::ParenOpen)?;

        // Whether this `(` opens a function type's parameter list — one rule, asked of
        // the bytes (`paren_starts_function_type`, acorn-typescript's
        // `tsIsUnambiguouslyStartOfFunctionType`): `()`, `(...`, or a parameter start
        // followed by `:` / `,` / `?` / `=`, or by `) =>`. Everything else is a
        // parenthesized type, whatever its first token — a literal (`(true | A)`),
        // `this`, an operator word (`(keyof T)`), or a reserved word standing as a
        // type name (`(default | A)`); the same words are parameter NAMES where the
        // rule says so (`(keyof) => U`, `(number: T) => U`).
        //
        // At an operand position (`fn_type_disallowed`: a union/intersection
        // constituent or type-operator operand) the grammar has no function types, so
        // the `(` never opens one — a following `=>` belongs to an enclosing
        // construct, e.g. the enclosing arrow function's own `=>` after its
        // return-type annotation (`(): A & (B) => x`). The inner parse is a full-type
        // position again (`parse_type` clears the flag), so `A & (() => B)` works.
        if self.fn_type_disallowed
            || !paren_starts_function_type(self.source.as_bytes(), paren_offset)
        {
            // one wire level: the `TSParenthesizedType` (the depth limit's count)
            let inner_type = self.nested(1, Self::parse_type)?;
            self.expect(&TokenKind::ParenClose)?;
            let end = self.prev_token_end();

            return Ok(self.alloc(TSType::Parenthesized(TSParenthesizedType {
                type_annotation: inner_type,
                span: Span::new(start as u32, end as u32),
            })));
        }

        let params = self.parse_function_type_params()?.into_bump_slice();
        self.expect(&TokenKind::ParenClose)?;

        // Committed to a function-type parameter list, so the `=>` and return type
        // are required — there is no implicit-void function type (acorn rejects
        // `(x: T)` / `()` without `=>`). The return type may be a type predicate
        // (asserts x, x is T).
        let arrow_start = self.current_pos().0 as u32;
        self.expect(&TokenKind::Arrow)?;
        // two wire levels: the function type and its `TSTypeAnnotation` (the depth
        // limit's count)
        let return_type = self.nested(2, |p| p.parse_return_type_inner(arrow_start))?;
        let end = return_type.span.end;

        Ok(self.alloc(TSType::Function(TSFunctionType {
            type_parameters: None,
            params,
            return_type,
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse generic function type: `<T>() => U`, `<T, U extends V>(x: T) => U`
    fn parse_generic_function_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        // Function types are not allowed at operand positions (`A & <T>() => U`
        // must be `A & (<T>() => U)`) — see `fn_type_disallowed`.
        if self.fn_type_disallowed {
            return Err(self.error_expected_found("type"));
        }

        let start = self.current_pos().0;

        // Parse type parameters: <T, U extends V, ...> — one wire level: the function type
        // over its type parameters
        let type_parameters = self.nested(1, Self::parse_type_parameters)?;

        // Parse parameter list
        self.expect(&TokenKind::ParenOpen)?;
        let params = self.parse_function_type_params()?.into_bump_slice();
        self.expect(&TokenKind::ParenClose)?;

        // Expect arrow
        let arrow_start = self.current_pos().0 as u32;
        self.expect(&TokenKind::Arrow)?;

        // Parse return type (may be a type predicate)
        // two wire levels: the function type and its `TSTypeAnnotation` (the depth
        // limit's count)
        let return_type = self.nested(2, |p| p.parse_return_type_inner(arrow_start))?;
        let end = return_type.span.end;

        Ok(self.alloc(TSType::Function(TSFunctionType {
            type_parameters: Some(type_parameters),
            params,
            return_type,
            span: Span::new(start as u32, end),
        })))
    }

    /// Parse constructor type: `new () => T`, `new <T>() => T`, `abstract new () => T`
    fn parse_constructor_type(
        &mut self,
        is_abstract: bool,
    ) -> Result<&'arena TSType<'arena>, Error> {
        // Constructor types are not allowed at operand positions (`A & new () => T`
        // must be `A & (new () => T)`) — see `fn_type_disallowed`.
        if self.fn_type_disallowed {
            return Err(self.error_expected_found("type"));
        }

        let start = self.current_pos().0;

        // If abstract, consume 'abstract' keyword
        if is_abstract {
            self.advance()?; // consume 'abstract'
        }

        // Expect 'new' keyword
        self.expect(&TokenKind::Keyword(KeywordKind::New))?;

        // Parse optional type parameters: <T> — one wire level: the constructor type over
        // its type parameters
        let type_parameters = self.nested(1, Self::parse_optional_type_parameters)?;

        // Parse parameter list
        self.expect(&TokenKind::ParenOpen)?;
        let params = self.parse_function_type_params()?.into_bump_slice();
        self.expect(&TokenKind::ParenClose)?;

        // Expect arrow
        let arrow_start = self.current_pos().0 as u32;
        self.expect(&TokenKind::Arrow)?;

        // Parse return type (may be a type predicate)
        // two wire levels: the function type and its `TSTypeAnnotation` (the depth
        // limit's count)
        let return_type = self.nested(2, |p| p.parse_return_type_inner(arrow_start))?;
        let end = return_type.span.end;

        Ok(
            self.alloc(TSType::Constructor(self.arena.alloc(TSConstructorType {
                abstract_: is_abstract,
                type_parameters,
                params,
                return_type,
                span: Span::new(start as u32, end),
            }))),
        )
    }

    /// Parse function type parameters, up to (not including) the closing `)`.
    fn parse_function_type_params(
        &mut self,
    ) -> Result<bumpalo::collections::Vec<'arena, Expression<'arena>>, Error> {
        let mut params = self.bvec();

        // two wire levels each: the function type over its parameters, and the parameter
        // over its pattern and annotation (the depth limit's count; the function type's
        // own level rides its return type's path apart)
        if !self.check(&TokenKind::ParenClose) {
            let first = self.nested(2, Self::parse_function_type_param)?;
            let mut rest_seen = matches!(first.kind, ExpressionKind::RestElement(_));
            params.push(first);
            // the parameters are siblings (`ListFrame`); the first is already counted
            let mut frame = self.list_frame();
            while self.eat(TokenKind::Comma)? {
                // A rest parameter must be last: nothing — not even a trailing
                // comma — may follow it (see `parse_parameter_list`). In an
                // ambient (`declare`) context acorn tolerates a single trailing
                // comma; the `)` check below permits exactly that shape.
                if rest_seen {
                    if self.in_ambient_context && self.check(&TokenKind::ParenClose) {
                        break;
                    }
                    return Err(self.error_msg("A rest parameter must be last in a parameter list"));
                }
                // Handle trailing comma
                if self.check(&TokenKind::ParenClose) {
                    break;
                }
                frame.element(self, params.len());
                let param = self.nested(2, Self::parse_function_type_param)?;
                rest_seen = matches!(param.kind, ExpressionKind::RestElement(_));
                params.push(param);
            }
            frame.close(self);
        }

        Ok(params)
    }

    /// Parse a single function type parameter: an identifier (`x: T`), the `this`
    /// parameter (`this: T`), a destructuring pattern (`[a]?: T`, `{ a }: T`), or a
    /// rest element wrapping any of those (`...a: T[]`, `...[a]: T[]`, `...{ a }: T`).
    fn parse_function_type_param(&mut self) -> Result<Expression<'arena>, Error> {
        // Rest parameter: `...a`, `...[a]`, `...{ a }` (with an optional annotation).
        if self.check(&TokenKind::DotDotDot) {
            let (start, _) = self.current_pos();
            self.advance()?;
            // A rest argument is a bare binding — an identifier or a destructuring
            // pattern. Its optional `?` and `: T` bind to the `RestElement` (acorn's
            // shape), never to the inner binding, so parse them here rather than
            // through the shared param parser (which attaches them to the binding,
            // as for a non-rest `([a]?: T) => U`). The `?` is a deferred
            // grammar-check error (TS1047; see `RestElement`), preserved just as
            // `parameters.rs` preserves it for a value signature.
            let argument = if matches!(
                self.current_kind(),
                TokenKind::BracketOpen | TokenKind::BraceOpen
            ) {
                // one wire level: the pattern under the `RestElement` (the depth limit's
                // count)
                self.nested(1, Self::parse_binding_pattern)?
            } else {
                let (id_start, id_end) = self.current_pos();
                let name = self
                    .try_param_name()
                    .ok_or_else(|| self.error_expected("parameter name"))?;
                self.advance()?;
                Expression::from_identifier(Identifier::simple(
                    name,
                    Span::new(id_start as u32, id_end as u32),
                ))
            };
            let (optional, type_annotation, arg_end) =
                self.parse_rest_param_tail(argument.span().end)?;
            return Ok(Expression::from_rest_element(RestElement {
                argument: self.alloc(argument),
                optional,
                type_annotation,
                span: Span::new(start as u32, arg_end),
            }));
        }

        // Destructuring-pattern parameter: `[a, b]?: T`, `{ a }: T`. Shares the
        // parameter-list pattern parser (bare pattern, optional `?`, `: Type`),
        // so `optional`/span handling matches a real signature parameter.
        if matches!(
            self.current_kind(),
            TokenKind::BracketOpen | TokenKind::BraceOpen
        ) {
            return self.parse_destructured_binding(true);
        }

        let (id_start, id_end) = self.current_pos();

        // Accept identifiers and contextual keywords (e.g., `from`, `as`) as parameter
        // names, plus the `this` keyword (TypeScript `this` parameter: `(this: T) => U`).
        let name = self
            .try_param_name()
            .ok_or_else(|| self.error_expected("parameter name"))?;
        self.advance()?;

        // Check for optional: param? — a bare `?` extends the span.
        let (optional, id_end) = self.eat_optional_marker(id_end)?;

        // Check for type annotation: : T
        let type_annotation = self.parse_optional_type_annotation()?;

        let end = type_annotation
            .as_ref()
            .map_or_else(|| id_end as u32, |ta| ta.span.end);

        let extra = type_annotation.map(|ta| self.typed_extra(ta));

        Ok(Expression::from_identifier(Identifier {
            escaped_name: name.escaped,
            name_len: name.raw_len,
            name_plain_ascii: name.plain_ascii,
            optional,
            extra,
            span: Span::new(id_start as u32, end),
        }))
    }

    /// Parse object type: `{ prop: T; method(): U }` or mapped type: `{ [K in T]: V }`
    fn parse_object_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.expect(&TokenKind::BraceOpen)?;

        // Check for unambiguous mapped type modifiers: +/- (with or without readonly)
        // +readonly, -readonly, +, - all indicate mapped type
        if self.check(&TokenKind::Minus) || self.check(&TokenKind::Plus) {
            return self.parse_mapped_type_body(start);
        }

        // A mapped type (`{ [K in T]: V }`, optionally `readonly`) is the sole
        // member and is parsed specially. Index signatures (`{ [k: T]: V }`) and
        // computed-key members (`{ [expr]: V }`) both flow through the general
        // member loop below, where `parse_type_element` handles the `readonly`
        // modifier, index signatures, and arbitrary computed-key expressions.
        if self.is_mapped_type_start() {
            return self.parse_mapped_type_body(start);
        }

        // one wire level: the `TSTypeLiteral` its members sit in (the depth limit's count)
        let members = self.nested(1, Self::parse_type_members)?;

        let (_, end) = self.current_pos();
        self.expect(&TokenKind::BraceClose)?;

        Ok(self.alloc(TSType::TypeLiteral(TSTypeLiteral {
            members: members.into_bump_slice(),
            span: Span::new(start as u32, end as u32),
        })))
    }

    /// Parse the body of a mapped type (after '{' has been consumed)
    fn parse_mapped_type_body(&mut self, start: usize) -> Result<&'arena TSType<'arena>, Error> {
        // Parse optional readonly modifier: `readonly`, `+readonly`, `-readonly`
        let readonly = self.parse_mapped_type_readonly_modifier()?;

        // Expect `[`
        self.expect(&TokenKind::BracketOpen)?;

        // Parse type parameter name: `K` (identifier or contextual keyword; the
        // `IdentName` is `Copy`, so no owned `String` is threaded through to
        // `finish_mapped_type`).
        let param_start = self.current_pos().0;
        let param_name = self
            .try_ident_or_contextual_name()
            .ok_or_else(|| self.error_expected("type parameter name in mapped type"))?;
        self.advance()?;

        // Expect `in`
        if !matches!(self.current_kind(), TokenKind::Keyword(KeywordKind::In)) {
            return Err(self.error_expected("'in' in mapped type"));
        }
        self.advance()?; // consume 'in'

        self.finish_mapped_type(start, param_start, param_name, readonly)
    }

    /// Shared tail for mapped type parsing after `[K in` has been consumed.
    /// Parses: constraint, optional `as` clause, `]`, optional modifier, `:`, value type, `}`
    fn finish_mapped_type(
        &mut self,
        start: usize,
        param_start: usize,
        param_name: IdentName<'arena>,
        readonly: Option<TSMappedTypeModifier>,
    ) -> Result<&'arena TSType<'arena>, Error> {
        // Parse constraint type (e.g., `keyof T`); two wire levels: the `TSMappedType` and
        // the `TSTypeParameter` the constraint sits in
        let constraint = self.nested(2, Self::parse_type)?;
        let param_end = constraint.span().end;

        // Check for optional `as` clause: `as NewKey`
        let name_type = if self.eat(TokenKind::Keyword(KeywordKind::As))? {
            Some(self.nested(1, Self::parse_type)?)
        } else {
            None
        };

        // Expect `]`
        self.expect(&TokenKind::BracketClose)?;

        // Parse optional modifier: `?`, `+?`, `-?`
        let optional = self.parse_mapped_type_optional_modifier()?;

        // Parse optional `:` and value type — the annotation may be absent
        // entirely (`{ [K in T] }`, `{ [K in T]+? }`), matching acorn.
        let type_annotation = if self.eat(TokenKind::Colon)? {
            Some(self.nested(1, Self::parse_type)?)
        } else {
            None
        };

        // Consume optional separator
        self.eat(TokenKind::Semicolon)?;

        // Expect `}`
        let (_, end) = self.current_pos();
        self.expect(&TokenKind::BraceClose)?;

        Ok(self.alloc(TSType::Mapped(TSMappedType {
            type_parameter: TSMappedTypeParameter {
                name: param_name,
                constraint,
                span: Span::new(param_start as u32, param_end),
            },
            name_type,
            type_annotation,
            readonly,
            optional,
            span: Span::new(start as u32, end as u32),
        })))
    }

    /// Parse readonly modifier for mapped type: `readonly`, `+readonly`, `-readonly`.
    /// A `+`/`-` is a single optional sign that *must* be followed by `readonly`;
    /// a stray sign (`+[K in T]`, `-+readonly`) is a syntax error, not a silently
    /// dropped token (matches acorn-typescript).
    fn parse_mapped_type_readonly_modifier(
        &mut self,
    ) -> Result<Option<TSMappedTypeModifier>, Error> {
        if self.eat(TokenKind::Minus)? {
            // `-readonly`
            if self.eat_contextual_keyword("readonly")? {
                return Ok(Some(TSMappedTypeModifier::Minus));
            }
            return Err(self.error_expected("'readonly' after '-' in mapped type"));
        }

        if self.eat(TokenKind::Plus)? {
            // `+readonly`
            if self.eat_contextual_keyword("readonly")? {
                return Ok(Some(TSMappedTypeModifier::Plus));
            }
            return Err(self.error_expected("'readonly' after '+' in mapped type"));
        }

        if self.eat_contextual_keyword("readonly")? {
            return Ok(Some(TSMappedTypeModifier::True));
        }

        Ok(None)
    }

    /// Parse optional modifier for mapped type: `?`, `+?`, `-?`. A `+`/`-` is a
    /// single optional sign that *must* be followed by `?`; a stray sign
    /// (`[K in T]+:`) is a syntax error, not a silently dropped token (matches
    /// acorn-typescript).
    fn parse_mapped_type_optional_modifier(
        &mut self,
    ) -> Result<Option<TSMappedTypeModifier>, Error> {
        if self.eat(TokenKind::Minus)? {
            // `-?`
            if self.eat(TokenKind::Question)? {
                return Ok(Some(TSMappedTypeModifier::Minus));
            }
            return Err(self.error_expected("'?' after '-' in mapped type"));
        }

        if self.eat(TokenKind::Plus)? {
            // `+?`
            if self.eat(TokenKind::Question)? {
                return Ok(Some(TSMappedTypeModifier::Plus));
            }
            return Err(self.error_expected("'?' after '+' in mapped type"));
        }

        if self.eat(TokenKind::Question)? {
            return Ok(Some(TSMappedTypeModifier::True));
        }

        Ok(None)
    }

    /// Parse tuple type: `[T, U, V]`, `[...T]`, `[label: T]`, `[T?]`, `[first: string, ...rest: T]`
    fn parse_tuple_type(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let start = self.current_pos().0;
        self.expect(&TokenKind::BracketOpen)?;

        let mut element_types = self.bvec();
        if !self.check(&TokenKind::BracketClose) {
            // each element one wire level below the `TSTupleType` (the depth limit's count)
            element_types.push(self.nested(1, Self::parse_tuple_element)?);
            // the elements are siblings (`ListFrame`); the first is already counted
            let mut frame = self.list_frame();
            while self.eat(TokenKind::Comma)? {
                if self.check(&TokenKind::BracketClose) {
                    break; // trailing comma
                }
                // the pair the printer adds around a union element of a tuple of more than
                // one once the tuple breaks (`[⏎\t(⏎\t\t| A⏎\t\t| B⏎\t),⏎\tc⏎]`), a level of
                // the output's nesting: the first element's, now that a second follows
                if element_types.len() == 1 && is_union_element(element_types[0]) {
                    self.printer_pair()?;
                }
                frame.element(self, element_types.len());
                let element = self.nested(1, Self::parse_tuple_element)?;
                if is_union_element(element) {
                    self.printer_pair()?;
                }
                element_types.push(element);
            }
            frame.close(self);
        }

        let (_, end) = self.current_pos();
        self.expect(&TokenKind::BracketClose)?;

        Ok(self.alloc(TSType::Tuple(TSTupleType {
            element_types: element_types.into_bump_slice(),
            span: Span::new(start as u32, end as u32),
        })))
    }

    /// Parse a single tuple element: `T`, `T?`, `...T`, `label: T`, `label?: T`, `...label: T`
    fn parse_tuple_element(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let elem_start = self.current_pos().0;

        // Check for rest element: `...T` or `...label: T`
        if self.eat(TokenKind::DotDotDot)? {
            // one wire level: the `TSRestType` over its element
            let inner = self.nested(1, Self::parse_tuple_element_inner)?;
            let end = inner.span().end;
            return Ok(self.alloc(TSType::Rest(TSRestType {
                type_annotation: inner,
                span: Span::new(elem_start as u32, end),
            })));
        }

        self.parse_tuple_element_inner()
    }

    /// The postfix optional `?` of a tuple element sits at a `[no LineTerminator here]`
    /// position, so `[T⏎?]` is a syntax error rather than an optional element.
    ///
    /// tsc runs the whole postfix suffix loop — `?`, `!` and `[` alike — under
    /// `while (!scanner.hasPrecedingLineBreak())` (`parsePostfixTypeOrHigher`), which is
    /// the same rule [`Self::parse_array_type`] applies to the postfix `[`; this is the
    /// remaining member of that family. oxc agrees. acorn-typescript and babel accept the
    /// break: their `tsParseTupleElementType` bare-`eat`s the `?` while spelling the guard
    /// for the array suffix one function below, so this is a slip in the port, not a
    /// choice — tsv is deliberately stricter, cataloged in `docs/conformance_svelte.md`
    /// §TypeScript Corrections.
    ///
    /// The **named**-member marker (`[a⏎?: T]`) is a different grammar position and takes
    /// the break; tsc parses it through `parseOptionalToken`, outside that loop.
    ///
    /// Per ecma262 §sec-comments a block comment holding a line terminator *is* one, so
    /// `[T /* c⏎ */?]` and `[T // c⏎?]` are rejected too — `had_line_terminator` already
    /// folds both in.
    ///
    /// `marker_pos` is the `?` itself, which the named-member path has already advanced
    /// past by the time it can tell the two markers apart — so both callers pass it
    /// rather than letting the caret drift a token between them.
    fn error_optional_marker_after_line_break(&self, marker_pos: usize) -> Error {
        self.error_msg_at(
            "Optional tuple element `?` cannot follow a line terminator",
            marker_pos,
        )
    }

    /// The current token read as a tuple element's LABEL, with the keyword it was
    /// spelled as (`None` for a plain identifier) — the head of `label: T` / `label?: T`.
    ///
    /// A label is an `IdentifierName`, so a reserved or contextual keyword spells one
    /// too (`[function: string]`, `[string?: number]`) — tsc, prettier and
    /// acorn-typescript all read it that way. A keyword token is never `\u`-escaped (the
    /// lexer re-classifies an escaped one as an `Identifier`), so its name reads raw.
    /// The caller keeps the keyword because the head may turn out to be a standalone
    /// type instead — see [`Parser::tuple_label_head_as_type`].
    fn tuple_label_head(&self) -> Option<(IdentName<'arena>, Option<KeywordKind>)> {
        match self.current_kind() {
            TokenKind::Identifier => Some((self.current_ident_name(), None)),
            TokenKind::Keyword(kw) => Some((self.current_raw_ident_name(), Some(*kw))),
            _ => None,
        }
    }

    /// The already-consumed label-position head of a tuple element, re-read as the
    /// standalone type it turned out to be (`[T?]`, `[this?]`, `[void?]`).
    ///
    /// `[T?]` and `[T?: U]` are told apart only by the token *after* the `?`, and this
    /// parser has one token of lookahead — so the head is consumed as a label first and
    /// rebuilt here when the `:` never arrives. Every head that reaches this point spells
    /// a **leaf** type, so nothing needs re-lexing: the primitive keywords
    /// (`void`/`null`/`true`/`string`/…) are their own node, `this` is the `this` type,
    /// and every other keyword is an ordinary type-reference name (TS's type space is a
    /// separate `IdentifierName` namespace).
    ///
    /// The exception is the three keywords that must be *followed* by more type syntax —
    /// `typeof T`, `new () => T`, `import('m')` — where the `?` we consumed already made
    /// this a syntax error (`[typeof?]` rejects in tsc and acorn-typescript alike). The
    /// caret points at the keyword, which is the construct that lost its operand.
    fn tuple_label_head_as_type(
        &self,
        keyword: Option<KeywordKind>,
        name: IdentName<'arena>,
        span: Span,
    ) -> Result<&'arena TSType<'arena>, Error> {
        if let Some(kw) = keyword {
            if let Some(ts_kind) = TSKeywordKind::from_lexer_keyword(kw) {
                return Ok(self.alloc(TSType::Keyword(TSKeywordType::new(ts_kind, span))));
            }
            match kw {
                KeywordKind::This => return Ok(self.alloc(TSType::ThisType(TSThisType { span }))),
                KeywordKind::Typeof | KeywordKind::New | KeywordKind::Import => {
                    return Err(self.error_msg_at("Expected a type name", span.start as usize));
                }
                _ => {}
            }
        }
        Ok(self.alloc(TSType::TypeReference(TSTypeReference {
            type_name: TSEntityName::Identifier(Identifier::simple(name, span)),
            type_arguments: None,
            span,
        })))
    }

    /// Parse a tuple element (without leading `...`): `T`, `T?`, `label: T`, `label?: T`
    fn parse_tuple_element_inner(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        let elem_start = self.current_pos().0;

        // Check for named tuple member: `label: T` or `label?: T`
        // A label head followed by `:` indicates a named tuple member
        // A label head followed by `?:` indicates an optional named tuple member
        if let Some((label_name, label_keyword)) = self.tuple_label_head()
            && matches!(self.peek_kind(), TokenKind::Colon | TokenKind::Question)
        {
            let (label_start, label_end) = self.current_pos();
            self.advance()?; // consume the label token

            // A `?` here is either the named-member marker (`label?: T`) or the postfix
            // optional one (`TypeRef?`), and only the token AFTER it tells them apart —
            // so consume it and decide, rather than backtracking (which this parser
            // can't do cheaply).
            let optional = if self.check(&TokenKind::Question) {
                // Only the named marker may follow a line break; the postfix one is a
                // `[no LineTerminator here]` position (see
                // `error_optional_marker_after_line_break`). Read before the `advance`,
                // which moves both the flag and the position onto the next token.
                let after_line_break = self.had_line_terminator;
                let marker_pos = self.current_pos().0;
                self.advance()?; // consume `?`
                if self.check(&TokenKind::Colon) {
                    true
                } else if after_line_break {
                    return Err(self.error_optional_marker_after_line_break(marker_pos));
                } else {
                    // This was actually `T?` — the head is a standalone type after all,
                    // and the `?` is the postfix optional marker.
                    let head = self.tuple_label_head_as_type(
                        label_keyword,
                        label_name,
                        Span::new(label_start as u32, label_end as u32),
                    )?;
                    // the postfix `?` wraps the type before it: a spine link
                    self.spine_link(LINK_TYPE_SUFFIX)?;
                    return Ok(self.alloc(TSType::Optional(TSOptionalType {
                        type_annotation: head,
                        span: Span::new(elem_start as u32, self.prev_token_end() as u32),
                    })));
                }
            } else {
                false
            };

            // Expect `:` and parse the element type; one wire level: the element type under
            // its `TSNamedTupleMember`
            self.expect(&TokenKind::Colon)?;
            let element_type = self.nested(1, Self::parse_type)?;
            let end = element_type.span().end;

            return Ok(self.alloc(TSType::NamedTupleMember(TSNamedTupleMember {
                label: Identifier::simple(
                    label_name,
                    Span::new(label_start as u32, label_end as u32),
                ),
                element_type,
                optional,
                span: Span::new(elem_start as u32, end),
            })));
        }

        // Parse as regular type, then check for trailing `?` (optional type)
        let inner_type = self.parse_type()?;

        // Check for optional suffix: `T?` — a `[no LineTerminator here]` position, see
        // `error_optional_marker_after_line_break`.
        if self.check(&TokenKind::Question) {
            if self.had_line_terminator {
                return Err(self.error_optional_marker_after_line_break(self.current_pos().0));
            }
            self.advance()?; // consume `?`
            // the postfix `?` wraps the type before it, as a `[]` does: a spine link
            // (`[[A?]?]` nests an optional type per tuple)
            self.spine_link(LINK_TYPE_SUFFIX)?;
            // the pair the printer adds around a bare element the `?` would rebind
            // (`[(A | B)?]`), a level of the output's nesting
            if bare_type_takes_pair(inner_type, TypePairPosition::Optional) {
                self.printer_pair()?;
            }
            let end = self.prev_token_end();
            Ok(self.alloc(TSType::Optional(TSOptionalType {
                type_annotation: inner_type,
                span: Span::new(elem_start as u32, end as u32),
            })))
        } else {
            Ok(inner_type)
        }
    }

    /// Parse a template literal in type context: `hello ${string} world`
    ///
    /// Parallel structure to `parse_template_literal()` in expression.rs but parses
    /// types inside ${} instead of expressions. Kept separate for clarity despite
    /// duplication - the two contexts (expression vs type) rarely change together.
    fn parse_template_literal_type(&mut self) -> Result<TemplateLiteralType<'arena>, Error> {
        let (start, _) = self.current_pos();
        let mut quasis = self.bvec();
        let mut types = self.bvec();

        match self.current_kind() {
            TokenKind::NoSubstitutionTemplate => {
                // Simple template with no interpolation: `hello world`
                let (elem_start, elem_end) = self.current_pos();
                let token = Span::new(elem_start as u32, elem_end as u32);
                let element = self.template_element(token, true, false)?;

                self.advance()?;

                quasis.push(element);

                Ok(TemplateLiteralType {
                    quasis: quasis.into_bump_slice(),
                    types: types.into_bump_slice(),
                    span: Span::new(start as u32, elem_end as u32),
                })
            }
            TokenKind::TemplateHead => {
                // Template with interpolation: `hello ${string}...`
                let (elem_start, elem_end) = self.current_pos();
                let token = Span::new(elem_start as u32, elem_end as u32);
                let element = self.template_element(token, false, false)?;

                self.advance()?;

                quasis.push(element);

                // Parse types and remaining template parts; the interpolations are siblings
                // (`ListFrame`)
                let mut frame = self.list_frame();
                loop {
                    frame.element(self, types.len());
                    // Parse the interpolated type (not expression!); two wire levels: the
                    // `TSLiteralType` and the `TemplateLiteral` it holds
                    let ts_type = self.nested(2, Self::parse_type)?;
                    types.push(ts_type);

                    // Expect closing } of the interpolation
                    if !self.check(&TokenKind::BraceClose) {
                        return Err(self.error_expected("'}' after type in template literal"));
                    }

                    // Use lexer to continue template from }
                    let token = self
                        .lexer
                        .continue_template_from_brace(self.current_raw_end())?;
                    self.update_current(token);

                    match *self.current_kind() {
                        TokenKind::TemplateTail => {
                            // Final part: }content`
                            let (tail_start, tail_end) = self.current_pos();
                            let element = self.template_element(
                                Span::new(tail_start as u32, tail_end as u32),
                                true,
                                false,
                            )?;

                            self.advance()?;

                            quasis.push(element);
                            frame.close(self);

                            return Ok(TemplateLiteralType {
                                quasis: quasis.into_bump_slice(),
                                types: types.into_bump_slice(),
                                span: Span::new(start as u32, tail_end as u32),
                            });
                        }
                        TokenKind::TemplateMiddle => {
                            // Middle part: }content${
                            let (mid_start, mid_end) = self.current_pos();
                            let element = self.template_element(
                                Span::new(mid_start as u32, mid_end as u32),
                                false,
                                false,
                            )?;

                            self.advance()?;

                            quasis.push(element);
                            // Continue loop for next interpolation
                        }
                        _ => {
                            return Err(self.error_msg("Unexpected token in template literal type"));
                        }
                    }
                }
            }
            _ => Err(self.error_expected_found("template literal type")),
        }
    }

    /// Parse type parameters: `<T, U extends V = W>`
    /// Parse a `<T, U>` type-parameter declaration list when the next token
    /// opens one (`<`), else `None` — the optional-generics guard shared by every
    /// declaration site (functions, classes, interfaces, type aliases, and call /
    /// method / construct signatures).
    pub(in crate::parser) fn parse_optional_type_parameters(
        &mut self,
    ) -> Result<Option<TSTypeParameterDeclaration<'arena>>, Error> {
        if self.check(&TokenKind::LessThan) {
            Ok(Some(self.parse_type_parameters()?))
        } else {
            Ok(None)
        }
    }

    pub(in crate::parser) fn parse_type_parameters(
        &mut self,
    ) -> Result<TSTypeParameterDeclaration<'arena>, Error> {
        let start = self.current_pos().0 as u32;
        self.expect(&TokenKind::LessThan)?;

        let mut params = self.bvec();
        let mut trailing_comma = None;
        // the parameters are siblings (`ListFrame`)
        let mut frame = self.list_frame();
        loop {
            frame.element(self, params.len());
            // two wire levels: the `TSTypeParameterDeclaration` and the parameter
            let param = self.nested(2, Self::parse_type_parameter)?;
            params.push(param);

            if !self.eat(TokenKind::Comma)? {
                break;
            }
            // Handle trailing comma
            if self.check_greater_than_in_type() {
                trailing_comma = Some(self.prev_token_end() as u32 - 1);
                break;
            }
        }
        frame.close(self);

        let end = self.greater_than_end_in_type()?;

        Ok(TSTypeParameterDeclaration {
            params: params.into_bump_slice(),
            trailing_comma,
            span: Span::new(start, end),
        })
    }

    /// Parse a single type parameter: `T`, `T extends U`, or `T extends U = V`
    /// With optional modifiers: `const T`, `in T`, `out T`, `in out T`
    fn parse_type_parameter(&mut self) -> Result<TSTypeParameter<'arena>, Error> {
        let start = self.current_pos().0 as u32;

        // Parse optional modifiers: `const` (TS 5.0) and the `in`/`out` variance pair
        // (TS 4.7), in ANY order. tsc's parser collects them with an order-free modifier
        // loop and leaves "'const' modifier must precede 'in'" to its grammar checker, so
        // the ordering rule joins the static-semantic early-errors tsv defers — and
        // prettier formats every ordering on a class, interface or type alias.
        let mut modifiers = TSTypeParameterModifiers::default();

        loop {
            let modifier = match self.current_kind() {
                TokenKind::Keyword(KeywordKind::Const) => TSTypeParameterModifier::Const,
                TokenKind::Keyword(KeywordKind::In) => TSTypeParameterModifier::In,
                // `out` is contextual, so it lexes as an identifier.
                TokenKind::Identifier if self.current_value() == "out" => {
                    TSTypeParameterModifier::Out
                }
                _ => break,
            };
            // A modifier keyword is only a MODIFIER when a name can still follow it on
            // the SAME line (tsc's `nextTokenCanFollowModifier`, whose default arm is
            // `nextTokenIsOnSameLineAndCanFollowModifier` — `nextToken()`, then bail on
            // `hasPrecedingLineBreak()`) — otherwise it IS the name, since `out` is
            // contextual and names a parameter as freely as `T` does (`<out>`,
            // `<out, T>`, `<out = string>`, `<in out>`). The test is the token's
            // *shape*, not its validity as a name: `extends` is a keyword, so
            // `<out extends string>` keeps `out` a modifier and then fails for want of
            // a name — which is what tsc, prettier and acorn all do. Reserved `in` /
            // `const` reach the name read and reject there, as before.
            //
            // The same-line half is what makes a break demote rather than weld: after
            // it, `<const⏎T>` reads `const` as the NAME and rejects because `const` is
            // reserved (tsc's TS1359, verbatim), and `<out⏎T>` makes `out` the name and
            // then trips on `T` (TS1005). Without it all three modifiers welded across
            // the break, tsv alone — acorn and prettier reject every spelling. Per
            // ecma262 §sec-comments a block comment holding a line terminator IS one,
            // so `<const /*⏎*/ T>` rejects on the same rule. The Svelte `{#snippet}`
            // generic list shares this parser, so it is one gate for both entry points.
            if !self.peek_is_identifier_or_keyword() || self.peek_preceded_by_line_terminator() {
                break;
            }
            // A REPEAT is rejected HERE, at the offending keyword, rather than left to
            // fail as a stray token further along: `<out out T>`. ⚠️ tsc's parser
            // instead accepts and raises TS1030 `'out' modifier already seen` from its
            // grammar checker, and prettier collapses the repeat. Under the
            // reject-vs-defer line (`docs/conformance_tsc.md`) a checker-raised rule only
            // *normally* defers, and this keeps the line the sibling positions already
            // draw — a repeated class-member modifier (`public public foo`) rejects too,
            // as a stray token. A deliberate rejection of input prettier formats, not a
            // gap. acorn agrees with tsv, message and all (`Duplicate modifier: 'out'`).
            //
            // The guard above runs FIRST, so a trailing repeat that is really the NAME
            // never reaches this: `<out out>` is variance `out` on a parameter named
            // `out`, which every oracle accepts.
            if !modifiers.push(modifier) {
                return Err(self.error_msg_at(
                    &format!("Duplicate modifier: '{}'", modifier.as_str()),
                    self.current_pos().0,
                ));
            }
            self.advance()?;
        }

        let (id_start, id_end) = self.current_pos();

        // Parse the type parameter name — a `BindingIdentifier`, so a contextual
        // type keyword is a legal name here (`class C { m<string>() {} }`), the
        // same set the value-binding positions take.
        let Some(ident_name) = self.try_binding_name() else {
            return Err(self.error_expected_found_at("type parameter name", id_start));
        };
        self.advance()?;
        let name = Identifier::simple(ident_name, Span::new(id_start as u32, id_end as u32));

        // Track the end position as we parse optional parts
        let mut end = id_end as u32;

        // Parse optional constraint: `extends U`
        let constraint = if self.check(&TokenKind::Keyword(KeywordKind::Extends)) {
            self.advance()?;
            let constraint_type = self.parse_type()?;
            // the pair the printer keeps around a conditional constraint for clarity
            // (`<T extends (A extends B ? C : D)>`), a level of the output's nesting
            if matches!(constraint_type, TSType::Conditional(_)) {
                self.printer_pair()?;
            }
            end = constraint_type.span().end;
            Some(constraint_type)
        } else {
            None
        };

        // Parse optional default: `= V`
        let default = if self.eat(TokenKind::Equals)? {
            let default_type = self.parse_type()?;
            end = default_type.span().end;
            Some(default_type)
        } else {
            None
        };

        Ok(TSTypeParameter {
            name,
            constraint,
            default,
            modifiers,
            span: Span::new(start, end),
        })
    }

    /// Parse type argument instantiation: `<T, U>` (for instantiation expressions like `f<T>`)
    ///
    /// Unlike parse_type_parameters, this parses actual types, not type parameter declarations.
    /// Used for TSInstantiationExpression and other type argument contexts.
    ///
    /// The list is read in the halves the expression-level lookahead grades apart
    /// — [`Self::parse_type_argument_list_head`] and
    /// [`Self::parse_type_argument_list_tail`] — which this runs back to back, committed.
    /// The one caller that tells them apart is `Parser::parse_type_arguments_or_rewind`.
    pub(in crate::parser) fn parse_type_parameter_instantiation(
        &mut self,
    ) -> Result<TSTypeParameterInstantiation<'arena>, Error> {
        let (start, first) = self.parse_type_argument_list_head()?;
        self.parse_type_argument_list_tail(start, first)
    }

    /// The head of a type-argument list: its `<` and its FIRST argument. Returns where
    /// the list starts and that argument, for [`Self::parse_type_argument_list_tail`].
    ///
    /// This is the half `Parser::is_type_arguments_start` grades before an expression
    /// commits to a list, so an error here is the list's own.
    pub(in crate::parser) fn parse_type_argument_list_head(
        &mut self,
    ) -> Result<(u32, &'arena TSType<'arena>), Error> {
        let start = self.current_pos().0 as u32;
        self.expect_less_than_in_type()?;
        Ok((start, self.parse_type_argument()?))
    }

    /// One argument of a type-argument list: two wire levels below the type that takes the
    /// list — the `TSTypeParameterInstantiation`, and the argument (the depth limit's
    /// count, [`Parser::nested`]). A type's nesting is counted where the type grammar
    /// recurses, as here, so a type that holds no other pays nothing.
    fn parse_type_argument(&mut self) -> Result<&'arena TSType<'arena>, Error> {
        self.nested(2, Self::parse_type)
    }

    /// The tail of a type-argument list, behind the first argument
    /// [`Self::parse_type_argument_list_head`] read: each `,` with the argument it
    /// separates (a trailing one with none), and the closing `>`.
    pub(in crate::parser) fn parse_type_argument_list_tail(
        &mut self,
        start: u32,
        first: &'arena TSType<'arena>,
    ) -> Result<TSTypeParameterInstantiation<'arena>, Error> {
        let mut params = self.bvec();
        params.push(first);
        // the arguments are siblings (`ListFrame`); the first is already counted
        let mut frame = self.list_frame();
        while self.eat(TokenKind::Comma)? {
            // Handle trailing comma
            if self.check_greater_than_in_type() {
                break;
            }
            frame.element(self, params.len());
            params.push(self.parse_type_argument()?);
        }
        frame.close(self);

        let end = self.greater_than_end_in_type()?;

        Ok(TSTypeParameterInstantiation {
            params: params.into_bump_slice(),
            span: Span::new(start, end),
        })
    }
}

/// Whether a tuple element is a union the printer parenthesizes once the tuple breaks,
/// where the author wrote no pair (`build_tuple_element_doc`, which strips an author's pair
/// and writes its own in its place).
fn is_union_element(element: &TSType<'_>) -> bool {
    matches!(element, TSType::Union(_))
}

/// The type positions whose pair the printer adds around a bare type that binds looser
/// than the position (`printer::types::helpers`'s `type_needs_parens_*` rules).
#[derive(Clone, Copy)]
enum TypePairPosition {
    /// A union or intersection member: `(A & B) | C`, `A | (infer U extends X)`.
    Member,
    /// An array element or an indexed access's object: `(typeof a)[]`, `(infer U)[K]`,
    /// `(-1)[]`.
    Suffix,
    /// An optional tuple element: `[(A | B)?]`.
    Optional,
}

/// Whether the printer adds a pair around `ts_type` in `position` where the author wrote
/// none — never around an author's pair (a `TSParenthesizedType` the parse counted as a
/// level already, which the printer keeps or strips), and around a bare type its rule
/// parenthesizes, read past a one-member union or intersection the printer prints as its
/// member as well as at it, so the answer is the printer's or above it.
fn bare_type_takes_pair(ts_type: &TSType<'_>, position: TypePairPosition) -> bool {
    if matches!(ts_type, TSType::Parenthesized(_)) {
        return false;
    }
    let mut ty = ts_type;
    loop {
        if type_takes_pair(ty, position) {
            return true;
        }
        ty = match ty {
            TSType::Union(u) if u.types.len() == 1 => u.types[0],
            TSType::Intersection(i) if i.types.len() == 1 => i.types[0],
            _ => return false,
        };
    }
}

/// [`bare_type_takes_pair`]'s rule for one type.
fn type_takes_pair(ty: &TSType<'_>, position: TypePairPosition) -> bool {
    let looser = matches!(
        ty,
        TSType::Union(_)
            | TSType::Intersection(_)
            | TSType::Function(_)
            | TSType::Constructor(_)
            | TSType::Conditional(_)
    );
    match position {
        TypePairPosition::Member => {
            looser || matches!(ty, TSType::Infer(i) if i.type_parameter.constraint.is_some())
        }
        TypePairPosition::Suffix => {
            looser
                || matches!(
                    ty,
                    TSType::TypeQuery(_)
                        | TSType::TypeOperator(_)
                        | TSType::Infer(_)
                        | TSType::Literal(TSLiteralType::UnaryExpression(_))
                )
        }
        TypePairPosition::Optional => {
            looser || matches!(ty, TSType::TypeOperator(_) | TSType::Infer(_))
        }
    }
}

impl<'arena> Parser<'_, 'arena> {
    /// Count the pair the printer adds around a bare union or intersection `member` that
    /// binds looser than its neighbours ([`TypePairPosition::Member`]), a level of the
    /// output's nesting.
    fn member_pair(&mut self, member: &TSType<'_>) -> Result<(), Error> {
        if bare_type_takes_pair(member, TypePairPosition::Member) {
            self.printer_pair()
        } else {
            Ok(())
        }
    }

    /// [`Parser::member_pair`] for a union's or intersection's first member, asked once a
    /// second follows it (`types` holding the first alone): a member of one is printed as
    /// itself.
    fn first_member_pair(&mut self, types: &[&TSType<'_>]) -> Result<(), Error> {
        match types {
            [first] => self.member_pair(first),
            _ => Ok(()),
        }
    }
}