llvm-native-core 0.1.13

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
//! libclang C API Equivalent in Rust — provides a safe, idiomatic wrapper
//! over the Clang frontend's internal data structures, mirroring the
//! libclang C API (CXIndex, CXTranslationUnit, CXCursor, CXType, etc.).
//!
//! This module enables programmatic access to the AST, types, source
//! locations, diagnostics, and code-completion from Rust code without
//! going through FFI boundaries.

use std::collections::HashMap;

use super::ast::*;
use super::CLangStandard;

// ═══════════════════════════════════════════════════════════════════════════
// CXIndex — the top-level context
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXIndex` in libclang.
///
/// Holds the set of parsed translation units and global options.
pub struct CXIndex {
    /// Parsed translation units, keyed by filename.
    pub translation_units: HashMap<String, CXTranslationUnit>,
    /// Global options (display diagnostics, etc.).
    pub global_options: CXGlobalOptions,
}

/// Global options for the index.
#[derive(Debug, Clone)]
pub struct CXGlobalOptions {
    pub exclude_declarations_from_pch: bool,
    pub display_diagnostics: bool,
}

impl Default for CXGlobalOptions {
    fn default() -> Self {
        Self {
            exclude_declarations_from_pch: false,
            display_diagnostics: true,
        }
    }
}

impl CXIndex {
    /// Create a new index with default options.
    pub fn create() -> Self {
        Self {
            translation_units: HashMap::new(),
            global_options: CXGlobalOptions::default(),
        }
    }

    /// Create an index with custom display-diagnostics flag.
    pub fn create_with_options(exclude_pch: bool, display_diags: bool) -> Self {
        Self {
            translation_units: HashMap::new(),
            global_options: CXGlobalOptions {
                exclude_declarations_from_pch: exclude_pch,
                display_diagnostics: display_diags,
            },
        }
    }

    /// Dispose (drop) the index and all associated translation units.
    pub fn dispose(&mut self) {
        self.translation_units.clear();
    }

    /// Parse a translation unit from source.
    pub fn parse_translation_unit(
        &mut self,
        source_file: &str,
        args: &[String],
        unsaved_files: &[CXUnsavedFile],
        options: CXTranslationUnitFlags,
    ) -> Result<CXTranslationUnit, String> {
        let source = std::fs::read_to_string(source_file)
            .map_err(|e| format!("Cannot read {}: {}", source_file, e))?;
        let tu = CXTranslationUnit::parse(source_file, &source, args, unsaved_files, options);
        self.translation_units
            .insert(source_file.to_string(), tu.clone());
        Ok(tu)
    }

    /// Parse a translation unit from source text (in-memory).
    pub fn parse_translation_unit_from_source(
        &mut self,
        source_file: &str,
        source: &str,
        args: &[String],
        options: CXTranslationUnitFlags,
    ) -> CXTranslationUnit {
        let tu = CXTranslationUnit::parse(source_file, source, args, &[], options);
        self.translation_units
            .insert(source_file.to_string(), tu.clone());
        tu
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXUnsavedFile — in-memory file overlay
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct CXUnsavedFile {
    pub filename: String,
    pub contents: String,
    pub length: usize,
}

impl CXUnsavedFile {
    pub fn new(filename: &str, contents: &str) -> Self {
        Self {
            filename: filename.to_string(),
            contents: contents.to_string(),
            length: contents.len(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXTranslationUnit — the parsed translation unit
// ═══════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct CXTranslationUnitFlags {
    pub detailed_preprocessing_record: bool,
    pub incomplete: bool,
    pub precompiled_preamble: bool,
    pub cache_completion_results: bool,
    pub for_serialization: bool,
    pub cxx_chained_pch: bool,
    pub skip_function_bodies: bool,
    pub include_brief_comments_in_code_completion: bool,
    pub create_preamble_on_first_parse: bool,
    pub keep_going: bool,
    pub single_file_parse: bool,
    pub limit_skip_function_bodies_to_preambles: bool,
    pub include_attributed_types: bool,
    pub visit_implicit_attributes: bool,
    pub ignore_non_errors_from_included_files: bool,
}

impl Default for CXTranslationUnitFlags {
    fn default() -> Self {
        Self {
            detailed_preprocessing_record: false,
            incomplete: false,
            precompiled_preamble: false,
            cache_completion_results: false,
            for_serialization: false,
            cxx_chained_pch: false,
            skip_function_bodies: false,
            include_brief_comments_in_code_completion: false,
            create_preamble_on_first_parse: false,
            keep_going: false,
            single_file_parse: false,
            limit_skip_function_bodies_to_preambles: false,
            include_attributed_types: false,
            visit_implicit_attributes: false,
            ignore_non_errors_from_included_files: false,
        }
    }
}

impl CXTranslationUnitFlags {
    pub fn none() -> Self {
        Self::default()
    }
}

/// Equivalent to `CXTranslationUnit` in libclang.
#[derive(Debug, Clone)]
pub struct CXTranslationUnit {
    pub filename: String,
    pub ast: TranslationUnit,
    pub diagnostics: Vec<CXDiagnostic>,
    pub cursors: Vec<CXCursor>,
    pub standard: CLangStandard,
}

impl CXTranslationUnit {
    /// Parse from source text.
    pub fn parse(
        filename: &str,
        source: &str,
        _args: &[String],
        _unsaved_files: &[CXUnsavedFile],
        _options: CXTranslationUnitFlags,
    ) -> Self {
        let standard = CLangStandard::C17;
        let tu = TranslationUnit::new(filename);
        // In a full implementation, we would run the full parsing pipeline here.
        Self {
            filename: filename.to_string(),
            ast: tu,
            diagnostics: Vec::new(),
            cursors: Vec::new(),
            standard,
        }
    }

    /// Get the translation unit cursor (the root cursor).
    pub fn cursor(&self) -> CXCursor {
        CXCursor {
            kind: CXCursorKind::TranslationUnit,
            spelling: self.filename.clone(),
            location: CXSourceLocation {
                file: self.filename.clone(),
                line: 1,
                column: 1,
                offset: 0,
            },
            extent: CXSourceRange {
                start: CXSourceLocation {
                    file: self.filename.clone(),
                    line: 1,
                    column: 1,
                    offset: 0,
                },
                end: CXSourceLocation {
                    file: self.filename.clone(),
                    line: 1,
                    column: 1,
                    offset: 0,
                },
            },
            children: Vec::new(),
            semantic_parent: None,
            lexical_parent: None,
            linkage: CXLinkageKind::External,
            is_definition: true,
            ty: None,
        }
    }

    /// Get the spelling of the translation unit (the filename).
    pub fn spelling(&self) -> &str {
        &self.filename
    }

    /// Get the file name.
    pub fn file(&self, _location: &CXSourceLocation) -> String {
        self.filename.clone()
    }

    /// Get the source location for a file/line/column.
    pub fn location(&self, _file: &str, _line: u32, _column: u32) -> CXSourceLocation {
        CXSourceLocation {
            file: self.filename.clone(),
            line: _line,
            column: _column,
            offset: 0,
        }
    }

    /// Get diagnostics for this translation unit.
    pub fn diagnostics(&self) -> &[CXDiagnostic] {
        &self.diagnostics
    }

    /// Get the number of diagnostics.
    pub fn num_diagnostics(&self) -> u32 {
        self.diagnostics.len() as u32
    }

    /// Dispose (drop) the translation unit.
    pub fn dispose(self) {
        // Resources are freed when the struct is dropped.
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXCursor — a reference to an AST node
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXCursor` in libclang.
#[derive(Debug, Clone)]
pub struct CXCursor {
    pub kind: CXCursorKind,
    pub spelling: String,
    pub location: CXSourceLocation,
    pub extent: CXSourceRange,
    pub children: Vec<CXCursor>,
    pub semantic_parent: Option<Box<CXCursor>>,
    pub lexical_parent: Option<Box<CXCursor>>,
    pub linkage: CXLinkageKind,
    pub is_definition: bool,
    pub ty: Option<CXType>,
}

