kglite 0.11.10

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

use serde_json::json;
use std::path::Path;
use tree_sitter::{Node, Parser, Tree};

use super::shared::{
    compute_complexity, count_lines, extract_comment_annotations, extract_procedure_annotations,
    get_type_parameters, is_generated_or_minified, looks_like_macro_decorator, node_text,
    BRANCH_KINDS_CPP, DEFAULT_COMMENT_TYPES,
};
use super::LanguageParser;
use crate::code_tree::models::{
    AttributeInfo, ClassInfo, ConstantInfo, EnumInfo, FileInfo, FunctionInfo, ParameterInfo,
    ParameterKind, ParseResult, TypeRelationship,
};

pub const C_NOISE_NAMES: &[&str] = &[
    "printf", "fprintf", "sprintf", "snprintf", "scanf", "sscanf", "puts", "fputs", "fgets",
    "getchar", "putchar", "malloc", "calloc", "realloc", "free", "exit", "abort", "atexit", "atoi",
    "atof", "memcpy", "memset", "memmove", "memcmp", "strlen", "strcmp", "strncmp", "strcpy",
    "strncpy", "strcat", "strstr", "strchr", "assert", "fopen", "fclose", "fread", "fwrite",
    "fseek", "ftell",
];

pub const CPP_NOISE_NAMES: &[&str] = &[
    // C noise
    "printf",
    "fprintf",
    "sprintf",
    "snprintf",
    "scanf",
    "sscanf",
    "puts",
    "fputs",
    "fgets",
    "getchar",
    "putchar",
    "malloc",
    "calloc",
    "realloc",
    "free",
    "exit",
    "abort",
    "atexit",
    "atoi",
    "atof",
    "memcpy",
    "memset",
    "memmove",
    "memcmp",
    "strlen",
    "strcmp",
    "strncmp",
    "strcpy",
    "strncpy",
    "strcat",
    "strstr",
    "strchr",
    "assert",
    "fopen",
    "fclose",
    "fread",
    "fwrite",
    "fseek",
    "ftell",
    // C++ extras
    "size",
    "empty",
    "begin",
    "end",
    "cbegin",
    "cend",
    "rbegin",
    "rend",
    "push_back",
    "pop_back",
    "emplace_back",
    "push_front",
    "pop_front",
    "emplace_front",
    "insert",
    "erase",
    "find",
    "count",
    "at",
    "front",
    "back",
    "data",
    "resize",
    "reserve",
    "clear",
    "swap",
    "shrink_to_fit",
    "move",
    "forward",
    "make_shared",
    "make_unique",
    "get",
    "reset",
    "cout",
    "cerr",
    "endl",
    "static_cast",
    "dynamic_cast",
    "reinterpret_cast",
    "const_cast",
];

const NESTED_SCOPES: &[&str] = &["function_definition", "lambda_expression"];

/// Scopes that own their own graph node — the call-walk stops here. Unlike
/// [`NESTED_SCOPES`] (complexity) this excludes `lambda_expression`: a C++
/// lambda gets no node, so calls inside `[&]{ foo(); }` belong to the
/// enclosing function (mirrors the Rust closure handling).
const NAMED_NESTED_SCOPES: &[&str] = &["function_definition"];

const TYPE_NODES: &[&str] = &[
    "primitive_type",
    "type_identifier",
    "sized_type_specifier",
    "struct_specifier",
    "enum_specifier",
    "union_specifier",
    // Generic / template return types: `iteration_proxy<int>`, `std::vector<T>`.
    "template_type",
    "qualified_identifier",
    // NOTE: `type_qualifier` (const, volatile, constexpr) intentionally excluded —
    // it's a qualifier, not a type. get_return_type skips past it to find the real type.
];

pub enum CppFlavor {
    C,
    Cpp,
}

pub struct CppParser {
    flavor: CppFlavor,
}

thread_local! {
    static C_PARSER: std::cell::RefCell<Parser> = {
        let mut p = Parser::new();
        p.set_language(&tree_sitter_c::LANGUAGE.into())
            .expect("loading tree-sitter-c grammar");
        std::cell::RefCell::new(p)
    };
    static CPP_PARSER: std::cell::RefCell<Parser> = {
        let mut p = Parser::new();
        p.set_language(&tree_sitter_cpp::LANGUAGE.into())
            .expect("loading tree-sitter-cpp grammar");
        std::cell::RefCell::new(p)
    };
}

impl CppParser {
    pub fn c() -> Self {
        CppParser {
            flavor: CppFlavor::C,
        }
    }
    pub fn cpp() -> Self {
        CppParser {
            flavor: CppFlavor::Cpp,
        }
    }

    fn parse_tree(&self, source: &[u8]) -> Option<Tree> {
        if self.is_cpp() {
            CPP_PARSER.with(|p| p.borrow_mut().parse(source, None))
        } else {
            C_PARSER.with(|p| p.borrow_mut().parse(source, None))
        }
    }

