llvm-native-core 0.1.11

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

use std::collections::{BTreeMap, HashMap};
use std::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// Deducing This (Explicit Object Parameter) — P0847R7
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the kind of explicit object parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExplicitObjectKind {
    /// `this auto&& self` — deduced reference
    DeducedRef,
    /// `this auto& self` — deduced lvalue reference
    DeducedLvalueRef,
    /// `this auto self` — deduced by value
    DeducedByValue,
    /// `this const auto& self` — deduced const lvalue reference
    DeducedConstLvalueRef,
    /// `this auto const& self` — alternative const spelling
    DeducedConstRefAlt,
}

impl ExplicitObjectKind {
    pub fn from_param_str(s: &str) -> Option<Self> {
        match s {
            "this auto&& self" | "this auto&&" => Some(Self::DeducedRef),
            "this auto& self" | "this auto&" => Some(Self::DeducedLvalueRef),
            "this auto self" | "this auto" => Some(Self::DeducedByValue),
            "this const auto& self" | "this const auto&" => Some(Self::DeducedConstLvalueRef),
            "this auto const& self" | "this auto const&" => Some(Self::DeducedConstRefAlt),
            _ => None,
        }
    }

    pub fn is_reference(&self) -> bool {
        matches!(
            self,
            Self::DeducedRef
                | Self::DeducedLvalueRef
                | Self::DeducedConstLvalueRef
                | Self::DeducedConstRefAlt
        )
    }

    pub fn is_const(&self) -> bool {
        matches!(self, Self::DeducedConstLvalueRef | Self::DeducedConstRefAlt)
    }
}

/// Represents a function with an explicit object parameter (deducing this).
#[derive(Debug, Clone)]
pub struct ExplicitObjectFunction {
    /// The name of the function/member function
    pub name: String,
    /// The explicit object parameter kind
    pub explicit_param: ExplicitObjectKind,
    /// Name of the explicit object parameter (e.g., "self")
    pub param_name: String,
    /// Remaining regular parameters after the explicit one
    pub regular_params: Vec<FunctionParam>,
    /// Return type (can be deduced via auto)
    pub return_type: DeducedReturnType,
    /// Whether this is a member function
    pub is_member: bool,
    /// Whether the function is constexpr
    pub is_constexpr: bool,
    /// The class name if this is a member
    pub class_name: Option<String>,
    /// Whether the function is static (static + explicit object is allowed in C++23)
    pub is_static: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum DeducedReturnType {
    Auto,
    AutoRef,
    AutoConstRef,
    Explicit(String),
    Void,
}

/// A function parameter descriptor.
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionParam {
    pub name: String,
    pub type_desc: String,
    pub default_value: Option<String>,
}

impl ExplicitObjectFunction {
    pub fn new(name: &str, kind: ExplicitObjectKind, param_name: &str) -> Self {
        Self {
            name: name.to_string(),
            explicit_param: kind,
            param_name: param_name.to_string(),
            regular_params: Vec::new(),
            return_type: DeducedReturnType::Auto,
            is_member: false,
            is_constexpr: false,
            class_name: None,
            is_static: false,
        }
    }

    /// Generates a pseudo-signature string for display.
    pub fn signature(&self) -> String {
        let class_prefix = if let Some(ref cls) = self.class_name {
            format!("{}::", cls)
        } else {
            String::new()
        };
        let static_prefix = if self.is_static { "static " } else { "" };
        let constexpr_prefix = if self.is_constexpr { "constexpr " } else { "" };
        let ret = match &self.return_type {
            DeducedReturnType::Auto => "auto".to_string(),
            DeducedReturnType::AutoRef => "auto&".to_string(),
            DeducedReturnType::AutoConstRef => "const auto&".to_string(),
            DeducedReturnType::Explicit(t) => t.clone(),
            DeducedReturnType::Void => "void".to_string(),
        };
        let explicit = format!("this auto&& {}", self.param_name);
        let params: Vec<String> = std::iter::once(explicit)
            .chain(self.regular_params.iter().map(|p| {
                if let Some(ref def) = p.default_value {
                    format!("{} {} = {}", p.type_desc, p.name, def)
                } else {
                    format!("{} {}", p.type_desc, p.name)
                }
            }))
            .collect();
        format!(
            "{}{}{}{}({})",
            constexpr_prefix,
            static_prefix,
            ret,
            format!("{}operator()", class_prefix),
            params.join(", ")
        )
    }

    /// Returns whether the function can be called with an lvalue argument.
    pub fn can_bind_lvalue(&self) -> bool {
        match self.explicit_param {
            ExplicitObjectKind::DeducedRef
            | ExplicitObjectKind::DeducedLvalueRef
            | ExplicitObjectKind::DeducedConstLvalueRef
            | ExplicitObjectKind::DeducedConstRefAlt => true,
            ExplicitObjectKind::DeducedByValue => true,
        }
    }

    /// Returns whether the function can be called with an rvalue argument.
    pub fn can_bind_rvalue(&self) -> bool {
        match self.explicit_param {
            ExplicitObjectKind::DeducedRef | ExplicitObjectKind::DeducedByValue => true,
            ExplicitObjectKind::DeducedLvalueRef
            | ExplicitObjectKind::DeducedConstLvalueRef
            | ExplicitObjectKind::DeducedConstRefAlt => false,
        }
    }
}

/// Parser for deducing-this syntax.
pub struct DeducingThisParser {
    pub enabled: bool,
    pub diagnostics: Vec<DeducingThisDiag>,
}

#[derive(Debug, Clone)]
pub struct DeducingThisDiag {
    pub message: String,
    pub is_error: bool,
}

impl DeducingThisParser {
    pub fn new() -> Self {
        Self {
            enabled: true,
            diagnostics: Vec::new(),
        }
    }

    /// Parse a parameter declaration to detect explicit object parameter syntax.
    pub fn parse_param(&mut self, param_str: &str) -> Option<ExplicitObjectKind> {
        let trimmed = param_str.trim();
        if !trimmed.starts_with("this ") {
            return None;
        }
        ExplicitObjectKind::from_param_str(trimmed)
    }

    /// Validate that an explicit object parameter is used correctly.
    pub fn validate(&mut self, func: &ExplicitObjectFunction) -> bool {
        let mut valid = true;

        // An explicit object parameter must be the first parameter
        // Static member functions cannot have explicit object parameters
        // (unless combined with static operator() in C++23)
        if func.is_static && !func.is_member {
            self.diagnostics.push(DeducingThisDiag {
                message: format!(
                    "free function '{}' cannot have an explicit object parameter",
                    func.name
                ),
                is_error: true,
            });
            valid = false;
        }

        // Constructors and destructors cannot have explicit object parameters
        if func.name == func.class_name.clone().unwrap_or_default() {
            self.diagnostics.push(DeducingThisDiag {
                message: "constructors cannot have explicit object parameters".to_string(),
                is_error: true,
            });
            valid = false;
        }

        if func.name.starts_with('~') {
            self.diagnostics.push(DeducingThisDiag {
                message: "destructors cannot have explicit object parameters".to_string(),
                is_error: true,
            });
            valid = false;
        }

        // Virtual functions with explicit object params need care
        // They can still be called virtually but can't be overridden trivially

        valid
    }

    /// Generate the deduced type for `this` in an explicit object function.
    pub fn deduce_this_type(&self, func: &ExplicitObjectFunction, call_is_lvalue: bool) -> String {
        match func.explicit_param {
            ExplicitObjectKind::DeducedRef => {
                if call_is_lvalue {
                    "auto&".to_string()
                } else {
                    "auto&&".to_string()
                }
            }
            ExplicitObjectKind::DeducedLvalueRef => "auto&".to_string(),
            ExplicitObjectKind::DeducedByValue => "auto".to_string(),
            ExplicitObjectKind::DeducedConstLvalueRef | ExplicitObjectKind::DeducedConstRefAlt => {
                "const auto&".to_string()
            }
        }
    }
}

impl Default for DeducingThisParser {
    fn default() -> Self {
        Self::new()
    }
}

/// Code generation support for deducing-this functions.
pub struct DeducingThisCodeGen {
    pub enabled: bool,
}

impl DeducingThisCodeGen {
    pub fn new() -> Self {
        Self { enabled: true }
    }

    /// Emit the LLVM IR function type for a deducing-this call operator.
    pub fn emit_call_operator_type(&self, _func: &ExplicitObjectFunction) -> String {
        // In a real implementation, this would emit the LLVM function type
        // with the deduced 'self' parameter as the first argument.
        "void (%class.Foo*, i32)*".to_string()
    }

    /// Lower a call to a deducing-this operator to LLVM IR.
    pub fn lower_call(&self, object_ptr: &str, args: &[String]) -> String {
        format!(
            "call void @operator()(ptr noundef {}, i32 {})",
            object_ptr,
            args.join(", i32 ")
        )
    }
}

impl Default for DeducingThisCodeGen {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// if consteval — P1938R3
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the result of evaluating an `if consteval` condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IfConstevalResult {
    /// We are in an immediate function context — take the consteval branch.
    ImmediateContext,
    /// We are not in an immediate function context — take the else branch.
    NonImmediateContext,
}

/// Context tracker for `if consteval` statements.
#[derive(Debug, Clone)]
pub struct ConstevalContext {
    /// Stack of consteval/non-consteval contexts
    stack: Vec<bool>,
    /// Current depth
    depth: usize,
}

impl ConstevalContext {
    pub fn new() -> Self {
        Self {
            stack: Vec::new(),
            depth: 0,
        }
    }