/// Cursor kind — mirrors `CXCursorKind` from libclang.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXCursorKind {
    // ── Declarations ─────────────────────────────────────────────────
    UnexpectedDecl = 1,
    StructDecl = 2,
    UnionDecl = 3,
    ClassDecl = 4,
    EnumDecl = 5,
    FieldDecl = 6,
    EnumConstantDecl = 7,
    FunctionDecl = 8,
    VarDecl = 9,
    ParmDecl = 10,
    ObjCInterfaceDecl = 11,
    ObjCCategoryDecl = 12,
    ObjCProtocolDecl = 13,
    ObjCPropertyDecl = 14,
    ObjCIvarDecl = 15,
    ObjCInstanceMethodDecl = 16,
    ObjCClassMethodDecl = 17,
    ObjCMessageExpr = 18,
    ObjCSelectorRef = 19,
    ObjCProtocolRef = 20,
    ObjCClassRef = 21,
    NullStmt = 22,
    CompoundStmt = 23,
    CaseStmt = 24,
    DefaultStmt = 25,
    IfStmt = 26,
    SwitchStmt = 27,
    WhileStmt = 28,
    DoStmt = 29,
    ForStmt = 30,
    GotoStmt = 31,
    LabelStmt = 32,
    ReturnStmt = 33,
    BreakStmt = 34,
    ContinueStmt = 35,
    TranslationUnit = 300,
    TypedefDecl = 40,
    TypeAliasDecl = 41,
    UsingDeclaration = 42,
    UsingDirective = 43,
    Namespace = 44,
    NamespaceAlias = 45,
    Constructor = 46,
    Destructor = 47,
    ConversionFunction = 48,
    TemplateTypeParameter = 49,
    NonTypeTemplateParameter = 50,
    TemplateTemplateParameter = 51,
    FunctionTemplate = 52,
    ClassTemplate = 53,
    ClassTemplatePartialSpecialization = 54,
    NamespaceRef = 55,
    MemberRef = 56,
    LabelRef = 57,
    OverloadedDeclRef = 58,
    VariableRef = 59,
    TypeRef = 60,
    CXXBaseSpecifier = 61,
    TemplateRef = 62,
    ConstructorRef = 63,
    DestructorRef = 64,
    UnresolvedConstructor = 65,
    UnresolvedDestructor = 66,
    UnresolvedMemberExpr = 67,
    CallExpr = 100,
    BinaryOperator = 101,
    UnaryOperator = 102,
    ConditionalOperator = 103,
    ArraySubscriptExpr = 104,
    MemberRefExpr = 105,
    IntegerLiteral = 106,
    FloatingLiteral = 107,
    CharacterLiteral = 108,
    StringLiteral = 109,
    ParenExpr = 110,
    UnaryExpr = 111,
    SizeOfExpr = 112,
    OffsetOfExpr = 113,
    AlignOfExpr = 114,
    CompoundLiteralExpr = 115,
    InitListExpr = 116,
    GenericSelectionExpr = 117,
    AtomicExpr = 118,
    StmtExpr = 119,
    BlockExpr = 120,
    LambdaExpr = 121,
    CXXStaticCastExpr = 122,
    CXXDynamicCastExpr = 123,
    CXXReinterpretCastExpr = 124,
    CXXConstCastExpr = 125,
    CXXFunctionalCastExpr = 126,
    CXXTypeidExpr = 127,
    CXXThrowExpr = 128,
    CXXNewExpr = 129,
    CXXDeleteExpr = 130,
    CXXMemberCallExpr = 131,
    CXXOperatorCallExpr = 132,
    PackExpansionExpr = 133,
    SizeOfPackExpr = 134,
    FoldExpr = 135,
    CoawaitExpr = 136,
    CoyieldExpr = 137,
    CoreturnExpr = 138,
    ModuleImportDecl = 600,
    TypeAliasTemplateDecl = 601,
    StaticAssert = 602,
    FriendDecl = 603,
    ConceptDecl = 604,
    RequiresExpr = 605,
    NotImplemented = 999,
}

impl CXCursorKind {
    pub fn is_declaration(&self) -> bool {
        matches!(
            self,
            Self::StructDecl
                | Self::UnionDecl
                | Self::ClassDecl
                | Self::EnumDecl
                | Self::FunctionDecl
                | Self::VarDecl
                | Self::ParmDecl
                | Self::TypedefDecl
                | Self::Namespace
                | Self::Constructor
                | Self::Destructor
                | Self::FunctionTemplate
                | Self::ClassTemplate
                | Self::TranslationUnit
        )
    }

    pub fn is_expression(&self) -> bool {
        matches!(
            self,
            Self::CallExpr
                | Self::BinaryOperator
                | Self::UnaryOperator
                | Self::IntegerLiteral
                | Self::FloatingLiteral
                | Self::StringLiteral
                | Self::CharacterLiteral
                | Self::ParenExpr
                | Self::ArraySubscriptExpr
                | Self::MemberRefExpr
                | Self::ConditionalOperator
                | Self::SizeOfExpr
                | Self::OffsetOfExpr
                | Self::AlignOfExpr
                | Self::CompoundLiteralExpr
                | Self::InitListExpr
                | Self::LambdaExpr
        )
    }

    pub fn is_statement(&self) -> bool {
        matches!(
            self,
            Self::NullStmt
                | Self::CompoundStmt
                | Self::IfStmt
                | Self::SwitchStmt
                | Self::WhileStmt
                | Self::DoStmt
                | Self::ForStmt
                | Self::GotoStmt
                | Self::ReturnStmt
                | Self::BreakStmt
                | Self::ContinueStmt
                | Self::LabelStmt
                | Self::CaseStmt
                | Self::DefaultStmt
        )
    }

    pub fn from_u32(val: u32) -> Self {
        match val {
            1 => Self::UnexpectedDecl,
            2 => Self::StructDecl,
            3 => Self::UnionDecl,
            4 => Self::ClassDecl,
            5 => Self::EnumDecl,
            8 => Self::FunctionDecl,
            9 => Self::VarDecl,
            10 => Self::ParmDecl,
            40 => Self::TypedefDecl,
            100 => Self::CallExpr,
            101 => Self::BinaryOperator,
            106 => Self::IntegerLiteral,
            109 => Self::StringLiteral,
            300 => Self::TranslationUnit,
            _ => Self::NotImplemented,
        }
    }
}

/// Equivalent to `CXLinkageKind` in libclang.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXLinkageKind {
    Invalid,
    NoLinkage,
    Internal,
    UniqueExternal,
    External,
}

impl CXCursor {
    pub fn new(kind: CXCursorKind, spelling: &str) -> Self {
        Self {
            kind,
            spelling: spelling.to_string(),
            location: CXSourceLocation::default(),
            extent: CXSourceRange::default(),
            children: Vec::new(),
            semantic_parent: None,
            lexical_parent: None,
            linkage: CXLinkageKind::External,
            is_definition: false,
            ty: None,
        }
    }

    /// Visit all direct children of this cursor.
    pub fn visit_children<F>(&self, mut visitor: F)
    where
        F: FnMut(&CXCursor) -> CXChildVisitResult,
    {
        for child in &self.children {
            let result = visitor(child);
            match result {
                CXChildVisitResult::Break => break,
                CXChildVisitResult::Continue => continue,
                CXChildVisitResult::Recurse => {
                    child.visit_children(|c| visitor(c));
                }
            }
        }
    }

    /// Get the semantic parent (the logical parent in the AST).
    pub fn semantic_parent(&self) -> Option<&CXCursor> {
        self.semantic_parent.as_deref()
    }

    /// Get the lexical parent (the enclosing scope).
    pub fn lexical_parent(&self) -> Option<&CXCursor> {
        self.lexical_parent.as_deref()
    }

    /// Get the linkage of the cursor's entity.
    pub fn linkage(&self) -> CXLinkageKind {
        self.linkage
    }

    /// Check if this cursor is a definition (vs. a declaration).
    pub fn is_definition(&self) -> bool {
        self.is_definition
    }

    /// Get the type associated with this cursor.
    pub fn cursor_type(&self) -> Option<&CXType> {
        self.ty.as_ref()
    }
}

/// Result of visiting a child cursor.
pub enum CXChildVisitResult {
    Break,
    Continue,
    Recurse,
}

// ═══════════════════════════════════════════════════════════════════════════
// CXType — type representation
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXType` in libclang.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CXType {
    pub kind: CXTypeKind,
    pub spelling: String,
    pub size: u64,
    pub alignment: u64,
    pub pointee_type: Option<Box<CXType>>,
    pub array_element_type: Option<Box<CXType>>,
    pub array_size: i64,
    pub result_type: Option<Box<CXType>>,
    pub argument_types: Vec<CXType>,
    pub is_const: bool,
    pub is_volatile: bool,
    pub is_restrict: bool,
    pub num_template_args: i32,
}

/// Equivalent to `CXTypeKind` in libclang.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CXTypeKind {
    #[default]
    Invalid = 0,
    Unexposed = 1,
    Void = 2,
    Bool = 3,
    Char_U = 4,
    UChar = 5,
    Char16 = 6,
    Char32 = 7,
    UShort = 8,
    UInt = 9,
    ULong = 10,
    ULongLong = 11,
    Int128 = 12,
    Char_S = 13,
    SChar = 14,
    WChar = 15,
    Short = 16,
    Int = 17,
    Long = 18,
    LongLong = 19,
    Float = 20,
    Double = 21,
    LongDouble = 22,
    Float128 = 30,
    Pointer = 100,
    BlockPointer = 101,
    LValueReference = 102,
    RValueReference = 103,
    Record = 104,
    Enum = 105,
    Typedef = 106,
    ObjCInterface = 107,
    ObjCObjectPointer = 108,
    Function = 109,
    FunctionProto = 110,
    ConstantArray = 111,
    Vector = 112,
    IncompleteArray = 113,
    VariableArray = 114,
    DependentSizedArray = 115,
    MemberPointer = 116,
    Auto = 117,
    Elaborated = 118,
    Pipe = 119,
    Attributed = 120,
    Atomic = 121,
    Complex = 122,
}

impl CXType {
    pub fn new(kind: CXTypeKind, spelling: &str) -> Self {
        Self {
            kind,
            spelling: spelling.to_string(),
            size: 0,
            alignment: 0,
            pointee_type: None,
            array_element_type: None,
            array_size: -1,
            result_type: None,
            argument_types: Vec::new(),
            is_const: false,
            is_volatile: false,
            is_restrict: false,
            num_template_args: -1,
        }
    }

    /// Get the pointee type (for pointer types).
    pub fn pointee_type(&self) -> Option<&CXType> {
        self.pointee_type.as_deref()
    }

    /// Get the array element type and element count.
    pub fn array_element_type(&self) -> (Option<&CXType>, i64) {
        (self.array_element_type.as_deref(), self.array_size)
    }

    /// Get the function result type.
    pub fn result_type(&self) -> Option<&CXType> {
        self.result_type.as_deref()
    }

    /// Get the number of argument types for function types.
    pub fn num_arg_types(&self) -> i32 {
        self.argument_types.len() as i32
    }

    /// Get the argument type at a specific index.
    pub fn arg_type(&self, index: usize) -> Option<&CXType> {
        self.argument_types.get(index)
    }

    /// Check if the type is `const` qualified.
    pub fn is_const_qualified(&self) -> bool {
        self.is_const
    }

    /// Check if the type is `volatile` qualified.
    pub fn is_volatile_qualified(&self) -> bool {
        self.is_volatile
    }

    /// Check if the type is pod (plain old data).
    pub fn is_pod(&self) -> bool {
        matches!(
            self.kind,
            CXTypeKind::Bool
                | CXTypeKind::Char_U
                | CXTypeKind::UChar
                | CXTypeKind::SChar
                | CXTypeKind::Short
                | CXTypeKind::Int
                | CXTypeKind::Long
                | CXTypeKind::LongLong
                | CXTypeKind::UShort
                | CXTypeKind::UInt
                | CXTypeKind::ULong
                | CXTypeKind::ULongLong
                | CXTypeKind::Float
                | CXTypeKind::Double
                | CXTypeKind::LongDouble
                | CXTypeKind::Pointer
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXSourceLocation and CXSourceRange
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXSourceLocation` in libclang.
#[derive(Debug, Clone, Default)]
pub struct CXSourceLocation {
    pub file: String,
    pub line: u32,
    pub column: u32,
    pub offset: u32,
}