    fn is_cpp(&self) -> bool {
        matches!(self.flavor, CppFlavor::Cpp)
    }
    fn sep(&self) -> &'static str {
        if self.is_cpp() {
            "::"
        } else {
            "/"
        }
    }

    fn get_name<'a>(node: Node<'a>, source: &'a [u8], name_type: &str) -> Option<&'a str> {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            match child.kind() {
                // Destructor (`~Widget`) and operator overloads (`operator()`,
                // `operator==`, `operator[]`) are single specifier nodes whose
                // full text *is* the name. Keep the `~` / `operator` so graph
                // queries can distinguish them from ordinary members.
                "destructor_name" | "operator_name" => {
                    return Some(node_text(child, source));
                }
                // Out-of-class / nested-qualified / template names —
                // `Foo::bar`, `A::B::c`, `Foo::operator==`, `convert<T>` — drill
                // to the trailing segment recursively.
                "qualified_identifier" | "template_function" | "template_method" => {
                    if let Some(n) = Self::resolve_trailing_name(child, source) {
                        return Some(n);
                    }
                }
                k if k == name_type
                    || k == "type_identifier"
                    || k == "field_identifier"
                    || k == "identifier" =>
                {
                    let text = node_text(child, source);
                    // Skip macro-shaped tokens (SPDLOG_INLINE, FMT_API, etc.) so
                    // the parser doesn't pick them up as the function name.
                    if looks_like_macro_decorator(text) {
                        continue;
                    }
                    return Some(text);
                }
                _ => {}
            }
        }
        None
    }

    /// Resolve the *trailing* (rightmost) name of a possibly-nested declarator:
    /// `A::B::c` → `c`, `Foo::operator==` → `operator==`, `convert<T>` →
    /// `convert`, `~Widget` → `~Widget`. A nested `qualified_identifier` exposes
    /// the trailing piece as its last named child; `template_function`/
    /// `template_method` via the `name` field. Recursion terminates at the leaf.
    fn resolve_trailing_name<'a>(node: Node<'a>, source: &'a [u8]) -> Option<&'a str> {
        match node.kind() {
            // No macro-decorator filter here: by the time we've drilled to the
            // trailing segment of a qualified/template name, the leaf *is* the
            // name — even an all-caps one (`a::b::Ctx::MINUS`, `Lexer::OK`). The
            // filter only belongs in the leading/decorator position (get_name).
            "identifier" | "field_identifier" | "type_identifier" => Some(node_text(node, source)),
            "destructor_name" | "operator_name" => Some(node_text(node, source)),
            // Nested qualified names (`a::b::Ctx::MINUS`) have *no* `name`
            // field — the `::` separators are anonymous and the segments nest
            // left-deep, so the trailing piece is the last *named* child.
            "qualified_identifier" => {
                let mut last = None;
                let mut c = node.walk();
                for sub in node.children(&mut c) {
                    if sub.is_named() {
                        last = Some(sub);
                    }
                }
                last.and_then(|n| Self::resolve_trailing_name(n, source))
            }
            // `convert<T>` — the name is the `name` field (an identifier).
            "template_function" | "template_method" => node
                .child_by_field_name("name")
                .or_else(|| node.named_child(0))
                .and_then(|n| Self::resolve_trailing_name(n, source)),
            _ => None,
        }
    }

    fn get_doc_comment(node: Node, source: &[u8]) -> Option<String> {
        let sibling = node.prev_named_sibling()?;
        if sibling.kind() != "comment" {
            return None;
        }
        let text = node_text(sibling, source).trim();
        if let Some(rest) = text.strip_prefix("/**") {
            let rest = rest.strip_suffix("*/").unwrap_or(rest);
            let mut lines = Vec::new();
            for line in rest.split('\n') {
                let line = line.trim();
                let cleaned = if let Some(r) = line.strip_prefix("* ") {
                    r
                } else if let Some(r) = line.strip_prefix('*') {
                    r
                } else {
                    line
                };
                lines.push(cleaned);
            }
            let joined = lines.join("\n").trim().to_string();
            return if joined.is_empty() {
                None
            } else {
                Some(joined)
            };
        }
        if text.starts_with("///") {
            let mut doc_lines: Vec<String> = Vec::new();
            let mut s = Some(sibling);
            while let Some(cur) = s {
                if cur.kind() != "comment" {
                    break;
                }
                let text = node_text(cur, source).trim();
                let Some(rest) = text.strip_prefix("///") else {
                    break;
                };
                let content = rest.strip_prefix(' ').unwrap_or(rest);
                doc_lines.insert(0, content.to_string());
                s = cur.prev_named_sibling();
            }
            if doc_lines.is_empty() {
                None
            } else {
                Some(doc_lines.join("\n"))
            }
        } else {
            None
        }
    }

    fn get_signature(node: Node, source: &[u8]) -> String {
        let mut parts: Vec<&str> = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if matches!(
                child.kind(),
                "compound_statement" | "field_declaration_list"
            ) {
                break;
            }
            parts.push(node_text(child, source));
        }
        parts.join(" ")
    }

    fn get_return_type(node: Node, source: &[u8]) -> Option<String> {
        // C/C++ primitive-type keywords. Used to recover return types when
        // tree-sitter-cpp wraps the type keyword in an ERROR node — typically
        // happens when a macro decorator confuses the parser (e.g.
        // `SPDLOG_INLINE void foo()` parses as type_identifier=SPDLOG_INLINE
        // followed by ERROR(void) instead of primitive_type=void).
        const PRIMITIVE_KEYWORDS: &[&str] = &[
            "void", "bool", "char", "int", "short", "long", "float", "double", "signed",
            "unsigned", "size_t", "ssize_t", "auto",
        ];
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            let text = node_text(child, source);
            // Skip macro decorators like `SPDLOG_INLINE`, `FMT_API`. Without
            // this, tree-sitter-cpp may surface them as bare `identifier` or
            // `type_identifier` children, producing return_type="SPDLOG_INLINE"
            // instead of the real type.
            if looks_like_macro_decorator(text) {
                continue;
            }
            // Skip C++ qualifiers — `const`, `volatile`, `constexpr`, `inline`,
            // `static`, `noexcept` etc. They aren't types but appear before the
            // real return type. Without skipping, `constexpr int foo()` returns
            // "constexpr" as the type.
            if matches!(
                child.kind(),
                "type_qualifier" | "storage_class_specifier" | "virtual_specifier"
            ) {
                continue;
            }
            // Recover from tree-sitter ERROR wrappers around primitive types.
            if child.kind() == "ERROR" {
                let trimmed = text.trim();
                if PRIMITIVE_KEYWORDS.contains(&trimmed) {
                    return Some(trimmed.to_string());
                }
                continue;
            }
            if matches!(
                child.kind(),
                "function_declarator" | "identifier" | "pointer_declarator"
            ) {
                break;
            }
            if TYPE_NODES.contains(&child.kind()) {
                return Some(text.to_string());
            }
        }
        None
    }

    fn has_storage_class(node: Node, source: &[u8], specifier: &str) -> bool {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "storage_class_specifier" && node_text(child, source) == specifier {
                return true;
            }
        }
        false
    }

    fn extract_calls(body: Node, source: &[u8]) -> Vec<(String, u32)> {
        let mut calls: Vec<(String, u32)> = Vec::new();
        fn walk(node: Node, source: &[u8], out: &mut Vec<(String, u32)>) {
            if node.kind() == "call_expression" {
                let line = node.start_position().row as u32 + 1;
                if let Some(func) = node.child(0) {
                    match func.kind() {
                        "identifier" => {
                            out.push((node_text(func, source).to_string(), line));
                        }
                        "field_expression" => {
                            let field = func.child_by_field_name("field");
                            let argument = func.child_by_field_name("argument");
                            match (field, argument) {
                                (Some(f), Some(a)) => {
                                    let field_name = node_text(f, source);
                                    let arg_text = node_text(a, source);
                                    let hint = arg_text
                                        .rsplit('.')
                                        .next()
                                        .and_then(|p| p.rsplit("->").next())
                                        .unwrap_or(arg_text);
                                    out.push((format!("{}.{}", hint, field_name), line));
                                }
                                (Some(f), None) => {
                                    out.push((node_text(f, source).to_string(), line));
                                }
                                _ => {}
                            }
                        }
                        "scoped_identifier" => {
                            let text = node_text(func, source);
                            let parts: Vec<&str> = text.split("::").collect();
                            if parts.len() >= 2 {
                                out.push((
                                    format!(
                                        "{}.{}",
                                        parts[parts.len() - 2],
                                        parts[parts.len() - 1]
                                    ),
                                    line,
                                ));
                            } else if let Some(last) = parts.last() {
                                out.push(((*last).to_string(), line));
                            }
                        }
                        _ => {}
                    }
                }
            }
            let mut cursor = node.walk();
            for child in node.children(&mut cursor) {
                if !NAMED_NESTED_SCOPES.contains(&child.kind()) {
                    walk(child, source, out);
                }
            }
        }
        walk(body, source, &mut calls);
        calls
    }

    fn file_to_module_path(filepath: &Path, src_root: &Path) -> String {
        let rel = filepath.strip_prefix(src_root).unwrap_or(filepath);
        let mut parts: Vec<String> = rel
            .components()
            .filter_map(|c| c.as_os_str().to_str().map(str::to_string))
            .collect();
        if let Some(last) = parts.last_mut() {
            for ext in [".hpp", ".cpp", ".cxx", ".hxx", ".hh", ".cc", ".h", ".c"] {
                if let Some(stem) = last.strip_suffix(ext) {
                    *last = stem.to_string();
                    break;
                }
            }
        }
        parts.join("/")
    }

    fn extract_struct_fields(
        node: Node,
        source: &[u8],
        owner_qname: &str,
        rel_path: &str,
    ) -> Vec<AttributeInfo> {
        let mut out = Vec::new();
        let sep = if owner_qname.contains("::") {
            "::"
        } else {
            "."
        };
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() != "field_declaration_list" {
                continue;
            }
            let mut fc = child.walk();
            for field in child.children(&mut fc) {
                if field.kind() != "field_declaration" {
                    continue;
                }
                let mut type_ann: Option<String> = None;
                let mut names: Vec<String> = Vec::new();
                let mut inner = field.walk();
                for fc2 in field.children(&mut inner) {
                    if TYPE_NODES.contains(&fc2.kind()) {
                        type_ann = Some(node_text(fc2, source).to_string());
                    } else if fc2.kind() == "field_identifier" {
                        names.push(node_text(fc2, source).to_string());
                    } else if matches!(fc2.kind(), "pointer_declarator" | "array_declarator") {
                        let mut ic = fc2.walk();
                        for sub in fc2.children(&mut ic) {
                            if sub.kind() == "field_identifier" {
                                names.push(node_text(sub, source).to_string());
                                break;
                            }
                        }
                    }
                }
                for name in names {
                    out.push(AttributeInfo {
                        qualified_name: format!("{}{}{}", owner_qname, sep, name),
                        owner_qualified_name: owner_qname.to_string(),
                        type_annotation: type_ann.clone(),
                        visibility: "public".into(),
                        file_path: rel_path.to_string(),
                        line_number: field.start_position().row as u32 + 1,
                        default_value: None,
                        name,
                    });
                }
            }
        }
        out
    }

    /// Walk a node tree (typically a `parenthesized_declarator`) looking for
    /// a buried `function_declarator`. Used to unwrap macro-decorated function
    /// definitions like `JSON_HEDLEY_NON_NULL(3) Foo(int x)`, where tree-sitter-cpp
    /// puts the real declarator inside `parenthesized_declarator > ERROR >
    /// function_declarator`.
    fn find_buried_function_declarator(node: Node) -> Option<Node> {
        // Iterative DFS — avoid blowing the stack on weird ASTs.
        let mut stack = vec![node];
        while let Some(n) = stack.pop() {
            if n.kind() == "function_declarator" {
                return Some(n);
            }
            let mut cursor = n.walk();
            for c in n.children(&mut cursor) {
                stack.push(c);
            }
        }
        None
    }

    fn get_enum_variants(node: Node, source: &[u8]) -> Vec<String> {
        let mut out = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "enumerator_list" {
                let mut ec = child.walk();
                for sub in child.children(&mut ec) {
                    if sub.kind() == "enumerator" {
                        if let Some(n) = Self::get_name(sub, source, "identifier") {
                            out.push(n.to_string());
                        }
                    }
                }
            }
        }
        out
    }

    fn parse_function(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        is_method: bool,
        owner: Option<&str>,
    ) -> FunctionInfo {
        let mut name = "unknown".to_string();
        let mut declarator: Option<Node> = None;
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if matches!(
                child.kind(),
                "function_declarator" | "pointer_declarator" | "reference_declarator"
            ) {
                declarator = Some(child);
                break;
            }
            // Macro-decorated constructors like `JSON_HEDLEY_NON_NULL(3) Foo(...)`
            // produce a `parenthesized_declarator` containing the macro args (3)
            // followed by an ERROR wrapping the real `function_declarator`.
            // Walk through the wrapper to find the buried declarator.
            if child.kind() == "parenthesized_declarator" {
                if let Some(buried) = Self::find_buried_function_declarator(child) {
                    declarator = Some(buried);
                    break;
                }
            }
        }
        // Unwrap pointer_declarator and reference_declarator wrappers — both
        // appear when the return type is `T *` or `T &`. The real
        // function_declarator lives inside.
        while let Some(d) = declarator {
            if matches!(d.kind(), "pointer_declarator" | "reference_declarator") {
                let mut dc = d.walk();
                let mut found: Option<Node> = None;
                for c in d.children(&mut dc) {
                    if c.kind() == "function_declarator" {
                        found = Some(c);
                        break;
                    }
                }
                if let Some(f) = found {
                    declarator = Some(f);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        if let Some(d) = declarator {
            if let Some(fn_name) = Self::get_name(d, source, "identifier") {
                name = fn_name.to_string();
            }
        }
        let sep = self.sep();
        let prefix = match owner {
            Some(o) => format!("{}{}{}", module_path, sep, o),
            None => module_path.to_string(),
        };
        let qualified_name = format!("{}{}{}", prefix, sep, name);

        let mut body: Option<Node> = None;
        let mut cursor2 = node.walk();
        for child in node.children(&mut cursor2) {
            if child.kind() == "compound_statement" {
                body = Some(child);
                break;
            }
        }

        let is_static = Self::has_storage_class(node, source, "static");
        let visibility = if is_static { "private" } else { "public" };
        let calls = body
            .map(|b| Self::extract_calls(b, source))
            .unwrap_or_default();
        let parameters = Self::extract_parameters(declarator, source);
        let param_count = Some(
            parameters
                .iter()
                .filter(|p| p.kind != ParameterKind::Receiver)
                .count() as u32,
        );
        let (branch_count, max_nesting) = match body {
            Some(b) => {
                let (c, n) = compute_complexity(b, BRANCH_KINDS_CPP, NESTED_SCOPES);
                (Some(c), Some(n))
            }
            None => (None, None),
        };
        let is_recursive = Some(calls.iter().any(|(n, _)| n == &name));
        let docstring = Self::get_doc_comment(node, source);
        let procedure_names = extract_procedure_annotations(docstring.as_deref());

        FunctionInfo {
            visibility: visibility.into(),
            is_async: false,
            is_method,
            signature: Self::get_signature(node, source),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            end_line: Some(node.end_position().row as u32 + 1),
            docstring,
            return_type: Self::get_return_type(node, source),
            decorators: Vec::new(),
            calls,
            references: Vec::new(),
            function_refs: Vec::new(),
            type_parameters: None,
            parameters,
            branch_count,
            param_count,
            max_nesting,
            is_recursive,
            procedure_names,
            metadata: Default::default(),
            qualified_name,
            name,
        }
    }

    /// Extract structured parameters from a C/C++ function definition.
    ///
    /// `declarator` is the resolved `function_declarator` (or None for malformed
    /// input). The parameters live in a `parameter_list` child of the declarator.
    /// tree-sitter-cpp wraps each parameter in a `parameter_declaration`.
    fn extract_parameters(declarator: Option<Node>, source: &[u8]) -> Vec<ParameterInfo> {
        let mut out = Vec::new();
        let Some(declarator) = declarator else {
            return out;
        };
        let mut cursor = declarator.walk();
        let Some(params_node) = declarator
            .children(&mut cursor)
            .find(|c| c.kind() == "parameter_list")
        else {
            return out;
        };
        let mut pcursor = params_node.walk();
        for child in params_node.children(&mut pcursor) {
            match child.kind() {
                "parameter_declaration" | "optional_parameter_declaration" => {
                    let mut name: Option<String> = None;
                    let mut type_ann: Option<String> = None;
                    let mut tcursor = child.walk();
                    for sub in child.children(&mut tcursor) {
                        let k = sub.kind();
                        if k == "identifier" && name.is_none() {
                            name = Some(node_text(sub, source).to_string());
                        } else if k == "pointer_declarator" || k == "reference_declarator" {
                            // Drill into declarator to find the bound name.
                            let mut dc = sub.walk();
                            for ds in sub.children(&mut dc) {
                                if ds.kind() == "identifier" {
                                    name = Some(node_text(ds, source).to_string());
                                    break;
                                }
                            }
                        } else if k.contains("type")
                            || k == "primitive_type"
                            || k == "qualified_identifier"
                            || k == "struct_specifier"
                            || k == "enum_specifier"
                            || k == "union_specifier"
                            || k == "class_specifier"
                            || k == "sized_type_specifier"
                        {
                            // C-style `struct llama_grammar *` parameters land
                            // here as struct_specifier (not in TYPE_NODES). Same
                            // for `enum X` / `union X` / `class X` parameter types.
                            type_ann = Some(node_text(sub, source).to_string());
                        }
                    }
                    let n = name.unwrap_or_default();
                    if n.is_empty() && type_ann.is_none() {
                        continue;
                    }
                    out.push(ParameterInfo {
                        name: if n.is_empty() { "_".into() } else { n },
                        type_annotation: type_ann,
                        default: None,
                        kind: ParameterKind::Positional,
                    });
                }
                "variadic_parameter" => {
                    out.push(ParameterInfo {
                        name: "...".into(),
                        type_annotation: None,
                        default: None,
                        kind: ParameterKind::Variadic,
                    });
                }
                _ => {}
            }
        }
        out
    }

    fn parse_struct(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
    ) {
        let Some(name) = Self::get_name(node, source, "type_identifier") else {
            return;
        };
        let name = name.to_string();
        let sep = self.sep();
        let qname = format!("{}{}{}", module_path, sep, name);
        result.classes.push(ClassInfo {
            qualified_name: qname.clone(),
            kind: "struct".into(),
            visibility: "public".into(),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            end_line: Some(node.end_position().row as u32 + 1),
            docstring: Self::get_doc_comment(node, source),
            bases: Vec::new(),
            type_parameters: None,
            metadata: Default::default(),
            name: name.clone(),
        });
        result
            .attributes
            .extend(Self::extract_struct_fields(node, source, &qname, rel_path));
    }

    fn parse_enum(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
    ) {
        let Some(name) = Self::get_name(node, source, "type_identifier") else {
            return;
        };
        let name = name.to_string();
        let sep = self.sep();
        result.enums.push(EnumInfo {
            qualified_name: format!("{}{}{}", module_path, sep, name),
            visibility: "public".into(),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            end_line: Some(node.end_position().row as u32 + 1),
            docstring: Self::get_doc_comment(node, source),
            variants: Self::get_enum_variants(node, source),
            variant_details: None,
            name,
        });
    }

    fn parse_typedef(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
    ) {
        let sep = self.sep();
        let mut typedef_name: Option<String> = None;
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "type_identifier" {
                typedef_name = Some(node_text(child, source).to_string());
            }
        }
        let mut cursor2 = node.walk();
        for child in node.children(&mut cursor2) {
            match child.kind() {
                "struct_specifier" => {
                    let struct_name =
                        Self::get_name(child, source, "type_identifier").map(str::to_string);
                    let name = struct_name.or_else(|| typedef_name.clone());
                    let Some(name) = name else {
                        continue;
                    };
                    let qname = format!("{}{}{}", module_path, sep, name);
                    result.classes.push(ClassInfo {
                        qualified_name: qname.clone(),
                        kind: "struct".into(),
                        visibility: "public".into(),
                        file_path: rel_path.to_string(),
                        line_number: node.start_position().row as u32 + 1,
                        end_line: Some(node.end_position().row as u32 + 1),
                        docstring: Self::get_doc_comment(node, source),
                        bases: Vec::new(),
                        type_parameters: None,
                        metadata: Default::default(),
                        name,
                    });
                    result
                        .attributes
                        .extend(Self::extract_struct_fields(child, source, &qname, rel_path));
                    return;
                }
                "enum_specifier" => {
                    let enum_name =
                        Self::get_name(child, source, "type_identifier").map(str::to_string);
                    let name = enum_name.or_else(|| typedef_name.clone());
                    let Some(name) = name else { continue };
                    result.enums.push(EnumInfo {
                        qualified_name: format!("{}{}{}", module_path, sep, name),
                        visibility: "public".into(),
                        file_path: rel_path.to_string(),
                        line_number: node.start_position().row as u32 + 1,
                        end_line: Some(node.end_position().row as u32 + 1),
                        docstring: Self::get_doc_comment(node, source),
                        variants: Self::get_enum_variants(child, source),
                        variant_details: None,
                        name,
                    });
                    return;
                }
                _ => {}
            }
        }
        let Some(name) = typedef_name else { return };
        result.constants.push(ConstantInfo {
            qualified_name: format!("{}{}{}", module_path, sep, name),
            kind: "type_alias".into(),
            type_annotation: None,
            value_preview: Some({
                let sig = Self::get_signature(node, source);
                let take = sig
                    .char_indices()
                    .nth(100)
                    .map(|(i, _)| i)
                    .unwrap_or(sig.len());
                sig[..take].to_string()
            }),
            visibility: "public".into(),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            name,
        });
    }

    fn parse_preproc_include(node: Node, source: &[u8], file_info: &mut FileInfo) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if matches!(child.kind(), "string_literal" | "system_lib_string") {
                let text = node_text(child, source);
                let trimmed = text.trim_matches(|c| c == '"' || c == '<' || c == '>');
                file_info.imports.push(trimmed.to_string());
            }
        }
    }

    fn parse_preproc_def(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
    ) {
        let Some(name) = Self::get_name(node, source, "identifier") else {
            return;
        };
        let name = name.to_string();
        let mut val_text: Option<String> = None;
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "preproc_arg" {
                let text = node_text(child, source).trim();
                let take = text
                    .char_indices()
                    .nth(100)
                    .map(|(i, _)| i)
                    .unwrap_or(text.len());
                val_text = Some(text[..take].to_string());
            }
        }
        let sep = self.sep();
        result.constants.push(ConstantInfo {
            qualified_name: format!("{}{}{}", module_path, sep, name),
            kind: "constant".into(),
            type_annotation: None,
            value_preview: val_text,
            visibility: "public".into(),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            name,
        });
    }

    // ── C++-only helpers ───────────────────────────────────────────

    fn get_base_classes(node: Node, source: &[u8]) -> Vec<String> {
        let mut out = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() != "base_class_clause" {
                continue;
            }
            let mut bc = child.walk();
            for sub in child.children(&mut bc) {
                match sub.kind() {
                    "type_identifier" | "qualified_identifier" => {
                        out.push(node_text(sub, source).to_string());
                    }
                    "template_type" => {
                        let mut tc = sub.walk();
                        for inner in sub.children(&mut tc) {
                            if inner.kind() == "type_identifier" {
                                out.push(node_text(inner, source).to_string());
                                break;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
        out
    }

    fn get_access_specifier_text<'a>(node: Node<'a>, source: &'a [u8]) -> Option<&'a str> {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if matches!(child.kind(), "public" | "private" | "protected") {
                return Some(node_text(child, source));
            }
        }
        let text = node_text(node, source).trim_end_matches(':');
        if matches!(text, "public" | "private" | "protected") {
            Some(text)
        } else {
            None
        }
    }

    fn parse_class_specifier(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
        is_struct: bool,
    ) {
        let Some(name) = Self::get_name(node, source, "type_identifier") else {
            return;
        };
        let name = name.to_string();
        let qname = format!("{}::{}", module_path, name);
        let bases = Self::get_base_classes(node, source);
        let docstring = Self::get_doc_comment(node, source);
        let kind = if is_struct { "struct" } else { "class" };

        result.classes.push(ClassInfo {
            qualified_name: qname.clone(),
            kind: kind.into(),
            visibility: "public".into(),
            file_path: rel_path.to_string(),
            line_number: node.start_position().row as u32 + 1,
            end_line: Some(node.end_position().row as u32 + 1),
            docstring,
            bases: bases.clone(),
            type_parameters: None,
            metadata: Default::default(),
            name: name.clone(),
        });
        for base in &bases {
            result.type_relationships.push(TypeRelationship {
                source_type: name.clone(),
                target_type: Some(base.clone()),
                relationship: "extends".into(),
                methods: Vec::new(),
            });
        }
        let default_vis = if is_struct { "public" } else { "private" };
        self.parse_class_body(
            node,
            source,
            module_path,
            rel_path,
            &name,
            &qname,
            result,
            default_vis,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn parse_class_body(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        class_name: &str,
        class_qname: &str,
        result: &mut ParseResult,
        default_vis: &str,
    ) {
        let mut method_rel = TypeRelationship {
            source_type: class_qname.to_string(),
            target_type: None,
            relationship: "inherent".into(),
            methods: Vec::new(),
        };
        let mut current_vis = default_vis.to_string();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() != "field_declaration_list" {
                continue;
            }
            let mut bc = child.walk();
            for item in child.children(&mut bc) {
                match item.kind() {
                    "access_specifier" => {
                        if let Some(spec) = Self::get_access_specifier_text(item, source) {
                            current_vis = spec.to_string();
                        }
                    }
                    "function_definition" => {
                        let mut fn_info = self.parse_function(
                            item,
                            source,
                            module_path,
                            rel_path,
                            true,
                            Some(class_name),
                        );
                        fn_info.visibility = current_vis.clone();
                        method_rel.methods.push(fn_info.clone());
                        result.functions.push(fn_info);
                    }
                    "declaration" => {
                        let mut ic = item.walk();
                        let has_func_decl = item
                            .children(&mut ic)
                            .any(|c| c.kind() == "function_declarator");
                        if has_func_decl {
                            let mut fn_info = self.parse_function(
                                item,
                                source,
                                module_path,
                                rel_path,
                                true,
                                Some(class_name),
                            );
                            fn_info.visibility = current_vis.clone();
                            method_rel.methods.push(fn_info.clone());
                            result.functions.push(fn_info);
                        } else {
                            self.parse_cpp_field(
                                item,
                                source,
                                rel_path,
                                class_qname,
                                &current_vis,
                                result,
                            );
                        }
                    }
                    "field_declaration" => {
                        // Methods with template return types like `proxy<T> items()`
                        // come through as `field_declaration` containing a
                        // `function_declarator`. Route those to parse_function;
                        // genuine fields (no function_declarator) go to parse_cpp_field.
                        let mut ic = item.walk();
                        let has_func_decl = item
                            .children(&mut ic)
                            .any(|c| c.kind() == "function_declarator");
                        if has_func_decl {
                            let mut fn_info = self.parse_function(
                                item,
                                source,
                                module_path,
                                rel_path,
                                true,
                                Some(class_name),
                            );
                            fn_info.visibility = current_vis.clone();
                            method_rel.methods.push(fn_info.clone());
                            result.functions.push(fn_info);
                        } else {
                            self.parse_cpp_field(
                                item,
                                source,
                                rel_path,
                                class_qname,
                                &current_vis,
                                result,
                            );
                        }
                    }
                    "template_declaration" => {
                        let tparams = get_type_parameters(item, source, "template_parameter_list");
                        let mut tc = item.walk();
                        for sub in item.children(&mut tc) {
                            if sub.kind() == "function_definition" {
                                let mut fn_info = self.parse_function(
                                    sub,
                                    source,
                                    module_path,
                                    rel_path,
                                    true,
                                    Some(class_name),
                                );
                                fn_info.visibility = current_vis.clone();
                                fn_info.metadata.insert("is_template".into(), json!(true));
                                fn_info.type_parameters = tparams.clone();
                                method_rel.methods.push(fn_info.clone());
                                result.functions.push(fn_info);
                            }
                        }
                    }
                    "class_specifier" | "struct_specifier" => {
                        let is_struct = item.kind() == "struct_specifier";
                        let nested_module = format!("{}::{}", module_path, class_name);
                        self.parse_class_specifier(
                            item,
                            source,
                            &nested_module,
                            rel_path,
                            result,
                            is_struct,
                        );
                    }
                    _ => {}
                }
            }
        }
        if !method_rel.methods.is_empty() {
            result.type_relationships.push(method_rel);
        }
    }

    fn parse_cpp_field(
        &self,
        node: Node,
        source: &[u8],
        rel_path: &str,
        class_qname: &str,
        visibility: &str,
        result: &mut ParseResult,
    ) {
        let mut type_ann: Option<String> = None;
        let mut names: Vec<String> = Vec::new();
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            match child.kind() {
                "primitive_type"
                | "type_identifier"
                | "sized_type_specifier"
                | "template_type"
                | "qualified_identifier" => {
                    if type_ann.is_none() {
                        type_ann = Some(node_text(child, source).to_string());
                    }
                }
                "field_identifier" => names.push(node_text(child, source).to_string()),
                "init_declarator" | "pointer_declarator" | "reference_declarator" => {
                    let mut ic = child.walk();
                    for sub in child.children(&mut ic) {
                        if matches!(sub.kind(), "field_identifier" | "identifier") {
                            names.push(node_text(sub, source).to_string());
                            break;
                        }
                    }
                }
                _ => {}
            }
        }
        for name in names {
            result.attributes.push(AttributeInfo {
                qualified_name: format!("{}::{}", class_qname, name),
                owner_qualified_name: class_qname.to_string(),
                type_annotation: type_ann.clone(),
                visibility: visibility.to_string(),
                file_path: rel_path.to_string(),
                line_number: node.start_position().row as u32 + 1,
                default_value: None,
                name,
            });
        }
    }

    fn parse_namespace(
        &self,
        node: Node,
        source: &[u8],
        parent_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
        file_info: &mut FileInfo,
    ) {
        let ns_name = Self::get_name(node, source, "identifier").map(str::to_string);
        let ns_path = match &ns_name {
            Some(n) => {
                file_info.submodule_declarations.push(n.clone());
                format!("{}::{}", parent_path, n)
            }
            None => parent_path.to_string(),
        };
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if child.kind() == "declaration_list" {
                let mut dc = child.walk();
                for item in child.children(&mut dc) {
                    self.parse_cpp_top_level(item, source, &ns_path, rel_path, result, file_info);
                }
            }
        }
    }

    fn parse_cpp_top_level(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
        file_info: &mut FileInfo,
    ) {
        match node.kind() {
            "function_definition" => {
                result.functions.push(self.parse_function(
                    node,
                    source,
                    module_path,
                    rel_path,
                    false,
                    None,
                ));
            }
            "class_specifier" => {
                self.parse_class_specifier(node, source, module_path, rel_path, result, false);
            }
            "struct_specifier" => {
                self.parse_class_specifier(node, source, module_path, rel_path, result, true);
            }
            "declaration" => {
                let mut cursor = node.walk();
                let mut handled = false;
                for sub in node.children(&mut cursor) {
                    match sub.kind() {
                        "class_specifier" => {
                            self.parse_class_specifier(
                                sub,
                                source,
                                module_path,
                                rel_path,
                                result,
                                false,
                            );
                            handled = true;
                            break;
                        }
                        "struct_specifier" => {
                            self.parse_class_specifier(
                                sub,
                                source,
                                module_path,
                                rel_path,
                                result,
                                true,
                            );
                            handled = true;
                            break;
                        }
                        "enum_specifier" => {
                            self.parse_enum(sub, source, module_path, rel_path, result);
                            handled = true;
                            break;
                        }
                        _ => {}
                    }
                }
                if !handled {
                    let mut cursor2 = node.walk();
                    if node
                        .children(&mut cursor2)
                        .any(|c| c.kind() == "function_declarator")
                    {
                        result.functions.push(self.parse_function(
                            node,
                            source,
                            module_path,
                            rel_path,
                            false,
                            None,
                        ));
                    }
                }
            }
            "enum_specifier" => self.parse_enum(node, source, module_path, rel_path, result),
            "namespace_definition" => {
                self.parse_namespace(node, source, module_path, rel_path, result, file_info)
            }
            "template_declaration" => {
                let tparams = get_type_parameters(node, source, "template_parameter_list");
                let n_funcs = result.functions.len();
                let n_classes = result.classes.len();
                let mut cursor = node.walk();
                for sub in node.children(&mut cursor) {
                    if matches!(
                        sub.kind(),
                        "function_definition"
                            | "class_specifier"
                            | "struct_specifier"
                            | "declaration"
                    ) {
                        self.parse_cpp_top_level(
                            sub,
                            source,
                            module_path,
                            rel_path,
                            result,
                            file_info,
                        );
                    }
                }
                if let Some(tp) = tparams {
                    for fn_info in &mut result.functions[n_funcs..] {
                        fn_info.metadata.insert("is_template".into(), json!(true));
                        fn_info.type_parameters = Some(tp.clone());
                    }
                    for cls in &mut result.classes[n_classes..] {
                        cls.type_parameters = Some(tp.clone());
                    }
                }
            }
            "type_definition" => self.parse_typedef(node, source, module_path, rel_path, result),
            "preproc_include" => Self::parse_preproc_include(node, source, file_info),
            "preproc_def" => self.parse_preproc_def(node, source, module_path, rel_path, result),
            "linkage_specification" => {
                let n_funcs = result.functions.len();
                let mut cursor = node.walk();
                for sub in node.children(&mut cursor) {
                    match sub.kind() {
                        "declaration_list" => {
                            let mut dc = sub.walk();
                            for item in sub.children(&mut dc) {
                                self.parse_cpp_top_level(
                                    item,
                                    source,
                                    module_path,
                                    rel_path,
                                    result,
                                    file_info,
                                );
                            }
                        }
                        "function_definition" | "declaration" => {
                            self.parse_cpp_top_level(
                                sub,
                                source,
                                module_path,
                                rel_path,
                                result,
                                file_info,
                            );
                        }
                        _ => {}
                    }
                }
                for fn_info in &mut result.functions[n_funcs..] {
                    fn_info.metadata.insert("is_ffi".into(), json!(true));
                    fn_info
                        .metadata
                        .insert("ffi_kind".into(), json!("extern_c"));
                }
            }
            "using_declaration" => {
                let mut cursor = node.walk();
                for sub in node.children(&mut cursor) {
                    if matches!(sub.kind(), "scoped_identifier" | "qualified_identifier") {
                        file_info.imports.push(node_text(sub, source).to_string());
                        break;
                    }
                }
            }
            _ => {}
        }
    }

    fn parse_c_top_level(
        &self,
        node: Node,
        source: &[u8],
        module_path: &str,
        rel_path: &str,
        result: &mut ParseResult,
        file_info: &mut FileInfo,
    ) {
        match node.kind() {
            "function_definition" => {
                result.functions.push(self.parse_function(
                    node,
                    source,
                    module_path,
                    rel_path,
                    false,
                    None,
                ));
            }
            // A bare top-level `struct Foo { … };` / `enum E { … };` is emitted
            // by tree-sitter-c as a direct specifier child (no `declaration`
            // wrapper), mirroring the C++ path above. Without these arms every
            // top-level struct/enum in a pure-C file was silently dropped.
            "struct_specifier" => {
                self.parse_struct(node, source, module_path, rel_path, result);
            }
            "enum_specifier" => self.parse_enum(node, source, module_path, rel_path, result),
            "declaration" => {
                let mut cursor = node.walk();
                let mut handled = false;
                for sub in node.children(&mut cursor) {
                    match sub.kind() {
                        "struct_specifier" => {
                            self.parse_struct(sub, source, module_path, rel_path, result);
                            handled = true;
                        }
                        "enum_specifier" => {
                            self.parse_enum(sub, source, module_path, rel_path, result);
                            handled = true;
                        }
                        _ => {}
                    }
                }
                let _ = handled;
            }
            "type_definition" => self.parse_typedef(node, source, module_path, rel_path, result),
            "preproc_include" => Self::parse_preproc_include(node, source, file_info),
            "preproc_def" => self.parse_preproc_def(node, source, module_path, rel_path, result),
            _ => {}
        }
    }
}

// ── Export-macro neutralization (pre-parse source fix) ──────────────────────
//
// tree-sitter-cpp has no preprocessor, so an export-visibility macro sitting in
// the `class`/`struct` **keyword slot** — `class KUZU_API Foo { … }` — is read
// as a `function_definition` (`class KUZU_API` → a `class_specifier` named after
// the macro; `Foo` → a bare declarator). The real class is dropped and the
// surrounding declarations frequently desync with it. This is ubiquitous in
// C/C++ libraries that build shared objects (`KUZU_API`, `ARROW_EXPORT`,
// `DUCKDB_API`, `LLVM_ABI`, `__declspec(dllexport)`, `__attribute__((visibility))`).
//
// We blank those keyword-slot macro tokens to equal-length spaces *before*
// parsing, so tree-sitter sees `class           Foo { … }` and extracts the
// class (and its members, and everything after it) correctly. Byte length is
// preserved, so every node position / line number stays exact.

fn is_ident_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Advance past whitespace and `//` / `/* */` comments. Returns the next
/// significant index.
fn skip_ws_and_comments(src: &[u8], mut i: usize) -> usize {
    let n = src.len();
    loop {
        while i < n && src[i].is_ascii_whitespace() {
            i += 1;
        }
        if i + 1 < n && src[i] == b'/' && src[i + 1] == b'/' {
            i += 2;
            while i < n && src[i] != b'\n' {
                i += 1;
            }
            continue;
        }
        if i + 1 < n && src[i] == b'/' && src[i + 1] == b'*' {
            i += 2;
            while i + 1 < n && !(src[i] == b'*' && src[i + 1] == b'/') {
                i += 1;
            }
            i = (i + 2).min(n);
            continue;
        }
        return i;
    }
}

/// Skip a string / char / raw-string literal starting at `i` (which is `"` or
/// `'`, possibly with a raw-string `R"delim(…)delim"` form). Returns the index
/// just past the closing quote.
fn skip_quoted(src: &[u8], i: usize) -> usize {
    let n = src.len();
    let quote = src[i];
    // Raw string: `R"delim( … )delim"` (the `R` is matched by the caller via the
    // preceding byte). We only get here on the `"`; detect a raw string by a
    // preceding `R`.
    if quote == b'"' && i > 0 && src[i - 1] == b'R' {
        // read delimiter up to '('
        let mut j = i + 1;
        let delim_start = j;
        while j < n && src[j] != b'(' && src[j] != b'"' {
            j += 1;
        }
        if j < n && src[j] == b'(' {
            let delim = &src[delim_start..j];
            j += 1; // past '('
                    // find  )delim"
            while j < n {
                if src[j] == b')' && src[j + 1..].starts_with(delim) {
                    let close = j + 1 + delim.len();
                    if close < n && src[close] == b'"' {
                        return close + 1;
                    }
                }
                j += 1;
            }
            return n;
        }
        // not actually a raw string — fall through to normal string handling
    }
    let mut j = i + 1;
    while j < n {
        if src[j] == b'\\' {
            j += 2;
            continue;
        }
        if src[j] == quote {
            return j + 1;
        }
        j += 1;
    }
    n
}

/// True when `text` looks like an export/visibility macro identifier
/// (`KUZU_API`, `ARROW_EXPORT`, `_PUBLIC`, …): all-uppercase / digits / `_`.
fn is_macro_ident(text: &[u8]) -> bool {
    std::str::from_utf8(text)
        .map(looks_like_macro_decorator)
        .unwrap_or(false)
}

/// Skip a `__declspec(…)` / `__attribute__((…))` / `alignas(…)` specifier
/// starting at `i` (the keyword start). Returns the index past the balanced
/// parens. If no `(` follows, returns the index past the keyword.
fn skip_attr_specifier(src: &[u8], i: usize) -> usize {
    let n = src.len();
    let mut j = i;
    while j < n && is_ident_byte(src[j]) {
        j += 1;
    }
    let after_kw = skip_ws_and_comments(src, j);
    if after_kw >= n || src[after_kw] != b'(' {
        return j;
    }
    let mut depth = 0usize;
    let mut k = after_kw;
    while k < n {
        match src[k] {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return k + 1;
                }
            }
            b'"' | b'\'' => {
                k = skip_quoted(src, k);
                continue;
            }
            _ => {}
        }
        k += 1;
    }
    n
}