    /// Enter a new context. `true` means we are in a consteval context.
    pub fn enter(&mut self, is_consteval: bool) {
        self.stack.push(is_consteval);
        self.depth += 1;
    }

    /// Leave the current context.
    pub fn leave(&mut self) {
        if self.depth > 0 {
            self.stack.pop();
            self.depth -= 1;
        }
    }

    /// Check if we are currently in a consteval context.
    pub fn is_consteval(&self) -> bool {
        self.stack.last().copied().unwrap_or(false)
    }

    /// Evaluate an `if consteval` condition.
    pub fn evaluate_if_consteval(&self) -> IfConstevalResult {
        if self.is_consteval() {
            IfConstevalResult::ImmediateContext
        } else {
            IfConstevalResult::NonImmediateContext
        }
    }
}

impl Default for ConstevalContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Parser for `if consteval` statements.
pub struct IfConstevalParser {
    pub contexts: ConstevalContext,
}

impl IfConstevalParser {
    pub fn new() -> Self {
        Self {
            contexts: ConstevalContext::new(),
        }
    }

    /// Parse a token sequence to detect `if consteval`.
    pub fn detect_consteval(&self, tokens: &[&str]) -> bool {
        if tokens.len() >= 2 {
            return tokens[0] == "if" && tokens[1] == "consteval";
        }
        false
    }

    /// Parse the body of `if consteval { ... } else { ... }`.
    pub fn parse_body(&mut self, is_immediate_context: bool, body: &str) -> String {
        self.contexts.enter(is_immediate_context);
        let result = body.to_string();
        self.contexts.leave();
        result
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// static operator() — P1169R4
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a static call operator.
#[derive(Debug, Clone)]
pub struct StaticOperatorCall {
    /// The enclosing class or lambda type name
    pub class_name: String,
    /// Parameter types
    pub params: Vec<String>,
    /// Return type
    pub return_type: String,
    /// Whether it's a lambda
    pub is_lambda: bool,
    /// Whether it captures anything (static lambdas have no captures)
    pub has_captures: bool,
}

impl StaticOperatorCall {
    pub fn new(class_name: &str) -> Self {
        Self {
            class_name: class_name.to_string(),
            params: Vec::new(),
            return_type: "void".to_string(),
            is_lambda: false,
            has_captures: false,
        }
    }

    /// Validate that a static operator() is well-formed.
    pub fn validate(&self) -> Result<(), String> {
        if self.is_lambda {
            // In C++23, static lambdas must have no captures
            if self.has_captures {
                return Err(
                    "static lambda cannot have captures (lambda with static operator())".to_string(),
                );
            }
        }
        // The static operator() cannot be virtual
        // It cannot be const, volatile, or ref-qualified
        Ok(())
    }

    /// The mangled name for the static operator().
    pub fn mangled_name(&self) -> String {
        format!("_ZN{}clE", self.class_name.len())
    }
}

/// Enum for the kind of call operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallOperatorKind {
    /// Non-static, non-const
    Mutable,
    /// Non-static, const-qualified
    Const,
    /// Static (C++23)
    Static,
    /// Explicit object parameter (C++23)
    ExplicitObject,
}

impl fmt::Display for CallOperatorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Mutable => write!(f, "operator()"),
            Self::Const => write!(f, "operator() const"),
            Self::Static => write!(f, "static operator()"),
            Self::ExplicitObject => write!(f, "operator() [explicit object]"),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Multidimensional Subscript Operator — P2128R6
// ═══════════════════════════════════════════════════════════════════════════════

/// Describes a multidimensional subscript operator.
#[derive(Debug, Clone)]
pub struct MultiDimSubscript {
    /// Number of indices accepted
    pub index_count: usize,
    /// Types of the indices
    pub index_types: Vec<String>,
    /// Return type
    pub return_type: String,
    /// Whether the operator is const-qualified
    pub is_const: bool,
    /// Source location for diagnostics
    pub source_line: usize,
}

impl MultiDimSubscript {
    pub fn new(index_count: usize) -> Self {
        Self {
            index_count,
            index_types: Vec::new(),
            return_type: "auto&".to_string(),
            is_const: false,
            source_line: 0,
        }
    }

    /// Validate the multidimensional subscript operator.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Must have at least one parameter (C++23 allows multiple)
        if self.index_count == 0 {
            errors.push("operator[] must have at least one parameter".to_string());
        }

        // Before C++23, only exactly one parameter was allowed
        // In C++23, any number >= 1 is allowed
        if self.index_count == 0 {
            errors.push("operator[] with zero indices is not allowed".to_string());
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Generate the call syntax: obj[i, j, k]
    pub fn call_syntax(&self, object: &str, indices: &[&str]) -> String {
        format!("{}[{}]", object, indices.join(", "))
    }

    /// Generate LLVM IR access
    pub fn lower_subscript(&self, base_ptr: &str, indices: &[i64]) -> String {
        let gep_indices: Vec<String> = indices.iter().map(|i| format!("i64 {}", i)).collect();
        format!(
            "getelementptr inbounds {}, {}, {}",
            "i8",
            base_ptr,
            gep_indices.join(", ")
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// auto(x) and auto{x} — Decay-Copy Prvalue Semantics — P0849R8
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the kind of decay-copy expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecayCopyKind {
    /// auto(x) — parentheses form
    DecayCopyParen,
    /// auto{x} — brace form
    DecayCopyBrace,
}

impl fmt::Display for DecayCopyKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DecayCopyParen => write!(f, "auto"),
            Self::DecayCopyBrace => write!(f, "auto{{}}"),
        }
    }
}

/// Represents a decay-copy expression `auto(x)` or `auto{x}`.
#[derive(Debug, Clone)]
pub struct DecayCopyExpr {
    /// The kind of decay-copy expression
    pub kind: DecayCopyKind,
    /// The inner expression being decay-copied
    pub inner_expr: String,
    /// The deduced type after decay
    pub deduced_type: String,
    /// Whether the result is a prvalue
    pub is_prvalue: bool,
}

impl DecayCopyExpr {
    pub fn new(kind: DecayCopyKind, inner: &str) -> Self {
        Self {
            kind,
            inner_expr: inner.to_string(),
            deduced_type: String::new(),
            is_prvalue: true,
        }
    }

    /// Emit the decay-copy as a source representation.
    pub fn emit(&self) -> String {
        match self.kind {
            DecayCopyKind::DecayCopyParen => format!("auto({})", self.inner_expr),
            DecayCopyKind::DecayCopyBrace => format!("auto{{{}}}", self.inner_expr),
        }
    }

    /// Describe the type decay that occurs:
    /// - Arrays decay to pointers
    /// - Functions decay to function pointers
    /// - Top-level cv-qualifiers are stripped
    /// - References are stripped
    pub fn apply_decay(&self, original_type: &str) -> String {
        let mut t = original_type.to_string();
        // Strip references
        if t.ends_with('&') {
            t = t[..t.len() - 1].to_string();
        }
        if t.ends_with("&&") {
            t = t[..t.len() - 2].to_string();
        }
        // Strip top-level const
        if t.starts_with("const ") {
            t = t[6..].to_string();
        }
        // Strip top-level volatile
        if t.starts_with("volatile ") {
            t = t[9..].to_string();
        }
        // Array-to-pointer decay
        if t.ends_with(']') {
            if let Some(bracket_pos) = t.find('[') {
                let base = t[..bracket_pos].trim().to_string();
                t = format!("{}*", base);
            }
        }
        t
    }
}

/// Parser for decay-copy expressions.
pub struct DecayCopyParser;
impl DecayCopyParser {
    /// Attempt to parse an `auto(` or `auto{` decay-copy expression.
    pub fn try_parse(input: &str) -> Option<DecayCopyExpr> {
        let trimmed = input.trim();
        if let Some(rest) = trimmed.strip_prefix("auto(") {
            if let Some(inner) = rest.strip_suffix(')') {
                return Some(DecayCopyExpr::new(DecayCopyKind::DecayCopyParen, inner.trim()));
            }
        }
        if let Some(rest) = trimmed.strip_prefix("auto{") {
            if let Some(inner) = rest.strip_suffix('}') {
                return Some(DecayCopyExpr::new(DecayCopyKind::DecayCopyBrace, inner.trim()));
            }
        }
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// #warning Preprocessor Directive — P2437R1
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a `#warning` preprocessor directive.
#[derive(Debug, Clone)]
pub struct WarningDirective {
    /// The message text
    pub message: String,
    /// Source location (line number)
    pub line: usize,
    /// Source file name
    pub file: String,
}

impl WarningDirective {
    pub fn new(message: &str, line: usize, file: &str) -> Self {
        Self {
            message: message.to_string(),
            line,
            file: file.to_string(),
        }
    }

    /// Format the diagnostic message like a compiler does.
    pub fn format_diagnostic(&self) -> String {
        format!("{}:{}: warning: {}", self.file, self.line, self.message)
    }
}

/// Handler for `#warning` in the preprocessor.
pub struct WarningDirectiveHandler {
    pub warnings: Vec<WarningDirective>,
    pub treat_warnings_as_errors: bool,
}

impl WarningDirectiveHandler {
    pub fn new() -> Self {
        Self {
            warnings: Vec::new(),
            treat_warnings_as_errors: false,
        }
    }

    /// Process a `#warning` directive.
    pub fn handle(&mut self, message: &str, line: usize, file: &str) {
        let warning = WarningDirective::new(message, line, file);
        self.warnings.push(warning);
    }

    /// Check if any warnings were emitted.
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }
}

impl Default for WarningDirectiveHandler {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// #elifdef and #elifndef — P2334R1
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the preprocessor conditional inclusion shortcuts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElifConditional {
    /// Standard `#elif`
    Elif,
    /// `#elifdef MACRO` — equivalent to `#elif defined(MACRO)`
    Elifdef,
    /// `#elifndef MACRO` — equivalent to `#elif !defined(MACRO)`
    Elifndef,
}

impl ElifConditional {
    pub fn from_directive(s: &str) -> Option<Self> {
        match s.trim() {
            "elif" => Some(Self::Elif),
            "elifdef" => Some(Self::Elifdef),
            "elifndef" => Some(Self::Elifndef),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Elif => "#elif",
            Self::Elifdef => "#elifdef",
            Self::Elifndef => "#elifndef",
        }
    }
}

/// A conditional block in the preprocessor.
#[derive(Debug, Clone)]
pub struct ConditionalBlock {
    pub condition: String,
    pub conditional_type: ElifConditional,
    pub body: String,
    pub was_taken: bool,
}

/// Preprocessor conditional chain handler.
pub struct ConditionalChain {
    /// The stack of #if / #ifdef / #ifndef conditions
    pub blocks: Vec<ConditionalBlock>,
    /// Whether we have taken a branch already
    pub branch_taken: bool,
    /// Whether we warned about missing #endif
    pub warned_missing_endif: bool,
}

impl ConditionalChain {
    pub fn new() -> Self {
        Self {
            blocks: Vec::new(),
            branch_taken: false,
            warned_missing_endif: false,
        }
    }

