macroforge_ts_quote 0.1.66

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

pub mod control_expr;
pub mod errors;
pub mod operators;
pub mod postfix;
pub mod precedence;
pub mod primary;

use crate::compiler::ir::{IrNode, IrSpan};
use crate::compiler::parser::{Context, Parser};
use crate::compiler::syntax::SyntaxKind;
use errors::{ParseError, ParseResult};
use precedence::prec;

impl Parser {
    /// Parses an expression.
    ///
    /// This is the main entry point for expression parsing.
    /// Returns a fully-parsed expression IR node.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let expr = parser.parse_expression()?;
    /// // expr might be: BinExpr { op: Add, left: NumLit("1"), right: NumLit("2") }
    /// ```
    pub fn parse_expression(&mut self) -> ParseResult<IrNode> {
        self.parse_expression_with_precedence(0)
    }

    /// Parses an expression with a minimum binding power.
    ///
    /// This is the core of the Pratt parser. It:
    /// 1. Parses a prefix expression (the "left" side)
    /// 2. Loops to parse infix operators while their precedence is high enough
    ///
    /// The `min_bp` parameter controls which operators can be parsed:
    /// - 0: Parse any expression (including comma)
    /// - prec::ASSIGN.right: Parse assignment-level and higher
    /// - prec::CONDITIONAL.right: Parse ternary-level and higher
    /// - etc.
    pub fn parse_expression_with_precedence(&mut self, min_bp: u8) -> ParseResult<IrNode> {
        self.skip_whitespace();

        // First, parse the prefix/primary expression
        let left = self.parse_primary_expr()?;

        // Then, loop to parse infix/postfix operators
        self.parse_postfix_and_infix(left, min_bp)
    }

    /// Parses an assignment expression.
    ///
    /// This is equivalent to `parse_expression_with_precedence(prec::COMMA.right)`,
    /// which excludes the comma operator. Use this when parsing individual items
    /// in comma-separated lists like function arguments or array elements.
    pub fn parse_assignment_expression(&mut self) -> ParseResult<IrNode> {
        self.parse_expression_with_precedence(prec::COMMA.right)
    }

    /// Parses an expression, stopping at any of the given terminators.
    ///
    /// This uses the Pratt parser with context-based termination. The terminators
    /// are pushed onto the context stack and checked in `at_terminator()` during
    /// the infix parsing loop.
    pub fn parse_expression_until(&mut self, terminators: &[SyntaxKind]) -> ParseResult<IrNode> {
        use super::{Context, ExpressionKind};
        self.with_context(
            Context::expression_from_slice(ExpressionKind::Normal, terminators),
            |parser| parser.parse_expression_with_precedence(0),
        )
    }

    /// Parses an expression until terminators, with explicit object literal context handling.
    ///
    /// The `in_object_literal` parameter explicitly indicates whether to parse in object literal
    /// context. This is used for control expressions like `{#for}` inside object literals where
    /// the context may have been modified during control block header parsing.
    ///
    /// When in object literal context, this parses a key-value property pattern (key: value)
    /// instead of treating `:` as an unexpected token.
    pub fn parse_expression_until_in_context(
        &mut self,
        terminators: &[SyntaxKind],
        in_object_literal: bool,
    ) -> ParseResult<IrNode> {
        use super::{Context, ExpressionKind};

        if in_object_literal {
            // Parse with ObjectLiteral context to properly handle `:` as property separator
            self.with_context(
                Context::expression_from_slice(ExpressionKind::ObjectLiteral, terminators),
                |parser| parser.parse_object_property_in_control_context(),
            )
        } else {
            // Normal expression parsing
            self.with_context(
                Context::expression_from_slice(ExpressionKind::Normal, terminators),
                |parser| parser.parse_expression_with_precedence(0),
            )
        }
    }

    /// Parses an object property inside a control block context.
    ///
    /// This handles patterns like `@{name}: @{value}` inside `{#for}` blocks within object literals.
    fn parse_object_property_in_control_context(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();
        let start_byte = self.current_byte_offset();

        // Parse the key (first part before potential `:`)
        let key = self.parse_expression_with_precedence(0)?;

        self.skip_whitespace();

        // Check if this is a key-value property (has `:`)
        if self.at(SyntaxKind::Colon) {
            self.consume(); // :
            self.skip_whitespace();

            // Parse the value - use assignment precedence to properly handle the value expression
            let value = self.parse_expression_with_precedence(prec::ASSIGN.right)?;

            self.skip_whitespace();

            // Consume trailing comma if present (common in for loops generating properties)
            if self.at(SyntaxKind::Comma) {
                self.consume();
            }

            Ok(IrNode::KeyValueProp {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                key: Box::new(key),
                value: Box::new(value),
            })
        } else {
            // No colon - treat as shorthand property or regular expression
            // Consume trailing comma if present
            if self.at(SyntaxKind::Comma) {
                self.consume();
            }

            // Check if it looks like a shorthand property (identifier without value)
            match &key {
                IrNode::Ident { .. } | IrNode::Placeholder { .. } => Ok(IrNode::ShorthandProp {
                    span: key.span(),
                    key: Box::new(key),
                }),
                _ => Ok(key),
            }
        }
    }

    /// Parses arrow function parameters.
    ///
    /// Handles: `(a, b, c)` or `a` (single identifier without parens).
    pub(super) fn parse_arrow_params(&mut self) -> ParseResult<Vec<IrNode>> {
        self.skip_whitespace();

        if self.at(SyntaxKind::LParen) {
            self.parse_function_params()
        } else if self.at(SyntaxKind::Ident) {
            // Single identifier: x => x + 1
            let token = self.consume().expect("guarded by at() check");
            let span = token.ir_span();
            Ok(vec![IrNode::Param {
                span,
                decorators: Vec::new(),
                pat: Box::new(IrNode::BindingIdent {
                    span,
                    name: Box::new(IrNode::ident(&token)),
                    type_ann: None,
                    optional: false,
                }),
            }])
        } else {
            Err(ParseError::new(
                errors::ParseErrorKind::InvalidArrowParams,
                self.current_byte_offset(),
            ))
        }
    }