/// Given `i` positioned just after a `class`/`struct` keyword, scan the keyword
/// slot and return `(continue_index, ranges_to_blank)`. Ranges are the
/// macro/attribute tokens strictly *between* the keyword and the type name.
fn scan_keyword_slot(src: &[u8], start: usize) -> (usize, Vec<(usize, usize)>) {
    let n = src.len();
    let mut edits: Vec<(usize, usize)> = Vec::new();
    let mut pending: Option<(usize, usize)> = None; // last macro-shaped ident seen
    let mut i = start;
    loop {
        i = skip_ws_and_comments(src, i);
        if i >= n {
            break;
        }
        let c = src[i];
        // `__declspec(...)` / `__attribute__((...))` / `alignas(...)`
        if (src[i..].starts_with(b"__declspec")
            || src[i..].starts_with(b"__attribute__")
            || src[i..].starts_with(b"alignas"))
            && (i == 0 || !is_ident_byte(src[i - 1]))
        {
            if let Some(r) = pending.take() {
                edits.push(r); // a real token follows ⇒ the pending ident was a macro
            }
            let end = skip_attr_specifier(src, i);
            edits.push((i, end));
            i = end;
            continue;
        }
        if c.is_ascii_alphabetic() || c == b'_' {
            let s = i;
            while i < n && is_ident_byte(src[i]) {
                i += 1;
            }
            let ident = &src[s..i];
            // contextual keywords that follow the *name* — stop, keep pending name.
            if ident == b"final" || ident == b"override" {
                break;
            }
            // another token follows the previous ident ⇒ that one was a macro.
            if let Some(r) = pending.take() {
                edits.push(r);
            }
            if is_macro_ident(ident) {
                pending = Some((s, i)); // could be a macro or the (ALLCAPS) name; decide later
            } else {
                break; // a normal identifier in the name slot ⇒ it's the type name
            }
        } else {
            break; // `{`, `:`, `;`, `<`, `=`, `,` … ⇒ end of slot; pending = the name
        }
    }
    // A still-pending ident at the stop is the type name itself — never blank it.
    (i, edits)
}

