codenexus 0.3.4

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! C language extractor (Adapter pattern, ADR-003, ADR-011).
//!
//! Adapts tree-sitter-c's syntax tree into CodeNexus nodes, edges, and
//! intermediate extraction records ([`ExtractResult`]).
//!
//! # Extracted node types
//!
//! - `function_definition` → [`NodeLabel::Function`]
//! - `declaration` (top-level) → [`NodeLabel::GlobalVar`]
//! - `type_definition` → [`NodeLabel::Typedef`]
//! - `struct_specifier` (with body) → [`NodeLabel::Struct`]
//! - `enum_specifier` (with body) → [`NodeLabel::Enum`]
//! - `preproc_def` → [`NodeLabel::Macro`] (object-like `#define`)
//! - `preproc_function_def` → [`NodeLabel::Macro`] (function-like `#define`)
//!
//! # Extracted records
//!
//! - `preproc_include` → [`ImportInfo`]
//! - `call_expression` → [`CallInfo`]

use tree_sitter::Node;

use crate::model::{Edge, EdgeType, Language, Node as ModelNode, NodeLabel};
use crate::resolve::{FqnGenerator, ScopeContext, ScopeResolverRegistry};

use super::dedupe_qn;
use super::error::{ParseError, Result};
use super::extractor::{ExtractResult, Extractor, ImportInfo, ReadInfo, WriteInfo};
use super::parser_factory::ParserFactory;

/// C language tree-sitter extractor (Adapter pattern).
pub struct CExtractor {
    _priv: (),
}

impl CExtractor {
    /// Creates a new `CExtractor`.
    #[must_use]
    pub const fn new() -> Self {
        Self { _priv: () }
    }
}

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

impl Extractor for CExtractor {
    fn language(&self) -> Language {
        Language::C
    }

    fn extract(&self, source: &str, file_path: &str, project: &str) -> Result<ExtractResult> {
        let mut result = ExtractResult::new(file_path, Language::C);
        let mut parser = ParserFactory::create_parser(Language::C)?;
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| ParseError::ParseFailed {
                file_path: file_path.to_string(),
            })?;
        let root = tree.root_node();
        // Walk all named children of the translation_unit.
        let registry = ScopeResolverRegistry::new();
        let ctx = VisitContext {
            file_path,
            project,
            current_func: None,
            current_parent: None,
            resolver: &registry,
        };
        for i in 0..root.named_child_count() as u32 {
            let child = match root.named_child(i) {
                Some(c) => c,
                None => continue,
            };
            visit_node(child, source, &ctx, &mut result);
        }
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// Tree-walking helpers
// ---------------------------------------------------------------------------

/// 不可变的遍历上下文,在 visit_node/visit_children 之间传递。
/// 封装 ADR-005 的 current_parent 和 current_func 语义。
struct VisitContext<'a> {
    file_path: &'a str,
    project: &'a str,
    current_func: Option<&'a str>,
    current_parent: Option<&'a str>,
    /// Scope resolver registry (design.md D3).
    resolver: &'a ScopeResolverRegistry,
}

fn visit_node(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    match node.kind() {
        "function_definition" => {
            // Use ScopeResolver to detect C++ namespace/class/struct blocks
            // misparsed as function_definition (design.md D3). The resolver
            // returns the appropriate NodeLabel, centralizing the quirk.
            let scope_ctx = ScopeContext {
                source,
                file_path: ctx.file_path,
                project: ctx.project,
                current_parent: ctx.current_parent,
            };
            let scope = ctx
                .resolver
                .get(Language::C)
                .and_then(|r| r.resolve(node, &scope_ctx));
            match scope.as_ref().map(|s| s.label) {
                Some(NodeLabel::Namespace) | Some(NodeLabel::Class) | Some(NodeLabel::Struct) => {
                    // C++ scope block misparsed as function_definition.
                    let scope_name = scope.as_ref().map(|s| s.name.as_str());
                    let combined = combine_scope(ctx.current_parent, scope_name);
                    for i in 0..node.named_child_count() as u32 {
                        if let Some(child) = node.named_child(i) {
                            if child.kind() == "compound_statement" {
                                let child_ctx = VisitContext {
                                    file_path: ctx.file_path,
                                    project: ctx.project,
                                    current_func: None,
                                    current_parent: combined.as_deref(),
                                    resolver: ctx.resolver,
                                };
                                visit_children(child, source, &child_ctx, result);
                            }
                        }
                    }
                }
                _ => {
                    // Normal C function — with overload disambiguation for C++ methods.
                    // When inside a struct/class/namespace (current_parent is Some),
                    // append line number to parent so overloaded methods get distinct FQNs.
                    let start_line = node.start_position().row as u32 + 1;
                    let method_parent = ctx.current_parent.map(|p| format!("{p}_L{start_line}"));
                    extract_function(node, source, ctx, method_parent.as_deref(), result);
                    let func_name = scope.as_ref().map(|s| s.name.as_str());
                    for i in 0..node.named_child_count() as u32 {
                        if let Some(child) = node.named_child(i) {
                            if child.kind() == "compound_statement" {
                                let child_ctx = VisitContext {
                                    file_path: ctx.file_path,
                                    project: ctx.project,
                                    current_func: func_name,
                                    current_parent: method_parent.as_deref(),
                                    resolver: ctx.resolver,
                                };
                                visit_children(child, source, &child_ctx, result);
                            }
                        }
                    }
                }
            }
        }
        "declaration" => {
            extract_global_var(node, source, ctx, result);
            // Always recurse into declarations to find calls/reads inside
            // (e.g. `int x = foo();`).
            visit_children(node, source, ctx, result);
        }
        "preproc_include" => {
            extract_include(node, source, result);
        }
        "preproc_def" | "preproc_function_def" => {
            // #define directives: object-like (`#define FOO 1`) and
            // function-like (`#define MAX(a,b) ...`). Both produce a
            // [`NodeLabel::Macro`] node (P1 bugfix: previously missed entirely).
            extract_macro(node, source, ctx, result);
        }
        "type_definition" => {
            extract_typedef(node, source, ctx, result);
        }
        "struct_specifier" => {
            extract_struct(node, source, ctx, result);
            // Pass the struct name as current_parent to children when a body exists.
            if node.child_by_field_name("body").is_some() {
                // Use ScopeResolver to get the struct name (design.md D3).
                let scope_ctx = ScopeContext {
                    source,
                    file_path: ctx.file_path,
                    project: ctx.project,
                    current_parent: ctx.current_parent,
                };
                let scope = ctx
                    .resolver
                    .get(Language::C)
                    .and_then(|r| r.resolve(node, &scope_ctx));
                let struct_name = scope.as_ref().map(|s| s.name.as_str());
                let combined = combine_scope(ctx.current_parent, struct_name);
                let child_ctx = VisitContext {
                    file_path: ctx.file_path,
                    project: ctx.project,
                    current_func: ctx.current_func,
                    current_parent: combined.as_deref(),
                    resolver: ctx.resolver,
                };
                visit_children(node, source, &child_ctx, result);
            }
        }
        "enum_specifier" => {
            extract_enum(node, source, ctx, result);
        }
        "call_expression" => {
            extract_call(node, source, ctx, result);
            // Recurse to handle nested calls in arguments.
            visit_children(node, source, ctx, result);
        }
        "init_declarator" => {
            // A local `int x = 1;` writes the declarator's identifier
            // (BR-TRACE-006). Only attribute the write when inside a function
            // body (current_func is Some).
            if let Some(func) = ctx.current_func {
                if let Some(name) = declarator_name(node, source) {
                    result.writes.push(WriteInfo {
                        writer_qn: Some(make_qn(
                            ctx.file_path,
                            func,
                            ctx.project,
                            ctx.current_parent,
                        )),
                        var_name: name,
                        line: node.start_position().row as u32 + 1,
                    });
                }
            }
            visit_children(node, source, ctx, result);
        }
        "assignment_expression" => {
            // `x = ...;` writes the left-hand identifier (BR-TRACE-006). Only
            // simple identifier targets are captured; field/index writes are
            // ignored.
            if let Some(func) = ctx.current_func {
                if let Some(left) = node.child_by_field_name("left") {
                    if let Some(name) = identifier_text(left, source) {
                        result.writes.push(WriteInfo {
                            writer_qn: Some(make_qn(
                                ctx.file_path,
                                func,
                                ctx.project,
                                ctx.current_parent,
                            )),
                            var_name: name,
                            line: node.start_position().row as u32 + 1,
                        });
                    }
                }
            }
            visit_children(node, source, ctx, result);
        }
        "identifier" => {
            // A bare identifier in an expression position is a variable read
            // (BR-TRACE-005). Name-defining positions (declarators, call
            // functions, assignment left) are excluded by `is_read_position`.
            if let Some(func) = ctx.current_func {
                if is_read_position(node) {
                    if let Some(name) = node_text(node, source).map(String::from) {
                        result.reads.push(ReadInfo {
                            reader_qn: Some(make_qn(
                                ctx.file_path,
                                func,
                                ctx.project,
                                ctx.current_parent,
                            )),
                            var_name: name,
                            line: node.start_position().row as u32 + 1,
                        });
                    }
                }
            }
            visit_children(node, source, ctx, result);
        }
        "linkage_specification" => {
            // extern "C" { ... } blocks: recurse to find function definitions.
            visit_children(node, source, ctx, result);
        }
        _ => {
            // Recurse into other nodes to find nested definitions/calls.
            visit_children(node, source, ctx, result);
        }
    }
}