    /// Handle `#ifdef MACRO`.
    pub fn handle_ifdef(&mut self, macro_name: &str, is_defined: bool) {
        let block = ConditionalBlock {
            condition: format!("defined({})", macro_name),
            conditional_type: ElifConditional::Elif,
            body: String::new(),
            was_taken: !self.branch_taken && is_defined,
        };
        if block.was_taken {
            self.branch_taken = true;
        }
        self.blocks.push(block);
    }

    /// Handle `#ifndef MACRO`.
    pub fn handle_ifndef(&mut self, macro_name: &str, is_defined: bool) {
        let block = ConditionalBlock {
            condition: format!("!defined({})", macro_name),
            conditional_type: ElifConditional::Elif,
            body: String::new(),
            was_taken: !self.branch_taken && !is_defined,
        };
        if block.was_taken {
            self.branch_taken = true;
        }
        self.blocks.push(block);
    }

    /// Handle `#elifdef MACRO`.
    pub fn handle_elifdef(&mut self, macro_name: &str, is_defined: bool) {
        if self.branch_taken {
            return; // Already took a branch, skip this
        }
        let block = ConditionalBlock {
            condition: format!("defined({})", macro_name),
            conditional_type: ElifConditional::Elifdef,
            body: String::new(),
            was_taken: is_defined,
        };
        if is_defined {
            self.branch_taken = true;
        }
        self.blocks.push(block);
    }

    /// Handle `#elifndef MACRO`.
    pub fn handle_elifndef(&mut self, macro_name: &str, is_defined: bool) {
        if self.branch_taken {
            return;
        }
        let block = ConditionalBlock {
            condition: format!("!defined({})", macro_name),
            conditional_type: ElifConditional::Elifndef,
            body: String::new(),
            was_taken: !is_defined,
        };
        if !is_defined {
            self.branch_taken = true;
        }
        self.blocks.push(block);
    }

    /// Handle the trailing `#else`.
    pub fn handle_else(&mut self) {
        if self.branch_taken {
            return;
        }
        let block = ConditionalBlock {
            condition: "else".to_string(),
            conditional_type: ElifConditional::Elif,
            body: String::new(),
            was_taken: true,
        };
        self.branch_taken = true;
        self.blocks.push(block);
    }

    /// Reset for a new conditional chain.
    pub fn reset(&mut self) {
        self.blocks.clear();
        self.branch_taken = false;
    }
}

impl Default for ConditionalChain {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Literal Suffix for size_t — P0330R8
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the C++23 literal suffixes for size_t and signed size_t.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeTLiteralSuffix {
    /// `uz` — unsigned size_t (std::size_t)
    Uz,
    /// `z` — signed size_t (std::ssize_t / ptrdiff_t)
    Z,
}

impl SizeTLiteralSuffix {
    pub fn from_suffix(s: &str) -> Option<Self> {
        match s {
            "uz" | "UZ" | "Uz" | "uZ" => Some(Self::Uz),
            "z" | "Z" => Some(Self::Z),
            _ => None,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Uz => "uz",
            Self::Z => "z",
        }
    }

    pub fn is_signed(&self) -> bool {
        matches!(self, Self::Z)
    }

    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Uz => "std::size_t",
            Self::Z => "std::ptrdiff_t",
        }
    }
}

/// A literal with a size_t suffix.
#[derive(Debug, Clone)]
pub struct SizeTLiteral {
    pub value: String,
    pub suffix: SizeTLiteralSuffix,
}

impl SizeTLiteral {
    pub fn new(value: &str, suffix: SizeTLiteralSuffix) -> Self {
        Self {
            value: value.to_string(),
            suffix,
        }
    }