/// See the module comment above. Returns `Cow::Borrowed` when nothing needed
/// rewriting (the overwhelmingly common case — zero allocation).
fn neutralize_export_macros(src: &[u8]) -> std::borrow::Cow<'_, [u8]> {
    let n = src.len();
    let mut edits: Vec<(usize, usize)> = Vec::new();
    let mut i = 0;
    while i < n {
        let c = src[i];
        if c == b'/' && i + 1 < n && (src[i + 1] == b'/' || src[i + 1] == b'*') {
            i = skip_ws_and_comments(src, i);
            continue;
        }
        if c == b'"' || c == b'\'' {
            i = skip_quoted(src, i);
            continue;
        }
        // `class` / `struct` at a word boundary, followed by a non-identifier.
        let is_boundary = i == 0 || !is_ident_byte(src[i - 1]);
        if is_boundary {
            let kwlen = if src[i..].starts_with(b"class") {
                5
            } else if src[i..].starts_with(b"struct") {
                6
            } else {
                0
            };
            if kwlen != 0 {
                let after = i + kwlen;
                if after < n && !is_ident_byte(src[after]) {
                    let (next, slot_edits) = scan_keyword_slot(src, after);
                    edits.extend(slot_edits);
                    i = next;
                    continue;
                }
            }
        }
        i += 1;
    }
    if edits.is_empty() {
        return std::borrow::Cow::Borrowed(src);
    }
    let mut out = src.to_vec();
    for (s, e) in edits {
        for b in &mut out[s..e] {
            if *b != b'\n' {
                *b = b' '; // keep newlines so line numbers are unchanged
            }
        }
    }
    std::borrow::Cow::Owned(out)
}