fn visit_children(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    for i in 0..node.named_child_count() as u32 {
        if let Some(child) = node.named_child(i) {
            visit_node(child, source, ctx, result);
        }
    }
}

// ---------------------------------------------------------------------------
// Definition extractors
// ---------------------------------------------------------------------------

fn extract_function(
    node: Node,
    source: &str,
    ctx: &VisitContext<'_>,
    parent: Option<&str>,
    result: &mut ExtractResult,
) {
    let Some(name) = function_name(node, source) else {
        return;
    };
    let start_line = node.start_position().row as u32 + 1;
    let end_line = node.end_position().row as u32 + 1;
    let signature = declarator_signature(node, source);
    let qn = dedupe_qn(
        make_qn(ctx.file_path, &name, ctx.project, parent),
        start_line,
        result,
    );
    let mut builder = ModelNode::builder(NodeLabel::Function, name.clone(), qn.clone())
        .file_path(ctx.file_path)
        .start_line(start_line)
        .end_line(end_line)
        .language(Language::C)
        .project(ctx.project)
        .is_global(true);
    if let Some(sig) = signature {
        builder = builder.signature(sig);
    }
    let model_node = builder.build();
    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
    result.push_node(model_node);
}

fn extract_global_var(
    node: Node,
    source: &str,
    ctx: &VisitContext<'_>,
    result: &mut ExtractResult,
) {
    // Only treat as global var if at the top level (parent is translation_unit).
    let is_top_level = node
        .parent()
        .map(|p| p.kind() == "translation_unit")
        .unwrap_or(false);
    if !is_top_level {
        return;
    }
    // P1-2: Detect function declarations in headers (e.g. `int foo(int x);`).
    // Walk named children for `function_declarator` (direct or wrapped in
    // `pointer_declarator`). If found, create Function nodes and skip global
    // var extraction to avoid double-counting the same declarator.
    let mut has_function_decl = false;
    for i in 0..node.named_child_count() as u32 {
        if let Some(child) = node.named_child(i) {
            if let Some(fd) = find_function_declarator(child) {
                extract_function_declaration(fd, node, source, ctx, result);
                has_function_decl = true;
            }
        }
    }
    if has_function_decl {
        return;
    }
    // A declaration may declare multiple variables; extract each declarator.
    let mut i: u32 = 0;
    while i < node.named_child_count() as u32 {
        if let Some(child) = node.named_child(i) {
            if child.kind() == "init_declarator" {
                if let Some(name) = declarator_name(child, source) {
                    push_global_var(
                        &name,
                        node.start_position().row as u32 + 1,
                        ctx.file_path,
                        ctx.project,
                        result,
                    );
                }
            }
        }
        i += 1;
    }
    // If no init_declarator, check for plain declarator children.
    let has_init = (0..node.named_child_count() as u32).any(|i| {
        node.named_child(i)
            .map(|c| c.kind() == "init_declarator")
            .unwrap_or(false)
    });
    if !has_init {
        for i in 0..node.named_child_count() as u32 {
            if let Some(child) = node.named_child(i) {
                if child.kind() == "identifier" {
                    if let Some(name) = node_text(child, source).map(String::from) {
                        push_global_var(
                            &name,
                            node.start_position().row as u32 + 1,
                            ctx.file_path,
                            ctx.project,
                            result,
                        );
                    }
                }
            }
        }
    }
}

fn push_global_var(
    name: &str,
    line: u32,
    file_path: &str,
    project: &str,
    result: &mut ExtractResult,
) {
    let qn = dedupe_qn(make_qn(file_path, name, project, None), line, result);
    let model_node = ModelNode::builder(NodeLabel::GlobalVar, name.to_string(), qn.clone())
        .file_path(file_path)
        .start_line(line)
        .language(Language::C)
        .project(project)
        .is_global(true)
        .build();
    add_definition_edges(file_path, project, &model_node, result);
    result.push_node(model_node);
}