    pub fn to_source(&self) -> String {
        format!("{}{}", self.value, self.suffix.as_str())
    }
}

/// Parser for size_t literal suffixes.
pub struct SizeTLiteralParser;

impl SizeTLiteralParser {
    /// Try to parse an integer literal with a `z` or `uz` suffix.
    pub fn try_parse(input: &str) -> Option<SizeTLiteral> {
        let trimmed = input.trim();
        // Check for uz suffix first (must check before z alone)
        for suffix_str in &["uz", "UZ", "Uz", "uZ"] {
            if let Some(value) = trimmed.strip_suffix(suffix_str) {
                if !value.is_empty()
                    && value.chars().all(|c| c.is_ascii_digit() || c == '\'')
                {
                    return Some(SizeTLiteral::new(value, SizeTLiteralSuffix::Uz));
                }
            }
        }
        // Check for z suffix
        for suffix_str in &["z", "Z"] {
            if let Some(value) = trimmed.strip_suffix(suffix_str) {
                if !value.is_empty()
                    && value.chars().all(|c| c.is_ascii_digit() || c == '\'')
                {
                    return Some(SizeTLiteral::new(value, SizeTLiteralSuffix::Z));
                }
            }
        }
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// constexpr Extensions — Virtual, Try-Catch, Dynamic Cast
// ═══════════════════════════════════════════════════════════════════════════════

/// Tracks which extended constexpr features are enabled.
#[derive(Debug, Clone)]
pub struct ConstexprExtensions {
    /// C++20: constexpr virtual functions (P1064R0)
    pub constexpr_virtual: bool,
    /// C++20: constexpr try-catch (P1002R1)
    pub constexpr_try_catch: bool,
    /// C++20: constexpr dynamic_cast / typeid (P1327R1)
    pub constexpr_dynamic_cast: bool,
    /// C++20: constexpr union with active member change (P1330R0)
    pub constexpr_union: bool,
    /// C++23: constexpr std::unique_ptr (P2273R1)
    pub constexpr_unique_ptr: bool,
    /// C++26: constexpr placement new
    pub constexpr_placement_new: bool,
}

impl Default for ConstexprExtensions {
    fn default() -> Self {
        Self {
            constexpr_virtual: true,
            constexpr_try_catch: true,
            constexpr_dynamic_cast: true,
            constexpr_union: true,
            constexpr_unique_ptr: false,
            constexpr_placement_new: false,
        }
    }
}

/// Represents a constexpr virtual function.
#[derive(Debug, Clone)]
pub struct ConstexprVirtualFunction {
    pub name: String,
    pub class_name: String,
    pub is_override: bool,
    pub is_final: bool,
    pub is_pure_virtual: bool,
    pub vtable_index: Option<usize>,
}

impl ConstexprVirtualFunction {
    pub fn new(name: &str, class_name: &str) -> Self {
        Self {
            name: name.to_string(),
            class_name: class_name.to_string(),
            is_override: false,
            is_final: false,
            is_pure_virtual: false,
            vtable_index: None,
        }
    }

    /// Validate that a constexpr virtual function is well-formed.
    pub fn validate(&self) -> Result<(), String> {
        if self.is_pure_virtual {
            return Err(format!(
                "constexpr virtual function '{}' cannot be pure virtual",
                self.name
            ));
        }
        // The function body must be a constant expression when evaluated
        // for a constexpr object
        Ok(())
    }
}

/// Represents a constexpr try-catch block.
#[derive(Debug, Clone)]
pub struct ConstexprTryCatch {
    /// Whether the try-block is in a constexpr context
    pub is_constexpr: bool,
    /// The exception types caught
    pub catch_types: Vec<String>,
    /// Whether any catch block can be evaluated at compile time
    pub can_be_constexpr: bool,
}

impl ConstexprTryCatch {
    pub fn new() -> Self {
        Self {
            is_constexpr: false,
            catch_types: Vec::new(),
            can_be_constexpr: true,
        }
    }

    /// Validate that try-catch can be constexpr.
    /// A throw that is actually evaluated in a constexpr context is an error.
    pub fn validate(&self) -> Result<(), String> {
        if !self.is_constexpr {
            return Ok(());
        }
        // constexpr try-catch is allowed, but if the try-block throws at
        // constant evaluation time, it's not a core constant expression
        Ok(())
    }
}

impl Default for ConstexprTryCatch {
    fn default() -> Self {
        Self::new()
    }
}

/// Represents a constexpr dynamic_cast.
#[derive(Debug, Clone)]
pub struct ConstexprDynamicCast {
    /// The source expression type
    pub src_type: String,
    /// The target type
    pub dst_type: String,
    /// Whether this is a downcast (base -> derived)
    pub is_downcast: bool,
    /// Whether this is a cross-cast
    pub is_crosscast: bool,
}

impl ConstexprDynamicCast {
    pub fn new(src_type: &str, dst_type: &str) -> Self {
        Self {
            src_type: src_type.to_string(),
            dst_type: dst_type.to_string(),
            is_downcast: false,
            is_crosscast: false,
        }
    }

    /// Validate that dynamic_cast can be constexpr.
    /// Requires the full type hierarchy to be known at compile time.
    pub fn validate(&self) -> Result<(), String> {
        if self.is_crosscast {
            // Cross-casts via virtual base are even trickier
            // but C++20 permits them in constexpr if the type is complete
        }
        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// std::unreachable() — P0627R6
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the `std::unreachable()` function (C++23).
#[derive(Debug, Clone)]
pub struct UnreachableBuiltin {
    /// The function name
    pub name: String,
    /// Whether it has the `[[noreturn]]` attribute
    pub is_noreturn: bool,
    /// Whether we should emit a trap instruction
    pub emit_trap: bool,
}

impl UnreachableBuiltin {
    pub fn new() -> Self {
        Self {
            name: "std::unreachable".to_string(),
            is_noreturn: true,
            emit_trap: true,
        }
    }

    /// Emit LLVM IR for a call to std::unreachable().
    pub fn emit_llvm(&self) -> String {
        if self.emit_trap {
            "call void @llvm.trap()\n  unreachable".to_string()
        } else {
            "unreachable".to_string()
        }
    }

    /// Describe the semantics for users.
    pub fn description(&self) -> &'static str {
        "std::unreachable() indicates that a code path cannot be reached. \
         If reached at runtime, behavior is undefined. At compile time, \
         the optimizer may use this to eliminate dead code."
    }
}

impl Default for UnreachableBuiltin {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Monadic Operations for std::optional — P0798R8
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the monadic operations available on std::optional<T>.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionalMonadicOp {
    /// `opt.and_then(f)` — returns f(*opt) if opt has value, nullopt otherwise
    AndThen,
    /// `opt.or_else(f)` — returns opt if it has value, f() otherwise
    OrElse,
    /// `opt.transform(f)` — returns optional<U>(f(*opt)) if opt has value
    Transform,
}

impl fmt::Display for OptionalMonadicOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AndThen => write!(f, "and_then"),
            Self::OrElse => write!(f, "or_else"),
            Self::Transform => write!(f, "transform"),
        }
    }
}

/// Descriptor for std::optional<T> with monadic operations.
#[derive(Debug, Clone)]
pub struct OptionalMonadic {
    /// The contained type
    pub value_type: String,
    /// Whether the monadic operations are enabled (C++23)
    pub monadic_enabled: bool,
}

impl OptionalMonadic {
    pub fn new(value_type: &str) -> Self {
        Self {
            value_type: value_type.to_string(),
            monadic_enabled: true,
        }
    }

    /// Generate the return type for and_then given a callable f.
    pub fn and_then_return_type(&self, f_return_optional_of: &str) -> String {
        format!("std::optional<{}>", f_return_optional_of)
    }

    /// Generate the return type for transform given a callable f.
    pub fn transform_return_type(&self, f_return_type: &str) -> String {
        format!("std::optional<{}>", f_return_type)
    }

    /// Generate the return type for or_else.
    /// or_else returns the same std::optional<T> type.
    pub fn or_else_return_type(&self) -> String {
        format!("std::optional<{}>", self.value_type)
    }

    /// Codegen: generate a pseudo-implementation of and_then.
    pub fn codegen_and_then(&self) -> String {
        format!(
            "if (this->has_value()) {{\n    return f(**this);  // f returns optional<U>\n}} else {{\n    return std::nullopt;\n}}"
        )
    }

    /// Codegen: generate a pseudo-implementation of or_else.
    pub fn codegen_or_else(&self) -> String {
        format!(
            "if (this->has_value()) {{\n    return *this;\n}} else {{\n    return f();\n}}"
        )
    }

    /// Codegen: generate a pseudo-implementation of transform.
    pub fn codegen_transform(&self) -> String {
        format!(
            "if (this->has_value()) {{\n    return std::optional<U>(f(**this));\n}} else {{\n    return std::nullopt;\n}}"
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// std::expected<T,E> — P0323R12
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents the error type in std::expected.
#[derive(Debug, Clone)]
pub enum ExpectedError {
    /// std::unexpected<E> wrapper
    Unexpected(String),
    /// Default-constructed error from E
    Default,
}

/// Monadic operations for std::expected<T,E> (C++23).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpectedMonadicOp {
    /// `exp.and_then(f)` — if has_value, returns f(*exp); else returns unexpected
    AndThen,
    /// `exp.or_else(f)` — if has_value, returns *exp; else calls f(error())
    OrElse,
    /// `exp.transform(f)` — if has_value, returns expected<U,E>(f(*exp))
    Transform,
    /// `exp.transform_error(f)` — if !has_value, returns expected<T,G>(unexpected, f(error()))
    TransformError,
}

impl fmt::Display for ExpectedMonadicOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AndThen => write!(f, "and_then"),
            Self::OrElse => write!(f, "or_else"),
            Self::Transform => write!(f, "transform"),
            Self::TransformError => write!(f, "transform_error"),
        }
    }
}

/// Descriptor for std::expected<T, E>.
#[derive(Debug, Clone)]
pub struct ExpectedType {
    /// The value type T
    pub value_type: String,
    /// The error type E (must not be a reference, must not be void)
    pub error_type: String,
    /// Whether monadic operations are enabled
    pub monadic_enabled: bool,
}

impl ExpectedType {
    pub fn new(value_type: &str, error_type: &str) -> Self {
        Self {
            value_type: value_type.to_string(),
            error_type: error_type.to_string(),
            monadic_enabled: true,
        }
    }

    /// Validate the std::expected type constraints.
    pub fn validate(&self) -> Result<(), String> {
        if self.value_type == "void" {
            // void value type is allowed in C++23 (P2505R5-style)
        }
        if self.error_type == "void" {
            return Err("std::expected error type cannot be void".to_string());
        }
        Ok(())
    }

    /// Generate the return type for and_then.
    pub fn and_then_return_type(&self, f_return_expected_of: &str) -> String {
        format!(
            "std::expected<{}, {}>",
            f_return_expected_of, self.error_type
        )
    }

    /// Generate the return type for transform.
    pub fn transform_return_type(&self, f_return_type: &str) -> String {
        format!(
            "std::expected<{}, {}>",
            f_return_type, self.error_type
        )
    }

    /// Generate the return type for transform_error.
    pub fn transform_error_return_type(&self, f_return_error: &str) -> String {
        format!(
            "std::expected<{}, {}>",
            self.value_type, f_return_error
        )
    }

    /// Generate the return type for or_else.
    pub fn or_else_return_type(&self) -> String {
        format!("std::expected<{}, {}>", self.value_type, self.error_type)
    }

    /// Codegen for and_then.
    pub fn codegen_and_then(&self) -> String {
        "if (has_value) return invoke(f, value); else return unexpected(error);".to_string()
    }

    /// Codegen for or_else.
    pub fn codegen_or_else(&self) -> String {
        "if (has_value) return expected(value, in_place); else return invoke(f, error);".to_string()
    }

    /// Codegen for transform.
    pub fn codegen_transform(&self) -> String {
        "if (has_value) return expected(invoke(f, value)); else return unexpected(error);".to_string()
    }

    /// Codegen for transform_error.
    pub fn codegen_transform_error(&self) -> String {
        "if (!has_value) return expected(unexpected(invoke(f, error))); else return expected(value, in_place);".to_string()
    }
}

/// A value-or-error construct.
#[derive(Debug, Clone)]
pub enum ExpectedValue<T, E> {
    Ok(T),
    Err(E),
}

impl<T, E> ExpectedValue<T, E> {
    pub fn is_ok(&self) -> bool {
        matches!(self, Self::Ok(_))
    }

    pub fn is_err(&self) -> bool {
        matches!(self, Self::Err(_))
    }

    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> ExpectedValue<U, E> {
        match self {
            Self::Ok(v) => ExpectedValue::Ok(f(v)),
            Self::Err(e) => ExpectedValue::Err(e),
        }
    }