impl LanguageParser for CppParser {
    fn language_name(&self) -> &'static str {
        if self.is_cpp() {
            "cpp"
        } else {
            "c"
        }
    }
    fn file_extensions(&self) -> &'static [&'static str] {
        if self.is_cpp() {
            &["cpp", "cc", "cxx", "hpp", "hh", "hxx"]
        } else {
            &["c", "h"]
        }
    }
    fn noise_names(&self) -> &'static [&'static str] {
        if self.is_cpp() {
            CPP_NOISE_NAMES
        } else {
            C_NOISE_NAMES
        }
    }

    fn parse_file(&self, filepath: &Path, src_root: &Path) -> ParseResult {
        let Ok(source) = std::fs::read(filepath) else {
            return ParseResult::new();
        };

        let rel_path = filepath
            .strip_prefix(src_root)
            .unwrap_or(filepath)
            .to_string_lossy()
            .replace('\\', "/");
        let module_path = Self::file_to_module_path(filepath, src_root);
        let loc = count_lines(&source);
        let filename = filepath
            .file_name()
            .and_then(|o| o.to_str())
            .unwrap_or("")
            .to_string();
        let stem = filepath
            .file_stem()
            .and_then(|o| o.to_str())
            .unwrap_or("")
            .to_string();
        let is_test = stem.ends_with("_test")
            || stem.ends_with("_tests")
            || stem.starts_with("test_")
            || rel_path.contains("/test/")
            || rel_path.contains("/tests/")
            || rel_path.starts_with("test/")
            || rel_path.starts_with("tests/");

        let language = if self.is_cpp() { "cpp" } else { "c" };

        if let Some(reason) = is_generated_or_minified(&source) {
            let mut r = ParseResult::new();
            r.files.push(FileInfo {
                path: rel_path,
                filename,
                loc,
                module_path,
                language: language.to_string(),
                submodule_declarations: Vec::new(),
                imports: Vec::new(),
                exports: Vec::new(),
                annotations: None,
                is_test,
                skip_reason: Some(reason.to_string()),
            });
            return r;
        }

        // Blank export-visibility macros in the `class`/`struct` keyword slot so
        // tree-sitter-cpp parses `class KUZU_API Foo` as a class, not a function.
        // Byte length is preserved, so node offsets index the *original* source
        // identically — we parse the neutralized bytes but read text from the
        // pristine original.
        let neutralized = neutralize_export_macros(&source);
        let Some(tree) = self.parse_tree(&neutralized) else {
            return ParseResult::new();
        };
        let root = tree.root_node();
        let mut file_info = FileInfo {
            path: rel_path.clone(),
            filename,
            loc,
            module_path: module_path.clone(),
            language: language.to_string(),
            submodule_declarations: Vec::new(),
            imports: Vec::new(),
            exports: Vec::new(),
            annotations: None,
            is_test,
            skip_reason: None,
        };
        let mut result = ParseResult::new();
        let mut cursor = root.walk();
        if self.is_cpp() {
            for child in root.children(&mut cursor) {
                self.parse_cpp_top_level(
                    child,
                    &source,
                    &module_path,
                    &rel_path,
                    &mut result,
                    &mut file_info,
                );
            }
        } else {
            for child in root.children(&mut cursor) {
                self.parse_c_top_level(
                    child,
                    &source,
                    &module_path,
                    &rel_path,
                    &mut result,
                    &mut file_info,
                );
            }
        }
        file_info.annotations = extract_comment_annotations(root, &source, DEFAULT_COMMENT_TYPES);
        result.files.push(file_info);
        result
    }
}