/// P1-2: Creates a [`NodeLabel::Function`] node for a function declaration
/// found in a header (e.g. `int foo(int x);`). The `fd_node` is the
/// `function_declarator` child of the parent `declaration` node; `decl_node`
/// is the parent `declaration` (used for line range and signature text).
fn extract_function_declaration(
    fd_node: Node,
    decl_node: Node,
    source: &str,
    ctx: &VisitContext<'_>,
    result: &mut ExtractResult,
) {
    let Some(name) = declarator_name(fd_node, source) else {
        return;
    };
    let start_line = decl_node.start_position().row as u32 + 1;
    let end_line = decl_node.end_position().row as u32 + 1;
    let signature = node_text(fd_node, source).map(String::from);
    let qn = dedupe_qn(
        make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
        start_line,
        result,
    );
    let mut builder = ModelNode::builder(NodeLabel::Function, name.clone(), qn)
        .file_path(ctx.file_path)
        .start_line(start_line)
        .end_line(end_line)
        .language(Language::C)
        .project(ctx.project)
        .is_global(true);
    if let Some(sig) = signature {
        builder = builder.signature(sig);
    }
    let model_node = builder.build();
    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
    result.push_node(model_node);
}

/// P1-2: Recursively unwraps declarator wrappers to find a `function_declarator`
/// child, if any. Handles `int *foo(int x);` (pointer_declarator wrapping
/// function_declarator) and `int (foo)(int x);` (parenthesized_declarator).
fn find_function_declarator(node: Node) -> Option<Node> {
    match node.kind() {
        "function_declarator" => Some(node),
        "pointer_declarator" | "parenthesized_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            find_function_declarator(inner)
        }
        _ => None,
    }
}

fn extract_typedef(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    // type_definition has a `type` field and a `declarator` field (type_identifier).
    // Walk all children for type_identifier nodes.
    // Also detect anonymous struct/enum unions inside typedef (P1-1):
    //   typedef struct { int x; } Name;  → create Struct node "Name"
    //   typedef enum { A, B } Name;       → create Enum node "Name"
    let mut typedef_name: Option<String> = None;
    for i in 0..node.named_child_count() as u32 {
        if let Some(child) = node.named_child(i) {
            if child.kind() == "type_identifier" {
                if let Some(name) = node_text(child, source).map(String::from) {
                    let line = node.start_position().row as u32 + 1;
                    let qn = dedupe_qn(
                        make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
                        line,
                        result,
                    );
                    let model_node = ModelNode::builder(NodeLabel::Typedef, name.clone(), qn)
                        .file_path(ctx.file_path)
                        .start_line(line)
                        .language(Language::C)
                        .project(ctx.project)
                        .is_global(true)
                        .build();
                    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
                    result.push_node(model_node);
                    typedef_name = Some(name);
                }
            }
        }
    }
    // If there is an anonymous struct/enum inside, create a Struct/Enum node
    // using the typedef name (P1-1).
    if let Some(name) = typedef_name {
        for i in 0..node.named_child_count() as u32 {
            if let Some(child) = node.named_child(i) {
                match child.kind() {
                    "struct_specifier"
                        if child.child_by_field_name("name").is_none()
                            && child.child_by_field_name("body").is_some() =>
                    {
                        let qn = dedupe_qn(
                            make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
                            child.start_position().row as u32 + 1,
                            result,
                        );
                        let model_node = ModelNode::builder(NodeLabel::Struct, name.clone(), qn)
                            .file_path(ctx.file_path)
                            .start_line(child.start_position().row as u32 + 1)
                            .end_line(child.end_position().row as u32 + 1)
                            .language(Language::C)
                            .project(ctx.project)
                            .is_global(true)
                            .build();
                        add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
                        result.push_node(model_node);
                    }
                    "enum_specifier"
                        if child.child_by_field_name("name").is_none()
                            && child.child_by_field_name("body").is_some() =>
                    {
                        let qn = dedupe_qn(
                            make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
                            child.start_position().row as u32 + 1,
                            result,
                        );
                        let model_node = ModelNode::builder(NodeLabel::Enum, name.clone(), qn)
                            .file_path(ctx.file_path)
                            .start_line(child.start_position().row as u32 + 1)
                            .end_line(child.end_position().row as u32 + 1)
                            .language(Language::C)
                            .project(ctx.project)
                            .is_global(true)
                            .build();
                        add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
                        result.push_node(model_node);
                    }
                    _ => {}
                }
            }
        }
    }
}

fn extract_struct(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    // Only extract if the struct has a name and a body.
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    if node.child_by_field_name("body").is_none() {
        return;
    }
    let Some(name) = node_text(name_node, source).map(String::from) else {
        return;
    };
    let qn = dedupe_qn(
        make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
        node.start_position().row as u32 + 1,
        result,
    );
    let model_node = ModelNode::builder(NodeLabel::Struct, name, qn)
        .file_path(ctx.file_path)
        .start_line(node.start_position().row as u32 + 1)
        .end_line(node.end_position().row as u32 + 1)
        .language(Language::C)
        .project(ctx.project)
        .is_global(true)
        .build();
    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
    result.push_node(model_node);
}

fn extract_enum(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    if node.child_by_field_name("body").is_none() {
        return;
    }
    let Some(name) = node_text(name_node, source).map(String::from) else {
        return;
    };
    let qn = dedupe_qn(
        make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
        node.start_position().row as u32 + 1,
        result,
    );
    let model_node = ModelNode::builder(NodeLabel::Enum, name, qn)
        .file_path(ctx.file_path)
        .start_line(node.start_position().row as u32 + 1)
        .end_line(node.end_position().row as u32 + 1)
        .language(Language::C)
        .project(ctx.project)
        .is_global(true)
        .build();
    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
    result.push_node(model_node);
}