    /// Parses function parameters: (param1, param2, ...)
    pub(super) fn parse_function_params(&mut self) -> ParseResult<Vec<IrNode>> {
        let start_pos = self.pos;

        self.expect(SyntaxKind::LParen).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["("])
        })?;

        let mut params = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RParen) {
                break;
            }

            let param = self.parse_single_param()?;
            params.push(param);

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::RParen) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingParen,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume(); // )

        Ok(params)
    }

    /// Parses a single function parameter.
    pub(super) fn parse_single_param(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();
        let start_byte = self.current_byte_offset();

        // Handle decorators
        let decorators = self.parse_decorators()?;

        self.skip_whitespace();

        // Handle rest parameter: ...arg
        if self.at(SyntaxKind::DotDotDot) {
            self.consume();
            self.skip_whitespace();
            let pat = self.parse_binding_pattern()?;
            return Ok(IrNode::RestPat {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                arg: Box::new(pat),
                type_ann: None, // TODO: parse type annotation
            });
        }

        // Handle placeholder
        if self.at(SyntaxKind::At) {
            let placeholder = self.parse_interpolation()?;
            return Ok(IrNode::Param {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                decorators,
                pat: Box::new(placeholder),
            });
        }

        // Parse the pattern (identifier, destructuring, etc.)
        let pat = self.parse_binding_pattern()?;

        Ok(IrNode::Param {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            decorators,
            pat: Box::new(pat),
        })
    }

    /// Parses a binding pattern (identifier with optional type annotation and initializer).
    fn parse_binding_pattern(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();

        let Some(token) = self.current() else {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "binding pattern",
            ));
        };

        match token.kind {
            SyntaxKind::Ident => {
                let ident_token = self.consume().expect("guarded by match arm");
                let span = ident_token.ir_span();
                self.skip_whitespace();

                // Check for optional marker: ?
                let optional = if self.at(SyntaxKind::Question) {
                    self.consume();
                    self.skip_whitespace();
                    true
                } else {
                    false
                };

                // Check for type annotation: : Type
                let type_ann = if self.at(SyntaxKind::Colon) {
                    self.consume();
                    self.skip_whitespace();
                    // Push TypeAnnotation context so placeholders get correct kind
                    self.push_context(Context::type_annotation([
                        SyntaxKind::Comma,
                        SyntaxKind::RParen,
                        SyntaxKind::Eq,
                    ]));
                    let ty = self.parse_type()?;
                    self.pop_context();
                    Some(Box::new(ty))
                } else {
                    None
                };

                self.skip_whitespace();

                // Check for initializer: = default
                if self.at_text("=") {
                    self.consume();
                    self.skip_whitespace();
                    let init = self.parse_expression_with_precedence(prec::ASSIGN.right)?;
                    return Ok(IrNode::AssignPat {
                        span,
                        left: Box::new(IrNode::BindingIdent {
                            span,
                            name: Box::new(IrNode::ident(&ident_token)),
                            type_ann,
                            optional,
                        }),
                        right: Box::new(init),
                    });
                }

                Ok(IrNode::BindingIdent {
                    span,
                    name: Box::new(IrNode::ident(&ident_token)),
                    type_ann,
                    optional,
                })
            }
            SyntaxKind::LBracket => self.parse_array_pattern(),
            SyntaxKind::LBrace => self.parse_object_pattern(),
            _ => Err(ParseError::new(
                errors::ParseErrorKind::InvalidFunctionParameter,
                self.current_byte_offset(),
            )
            .with_found(&token.text)),
        }
    }

    /// Parses an array destructuring pattern: [a, b, ...rest]
    fn parse_array_pattern(&mut self) -> ParseResult<IrNode> {
        let start_pos = self.pos;
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LBracket);

        let mut elems = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBracket) {
                break;
            }

            // Handle holes: [,, x]
            if self.at(SyntaxKind::Comma) {
                elems.push(None); // Hole in array pattern
                self.consume();
                continue;
            }

            // Handle rest: [...x]
            if self.at(SyntaxKind::DotDotDot) {
                let rest_start = self.current_byte_offset();
                self.consume();
                self.skip_whitespace();
                let arg = self.parse_binding_pattern()?;
                elems.push(Some(IrNode::RestPat {
                    span: IrSpan::new(rest_start, self.current_byte_offset()),
                    arg: Box::new(arg),
                    type_ann: None,
                }));
            } else {
                let elem = self.parse_binding_pattern()?;
                elems.push(Some(elem));
            }

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::RBracket) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBracket,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        self.skip_whitespace();

        // Optional type annotation
        let type_ann = if self.at(SyntaxKind::Colon) {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        Ok(IrNode::ArrayPat {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            elems,
            type_ann,
            optional: false,
        })
    }

    /// Parses an object destructuring pattern: { a, b: c, ...rest }
    fn parse_object_pattern(&mut self) -> ParseResult<IrNode> {
        let start_pos = self.pos;
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LBrace);

        let mut props = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBrace) {
                break;
            }

            // Handle rest: {...x}
            if self.at(SyntaxKind::DotDotDot) {
                let rest_start = self.current_byte_offset();
                self.consume();
                self.skip_whitespace();
                let arg = self.parse_binding_pattern()?;
                props.push(IrNode::RestPat {
                    span: IrSpan::new(rest_start, self.current_byte_offset()),
                    arg: Box::new(arg),
                    type_ann: None,
                });
            } else {
                let prop = self.parse_binding_object_prop()?;
                props.push(prop);
            }

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::RBrace) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        self.skip_whitespace();

        // Optional type annotation
        let type_ann = if self.at(SyntaxKind::Colon) {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        Ok(IrNode::ObjectPat {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            props,
            type_ann,
            optional: false,
        })
    }

    /// Parses a single property in an object pattern.
    fn parse_binding_object_prop(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();

        let Some(token) = self.current() else {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "object pattern property",
            ));
        };

        // Get the key
        let key = match token.kind {
            SyntaxKind::Ident => {
                let t = self.consume().expect("guarded by match arm");
                IrNode::ident(&t)
            }
            SyntaxKind::DoubleQuote | SyntaxKind::SingleQuote => self.parse_string_literal()?,
            SyntaxKind::LBracket => {
                // Computed property name
                self.consume();
                self.skip_whitespace();
                let expr = self.parse_expression_with_precedence(0)?;
                self.skip_whitespace();
                self.expect(SyntaxKind::RBracket);
                IrNode::ComputedPropName {
                    span: IrSpan::empty(),
                    expr: Box::new(expr),
                }
            }
            _ if token.kind.is_ts_keyword() => {
                let t = self.consume().expect("guarded by match arm");
                IrNode::ident(&t)
            }
            _ => {
                return Err(ParseError::new(
                    errors::ParseErrorKind::InvalidPropertyName,
                    self.current_byte_offset(),
                )
                .with_found(&token.text));
            }
        };

        self.skip_whitespace();

        let key_span = key.span();

        // Check for : to rename
        if self.at(SyntaxKind::Colon) {
            self.consume();
            self.skip_whitespace();
            let value = self.parse_binding_pattern()?;
            return Ok(IrNode::ObjectPatProp {
                span: key_span,
                key: Box::new(key),
                value: Some(Box::new(value)),
            });
        }

        // Shorthand: { a } or { a = default }
        self.skip_whitespace();

        if self.at_text("=") {
            self.consume();
            self.skip_whitespace();
            let init = self.parse_expression_with_precedence(prec::ASSIGN.right)?;
            // For default values in destructuring, wrap in AssignPat
            return Ok(IrNode::ObjectPatProp {
                span: key_span,
                key: Box::new(key.clone()),
                value: Some(Box::new(IrNode::AssignPat {
                    span: key_span,
                    left: Box::new(key),
                    right: Box::new(init),
                })),
            });
        }

        // Shorthand property: { a }
        Ok(IrNode::ObjectPatProp {
            span: key_span,
            key: Box::new(key),
            value: None,
        })
    }

    /// Parses decorators: @decorator @decorator2
    fn parse_decorators(&mut self) -> ParseResult<Vec<IrNode>> {
        let mut decorators = Vec::new();

        // Handle both At (placeholder @{...}) and DecoratorAt (@name) tokens
        while self.at(SyntaxKind::At) || self.at(SyntaxKind::DecoratorAt) {
            // Check if this is a placeholder @{} or a decorator @name
            // The lexer combines "@{" into a single At token, so check the text
            if let Some(text) = self.current_text() {
                if text.starts_with("@{") {
                    // It's a placeholder, stop parsing decorators
                    break;
                }
            }

            let dec_start = self.current_byte_offset();
            self.consume(); // @ or DecoratorAt
            self.skip_whitespace();

            let expr = self.parse_expression_with_precedence(prec::CALL.left)?;
            decorators.push(IrNode::Decorator {
                span: IrSpan::new(dec_start, self.current_byte_offset()),
                expr: Box::new(expr),
            });

            self.skip_whitespace();
        }

        Ok(decorators)
    }

    /// Parses optional type parameters: <T, U>
    pub(super) fn parse_optional_type_params(&mut self) -> Option<Box<IrNode>> {
        self.skip_whitespace();

        if !self.at(SyntaxKind::Lt) {
            return None;
        }

        // Try to parse type params
        match self.parse_type_params() {
            Ok(params) => Some(Box::new(params)),
            Err(_) => None,
        }
    }

    /// Parses type parameters: <T, U extends V>
    fn parse_type_params(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        self.expect(SyntaxKind::Lt).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["<"])
        })?;

        let mut params = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::Gt) {
                break;
            }

            let param = self.parse_type_param()?;
            params.push(param);

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::Gt) {
            return Err(ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&[">"]));
        }
        self.consume();

        Ok(IrNode::TypeParams {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            params,
        })
    }

    /// Parses a single type parameter: T or T extends U = Default
    fn parse_type_param(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();
        let start_byte = self.current_byte_offset();

        // Get the name
        let name = if self.at(SyntaxKind::Ident) {
            self.consume().expect("guarded by at() check").text
        } else if self.at(SyntaxKind::At) {
            // Placeholder as type param name
            let placeholder = self.parse_interpolation()?;
            return Ok(placeholder);
        } else {
            return Err(ParseError::new(
                errors::ParseErrorKind::ExpectedIdentifier,
                self.current_byte_offset(),
            ));
        };

        self.skip_whitespace();

        // Optional constraint: extends Type
        let constraint = if self.at(SyntaxKind::ExtendsKw) {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        self.skip_whitespace();

        // Optional default: = Type
        let default = if self.at_text("=") {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        Ok(IrNode::TypeParam {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            name,
            constraint,
            default,
        })
    }

    /// Parses optional type arguments: <T, U>
    pub(super) fn parse_optional_type_args(&mut self) -> ParseResult<Option<IrNode>> {
        self.skip_whitespace();

        if !self.at(SyntaxKind::Lt) {
            return Ok(None);
        }

        let type_args = self.parse_type_args()?;
        Ok(Some(type_args))
    }

    /// Parses type arguments: <T, U>
    fn parse_type_args(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        self.expect(SyntaxKind::Lt).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["<"])
        })?;

        let mut params = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::Gt) {
                break;
            }

            let ty = self.parse_type()?;
            params.push(ty);

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::Gt) {
            return Err(ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&[">"]));
        }
        self.consume();

        Ok(IrNode::TypeArgs {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            args: params,
        })
    }

    /// Parses an optional return type annotation: : Type
    pub(super) fn parse_optional_return_type(&mut self) -> ParseResult<Option<Box<IrNode>>> {
        self.skip_whitespace();

        if !self.at(SyntaxKind::Colon) {
            return Ok(None);
        }

        self.consume(); // :
        self.skip_whitespace();

        // Push TypeAnnotation context so placeholders get correct kind
        self.push_context(Context::type_annotation([
            SyntaxKind::LBrace,
            SyntaxKind::Semicolon,
        ]));
        let ty = self.parse_type()?;
        self.pop_context();
        Ok(Some(Box::new(ty)))
    }

    /// Parses a type annotation.
    ///
    /// This is a simplified type parser - full TypeScript type parsing is complex.
    /// For now, we handle common cases and fall back to collecting tokens for complex types.
    pub(super) fn parse_type(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();

        // Handle placeholder - need to check for type modifiers ([], |, &)
        if self.at(SyntaxKind::At) {
            let placeholder = self.parse_interpolation()?;
            self.skip_whitespace();
            // Always check for type modifiers (array [], union |, intersection &)
            return self.parse_type_modifiers(placeholder);
        }

        let Some(token) = self.current() else {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "type annotation",
            ));
        };

        // Handle keyword types
        let base_type = match token.kind {
            SyntaxKind::TypeKw
                if token.text == "string" || token.text == "number" || token.text == "boolean" =>
            {
                let t = self.consume().ok_or_else(|| {
                    ParseError::unexpected_eof(self.current_byte_offset(), "expected type keyword")
                })?;
                IrNode::keyword_type(&t, self.text_to_ts_keyword(&t.text)?)
            }
            SyntaxKind::Ident => {
                let t = self.consume().expect("guarded by match arm");
                let span = t.ir_span();

                // Check for common type keywords that come as identifiers
                match t.text.as_str() {
                    "string" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::String),
                    "number" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Number),
                    "boolean" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Boolean),
                    "any" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Any),
                    "unknown" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Unknown),
                    "never" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Never),
                    "object" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Object),
                    "symbol" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Symbol),
                    "bigint" => IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::BigInt),
                    _ => {
                        // Check for qualified name: NS.SubModule.Type
                        let mut current: IrNode = IrNode::ident(&t);
                        let mut current_span = span;

                        while self.at(SyntaxKind::Dot) {
                            self.consume(); // consume '.'
                            self.skip_whitespace();

                            if !self.at(SyntaxKind::Ident) {
                                return Err(ParseError::new(
                                    errors::ParseErrorKind::ExpectedTypeAnnotation,
                                    self.current_byte_offset(),
                                )
                                .with_expected(&["identifier"]));
                            }

                            let right_token = self.consume().expect("guarded by at() check");
                            let right_span = right_token.ir_span();

                            current = IrNode::QualifiedName {
                                span: IrSpan::new(current_span.start, right_span.end),
                                left: Box::new(current),
                                right: Box::new(IrNode::ident(&right_token)),
                            };
                            current_span = IrSpan::new(current_span.start, right_span.end);
                        }

                        // Check for generic type arguments like <string, unknown>
                        let type_params = self.parse_optional_type_args()?.map(Box::new);
                        IrNode::TypeRef {
                            span: current_span,
                            name: Box::new(current),
                            type_params,
                        }
                    }
                }
            }
            SyntaxKind::VoidKw => {
                let t = self.consume().unwrap();
                IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Void)
            }
            SyntaxKind::NullKw => {
                let t = self.consume().unwrap();
                IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Null)
            }
            SyntaxKind::UndefinedKw => {
                let t = self.consume().unwrap();
                IrNode::keyword_type(&t, crate::compiler::ir::TsKeyword::Undefined)
            }
            // Function type: () => T  OR  Parenthesized type: (T)
            SyntaxKind::LParen => self.parse_paren_or_function_type()?,
            // Array type or tuple: [T, U] or T[]
            SyntaxKind::LBracket => self.parse_tuple_type()?,
            // Object type: { prop: T }
            SyntaxKind::LBrace => self.parse_object_type()?,
            // typeof type
            SyntaxKind::TypeofKw => {
                let t = self.consume().unwrap();
                self.skip_whitespace();
                let expr = self.parse_primary_expr()?;
                IrNode::TypeofType {
                    span: t.ir_span(),
                    expr: Box::new(expr),
                }
            }
            // keyof type
            SyntaxKind::KeyofKw => {
                let t = self.consume().unwrap();
                self.skip_whitespace();
                let ty = self.parse_type()?;
                IrNode::KeyofType {
                    span: t.ir_span(),
                    type_ann: Box::new(ty),
                }
            }
            // String literal type: "foo" or 'bar'
            SyntaxKind::DoubleQuote | SyntaxKind::SingleQuote => {
                let lit = self.parse_string_literal()?;
                IrNode::LiteralType {
                    span: lit.span(),
                    lit: Box::new(lit),
                }
            }
            // Number literal type: 42, 3.14
            SyntaxKind::Text
                if token
                    .text
                    .chars()
                    .next()
                    .map(|c| c.is_ascii_digit() || c == '-')
                    .unwrap_or(false) =>
            {
                let lit = self.parse_numeric_literal()?;
                IrNode::LiteralType {
                    span: lit.span(),
                    lit: Box::new(lit),
                }
            }
            // Boolean literal type: true, false
            SyntaxKind::TrueKw | SyntaxKind::FalseKw => {
                let t = self.consume().unwrap();
                let lit = IrNode::bool_lit(&t);
                IrNode::LiteralType {
                    span: t.ir_span(),
                    lit: Box::new(lit),
                }
            }
            // Constructor type: new (params) => Type
            SyntaxKind::NewKw => {
                let start = self.consume().unwrap(); // consume 'new'
                self.skip_whitespace();

                // Parse optional type parameters
                let type_params = self.parse_optional_type_params();
                self.skip_whitespace();

                // Parse parameters
                let params = self.parse_function_params()?;
                self.skip_whitespace();

                // Expect =>
                if !self.at_text("=>") {
                    return Err(ParseError::new(
                        errors::ParseErrorKind::MissingArrowBody,
                        self.current_byte_offset(),
                    )
                    .with_expected(&["=>"]));
                }
                self.consume();
                self.skip_whitespace();

                let return_type = self.parse_type()?;

                IrNode::ConstructorType {
                    span: IrSpan::new(start.ir_span().start, self.current_byte_offset()),
                    type_params,
                    params,
                    return_type: Box::new(return_type),
                }
            }
            // this type
            SyntaxKind::ThisKw => {
                let t = self.consume().unwrap();
                IrNode::this_type(&t)
            }
            // infer type: infer T
            SyntaxKind::InferKw => {
                let start = self.consume().unwrap(); // consume 'infer'
                self.skip_whitespace();

                // Parse the type parameter name
                let type_param = self.parse_type_param()?;

                IrNode::InferType {
                    span: IrSpan::new(start.ir_span().start, self.current_byte_offset()),
                    type_param: Box::new(type_param),
                }
            }
            // import type: import("module")
            SyntaxKind::ImportKw => {
                let start = self.consume().unwrap(); // consume 'import'
                self.skip_whitespace();

                // Expect (
                if !self.at(SyntaxKind::LParen) {
                    return Err(ParseError::new(
                        errors::ParseErrorKind::ExpectedTypeAnnotation,
                        self.current_byte_offset(),
                    )
                    .with_expected(&["("]));
                }
                self.consume(); // consume '('
                self.skip_whitespace();

                // Parse the module string argument
                let arg = self.parse_type()?;
                self.skip_whitespace();

                // Expect )
                if !self.at(SyntaxKind::RParen) {
                    return Err(ParseError::new(
                        errors::ParseErrorKind::MissingClosingParen,
                        self.current_byte_offset(),
                    )
                    .with_expected(&[")"]));
                }
                self.consume(); // consume ')'
                self.skip_whitespace();

                // Optional qualifier: import("module").Foo
                let qualifier = if self.at(SyntaxKind::Dot) {
                    self.consume(); // consume '.'
                    self.skip_whitespace();
                    let q = self.parse_type()?;
                    Some(Box::new(q))
                } else {
                    None
                };

                // Optional type args: import("module")<T>
                let type_args = self.parse_optional_type_args()?.map(Box::new);

                IrNode::ImportType {
                    span: IrSpan::new(start.ir_span().start, self.current_byte_offset()),
                    arg: Box::new(arg),
                    qualifier,
                    type_args,
                }
            }
            _ => {
                return Err(ParseError::new(
                    errors::ParseErrorKind::ExpectedTypeAnnotation,
                    self.current_byte_offset(),
                )
                .with_found(&token.text));
            }
        };

        self.skip_whitespace();

        // Handle type modifiers: []  for array, | for union, & for intersection
        self.parse_type_modifiers(base_type)
    }

    /// Parses type modifiers after a base type ([], |, &, extends, [K], is)
    fn parse_type_modifiers(&mut self, mut ty: IrNode) -> ParseResult<IrNode> {
        loop {
            self.skip_whitespace();

            // Type predicate: param is Type
            // Only handle this for identifier/this base types (not complex types)
            if self.at(SyntaxKind::IsKw) {
                // The current `ty` should be an identifier (param name)
                // If it's wrapped in TypeRef, unwrap to get the inner Ident
                let param_name = match ty {
                    IrNode::TypeRef {
                        name,
                        type_params: None,
                        ..
                    } => *name,
                    other => other,
                };
                let start = param_name.span().start;
                self.consume(); // consume 'is'
                self.skip_whitespace();

                let predicate_type = self.parse_type()?;

                ty = IrNode::TypePredicate {
                    span: IrSpan::new(start, self.current_byte_offset()),
                    asserts: false,
                    param_name: Box::new(param_name),
                    type_ann: Some(Box::new(predicate_type)),
                };
                // Type predicate is terminal - don't continue to other modifiers
                break;
            }

            // Array type: T[] or Indexed access type: T[K]
            if self.at(SyntaxKind::LBracket) {
                self.consume(); // [
                self.skip_whitespace();

                if self.at(SyntaxKind::RBracket) {
                    // Array type: T[]
                    self.consume(); // ]
                    ty = IrNode::ArrayType {
                        span: ty.span(),
                        elem: Box::new(ty),
                    };
                    continue;
                } else {
                    // Indexed access type: T[K]
                    let index_type = self.parse_type()?;
                    self.skip_whitespace();

                    if !self.at(SyntaxKind::RBracket) {
                        return Err(ParseError::new(
                            errors::ParseErrorKind::MissingClosingBracket,
                            self.current_byte_offset(),
                        ));
                    }
                    self.consume(); // ]

                    ty = IrNode::IndexedAccessType {
                        span: ty.span().extend(IrSpan::at(self.current_byte_offset())),
                        obj: Box::new(ty),
                        index: Box::new(index_type),
                    };
                    continue;
                }
            }

            // Conditional type: T extends U ? X : Y
            if self.at(SyntaxKind::ExtendsKw) {
                self.consume(); // extends
                self.skip_whitespace();

                let extends_type = self.parse_type()?;
                self.skip_whitespace();

                // Check for ? (conditional type)
                if self.at(SyntaxKind::Question) {
                    self.consume(); // ?
                    self.skip_whitespace();

                    let true_type = self.parse_type()?;
                    self.skip_whitespace();

                    if !self.at(SyntaxKind::Colon) {
                        return Err(ParseError::new(
                            errors::ParseErrorKind::UnexpectedToken,
                            self.current_byte_offset(),
                        )
                        .with_expected(&[":"]));
                    }
                    self.consume(); // :
                    self.skip_whitespace();

                    let false_type = self.parse_type()?;

                    ty = IrNode::ConditionalType {
                        span: ty.span().extend(false_type.span()),
                        check: Box::new(ty),
                        extends: Box::new(extends_type),
                        true_type: Box::new(true_type),
                        false_type: Box::new(false_type),
                    };
                    continue;
                }
                // If no ?, this might be a constraint - for now, error
                return Err(ParseError::new(
                    errors::ParseErrorKind::UnexpectedToken,
                    self.current_byte_offset(),
                )
                .with_expected(&["?"]));
            }

            // Union type: T | U
            if self.at_text("|") {
                self.consume();
                self.skip_whitespace();
                let right = self.parse_type()?;
                ty = IrNode::UnionType {
                    span: ty.span().extend(right.span()),
                    types: vec![ty, right],
                };
                continue;
            }

            // Intersection type: T & U
            if self.at(SyntaxKind::Ampersand) && self.current_text() == Some("&") {
                self.consume();
                self.skip_whitespace();
                let right = self.parse_type()?;
                ty = IrNode::IntersectionType {
                    span: ty.span().extend(right.span()),
                    types: vec![ty, right],
                };
                continue;
            }

            break;
        }

        Ok(ty)
    }

    /// Parses either a parenthesized type `(T)` or a function type `(params) => R`
    fn parse_paren_or_function_type(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LParen).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["("])
        })?;

        self.skip_whitespace();

        // Empty parens `()` must be function type
        if self.at(SyntaxKind::RParen) {
            self.consume(); // consume )
            self.skip_whitespace();

            // Expect =>
            if !self.at_text("=>") {
                return Err(ParseError::new(
                    errors::ParseErrorKind::MissingArrowBody,
                    self.current_byte_offset(),
                )
                .with_expected(&["=>"]));
            }
            self.consume();
            self.skip_whitespace();

            let return_type = self.parse_type()?;
            return Ok(IrNode::FnType {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                type_params: None,
                params: vec![],
                return_type: Box::new(return_type),
            });
        }

        // Check if this looks like a function parameter (has `:` or is `...`)
        // Peek ahead: if we see Ident followed by `:` or `,`, or `...`, it's function params
        let is_function_params = self.at(SyntaxKind::DotDotDot)
            || self.at(SyntaxKind::At) // placeholder as param
            || (self.at(SyntaxKind::Ident) && {
                // Look ahead for : or , after the identifier
                let mut lookahead = 1;
                while self.peek_kind(lookahead) == Some(SyntaxKind::Whitespace) {
                    lookahead += 1;
                }
                matches!(
                    self.peek_kind(lookahead),
                    Some(SyntaxKind::Colon) | Some(SyntaxKind::Comma) | Some(SyntaxKind::Question)
                )
            });

        if is_function_params {
            // Parse as function type - need to re-parse from (
            // We already consumed the (, so parse params from here
            let mut params = Vec::new();

            loop {
                self.skip_whitespace();
                if self.at(SyntaxKind::RParen) {
                    break;
                }

                let param = self.parse_single_param()?;
                params.push(param);

                self.skip_whitespace();
                if self.at(SyntaxKind::Comma) {
                    self.consume();
                } else {
                    break;
                }
            }

            if !self.at(SyntaxKind::RParen) {
                return Err(ParseError::new(
                    errors::ParseErrorKind::MissingClosingParen,
                    self.current_byte_offset(),
                ));
            }
            self.consume(); // )

            self.skip_whitespace();

            // Expect =>
            if !self.at_text("=>") {
                return Err(ParseError::new(
                    errors::ParseErrorKind::MissingArrowBody,
                    self.current_byte_offset(),
                )
                .with_expected(&["=>"]));
            }
            self.consume();
            self.skip_whitespace();

            let return_type = self.parse_type()?;
            return Ok(IrNode::FnType {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                type_params: None,
                params,
                return_type: Box::new(return_type),
            });
        }

        // Otherwise, try to parse as parenthesized type (T)
        let inner_type = self.parse_type()?;

        self.skip_whitespace();

        if !self.at(SyntaxKind::RParen) {
            return Err(ParseError::new(
                errors::ParseErrorKind::MissingClosingParen,
                self.current_byte_offset(),
            ));
        }
        self.consume(); // )

        self.skip_whitespace();

        // Check if followed by => (would be function type with single unnamed param)
        if self.at_text("=>") {
            // This is `(Type) => R` which in TypeScript is a function type
            // where "Type" is actually the parameter name
            self.consume();
            self.skip_whitespace();

            let return_type = self.parse_type()?;

            // Treat the inner_type as a parameter name (convert to BindingIdent)
            let param = IrNode::Param {
                span: inner_type.span(),
                decorators: vec![],
                pat: Box::new(IrNode::BindingIdent {
                    span: inner_type.span(),
                    name: Box::new(inner_type),
                    type_ann: None,
                    optional: false,
                }),
            };

            return Ok(IrNode::FnType {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                type_params: None,
                params: vec![param],
                return_type: Box::new(return_type),
            });
        }

        // It's a parenthesized type
        Ok(IrNode::ParenType {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            type_ann: Box::new(inner_type),
        })
    }

    /// Parses a function type: (a: A, b: B) => R
    fn parse_function_type(&mut self) -> ParseResult<IrNode> {
        let start_byte = self.current_byte_offset();
        let params = self.parse_function_params()?;

        self.skip_whitespace();

        // Expect =>
        if !self.at_text("=>") {
            return Err(ParseError::new(
                errors::ParseErrorKind::MissingArrowBody,
                self.current_byte_offset(),
            )
            .with_expected(&["=>"]));
        }
        self.consume();

        self.skip_whitespace();

        let return_type = self.parse_type()?;

        Ok(IrNode::FnType {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            type_params: None,
            params,
            return_type: Box::new(return_type),
        })
    }

    /// Parses a tuple type: [A, B?, ...C]
    fn parse_tuple_type(&mut self) -> ParseResult<IrNode> {
        let start_pos = self.pos;
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LBracket);

        let mut elems = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBracket) {
                break;
            }

            let elem_start = self.current_byte_offset();

            // Check for rest element: ...T
            let is_rest = self.at(SyntaxKind::DotDotDot);
            if is_rest {
                self.consume(); // consume ...
                self.skip_whitespace();
            }

            let ty = self.parse_type()?;

            self.skip_whitespace();

            // Check for optional element: T?
            // Only valid if not a rest element
            let is_optional = !is_rest && self.at(SyntaxKind::Question);
            if is_optional {
                self.consume(); // consume ?
            }

            let elem = if is_rest {
                IrNode::RestType {
                    span: IrSpan::new(elem_start, self.current_byte_offset()),
                    type_ann: Box::new(ty),
                }
            } else if is_optional {
                IrNode::OptionalType {
                    span: IrSpan::new(elem_start, self.current_byte_offset()),
                    type_ann: Box::new(ty),
                }
            } else {
                ty
            };

            elems.push(elem);

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        if !self.at(SyntaxKind::RBracket) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBracket,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        Ok(IrNode::TupleType {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            elems,
        })
    }

    /// Parses an object type: { prop: T, method(): R } or mapped type: { [K in T]: V }
    fn parse_object_type(&mut self) -> ParseResult<IrNode> {
        let start_pos = self.pos;
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LBrace);
        self.skip_whitespace();

        // Check for mapped type: { [readonly] [K in T]: V }
        // Look ahead to see if this is a mapped type
        let is_mapped_type = self.is_mapped_type_start();

        if is_mapped_type {
            return self.parse_mapped_type_body(start_pos, start_byte);
        }

        let mut members = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBrace) {
                break;
            }

            let member = self.parse_type_member()?;
            members.push(member);

            self.skip_whitespace();

            // Allow ; or , as separator, or neither
            if self.at(SyntaxKind::Semicolon) || self.at(SyntaxKind::Comma) {
                self.consume();
            }
        }

        if !self.at(SyntaxKind::RBrace) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        Ok(IrNode::ObjectType {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            members,
        })
    }

    /// Check if we're at the start of a mapped type: [readonly] [+/-readonly] [K in ...]
    fn is_mapped_type_start(&self) -> bool {
        let mut lookahead_pos = self.pos;

        // Helper to skip whitespace
        macro_rules! skip_ws {
            () => {
                while lookahead_pos < self.tokens.len()
                    && self.tokens[lookahead_pos].kind == SyntaxKind::Whitespace
                {
                    lookahead_pos += 1;
                }
            };
        }

        // Helper to get current token
        macro_rules! current {
            () => {
                if lookahead_pos < self.tokens.len() {
                    Some(&self.tokens[lookahead_pos])
                } else {
                    None
                }
            };
        }

        skip_ws!();

        // Skip optional readonly/+readonly/-readonly modifier
        if let Some(t) = current!() {
            if t.kind == SyntaxKind::ReadonlyKw || t.text == "+" || t.text == "-" {
                lookahead_pos += 1;
                skip_ws!();
                // Skip readonly after +/-
                if let Some(t2) = current!() {
                    if t2.kind == SyntaxKind::ReadonlyKw {
                        lookahead_pos += 1;
                        skip_ws!();
                    }
                }
            }
        }

        // Expect [
        if let Some(t) = current!() {
            if t.kind != SyntaxKind::LBracket {
                return false;
            }
            lookahead_pos += 1;
            skip_ws!();
        } else {
            return false;
        }

        // Skip identifier
        if let Some(t) = current!() {
            if t.kind != SyntaxKind::Ident {
                return false;
            }
            lookahead_pos += 1;
            skip_ws!();
        } else {
            return false;
        }

        // Check for "in" keyword
        if let Some(t) = current!() {
            t.kind == SyntaxKind::InKw
        } else {
            false
        }
    }

    /// Parse the body of a mapped type after the opening brace
    fn parse_mapped_type_body(
        &mut self,
        start_pos: usize,
        start_byte: usize,
    ) -> ParseResult<IrNode> {
        // Parse optional readonly modifier: readonly, +readonly, -readonly
        let readonly = if self.at_text("+") || self.at_text("-") {
            let sign = self.consume().unwrap();
            let is_plus = sign.text == "+";
            self.skip_whitespace();
            if self.at(SyntaxKind::ReadonlyKw) {
                self.consume();
                self.skip_whitespace();
            }
            Some(is_plus)
        } else if self.at(SyntaxKind::ReadonlyKw) {
            self.consume();
            self.skip_whitespace();
            Some(true)
        } else {
            None
        };

        // Expect [
        self.expect(SyntaxKind::LBracket);
        self.skip_whitespace();

        // Parse type parameter name: K
        let (type_param_name, name_span) = if self.at(SyntaxKind::Ident) {
            let t = self.consume().unwrap();
            let name = t.text.clone();
            let span = IrSpan::new(t.start, t.start + t.text.len());
            (name, span)
        } else {
            return Err(ParseError::new(
                errors::ParseErrorKind::ExpectedIdentifier,
                self.current_byte_offset(),
            )
            .with_context("mapped type parameter"));
        };
        self.skip_whitespace();

        // Expect "in"
        if !self.at(SyntaxKind::InKw) {
            return Err(ParseError::new(
                errors::ParseErrorKind::ExpectedTypeAnnotation,
                self.current_byte_offset(),
            )
            .with_expected(&["in"]));
        }
        self.consume();
        self.skip_whitespace();

        // Parse constraint type
        let constraint_type = self.parse_type()?;
        self.skip_whitespace();

        // Build type parameter
        let type_param = IrNode::TypeParam {
            span: name_span,
            name: type_param_name,
            constraint: Some(Box::new(constraint_type)),
            default: None,
        };

        // Parse optional "as" clause for key remapping
        let name_type = if self.at(SyntaxKind::AsKw) {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };
        self.skip_whitespace();

        // Expect ]
        self.expect(SyntaxKind::RBracket);
        self.skip_whitespace();

        // Parse optional modifier: ?, +?, -?
        let optional = if self.at_text("+") || self.at_text("-") {
            let sign = self.consume().unwrap();
            let is_plus = sign.text == "+";
            self.skip_whitespace();
            if self.at(SyntaxKind::Question) {
                self.consume();
                self.skip_whitespace();
            }
            Some(is_plus)
        } else if self.at(SyntaxKind::Question) {
            self.consume();
            self.skip_whitespace();
            Some(true)
        } else {
            None
        };

        // Expect :
        self.expect(SyntaxKind::Colon);
        self.skip_whitespace();

        // Parse value type
        let type_ann = self.parse_type()?;
        self.skip_whitespace();

        // Allow optional semicolon
        if self.at(SyntaxKind::Semicolon) {
            self.consume();
            self.skip_whitespace();
        }

        // Expect }
        if !self.at(SyntaxKind::RBrace) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        Ok(IrNode::MappedType {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            readonly,
            type_param: Box::new(type_param),
            name_type,
            optional,
            type_ann: Some(Box::new(type_ann)),
        })
    }

    /// Parses a single type member in an object type.
    fn parse_type_member(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();
        let start_byte = self.current_byte_offset();

        // Handle readonly modifier
        let readonly = if self.at(SyntaxKind::ReadonlyKw) {
            self.consume();
            self.skip_whitespace();
            true
        } else {
            false
        };

        let Some(token) = self.current() else {
            return Err(ParseError::unexpected_eof(
                self.current_byte_offset(),
                "type member",
            ));
        };

        // Get the key
        let key = match token.kind {
            SyntaxKind::Ident => {
                let t = self.consume().expect("guarded by match arm");
                IrNode::ident(&t)
            }
            SyntaxKind::LBracket => {
                // Index signature: [key: string]: T
                self.consume();
                self.skip_whitespace();

                let param_token = if self.at(SyntaxKind::Ident) {
                    self.consume().expect("guarded by at() check")
                } else {
                    return Err(ParseError::new(
                        errors::ParseErrorKind::ExpectedIdentifier,
                        self.current_byte_offset(),
                    )
                    .with_context("index signature"));
                };
                let param_span = param_token.ir_span();

                self.skip_whitespace();
                self.expect(SyntaxKind::Colon);
                self.skip_whitespace();

                let key_type = self.parse_type()?;

                self.skip_whitespace();
                self.expect(SyntaxKind::RBracket);

                self.skip_whitespace();
                self.expect(SyntaxKind::Colon);
                self.skip_whitespace();

                let value_type = self.parse_type()?;

                return Ok(IrNode::IndexSignature {
                    span: IrSpan::new(start_byte, self.current_byte_offset()),
                    readonly,
                    params: vec![IrNode::BindingIdent {
                        span: param_span,
                        name: Box::new(IrNode::ident(&param_token)),
                        type_ann: Some(Box::new(key_type)),
                        optional: false,
                    }],
                    type_ann: Box::new(value_type),
                });
            }
            _ if token.kind.is_ts_keyword() => {
                let t = self.consume().expect("guarded by match arm");
                IrNode::ident(&t)
            }
            _ => {
                return Err(ParseError::new(
                    errors::ParseErrorKind::InvalidPropertyName,
                    self.current_byte_offset(),
                )
                .with_found(&token.text));
            }
        };

        self.skip_whitespace();

        // Check for optional: ?
        let optional = if self.at(SyntaxKind::Question) {
            self.consume();
            self.skip_whitespace();
            true
        } else {
            false
        };

        // Check for method signature: ()
        if self.at(SyntaxKind::LParen) || self.at(SyntaxKind::Lt) {
            let type_params = self.parse_optional_type_params();
            let params = self.parse_function_params()?;
            self.skip_whitespace();
            let return_type = self.parse_optional_return_type()?;

            return Ok(IrNode::MethodSignature {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                name: Box::new(key),
                optional,
                type_params,
                params,
                return_type,
            });
        }

        // Property signature: : T
        self.expect(SyntaxKind::Colon);
        self.skip_whitespace();

        let type_ann = self.parse_type()?;

        Ok(IrNode::PropSignature {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            readonly,
            name: Box::new(key),
            optional,
            type_ann: Some(Box::new(type_ann)),
        })
    }

    /// Converts a string to a TypeScript keyword type.
    fn text_to_ts_keyword(&self, text: &str) -> ParseResult<crate::compiler::ir::TsKeyword> {
        match text {
            "string" => Ok(crate::compiler::ir::TsKeyword::String),
            "number" => Ok(crate::compiler::ir::TsKeyword::Number),
            "boolean" => Ok(crate::compiler::ir::TsKeyword::Boolean),
            "any" => Ok(crate::compiler::ir::TsKeyword::Any),
            "unknown" => Ok(crate::compiler::ir::TsKeyword::Unknown),
            "never" => Ok(crate::compiler::ir::TsKeyword::Never),
            "void" => Ok(crate::compiler::ir::TsKeyword::Void),
            "null" => Ok(crate::compiler::ir::TsKeyword::Null),
            "undefined" => Ok(crate::compiler::ir::TsKeyword::Undefined),
            "object" => Ok(crate::compiler::ir::TsKeyword::Object),
            "symbol" => Ok(crate::compiler::ir::TsKeyword::Symbol),
            "bigint" => Ok(crate::compiler::ir::TsKeyword::BigInt),
            _ => Err(ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_found(text)
            .with_expected(&[
                "string",
                "number",
                "boolean",
                "any",
                "unknown",
                "never",
                "void",
                "null",
                "undefined",
                "object",
                "symbol",
                "bigint",
            ])),
        }
    }

    /// Parses implements list: implements A, B, C
    pub(super) fn parse_implements_list(&mut self) -> ParseResult<Vec<IrNode>> {
        let mut implements = Vec::new();

        loop {
            self.skip_whitespace();

            let ty = self.parse_type()?;
            implements.push(ty);

            self.skip_whitespace();

            if self.at(SyntaxKind::Comma) {
                self.consume();
            } else {
                break;
            }
        }

        Ok(implements)
    }

    /// Parses a block statement: { stmt; stmt; }
    pub(super) fn parse_block_stmt(&mut self) -> ParseResult<IrNode> {
        let start_pos = self.pos;
        let start_byte = self.current_byte_offset();

        self.expect(SyntaxKind::LBrace).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{"])
        })?;

        // Parse statements using the proper statement list parser
        let stmts = self.parse_block_stmt_list()?;

        if !self.at(SyntaxKind::RBrace) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        Ok(IrNode::BlockStmt {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            stmts,
        })
    }

    /// Parses a list of statements inside a block until `}`
    fn parse_block_stmt_list(&mut self) -> ParseResult<Vec<IrNode>> {
        let mut stmts = Vec::new();

        while !self.at_eof() && !self.at(SyntaxKind::RBrace) {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBrace) {
                break;
            }

            // Check for control flow - any {#... opening token
            if self.at_brace_hash_open() {
                let kind = self.current_kind().unwrap();
                stmts.push(self.parse_control_block(kind)?);
                continue;
            }

            // Check for directives
            if self.at(SyntaxKind::DollarOpen) {
                if let Some(node) = self.parse_directive() {
                    stmts.push(node);
                }
                continue;
            }

            // Parse statement
            match self.parse_stmt() {
                Ok(stmt) => stmts.push(stmt),
                Err(e) => {
                    // For expression statements that fail to parse, we might have raw text
                    // But propagate the actual error for debugging
                    return Err(e.with_context("parsing statement in block"));
                }
            }
        }

        Ok(Self::merge_adjacent_text(stmts))
    }

    /// Parses a class body: { members }
    pub(super) fn parse_class_body(&mut self) -> ParseResult<Vec<IrNode>> {
        let start_pos = self.pos;

        self.expect(SyntaxKind::LBrace).ok_or_else(|| {
            ParseError::new(
                errors::ParseErrorKind::UnexpectedToken,
                self.current_byte_offset(),
            )
            .with_expected(&["{"])
        })?;

        let mut body = Vec::new();

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::RBrace) {
                break;
            }

            if self.at_eof() {
                return Err(ParseError::missing_closing(
                    errors::ParseErrorKind::MissingClosingBrace,
                    self.current_byte_offset(),
                    start_pos,
                ));
            }

            // Parse class member
            let member = self.parse_class_member()?;
            body.push(member);

            self.skip_whitespace();

            // Optional semicolon
            if self.at(SyntaxKind::Semicolon) {
                self.consume();
            }
        }

        if !self.at(SyntaxKind::RBrace) {
            return Err(ParseError::missing_closing(
                errors::ParseErrorKind::MissingClosingBrace,
                self.current_byte_offset(),
                start_pos,
            ));
        }
        self.consume();

        Ok(body)
    }

    /// Parses a single class member.
    fn parse_class_member(&mut self) -> ParseResult<IrNode> {
        self.skip_whitespace();
        let start_byte = self.current_byte_offset();

        // Parse decorators (parsed but not stored in IR Method/ClassProp)
        let _decorators = self.parse_decorators()?;

        self.skip_whitespace();

        // Parse modifiers
        let mut is_static = false;
        let mut accessibility = None;
        #[allow(unused_variables)]
        let mut is_abstract = false;
        let mut is_readonly = false;
        #[allow(unused_variables)]
        let mut is_override = false;

        loop {
            self.skip_whitespace();

            if self.at(SyntaxKind::StaticKw) {
                self.consume();
                is_static = true;
            } else if self.at(SyntaxKind::PublicKw) {
                self.consume();
                accessibility = Some(crate::compiler::ir::Accessibility::Public);
            } else if self.at(SyntaxKind::PrivateKw) {
                self.consume();
                accessibility = Some(crate::compiler::ir::Accessibility::Private);
            } else if self.at(SyntaxKind::ProtectedKw) {
                self.consume();
                accessibility = Some(crate::compiler::ir::Accessibility::Protected);
            } else if self.at(SyntaxKind::AbstractKw) {
                self.consume();
                is_abstract = true;
            } else if self.at(SyntaxKind::ReadonlyKw) {
                self.consume();
                is_readonly = true;
            } else if self.at_text("override") {
                self.consume();
                is_override = true;
            } else {
                break;
            }
        }

        self.skip_whitespace();

        // Check for getter/setter
        if self.at(SyntaxKind::GetKw) || self.at(SyntaxKind::SetKw) {
            let is_getter = self.at(SyntaxKind::GetKw);
            self.consume();
            self.skip_whitespace();

            let key = self.parse_property_name()?;
            let type_params = self.parse_optional_type_params();

            if is_getter {
                self.expect(SyntaxKind::LParen);
                self.skip_whitespace();
                self.expect(SyntaxKind::RParen);
                self.skip_whitespace();

                let type_ann = self.parse_optional_return_type()?;
                self.skip_whitespace();

                let body = if self.at(SyntaxKind::LBrace) {
                    Some(Box::new(self.parse_block_stmt()?))
                } else {
                    None
                };

                return Ok(IrNode::Method {
                    span: IrSpan::new(start_byte, self.current_byte_offset()),
                    static_: is_static,
                    accessibility,
                    readonly: is_readonly,
                    async_: false,
                    generator: false,
                    kind: crate::compiler::ir::MethodKind::Getter,
                    name: Box::new(key),
                    optional: false,
                    type_params,
                    params: Vec::new(),
                    return_type: type_ann,
                    body,
                });
            } else {
                let params = self.parse_function_params()?;
                self.skip_whitespace();

                let body = if self.at(SyntaxKind::LBrace) {
                    Some(Box::new(self.parse_block_stmt()?))
                } else {
                    None
                };

                return Ok(IrNode::Method {
                    span: IrSpan::new(start_byte, self.current_byte_offset()),
                    static_: is_static,
                    accessibility,
                    readonly: is_readonly,
                    async_: false,
                    generator: false,
                    kind: crate::compiler::ir::MethodKind::Setter,
                    name: Box::new(key),
                    optional: false,
                    type_params,
                    params,
                    return_type: None,
                    body,
                });
            }
        }

        // Check for constructor
        if self.at_text("constructor") {
            self.consume();
            self.skip_whitespace();

            let params = self.parse_function_params()?;
            self.skip_whitespace();

            let body = if self.at(SyntaxKind::LBrace) {
                Some(Box::new(self.parse_block_stmt()?))
            } else {
                None
            };

            return Ok(IrNode::Constructor {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                accessibility,
                params,
                body,
            });
        }

        // Parse key (property/method name)
        let key = self.parse_property_name()?;

        self.skip_whitespace();

        // Check for optional: ?
        let is_optional = if self.at(SyntaxKind::Question) {
            self.consume();
            self.skip_whitespace();
            true
        } else {
            false
        };

        // Check for method: ( or <
        if self.at(SyntaxKind::LParen) || self.at(SyntaxKind::Lt) {
            let type_params = self.parse_optional_type_params();
            let params = self.parse_function_params()?;
            self.skip_whitespace();

            let return_type = self.parse_optional_return_type()?;
            self.skip_whitespace();

            let body = if self.at(SyntaxKind::LBrace) {
                Some(Box::new(self.parse_block_stmt()?))
            } else {
                None
            };

            return Ok(IrNode::Method {
                span: IrSpan::new(start_byte, self.current_byte_offset()),
                static_: is_static,
                accessibility,
                readonly: is_readonly,
                async_: false,
                generator: false,
                kind: crate::compiler::ir::MethodKind::Method,
                name: Box::new(key),
                optional: is_optional,
                type_params,
                params,
                return_type,
                body,
            });
        }

        // Property
        self.skip_whitespace();

        // Type annotation
        let type_ann = if self.at(SyntaxKind::Colon) {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(self.parse_type()?))
        } else {
            None
        };

        self.skip_whitespace();

        // Initializer
        let value = if self.at_text("=") {
            self.consume();
            self.skip_whitespace();
            Some(Box::new(
                self.parse_expression_with_precedence(prec::ASSIGN.right)?,
            ))
        } else {
            None
        };

        Ok(IrNode::ClassProp {
            span: IrSpan::new(start_byte, self.current_byte_offset()),
            static_: is_static,
            accessibility,
            readonly: is_readonly,
            declare: false,
            optional: is_optional,
            definite: false,
            name: Box::new(key),
            type_ann,
            value,
        })
    }
}

#[cfg(test)]
mod tests {
    // Tests will be added with the integration
}