#[cfg(test)]
mod export_macro_tests {
    use super::{neutralize_export_macros, CppParser};
    use crate::code_tree::models::ParseResult;
    use crate::code_tree::parsers::LanguageParser;

    fn neut(s: &str) -> String {
        String::from_utf8(neutralize_export_macros(s.as_bytes()).into_owned()).unwrap()
    }

    fn is_unchanged(s: &str) -> bool {
        matches!(
            neutralize_export_macros(s.as_bytes()),
            std::borrow::Cow::Borrowed(_)
        )
    }

    #[test]
    fn blanks_keyword_slot_macro_preserving_length() {
        for (input, name, macro_tok) in [
            ("class KUZU_API Foo {", "Foo", "KUZU_API"),
            ("struct ARROW_EXPORT Bar {", "Bar", "ARROW_EXPORT"),
        ] {
            let out = neut(input);
            assert_eq!(
                out.len(),
                input.len(),
                "length must be preserved: {input:?}"
            );
            assert!(out.contains(name), "name dropped: {out:?}");
            assert!(!out.contains(macro_tok), "macro not blanked: {out:?}");
            // Only the macro span changed — modulo spaces, the rest is identical.
            assert_eq!(
                out.replace(' ', ""),
                input.replace(macro_tok, "").replace(' ', "")
            );
        }
    }