fn extract_macro(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    // Both `preproc_def` (`#define FOO 1`) and `preproc_function_def`
    // (`#define MAX(a,b) ...`) expose a `name` field pointing to an
    // `identifier`. Function-like macros additionally carry a `parameters`
    // field; we capture that as the signature when present.
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let Some(name) = node_text(name_node, source).map(String::from) else {
        return;
    };
    let start_line = node.start_position().row as u32 + 1;
    let end_line = node.end_position().row as u32 + 1;
    let signature = node
        .child_by_field_name("parameters")
        .and_then(|p| node_text(p, source).map(String::from));
    let qn = dedupe_qn(
        make_qn(ctx.file_path, &name, ctx.project, ctx.current_parent),
        start_line,
        result,
    );
    let mut builder = ModelNode::builder(NodeLabel::Macro, name, qn)
        .file_path(ctx.file_path)
        .start_line(start_line)
        .end_line(end_line)
        .language(Language::C)
        .project(ctx.project)
        .is_global(true);
    if let Some(sig) = signature {
        builder = builder.signature(sig);
    }
    let model_node = builder.build();
    add_definition_edges(ctx.file_path, ctx.project, &model_node, result);
    result.push_node(model_node);
}

// ---------------------------------------------------------------------------
// Record extractors
// ---------------------------------------------------------------------------

fn extract_include(node: Node, source: &str, result: &mut ExtractResult) {
    // preproc_include has a `path` field that is either system_lib_string
    // (<stdio.h>) or string_literal ("myheader.h").
    let Some(path_node) = node.child_by_field_name("path") else {
        return;
    };
    let raw = node_text(path_node, source).unwrap_or("");
    // Strip surrounding quotes/angle brackets.
    let cleaned = raw
        .trim_start_matches('<')
        .trim_end_matches('>')
        .trim_start_matches('"')
        .trim_end_matches('"')
        .to_string();
    result.imports.push(ImportInfo {
        source_file: cleaned,
        imported_names: Vec::new(),
        line: node.start_position().row as u32 + 1,
    });
}

fn extract_call(node: Node, source: &str, ctx: &VisitContext<'_>, result: &mut ExtractResult) {
    let Some(func_node) = node.child_by_field_name("function") else {
        return;
    };
    let Some(callee) = callee_name(func_node, source) else {
        return;
    };
    let args = call_arguments(node, source);
    let caller_qn = ctx
        .current_func
        .map(|name| make_qn(ctx.file_path, name, ctx.project, ctx.current_parent));
    result.calls.push(super::extractor::CallInfo {
        caller_qn,
        callee_name: callee,
        line: node.start_position().row as u32 + 1,
        args,
    });
}

// ---------------------------------------------------------------------------
// Name / signature helpers
// ---------------------------------------------------------------------------

fn function_name(node: Node, source: &str) -> Option<String> {
    // function_definition has a `declarator` field (function_declarator).
    let declarator = node.child_by_field_name("declarator")?;
    declarator_name(declarator, source)
}

/// Recursively unwraps declarator nodes (function_declarator, pointer_declarator,
/// etc.) to find the inner identifier.
fn declarator_name(node: Node, source: &str) -> Option<String> {
    match node.kind() {
        "identifier" => node_text(node, source).map(String::from),
        "function_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            // B9 fix: detect nested function_declarator (function returning
            // function), which is invalid in C. This pattern occurs when a
            // macro invocation like `API_SUFFIX(cblas_caxpy)` is misparsed by
            // tree-sitter-c as a function_declarator wrapping another
            // function_declarator. Without this check, the macro name (e.g.
            // "API_SUFFIX") would be extracted as a Function node, inflating
            // function counts by 148 on LAPACK and causing 100% query diff in
            // file_contains_symbols. C functions cannot return functions (only
            // function pointers, which use pointer_declarator), so nested
            // function_declarator is always a macro artifact. See
            // tools/verification/results/triage.md §B9.
            if inner.kind() == "function_declarator" {
                return None;
            }
            declarator_name(inner, source)
        }
        "pointer_declarator"
        | "array_declarator"
        | "parenthesized_declarator"
        | "init_declarator" => {
            let inner = node.child_by_field_name("declarator")?;
            declarator_name(inner, source)
        }
        _ => None,
    }
}

fn declarator_signature(node: Node, source: &str) -> Option<String> {
    // Use the declarator text as the signature.
    let declarator = node.child_by_field_name("declarator")?;
    node_text(declarator, source).map(String::from)
}

fn callee_name(node: Node, source: &str) -> Option<String> {
    match node.kind() {
        "identifier" | "type_identifier" => node_text(node, source).map(String::from),
        "field_expression" => {
            // e.g. obj.method() -> "method"
            let field = node.child_by_field_name("field")?;
            node_text(field, source).map(String::from)
        }
        "call_expression" => {
            let func = node.child_by_field_name("function")?;
            callee_name(func, source)
        }
        "parenthesized_expression" => {
            let inner = node.named_child(0)?;
            callee_name(inner, source)
        }
        _ => None,
    }
}

fn call_arguments(node: Node, source: &str) -> Vec<String> {
    let Some(args_node) = node.child_by_field_name("arguments") else {
        return Vec::new();
    };
    let mut args = Vec::new();
    for i in 0..args_node.named_child_count() as u32 {
        if let Some(arg) = args_node.named_child(i) {
            if let Ok(text) = arg.utf8_text(source.as_bytes()) {
                args.push(text.to_string());
            }
        }
    }
    args
}

fn node_text<'a>(node: Node<'a>, source: &'a str) -> Option<&'a str> {
    node.utf8_text(source.as_bytes()).ok()
}

/// Returns the text of `node` if it is a plain `identifier`, else `None`.
fn identifier_text(node: Node, source: &str) -> Option<String> {
    if node.kind() == "identifier" {
        node_text(node, source).map(String::from)
    } else {
        None
    }
}

/// Returns `true` if a bare `identifier` node sits in a read (expression)
/// position rather than a name-defining position (declarator, callee, write
/// target). Minimal version: only checks the direct parent kind, matching the
/// rust_extractor convention (design.md Decision 4, Open Question 2).
fn is_read_position(node: Node) -> bool {
    let Some(parent) = node.parent() else {
        return false;
    };
    match parent.kind() {
        // Identifiers directly inside these expression containers are reads.
        "binary_expression"
        | "unary_expression"
        | "parenthesized_expression"
        | "return_statement"
        | "argument_list"
        | "subscript_expression"
        | "conditional_expression" => true,
        // `foo(x)` -> the callee `foo` is not a read; arguments are handled
        // above via the `argument_list` parent.
        "call_expression" => !is_at_field(node, parent, "function"),
        // `x = y;` -> `y` (the right side) is a read; `x` (the left) is not.
        "assignment_expression" => !is_at_field(node, parent, "left"),
        // `obj.field` -> `obj` (the object) is a read; the field name is a
        // `field_identifier`, not a plain `identifier`, so it is not reached
        // here, but guard explicitly for safety.
        "field_expression" => is_at_field(node, parent, "argument"),
        _ => false,
    }
}

