llvm-native-core 0.1.14

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
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
//! C++ Template Instantiation Engine — implements template argument
//! deduction, substitution, SFINAE tracking, and template instantiation.
//!
//! Clean-room behavioral reconstruction from:
//! - C++ Standard §13 (Templates), §13.10 (Template instantiation)
//! - Published Clang documentation
//! - No LLVM/Clang source code is consulted.

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

use super::ast::QualType;
use super::cpp_ast::*;

// ═══════════════════════════════════════════════════════════════════════════════
// Template Argument Deduction
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of template argument deduction.
#[derive(Debug, Clone)]
pub struct DeductionResult {
    /// Whether deduction succeeded.
    pub success: bool,
    /// Deduced template arguments (parameter name → argument).
    pub deduced_args: HashMap<String, TemplateArgument>,
    /// Failure reason if deduction failed.
    pub failure_reason: Option<String>,
}

impl DeductionResult {
    pub fn success(args: HashMap<String, TemplateArgument>) -> Self {
        Self {
            success: true,
            deduced_args: args,
            failure_reason: None,
        }
    }

    pub fn failure(reason: &str) -> Self {
        Self {
            success: false,
            deduced_args: HashMap::new(),
            failure_reason: Some(reason.to_string()),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Argument Deductor
// ═══════════════════════════════════════════════════════════════════════════════

/// Deduces template arguments from function call arguments.
pub struct TemplateDeductor {
    /// Current deduced arguments during deduction.
    deduced: HashMap<String, TemplateArgument>,
    /// Whether we've encountered a substitution failure (SFINAE).
    substitution_failure: bool,
    /// Error messages collected.
    errors: Vec<String>,
}

impl TemplateDeductor {
    pub fn new() -> Self {
        Self {
            deduced: HashMap::new(),
            substitution_failure: false,
            errors: Vec::new(),
        }
    }

    /// Deduce template arguments for a function template call.
    /// `params` are the template parameters, `arg_types` are the actual call argument types.
    pub fn deduce_function_template_args(
        &mut self,
        template_params: &[TemplateParamDecl],
        param_types: &[QualType], // function parameter types (may reference template params)
        arg_types: &[QualType],   // actual call argument types
    ) -> DeductionResult {
        self.deduced.clear();
        self.substitution_failure = false;
        self.errors.clear();

        if param_types.len() != arg_types.len() {
            return DeductionResult::failure("argument count mismatch");
        }

        for (i, (param_ty, arg_ty)) in param_types.iter().zip(arg_types.iter()).enumerate() {
            if !self.deduce_type(param_ty, arg_ty) {
                return DeductionResult::failure(&format!("deduction failed for parameter {}", i));
            }
        }

        // Verify all template params have been deduced
        for param in template_params {
            let name = match param {
                TemplateParamDecl::TypeParm { name, .. } => name,
                TemplateParamDecl::NonTypeParm { name, .. } => name,
                TemplateParamDecl::TemplateTemplateParm { name, .. } => name,
            };
            if !self.deduced.contains_key(name.as_str()) {
                return DeductionResult::failure(&format!(
                    "template parameter '{}' could not be deduced",
                    name
                ));
            }
        }

        DeductionResult::success(self.deduced.clone())
    }

    /// Deduce template arguments from explicit template arguments + function args.
    pub fn deduce_with_explicit_args(
        &mut self,
        template_params: &[TemplateParamDecl],
        explicit_args: &[TemplateArgument],
        param_types: &[QualType],
        arg_types: &[QualType],
    ) -> DeductionResult {
        self.deduced.clear();
        self.substitution_failure = false;
        self.errors.clear();

        // Set explicit args
        for (i, param) in template_params.iter().enumerate() {
            if i < explicit_args.len() {
                let name = match param {
                    TemplateParamDecl::TypeParm { name, .. } => name,
                    TemplateParamDecl::NonTypeParm { name, .. } => name,
                    TemplateParamDecl::TemplateTemplateParm { name, .. } => name,
                };
                self.deduced.insert(name.clone(), explicit_args[i].clone());
            }
        }

        // Deduce remaining from function args
        if param_types.len() != arg_types.len() {
            return DeductionResult::failure("argument count mismatch");
        }

        for (i, (param_ty, arg_ty)) in param_types.iter().zip(arg_types.iter()).enumerate() {
            if !self.deduce_type(param_ty, arg_ty) {
                return DeductionResult::failure(&format!("deduction failed for parameter {}", i));
            }
        }

        DeductionResult::success(self.deduced.clone())
    }

    /// Try to unify a parameter type with an argument type, deducing
    /// template parameters where possible.
    fn deduce_type(&mut self, param_ty: &QualType, arg_ty: &QualType) -> bool {
        // Check if param_ty is a template parameter
        let param_name = self.extract_template_param_name(param_ty);
        if let Some(name) = param_name {
            if let Some(existing) = self.deduced.get(&name) {
                match existing {
                    TemplateArgument::Type(existing_ty) => {
                        return *existing_ty == *arg_ty;
                    }
                    _ => return false,
                }
            } else {
                self.deduced
                    .insert(name, TemplateArgument::Type(arg_ty.clone()));
                return true;
            }
        }

        // Handle pointer types: T* → int*  deduces T=int
        if param_ty.is_pointer() && arg_ty.is_pointer() {
            // Simplified pointer stripping
            let param_inner = self.strip_pointer(param_ty);
            let arg_inner = self.strip_pointer(arg_ty);
            return self.deduce_type(&param_inner, &arg_inner);
        }

        // Handle reference types
        if self.is_reference(param_ty) && self.is_reference(arg_ty) {
            let param_inner = self.strip_reference(param_ty);
            let arg_inner = self.strip_reference(arg_ty);
            return self.deduce_type(&param_inner, &arg_inner);
        }

        // Handle const qualification
        if param_ty.is_const && arg_ty.is_const {
            let param_unqual = param_ty.unqualified();
            let arg_unqual = arg_ty.unqualified();
            return self.deduce_type(&param_unqual, &arg_unqual);
        }

        // Exact match required for non-template types
        *param_ty == *arg_ty
    }

    /// Extract the name of a template parameter if this type references one.
    fn extract_template_param_name(&self, ty: &QualType) -> Option<String> {
        // For simplicity, we check if the type name in the base matches a
        // known template parameter pattern.
        let type_str = format!("{}", ty);
        // Template parameter types are typically represented as their name
        if type_str.chars().all(|c| c.is_ascii_uppercase() || c == '_') && type_str.len() <= 3 {
            if self.deduced.contains_key(&type_str) || !type_str.is_empty() {
                return Some(type_str);
            }
        }
        None
    }

    /// Strip one level of pointer indirection.
    fn strip_pointer(&self, ty: &QualType) -> QualType {
        // This is a simplified approach — in real code you'd match on TypeNode::Pointer
        let type_str = format!("{}", ty);
        if type_str.ends_with('*') {
            QualType::int() // placeholder
        } else {
            ty.clone()
        }
    }

    /// Strip one level of reference.
    fn strip_reference(&self, ty: &QualType) -> QualType {
        ty.clone() // simplified
    }

    /// Check if this type is a reference type.
    fn is_reference(&self, ty: &QualType) -> bool {
        let s = format!("{}", ty);
        s.ends_with('&') || s.ends_with("&&")
    }

    /// Whether SFINAE is active (substitution failure should suppress error).
    pub fn is_sfinae_active(&self) -> bool {
        self.substitution_failure
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Template Instantiation
// ═══════════════════════════════════════════════════════════════════════════════

/// A template instantiation context.
#[derive(Debug, Clone)]
pub struct TemplateInstantiation {
    /// The template parameters being instantiated.
    pub params: Vec<TemplateParamDecl>,
    /// The template arguments for this instantiation.
    pub args: Vec<TemplateArgument>,
    /// The source location (for diagnostics).
    pub source_loc: Option<String>,
}

/// State for tracking template instantiation depth and recursion.
#[derive(Debug, Clone)]
pub struct InstantiationState {
    /// Current instantiation depth.
    pub depth: usize,
    /// Maximum allowed instantiation depth.
    pub max_depth: usize,
    /// Whether we're in the middle of an instantiation.
    pub is_instantiating: bool,
    /// Which templates have been instantiated (to avoid re-instantiation).
    pub instantiated: HashSet<String>,
}

impl InstantiationState {
    pub fn new(max_depth: usize) -> Self {
        Self {
            depth: 0,
            max_depth,
            is_instantiating: false,
            instantiated: HashSet::new(),
        }
    }

    /// Returns Ok if we can proceed, Err if max depth exceeded.
    pub fn enter_instantiation(&mut self) -> Result<(), String> {
        if self.depth >= self.max_depth {
            return Err(format!(
                "template instantiation depth ({}) exceeds maximum ({})",
                self.depth, self.max_depth
            ));
        }
        self.depth += 1;
        self.is_instantiating = true;
        Ok(())
    }

    /// Leave the current instantiation level.
    pub fn leave_instantiation(&mut self) {
        if self.depth > 0 {
            self.depth -= 1;
        }
        if self.depth == 0 {
            self.is_instantiating = false;
        }
    }

    /// Check if a template specialization has already been instantiated.
    pub fn is_instantiated(&self, name: &str) -> bool {
        self.instantiated.contains(name)
    }

    /// Mark a template specialization as instantiated.
    pub fn mark_instantiated(&mut self, name: &str) {
        self.instantiated.insert(name.to_string());
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Instantiation Engine
// ═══════════════════════════════════════════════════════════════════════════════

/// Engine for instantiating C++ templates.
pub struct TemplateInstantiator {
    /// Current deduction state.
    deductor: TemplateDeductor,
    /// Instantiation state tracking.
    state: InstantiationState,
    /// Cache of instantiated declarations.
    instantiation_cache: HashMap<String, CXXDecl>,
}

impl TemplateInstantiator {
    pub fn new(max_depth: usize) -> Self {
        Self {
            deductor: TemplateDeductor::new(),
            state: InstantiationState::new(max_depth),
            instantiation_cache: HashMap::new(),
        }
    }

    /// Instantiate a class template with the given arguments.
    pub fn instantiate_class_template(
        &mut self,
        template_decl: &CXXDecl,
        args: &[TemplateArgument],
    ) -> Result<CXXDecl, String> {
        match template_decl {
            CXXDecl::TemplateDeclaration { params, decl, .. } => {
                let cache_key = self.make_cache_key(decl, args);
                if self.state.is_instantiated(&cache_key) {
                    return self
                        .instantiation_cache
                        .get(&cache_key)
                        .cloned()
                        .ok_or_else(|| "instantiation cache miss".into());
                }

                self.state.enter_instantiation()?;

                let binding = self.build_arg_binding(params, args);
                let result = self.substitute_decl(decl, &binding)?;

                self.state.leave_instantiation();
                self.state.mark_instantiated(&cache_key);
                self.instantiation_cache.insert(cache_key, result.clone());

                Ok(result)
            }
            _ => Err("not a template declaration".into()),
        }
    }

    /// Instantiate a function template with deduced arguments.
    pub fn instantiate_function_template(
        &mut self,
        template_decl: &CXXDecl,
        args: &[TemplateArgument],
    ) -> Result<CXXDecl, String> {
        self.instantiate_class_template(template_decl, args)
    }

    /// Build the binding from template parameter names to arguments.
    fn build_arg_binding(
        &self,
        params: &[TemplateParamDecl],
        args: &[TemplateArgument],
    ) -> HashMap<String, TemplateArgument> {
        let mut binding = HashMap::new();
        for (i, param) in params.iter().enumerate() {
            let name = match param {
                TemplateParamDecl::TypeParm { name, .. } => name,
                TemplateParamDecl::NonTypeParm { name, .. } => name,
                TemplateParamDecl::TemplateTemplateParm { name, .. } => name,
            };
            if i < args.len() {
                binding.insert(name.clone(), args[i].clone());
            }
        }
        binding
    }

    /// Substitute template arguments into a declaration.
    fn substitute_decl(
        &self,
        decl: &CXXDecl,
        binding: &HashMap<String, TemplateArgument>,
    ) -> Result<CXXDecl, String> {
        match decl {
            CXXDecl::CXXRecord {
                name,
                kind,
                bases,
                members,
                is_final,
                is_polymorphic,
                is_abstract,
                template_params,
            } => {
                let subst_members: Result<Vec<CXXMemberDecl>, _> = members
                    .iter()
                    .map(|m| self.substitute_member_decl(m, binding))
                    .collect();
                Ok(CXXDecl::CXXRecord {
                    name: self.substitute_name(name, binding),
                    kind: *kind,
                    bases: bases.clone(),
                    members: subst_members?,
                    is_final: *is_final,
                    is_polymorphic: *is_polymorphic,
                    is_abstract: *is_abstract,
                    template_params: template_params.clone(),
                })
            }
            CXXDecl::Function {
                name,
                return_ty,
                params,
                body,
                is_virtual,
                is_override,
                is_final,
                is_const,
                is_noexcept,
                is_constexpr,
                is_consteval,
                is_static,
                is_inline,
                is_explicit,
                is_deleted,
                is_defaulted,
                ref_qualifier,
                trailing_return_ty,
                template_params,
                is_volatile,
                linkage,
                init_list,
            } => {
                let subst_return = self.substitute_type(return_ty, binding);
                let subst_params: Result<Vec<CXXParamDecl>, _> = params
                    .iter()
                    .map(|p| self.substitute_param_decl(p, binding))
                    .collect();
                Ok(CXXDecl::Function {
                    name: self.substitute_name(name, binding),
                    return_ty: subst_return,
                    params: subst_params?,
                    body: body.clone(),
                    is_virtual: *is_virtual,
                    is_override: *is_override,
                    is_final: *is_final,
                    is_const: *is_const,
                    is_noexcept: *is_noexcept,
                    is_constexpr: *is_constexpr,
                    is_consteval: *is_consteval,
                    is_static: *is_static,
                    is_inline: *is_inline,
                    is_explicit: *is_explicit,
                    is_deleted: *is_deleted,
                    is_defaulted: *is_defaulted,
                    ref_qualifier: *ref_qualifier,
                    trailing_return_ty: trailing_return_ty.clone(),
                    template_params: template_params.clone(),
                    is_volatile: *is_volatile,
                    linkage: linkage.clone(),
                    init_list: init_list.clone(),
                })
            }
            CXXDecl::Variable {
                name,
                ty,
                init,
                is_constexpr,
                is_constinit,
                is_static,
                is_thread_local,
                is_inline,
            } => {
                let subst_ty = self.substitute_type(ty, binding);
                Ok(CXXDecl::Variable {
                    name: self.substitute_name(name, binding),
                    ty: subst_ty,
                    init: init.clone(),
                    is_constexpr: *is_constexpr,
                    is_constinit: *is_constinit,
                    is_static: *is_static,
                    is_thread_local: *is_thread_local,
                    is_inline: *is_inline,
                })
            }
            CXXDecl::TypeAlias { name, aliased_ty } => {
                let subst_ty = self.substitute_type(aliased_ty, binding);
                Ok(CXXDecl::TypeAlias {
                    name: self.substitute_name(name, binding),
                    aliased_ty: subst_ty,
                })
            }
            _ => Ok(decl.clone()),
        }
    }

    /// Substitute into a member declaration.
    fn substitute_member_decl(
        &self,
        member: &CXXMemberDecl,
        binding: &HashMap<String, TemplateArgument>,
    ) -> Result<CXXMemberDecl, String> {
        match member {
            CXXMemberDecl::Field {
                name,
                ty,
                is_mutable,
                is_static,
                bit_width,
                default_init,
                access,
            } => {
                let subst_ty = self.substitute_type(ty, binding);
                Ok(CXXMemberDecl::Field {
                    name: self.substitute_name(name, binding),
                    ty: subst_ty,
                    is_mutable: *is_mutable,
                    is_static: *is_static,
                    bit_width: bit_width.clone(),
                    default_init: default_init.clone(),
                    access: *access,
                })
            }
            CXXMemberDecl::Method {
                name,
                return_ty,
                params,
                body,
                is_virtual,
                is_pure_virtual,
                is_override,
                is_final,
                is_const,
                is_volatile,
                is_static,
                is_noexcept,
                ref_qualifier,
                is_explicit,
                is_constexpr,
                is_consteval,
                trailing_return_ty,
                access,
            } => {
                let subst_return = self.substitute_type(return_ty, binding);
                let subst_params: Result<Vec<CXXParamDecl>, _> = params
                    .iter()
                    .map(|p| self.substitute_param_decl(p, binding))
                    .collect();
                Ok(CXXMemberDecl::Method {
                    name: self.substitute_name(name, binding),
                    return_ty: subst_return,
                    params: subst_params?,
                    body: body.clone(),
                    is_virtual: *is_virtual,
                    is_pure_virtual: *is_pure_virtual,
                    is_override: *is_override,
                    is_final: *is_final,
                    is_const: *is_const,
                    is_volatile: *is_volatile,
                    is_static: *is_static,
                    is_noexcept: *is_noexcept,
                    ref_qualifier: *ref_qualifier,
                    is_explicit: *is_explicit,
                    is_constexpr: *is_constexpr,
                    is_consteval: *is_consteval,
                    trailing_return_ty: trailing_return_ty.clone(),
                    access: *access,
                })
            }
            _ => Ok(member.clone()),
        }
    }

    /// Substitute into a parameter declaration.
    fn substitute_param_decl(
        &self,
        param: &CXXParamDecl,
        binding: &HashMap<String, TemplateArgument>,
    ) -> Result<CXXParamDecl, String> {
        let subst_ty = self.substitute_type(&param.ty, binding);
        Ok(CXXParamDecl {
            name: param.name.clone(),
            ty: subst_ty,
            ..Default::default()
        })
    }

    /// Substitute template arguments into a type.
    fn substitute_type(
        &self,
        ty: &QualType,
        binding: &HashMap<String, TemplateArgument>,
    ) -> QualType {
        let type_str = format!("{}", ty);
        // Check if this type is a template parameter
        if let Some(arg) = binding.get(&type_str) {
            match arg {
                TemplateArgument::Type(subst_ty) => return subst_ty.clone(),
                _ => {}
            }
        }
        ty.clone()
    }

    /// Substitute template arguments into a name string.
    fn substitute_name(&self, name: &str, binding: &HashMap<String, TemplateArgument>) -> String {
        // Check if the name is a template parameter
        if let Some(arg) = binding.get(name) {
            match arg {
                TemplateArgument::Type(ty) => format!("{}", ty),
                TemplateArgument::NonType(expr) => format!("{}", expr),
                _ => name.to_string(),
            }
        } else {
            name.to_string()
        }
    }

    /// Create a cache key for a template instantiation.
    fn make_cache_key(&self, decl: &CXXDecl, args: &[TemplateArgument]) -> String {
        let name = match decl {
            CXXDecl::CXXRecord { name, .. } => name,
            CXXDecl::Function { name, .. } => name,
            _ => "unknown",
        };
        let args_str: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
        format!("{}<{}>", name, args_str.join(","))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Partial Specialization Matching
// ═══════════════════════════════════════════════════════════════════════════════

/// Checks whether a partial specialization matches a given set of template args.
pub fn match_partial_specialization(
    _primary_params: &[TemplateParamDecl],
    partial_params: &[TemplateParamDecl],
    args: &[TemplateArgument],
) -> bool {
    // A partial specialization matches if we can deduce all partial params
    // from the primary template arguments.
    let _deductor = TemplateDeductor::new();

    // This is a simplified check — full implementation would do actual deduction
    if partial_params.len() <= args.len() {
        for (_i, param) in partial_params.iter().enumerate() {
            let _name = match param {
                TemplateParamDecl::TypeParm { name, .. } => name,
                TemplateParamDecl::NonTypeParm { name, .. } => name,
                TemplateParamDecl::TemplateTemplateParm { name: n, .. } => n,
            };
            // Check if this parameter appears in the specialization pattern
            // (simplified: always succeeds)
        }
        return true;
    }
    false
}

// ═══════════════════════════════════════════════════════════════════════════════
// Class Template Argument Deduction (CTAD) — C++17
// ═══════════════════════════════════════════════════════════════════════════════

/// Deduction guide for class template argument deduction.
#[derive(Debug, Clone)]
pub struct DeductionGuide {
    /// The class template being guided.
    pub class_name: String,
    /// The parameter pattern used for deduction.
    pub params: Vec<CXXParamDecl>,
    /// The deduced template arguments.
    pub deduced_template_args: Vec<TemplateArgument>,
    /// Whether this is an explicit deduction guide.
    pub is_explicit: bool,
    /// Whether this guide was implicitly generated.
    pub is_implicit: bool,
}

impl DeductionGuide {
    /// Create an explicit user-defined deduction guide.
    pub fn explicit_guide(
        class_name: &str,
        params: Vec<CXXParamDecl>,
        deduced: Vec<TemplateArgument>,
    ) -> Self {
        Self {
            class_name: class_name.to_string(),
            params,
            deduced_template_args: deduced,
            is_explicit: true,
            is_implicit: false,
        }
    }

    /// Create an implicit deduction guide from constructors.
    pub fn implicit_from_constructor(
        class_name: &str,
        params: Vec<CXXParamDecl>,
        template_params: &[TemplateParamDecl],
    ) -> Self {
        let deduced: Vec<TemplateArgument> = template_params
            .iter()
            .map(|p| match p {
                TemplateParamDecl::TypeParm { name, .. } => {
                    TemplateArgument::Type(QualType::new(super::ast::TypeNode::Struct {
                        name: Some(name.clone()),
                        fields: vec![],
                        is_union: false,
                    }))
                }
                TemplateParamDecl::NonTypeParm { name, .. } => {
                    TemplateArgument::NonType(CXXExpr::CExpr(super::ast::Expr::Ident(name.clone())))
                }
                TemplateParamDecl::TemplateTemplateParm { name, .. } => {
                    TemplateArgument::Template(CXXName::new(name))
                }
            })
            .collect();
        Self {
            class_name: class_name.to_string(),
            params,
            deduced_template_args: deduced,
            is_explicit: false,
            is_implicit: true,
        }
    }
}

/// CTAD resolver: given constructor arguments, deduce class template args.
pub struct CtadResolver {
    /// Registered deduction guides (user-defined + implicit).
    guides: Vec<DeductionGuide>,
}

impl CtadResolver {
    pub fn new() -> Self {
        Self { guides: Vec::new() }
    }

    /// Register a deduction guide.
    pub fn add_guide(&mut self, guide: DeductionGuide) {
        self.guides.push(guide);
    }

    /// Deduce class template arguments from constructor call arguments.
    /// Returns a map of parameter names to deduced template arguments.
    pub fn deduce_class_template_args(
        &self,
        class_name: &str,
        arg_types: &[QualType],
    ) -> Result<HashMap<String, TemplateArgument>, String> {
        let mut best: Option<(usize, HashMap<String, TemplateArgument>)> = None;

        for guide in &self.guides {
            if guide.class_name != class_name {
                continue;
            }
            if guide.params.len() != arg_types.len() {
                continue;
            }

            let mut deductor = TemplateDeductor::new();
            let mut deduced = HashMap::new();
            let mut ok = true;

            for (pi, param) in guide.params.iter().enumerate() {
                let success = deductor.deduce_type(&param.ty, &arg_types[pi]);
                if success {
                    // Copy deduced args from the deductor's internal state
                    for (k, v) in &deductor.deduced {
                        deduced.insert(k.clone(), v.clone());
                    }
                } else {
                    ok = false;
                    break;
                }
            }

            if ok {
                let score = guide.conversion_cost(arg_types);
                if best.is_none() || score < best.as_ref().unwrap().0 {
                    best = Some((score, deduced));
                }
            }
        }

        best.map(|(_, args)| args)
            .ok_or_else(|| format!("CTAD failed for class '{}'", class_name))
    }
}

impl DeductionGuide {
    /// Estimate conversion cost for candidate matching (lower = better).
    fn conversion_cost(&self, arg_types: &[QualType]) -> usize {
        self.params
            .iter()
            .zip(arg_types.iter())
            .map(|(p, a)| if p.ty.base == a.base { 0 } else { 1 })
            .sum()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Auto Deduction (placeholder type deduction) — C++14/C++17/C++20
// ═══════════════════════════════════════════════════════════════════════════════

/// Kinds of auto deduction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutoDeductionKind {
    /// `auto` — strips references and top-level cv.
    Auto,
    /// `decltype(auto)` — preserves references and cv.
    DecltypeAuto,
    /// `auto&` / `auto&&` — reference binding.
    AutoRef,
}

/// Deduces the actual type of an `auto` placeholder.
pub fn deduce_auto(kind: AutoDeductionKind, from_ty: &QualType) -> QualType {
    match kind {
        AutoDeductionKind::Auto => {
            // Strip reference and top-level cv-qualifiers
            let mut ty = from_ty.clone();
            ty.is_const = false;
            ty.is_volatile = false;
            ty
        }
        AutoDeductionKind::DecltypeAuto => from_ty.clone(),
        AutoDeductionKind::AutoRef => {
            // Preserve reference semantics (strip only top-level cv optionally)
            from_ty.clone()
        }
    }
}

/// Deduce auto from a braced-init-list (yields std::initializer_list<T>).
pub fn deduce_auto_from_braced_init(element_ty: &QualType) -> QualType {
    // In actual Clang, this would produce std::initializer_list<element_ty>
    // We synthesise a named type for the initializer_list instantiation.
    QualType::new(super::ast::TypeNode::Struct {
        name: Some(format!("std::initializer_list<{}>", element_ty)),
        fields: vec![],
        is_union: false,
    })
}

// ═══════════════════════════════════════════════════════════════════════════════
// SFINAE Integration — Substitution Failure Is Not An Error
// ═══════════════════════════════════════════════════════════════════════════════

/// A SFINAE context tracks whether substitution failures are treated as
/// hard errors or simply remove the candidate from overload resolution.
#[derive(Debug, Clone)]
pub struct SfinaeContext {
    /// Whether SFINAE is currently active.
    pub is_active: bool,
    /// Number of active substitution attempts (for nested tracking).
    depth: usize,
    /// Soft errors collected during substitution.
    soft_errors: Vec<String>,
}

impl SfinaeContext {
    pub fn new() -> Self {
        Self {
            is_active: true,
            depth: 0,
            soft_errors: Vec::new(),
        }
    }

    /// Enter a SFINAE-enabled substitution context.
    pub fn enter_substitution(&mut self) -> SfinaeGuard {
        self.depth += 1;
        SfinaeGuard { active: true }
    }

    /// Record a soft (SFINAE) error.
    pub fn record_soft_error(&mut self, msg: &str) {
        if self.is_active {
            self.soft_errors.push(msg.to_string());
        }
    }

    /// Whether any soft errors have been recorded.
    pub fn has_soft_errors(&self) -> bool {
        !self.soft_errors.is_empty()
    }

    /// Consume and clear soft errors.
    pub fn take_soft_errors(&mut self) -> Vec<String> {
        std::mem::take(&mut self.soft_errors)
    }
}

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

/// RAII guard that exits SFINAE context on drop.
pub struct SfinaeGuard {
    active: bool,
}

impl Drop for SfinaeGuard {
    fn drop(&mut self) {
        // SFINAE guard cleanup
    }
}

/// Full overload resolution integration: attempt substitution for a template
/// candidate; if SFINAE triggers, the candidate is removed rather than
/// causing a compilation error.
pub fn try_template_substitution_for_overload(
    candidate_decl: &CXXDecl,
    call_args: &[QualType],
    sfinae: &mut SfinaeContext,
) -> Option<HashMap<String, TemplateArgument>> {
    let template_params = match candidate_decl {
        CXXDecl::Function {
            template_params: Some(ps),
            ..
        } => ps,
        CXXDecl::TemplateDeclaration { params, .. } => params,
        _ => return None,
    };

    let _guard = sfinae.enter_substitution();
    let mut deductor = TemplateDeductor::new();

    let result = deductor.deduce_function_template_args(template_params, call_args, &[]);

    if sfinae.has_soft_errors() {
        return None; // SFINAE removed this candidate
    }

    if result.success {
        Some(result.deduced_args)
    } else {
        sfinae.record_soft_error(&format!(
            "deduction failure: {}",
            result.failure_reason.unwrap_or_default()
        ));
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Dependent Name Resolution
// ═══════════════════════════════════════════════════════════════════════════════

/// Whether a name is dependent (depends on a template parameter).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameDependence {
    /// The name is not dependent.
    NonDependent,
    /// The name depends on a template type parameter.
    TypeDependent,
    /// The name depends on a template value parameter.
    ValueDependent,
    /// The name is dependent in both type and value senses.
    FullyDependent,
}

/// Resolver for dependent names within templates.
pub struct DependentNameResolver {
    /// Whether we are in a template context.
    in_template: bool,
    /// The active template parameters at this scope.
    active_template_params: Vec<String>,
}

impl DependentNameResolver {
    pub fn new(in_template: bool) -> Self {
        Self {
            in_template,
            active_template_params: Vec::new(),
        }
    }

    /// Set the active template parameters.
    pub fn set_template_params(&mut self, params: &[TemplateParamDecl]) {
        self.active_template_params = params
            .iter()
            .map(|p| match p {
                TemplateParamDecl::TypeParm { name, .. } => name.clone(),
                TemplateParamDecl::NonTypeParm { name, .. } => name.clone(),
                TemplateParamDecl::TemplateTemplateParm { name, .. } => name.clone(),
            })
            .collect();
    }

    /// Check whether a name is dependent.
    pub fn classify_dependence(&self, name: &str) -> NameDependence {
        if !self.in_template {
            return NameDependence::NonDependent;
        }
        if self.active_template_params.contains(&name.to_string()) {
            return NameDependence::TypeDependent;
        }
        // Check if any parameter appears as a substring (approximate)
        for param in &self.active_template_params {
            if name.contains(param.as_str()) {
                return NameDependence::TypeDependent;
            }
        }
        NameDependence::NonDependent
    }

    /// Whether the `typename` keyword is required for disambiguation.
    pub fn needs_typename_keyword(&self, qualifier: &NestedNameSpecifier) -> bool {
        // `typename` is needed when a qualified name depends on a template
        // parameter and refers to a type.
        self.in_template
            && qualifier
                .components
                .iter()
                .any(|c| matches!(c, NestedNameComponent::Template(_)))
    }

    /// Whether the `template` keyword is required for disambiguation.
    pub fn needs_template_keyword(&self, qualifier: &NestedNameSpecifier, member: &str) -> bool {
        // `template` is needed when: a dependent qualified name is followed
        // by `<` but refers to a template member.
        self.in_template
            && qualifier
                .components
                .iter()
                .any(|c| matches!(c, NestedNameComponent::Type(_)))
            && !member.is_empty()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Two-Phase Name Lookup
// ═══════════════════════════════════════════════════════════════════════════════

/// Phase of two-phase lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LookupPhase {
    /// Phase 1: at template definition time — non-dependent names resolved.
    Phase1,
    /// Phase 2: at template instantiation time — dependent names resolved.
    Phase2,
}

/// Tracks the current phase of two-phase name lookup.
pub struct TwoPhaseLookup {
    /// The current lookup phase.
    pub phase: LookupPhase,
    /// Names resolved in phase 1 (non-dependent).
    phase1_resolved: HashMap<String, CXXDecl>,
    /// Names deferred to phase 2 (dependent).
    deferred_names: Vec<DependentName>,
}

/// A name whose resolution was deferred from phase 1 to phase 2.
#[derive(Debug, Clone)]
pub struct DependentName {
    /// The dependent name expression.
    pub name: String,
    /// The qualifier scope.
    pub scope: Option<NestedNameSpecifier>,
    /// The source location.
    pub source_loc: usize,
}

impl TwoPhaseLookup {
    pub fn new() -> Self {
        Self {
            phase: LookupPhase::Phase1,
            phase1_resolved: HashMap::new(),
            deferred_names: Vec::new(),
        }
    }

    /// Switch to phase 2 lookup.
    pub fn enter_phase2(&mut self) {
        self.phase = LookupPhase::Phase2;
    }

    /// Look up a name. In phase 1, non-dependent names are resolved immediately;
    /// dependent names are deferred. In phase 2, dependent names are resolved
    /// using the instantiation context.
    pub fn lookup(&mut self, name: &str, resolver: &DependentNameResolver) -> NameLookupResult {
        match self.phase {
            LookupPhase::Phase1 => {
                let dep = resolver.classify_dependence(name);
                match dep {
                    NameDependence::NonDependent => {
                        // Resolve immediately
                        if let Some(decl) = self.phase1_resolved.get(name) {
                            NameLookupResult::Found(decl.clone())
                        } else {
                            NameLookupResult::NotFound
                        }
                    }
                    _ => {
                        // Defer to phase 2
                        self.deferred_names.push(DependentName {
                            name: name.to_string(),
                            scope: None,
                            source_loc: 0,
                        });
                        NameLookupResult::Deferred
                    }
                }
            }
            LookupPhase::Phase2 => {
                // In phase 2, perform actual lookup with instantiation args
                if let Some(decl) = self.phase1_resolved.get(name) {
                    NameLookupResult::Found(decl.clone())
                } else {
                    NameLookupResult::NotFound
                }
            }
        }
    }

    /// Register a non-dependent name resolved in phase 1.
    pub fn register_phase1(&mut self, name: &str, decl: CXXDecl) {
        self.phase1_resolved.insert(name.to_string(), decl);
    }

    /// Get all names deferred to phase 2.
    pub fn deferred_names(&self) -> &[DependentName] {
        &self.deferred_names
    }
}

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

/// Result of a two-phase name lookup.
#[derive(Debug, Clone)]
pub enum NameLookupResult {
    /// The name was resolved to a declaration.
    Found(CXXDecl),
    /// The name was not found.
    NotFound,
    /// Resolution of this name is deferred to phase 2.
    Deferred,
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Instantiation Depth Tracking (`-ftemplate-depth=N`)
// ═══════════════════════════════════════════════════════════════════════════════

/// Manages template instantiation depth with configurable limits.
pub struct TemplateDepthTracker {
    /// Current instantiation depth.
    current_depth: usize,
    /// Maximum allowed depth (default 1024).
    max_depth: usize,
    /// The instantiation backtrace for diagnostics.
    backtrace: Vec<InstantiationRecord>,
}

/// A record of one level of template instantiation.
#[derive(Debug, Clone)]
pub struct InstantiationRecord {
    /// The template being instantiated.
    pub template_name: String,
    /// The arguments used for this instantiation.
    pub args: Vec<TemplateArgument>,
    /// Source location (line number).
    pub source_loc: usize,
}

impl TemplateDepthTracker {
    /// Create a depth tracker with the default limit of 1024.
    pub fn new() -> Self {
        Self {
            current_depth: 0,
            max_depth: 1024,
            backtrace: Vec::new(),
        }
    }

    /// Create a depth tracker with a custom limit.
    pub fn with_max_depth(max_depth: usize) -> Self {
        Self {
            current_depth: 0,
            max_depth,
            backtrace: Vec::new(),
        }
    }

    /// Enter a new instantiation level. Returns `Err` if max depth exceeded.
    pub fn enter_instantiation(
        &mut self,
        name: &str,
        args: &[TemplateArgument],
    ) -> Result<(), String> {
        if self.current_depth >= self.max_depth {
            return Err(format!(
                "template instantiation depth exceeds maximum of {} (use -ftemplate-depth=N to increase)",
                self.max_depth
            ));
        }
        self.current_depth += 1;
        self.backtrace.push(InstantiationRecord {
            template_name: name.to_string(),
            args: args.to_vec(),
            source_loc: self.current_depth, // proxy for line
        });
        Ok(())
    }

    /// Leave the current instantiation level.
    pub fn leave_instantiation(&mut self) {
        if self.current_depth > 0 {
            self.current_depth -= 1;
            self.backtrace.pop();
        }
    }

    /// The current instantiation depth.
    pub fn depth(&self) -> usize {
        self.current_depth
    }

    /// The maximum allowed depth.
    pub fn max_depth(&self) -> usize {
        self.max_depth
    }

    /// Get a diagnostic backtrace.
    pub fn backtrace_string(&self) -> String {
        self.backtrace
            .iter()
            .enumerate()
            .map(|(i, rec)| {
                format!(
                    "  #{}: in instantiation of '{}' with args [{}]",
                    i,
                    rec.template_name,
                    rec.args
                        .iter()
                        .map(|a| format!("{}", a))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Variadic Template Expansion (Parameter Packs) — C++11
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a parameter pack expansion pattern.
#[derive(Debug, Clone)]
pub struct PackExpansion {
    /// The pattern to expand (e.g., `args` in `args...`).
    pub pattern: String,
    /// The pack parameter name.
    pub pack_name: String,
    /// Whether this is a type pack or expression pack.
    pub kind: PackKind,
    /// The expansion locus: where in the AST this expansion occurs.
    pub expansion_locus: PackExpansionLocus,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackKind {
    /// `typename... Args` — type parameter pack.
    TypePack,
    /// `int... Is` — non-type parameter pack.
    NonTypePack,
    /// `template... Ts` — template template parameter pack.
    TemplatePack,
    /// `sizeof...(Args)` — pack size query.
    PackSize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PackExpansionLocus {
    /// `Args...` in a type list.
    TemplateArgumentList,
    /// `f(args)...` in a function call.
    FunctionCall,
    /// Base class `Base<Args>...`.
    BaseSpecifier,
    /// Member initializer `m(args)...`.
    MemberInitializer,
    /// `capture...` in lambda capture.
    LambdaCapture,
}

impl PackExpansion {
    pub fn new(pack_name: &str, pattern: &str, kind: PackKind, locus: PackExpansionLocus) -> Self {
        Self {
            pattern: pattern.to_string(),
            pack_name: pack_name.to_string(),
            kind,
            expansion_locus: locus,
        }
    }

    /// Expand a type pack into a list of types.
    pub fn expand_type_pack(args: &[TemplateArgument]) -> Vec<TemplateArgument> {
        args.to_vec()
    }

    /// Expand a non-type pack into a list of non-type arguments.
    pub fn expand_nontype_pack(args: &[CXXExpr]) -> Vec<CXXExpr> {
        args.to_vec()
    }

    /// Check if the pack expansion is valid in the given context.
    pub fn is_valid_in_context(&self, locus: PackExpansionLocus) -> bool {
        self.expansion_locus == locus
    }

    /// The number of elements in the expanded pack.
    pub fn expanded_size(&self, args: &[TemplateArgument]) -> usize {
        args.len()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Fold Expressions — C++17
// ═══════════════════════════════════════════════════════════════════════════════

/// A C++17 fold expression over a parameter pack.
#[derive(Debug, Clone)]
pub struct FoldExpression {
    /// The operator used in the fold.
    pub operator: CXXOperator,
    /// Whether this is a left fold `(... op pack)` or right fold `(pack op ...)`.
    pub is_left_fold: bool,
    /// Whether this is a unary fold (no init) or binary fold (with init).
    pub is_unary: bool,
    /// The init expression for binary folds.
    pub init: Option<Box<CXXExpr>>,
    /// The pack being folded over.
    pub pack_name: String,
}

impl FoldExpression {
    /// Create a unary left fold: `(... + args)`
    pub fn unary_left(op: CXXOperator, pack: &str) -> Self {
        Self {
            operator: op,
            is_left_fold: true,
            is_unary: true,
            init: None,
            pack_name: pack.to_string(),
        }
    }

    /// Create a unary right fold: `(args + ...)`
    pub fn unary_right(op: CXXOperator, pack: &str) -> Self {
        Self {
            operator: op,
            is_left_fold: false,
            is_unary: true,
            init: None,
            pack_name: pack.to_string(),
        }
    }

    /// Create a binary left fold: `(init + ... + args)`
    pub fn binary_left(op: CXXOperator, pack: &str, init: CXXExpr) -> Self {
        Self {
            operator: op,
            is_left_fold: true,
            is_unary: false,
            init: Some(Box::new(init)),
            pack_name: pack.to_string(),
        }
    }

    /// Create a binary right fold: `(args + ... + init)`
    pub fn binary_right(op: CXXOperator, pack: &str, init: CXXExpr) -> Self {
        Self {
            operator: op,
            is_left_fold: false,
            is_unary: false,
            init: Some(Box::new(init)),
            pack_name: pack.to_string(),
        }
    }

    /// Get the associativity of this fold expression.
    pub fn associativity(&self) -> &'static str {
        if self.is_left_fold {
            "left-associative"
        } else {
            "right-associative"
        }
    }

    /// Returns the identity element for this operator (for empty packs).
    pub fn identity_value(&self) -> Option<&'static str> {
        match self.operator {
            CXXOperator::Add => Some("0"),
            CXXOperator::Mul => Some("1"),
            CXXOperator::BitAnd => Some("-1"),
            CXXOperator::BitOr => Some("0"),
            CXXOperator::BitXor => Some("0"),
            CXXOperator::LogicalAnd => Some("true"),
            CXXOperator::LogicalOr => Some("false"),
            CXXOperator::Comma => Some("void()"),
            _ => None,
        }
    }

    /// Check if this operator supports fold expressions.
    pub fn is_foldable_operator(op: CXXOperator) -> bool {
        matches!(
            op,
            CXXOperator::Add
                | CXXOperator::Sub
                | CXXOperator::Mul
                | CXXOperator::Div
                | CXXOperator::Mod
                | CXXOperator::BitAnd
                | CXXOperator::BitOr
                | CXXOperator::BitXor
                | CXXOperator::Shl
                | CXXOperator::Shr
                | CXXOperator::Assign
                | CXXOperator::AddAssign
                | CXXOperator::SubAssign
                | CXXOperator::MulAssign
                | CXXOperator::DivAssign
                | CXXOperator::ModAssign
                | CXXOperator::AndAssign
                | CXXOperator::OrAssign
                | CXXOperator::XorAssign
                | CXXOperator::ShlAssign
                | CXXOperator::ShrAssign
                | CXXOperator::Eq
                | CXXOperator::Ne
                | CXXOperator::Lt
                | CXXOperator::Gt
                | CXXOperator::Le
                | CXXOperator::Ge
                | CXXOperator::Spaceship
                | CXXOperator::LogicalAnd
                | CXXOperator::LogicalOr
                | CXXOperator::Comma
                | CXXOperator::ArrowStar
        )
    }

    /// Generate the unfolded representation for a given pack size.
    pub fn unfold(&self, elements: &[&str]) -> String {
        if elements.is_empty() {
            return self
                .identity_value()
                .unwrap_or("/* empty fold */")
                .to_string();
        }

        let op_str = match self.operator {
            CXXOperator::Add => "+",
            CXXOperator::Sub => "-",
            CXXOperator::Mul => "*",
            CXXOperator::Div => "/",
            CXXOperator::Mod => "%",
            CXXOperator::BitAnd => "&",
            CXXOperator::BitOr => "|",
            CXXOperator::BitXor => "^",
            CXXOperator::Shl => "<<",
            CXXOperator::Shr => ">>",
            CXXOperator::Eq => "==",
            CXXOperator::Ne => "!=",
            CXXOperator::Lt => "<",
            CXXOperator::Gt => ">",
            CXXOperator::Le => "<=",
            CXXOperator::Ge => ">=",
            CXXOperator::LogicalAnd => "&&",
            CXXOperator::LogicalOr => "||",
            CXXOperator::Comma => ",",
            CXXOperator::Spaceship => "<=>",
            _ => "?",
        };

        if self.is_unary {
            elements.join(&format!(" {} ", op_str))
        } else if self.is_left_fold {
            let init_str = self
                .init
                .as_ref()
                .map(|i| format!("{}", i))
                .unwrap_or_default();
            format!(
                "({} {} {})",
                init_str,
                op_str,
                elements.join(&format!(" {} ", op_str))
            )
        } else {
            let init_str = self
                .init
                .as_ref()
                .map(|i| format!("{}", i))
                .unwrap_or_default();
            format!(
                "({} {} {})",
                elements.join(&format!(" {} ", op_str)),
                op_str,
                init_str
            )
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Non-Type Template Parameters — C++17/C++20 Extensions
// ═══════════════════════════════════════════════════════════════════════════════

/// Enhanced non-type template parameter with C++20 class-type support.
#[derive(Debug, Clone)]
pub struct NonTypeTemplateArg {
    /// The value representation.
    pub value: String,
    /// The type of the non-type parameter.
    pub ty: QualType,
    /// Whether this uses `auto` (C++17 placeholder).
    pub is_auto: bool,
    /// Whether this is a class-type NTTP (C++20).
    pub is_class_type: bool,
    /// Structural comparison fields for class-type NTTP.
    pub structural_fields: Vec<String>,
}

impl NonTypeTemplateArg {
    /// Create a simple integral NTTP value.
    pub fn integral(value: &str, ty: &QualType) -> Self {
        Self {
            value: value.to_string(),
            ty: ty.clone(),
            is_auto: false,
            is_class_type: false,
            structural_fields: Vec::new(),
        }
    }

    /// Create an auto-deduced NTTP (C++17).
    pub fn auto_deduced(value: &str, deduced_ty: &QualType) -> Self {
        Self {
            value: value.to_string(),
            ty: deduced_ty.clone(),
            is_auto: true,
            is_class_type: false,
            structural_fields: Vec::new(),
        }
    }

    /// Create a class-type NTTP with structural fields (C++20).
    pub fn class_type(value: &str, ty: &QualType, structural_fields: Vec<String>) -> Self {
        Self {
            value: value.to_string(),
            ty: ty.clone(),
            is_auto: false,
            is_class_type: true,
            structural_fields,
        }
    }

    /// Convert to a TemplateArgument.
    pub fn to_template_arg(&self) -> TemplateArgument {
        TemplateArgument::NonType(CXXExpr::CExpr(super::ast::Expr::Ident(self.value.clone())))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Template Parameters with Default Arguments
// ═══════════════════════════════════════════════════════════════════════════════

/// A template template parameter with optional default.
#[derive(Debug, Clone)]
pub struct TemplateTemplateParam {
    /// The parameter name.
    pub name: String,
    /// The template parameter list of this template template param.
    pub params: Vec<TemplateParamDecl>,
    /// The default template argument (optional).
    pub default_template: Option<CXXName>,
    /// Whether this is a parameter pack.
    pub is_parameter_pack: bool,
    /// Requires clause (C++20).
    pub requires_clause: Option<Box<CXXExpr>>,
}

impl TemplateTemplateParam {
    pub fn new(name: &str, params: Vec<TemplateParamDecl>) -> Self {
        Self {
            name: name.to_string(),
            params,
            default_template: None,
            is_parameter_pack: false,
            requires_clause: None,
        }
    }

    pub fn with_default(mut self, default: CXXName) -> Self {
        self.default_template = Some(default);
        self
    }

    pub fn pack(mut self) -> Self {
        self.is_parameter_pack = true;
        self
    }

    pub fn with_requires(mut self, expr: CXXExpr) -> Self {
        self.requires_clause = Some(Box::new(expr));
        self
    }

    /// Check if this template template parameter matches a given template argument.
    pub fn matches_arg(&self, arg: &TemplateArgument) -> bool {
        // A template template parameter accepts template arguments
        matches!(arg, TemplateArgument::Template(_))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Requires-Clause and Requires-Expression — C++20 Concepts
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluation of a requires-clause attached to a template.
pub struct RequiresClauseEvaluator {
    /// The template parameters in scope.
    pub params: Vec<TemplateParamDecl>,
    /// Bound arguments for this evaluation.
    pub args: HashMap<String, TemplateArgument>,
}

impl RequiresClauseEvaluator {
    pub fn new(params: &[TemplateParamDecl]) -> Self {
        Self {
            params: params.to_vec(),
            args: HashMap::new(),
        }
    }

    /// Bind a template argument to a parameter name.
    pub fn bind(&mut self, param_name: &str, arg: TemplateArgument) {
        self.args.insert(param_name.to_string(), arg);
    }

    /// Evaluate a requires-clause expression to determine satisfaction.
    pub fn evaluate(&self, expr: &CXXExpr) -> RequiresResult {
        match expr {
            CXXExpr::RequiresExpr {
                params: req_params,
                requirements,
            } => self.evaluate_requires_expression(req_params, requirements),
            CXXExpr::TypeidExpr { .. } => RequiresResult::Satisfied,
            _ => {
                // Simple constraint: check if the expression is well-formed
                // with the current bindings.
                if self.is_expression_valid(expr) {
                    RequiresResult::Satisfied
                } else {
                    RequiresResult::NotSatisfied(
                        "constraint expression is not satisfied".to_string(),
                    )
                }
            }
        }
    }

    /// Evaluate a requires-expression: `requires (params) { reqs... }`.
    fn evaluate_requires_expression(
        &self,
        _req_params: &[CXXParamDecl],
        requirements: &[Requirement],
    ) -> RequiresResult {
        for req in requirements {
            let result = self.check_requirement(req);
            if !result.is_satisfied() {
                return result;
            }
        }
        RequiresResult::Satisfied
    }

    /// Check a single requirement.
    fn check_requirement(&self, req: &Requirement) -> RequiresResult {
        match req {
            Requirement::Simple(expr) => {
                if self.is_expression_valid(expr) {
                    RequiresResult::Satisfied
                } else {
                    RequiresResult::NotSatisfied(format!("requirement '{}' is not satisfied", expr))
                }
            }
            Requirement::Type { name } => {
                // Check if the type exists with current bindings
                if self.args.contains_key(name.as_str())
                    || self.params.iter().any(|p| match p {
                        TemplateParamDecl::TypeParm { name: n, .. } => n == name,
                        _ => false,
                    })
                {
                    RequiresResult::Satisfied
                } else {
                    RequiresResult::NotSatisfied(format!(
                        "type '{}' is not valid in this context",
                        name
                    ))
                }
            }
            Requirement::Compound {
                expr,
                is_noexcept,
                return_type_concept,
            } => {
                if !self.is_expression_valid(expr) {
                    return RequiresResult::NotSatisfied(format!(
                        "compound requirement '{}' is not satisfied",
                        expr
                    ));
                }
                if *is_noexcept {
                    // Simplified check: assume noexcept is satisfied
                }
                if return_type_concept.is_some() {
                    // Simplified: assume concept check succeeds
                }
                RequiresResult::Satisfied
            }
            Requirement::Nested(inner) => self.evaluate(inner),
        }
    }

    /// Check if an expression is well-formed with current bindings.
    fn is_expression_valid(&self, _expr: &CXXExpr) -> bool {
        // In a real implementation, this would perform semantic analysis
        // with the bound template arguments.
        !self.args.is_empty() || self.params.is_empty()
    }
}

/// Result of evaluating a requires clause/expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequiresResult {
    Satisfied,
    NotSatisfied(String),
    Dependent,
}

impl RequiresResult {
    pub fn is_satisfied(&self) -> bool {
        matches!(self, RequiresResult::Satisfied)
    }

    pub fn is_not_satisfied(&self) -> bool {
        matches!(self, RequiresResult::NotSatisfied(_))
    }

    pub fn failure_reason(&self) -> Option<&str> {
        match self {
            RequiresResult::NotSatisfied(reason) => Some(reason),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TemplateName, TemplateArgument, TemplateParameterList Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a template name (what follows the `template` keyword).
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateName {
    /// The base name of the template.
    pub name: CXXName,
    /// Whether this is a dependent template name.
    pub is_dependent: bool,
    /// Whether this is a builtin template.
    pub is_builtin: bool,
}

impl TemplateName {
    pub fn new(name: &str) -> Self {
        Self {
            name: CXXName::new(name),
            is_dependent: false,
            is_builtin: false,
        }
    }

    pub fn dependent(name: &str) -> Self {
        Self {
            name: CXXName::new(name),
            is_dependent: true,
            is_builtin: false,
        }
    }

    pub fn builtin(name: &str) -> Self {
        Self {
            name: CXXName::new(name),
            is_dependent: false,
            is_builtin: true,
        }
    }
}

impl fmt::Display for TemplateName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)
    }
}

/// A template parameter list: the `<T, U = int, ...>` after a template name.
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateParameterList {
    /// The template parameters.
    pub params: Vec<TemplateParamDecl>,
    /// Optional requires clause (C++20).
    pub requires_clause: Option<Box<CXXExpr>>,
    /// Source location.
    pub source_loc: usize,
}

impl TemplateParameterList {
    pub fn new(params: Vec<TemplateParamDecl>) -> Self {
        Self {
            params,
            requires_clause: None,
            source_loc: 0,
        }
    }

    pub fn with_requires(mut self, expr: CXXExpr) -> Self {
        self.requires_clause = Some(Box::new(expr));
        self
    }

    pub fn at_location(mut self, loc: usize) -> Self {
        self.source_loc = loc;
        self
    }

    /// Check if this parameter list contains a parameter pack.
    pub fn has_parameter_pack(&self) -> bool {
        self.params.iter().any(|p| match p {
            TemplateParamDecl::TypeParm {
                is_parameter_pack, ..
            } => *is_parameter_pack,
            TemplateParamDecl::NonTypeParm {
                is_parameter_pack, ..
            } => *is_parameter_pack,
            TemplateParamDecl::TemplateTemplateParm {
                is_parameter_pack, ..
            } => *is_parameter_pack,
        })
    }

    /// Count actual parameters (excluding parameter packs for overload purposes).
    pub fn parameter_count(&self) -> usize {
        self.params.len()
    }

    /// Extract the names of all template parameters.
    pub fn parameter_names(&self) -> Vec<String> {
        self.params
            .iter()
            .map(|p| match p {
                TemplateParamDecl::TypeParm { name, .. } => name.clone(),
                TemplateParamDecl::NonTypeParm { name, .. } => name.clone(),
                TemplateParamDecl::TemplateTemplateParm { name, .. } => name.clone(),
            })
            .collect()
    }

    /// Whether any parameter has a default argument.
    pub fn has_default_args(&self) -> bool {
        self.params.iter().any(|p| match p {
            TemplateParamDecl::TypeParm { default_ty, .. } => default_ty.is_some(),
            TemplateParamDecl::NonTypeParm { default_value, .. } => default_value.is_some(),
            TemplateParamDecl::TemplateTemplateParm {
                default_template, ..
            } => default_template.is_some(),
        })
    }

    /// Get the default arguments for trailing parameters.
    pub fn default_args(&self) -> Vec<Option<TemplateArgument>> {
        self.params
            .iter()
            .map(|p| match p {
                TemplateParamDecl::TypeParm {
                    default_ty: Some(ty),
                    ..
                } => Some(TemplateArgument::Type(ty.clone())),
                TemplateParamDecl::NonTypeParm {
                    default_value: Some(v),
                    ..
                } => Some(TemplateArgument::NonType(*v.clone())),
                TemplateParamDecl::TemplateTemplateParm {
                    default_template: Some(t),
                    ..
                } => Some(TemplateArgument::Template(t.clone())),
                _ => None,
            })
            .collect()
    }
}

impl fmt::Display for TemplateParameterList {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<")?;
        for (i, p) in self.params.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{}", p)?;
        }
        write!(f, ">")?;
        if let Some(ref req) = self.requires_clause {
            write!(f, " requires {}", req)?;
        }
        Ok(())
    }
}

/// Helper: Check if a TemplateArgument matches the kind expected by a TemplateParamDecl.
pub fn template_arg_matches_param_kind(arg: &TemplateArgument, param: &TemplateParamDecl) -> bool {
    match (arg, param) {
        (TemplateArgument::Type(_), TemplateParamDecl::TypeParm { .. }) => true,
        (TemplateArgument::NonType(_), TemplateParamDecl::NonTypeParm { .. }) => true,
        (TemplateArgument::Template(_), TemplateParamDecl::TemplateTemplateParm { .. }) => true,
        _ => false,
    }
}

/// Order template arguments to match a parameter list, using defaults if needed.
pub fn arrange_template_args(
    params: &[TemplateParamDecl],
    explicit_args: &[TemplateArgument],
) -> Result<Vec<TemplateArgument>, String> {
    let mut result = Vec::new();

    if explicit_args.len() > params.len() {
        return Err(format!(
            "too many template arguments (expected {}, got {})",
            params.len(),
            explicit_args.len()
        ));
    }

    for (i, param) in params.iter().enumerate() {
        if i < explicit_args.len() {
            let arg = &explicit_args[i];
            if !template_arg_matches_param_kind(arg, param) {
                return Err(format!(
                    "template argument {} does not match parameter kind",
                    i
                ));
            }
            result.push(arg.clone());
        } else {
            // Try to use default argument
            let default: Option<TemplateArgument> = match param {
                TemplateParamDecl::TypeParm {
                    default_ty: Some(ty),
                    ..
                } => Some(TemplateArgument::Type(ty.clone())),
                TemplateParamDecl::NonTypeParm {
                    default_value: Some(v),
                    ..
                } => Some(TemplateArgument::NonType(*v.clone())),
                TemplateParamDecl::TemplateTemplateParm {
                    default_template: Some(t),
                    ..
                } => Some(TemplateArgument::Template(t.clone())),
                _ => None,
            };
            match default {
                Some(d) => result.push(d),
                None => {
                    return Err(format!(
                        "no default argument for template parameter '{}'",
                        match param {
                            TemplateParamDecl::TypeParm { name, .. } => name,
                            TemplateParamDecl::NonTypeParm { name, .. } => name,
                            TemplateParamDecl::TemplateTemplateParm { name, .. } => name,
                        }
                    ));
                }
            }
        }
    }

    Ok(result)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Specialization Ordering
// ═══════════════════════════════════════════════════════════════════════════════

/// Order two template specializations to determine which is more specialized.
/// Returns `Some(true)` if `spec1` is more specialized, `Some(false)` if `spec2`
/// is more specialized, or `None` if they are unordered.
pub fn is_more_specialized(
    spec1_params: &[TemplateParamDecl],
    spec2_params: &[TemplateParamDecl],
) -> Option<bool> {
    // Two-phase ordering according to C++ standard §13.7.7.2:
    // 1. Try to deduce spec2 from spec1.
    // 2. Try to deduce spec1 from spec2.
    // If exactly one succeeds, that one is more specialized.
    let spec1_deduces_spec2 = try_ordering_deduction(spec1_params, spec2_params);
    let spec2_deduces_spec1 = try_ordering_deduction(spec2_params, spec1_params);

    match (spec1_deduces_spec2, spec2_deduces_spec1) {
        (true, false) => Some(true),  // spec1 is more specialized
        (false, true) => Some(false), // spec2 is more specialized
        _ => None,                    // unordered or ambiguous
    }
}

fn try_ordering_deduction(
    from_params: &[TemplateParamDecl],
    to_params: &[TemplateParamDecl],
) -> bool {
    // Create synthetic types for each parameter in `to_params` and try to
    // deduce them from the corresponding parameter in `from_params`.
    if from_params.len() != to_params.len() {
        return false;
    }
    let _deductor = TemplateDeductor::new();
    let mut synthetic_from: HashMap<String, QualType> = HashMap::new();

    for (i, _) in to_params.iter().enumerate() {
        let syn_ty = QualType::new(super::ast::TypeNode::Struct {
            name: Some(format!("_Syn{}", i)),
            fields: vec![],
            is_union: false,
        });
        synthetic_from.insert(format!("_Syn{}", i), syn_ty.clone());
    }

    // Simplified: assume ordering deduction succeeds if param counts match.
    true
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Static Data Member Instantiation
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles instantiation of static data members of class templates.
#[derive(Debug, Clone)]
pub struct StaticDataMemberInstantiation {
    /// The class template name.
    pub class_name: String,
    /// The static member name.
    pub member_name: String,
    /// The member type.
    pub member_type: String,
    /// Whether this instance has been explicitly instantiated.
    pub is_explicit_instantiation: bool,
    /// The guard variable for thread-safe initialization.
    pub guard_variable: Option<String>,
}

impl StaticDataMemberInstantiation {
    pub fn new(class_name: &str, member_name: &str) -> Self {
        Self {
            class_name: class_name.to_string(),
            member_name: member_name.to_string(),
            member_type: "int".to_string(),
            is_explicit_instantiation: false,
            guard_variable: None,
        }
    }

    /// Generate the instantiation definition.
    pub fn gen_definition(&self, template_args: &[TemplateArgument]) -> String {
        let args_str: Vec<String> = template_args.iter().map(|a| format!("{}", a)).collect();
        format!(
            "template {} {}::{};\n",
            self.member_type, self.class_name, self.member_name
        )
    }

    /// Check if this member needs an explicit instantiation definition.
    pub fn needs_explicit_instantiation(&self, is_odr_used: bool) -> bool {
        is_odr_used && !self.is_explicit_instantiation
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Friend Declaration Instantiation
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles friend declarations in class templates.
#[derive(Debug, Clone)]
pub struct FriendTemplateInstantiation {
    /// The befriending class.
    pub befriending_class: String,
    /// The friend function or class name.
    pub friend_name: String,
    /// Whether the friend is a function template.
    pub is_template: bool,
    /// The template arguments for the friend (if template).
    pub friend_template_args: Vec<TemplateArgument>,
}

impl FriendTemplateInstantiation {
    pub fn new(befriending: &str, friend: &str) -> Self {
        Self {
            befriending_class: befriending.to_string(),
            friend_name: friend.to_string(),
            is_template: false,
            friend_template_args: Vec::new(),
        }
    }

    /// Check if a function is a valid friend per the template's friend declaration.
    pub fn is_valid_friend(&self, candidate: &CXXDecl) -> bool {
        match candidate {
            CXXDecl::Function {
                name,
                template_params,
                ..
            } => {
                if *name == self.friend_name {
                    if self.is_template {
                        template_params.is_some()
                    } else {
                        true
                    }
                } else {
                    false
                }
            }
            CXXDecl::TemplateDeclaration { decl, .. } => self.is_valid_friend(decl),
            _ => false,
        }
    }

    /// Instantiate the friend declaration with the given template arguments.
    pub fn instantiate_friend(&self, args: &[TemplateArgument]) -> Option<CXXDecl> {
        if args.is_empty() && self.is_template {
            return None;
        }
        Some(CXXDecl::FriendDeclaration(Box::new(CXXDecl::Function {
            name: self.friend_name.clone(),
            return_ty: QualType::new(super::ast::TypeNode::Void),
            params: vec![],
            body: None,
            is_virtual: false,
            is_override: false,
            is_final: false,
            is_const: false,
            is_noexcept: false,
            is_constexpr: false,
            is_consteval: false,
            is_static: false,
            is_inline: true,
            is_explicit: false,
            is_deleted: false,
            is_defaulted: false,
            ref_qualifier: None,
            trailing_return_ty: None,
            template_params: None,
            is_volatile: false,
            linkage: String::new(),
            init_list: vec![],
        })))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template Alias Expansion
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles expansion of alias templates (C++11 `using` aliases with template params).
#[derive(Debug, Clone)]
pub struct AliasTemplateExpander {
    /// The alias name.
    pub alias_name: String,
    /// The alias template parameters.
    pub params: Vec<TemplateParamDecl>,
    /// The underlying aliased type.
    pub aliased_type: QualType,
    /// Whether this alias is dependent.
    pub is_dependent: bool,
}

impl AliasTemplateExpander {
    pub fn new(name: &str, params: Vec<TemplateParamDecl>, aliased: QualType) -> Self {
        let is_dependent = !params.is_empty();
        Self {
            alias_name: name.to_string(),
            params,
            aliased_type: aliased,
            is_dependent,
        }
    }

    /// Expand the alias with given template arguments.
    pub fn expand(&self, args: &[TemplateArgument]) -> Result<QualType, String> {
        if args.len() != self.params.len() {
            return Err(format!(
                "alias template '{}' expects {} arguments, got {}",
                self.alias_name,
                self.params.len(),
                args.len()
            ));
        }

        // In a full implementation, this would substitute args into the aliased type
        // For now, return a synthetic type representing the expansion
        let args_str: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
        Ok(QualType::new(super::ast::TypeNode::Struct {
            name: Some(format!("{}<{}>", self.alias_name, args_str.join(","))),
            fields: vec![],
            is_union: false,
        }))
    }

    /// Check if this alias is a type alias or more complex.
    pub fn is_simple_alias(&self) -> bool {
        self.params.is_empty()
    }

    /// Get the number of template parameters.
    pub fn param_count(&self) -> usize {
        self.params.len()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Template ODR Merging
// ═══════════════════════════════════════════════════════════════════════════════

/// Handles ODR (One Definition Rule) for template instantiations.
/// Multiple translation units may instantiate the same template with the
/// same arguments — the linker must merge them.
#[derive(Debug, Clone)]
pub struct TemplateOdrMerger {
    /// Map of mangled name → instantiation status.
    pub instantiated: HashMap<String, bool>,
    /// Whether to emit linkonce_odr linkage.
    pub use_linkonce_odr: bool,
}

impl TemplateOdrMerger {
    pub fn new() -> Self {
        Self {
            instantiated: HashMap::new(),
            use_linkonce_odr: true,
        }
    }

    /// Check if a template instantiation has been seen before.
    pub fn is_duplicate(&self, mangled_name: &str) -> bool {
        self.instantiated.contains_key(mangled_name)
    }

    /// Register a template instantiation.
    pub fn register_instantiation(&mut self, mangled_name: &str) {
        self.instantiated.insert(mangled_name.to_string(), true);
    }

    /// Generate the appropriate linkage string for a template instantiation.
    pub fn linkage_string(&self) -> &'static str {
        if self.use_linkonce_odr {
            "linkonce_odr"
        } else {
            "weak_odr"
        }
    }

    /// Generate IR with appropriate linkage for ODR safety.
    pub fn gen_odr_safe_definition(&self, mangled_name: &str, body_ir: &str) -> String {
        format!(
            "define {} void @{}() {{\n{}}}\n",
            self.linkage_string(),
            mangled_name,
            body_ir
        )
    }

    /// Check if this instantiation can be COMDAT-folded.
    pub fn can_comdat_fold(&self, mangled_name: &str) -> bool {
        self.instantiated.contains_key(mangled_name)
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// Template Argument Canonicalization
// ═══════════════════════════════════════════════════════════════════════════════

/// Canonicalizes template arguments for comparison and caching.
/// Two different representations of the same template argument should
/// be canonicalized to the same form.
#[derive(Debug, Clone)]
pub struct TemplateArgCanonicalizer {
    /// Whether to strip typedefs from type arguments.
    pub strip_typedefs: bool,
    /// Whether to normalize non-type arguments.
    pub normalize_nontype: bool,
}

impl TemplateArgCanonicalizer {
    pub fn new() -> Self {
        Self {
            strip_typedefs: true,
            normalize_nontype: true,
        }
    }

    /// Canonicalize a type template argument.
    pub fn canonicalize_type(&self, ty: &QualType) -> QualType {
        if self.strip_typedefs {
            // Strip typedefs — follow the chain to the underlying type
            match &*ty.base {
                super::ast::TypeNode::Typedef { underlying, .. } => {
                    return self.canonicalize_type(underlying);
                }
                _ => {}
            }
        }
        ty.clone()
    }

    /// Canonicalize a non-type template argument.
    pub fn canonicalize_nontype(&self, expr: &CXXExpr) -> CXXExpr {
        if self.normalize_nontype {
            // Evaluate constant expressions where possible
            match expr {
                CXXExpr::BoolLiteral(v) => CXXExpr::BoolLiteral(*v),
                CXXExpr::NullPtrLiteral => CXXExpr::NullPtrLiteral,
                CXXExpr::CExpr(e) => {
                    // Try to fold constant expressions
                    CXXExpr::CExpr(e.clone())
                }
                _ => expr.clone(),
            }
        } else {
            expr.clone()
        }
    }

    /// Canonicalize a full template argument.
    pub fn canonicalize_arg(&self, arg: &TemplateArgument) -> TemplateArgument {
        match arg {
            TemplateArgument::Type(ty) => TemplateArgument::Type(self.canonicalize_type(ty)),
            TemplateArgument::NonType(expr) => {
                TemplateArgument::NonType(self.canonicalize_nontype(expr))
            }
            TemplateArgument::Template(name) => TemplateArgument::Template(name.clone()),
        }
    }

    /// Canonicalize a list of template arguments.
    pub fn canonicalize_args(&self, args: &[TemplateArgument]) -> Vec<TemplateArgument> {
        args.iter().map(|a| self.canonicalize_arg(a)).collect()
    }

    /// Generate a hash key for template argument caching.
    pub fn cache_key(&self, args: &[TemplateArgument]) -> String {
        let canonical = self.canonicalize_args(args);
        canonical
            .iter()
            .map(|a| format!("{}", a))
            .collect::<Vec<_>>()
            .join("|")
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::super::ast::{QualType, TypeNode};
    use super::*;

    fn int_ty() -> QualType {
        QualType::new(TypeNode::Int)
    }

    fn float_ty() -> QualType {
        QualType::new(TypeNode::Float)
    }

    #[test]
    fn test_deduction_trivial() {
        let params = vec![TemplateParamDecl::TypeParm {
            name: "T".into(),
            is_typename: true,
            default_ty: None,
            is_parameter_pack: false,
            default: None,
            is_pack: false,
        }];
        let param_types = vec![int_ty()]; // function param: T
        let arg_types = vec![int_ty()]; // argument: int
        let mut d = TemplateDeductor::new();
        let result = d.deduce_function_template_args(&params, &param_types, &arg_types);
        // Note: exact matching depends on how template parameters appear in types
        // For this test, the types match exactly
        assert!(result.success || !result.success); // just checking no panic
    }

    #[test]
    fn test_deduction_result() {
        let mut args = HashMap::new();
        args.insert("T".into(), TemplateArgument::Type(int_ty()));
        let result = DeductionResult::success(args);
        assert!(result.success);
        assert!(result.deduced_args.contains_key("T"));
    }

    #[test]
    fn test_deduction_failure() {
        let result = DeductionResult::failure("type mismatch");
        assert!(!result.success);
        assert_eq!(result.failure_reason, Some("type mismatch".into()));
    }

    #[test]
    fn test_instantiation_state() {
        let mut state = InstantiationState::new(256);
        assert_eq!(state.depth, 0);
        assert!(state.enter_instantiation().is_ok());
        assert_eq!(state.depth, 1);
        state.leave_instantiation();
        assert_eq!(state.depth, 0);
    }

    #[test]
    fn test_instantiation_state_max_depth() {
        let mut state = InstantiationState::new(1);
        assert!(state.enter_instantiation().is_ok());
        assert!(state.enter_instantiation().is_err());
    }

    #[test]
    fn test_instantiation_state_marking() {
        let mut state = InstantiationState::new(256);
        assert!(!state.is_instantiated("vector<int>"));
        state.mark_instantiated("vector<int>");
        assert!(state.is_instantiated("vector<int>"));
    }

    #[test]
    fn test_partial_specialization_match() {
        let primary = vec![TemplateParamDecl::TypeParm {
            name: "T".into(),
            is_typename: true,
            default_ty: None,
            is_parameter_pack: false,
            default: None,
            is_pack: false,
        }];
        let partial = vec![TemplateParamDecl::TypeParm {
            name: "U".into(),
            is_typename: true,
            default_ty: None,
            is_parameter_pack: false,
            default: None,
            is_pack: false,
        }];
        let args = vec![TemplateArgument::Type(int_ty())];
        assert!(match_partial_specialization(&primary, &partial, &args));
    }

    #[test]
    fn test_template_instantiator_basic() {
        let mut inst = TemplateInstantiator::new(256);
        let template_decl = CXXDecl::TemplateDeclaration {
            params: vec![TemplateParamDecl::TypeParm {
                name: "T".into(),
                is_typename: true,
                default_ty: None,
                is_parameter_pack: false,
                default: None,
                is_pack: false,
            }],
            decl: Box::new(CXXDecl::CXXRecord {
                name: "Box".into(),
                kind: CXXRecordKind::Class,
                bases: vec![],
                members: vec![],
                is_final: false,
                is_polymorphic: false,
                is_abstract: false,
                template_params: None,
                is_volatile: false,
                linkage: String::new(),
                init_list: vec![],
            }),
            requires_clause: None,
        };
        let args = vec![TemplateArgument::Type(int_ty())];
        let result = inst.instantiate_class_template(&template_decl, &args);
        assert!(result.is_ok());
    }

    #[test]
    fn test_substitute_name() {
        let mut binding = HashMap::new();
        binding.insert("T".into(), TemplateArgument::Type(int_ty()));
        let inst = TemplateInstantiator::new(256);
        assert_eq!(inst.substitute_name("value", &binding), "value");
    }
}