    #[test]
    fn keeps_real_classes_untouched() {
        // single identifier after the keyword = the name, even if ALLCAPS.
        assert!(is_unchanged("class Foo {"));
        assert!(is_unchanged("class FOO {")); // a real class literally named FOO
        assert!(is_unchanged("struct Plain { int x; };"));
        assert!(is_unchanged("class Foo : public Base {"));
        assert!(is_unchanged("class Foo final {"));
        assert!(is_unchanged("enum class Color { Red };"));
    }

    #[test]
    fn handles_base_clause_and_final_and_allcaps_names() {
        assert_eq!(
            neut("class KUZU_API Foo : Base {"),
            "class          Foo : Base {"
        );
        // ALLCAPS *name* after a macro: blank the macro, keep the name.
        assert_eq!(
            neut("class KUZU_API FOO_T final"),
            "class          FOO_T final"
        );
        // multiple macros in the slot.
        assert_eq!(neut("class M1 M2 Foo {"), "class       Foo {");
    }

    #[test]
    fn ignores_macro_inside_strings_and_comments() {
        assert!(is_unchanged("const char* s = \"class KUZU_API Foo {\";"));
        assert!(is_unchanged("// class KUZU_API Foo {\nint x;"));
        assert!(is_unchanged("/* class KUZU_API Foo */ int y;"));
    }