    pub fn and_then<U, F: FnOnce(T) -> ExpectedValue<U, E>>(self, f: F) -> ExpectedValue<U, E> {
        match self {
            Self::Ok(v) => f(v),
            Self::Err(e) => ExpectedValue::Err(e),
        }
    }

    pub fn or_else<F: FnOnce(E) -> ExpectedValue<T, E>>(self, f: F) -> ExpectedValue<T, E> {
        match self {
            Self::Ok(v) => ExpectedValue::Ok(v),
            Self::Err(e) => f(e),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Ranges Extensions — C++23/C++26
// ═══════════════════════════════════════════════════════════════════════════════

/// A view adaptor in the ranges library.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RangeViewAdaptor {
    /// `views::zip` — zip multiple ranges
    Zip,
    /// `views::zip_transform` — zip with transformation
    ZipTransform,
    /// `views::adjacent<N>` — sliding window of N elements
    Adjacent,
    /// `views::adjacent_transform<N>` — sliding window with transform
    AdjacentTransform,
    /// `views::cartesian_product` — cartesian product of ranges
    CartesianProduct,
    /// `views::enumerate` — index + element pairs
    Enumerate,
    /// `views::as_const` — const view of range elements
    AsConst,
    /// `views::as_rvalue` — rvalue view of range elements
    AsRvalue,
    /// `views::repeat` — repeat a value N or infinite times
    Repeat,
    /// `views::stride` — skip N-1 elements between each returned
    Stride,
    /// `views::slide` — sliding window of N elements (overlapping)
    Slide,
    /// `views::chunk` — non-overlapping chunks of N elements
    Chunk,
    /// `views::chunk_by` — chunk by a predicate
    ChunkBy,
    /// `views::join_with` — join with a delimiter
    JoinWith,
    /// `views::iota` — iota view extensions
    Iota,
}

impl RangeViewAdaptor {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Zip => "zip",
            Self::ZipTransform => "zip_transform",
            Self::Adjacent => "adjacent",
            Self::AdjacentTransform => "adjacent_transform",
            Self::CartesianProduct => "cartesian_product",
            Self::Enumerate => "enumerate",
            Self::AsConst => "as_const",
            Self::AsRvalue => "as_rvalue",
            Self::Repeat => "repeat",
            Self::Stride => "stride",
            Self::Slide => "slide",
            Self::Chunk => "chunk",
            Self::ChunkBy => "chunk_by",
            Self::JoinWith => "join_with",
            Self::Iota => "iota",
        }
    }

    pub fn header(&self) -> &'static str {
        match self {
            Self::Zip | Self::ZipTransform | Self::Adjacent | Self::AdjacentTransform => {
                "<ranges>"
            }
            Self::CartesianProduct | Self::Enumerate | Self::AsConst | Self::AsRvalue => {
                "<ranges>"
            }
            Self::Repeat | Self::Stride | Self::Slide | Self::Chunk | Self::ChunkBy
            | Self::JoinWith | Self::Iota => "<ranges>",
        }
    }
}

/// Configuration for a range view.
#[derive(Debug, Clone)]
pub struct RangeViewConfig {
    pub adaptor: RangeViewAdaptor,
    pub element_type: String,
    pub is_const: bool,
    pub is_sized: bool,
    pub is_borrowed: bool,
    pub is_common: bool,
}

impl RangeViewConfig {
    pub fn new(adaptor: RangeViewAdaptor, element_type: &str) -> Self {
        let (is_sized, is_borrowed, is_common) = match adaptor {
            RangeViewAdaptor::Zip => (true, false, true),
            RangeViewAdaptor::ZipTransform => (true, false, true),
            RangeViewAdaptor::Adjacent => (true, false, false),
            RangeViewAdaptor::AdjacentTransform => (true, false, false),
            RangeViewAdaptor::CartesianProduct => (true, false, true),
            RangeViewAdaptor::Enumerate => (true, false, true),
            RangeViewAdaptor::AsConst => (true, false, true),
            RangeViewAdaptor::AsRvalue => (true, false, true),
            RangeViewAdaptor::Repeat => (false, false, false),
            RangeViewAdaptor::Stride => (true, false, false),
            RangeViewAdaptor::Slide => (true, false, false),
            RangeViewAdaptor::Chunk => (true, false, false),
            RangeViewAdaptor::ChunkBy => (false, false, false),
            RangeViewAdaptor::JoinWith => (false, false, false),
            RangeViewAdaptor::Iota => (true, false, true),
        };
        Self {
            adaptor,
            element_type: element_type.to_string(),
            is_const: false,
            is_sized,
            is_borrowed,
            is_common,
        }
    }
}

/// Iterator for a zip view.
#[derive(Debug, Clone)]
pub struct ZipIterator {
    pub ranges_count: usize,
    pub value_types: Vec<String>,
}

impl ZipIterator {
    pub fn new(count: usize, types: Vec<String>) -> Self {
        Self {
            ranges_count: count,
            value_types: types,
        }
    }

    pub fn deref_type(&self) -> String {
        format!(
            "std::tuple<{}>",
            self.value_types
                .iter()
                .map(|t| format!("{}&", t))
                .collect::<Vec<_>>()
                .join(", ")
        )
    }
}

/// Iterator for an enumerate view.
#[derive(Debug, Clone)]
pub struct EnumerateIterator {
    pub value_type: String,
    pub index_type: String,
}

impl EnumerateIterator {
    pub fn new(value_type: &str) -> Self {
        Self {
            value_type: value_type.to_string(),
            index_type: "std::size_t".to_string(),
        }
    }

    pub fn element_type(&self) -> String {
        format!(
            "std::tuple<{}, {}&>",
            self.index_type, self.value_type
        )
    }
}

/// A chunk view over a range.
#[derive(Debug, Clone)]
pub struct ChunkView {
    pub chunk_size: usize,
    pub element_type: String,
}

impl ChunkView {
    pub fn new(chunk_size: usize, element_type: &str) -> Self {
        Self {
            chunk_size,
            element_type: element_type.to_string(),
        }
    }

    pub fn inner_range_type(&self) -> String {
        format!("std::ranges::take_view<std::ranges::ref_view<{}>>", self.element_type)
    }
}

/// A cartesian product view.
#[derive(Debug, Clone)]
pub struct CartesianProductView {
    pub first_type: String,
    pub second_type: String,
}

impl CartesianProductView {
    pub fn new(first: &str, second: &str) -> Self {
        Self {
            first_type: first.to_string(),
            second_type: second.to_string(),
        }
    }

    pub fn element_type(&self) -> String {
        format!(
            "std::tuple<{}&, {}&>",
            self.first_type, self.second_type
        )
    }
}

/// Registry for ranges adaptors.
pub struct RangesAdaptorRegistry {
    adaptors: BTreeMap<String, RangeViewConfig>,
}

impl RangesAdaptorRegistry {
    pub fn new() -> Self {
        let mut registry = Self {
            adaptors: BTreeMap::new(),
        };
        // Register all C++23 adaptors
        for adaptor in &[
            RangeViewAdaptor::Zip,
            RangeViewAdaptor::ZipTransform,
            RangeViewAdaptor::Adjacent,
            RangeViewAdaptor::AdjacentTransform,
            RangeViewAdaptor::CartesianProduct,
            RangeViewAdaptor::Enumerate,
            RangeViewAdaptor::AsConst,
            RangeViewAdaptor::AsRvalue,
            RangeViewAdaptor::Repeat,
            RangeViewAdaptor::Stride,
            RangeViewAdaptor::Slide,
            RangeViewAdaptor::Chunk,
            RangeViewAdaptor::ChunkBy,
            RangeViewAdaptor::JoinWith,
            RangeViewAdaptor::Iota,
        ] {
            let config = RangeViewConfig::new(*adaptor, "auto");
            registry.adaptors.insert(adaptor.name().to_string(), config);
        }
        registry
    }

    pub fn lookup(&self, name: &str) -> Option<&RangeViewConfig> {
        self.adaptors.get(name)
    }

    pub fn is_adaptor(&self, name: &str) -> bool {
        self.adaptors.contains_key(name)
    }

    pub fn adaptor_names(&self) -> Vec<&str> {
        self.adaptors.keys().map(|s| s.as_str()).collect()
    }