impl CXSourceLocation {
    /// Get file, line, column, offset tuple.
    pub fn expansion_location(&self) -> (&str, u32, u32, u32) {
        (&self.file, self.line, self.column, self.offset)
    }

    /// Check if two locations are from the same file.
    pub fn is_from_same_file(&self, other: &CXSourceLocation) -> bool {
        self.file == other.file
    }
}

/// Equivalent to `CXSourceRange` in libclang.
#[derive(Debug, Clone, Default)]
pub struct CXSourceRange {
    pub start: CXSourceLocation,
    pub end: CXSourceLocation,
}

impl CXSourceRange {
    /// Get the start and end locations of the range.
    pub fn range_locations(&self) -> (&CXSourceLocation, &CXSourceLocation) {
        (&self.start, &self.end)
    }

    /// Check if the range is a null range (same location for start and end).
    pub fn is_null(&self) -> bool {
        self.start.file == self.end.file
            && self.start.line == self.end.line
            && self.start.column == self.end.column
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXCodeCompleteResults — code completion
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXCodeCompleteResults` in libclang.
#[derive(Debug, Clone)]
pub struct CXCodeCompleteResults {
    pub results: Vec<CXCompletionResult>,
    pub context: Option<String>,
}

/// A single code-completion result.
#[derive(Debug, Clone)]
pub struct CXCompletionResult {
    pub kind: CXCompletionKind,
    pub completion_string: CXCompletionString,
    pub priority: u32,
}

/// Kind of completion result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXCompletionKind {
    Macro,
    Keyword,
    Typedef,
    Function,
    Variable,
    Field,
    EnumConstant,
    Struct,
    Union,
    Class,
    Namespace,
    Enum,
    Template,
    Type,
    Parameter,
    Unknown,
}

/// The completion string with chunks and annotations.
#[derive(Debug, Clone)]
pub struct CXCompletionString {
    pub chunks: Vec<CXCompletionChunk>,
    pub priority: u32,
    pub availability: CXAvailabilityKind,
    pub brief_comment: Option<String>,
}

/// A single chunk in a completion string.
#[derive(Debug, Clone)]
pub struct CXCompletionChunk {
    pub kind: CXCompletionChunkKind,
    pub text: String,
    pub annotation: Option<String>,
}

/// Kind of completion chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXCompletionChunkKind {
    Optional,
    TypedText,
    Text,
    Placeholder,
    Informative,
    CurrentParameter,
    LeftParen,
    RightParen,
    LeftBracket,
    RightBracket,
    LeftBrace,
    RightBrace,
    LeftAngle,
    RightAngle,
    Comma,
    ResultType,
    Colon,
    SemiColon,
    Equal,
    HorizontalSpace,
    VerticalSpace,
}

/// Availability kind for completion results.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXAvailabilityKind {
    Available,
    Deprecated,
    NotAvailable,
    NotAccessible,
}

impl CXCodeCompleteResults {
    /// Code-complete at a given location in the file.
    pub fn complete_at(
        _file: &str,
        _line: u32,
        _column: u32,
        _unsaved_files: &[CXUnsavedFile],
        _options: CXTranslationUnitFlags,
    ) -> Self {
        // In a full implementation, this would invoke the actual code-completion
        // engine with the Clang frontend.
        Self {
            results: Vec::new(),
            context: None,
        }
    }

    /// Get the number of completion results.
    pub fn num_results(&self) -> u32 {
        self.results.len() as u32
    }

    /// Get a completion result by index.
    pub fn result(&self, index: u32) -> Option<&CXCompletionResult> {
        self.results.get(index as usize)
    }

    /// Sort the completion results by priority.
    pub fn sort_by_priority(&mut self) {
        self.results.sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    /// Dispose the completion results.
    pub fn dispose(self) {
        // Resources are freed on drop.
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// CXDiagnostic — diagnostic (error/warning/note)
// ═══════════════════════════════════════════════════════════════════════════

/// Equivalent to `CXDiagnostic` in libclang.
#[derive(Debug, Clone)]
pub struct CXDiagnostic {
    pub severity: CXDiagnosticSeverity,
    pub spelling: String,
    pub location: CXSourceLocation,
    pub ranges: Vec<CXSourceRange>,
    pub fixits: Vec<CXFixIt>,
    pub children: Vec<CXDiagnostic>,
    pub category: u32,
    pub category_text: String,
    pub option: Option<String>,
    pub disable_option: Option<String>,
}

/// Severity of a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXDiagnosticSeverity {
    Ignored,
    Note,
    Warning,
    Error,
    Fatal,
}

impl CXDiagnostic {
    pub fn new_error(spelling: &str) -> Self {
        Self {
            severity: CXDiagnosticSeverity::Error,
            spelling: spelling.to_string(),
            location: CXSourceLocation::default(),
            ranges: Vec::new(),
            fixits: Vec::new(),
            children: Vec::new(),
            category: 0,
            category_text: String::new(),
            option: None,
            disable_option: None,
        }
    }

    pub fn new_warning(spelling: &str) -> Self {
        Self {
            severity: CXDiagnosticSeverity::Warning,
            spelling: spelling.to_string(),
            ..Self::new_error(spelling)
        }
    }

    pub fn new_note(spelling: &str) -> Self {
        Self {
            severity: CXDiagnosticSeverity::Note,
            spelling: spelling.to_string(),
            ..Self::new_error(spelling)
        }
    }

    /// Get the diagnostic severity.
    pub fn severity(&self) -> CXDiagnosticSeverity {
        self.severity
    }

    /// Get the diagnostic spelling (the message text).
    pub fn spelling(&self) -> &str {
        &self.spelling
    }

    /// Get the source location of the diagnostic.
    pub fn location(&self) -> &CXSourceLocation {
        &self.location
    }

    /// Get the number of fix-it hints.
    pub fn num_fixits(&self) -> u32 {
        self.fixits.len() as u32
    }

    /// Get a fix-it hint by index.
    pub fn fixit(&self, index: u32) -> Option<&CXFixIt> {
        self.fixits.get(index as usize)
    }

    /// Get child diagnostics (notes attached to the main diagnostic).
    pub fn children(&self) -> &[CXDiagnostic] {
        &self.children
    }

    /// Set the disable option string (e.g., "-Wunused-variable").
    pub fn with_disable_option(mut self, option: &str) -> Self {
        self.disable_option = Some(option.to_string());
        self
    }

    /// Format the diagnostic as a string.
    pub fn format(&self) -> String {
        let severity_str = match self.severity {
            CXDiagnosticSeverity::Ignored => "ignored",
            CXDiagnosticSeverity::Note => "note",
            CXDiagnosticSeverity::Warning => "warning",
            CXDiagnosticSeverity::Error => "error",
            CXDiagnosticSeverity::Fatal => "fatal error",
        };
        format!(
            "{}:{}:{}: {}: {}",
            self.location.file,
            self.location.line,
            self.location.column,
            severity_str,
            self.spelling
        )
    }
}

/// A fix-it hint.
#[derive(Debug, Clone)]
pub struct CXFixIt {
    pub range: CXSourceRange,
    pub replacement: String,
}

impl CXFixIt {
    /// Create a fix-it that replaces a range with new text.
    pub fn new_replacement(range: CXSourceRange, replacement: &str) -> Self {
        Self {
            range,
            replacement: replacement.to_string(),
        }
    }

    /// Create a fix-it that removes a range.
    pub fn new_removal(range: CXSourceRange) -> Self {
        Self {
            range,
            replacement: String::new(),
        }
    }

    /// Create a fix-it that inserts text at a location.
    pub fn new_insertion(location: CXSourceLocation, text: &str) -> Self {
        Self {
            range: CXSourceRange {
                start: location.clone(),
                end: location,
            },
            replacement: text.to_string(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Cursor operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the kind of a cursor.
///
/// Maps a CXCursor to its CXCursorKind value with a full
/// mapping covering declarations, expressions, statements, and references.
pub fn clang_getCursorKind(cursor: &CXCursor) -> CXCursorKind {
    cursor.kind
}

/// Get the spelling (name) of the entity at the given cursor.
pub fn clang_getCursorSpelling(cursor: &CXCursor) -> String {
    cursor.spelling.clone()
}

/// Get the display name for the cursor (often same as spelling).
pub fn clang_getCursorDisplayName(cursor: &CXCursor) -> String {
    clang_getCursorSpelling(cursor)
}

/// Get the CXType for the cursor.
pub fn clang_getCursorType(cursor: &CXCursor) -> CXType {
    cursor.cursor_type().cloned().unwrap_or_default()
}

/// Get the type spelling as a string.
pub fn clang_getTypeSpelling(ty: &CXType) -> String {
    ty.spelling.clone()
}

/// Get the kind spelling string for a type kind.
pub fn clang_getTypeKindSpelling(kind: CXTypeKind) -> &'static str {
    match kind {
        CXTypeKind::Invalid => "Invalid",
        CXTypeKind::Unexposed => "Unexposed",
        CXTypeKind::Void => "Void",
        CXTypeKind::Bool => "Bool",
        CXTypeKind::Char_U => "Char_U",
        CXTypeKind::UChar => "UnsignedChar",
        CXTypeKind::Char16 => "Char16",
        CXTypeKind::Char32 => "Char32",
        CXTypeKind::UShort => "UnsignedShort",
        CXTypeKind::UInt => "UnsignedInt",
        CXTypeKind::ULong => "UnsignedLong",
        CXTypeKind::ULongLong => "UnsignedLongLong",
        CXTypeKind::Int128 => "Int128",
        CXTypeKind::Char_S => "Char_S",
        CXTypeKind::SChar => "SignedChar",
        CXTypeKind::WChar => "WChar",
        CXTypeKind::Short => "Short",
        CXTypeKind::Int => "Int",
        CXTypeKind::Long => "Long",
        CXTypeKind::LongLong => "LongLong",
        CXTypeKind::Float => "Float",
        CXTypeKind::Double => "Double",
        CXTypeKind::LongDouble => "LongDouble",
        CXTypeKind::Float128 => "Float128",
        CXTypeKind::Pointer => "Pointer",
        CXTypeKind::BlockPointer => "BlockPointer",
        CXTypeKind::LValueReference => "LValueReference",
        CXTypeKind::RValueReference => "RValueReference",
        CXTypeKind::Record => "Record",
        CXTypeKind::Enum => "Enum",
        CXTypeKind::Typedef => "Typedef",
        CXTypeKind::ObjCInterface => "ObjCInterface",
        CXTypeKind::ObjCObjectPointer => "ObjCObjectPointer",
        CXTypeKind::Function => "FunctionNoProto",
        CXTypeKind::FunctionProto => "FunctionProto",
        CXTypeKind::ConstantArray => "ConstantArray",
        CXTypeKind::Vector => "Vector",
        CXTypeKind::IncompleteArray => "IncompleteArray",
        CXTypeKind::VariableArray => "VariableArray",
        CXTypeKind::DependentSizedArray => "DependentSizedArray",
        CXTypeKind::MemberPointer => "MemberPointer",
        CXTypeKind::Auto => "Auto",
        CXTypeKind::Elaborated => "Elaborated",
        CXTypeKind::Pipe => "Pipe",
        CXTypeKind::Attributed => "Attributed",
        CXTypeKind::Atomic => "Atomic",
        CXTypeKind::Complex => "Complex",
    }
}

/// Get the number of argument types for a function type.
pub fn clang_getNumArgTypes(ty: &CXType) -> i32 {
    ty.num_arg_types() as i32
}

/// Get the i-th argument type of a function type.
pub fn clang_getArgType(ty: &CXType, i: u32) -> Option<CXType> {
    ty.arg_type(i as usize).cloned()
}

/// Get the result type of a function type.
pub fn clang_getResultType(ty: &CXType) -> CXType {
    ty.result_type().cloned().unwrap_or_default()
}

/// Return 1 if the type is const-qualified, 0 otherwise.
pub fn clang_isConstQualifiedType(ty: &CXType) -> u32 {
    ty.is_const_qualified() as u32
}

/// Return 1 if the type is volatile-qualified, 0 otherwise.
pub fn clang_isVolatileQualifiedType(ty: &CXType) -> u32 {
    ty.is_volatile_qualified() as u32
}

/// Return 1 if the type is restrict-qualified, 0 otherwise.
pub fn clang_isRestrictQualifiedType(ty: &CXType) -> u32 {
    ty.is_restrict as u32
}

/// Get the pointee type of a pointer type.
pub fn clang_getPointeeType(ty: &CXType) -> CXType {
    ty.pointee_type().cloned().unwrap_or_default()
}

/// Get the element type and size of an array type.
pub fn clang_getArrayElementType(ty: &CXType) -> CXType {
    ty.array_element_type().0.cloned().unwrap_or_default()
}

/// Get the size of an array type (-1 for incomplete arrays).
pub fn clang_getArraySize(ty: &CXType) -> i64 {
    ty.array_size as i64
}

/// Get the address space of a type.
pub fn clang_getAddressSpace(_ty: &CXType) -> u32 {
    // Default address space is 0.
    0
}

/// Get the size of a type in bytes (target-dependent).
pub fn clang_Type_getSizeOf(ty: &CXType) -> i64 {
    ty.size as i64
}

/// Get the alignment of a type in bytes (target-dependent).
pub fn clang_Type_getAlignOf(ty: &CXType) -> i64 {
    ty.alignment as i64
}

/// Get the offset of a field in a struct/union in bits.
pub fn clang_Type_getOffsetOf(ty: &CXType, _field_name: &str) -> i64 {
    // Returns -1 if the field is not found.
    // For now, return a placeholder.
    let _ = ty;
    -1
}

/// Get the number of template arguments for a type.
pub fn clang_Type_getNumTemplateArguments(ty: &CXType) -> i32 {
    ty.num_template_args as i32
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Cursor value operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the value of an enum constant declaration.
pub fn clang_getEnumConstantDeclValue(cursor: &CXCursor) -> i64 {
    match cursor.kind {
        CXCursorKind::EnumConstantDecl => {
            // Try to parse the spelling as an integer.
            cursor.spelling.parse().unwrap_or(0)
        }
        _ => 0,
    }
}

/// Get the unsigned value of an enum constant declaration.
pub fn clang_getEnumConstantDeclUnsignedValue(cursor: &CXCursor) -> u64 {
    clang_getEnumConstantDeclValue(cursor) as u64
}

/// Get the bit width of a bit-field declaration.
pub fn clang_getFieldDeclBitWidth(cursor: &CXCursor) -> i32 {
    match cursor.kind {
        CXCursorKind::FieldDecl => {
            // Parse the bit width from the type or a synthetic attribute.
            // For now, try to extract from cursor metadata.
            if let Some(ref ty) = cursor.ty {
                if ty.spelling.contains(':') {
                    let parts: Vec<&str> = ty.spelling.split(':').collect();
                    if parts.len() > 1 {
                        return parts[1].trim().parse().unwrap_or(-1);
                    }
                }
            }
            -1
        }
        _ => -1,
    }
}

/// Get the number of arguments of a call expression cursor.
pub fn clang_Cursor_getNumArguments(cursor: &CXCursor) -> i32 {
    match cursor.kind {
        CXCursorKind::CallExpr
        | CXCursorKind::CXXMemberCallExpr
        | CXCursorKind::CXXOperatorCallExpr
        | CXCursorKind::Constructor
        | CXCursorKind::Destructor => cursor.children.len() as i32,
        _ => -1,
    }
}

/// Get the i-th argument cursor of a call expression.
pub fn clang_Cursor_getArgument(cursor: &CXCursor, i: u32) -> Option<CXCursor> {
    if i < cursor.children.len() as u32 {
        Some(cursor.children[i as usize].clone())
    } else {
        None
    }
}

/// Return 1 if the cursor is a bit field.
pub fn clang_Cursor_isBitField(cursor: &CXCursor) -> u32 {
    match cursor.kind {
        CXCursorKind::FieldDecl => {
            if let Some(ref ty) = cursor.ty {
                ty.spelling.contains(':') as u32
            } else {
                0
            }
        }
        _ => 0,
    }
}

/// Return 1 if the cursor is an anonymous record/union.
pub fn clang_Cursor_isAnonymous(cursor: &CXCursor) -> u32 {
    match cursor.kind {
        CXCursorKind::StructDecl | CXCursorKind::UnionDecl => cursor.spelling.is_empty() as u32,
        _ => 0,
    }
}

/// Return 1 if the cursor is an anonymous record or namespace.
pub fn clang_Cursor_isAnonymousRecordDecl(cursor: &CXCursor) -> u32 {
    clang_Cursor_isAnonymous(cursor)
}

/// Return 1 if the cursor is an inline namespace.
pub fn clang_Cursor_isInlineNamespace(_cursor: &CXCursor) -> u32 {
    // Inline namespace support.
    0
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Cursor visibility and linkage
// ═══════════════════════════════════════════════════════════════════════════════

/// Visibility of a symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CXVisibilityKind {
    Invalid,
    Hidden,
    Protected,
    Default,
}

/// Get the visibility of a cursor.
pub fn clang_getCursorVisibility(cursor: &CXCursor) -> CXVisibilityKind {
    // Default visibility for most declarations.
    // This could be refined based on attributes.
    if matches!(
        cursor.kind,
        CXCursorKind::UnexpectedDecl | CXCursorKind::NotImplemented
    ) {
        CXVisibilityKind::Invalid
    } else {
        CXVisibilityKind::Default
    }
}

/// Get the linkage kind of a cursor.
pub fn clang_getCursorLinkage(cursor: &CXCursor) -> CXLinkageKind {
    cursor.linkage()
}

/// Get the language kind of a cursor.
pub fn clang_getCursorLanguage(_cursor: &CXCursor) -> u32 {
    // Returns CXLanguage enum value.
    // 0 = Invalid, 1 = C, 2 = C++, 3 = ObjC
    1 // Assume C for now
}

/// Get the translation unit that a cursor originated from.
pub fn clang_Cursor_getTranslationUnit(cursor: &CXCursor) -> CXTranslationUnit {
    // Create a synthetic TU for the cursor.
    CXTranslationUnit {
        filename: String::new(),
        ast: TranslationUnit {
            decls: Vec::new(),
            filename: String::new(),
        },
        diagnostics: Vec::new(),
        cursors: vec![cursor.clone()],
        standard: CLangStandard::C17,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Visitor and cursor traversal
// ═══════════════════════════════════════════════════════════════════════════════

/// Visitor for clang_visitChildren.
///
/// Returns CXChildVisitResult to control traversal.
pub type CXCursorVisitor = dyn FnMut(&CXCursor, &CXCursor) -> CXChildVisitResult;

/// Visit the children of a cursor with the given visitor.
///
/// Traverses the AST subtree rooted at the given cursor,
/// calling the visitor for each direct child.
/// The visitor receives (child, parent) and returns CXChildVisitResult.
pub fn clang_visitChildren(cursor: &CXCursor, visitor: &mut CXCursorVisitor) -> u32 {
    // If the cursor has no children, return immediately.
    if cursor.children.is_empty() {
        return 0; // CXChildVisit_Break
    }

    // Visit each direct child.
    for child in &cursor.children {
        match visitor(child, cursor) {
            CXChildVisitResult::Break => return 0,
            CXChildVisitResult::Continue => {}
            CXChildVisitResult::Recurse => {
                // Recursively visit grandchildren.
                // In a real implementation, this would do a full depth-first traversal.
            }
        }
    }

    1 // CXChildVisit_Continue
}

/// Visit children with a typed visitor function.
pub fn clang_visitChildren_typed<F>(cursor: &CXCursor, mut visitor: F) -> u32
where
    F: FnMut(&CXCursor, &CXCursor) -> CXChildVisitResult + 'static,
{
    clang_visitChildren(cursor, &mut visitor)
}

/// Get the root cursor of a translation unit.
pub fn clang_getTranslationUnitCursor(tu: &CXTranslationUnit) -> CXCursor {
    tu.cursor()
}

/// Get the number of cursors in a translation unit.
pub fn clang_getNumCursors(tu: &CXTranslationUnit) -> u32 {
    tu.cursors.len() as u32
}

/// Get the i-th cursor in a translation unit.
pub fn clang_getCursor(tu: &CXTranslationUnit, i: u32) -> Option<CXCursor> {
    tu.cursors.get(i as usize).cloned()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Location and source range operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the location of a cursor.
pub fn clang_getCursorLocation(cursor: &CXCursor) -> CXSourceLocation {
    cursor.location.clone()
}

/// Get the extent (source range) of a cursor.
pub fn clang_getCursorExtent(cursor: &CXCursor) -> CXSourceRange {
    CXSourceRange {
        start: cursor.location.clone(),
        end: cursor.extent.end.clone(),
    }
}

/// Get the null location.
pub fn clang_getNullLocation() -> CXSourceLocation {
    CXSourceLocation {
        file: String::new(),
        line: 0,
        column: 0,
        offset: 0,
    }
}

/// Get the null range.
pub fn clang_getNullRange() -> CXSourceRange {
    let null_loc = clang_getNullLocation();
    CXSourceRange {
        start: null_loc.clone(),
        end: null_loc,
    }
}

/// Get the file name from a source location.
pub fn clang_getFileName(location: &CXSourceLocation) -> String {
    location.file.clone()
}

/// Get the line number from a source location.
pub fn clang_getLineNumber(location: &CXSourceLocation) -> u32 {
    location.line
}

/// Get the column number from a source location.
pub fn clang_getColumnNumber(location: &CXSourceLocation) -> u32 {
    location.column
}

/// Get the file offset from a source location.
pub fn clang_getFileOffset(location: &CXSourceLocation) -> u32 {
    location.offset
}

/// Check if two locations are from the same file.
pub fn clang_equalLocations(loc1: &CXSourceLocation, loc2: &CXSourceLocation) -> u32 {
    loc1.is_from_same_file(loc2) as u32
}

/// Check if two ranges are equal.
pub fn clang_equalRanges(range1: &CXSourceRange, range2: &CXSourceRange) -> u32 {
    (clang_equalLocations(&range1.start, &range2.start) != 0
        && clang_equalLocations(&range1.end, &range2.end) != 0) as u32
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Type operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Return 1 if two types are equal, 0 otherwise.
pub fn clang_equalTypes(ty1: &CXType, ty2: &CXType) -> u32 {
    (ty1.kind == ty2.kind && ty1.spelling == ty2.spelling) as u32
}

/// Get the canonical type.
pub fn clang_getCanonicalType(ty: &CXType) -> CXType {
    // Canonical types strip typedefs and other sugar.
    // For now, return a clone since our types are simple.
    ty.clone()
}

/// Return 1 if the type is a POD (Plain Old Data) type.
pub fn clang_isPODType(ty: &CXType) -> u32 {
    ty.is_pod() as u32
}

/// Get the type declaration cursor for a type (e.g., struct/union/typedef).
pub fn clang_getTypeDeclaration(ty: &CXType) -> CXCursor {
    match ty.kind {
        CXTypeKind::Record => CXCursor::new(CXCursorKind::StructDecl, &ty.spelling),
        CXTypeKind::Enum => CXCursor::new(CXCursorKind::EnumDecl, &ty.spelling),
        CXTypeKind::Typedef => CXCursor::new(CXCursorKind::TypedefDecl, &ty.spelling),
        CXTypeKind::ObjCInterface => CXCursor::new(CXCursorKind::ObjCInterfaceDecl, &ty.spelling),
        _ => CXCursor::new(CXCursorKind::NotImplemented, ""),
    }
}

/// Get the number of elements in a vector or array type.
pub fn clang_getNumElements(ty: &CXType) -> i64 {
    match ty.kind {
        CXTypeKind::ConstantArray | CXTypeKind::Vector => ty.array_size as i64,
        CXTypeKind::IncompleteArray => -1,
        _ => 1,
    }
}

/// Get the element type of a vector or array type.
pub fn clang_getElementType(ty: &CXType) -> CXType {
    ty.array_element_type().0.cloned().unwrap_or_default()
}

/// Get the elaborated type.
pub fn clang_Type_getNamedType(ty: &CXType) -> CXType {
    // For elaborated types, get the underlying named type.
    if ty.kind == CXTypeKind::Elaborated {
        // Remove the elaborated sugar.
        let mut canonical = ty.clone();
        canonical.kind = CXTypeKind::Record;
        canonical
    } else {
        ty.clone()
    }
}

/// Get the C++ class type from a member pointer type.
pub fn clang_Type_getClassType(_ty: &CXType) -> CXType {
    // For member pointer types, get the class type.
    CXType::new(CXTypeKind::Record, "")
}

// ═══════════════════════════════════════════════════════════════════════════════
// Libclang API — Token operations
// ═══════════════════════════════════════════════════════════════════════════════

/// A token for clang_tokenize.
#[derive(Debug, Clone)]
pub struct CXToken {
    /// Token kind identifier.
    pub kind: u32,
    /// Token spelling text.
    pub spelling: String,
    /// Source location of the token.
    pub location: CXSourceLocation,
    /// Extent of the token.
    pub extent: CXSourceRange,
}

impl CXToken {
    /// Create a new token.
    pub fn new(kind: u32, spelling: &str, location: CXSourceLocation) -> Self {
        Self {
            kind,
            spelling: spelling.to_string(),
            location: location.clone(),
            extent: CXSourceRange {
                start: location.clone(),
                end: location,
            },
        }
    }
}

/// Get the token kind string.
pub fn clang_getTokenKind(kind: u32) -> &'static str {
    match kind {
        0 => "punctuation",
        1 => "keyword",
        2 => "identifier",
        3 => "literal",
        4 => "comment",
        _ => "unknown",
    }
}

/// Get token spelling.
pub fn clang_getTokenSpelling(_tu: &CXTranslationUnit, token: &CXToken) -> String {
    token.spelling.clone()
}

/// Get token location.
pub fn clang_getTokenLocation(_tu: &CXTranslationUnit, token: &CXToken) -> CXSourceLocation {
    token.location.clone()
}

/// Get token extent.
pub fn clang_getTokenExtent(_tu: &CXTranslationUnit, token: &CXToken) -> CXSourceRange {
    CXSourceRange {
        start: token.location.clone(),
        end: token.extent.end.clone(),
    }
}

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

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

    #[test]
    fn test_index_create_and_dispose() {
        let mut index = CXIndex::create();
        assert!(index.translation_units.is_empty());
        index.dispose();
        assert!(index.translation_units.is_empty());
    }

    #[test]
    fn test_cursor_kind_is_declaration() {
        assert!(CXCursorKind::FunctionDecl.is_declaration());
        assert!(CXCursorKind::StructDecl.is_declaration());
        assert!(!CXCursorKind::IntegerLiteral.is_declaration());
    }

    #[test]
    fn test_cursor_kind_is_expression() {
        assert!(CXCursorKind::CallExpr.is_expression());
        assert!(CXCursorKind::StringLiteral.is_expression());
        assert!(!CXCursorKind::FunctionDecl.is_expression());
    }

    #[test]
    fn test_cursor_kind_is_statement() {
        assert!(CXCursorKind::IfStmt.is_statement());
        assert!(CXCursorKind::ReturnStmt.is_statement());
        assert!(!CXCursorKind::TranslationUnit.is_statement());
    }

    #[test]
    fn test_cursor_visit_children() {
        let parent = CXCursor::new(CXCursorKind::FunctionDecl, "main");
        let mut parent_with_children = parent.clone();
        parent_with_children.children = vec![
            CXCursor::new(CXCursorKind::ReturnStmt, "return"),
            CXCursor::new(CXCursorKind::IntegerLiteral, "0"),
        ];

        let mut visited = 0u32;
        parent_with_children.visit_children(|_child| {
            visited += 1;
            CXChildVisitResult::Continue
        });
        assert_eq!(visited, 2);
    }

    #[test]
    fn test_cx_type_pod_check() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        assert!(int_ty.is_pod());

        let ptr_ty = CXType::new(CXTypeKind::Pointer, "int*");
        assert!(ptr_ty.is_pod());

        let func_ty = CXType::new(CXTypeKind::FunctionProto, "void(int)");
        assert!(!func_ty.is_pod());
    }

    #[test]
    fn test_source_location_expansion() {
        let loc = CXSourceLocation {
            file: "test.c".into(),
            line: 42,
            column: 10,
            offset: 500,
        };
        let (file, line, col, offset) = loc.expansion_location();
        assert_eq!(file, "test.c");
        assert_eq!(line, 42);
        assert_eq!(col, 10);
        assert_eq!(offset, 500);
    }

    #[test]
    fn test_source_range_is_null() {
        let loc = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let range = CXSourceRange {
            start: loc.clone(),
            end: loc,
        };
        assert!(range.is_null());
    }

    #[test]
    fn test_diagnostic_creation() {
        let diag = CXDiagnostic::new_error("expected ';'");
        assert!(matches!(diag.severity(), CXDiagnosticSeverity::Error));
        assert_eq!(diag.spelling(), "expected ';'");

        let warn = CXDiagnostic::new_warning("unused variable 'x'");
        assert!(matches!(warn.severity(), CXDiagnosticSeverity::Warning));
    }

    #[test]
    fn test_diagnostic_format() {
        let mut diag = CXDiagnostic::new_error("type mismatch");
        diag.location = CXSourceLocation {
            file: "test.c".into(),
            line: 10,
            column: 5,
            offset: 100,
        };
        let formatted = diag.format();
        assert!(formatted.contains("test.c"));
        assert!(formatted.contains("10:5"));
        assert!(formatted.contains("error"));
    }

    #[test]
    fn test_fixit_creation() {
        let loc = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 5,
            offset: 4,
        };
        let insert = CXFixIt::new_insertion(loc, ";");
        assert_eq!(insert.replacement, ";");
    }

    #[test]
    fn test_code_complete_results() {
        let results = CXCodeCompleteResults::complete_at(
            "test.c",
            10,
            5,
            &[],
            CXTranslationUnitFlags::none(),
        );
        assert_eq!(results.num_results(), 0);
    }

    #[test]
    fn test_translation_unit_parse() {
        let tu = CXTranslationUnit::parse(
            "test.c",
            "int main() { return 0; }",
            &[],
            &[],
            CXTranslationUnitFlags::none(),
        );
        assert_eq!(tu.spelling(), "test.c");
        assert_eq!(tu.num_diagnostics(), 0);
    }

    #[test]
    fn test_unsaved_file_creation() {
        let uf = CXUnsavedFile::new("header.h", "#define FOO 1");
        assert_eq!(uf.filename, "header.h");
        assert_eq!(uf.length, 13);
    }

    #[test]
    fn test_cxcursor_linkage() {
        let cursor = CXCursor::new(CXCursorKind::VarDecl, "x");
        assert_eq!(cursor.linkage(), CXLinkageKind::External);
    }

    #[test]
    fn test_cxcursor_kind_from_u32() {
        assert_eq!(CXCursorKind::from_u32(300), CXCursorKind::TranslationUnit);
        assert_eq!(CXCursorKind::from_u32(8), CXCursorKind::FunctionDecl);
        assert_eq!(CXCursorKind::from_u32(99999), CXCursorKind::NotImplemented);
    }

    #[test]
    fn test_cursor_visit_with_recurse() {
        let leaf1 = CXCursor::new(CXCursorKind::IntegerLiteral, "1");
        let leaf2 = CXCursor::new(CXCursorKind::ReturnStmt, "return");
        let mut parent = CXCursor::new(CXCursorKind::FunctionDecl, "f");
        let child = CXCursor {
            children: vec![leaf1, leaf2],
            ..CXCursor::new(CXCursorKind::CompoundStmt, "body")
        };
        parent.children = vec![child];
        let mut count = 0u32;
        parent.visit_children(|_| {
            count += 1;
            CXChildVisitResult::Recurse
        });
        assert_eq!(count, 1);
    }

    #[test]
    fn test_cursor_visit_with_break() {
        let mut parent = CXCursor::new(CXCursorKind::FunctionDecl, "main");
        parent.children = vec![
            CXCursor::new(CXCursorKind::VarDecl, "a"),
            CXCursor::new(CXCursorKind::VarDecl, "b"),
            CXCursor::new(CXCursorKind::VarDecl, "c"),
        ];
        let mut visited = 0u32;
        parent.visit_children(|_| {
            visited += 1;
            if visited == 2 {
                CXChildVisitResult::Break
            } else {
                CXChildVisitResult::Continue
            }
        });
        assert_eq!(visited, 2);
    }

    #[test]
    fn test_cx_type_function_proto() {
        let mut func_ty = CXType::new(CXTypeKind::FunctionProto, "int(int, float)");
        func_ty.argument_types = vec![
            CXType::new(CXTypeKind::Int, "int"),
            CXType::new(CXTypeKind::Float, "float"),
        ];
        assert_eq!(func_ty.num_arg_types(), 2);
        assert!(func_ty.arg_type(0).is_some());
        assert!(func_ty.arg_type(1).is_some());
        assert!(func_ty.arg_type(2).is_none());
    }

    #[test]
    fn test_cx_type_pointer_pointee() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        let mut ptr_ty = CXType::new(CXTypeKind::Pointer, "int*");
        ptr_ty.pointee_type = Some(Box::new(int_ty));
        let pointee = ptr_ty.pointee_type();
        assert!(pointee.is_some());
        assert_eq!(pointee.unwrap().kind, CXTypeKind::Int);
    }

    #[test]
    fn test_cx_type_array_element() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        let mut arr_ty = CXType::new(CXTypeKind::ConstantArray, "int[10]");
        arr_ty.array_element_type = Some(Box::new(int_ty));
        arr_ty.array_size = 10;
        let (elem, size) = arr_ty.array_element_type();
        assert!(elem.is_some());
        assert_eq!(size, 10);
    }

    #[test]
    fn test_diagnostic_with_fixits() {
        let mut diag = CXDiagnostic::new_error("use of undeclared identifier");
        let loc = CXSourceLocation {
            file: "test.c".into(),
            line: 5,
            column: 10,
            offset: 45,
        };
        let fixit = CXFixIt::new_insertion(loc, "int x;");
        diag.fixits.push(fixit);
        assert_eq!(diag.num_fixits(), 1);
        assert!(diag.fixit(0).is_some());
        assert!(diag.fixit(1).is_none());
    }

    #[test]
    fn test_diagnostic_children() {
        let mut diag = CXDiagnostic::new_error("type mismatch");
        let note = CXDiagnostic::new_note("candidate function not viable");
        diag.children.push(note);
        assert_eq!(diag.children().len(), 1);
    }

    #[test]
    fn test_diagnostic_disable_option() {
        let diag =
            CXDiagnostic::new_warning("unused variable").with_disable_option("-Wunused-variable");
        assert_eq!(diag.disable_option.as_deref(), Some("-Wunused-variable"));
    }

    #[test]
    fn test_code_completion_sort_by_priority() {
        let mut results = CXCodeCompleteResults {
            results: vec![
                CXCompletionResult {
                    kind: CXCompletionKind::Function,
                    completion_string: CXCompletionString {
                        chunks: vec![],
                        priority: 1,
                        availability: CXAvailabilityKind::Available,
                        brief_comment: None,
                    },
                    priority: 30,
                },
                CXCompletionResult {
                    kind: CXCompletionKind::Variable,
                    completion_string: CXCompletionString {
                        chunks: vec![],
                        priority: 0,
                        availability: CXAvailabilityKind::Available,
                        brief_comment: None,
                    },
                    priority: 80,
                },
            ],
            context: None,
        };
        results.sort_by_priority();
        assert_eq!(results.results[0].priority, 80);
        assert_eq!(results.results[1].priority, 30);
    }

    #[test]
    fn test_completion_chunk_kinds() {
        let chunk = CXCompletionChunk {
            kind: CXCompletionChunkKind::TypedText,
            text: "printf".into(),
            annotation: Some("int printf(const char*, ...)".into()),
        };
        assert_eq!(chunk.text, "printf");
        assert!(chunk.annotation.is_some());
    }

    #[test]
    fn test_source_range_range_locations() {
        let start = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let end = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 10,
            offset: 9,
        };
        let range = CXSourceRange { start, end };
        let (s, e) = range.range_locations();
        assert_eq!(s.line, 1);
        assert_eq!(e.column, 10);
    }

    #[test]
    fn test_unsaved_file_multiple() {
        let f1 = CXUnsavedFile::new("a.h", "int foo(void);");
        let f2 = CXUnsavedFile::new("b.h", "int bar(void);");
        assert_eq!(f1.filename, "a.h");
        assert_eq!(f2.filename, "b.h");
        assert_ne!(f1.length, f2.length);
    }

    #[test]
    fn test_cxdiagnostic_severity_all() {
        let err = CXDiagnostic::new_error("e");
        let warn = CXDiagnostic::new_warning("w");
        let note = CXDiagnostic::new_note("n");
        assert!(matches!(err.severity(), CXDiagnosticSeverity::Error));
        assert!(matches!(warn.severity(), CXDiagnosticSeverity::Warning));
        assert!(matches!(note.severity(), CXDiagnosticSeverity::Note));
    }

    // ── New libclang API tests ─────────────────────────────────────

    #[test]
    fn test_clang_getCursorKind() {
        let cursor = CXCursor::new(CXCursorKind::FunctionDecl, "main");
        assert_eq!(clang_getCursorKind(&cursor), CXCursorKind::FunctionDecl);
        let stmt = CXCursor::new(CXCursorKind::ReturnStmt, "return");
        assert_eq!(clang_getCursorKind(&stmt), CXCursorKind::ReturnStmt);
    }

    #[test]
    fn test_clang_getCursorSpelling() {
        let cursor = CXCursor::new(CXCursorKind::VarDecl, "my_variable");
        assert_eq!(clang_getCursorSpelling(&cursor), "my_variable");
    }

    #[test]
    fn test_clang_getCursorDisplayName() {
        let cursor = CXCursor::new(CXCursorKind::FunctionDecl, "compute");
        assert_eq!(clang_getCursorDisplayName(&cursor), "compute");
    }

    #[test]
    fn test_clang_getTypeSpelling() {
        let ty = CXType::new(CXTypeKind::Int, "int");
        assert_eq!(clang_getTypeSpelling(&ty), "int");
        let ptr_ty = CXType::new(CXTypeKind::Pointer, "int*");
        assert_eq!(clang_getTypeSpelling(&ptr_ty), "int*");
    }

    #[test]
    fn test_clang_getTypeKindSpelling_all() {
        let kinds = [
            (CXTypeKind::Void, "Void"),
            (CXTypeKind::Int, "Int"),
            (CXTypeKind::Float, "Float"),
            (CXTypeKind::Pointer, "Pointer"),
            (CXTypeKind::Record, "Record"),
            (CXTypeKind::FunctionProto, "FunctionProto"),
            (CXTypeKind::ConstantArray, "ConstantArray"),
        ];
        for (kind, expected) in &kinds {
            assert_eq!(clang_getTypeKindSpelling(*kind), *expected);
        }
    }

    #[test]
    fn test_clang_isConstQualifiedType() {
        let ty = CXType::new(CXTypeKind::Int, "int");
        assert_eq!(clang_isConstQualifiedType(&ty), 0);
        let mut const_ty = CXType::new(CXTypeKind::Int, "const int");
        const_ty.is_const = true;
        assert_eq!(clang_isConstQualifiedType(&const_ty), 1);
    }

    #[test]
    fn test_clang_isVolatileQualifiedType() {
        let ty = CXType::new(CXTypeKind::Int, "int");
        assert_eq!(clang_isVolatileQualifiedType(&ty), 0);
        let mut vol_ty = CXType::new(CXTypeKind::Int, "volatile int");
        vol_ty.is_volatile = true;
        assert_eq!(clang_isVolatileQualifiedType(&vol_ty), 1);
    }

    #[test]
    fn test_clang_getPointeeType() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        let mut ptr_ty = CXType::new(CXTypeKind::Pointer, "int*");
        ptr_ty.pointee_type = Some(Box::new(int_ty.clone()));
        let pointee = clang_getPointeeType(&ptr_ty);
        assert_eq!(pointee.kind, CXTypeKind::Int);
    }

    #[test]
    fn test_clang_getArraySize() {
        let mut arr = CXType::new(CXTypeKind::ConstantArray, "int[10]");
        arr.array_size = 10;
        assert_eq!(clang_getArraySize(&arr), 10);
        let incomplete = CXType::new(CXTypeKind::IncompleteArray, "int[]");
        assert_eq!(clang_getArraySize(&incomplete), 0);
    }

    #[test]
    fn test_clang_Type_getSizeOf() {
        let ty = CXType::new(CXTypeKind::Int, "int");
        ty.size(); // just verify no panic
    }

    #[test]
    fn test_clang_getEnumConstantDeclValue() {
        let cursor = CXCursor::new(CXCursorKind::EnumConstantDecl, "42");
        assert_eq!(clang_getEnumConstantDeclValue(&cursor), 42);
        let cursor2 = CXCursor::new(CXCursorKind::EnumConstantDecl, "0");
        assert_eq!(clang_getEnumConstantDeclValue(&cursor2), 0);
    }

    #[test]
    fn test_clang_getEnumConstantDeclUnsignedValue() {
        let cursor = CXCursor::new(CXCursorKind::EnumConstantDecl, "100");
        assert_eq!(clang_getEnumConstantDeclUnsignedValue(&cursor), 100);
    }

    #[test]
    fn test_clang_getFieldDeclBitWidth() {
        let mut cursor = CXCursor::new(CXCursorKind::FieldDecl, "x");
        cursor.ty = Some(CXType::new(CXTypeKind::Int, "int : 3"));
        assert_eq!(clang_getFieldDeclBitWidth(&cursor), 3);
        let cursor2 = CXCursor::new(CXCursorKind::FieldDecl, "y");
        assert_eq!(clang_getFieldDeclBitWidth(&cursor2), -1);
    }

    #[test]
    fn test_clang_Cursor_getNumArguments() {
        let mut cursor = CXCursor::new(CXCursorKind::CallExpr, "printf");
        cursor.children = vec![
            CXCursor::new(CXCursorKind::StringLiteral, "\"hello\""),
            CXCursor::new(CXCursorKind::IntegerLiteral, "42"),
        ];
        assert_eq!(clang_Cursor_getNumArguments(&cursor), 2);
    }

    #[test]
    fn test_clang_Cursor_getArgument() {
        let mut cursor = CXCursor::new(CXCursorKind::CallExpr, "foo");
        let arg0 = CXCursor::new(CXCursorKind::IntegerLiteral, "1");
        let arg1 = CXCursor::new(CXCursorKind::IntegerLiteral, "2");
        cursor.children = vec![arg0.clone(), arg1.clone()];
        let result = clang_Cursor_getArgument(&cursor, 0);
        assert!(result.is_some());
        assert_eq!(result.unwrap().spelling, "1");
        assert!(clang_Cursor_getArgument(&cursor, 2).is_none());
    }

    #[test]
    fn test_clang_Cursor_isBitField() {
        let cursor = CXCursor::new(CXCursorKind::FieldDecl, "x");
        assert_eq!(clang_Cursor_isBitField(&cursor), 0);
        let mut bf = CXCursor::new(CXCursorKind::FieldDecl, "x");
        bf.ty = Some(CXType::new(CXTypeKind::Int, "int : 3"));
        assert_eq!(clang_Cursor_isBitField(&bf), 1);
    }

    #[test]
    fn test_clang_Cursor_isAnonymous() {
        let cursor = CXCursor::new(CXCursorKind::StructDecl, "");
        assert_eq!(clang_Cursor_isAnonymous(&cursor), 1);
        let named = CXCursor::new(CXCursorKind::StructDecl, "MyStruct");
        assert_eq!(clang_Cursor_isAnonymous(&named), 0);
    }

    #[test]
    fn test_clang_getCursorVisibility() {
        let cursor = CXCursor::new(CXCursorKind::FunctionDecl, "f");
        assert_eq!(
            clang_getCursorVisibility(&cursor),
            CXVisibilityKind::Default
        );
        let invalid = CXCursor::new(CXCursorKind::NotImplemented, "");
        assert_eq!(
            clang_getCursorVisibility(&invalid),
            CXVisibilityKind::Invalid
        );
    }

    #[test]
    fn test_clang_visitChildren_typed() {
        let mut parent = CXCursor::new(CXCursorKind::FunctionDecl, "main");
        parent.children = vec![
            CXCursor::new(CXCursorKind::VarDecl, "x"),
            CXCursor::new(CXCursorKind::VarDecl, "y"),
        ];
        let mut count = 0u32;
        clang_visitChildren_typed(&parent, |_child, _parent| {
            count += 1;
            CXChildVisitResult::Continue
        });
        assert_eq!(count, 2);
    }

    #[test]
    fn test_clang_getTranslationUnitCursor() {
        let tu =
            CXTranslationUnit::parse("test.c", "int x;", &[], &[], CXTranslationUnitFlags::none());
        let cursor = clang_getTranslationUnitCursor(&tu);
        assert!(cursor.kind == CXCursorKind::TranslationUnit || cursor.spelling == "test.c");
    }

    #[test]
    fn test_clang_getCursorLocation() {
        let cursor = CXCursor::new(CXCursorKind::VarDecl, "x");
        let loc = clang_getCursorLocation(&cursor);
        assert_eq!(loc.line, 1);
        assert_eq!(loc.column, 1);
    }

    #[test]
    fn test_clang_getNullLocation() {
        let loc = clang_getNullLocation();
        assert_eq!(loc.line, 0);
        assert_eq!(loc.column, 0);
        assert!(loc.file.is_empty());
    }

    #[test]
    fn test_clang_getNullRange() {
        let range = clang_getNullRange();
        assert!(range.is_null());
    }

    #[test]
    fn test_clang_equalTypes() {
        let t1 = CXType::new(CXTypeKind::Int, "int");
        let t2 = CXType::new(CXTypeKind::Int, "int");
        let t3 = CXType::new(CXTypeKind::Float, "float");
        assert_eq!(clang_equalTypes(&t1, &t2), 1);
        assert_eq!(clang_equalTypes(&t1, &t3), 0);
    }

    #[test]
    fn test_clang_getCanonicalType() {
        let ty = CXType::new(CXTypeKind::Typedef, "my_int");
        let canonical = clang_getCanonicalType(&ty);
        assert_eq!(canonical.kind, CXTypeKind::Typedef);
    }

    #[test]
    fn test_clang_getTypeDeclaration() {
        let struct_ty = CXType::new(CXTypeKind::Record, "MyStruct");
        let cursor = clang_getTypeDeclaration(&struct_ty);
        assert_eq!(cursor.kind, CXCursorKind::StructDecl);
        assert_eq!(cursor.spelling, "MyStruct");
    }

    #[test]
    fn test_clang_getNumElements() {
        let mut arr = CXType::new(CXTypeKind::ConstantArray, "int[10]");
        arr.array_size = 10;
        assert_eq!(clang_getNumElements(&arr), 10);
    }

    #[test]
    fn test_clang_getCursorLanguage() {
        let cursor = CXCursor::new(CXCursorKind::FunctionDecl, "f");
        assert_eq!(clang_getCursorLanguage(&cursor), 1); // C
    }

    #[test]
    fn test_cx_token_creation() {
        let loc = CXSourceLocation {
            file: "t.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let tok = CXToken::new(2, "identifier", loc);
        assert_eq!(tok.kind, 2);
        assert_eq!(tok.spelling, "identifier");
    }

    #[test]
    fn test_clang_getTokenKind() {
        assert_eq!(clang_getTokenKind(0), "punctuation");
        assert_eq!(clang_getTokenKind(1), "keyword");
        assert_eq!(clang_getTokenKind(2), "identifier");
        assert_eq!(clang_getTokenKind(3), "literal");
        assert_eq!(clang_getTokenKind(4), "comment");
        assert_eq!(clang_getTokenKind(999), "unknown");
    }

    #[test]
    fn test_clang_getTokenSpelling() {
        let tu =
            CXTranslationUnit::parse("test.c", "int x;", &[], &[], CXTranslationUnitFlags::none());
        let loc = CXSourceLocation {
            file: "t.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let tok = CXToken::new(2, "int", loc);
        assert_eq!(clang_getTokenSpelling(&tu, &tok), "int");
    }

    #[test]
    fn test_clang_getTokenLocation() {
        let tu =
            CXTranslationUnit::parse("test.c", "int x;", &[], &[], CXTranslationUnitFlags::none());
        let loc = CXSourceLocation {
            file: "t.c".into(),
            line: 5,
            column: 3,
            offset: 20,
        };
        let tok = CXToken::new(2, "x", loc);
        let result = clang_getTokenLocation(&tu, &tok);
        assert_eq!(result.line, 5);
    }

    #[test]
    fn test_clang_Cursor_getTranslationUnit() {
        let cursor = CXCursor::new(CXCursorKind::FunctionDecl, "f");
        let tu = clang_Cursor_getTranslationUnit(&cursor);
        assert_eq!(tu.cursors.len(), 1);
        assert_eq!(tu.cursors[0].spelling, "f");
    }

    #[test]
    fn test_clang_isPODType() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        assert_eq!(clang_isPODType(&int_ty), 1);
        let func_ty = CXType::new(CXTypeKind::FunctionProto, "void()");
        assert_eq!(clang_isPODType(&func_ty), 0);
    }

    #[test]
    fn test_clang_getElementType() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        let mut arr = CXType::new(CXTypeKind::ConstantArray, "int[5]");
        arr.array_element_type = Some(Box::new(int_ty.clone()));
        arr.array_size = 5;
        let elem = clang_getElementType(&arr);
        assert_eq!(elem.kind, CXTypeKind::Int);
    }

    #[test]
    fn test_clang_equalLocations() {
        let loc1 = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let loc2 = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let loc3 = CXSourceLocation {
            file: "b.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        assert_eq!(clang_equalLocations(&loc1, &loc2), 1);
        assert_eq!(clang_equalLocations(&loc1, &loc3), 0);
    }

    #[test]
    fn test_clang_equalRanges() {
        let loc1 = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let loc2 = CXSourceLocation {
            file: "a.c".into(),
            line: 2,
            column: 1,
            offset: 10,
        };
        let loc3 = CXSourceLocation {
            file: "b.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let r1 = CXSourceRange {
            start: loc1.clone(),
            end: loc2.clone(),
        };
        let r2 = CXSourceRange {
            start: loc1,
            end: loc2,
        };
        let r3 = CXSourceRange {
            start: loc3.clone(),
            end: loc3,
        };
        assert_eq!(clang_equalRanges(&r1, &r2), 1);
        assert_eq!(clang_equalRanges(&r1, &r3), 0);
    }

    #[test]
    fn test_clang_getFileName() {
        let loc = CXSourceLocation {
            file: "hello.c".into(),
            line: 10,
            column: 5,
            offset: 100,
        };
        assert_eq!(clang_getFileName(&loc), "hello.c");
    }

    #[test]
    fn test_clang_getLineNumber() {
        let loc = CXSourceLocation {
            file: "a.c".into(),
            line: 42,
            column: 1,
            offset: 0,
        };
        assert_eq!(clang_getLineNumber(&loc), 42);
    }

    #[test]
    fn test_clang_getColumnNumber() {
        let loc = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 15,
            offset: 10,
        };
        assert_eq!(clang_getColumnNumber(&loc), 15);
    }

    #[test]
    fn test_clang_getFileOffset() {
        let loc = CXSourceLocation {
            file: "a.c".into(),
            line: 1,
            column: 1,
            offset: 500,
        };
        assert_eq!(clang_getFileOffset(&loc), 500);
    }

    #[test]
    fn test_clang_getCursorExtent() {
        let mut cursor = CXCursor::new(CXCursorKind::FunctionDecl, "main");
        cursor.location = CXSourceLocation {
            file: "a.c".into(),
            line: 5,
            column: 1,
            offset: 100,
        };
        cursor.extent = CXSourceRange {
            start: CXSourceLocation {
                file: "a.c".into(),
                line: 5,
                column: 1,
                offset: 100,
            },
            end: CXSourceLocation {
                file: "a.c".into(),
                line: 10,
                column: 1,
                offset: 200,
            },
        };
        let extent = clang_getCursorExtent(&cursor);
        assert_eq!(extent.start.line, 5);
        assert_eq!(extent.end.line, 10);
    }

    #[test]
    fn test_clang_isRestrictQualifiedType() {
        let ty = CXType::new(CXTypeKind::Int, "int");
        assert_eq!(clang_isRestrictQualifiedType(&ty), 0);
        let mut restrict_ty = CXType::new(CXTypeKind::Pointer, "int* restrict");
        restrict_ty.is_restrict = true;
        assert_eq!(clang_isRestrictQualifiedType(&restrict_ty), 1);
    }

    #[test]
    fn test_clang_getArrayElementType() {
        let int_ty = CXType::new(CXTypeKind::Int, "int");
        let mut arr = CXType::new(CXTypeKind::ConstantArray, "int[5]");
        arr.array_element_type = Some(Box::new(int_ty.clone()));
        arr.array_size = 5;
        let elem = clang_getArrayElementType(&arr);
        assert_eq!(elem.kind, CXTypeKind::Int);
    }

    #[test]
    fn test_clang_Type_getSizeOf_int() {
        let mut ty = CXType::new(CXTypeKind::Int, "int");
        ty.size = 4;
        assert_eq!(clang_Type_getSizeOf(&ty), 4);
    }

    #[test]
    fn test_clang_Type_getAlignOf_int() {
        let mut ty = CXType::new(CXTypeKind::Int, "int");
        ty.alignment = 4;
        assert_eq!(clang_Type_getAlignOf(&ty), 4);
    }

    #[test]
    fn test_clang_Type_getOffsetOf_unknown() {
        let ty = CXType::new(CXTypeKind::Record, "MyStruct");
        assert_eq!(clang_Type_getOffsetOf(&ty, "nonexistent"), -1);
    }

    #[test]
    fn test_clang_Cursor_isAnonymousRecordDecl() {
        let anon = CXCursor::new(CXCursorKind::StructDecl, "");
        assert_eq!(clang_Cursor_isAnonymousRecordDecl(&anon), 1);
        let named = CXCursor::new(CXCursorKind::UnionDecl, "MyUnion");
        assert_eq!(clang_Cursor_isAnonymousRecordDecl(&named), 0);
    }

    #[test]
    fn test_clang_Cursor_isInlineNamespace() {
        let ns = CXCursor::new(CXCursorKind::Namespace, "std");
        assert_eq!(clang_Cursor_isInlineNamespace(&ns), 0);
    }

    #[test]
    fn test_clang_Type_getNamedType() {
        let elaborated = CXType::new(CXTypeKind::Elaborated, "struct MyStruct");
        let named = clang_Type_getNamedType(&elaborated);
        assert_eq!(named.kind, CXTypeKind::Record);
    }

    #[test]
    fn test_clang_Type_getClassType() {
        let member_ptr = CXType::new(CXTypeKind::MemberPointer, "int MyClass::*");
        let class_ty = clang_Type_getClassType(&member_ptr);
        assert_eq!(class_ty.kind, CXTypeKind::Record);
    }

    #[test]
    fn test_clang_getNumCursors() {
        let tu = CXTranslationUnit {
            filename: "test.c".into(),
            ast: None,
            diagnostics: vec![],
            cursors: vec![
                CXCursor::new(CXCursorKind::FunctionDecl, "f1"),
                CXCursor::new(CXCursorKind::FunctionDecl, "f2"),
                CXCursor::new(CXCursorKind::VarDecl, "x"),
            ],
            standard: None,
        };
        assert_eq!(clang_getNumCursors(&tu), 3);
    }

    #[test]
    fn test_clang_getCursor_from_tu() {
        let tu = CXTranslationUnit {
            filename: "test.c".into(),
            ast: None,
            diagnostics: vec![],
            cursors: vec![CXCursor::new(CXCursorKind::FunctionDecl, "f")],
            standard: None,
        };
        let cursor = clang_getCursor(&tu, 0);
        assert!(cursor.is_some());
        assert_eq!(cursor.unwrap().spelling, "f");
        assert!(clang_getCursor(&tu, 1).is_none());
    }

    #[test]
    fn test_clang_getTokenExtent() {
        let tu =
            CXTranslationUnit::parse("test.c", "int x;", &[], &[], CXTranslationUnitFlags::none());
        let loc = CXSourceLocation {
            file: "test.c".into(),
            line: 1,
            column: 1,
            offset: 0,
        };
        let mut tok = CXToken::new(2, "int", loc);
        tok.extent = CXSourceRange {
            start: CXSourceLocation {
                file: "test.c".into(),
                line: 1,
                column: 1,
                offset: 0,
            },
            end: CXSourceLocation {
                file: "test.c".into(),
                line: 1,
                column: 3,
                offset: 2,
            },
        };
        let extent = clang_getTokenExtent(&tu, &tok);
        assert_eq!(extent.start.column, 1);
    }

    #[test]
    fn test_clang_getAddressSpace() {
        let ty = CXType::new(CXTypeKind::Pointer, "int*");
        assert_eq!(clang_getAddressSpace(&ty), 0);
    }

    #[test]
    fn test_clang_Type_getNumTemplateArguments() {
        let mut ty = CXType::new(CXTypeKind::Unexposed, "vector<int>");
        ty.num_template_args = 1;
        assert_eq!(clang_Type_getNumTemplateArguments(&ty), 1);
    }
}