    #[test]
    fn handles_declspec_attribute_specifiers() {
        let out = neut("class __declspec(dllexport) Baz {");
        assert!(out.contains("Baz {"), "{out}");
        assert!(!out.contains("dllexport"), "{out}");
        assert_eq!(out.len(), "class __declspec(dllexport) Baz {".len());
    }

    fn parse_cpp(src: &str) -> ParseResult {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("hdr.hpp");
        std::fs::write(&file, src).unwrap();
        CppParser::cpp().parse_file(&file, dir.path())
    }

    #[test]
    fn export_macro_class_is_extracted_end_to_end() {
        // The minimal repro from the bug report: the macro-annotated class, the
        // macro-position method, and a following macro-free struct must all land.
        let src = "#define MYLIB_API\n\
                   struct Plain { int x; };\n\
                   class MYLIB_API Foo : public Base {\n\
                   public:\n  MYLIB_API void bar();\n  int field;\n};\n\
                   enum class Color { Red, Green };\n";
        let r = parse_cpp(src);
        let classes: Vec<&str> = r.classes.iter().map(|c| c.name.as_str()).collect();
        assert!(classes.contains(&"Foo"), "Foo class missing: {classes:?}");
        assert!(
            classes.contains(&"Plain"),
            "Plain struct missing: {classes:?}"
        );
        let enums: Vec<&str> = r.enums.iter().map(|e| e.name.as_str()).collect();
        assert!(enums.contains(&"Color"), "Color enum missing: {enums:?}");
        // the macro-annotated class records its base + method, and yields no
        // `unknown`-named functions.
        let foo = r.classes.iter().find(|c| c.name == "Foo").unwrap();
        assert!(
            foo.bases.iter().any(|b| b == "Base"),
            "base lost: {:?}",
            foo.bases
        );
        assert!(
            r.functions.iter().any(|f| f.name == "bar"),
            "method bar missing: {:?}",
            r.functions.iter().map(|f| &f.name).collect::<Vec<_>>()
        );
        assert!(
            !r.functions.iter().any(|f| f.name == "unknown"),
            "degenerate unknown function present"
        );
    }
}