    pub fn count(&self) -> usize {
        self.adaptors.len()
    }
}

impl Default for RangesAdaptorRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C++23 Feature Flags Registry
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a C++23 or C++26 feature flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CXX23Feature {
    DeducingThis,
    IfConsteval,
    StaticOperatorCall,
    MultiDimSubscript,
    DecayCopy,
    WarningDirective,
    ElifdefElifndef,
    SizeTLiteral,
    ConstexprVirtual,
    ConstexprTryCatch,
    ConstexprDynamicCast,
    Unreachable,
    OptionalMonadic,
    Expected,
    ZipView,
    ZipTransformView,
    EnumerateView,
    AdjacentView,
    CartesianProductView,
    AsConstView,
    AsRvalueView,
    RepeatView,
    StrideView,
    SlideView,
    ChunkView,
    ChunkByView,
    JoinWithView,
}

impl CXX23Feature {
    pub fn name(&self) -> &'static str {
        match self {
            Self::DeducingThis => "deducing_this",
            Self::IfConsteval => "if_consteval",
            Self::StaticOperatorCall => "static_operator_call",
            Self::MultiDimSubscript => "multidimensional_subscript",
            Self::DecayCopy => "decay_copy",
            Self::WarningDirective => "warning_directive",
            Self::ElifdefElifndef => "elifdef_elifndef",
            Self::SizeTLiteral => "size_t_literal",
            Self::ConstexprVirtual => "constexpr_virtual",
            Self::ConstexprTryCatch => "constexpr_try_catch",
            Self::ConstexprDynamicCast => "constexpr_dynamic_cast",
            Self::Unreachable => "unreachable",
            Self::OptionalMonadic => "optional_monadic",
            Self::Expected => "expected",
            Self::ZipView => "zip_view",
            Self::ZipTransformView => "zip_transform_view",
            Self::EnumerateView => "enumerate_view",
            Self::AdjacentView => "adjacent_view",
            Self::CartesianProductView => "cartesian_product_view",
            Self::AsConstView => "as_const_view",
            Self::AsRvalueView => "as_rvalue_view",
            Self::RepeatView => "repeat_view",
            Self::StrideView => "stride_view",
            Self::SlideView => "slide_view",
            Self::ChunkView => "chunk_view",
            Self::ChunkByView => "chunk_by_view",
            Self::JoinWithView => "join_with_view",
        }
    }

    pub fn paper_number(&self) -> &'static str {
        match self {
            Self::DeducingThis => "P0847R7",
            Self::IfConsteval => "P1938R3",
            Self::StaticOperatorCall => "P1169R4",
            Self::MultiDimSubscript => "P2128R6",
            Self::DecayCopy => "P0849R8",
            Self::WarningDirective => "P2437R1",
            Self::ElifdefElifndef => "P2334R1",
            Self::SizeTLiteral => "P0330R8",
            Self::ConstexprVirtual => "P1064R0",
            Self::ConstexprTryCatch => "P1002R1",
            Self::ConstexprDynamicCast => "P1327R1",
            Self::Unreachable => "P0627R6",
            Self::OptionalMonadic => "P0798R8",
            Self::Expected => "P0323R12",
            Self::ZipView => "P2321R2",
            Self::ZipTransformView => "P2321R2",
            Self::EnumerateView => "P2164R9",
            Self::AdjacentView => "P2321R2",
            Self::CartesianProductView => "P2374R4",
            Self::AsConstView => "P2278R4",
            Self::AsRvalueView => "P2446R2",
            Self::RepeatView => "P2474R2",
            Self::StrideView => "P1899R3",
            Self::SlideView => "P2442R1",
            Self::ChunkView => "P2442R1",
            Self::ChunkByView => "P2443R1",
            Self::JoinWithView => "P2441R2",
        }
    }
}

/// Registry for tracking which C++23/26 features are enabled.
pub struct CXX23FeatureRegistry {
    features: HashMap<CXX23Feature, bool>,
    standard_version: CXXStandardVersion,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXXStandardVersion {
    CXX17,
    CXX20,
    CXX23,
    CXX26,
}

impl CXXStandardVersion {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::CXX17 => "c++17",
            Self::CXX20 => "c++20",
            Self::CXX23 => "c++23",
            Self::CXX26 => "c++26",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "c++17" | "c++1z" => Some(Self::CXX17),
            "c++20" | "c++2a" => Some(Self::CXX20),
            "c++23" | "c++2b" => Some(Self::CXX23),
            "c++26" | "c++2c" => Some(Self::CXX26),
            _ => None,
        }
    }
}

impl CXX23FeatureRegistry {
    pub fn new(standard: CXXStandardVersion) -> Self {
        let mut features = HashMap::new();
        // Initialize all features to false
        for feature in &[
            CXX23Feature::DeducingThis,
            CXX23Feature::IfConsteval,
            CXX23Feature::StaticOperatorCall,
            CXX23Feature::MultiDimSubscript,
            CXX23Feature::DecayCopy,
            CXX23Feature::WarningDirective,
            CXX23Feature::ElifdefElifndef,
            CXX23Feature::SizeTLiteral,
            CXX23Feature::ConstexprVirtual,
            CXX23Feature::ConstexprTryCatch,
            CXX23Feature::ConstexprDynamicCast,
            CXX23Feature::Unreachable,
            CXX23Feature::OptionalMonadic,
            CXX23Feature::Expected,
            CXX23Feature::ZipView,
            CXX23Feature::ZipTransformView,
            CXX23Feature::EnumerateView,
            CXX23Feature::AdjacentView,
            CXX23Feature::CartesianProductView,
            CXX23Feature::AsConstView,
            CXX23Feature::AsRvalueView,
            CXX23Feature::RepeatView,
            CXX23Feature::StrideView,
            CXX23Feature::SlideView,
            CXX23Feature::ChunkView,
            CXX23Feature::ChunkByView,
            CXX23Feature::JoinWithView,
        ] {
            // Enable features based on standard version
            let enabled = match standard {
                CXXStandardVersion::CXX17 => false,
                CXXStandardVersion::CXX20 => matches!(
                    feature,
                    CXX23Feature::ConstexprVirtual
                        | CXX23Feature::ConstexprTryCatch
                        | CXX23Feature::ConstexprDynamicCast
                ),
                CXXStandardVersion::CXX23 => true,
                CXXStandardVersion::CXX26 => true,
            };
            features.insert(*feature, enabled);
        }
        Self {
            features,
            standard_version: standard,
        }
    }

    pub fn is_enabled(&self, feature: CXX23Feature) -> bool {
        self.features.get(&feature).copied().unwrap_or(false)
    }

    pub fn enable(&mut self, feature: CXX23Feature) {
        self.features.insert(feature, true);
    }

    pub fn disable(&mut self, feature: CXX23Feature) {
        self.features.insert(feature, false);
    }

    pub fn standard(&self) -> CXXStandardVersion {
        self.standard_version
    }

    pub fn enabled_features(&self) -> Vec<CXX23Feature> {
        self.features
            .iter()
            .filter_map(|(f, &enabled)| if enabled { Some(*f) } else { None })
            .collect()
    }

    pub fn feature_count(&self) -> usize {
        self.features.len()
    }