/// Returns `true` if `node` occupies the given named `field` of `parent`,
/// compared by byte range.
fn is_at_field(node: Node, parent: Node, field: &str) -> bool {
    parent
        .child_by_field_name(field)
        .is_some_and(|f| f.byte_range() == node.byte_range())
}

fn make_qn(file_path: &str, name: &str, project: &str, parent: Option<&str>) -> String {
    FqnGenerator::generate(project, file_path, name, Language::C, parent)
}

// `dedupe_qn` is shared across all extractors — see `parse::dedupe_qn` (MED-002).

/// Combines a parent scope context with a child scope name (ADR-005).
/// Returns `Some("{parent}_{child}")` when both are present, the non-`None`
/// value when only one is, or `None` when neither is.
fn combine_scope(parent: Option<&str>, child: Option<&str>) -> Option<String> {
    match (parent, child) {
        (Some(p), Some(c)) => Some(format!("{p}_{c}")),
        (None, Some(c)) => Some(c.to_string()),
        (Some(p), None) => Some(p.to_string()),
        (None, None) => None,
    }
}

fn add_definition_edges(
    file_path: &str,
    project: &str,
    node: &ModelNode,
    result: &mut ExtractResult,
) {
    // B1 fix: only emit DEFINES (file -> definition). The previous CONTAINS
    // emission was redundant — for (file, node) pairs, CONTAINS and DEFINES
    // carry identical semantics, producing duplicate edges that inflated
    // verification diffs against gitnexus (see triage.md §B1).
    // DEFINES edge: file -> definition
    result.edges.push(Edge::new(
        file_path.to_string(),
        node.id.clone(),
        EdgeType::Defines,
        project,
    ));
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    const C_SOURCE: &str = r#"#include <stdio.h>
#include "myheader.h"
typedef int my_int;
int global_var = 42;
int add(int a, int b) {
    return a + b;
}
int main() {
    int result = add(1, 2);
    printf("hello");
    return result;
}
"#;

    fn extract(source: &str) -> ExtractResult {
        let ext = CExtractor::new();
        ext.extract(source, "test.c", "proj")
            .expect("extraction should succeed")
    }

    #[test]
    fn language_returns_c() {
        assert_eq!(CExtractor::new().language(), Language::C);
    }

    #[test]
    fn default_creates_extractor() {
        let ext = CExtractor::default();
        assert_eq!(ext.language(), Language::C);
    }

    #[test]
    fn extracts_two_includes() {
        let result = extract(C_SOURCE);
        assert_eq!(
            result.imports.len(),
            2,
            "should extract 2 #include directives"
        );
        assert_eq!(result.imports[0].source_file, "stdio.h");
        assert_eq!(result.imports[1].source_file, "myheader.h");
        assert_eq!(result.imports[0].line, 1);
        assert_eq!(result.imports[1].line, 2);
    }

    #[test]
    fn extracts_typedef() {
        let result = extract(C_SOURCE);
        let typedefs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Typedef)
            .collect();
        assert_eq!(typedefs.len(), 1, "should extract 1 typedef");
        assert_eq!(typedefs[0].name, "my_int");
        assert_eq!(typedefs[0].start_line, Some(3));
        assert_eq!(typedefs[0].language, Some(Language::C));
        assert_eq!(typedefs[0].project, "proj");
        assert_eq!(typedefs[0].file_path.as_deref(), Some("test.c"));
        assert!(typedefs[0].is_global);
    }

    #[test]
    fn typedef_duplicate_name_disambiguated() {
        // 模拟 flex 生成代码的 #ifdef/#else 同名 typedef(WRF lexer.c 碰撞)。
        // tree-sitter 不处理预处理器,会同时看到两个 typedef 节点。
        let src = r#"typedef int flex_uint16_t;
typedef unsigned short int flex_uint16_t;
"#;
        let result = extract(src);
        let typedefs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Typedef && n.name == "flex_uint16_t")
            .collect();
        assert_eq!(typedefs.len(), 2, "should extract 2 typedefs");
        // 第一个无消歧符
        assert!(
            !typedefs[0].qualified_name.contains('#'),
            "first typedef should have no disambiguator: {}",
            typedefs[0].qualified_name
        );
        // 第二个含 #L 行号消歧符
        assert!(
            typedefs[1].qualified_name.contains("#L"),
            "second typedef should have #L disambiguator: {}",
            typedefs[1].qualified_name
        );
        // 两个 FQN 不同
        assert_ne!(
            typedefs[0].qualified_name, typedefs[1].qualified_name,
            "FQNs must differ to avoid collision"
        );
    }

    #[test]
    fn extracts_global_var() {
        let result = extract(C_SOURCE);
        let globals: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::GlobalVar)
            .collect();
        assert_eq!(globals.len(), 1, "should extract 1 global variable");
        assert_eq!(globals[0].name, "global_var");
        assert_eq!(globals[0].start_line, Some(4));
        assert_eq!(globals[0].language, Some(Language::C));
    }

    #[test]
    fn extracts_functions() {
        let result = extract(C_SOURCE);
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(funcs.len(), 2, "should extract 2 functions (add, main)");
        let names: Vec<_> = funcs.iter().map(|n| n.name.as_str()).collect();
        assert!(names.contains(&"add"));
        assert!(names.contains(&"main"));
    }

    #[test]
    fn function_has_signature_and_lines() {
        let result = extract(C_SOURCE);
        let add = result
            .nodes
            .iter()
            .find(|n| n.name == "add")
            .expect("add function should exist");
        assert_eq!(add.start_line, Some(5));
        assert_eq!(add.end_line, Some(7));
        assert!(add.signature.is_some(), "function should have a signature");
        assert!(add.signature.as_deref().unwrap().contains("add"));
    }

    #[test]
    fn extracts_calls() {
        let result = extract(C_SOURCE);
        let callees: Vec<_> = result
            .calls
            .iter()
            .map(|c| c.callee_name.as_str())
            .collect();
        assert!(callees.contains(&"add"), "should extract call to add");
        assert!(callees.contains(&"printf"), "should extract call to printf");
    }

    #[test]
    fn call_has_line_and_args() {
        let result = extract(C_SOURCE);
        let add_call = result
            .calls
            .iter()
            .find(|c| c.callee_name == "add")
            .expect("call to add should exist");
        assert_eq!(add_call.line, 9);
        assert_eq!(add_call.args.len(), 2, "add(1, 2) should have 2 args");
    }

    #[test]
    fn creates_defines_edges() {
        // B1 fix: CONTAINS emission removed; only DEFINES remains.
        let result = extract(C_SOURCE);
        let defines_count = result
            .edges
            .iter()
            .filter(|e| e.edge_type == EdgeType::Defines)
            .count();
        let node_count = result.nodes.len();
        assert_eq!(
            defines_count, node_count,
            "each node should have a DEFINES edge"
        );
        // B1 fix verification: no CONTAINS edges should be emitted
        let contains_count = result
            .edges
            .iter()
            .filter(|e| e.edge_type == EdgeType::Contains)
            .count();
        assert_eq!(
            contains_count, 0,
            "B1 fix: no CONTAINS edges should be emitted"
        );
    }

    #[test]
    fn edges_reference_file_and_node_ids() {
        let result = extract(C_SOURCE);
        for edge in &result.edges {
            assert_eq!(edge.source, "test.c", "edge source should be the file path");
            assert!(!edge.target.is_empty(), "edge target should be a node id");
            assert_eq!(edge.project, "proj");
        }
    }

    #[test]
    fn qualified_name_uses_file_path_and_name() {
        let result = extract(C_SOURCE);
        let add = result.nodes.iter().find(|n| n.name == "add").unwrap();
        assert_eq!(add.qualified_name, "proj.test.c.add");
    }

    #[test]
    fn empty_source_returns_empty_result() {
        let result = extract("");
        assert!(result.nodes.is_empty());
        assert!(result.imports.is_empty());
        assert!(result.calls.is_empty());
        assert!(result.is_empty());
    }

    #[test]
    fn extracts_struct_definition() {
        let src = "struct Point { int x; int y; };";
        let result = extract(src);
        let structs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Struct)
            .collect();
        assert_eq!(structs.len(), 1);
        assert_eq!(structs[0].name, "Point");
    }

    #[test]
    fn extracts_enum_definition() {
        let src = "enum Color { RED, GREEN, BLUE };";
        let result = extract(src);
        let enums: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Enum)
            .collect();
        assert_eq!(enums.len(), 1);
        assert_eq!(enums[0].name, "Color");
    }

    #[test]
    fn struct_without_body_is_not_extracted() {
        // `struct Point p;` is a declaration, not a definition.
        let src = "struct Point p;";
        let result = extract(src);
        let structs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Struct)
            .collect();
        assert_eq!(
            structs.len(),
            0,
            "struct without body should not be extracted"
        );
    }

    #[test]
    fn handles_pointer_function_declarator() {
        let src = "int* alloc(int n) { return 0; }";
        let result = extract(src);
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(funcs.len(), 1);
        assert_eq!(funcs[0].name, "alloc");
    }

    #[test]
    fn handles_extern_linkage_block() {
        let src = r#"extern "C" {
            int c_func(int x);
        }"#;
        let result = extract(src);
        // The function declaration inside extern block should be found via recursion.
        // (It's a declaration, not a definition, so no Function node, but no crash.)
        // Verify no panic occurs and the result is returned.
        assert_eq!(result.language, Language::C);
    }

    #[test]
    fn multiple_global_vars_in_one_declaration() {
        let src = "int a = 1, b = 2, c = 3;";
        let result = extract(src);
        let globals: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::GlobalVar)
            .collect();
        assert_eq!(globals.len(), 3, "should extract 3 global variables");
        let names: Vec<_> = globals.iter().map(|n| n.name.as_str()).collect();
        assert!(names.contains(&"a"));
        assert!(names.contains(&"b"));
        assert!(names.contains(&"c"));
    }

    #[test]
    fn nested_call_expressions() {
        let src = "int main() { printf(format_str(add(1))); }";
        let result = extract(src);
        let callees: Vec<_> = result
            .calls
            .iter()
            .map(|c| c.callee_name.as_str())
            .collect();
        assert!(callees.contains(&"printf"), "should find printf call");
        assert!(callees.contains(&"add"), "should find nested add call");
    }

    #[test]
    fn field_expression_call() {
        let src = "int main() { obj.method(); }";
        let result = extract(src);
        let callees: Vec<_> = result
            .calls
            .iter()
            .map(|c| c.callee_name.as_str())
            .collect();
        assert!(
            callees.contains(&"method"),
            "should extract method name from field expression"
        );
    }

    #[test]
    fn result_language_is_c() {
        let result = extract(C_SOURCE);
        assert_eq!(result.language, Language::C);
        assert_eq!(result.file_path, "test.c");
    }

    #[test]
    fn call_in_function_has_dotted_fqn_caller_qn() {
        // Spec: C 函数内调用生成非 None caller_qn (点分 FQN 格式)。
        let src = "int caller(void) {\n    callee();\n    return 0;\n}\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        let call = result
            .calls
            .iter()
            .find(|c| c.callee_name == "callee")
            .expect("should find call to callee");
        assert_eq!(
            call.caller_qn.as_deref(),
            Some("proj.tmp.demo.main.c.caller"),
            "caller_qn should be the dotted FQN of the enclosing function"
        );
        // The caller FQN must match the enclosing function's node id.
        let caller_node = result
            .nodes
            .iter()
            .find(|n| n.name == "caller")
            .expect("should find caller function node");
        assert_eq!(
            call.caller_qn.as_deref(),
            Some(caller_node.qualified_name.as_str()),
            "caller_qn must match the caller function node id"
        );
    }

    #[test]
    fn read_in_function_has_dotted_fqn_reader_qn() {
        // Spec: C 函数内 identifier 读取提取 (BR-TRACE-005)。
        let src = "int caller(int x) {\n    return x;\n}\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        let read = result
            .reads
            .iter()
            .find(|r| r.var_name == "x")
            .expect("should find a read of x");
        assert_eq!(
            read.reader_qn.as_deref(),
            Some("proj.tmp.demo.main.c.caller"),
            "reader_qn should be the dotted FQN of the enclosing function"
        );
        let caller_node = result
            .nodes
            .iter()
            .find(|n| n.name == "caller")
            .expect("should find caller function node");
        assert_eq!(
            read.reader_qn.as_deref(),
            Some(caller_node.qualified_name.as_str()),
            "reader_qn must match the caller function node id"
        );
    }

    #[test]
    fn write_in_function_init_declarator_has_dotted_fqn_writer_qn() {
        // Spec: C 函数内 init_declarator 写入提取 (BR-TRACE-006)。
        let src = "void caller(void) {\n    int y = 1;\n}\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        let write = result
            .writes
            .iter()
            .find(|w| w.var_name == "y")
            .expect("should find a write of y");
        assert_eq!(write.var_name, "y");
        assert_eq!(
            write.writer_qn.as_deref(),
            Some("proj.tmp.demo.main.c.caller"),
            "writer_qn should be the dotted FQN of the enclosing function"
        );
        let caller_node = result
            .nodes
            .iter()
            .find(|n| n.name == "caller")
            .expect("should find caller function node");
        assert_eq!(
            write.writer_qn.as_deref(),
            Some(caller_node.qualified_name.as_str()),
            "writer_qn must match the caller function node id"
        );
    }

    #[test]
    fn write_in_function_assignment_has_dotted_fqn_writer_qn() {
        // Spec: C 函数内 assignment_expression 写入提取 (BR-TRACE-006)。
        let src = "void caller(void) {\n    int y;\n    y = 2;\n}\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        // `int y;` declares y (no init_declarator, so no write from declaration);
        // `y = 2;` is an assignment_expression write.
        let assignment_write = result
            .writes
            .iter()
            .find(|w| w.var_name == "y")
            .expect("should find a write of y from assignment");
        assert_eq!(
            assignment_write.writer_qn.as_deref(),
            Some("proj.tmp.demo.main.c.caller"),
            "writer_qn should be the dotted FQN of the enclosing function"
        );
    }

    #[test]
    fn declaration_position_identifier_not_a_read() {
        // Spec: C 声明位置的 identifier 不被误识别为读取。
        // `int x = 1;` inside a function: x is the declarator (write target),
        // not a read. x MUST NOT appear in ReadInfo.
        let src = "void caller(void) {\n    int x = 1;\n}\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        let x_reads: Vec<_> = result.reads.iter().filter(|r| r.var_name == "x").collect();
        assert!(
            x_reads.is_empty(),
            "declarator-position x must NOT appear in ReadInfo: {:?}",
            x_reads
        );
        // x should appear as a WriteInfo target (init_declarator write).
        let x_writes: Vec<_> = result.writes.iter().filter(|w| w.var_name == "x").collect();
        assert!(
            !x_writes.is_empty(),
            "declarator-position x SHOULD appear in WriteInfo"
        );
    }

    #[test]
    fn top_level_declaration_no_reads_or_writes() {
        // Spec: C 顶层声明的 identifier 不生成读写记录 (current_func 为 None)。
        let src = "int g = 0;\n";
        let ext = CExtractor::new();
        let result = ext
            .extract(src, "/tmp/demo/main.c", "proj")
            .expect("extraction should succeed");
        assert!(
            result.reads.is_empty(),
            "top-level declaration must not produce ReadInfo: {:?}",
            result.reads
        );
        assert!(
            result.writes.is_empty(),
            "top-level declaration must not produce WriteInfo: {:?}",
            result.writes
        );
    }

    #[test]
    fn cpp_overloaded_methods_get_line_disambiguator() {
        let src = "\
class Container {
public:
    int* begin() { return data_; }
    const int* begin() const { return data_; }
    int* end() { return data_ + size_; }
    const int* end() const { return data_ + size_; }
private:
    int data_[10];
    int size_ = 0;
};
";
        let result = extract(src);
        let ends: Vec<_> = result.nodes.iter().filter(|n| n.name == "end").collect();
        assert_eq!(ends.len(), 2, "should extract two `end` methods");
        assert_ne!(ends[0].qualified_name, ends[1].qualified_name);
        for e in &ends {
            assert!(
                e.qualified_name.contains("#Container_L"),
                "expected #Container_L<line>: {}",
                e.qualified_name
            );
        }
    }

    // --- P1 bugfix: #define macro extraction (regression tests) ---

    #[test]
    fn extracts_object_like_macro() {
        // P1 regression: `#define FOO 1` was previously missed entirely.
        let src = "#define FOO 1\n";
        let result = extract(src);
        let macros: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Macro)
            .collect();
        assert_eq!(macros.len(), 1, "should extract 1 object-like macro");
        assert_eq!(macros[0].name, "FOO");
        assert_eq!(macros[0].start_line, Some(1));
        assert_eq!(macros[0].language, Some(Language::C));
        assert_eq!(macros[0].project, "proj");
        assert_eq!(macros[0].file_path.as_deref(), Some("test.c"));
        assert!(
            macros[0].signature.is_none(),
            "object-like macro has no parameter signature"
        );
    }

    #[test]
    fn extracts_function_like_macro() {
        // P1 regression: `#define MAX(a, b) ((a) > (b) ? (a) : (b))` was
        // previously missed entirely.
        let src = "#define MAX(a, b) ((a) > (b) ? (a) : (b))\n";
        let result = extract(src);
        let macros: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Macro && n.name == "MAX")
            .collect();
        assert_eq!(macros.len(), 1, "should extract 1 function-like macro");
        assert_eq!(macros[0].start_line, Some(1));
        assert!(
            macros[0].signature.is_some(),
            "function-like macro should expose parameter list as signature"
        );
        let sig = macros[0].signature.as_deref().unwrap();
        assert!(sig.contains('a'), "signature should contain param a: {sig}");
        assert!(sig.contains('b'), "signature should contain param b: {sig}");
    }

    #[test]
    fn extracts_mixed_macros_and_functions() {
        // Reproduces the cJSON-class scenario: many macros mixed with
        // functions. Macros MUST NOT be silently dropped.
        let src = r#"#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define cJSON_min(a, b) ((a) < (b) ? (a) : (b))
#define cJSON_max(a, b) ((a) > (b) ? (a) : (b))

static void cJSON_skip_whitespace(const char *buffer) {
    (void)buffer;
}
"#;
        let result = extract(src);
        let macros: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Macro)
            .collect();
        assert_eq!(macros.len(), 4, "should extract all 4 #define macros");
        let macro_names: Vec<_> = macros.iter().map(|n| n.name.as_str()).collect();
        assert!(macro_names.contains(&"CJSON_VERSION_MAJOR"));
        assert!(macro_names.contains(&"CJSON_VERSION_MINOR"));
        assert!(macro_names.contains(&"cJSON_min"));
        assert!(macro_names.contains(&"cJSON_max"));
        // Function extraction must still work alongside macros.
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(funcs.len(), 1, "should still extract the function");
        assert_eq!(funcs[0].name, "cJSON_skip_whitespace");
    }

    #[test]
    fn macro_invocation_not_extracted_as_function() {
        // B9 fix: `void API_SUFFIX(cblas_caxpy)(int x) { ... }` is a LAPACK
        // CBLAS pattern where API_SUFFIX is a macro. tree-sitter-c (without
        // preprocessing) parses this as a nested function_declarator (function
        // returning function), which is invalid C. The extractor must NOT
        // create a Function node for the macro name "API_SUFFIX".
        // See tools/verification/results/triage.md §B9.
        let src = r#"#define API_SUFFIX(a) a##_64
void API_SUFFIX(cblas_caxpy)(int N, const void *X) {
    (void)N;
    (void)X;
}
void normal_func(int x) {
    (void)x;
}
"#;
        let result = extract(src);
        let api_suffix_funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function && n.name == "API_SUFFIX")
            .collect();
        assert!(
            api_suffix_funcs.is_empty(),
            "B9 fix: API_SUFFIX (macro invocation) must NOT be extracted as Function: {:?}",
            api_suffix_funcs
        );
        // The normal function should still be extracted.
        let normal_funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function && n.name == "normal_func")
            .collect();
        assert_eq!(
            normal_funcs.len(),
            1,
            "normal function should still be extracted"
        );
        // The API_SUFFIX macro definition should be extracted as a Macro node.
        let macros: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Macro && n.name == "API_SUFFIX")
            .collect();
        assert_eq!(
            macros.len(),
            1,
            "API_SUFFIX macro definition should be extracted as Macro"
        );
    }

    #[test]
    fn macro_has_contains_and_defines_edges() {
        // Spec REQ-LV-004: defect must be reproducible + fixable. Edges are
        // part of the contract — a Macro node without CONTAINS/DEFINES would
        // be invisible in the knowledge graph. Edge target is the node id
        // (UUIDv7), not the qualified_name.
        let src = "#define FOO 1\n";
        let result = extract(src);
        let macro_node = result
            .nodes
            .iter()
            .find(|n| n.label == NodeLabel::Macro)
            .expect("macro node should exist");
        let defines_count = result
            .edges
            .iter()
            .filter(|e| e.edge_type == EdgeType::Defines && e.target == macro_node.id)
            .count();
        assert_eq!(defines_count, 1, "macro should have 1 DEFINES edge");
        // B1 fix verification: no CONTAINS edges should remain
        let contains_count = result
            .edges
            .iter()
            .filter(|e| e.edge_type == EdgeType::Contains && e.target == macro_node.id)
            .count();
        assert_eq!(
            contains_count, 0,
            "B1 fix: macro should have 0 CONTAINS edges"
        );
    }

    // --- P1-2: function declarations in headers ---

    #[test]
    fn extracts_function_declaration_in_header() {
        // `int foo(int x);` at top level → Function node (declaration, no body).
        let src = "int foo(int x);\n";
        let result = extract(src);
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(funcs.len(), 1, "should extract 1 function declaration");
        assert_eq!(funcs[0].name, "foo");
        assert!(
            funcs[0].signature.is_some(),
            "declaration should have signature"
        );
        assert_eq!(funcs[0].start_line, Some(1));
    }

    #[test]
    fn function_declaration_does_not_create_global_var() {
        // A function declaration must not be double-counted as a global var.
        let src = "int declare_only(int x);\n";
        let result = extract(src);
        let globals: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::GlobalVar)
            .collect();
        assert!(
            globals.is_empty(),
            "function declaration should not create a global var"
        );
    }

    #[test]
    fn pointer_function_declaration_extracted() {
        // `int *get_ptr(void);` — pointer_declarator wrapping function_declarator.
        let src = "int *get_ptr(void);\n";
        let result = extract(src);
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(
            funcs.len(),
            1,
            "pointer function declaration should be extracted"
        );
        assert_eq!(funcs[0].name, "get_ptr");
    }

    #[test]
    fn multiple_function_declarations_in_header() {
        let src = "int add(int a, int b);\nint sub(int a, int b);\n";
        let result = extract(src);
        let funcs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Function)
            .collect();
        assert_eq!(funcs.len(), 2, "should extract 2 function declarations");
        let names: Vec<_> = funcs.iter().map(|n| n.name.as_str()).collect();
        assert!(names.contains(&"add"));
        assert!(names.contains(&"sub"));
    }

    // --- P1-1: anonymous struct/enum in typedef ---

    #[test]
    fn anonymous_struct_in_typedef_creates_struct_node() {
        // `typedef struct { int x; int y; } Point;` → Typedef + Struct node.
        let src = "typedef struct { int x; int y; } Point;\n";
        let result = extract(src);
        let structs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Struct)
            .collect();
        assert_eq!(
            structs.len(),
            1,
            "anonymous struct should create a Struct node"
        );
        assert_eq!(
            structs[0].name, "Point",
            "struct should use the typedef name"
        );
        let typedefs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Typedef)
            .collect();
        assert_eq!(typedefs.len(), 1, "typedef should also be extracted");
    }

    #[test]
    fn anonymous_enum_in_typedef_creates_enum_node() {
        // `typedef enum { RED, GREEN, BLUE } Color;` → Typedef + Enum node.
        let src = "typedef enum { RED, GREEN, BLUE } Color;\n";
        let result = extract(src);
        let enums: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Enum)
            .collect();
        assert_eq!(enums.len(), 1, "anonymous enum should create an Enum node");
        assert_eq!(enums[0].name, "Color", "enum should use the typedef name");
    }

    // --- callee_name edge cases ---

    #[test]
    fn parenthesized_call_expression_extracts_callee() {
        // `(func)(arg)` — parenthesized_expression callee.
        let src = "void wrapper(void) { (func)(42); }\n";
        let result = extract(src);
        let callees: Vec<_> = result
            .calls
            .iter()
            .map(|c| c.callee_name.as_str())
            .collect();
        assert!(
            callees.contains(&"func"),
            "parenthesized call should extract callee name"
        );
    }

    #[test]
    fn call_expression_result_as_callee() {
        // `get_fn()(arg)` — call_expression whose function is another call_expression.
        // The inner callee (get_fn) should be extracted.
        let src = "void caller(void) { get_fn()(42); }\n";
        let result = extract(src);
        let callees: Vec<_> = result
            .calls
            .iter()
            .map(|c| c.callee_name.as_str())
            .collect();
        assert!(
            callees.contains(&"get_fn"),
            "chained call should extract inner callee"
        );
    }

    // --- empty/error edge cases ---

    #[test]
    fn struct_without_name_skipped() {
        // Anonymous struct without typedef context should not create a node.
        let src = "struct { int x; };\n";
        let result = extract(src);
        let structs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Struct)
            .collect();
        assert!(
            structs.is_empty(),
            "unnamed struct without typedef should not be extracted"
        );
    }

    #[test]
    fn struct_without_body_skipped() {
        // Forward declaration: `struct Point;` — no body, no extraction.
        let src = "struct Point;\n";
        let result = extract(src);
        let structs: Vec<_> = result
            .nodes
            .iter()
            .filter(|n| n.label == NodeLabel::Struct)
            .collect();
        assert!(
            structs.is_empty(),
            "struct without body should not be extracted"
        );
    }
}