    pub fn enabled_count(&self) -> usize {
        self.enabled_features().len()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    // ── Deducing This tests ──────────────────────────────────────────────

    #[test]
    fn test_explicit_object_kind_from_param_str() {
        assert_eq!(
            ExplicitObjectKind::from_param_str("this auto&& self"),
            Some(ExplicitObjectKind::DeducedRef)
        );
        assert_eq!(
            ExplicitObjectKind::from_param_str("this auto& self"),
            Some(ExplicitObjectKind::DeducedLvalueRef)
        );
        assert_eq!(
            ExplicitObjectKind::from_param_str("this auto self"),
            Some(ExplicitObjectKind::DeducedByValue)
        );
        assert_eq!(
            ExplicitObjectKind::from_param_str("this const auto& self"),
            Some(ExplicitObjectKind::DeducedConstLvalueRef)
        );
        assert_eq!(ExplicitObjectKind::from_param_str("int x"), None);
    }

    #[test]
    fn test_explicit_object_kind_properties() {
        let by_value = ExplicitObjectKind::DeducedByValue;
        let ref_kind = ExplicitObjectKind::DeducedRef;
        let const_ref = ExplicitObjectKind::DeducedConstLvalueRef;

        assert!(!by_value.is_reference());
        assert!(ref_kind.is_reference());
        assert!(const_ref.is_reference());
        assert!(!by_value.is_const());
        assert!(const_ref.is_const());
    }

    #[test]
    fn test_explicit_object_function_creation() {
        let func = ExplicitObjectFunction::new("f", ExplicitObjectKind::DeducedRef, "self");
        assert_eq!(func.name, "f");
        assert_eq!(func.param_name, "self");
        assert!(func.can_bind_lvalue());
        assert!(func.can_bind_rvalue());
    }

    #[test]
    fn test_explicit_object_function_lvalue_only() {
        let func = ExplicitObjectFunction::new(
            "f",
            ExplicitObjectKind::DeducedLvalueRef,
            "self",
        );
        assert!(func.can_bind_lvalue());
        assert!(!func.can_bind_rvalue());
    }

    #[test]
    fn test_deducing_this_parser_parse_param() {
        let mut parser = DeducingThisParser::new();
        assert_eq!(
            parser.parse_param("this auto&& self"),
            Some(ExplicitObjectKind::DeducedRef)
        );
        assert_eq!(parser.parse_param("int x"), None);
        assert_eq!(parser.parse_param("this is not valid"), None);
    }

    #[test]
    fn test_deducing_this_parser_validate_constructor() {
        let mut parser = DeducingThisParser::new();
        let mut func = ExplicitObjectFunction::new("Foo", ExplicitObjectKind::DeducedRef, "self");
        func.class_name = Some("Foo".to_string());
        func.is_member = true;
        assert!(!parser.validate(&func));
        assert!(!parser.diagnostics.is_empty());
    }

    #[test]
    fn test_deducing_this_parser_deduce_type() {
        let parser = DeducingThisParser::new();
        let func = ExplicitObjectFunction::new("f", ExplicitObjectKind::DeducedRef, "self");
        assert_eq!(parser.deduce_this_type(&func, true), "auto&");
        assert_eq!(parser.deduce_this_type(&func, false), "auto&&");
    }

    // ── if consteval tests ─────────────────────────────────────────────

    #[test]
    fn test_consteval_context_enter_leave() {
        let mut ctx = ConstevalContext::new();
        assert!(!ctx.is_consteval());
        ctx.enter(true);
        assert!(ctx.is_consteval());
        ctx.leave();
        assert!(!ctx.is_consteval());
    }

    #[test]
    fn test_consteval_context_nested() {
        let mut ctx = ConstevalContext::new();
        ctx.enter(false);
        assert!(!ctx.is_consteval());
        ctx.enter(true);
        assert!(ctx.is_consteval());
        ctx.leave();
        assert!(!ctx.is_consteval());
    }

    #[test]
    fn test_evaluate_if_consteval() {
        let mut ctx = ConstevalContext::new();
        assert_eq!(
            ctx.evaluate_if_consteval(),
            IfConstevalResult::NonImmediateContext
        );
        ctx.enter(true);
        assert_eq!(
            ctx.evaluate_if_consteval(),
            IfConstevalResult::ImmediateContext
        );
    }

    #[test]
    fn test_if_consteval_parser_detect() {
        let parser = IfConstevalParser::new();
        assert!(parser.detect_consteval(&["if", "consteval"]));
        assert!(!parser.detect_consteval(&["if", "constexpr"]));
        assert!(!parser.detect_consteval(&["if"]));
    }

    // ── static operator() tests ────────────────────────────────────────

    #[test]
    fn test_static_operator_call_validation() {
        let mut op = StaticOperatorCall::new("MyLambda");
        op.is_lambda = true;
        op.has_captures = false;
        assert!(op.validate().is_ok());

        op.has_captures = true;
        assert!(op.validate().is_err());
    }

    #[test]
    fn test_call_operator_kind_display() {
        assert_eq!(CallOperatorKind::Static.to_string(), "static operator()");
        assert_eq!(CallOperatorKind::Const.to_string(), "operator() const");
    }

    // ── Multidimensional Subscript tests ───────────────────────────────

    #[test]
    fn test_multi_dim_subscript_validation() {
        let sub = MultiDimSubscript::new(2);
        assert!(sub.validate().is_ok());

        let sub0 = MultiDimSubscript::new(0);
        assert!(sub0.validate().is_err());
    }

    #[test]
    fn test_multi_dim_subscript_call_syntax() {
        let sub = MultiDimSubscript::new(2);
        assert_eq!(sub.call_syntax("m", &["i", "j"]), "m[i, j]");
    }

    #[test]
    fn test_multi_dim_subscript_lower() {
        let sub = MultiDimSubscript::new(2);
        let ir = sub.lower_subscript("ptr", &[1, 2]);
        assert!(ir.contains("getelementptr"));
        assert!(ir.contains("i64 1"));
        assert!(ir.contains("i64 2"));
    }

    // ── Decay Copy tests ───────────────────────────────────────────────

    #[test]
    fn test_decay_copy_parser_paren() {
        let expr = DecayCopyParser::try_parse("auto(x)");
        assert!(expr.is_some());
        let expr = expr.unwrap();
        assert_eq!(expr.kind, DecayCopyKind::DecayCopyParen);
        assert_eq!(expr.inner_expr, "x");
    }

    #[test]
    fn test_decay_copy_parser_brace() {
        let expr = DecayCopyParser::try_parse("auto{x}");
        assert!(expr.is_some());
        let expr = expr.unwrap();
        assert_eq!(expr.kind, DecayCopyKind::DecayCopyBrace);
        assert_eq!(expr.inner_expr, "x");
    }

    #[test]
    fn test_decay_copy_parser_not_decay() {
        assert!(DecayCopyParser::try_parse("42").is_none());
        assert!(DecayCopyParser::try_parse("auto").is_none());
    }

    #[test]
    fn test_decay_copy_apply_decay_const_ref() {
        let expr = DecayCopyExpr::new(DecayCopyKind::DecayCopyParen, "x");
        assert_eq!(expr.apply_decay("const int&"), "int");
    }

    #[test]
    fn test_decay_copy_apply_decay_array() {
        let expr = DecayCopyExpr::new(DecayCopyKind::DecayCopyParen, "arr");
        assert_eq!(expr.apply_decay("int[10]"), "int*");
    }

    #[test]
    fn test_decay_copy_display() {
        assert_eq!(
            DecayCopyKind::DecayCopyParen.to_string(),
            "auto"
        );
        assert_eq!(
            DecayCopyKind::DecayCopyBrace.to_string(),
            "auto{}"
        );
    }

    // ── #warning directive tests ───────────────────────────────────────

    #[test]
    fn test_warning_directive_format() {
        let w = WarningDirective::new("deprecated API", 42, "test.cpp");
        assert!(w.format_diagnostic().contains("test.cpp"));
        assert!(w.format_diagnostic().contains("42"));
        assert!(w.format_diagnostic().contains("deprecated API"));
    }

    #[test]
    fn test_warning_handler() {
        let mut handler = WarningDirectiveHandler::new();
        handler.handle("test warning", 10, "file.cpp");
        assert!(handler.has_warnings());
        assert_eq!(handler.warnings.len(), 1);
    }

    // ── #elifdef / #elifndef tests ──────────────────────────────────────

    #[test]
    fn test_elif_conditional_from_directive() {
        assert_eq!(
            ElifConditional::from_directive("elifdef"),
            Some(ElifConditional::Elifdef)
        );
        assert_eq!(
            ElifConditional::from_directive("elifndef"),
            Some(ElifConditional::Elifndef)
        );
        assert_eq!(
            ElifConditional::from_directive("elif"),
            Some(ElifConditional::Elif)
        );
        assert_eq!(ElifConditional::from_directive("ifndef"), None);
    }

    #[test]
    fn test_conditional_chain_ifdef() {
        let mut chain = ConditionalChain::new();
        chain.handle_ifdef("FOO", true);
        assert!(chain.branch_taken);
        assert_eq!(chain.blocks.len(), 1);
    }

    #[test]
    fn test_conditional_chain_elifdef() {
        let mut chain = ConditionalChain::new();
        chain.handle_ifdef("FOO", false);
        assert!(!chain.branch_taken);
        chain.handle_elifdef("BAR", true);
        assert!(chain.branch_taken);
    }

    #[test]
    fn test_conditional_chain_elifndef() {
        let mut chain = ConditionalChain::new();
        chain.handle_ifdef("FOO", false);
        assert!(!chain.branch_taken);
        chain.handle_elifndef("BAR", false);
        assert!(chain.branch_taken);
    }

    #[test]
    fn test_conditional_chain_else() {
        let mut chain = ConditionalChain::new();
        chain.handle_ifdef("FOO", false);
        chain.handle_elifdef("BAR", false);
        chain.handle_else();
        assert!(chain.branch_taken);
    }

    #[test]
    fn test_conditional_chain_reset() {
        let mut chain = ConditionalChain::new();
        chain.handle_ifdef("FOO", true);
        chain.reset();
        assert!(!chain.branch_taken);
        assert!(chain.blocks.is_empty());
    }

    // ── Size T Literal tests ───────────────────────────────────────────

    #[test]
    fn test_size_t_literal_parser_uz() {
        let lit = SizeTLiteralParser::try_parse("42uz");
        assert!(lit.is_some());
        let lit = lit.unwrap();
        assert_eq!(lit.value, "42");
        assert_eq!(lit.suffix, SizeTLiteralSuffix::Uz);
        assert!(!lit.suffix.is_signed());
    }

    #[test]
    fn test_size_t_literal_parser_z() {
        let lit = SizeTLiteralParser::try_parse("42z");
        assert!(lit.is_some());
        let lit = lit.unwrap();
        assert_eq!(lit.suffix, SizeTLiteralSuffix::Z);
        assert!(lit.suffix.is_signed());
    }

    #[test]
    fn test_size_t_literal_parser_non_literal() {
        assert!(SizeTLiteralParser::try_parse("42").is_none());
        assert!(SizeTLiteralParser::try_parse("abc").is_none());
    }

    #[test]
    fn test_size_t_literal_to_source() {
        let lit = SizeTLiteral::new("100", SizeTLiteralSuffix::Uz);
        assert_eq!(lit.to_source(), "100uz");
    }

    // ── constexpr extensions tests ──────────────────────────────────────

    #[test]
    fn test_constexpr_extensions_default() {
        let ext = ConstexprExtensions::default();
        assert!(ext.constexpr_virtual);
        assert!(ext.constexpr_try_catch);
        assert!(ext.constexpr_dynamic_cast);
    }

    #[test]
    fn test_constexpr_virtual_validate_pure() {
        let mut func = ConstexprVirtualFunction::new("f", "Base");
        func.is_pure_virtual = true;
        assert!(func.validate().is_err());
    }

    #[test]
    fn test_constexpr_virtual_validate_normal() {
        let func = ConstexprVirtualFunction::new("f", "Base");
        assert!(func.validate().is_ok());
    }

    #[test]
    fn test_constexpr_try_catch_new() {
        let tc = ConstexprTryCatch::new();
        assert!(!tc.is_constexpr);
        assert!(tc.catch_types.is_empty());
        assert!(tc.can_be_constexpr);
    }

    #[test]
    fn test_constexpr_dynamic_cast_new() {
        let cd = ConstexprDynamicCast::new("Base*", "Derived*");
        assert_eq!(cd.src_type, "Base*");
        assert_eq!(cd.dst_type, "Derived*");
    }

    // ── std::unreachable tests ─────────────────────────────────────────

    #[test]
    fn test_unreachable_emit_llvm() {
        let ub = UnreachableBuiltin::new();
        let ir = ub.emit_llvm();
        assert!(ir.contains("llvm.trap"));
        assert!(ir.contains("unreachable"));
    }

    #[test]
    fn test_unreachable_default() {
        let ub = UnreachableBuiltin::default();
        assert!(ub.is_noreturn);
    }

    // ── Optional Monadic tests ─────────────────────────────────────────

    #[test]
    fn test_optional_monadic_and_then_return() {
        let opt = OptionalMonadic::new("int");
        assert_eq!(
            opt.and_then_return_type("double"),
            "std::optional<double>"
        );
    }

    #[test]
    fn test_optional_monadic_transform_return() {
        let opt = OptionalMonadic::new("int");
        assert_eq!(
            opt.transform_return_type("double"),
            "std::optional<double>"
        );
    }

    #[test]
    fn test_optional_monadic_or_else_return() {
        let opt = OptionalMonadic::new("int");
        assert_eq!(opt.or_else_return_type(), "std::optional<int>");
    }

    #[test]
    fn test_optional_monadic_codegen_and_then() {
        let opt = OptionalMonadic::new("int");
        let cg = opt.codegen_and_then();
        assert!(cg.contains("has_value"));
        assert!(cg.contains("nullopt"));
    }

    #[test]
    fn test_optional_monadic_codegen_or_else() {
        let opt = OptionalMonadic::new("int");
        let cg = opt.codegen_or_else();
        assert!(cg.contains("has_value"));
        assert!(cg.contains("f()"));
    }

    #[test]
    fn test_optional_monadic_op_display() {
        assert_eq!(OptionalMonadicOp::AndThen.to_string(), "and_then");
        assert_eq!(OptionalMonadicOp::OrElse.to_string(), "or_else");
        assert_eq!(OptionalMonadicOp::Transform.to_string(), "transform");
    }

    // ── std::expected tests ────────────────────────────────────────────

    #[test]
    fn test_expected_validation() {
        let exp = ExpectedType::new("int", "std::error_code");
        assert!(exp.validate().is_ok());
    }

    #[test]
    fn test_expected_validation_error_void() {
        let exp = ExpectedType::new("int", "void");
        assert!(exp.validate().is_err());
    }

    #[test]
    fn test_expected_and_then_return() {
        let exp = ExpectedType::new("int", "std::string");
        assert_eq!(
            exp.and_then_return_type("double"),
            "std::expected<double, std::string>"
        );
    }

    #[test]
    fn test_expected_transform_error_return() {
        let exp = ExpectedType::new("int", "std::string");
        assert_eq!(
            exp.transform_error_return_type("int"),
            "std::expected<int, int>"
        );
    }

    #[test]
    fn test_expected_monadic_op_display() {
        assert_eq!(ExpectedMonadicOp::AndThen.to_string(), "and_then");
        assert_eq!(ExpectedMonadicOp::TransformError.to_string(), "transform_error");
    }

    #[test]
    fn test_expected_value_is_ok() {
        let v: ExpectedValue<i32, String> = ExpectedValue::Ok(42);
        assert!(v.is_ok());
        assert!(!v.is_err());
    }

    #[test]
    fn test_expected_value_is_err() {
        let v: ExpectedValue<i32, String> = ExpectedValue::Err("bad".into());
        assert!(!v.is_ok());
        assert!(v.is_err());
    }

    #[test]
    fn test_expected_value_map() {
        let v: ExpectedValue<i32, String> = ExpectedValue::Ok(2);
        let mapped = v.map(|x| x * 3);
        assert!(mapped.is_ok());
        match mapped {
            ExpectedValue::Ok(val) => assert_eq!(val, 6),
            _ => panic!("Expected Ok"),
        }
    }

    #[test]
    fn test_expected_value_and_then() {
        let v: ExpectedValue<i32, String> = ExpectedValue::Ok(1);
        let result = v.and_then(|x| ExpectedValue::Ok(x + 1));
        assert!(result.is_ok());
    }

    #[test]
    fn test_expected_value_or_else() {
        let v: ExpectedValue<i32, String> = ExpectedValue::Err("fail".into());
        let result = v.or_else(|_| ExpectedValue::Ok(0));
        assert!(result.is_ok());
    }

    // ── Range View Adaptor tests ───────────────────────────────────────

    #[test]
    fn test_range_view_adaptor_names() {
        assert_eq!(RangeViewAdaptor::Zip.name(), "zip");
        assert_eq!(RangeViewAdaptor::Enumerate.name(), "enumerate");
        assert_eq!(RangeViewAdaptor::Chunk.name(), "chunk");
        assert_eq!(RangeViewAdaptor::Iota.name(), "iota");
    }

    #[test]
    fn test_range_view_config_zip() {
        let config = RangeViewConfig::new(RangeViewAdaptor::Zip, "int");
        assert!(config.is_sized);
        assert!(!config.is_borrowed);
        assert!(config.is_common);
    }

    #[test]
    fn test_zip_iterator_deref_type() {
        let iter = ZipIterator::new(2, vec!["int".into(), "double".into()]);
        let deref = iter.deref_type();
        assert!(deref.contains("int&"));
        assert!(deref.contains("double&"));
        assert!(deref.contains("tuple"));
    }

    #[test]
    fn test_enumerate_iterator_element_type() {
        let iter = EnumerateIterator::new("int");
        assert!(iter.element_type().contains("size_t"));
        assert!(iter.element_type().contains("int&"));
    }

    #[test]
    fn test_ranges_adaptor_registry_new() {
        let registry = RangesAdaptorRegistry::new();
        assert!(registry.count() > 10);
        assert!(registry.is_adaptor("zip"));
        assert!(registry.is_adaptor("enumerate"));
        assert!(registry.is_adaptor("chunk"));
    }

    #[test]
    fn test_ranges_adaptor_registry_lookup() {
        let registry = RangesAdaptorRegistry::new();
        assert!(registry.lookup("zip").is_some());
        assert!(registry.lookup("nonexistent").is_none());
    }

    // ── Feature flags tests ────────────────────────────────────────────

    #[test]
    fn test_feature_registry_cxx23() {
        let reg = CXX23FeatureRegistry::new(CXXStandardVersion::CXX23);
        assert!(reg.is_enabled(CXX23Feature::DeducingThis));
        assert!(reg.is_enabled(CXX23Feature::OptionalMonadic));
        assert!(reg.is_enabled(CXX23Feature::Expected));
        assert_eq!(reg.standard(), CXXStandardVersion::CXX23);
    }

    #[test]
    fn test_feature_registry_cxx20() {
        let reg = CXX23FeatureRegistry::new(CXXStandardVersion::CXX20);
        assert!(!reg.is_enabled(CXX23Feature::DeducingThis));
        assert!(reg.is_enabled(CXX23Feature::ConstexprVirtual));
        assert!(!reg.is_enabled(CXX23Feature::Expected));
    }

    #[test]
    fn test_feature_registry_cxx17() {
        let reg = CXX23FeatureRegistry::new(CXXStandardVersion::CXX17);
        assert!(!reg.is_enabled(CXX23Feature::DeducingThis));
        assert!(!reg.is_enabled(CXX23Feature::ConstexprVirtual));
    }

    #[test]
    fn test_feature_registry_enable_disable() {
        let mut reg = CXX23FeatureRegistry::new(CXXStandardVersion::CXX20);
        assert!(!reg.is_enabled(CXX23Feature::DeducingThis));
        reg.enable(CXX23Feature::DeducingThis);
        assert!(reg.is_enabled(CXX23Feature::DeducingThis));
        reg.disable(CXX23Feature::DeducingThis);
        assert!(!reg.is_enabled(CXX23Feature::DeducingThis));
    }

    #[test]
    fn test_feature_registry_enabled_count() {
        let reg = CXX23FeatureRegistry::new(CXXStandardVersion::CXX23);
        assert_eq!(reg.enabled_count(), reg.feature_count());
    }

    #[test]
    fn test_cxx_standard_version_from_str() {
        assert_eq!(
            CXXStandardVersion::from_str("c++23"),
            Some(CXXStandardVersion::CXX23)
        );
        assert_eq!(
            CXXStandardVersion::from_str("c++2b"),
            Some(CXXStandardVersion::CXX23)
        );
        assert_eq!(
            CXXStandardVersion::from_str("c++26"),
            Some(CXXStandardVersion::CXX26)
        );
        assert_eq!(CXXStandardVersion::from_str("c++14"), None);
    }

    #[test]
    fn test_feature_paper_numbers() {
        assert_eq!(CXX23Feature::DeducingThis.paper_number(), "P0847R7");
        assert_eq!(CXX23Feature::Expected.paper_number(), "P0323R12");
        assert_eq!(CXX23Feature::EnumerateView.paper_number(), "P2164R9");
    }
}