ochna 0.3.1

A structural code graph indexing and analysis CLI using Tree-sitter and SQLite
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
//! Tree-sitter parsing and call-graph resolution, split by concern:
//! - [`common`] — shared AST helpers (signature/doc extraction, node lookup).
//! - [`interner`] — the symbol index and string interner.
//! - [`resolve`] — raw-call-site to call-edge resolution.
//! - `rust`/`go`/`c_like`/`zig`/`java` — per-language AST traversals.
//!
//! [`parse_code`] is the entry point: it parses a source file and dispatches to
//! the matching per-language traversal.

use crate::db::{Node, RawCall};
use std::error::Error;
use tree_sitter::Parser;

mod c_like;
mod common;
mod go;
mod interner;
mod java;
mod resolve;
mod rust;
mod zig;

pub use interner::{
    CandidateByFile, CandidateList, InternedString, StringInterner, SymbolCandidate, SymbolIndex,
    SymbolIndexBuilder, SymbolIx,
};
pub use resolve::{resolve_calls_global, resolve_calls_local};

use c_like::{traverse_c_like, CLikeContext};

/// Parse supported source and extract nodes (symbols) plus the raw,
/// unresolved call sites within them. Call sites are returned unresolved so the
/// caller can resolve them against the whole-project symbol index (see
/// [`resolve_calls_global`]) rather than only the symbols in this one file.
pub fn parse_code(
    file_path: &str,
    content: &str,
    language: &str,
) -> Result<(Vec<Node>, Vec<RawCall>), Box<dyn Error>> {
    let mut parser = Parser::new();
    let lang = language.to_lowercase();

    match lang.as_str() {
        "rust" | "rs" => parser.set_language(&tree_sitter_rust::LANGUAGE.into())?,
        "go" => parser.set_language(&tree_sitter_go::LANGUAGE.into())?,
        "java" => parser.set_language(&tree_sitter_java::LANGUAGE.into())?,
        "c" => parser.set_language(&tree_sitter_c::LANGUAGE.into())?,
        "cpp" | "c++" | "cc" | "cxx" => parser.set_language(&tree_sitter_cpp::LANGUAGE.into())?,
        "zig" => parser.set_language(&tree_sitter_zig::LANGUAGE.into())?,
        _ => return Err(format!("Unsupported language: {}", language).into()),
    }

    let tree = parser
        .parse(content, None)
        .ok_or("Failed to parse code content")?;

    let mut nodes = Vec::new();
    let mut raw_calls = Vec::new();

    if lang == "rust" || lang == "rs" {
        rust::traverse_rust(
            tree.root_node(),
            content,
            file_path,
            None,
            &mut nodes,
            &mut raw_calls,
            None,
        );
    } else if lang == "go" {
        let package_node = common::find_child_by_kind(tree.root_node(), "package_clause");
        let package_name = package_node.and_then(|n| {
            common::find_child_by_kind(n, "package_identifier")
                .or_else(|| common::find_child_by_kind(n, "identifier"))
                .map(|name_node| {
                    name_node
                        .utf8_text(content.as_bytes())
                        .unwrap_or("")
                        .trim()
                        .to_string()
                })
        });
        let imports = go::collect_go_imports(tree.root_node(), content);
        go::traverse_go(
            tree.root_node(),
            content,
            file_path,
            &mut nodes,
            &mut raw_calls,
            None,
            package_name.as_deref(),
            &imports,
        );
    } else if lang == "java" {
        let package_node = common::find_child_by_kind(tree.root_node(), "package_declaration");
        let package_name = package_node.and_then(|n| {
            common::find_child_by_kind(n, "scoped_identifier")
                .or_else(|| common::find_child_by_kind(n, "identifier"))
                .map(|name_node| {
                    name_node
                        .utf8_text(content.as_bytes())
                        .unwrap_or("")
                        .trim()
                        .to_string()
                })
        });

        let mut imports = Vec::new();
        let mut cursor = tree.root_node().walk();
        for child in tree.root_node().children(&mut cursor) {
            if child.kind() == "import_declaration" {
                if let Some(imported_node) = child
                    .child_by_field_name("name")
                    .or_else(|| common::find_child_by_kind(child, "scoped_identifier"))
                    .or_else(|| common::find_child_by_kind(child, "identifier"))
                {
                    let imported_str = imported_node
                        .utf8_text(content.as_bytes())
                        .unwrap_or("")
                        .trim()
                        .to_string();
                    if !imported_str.is_empty() {
                        imports.push(imported_str);
                    }
                }
            }
        }

        java::traverse_java(
            tree.root_node(),
            content,
            file_path,
            &mut nodes,
            &mut raw_calls,
            None,
            None,
            None,
            package_name.as_deref(),
            &imports,
            None,
        );
        java::extract_framework_relationships(
            tree.root_node(),
            content,
            file_path,
            &mut nodes,
            &mut raw_calls,
            package_name.as_deref(),
        );
    } else if lang == "c" || lang == "cpp" || lang == "c++" || lang == "cc" || lang == "cxx" {
        traverse_c_like(
            tree.root_node(),
            content,
            file_path,
            &mut nodes,
            &mut raw_calls,
            CLikeContext {
                parent_qualified_name: None,
                parent_is_type: false,
            },
            None,
            None,
        );
    } else if lang == "zig" {
        zig::traverse_zig(
            tree.root_node(),
            content,
            file_path,
            &mut nodes,
            &mut raw_calls,
            None,
            None,
        );
    }

    Ok((nodes, raw_calls))
}

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

    #[test]
    fn test_parse_rust_code() {
        let rust_code = r#"
/// A simple Rust struct.
pub struct Point {
    pub x: i32,
    pub y: i32,
}

/// Point implementation.
impl Point {
    /// Create a new point.
    pub fn new(x: i32, y: i32) -> Self {
        Point { x, y }
    }

    /// Retrieve sum of coordinates.
    pub fn sum(&self) -> i32 {
        self.helper()
    }

    fn helper(&self) -> i32 {
        self.x + self.y
    }
}

/// Enum for directions.
pub enum Direction {
    Up,
    Down,
}

/// Trait for displaying point information.
pub trait Printable {
    fn print(&self);
}

fn test_free_fn() {
    let p = Point::new(1, 2);
    p.sum();
}
"#;

        let (nodes, calls) = parse_code("src/point.rs", rust_code, "rust").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        // Let's assert nodes
        let struct_node = nodes
            .iter()
            .find(|n| n.name == "Point" && n.kind == "struct")
            .unwrap();
        assert_eq!(struct_node.id, "src/point.rs::Point");
        assert_eq!(
            struct_node.doc_comment.as_deref(),
            Some("/// A simple Rust struct.")
        );
        assert_eq!(struct_node.signature.as_deref(), Some("pub struct Point"));

        let enum_node = nodes
            .iter()
            .find(|n| n.name == "Direction" && n.kind == "enum")
            .unwrap();
        assert_eq!(enum_node.id, "src/point.rs::Direction");
        assert_eq!(
            enum_node.doc_comment.as_deref(),
            Some("/// Enum for directions.")
        );

        let trait_node = nodes
            .iter()
            .find(|n| n.name == "Printable" && n.kind == "trait")
            .unwrap();
        assert_eq!(trait_node.id, "src/point.rs::Printable");
        assert_eq!(
            trait_node.doc_comment.as_deref(),
            Some("/// Trait for displaying point information.")
        );

        // Methods within impl block
        let new_method = nodes
            .iter()
            .find(|n| n.name == "new" && n.kind == "method")
            .unwrap();
        assert_eq!(new_method.id, "src/point.rs::Point::new");
        assert_eq!(
            new_method.doc_comment.as_deref(),
            Some("/// Create a new point.")
        );
        assert_eq!(
            new_method.signature.as_deref(),
            Some("pub fn new(x: i32, y: i32) -> Self")
        );

        let sum_method = nodes
            .iter()
            .find(|n| n.name == "sum" && n.kind == "method")
            .unwrap();
        assert_eq!(sum_method.id, "src/point.rs::Point::sum");
        assert_eq!(
            sum_method.doc_comment.as_deref(),
            Some("/// Retrieve sum of coordinates.")
        );

        let helper_method = nodes
            .iter()
            .find(|n| n.name == "helper" && n.kind == "method")
            .unwrap();
        assert_eq!(helper_method.id, "src/point.rs::Point::helper");

        let free_fn = nodes
            .iter()
            .find(|n| n.name == "test_free_fn" && n.kind == "function")
            .unwrap();
        assert_eq!(free_fn.id, "src/point.rs::test_free_fn");

        // Edges: sum calls helper
        let edge_sum_helper = edges
            .iter()
            .find(|e| e.source_id == sum_method.id && e.target_id == helper_method.id)
            .unwrap();
        assert_eq!(edge_sum_helper.kind, "calls");

        // Edges: test_free_fn calls Point::new (via new) and sum
        let edge_free_new = edges
            .iter()
            .find(|e| e.source_id == free_fn.id && e.target_id == new_method.id)
            .unwrap();
        assert_eq!(edge_free_new.kind, "calls");

        let edge_free_sum = edges
            .iter()
            .find(|e| e.source_id == free_fn.id && e.target_id == sum_method.id)
            .unwrap();
        assert_eq!(edge_free_sum.kind, "calls");
    }

    #[test]
    fn test_resolve_calls_global_prefers_explicit_namespace() {
        let nodes = vec![
            Node {
                id: "src/shapes.rs::Point::new".to_string(),
                name: "new".to_string(),
                kind: "method".to_string(),
                qualified_name: Some("Point::new".to_string()),
                file_path: "src/shapes.rs".to_string(),
                start_line: 1,
                end_line: 1,
                start_column: 0,
                end_column: 0,
                signature: None,
                doc_comment: None,
                is_test: false,
                resolution_kind: None,
                confidence: None,
            },
            Node {
                id: "src/shapes.rs::Line::new".to_string(),
                name: "new".to_string(),
                kind: "method".to_string(),
                qualified_name: Some("Line::new".to_string()),
                file_path: "src/shapes.rs".to_string(),
                start_line: 2,
                end_line: 2,
                start_column: 0,
                end_column: 0,
                signature: None,
                doc_comment: None,
                is_test: false,
                resolution_kind: None,
                confidence: None,
            },
            Node {
                id: "src/shapes.rs::build".to_string(),
                name: "build".to_string(),
                kind: "function".to_string(),
                qualified_name: Some("build".to_string()),
                file_path: "src/shapes.rs".to_string(),
                start_line: 3,
                end_line: 3,
                start_column: 0,
                end_column: 0,
                signature: None,
                doc_comment: None,
                is_test: false,
                resolution_kind: None,
                confidence: None,
            },
        ];
        let calls = vec![RawCall::new(
            "src/shapes.rs::build".to_string(),
            "Line::new".to_string(),
            3,
            4,
        )];

        let edges = resolve_calls_local(&nodes, &calls);

        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].source_id, "src/shapes.rs::build");
        assert_eq!(edges[0].target_id, "src/shapes.rs::Line::new");
    }

    #[test]
    fn test_symbol_index_interns_ids_paths_and_namespaces() {
        let nodes = vec![
            Node {
                id: "src/shapes.rs::Point::new".to_string(),
                name: "new".to_string(),
                kind: "method".to_string(),
                qualified_name: Some("Point::new".to_string()),
                file_path: "src/shapes.rs".to_string(),
                start_line: 1,
                end_line: 1,
                start_column: 0,
                end_column: 0,
                signature: None,
                doc_comment: None,
                is_test: false,
                resolution_kind: None,
                confidence: None,
            },
            Node {
                id: "src/shapes.rs::Point::sum".to_string(),
                name: "sum".to_string(),
                kind: "method".to_string(),
                qualified_name: Some("Point::sum".to_string()),
                file_path: "src/shapes.rs".to_string(),
                start_line: 2,
                end_line: 2,
                start_column: 0,
                end_column: 0,
                signature: None,
                doc_comment: None,
                is_test: false,
                resolution_kind: None,
                confidence: None,
            },
        ];

        let index = SymbolIndex::from_nodes(&nodes);

        assert_eq!(index.symbols.len(), 2);
        assert_ne!(index.symbols[0].id, index.symbols[1].id);
        assert_eq!(index.symbols[0].file_path, index.symbols[1].file_path);
        assert_eq!(index.symbols[0].namespace, index.symbols[1].namespace);
        assert_eq!(
            index.strings[index.symbols[0].file_path as usize],
            "src/shapes.rs"
        );
        assert_eq!(
            index.strings[index.symbols[0].namespace.unwrap() as usize],
            "Point"
        );
    }

    #[test]
    fn test_parse_go_code() {
        let go_code = r#"
package geometry

// Point represents a 2D point.
type Point struct {
	X, Y int
}

// Printer is an interface.
type Printer interface {
	Print()
}

// NewPoint creates a new point.
func NewPoint(x, y int) *Point {
	return &Point{X: x, Y: y}
}

// Distance calculates distance.
func (p *Point) Distance() float64 {
	p.helper()
	return 0.0
}

func (p *Point) helper() {
	// nested helper
}
"#;

        let (nodes, calls) = parse_code("geometry.go", go_code, "go").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        // Assert nodes
        let struct_node = nodes
            .iter()
            .find(|n| n.name == "Point" && n.kind == "struct")
            .unwrap();
        assert_eq!(struct_node.id, "geometry.go::Point");
        assert_eq!(
            struct_node.doc_comment.as_deref(),
            Some("// Point represents a 2D point.")
        );
        assert_eq!(struct_node.signature.as_deref(), Some("type Point"));

        let interface_node = nodes
            .iter()
            .find(|n| n.name == "Printer" && n.kind == "interface")
            .unwrap();
        assert_eq!(interface_node.id, "geometry.go::Printer");
        assert_eq!(
            interface_node.doc_comment.as_deref(),
            Some("// Printer is an interface.")
        );

        let func_node = nodes
            .iter()
            .find(|n| n.name == "NewPoint" && n.kind == "function")
            .unwrap();
        assert_eq!(func_node.id, "geometry.go::NewPoint");
        assert_eq!(
            func_node.doc_comment.as_deref(),
            Some("// NewPoint creates a new point.")
        );
        assert_eq!(
            func_node.signature.as_deref(),
            Some("func NewPoint(x, y int) *Point")
        );

        let method_node = nodes
            .iter()
            .find(|n| n.name == "Distance" && n.kind == "method")
            .unwrap();
        assert_eq!(method_node.id, "geometry.go::Point::Distance");
        assert_eq!(
            method_node.doc_comment.as_deref(),
            Some("// Distance calculates distance.")
        );
        assert_eq!(
            method_node.signature.as_deref(),
            Some("func (p *Point) Distance() float64")
        );

        let helper_method = nodes
            .iter()
            .find(|n| n.name == "helper" && n.kind == "method")
            .unwrap();
        assert_eq!(helper_method.id, "geometry.go::Point::helper");

        // Edges: Distance calls helper
        let edge_call = edges
            .iter()
            .find(|e| e.source_id == method_node.id && e.target_id == helper_method.id)
            .unwrap();
        assert_eq!(edge_call.kind, "calls");
    }

    #[test]
    fn test_parse_java_code() {
        let java_code = r#"
/**
 * A sample Java class.
 */
public class App {
    private String name;

    /**
     * Constructor.
     */
    public App(String name) {
        this.name = name;
        init();
    }

    /**
     * Init method.
     */
    public void init() {
        // init
    }

    /**
     * Run method.
     */
    public void run() {
        System.out.println("Run");
    }

    /**
     * Main entry point.
     */
    public static void main(String[] args) {
        App app = new App("Demo");
        app.run();
    }
}
"#;

        let (nodes, calls) = parse_code("src/App.java", java_code, "java").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        // Find class node
        let class_node = nodes
            .iter()
            .find(|n| n.name == "App" && n.kind == "class")
            .unwrap();
        assert_eq!(class_node.id, "src/App.java::App");
        assert_eq!(
            class_node.doc_comment.as_deref(),
            Some("/**\n * A sample Java class.\n */")
        );
        assert_eq!(class_node.signature.as_deref(), Some("public class App"));

        // Find constructor node
        let constr_node = nodes
            .iter()
            .find(|n| n.name == "App" && n.kind == "constructor")
            .unwrap();
        assert_eq!(constr_node.id, "src/App.java::App::App");
        assert_eq!(
            constr_node.doc_comment.as_deref(),
            Some("/**\n     * Constructor.\n     */")
        );
        assert_eq!(
            constr_node.signature.as_deref(),
            Some("public App(String name)")
        );

        // Find init method
        let init_method = nodes
            .iter()
            .find(|n| n.name == "init" && n.kind == "method")
            .unwrap();
        assert_eq!(init_method.id, "src/App.java::App::init");
        assert_eq!(
            init_method.doc_comment.as_deref(),
            Some("/**\n     * Init method.\n     */")
        );
        assert_eq!(init_method.signature.as_deref(), Some("public void init()"));

        // Find run method
        let run_method = nodes
            .iter()
            .find(|n| n.name == "run" && n.kind == "method")
            .unwrap();
        assert_eq!(run_method.id, "src/App.java::App::run");

        // Find main method
        let main_method = nodes
            .iter()
            .find(|n| n.name == "main" && n.kind == "method")
            .unwrap();
        assert_eq!(main_method.id, "src/App.java::App::main");

        // Check call edges
        // Constructor App calls init
        let edge_constr_init = edges
            .iter()
            .find(|e| e.source_id == constr_node.id && e.target_id == init_method.id)
            .unwrap();
        assert_eq!(edge_constr_init.kind, "calls");

        // main calls constructor (via new App)
        let edge_main_constr = edges
            .iter()
            .find(|e| e.source_id == main_method.id && e.target_id == constr_node.id)
            .unwrap();
        assert_eq!(edge_main_constr.kind, "calls");

        // main calls run method (via app.run)
        let edge_main_run = edges
            .iter()
            .find(|e| e.source_id == main_method.id && e.target_id == run_method.id)
            .unwrap();
        assert_eq!(edge_main_run.kind, "calls");
    }

    #[test]
    fn test_parse_spring_routes() {
        let java_code = r#"
@RestController
@RequestMapping(value = "/api/v2")
public class UserController {
    @GetMapping("/users/{id}")
    public User getUser(@PathVariable String id) {
        return null;
    }

    @PostMapping(path = {"/users", "/create"})
    public User createUser() {
        return null;
    }

    @RequestMapping(value = "/status", method = RequestMethod.POST)
    public String getStatus() {
        return "OK";
    }
}
"#;

        let (nodes, calls) = parse_code("src/UserController.java", java_code, "java").unwrap();

        let class_node = nodes
            .iter()
            .find(|n| n.name == "UserController" && n.kind == "class")
            .unwrap();
        assert_eq!(class_node.id, "src/UserController.java::UserController");

        let get_user = nodes
            .iter()
            .find(|n| n.name == "getUser" && n.kind == "method")
            .unwrap();
        let create_user = nodes
            .iter()
            .find(|n| n.name == "createUser" && n.kind == "method")
            .unwrap();
        let get_status = nodes
            .iter()
            .find(|n| n.name == "getStatus" && n.kind == "method")
            .unwrap();

        let route_get = nodes
            .iter()
            .find(|n| {
                n.id == "src/UserController.java::UserController::getUser::route::GET /api/v2/users/{id}"
            })
            .unwrap();
        assert_eq!(route_get.name, "GET /api/v2/users/{id}");
        assert_eq!(route_get.kind, "route");
        assert_eq!(
            route_get.qualified_name.as_deref(),
            Some("GET /api/v2/users/{id}")
        );

        let route_create1 = nodes
            .iter()
            .find(|n| {
                n.id == "src/UserController.java::UserController::createUser::route::POST /api/v2/users"
            })
            .unwrap();
        assert_eq!(route_create1.name, "POST /api/v2/users");

        let route_create2 = nodes
            .iter()
            .find(|n| {
                n.id == "src/UserController.java::UserController::createUser::route::POST /api/v2/create"
            })
            .unwrap();
        assert_eq!(route_create2.name, "POST /api/v2/create");

        let route_status = nodes
            .iter()
            .find(|n| {
                n.id == "src/UserController.java::UserController::getStatus::route::POST /api/v2/status"
            })
            .unwrap();
        assert_eq!(route_status.name, "POST /api/v2/status");

        let edges = resolve_calls_local(&nodes, &calls);

        let edge_get = edges.iter().find(|e| e.source_id == route_get.id).unwrap();
        assert_eq!(edge_get.target_id, get_user.id);
        assert_eq!(edge_get.kind, "route_handler");

        let edge_create1 = edges
            .iter()
            .find(|e| e.source_id == route_create1.id)
            .unwrap();
        assert_eq!(edge_create1.target_id, create_user.id);

        let edge_create2 = edges
            .iter()
            .find(|e| e.source_id == route_create2.id)
            .unwrap();
        assert_eq!(edge_create2.target_id, create_user.id);

        let edge_status = edges
            .iter()
            .find(|e| e.source_id == route_status.id)
            .unwrap();
        assert_eq!(edge_status.target_id, get_status.id);
    }

    #[test]
    fn test_parse_spring_routes_keeps_duplicate_paths_distinct() {
        let first = r#"
@RestController
@RequestMapping("/api")
public class FirstController {
    @RequestMapping("/status")
    public String status() {
        return "first";
    }

}
"#;
        let second = r#"
@RestController
@RequestMapping("/api")
public class SecondController {
    @RequestMapping("/status")
    public String status() {
        return "second";
    }
}
"#;

        let (mut nodes, mut calls) = parse_code("src/FirstController.java", first, "java").unwrap();
        let (second_nodes, second_calls) =
            parse_code("src/SecondController.java", second, "java").unwrap();
        nodes.extend(second_nodes);
        calls.extend(second_calls);

        let first_route = nodes
            .iter()
            .find(|n| {
                n.id == "src/FirstController.java::FirstController::status::route::ANY /api/status"
            })
            .unwrap();
        let second_route = nodes
            .iter()
            .find(|n| {
                n.id
                    == "src/SecondController.java::SecondController::status::route::ANY /api/status"
            })
            .unwrap();
        assert_ne!(first_route.id, second_route.id);
        assert_eq!(first_route.name, "ANY /api/status");
        assert_eq!(second_route.name, "ANY /api/status");

        let edges = resolve_calls_local(&nodes, &calls);
        let first_status = nodes
            .iter()
            .find(|n| n.id == "src/FirstController.java::FirstController::status")
            .unwrap();
        let second_status = nodes
            .iter()
            .find(|n| n.id == "src/SecondController.java::SecondController::status")
            .unwrap();
        assert!(edges
            .iter()
            .any(|e| e.source_id == first_route.id && e.target_id == first_status.id));
        assert!(edges
            .iter()
            .any(|e| e.source_id == second_route.id && e.target_id == second_status.id));
    }

    #[test]
    fn test_parse_java_framework_relationships_are_explicit_and_non_exact() {
        let java_code = r#"
@RestController class ApiController {
    private final Orders orders;
    ApiController(Orders orders) { this.orders = orders; }
    @GetMapping("/orders") public String list() { return "ok"; }
}
interface Orders {}
@ConfigurationProperties("billing") class BillingProperties {}
@Component class Publisher {
    @Value("${billing.timeout}") String timeout;
    ApplicationEventPublisher events;
    void publish() { events.publishEvent(new InvoiceCreated()); }
}
class InvoiceCreated {}
@Component class Listener {
  @EventListener(InvoiceCreated.class) void receive(InvoiceCreated event) {}
  @EventListener void inferred(InvoiceCreated event) {}
}
@Component class TypedPublisher {
  ApplicationEventPublisher events;
  void publishTyped() { InvoiceCreated event = new InvoiceCreated(); events.publishEvent(event); }
  void noise() { String text = "publishEvent(new WrongEvent())"; }
}
class WrongEvent {}
@FeignClient(name = "catalog") interface CatalogClient { @GetMapping("/products") Product getProduct(); }
class Product {}
@GrpcService class HelloService extends HelloGrpc.HelloImplBase { void sayHello(Request request) {} }
@Component class HelloClient { HelloGrpc.HelloBlockingStub stub; void call() { stub.sayHello(new Request()); } }
class Request {}
@Component class Outer { class Nested { Nested(Orders orders) {} } }
"#;
        let (nodes, calls) = parse_code("src/App.java", java_code, "java").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);
        let edge = |kind: &str, source_suffix: &str, target_suffix: &str| {
            edges.iter().find(|edge| {
                edge.kind == kind
                    && edge.source_id.ends_with(source_suffix)
                    && edge.target_id.ends_with(target_suffix)
            })
        };
        assert_eq!(
            edge("route_handler", "route::GET /orders", "ApiController::list")
                .unwrap()
                .resolution_kind,
            6
        );
        assert_eq!(
            edge("injected_into", "Orders", "ApiController")
                .unwrap()
                .resolution_kind,
            7
        );
        assert!(edge(
            "configuration_binds",
            "config::billing::BillingProperties",
            "BillingProperties"
        )
        .is_some());
        assert!(edge(
            "configuration_binds",
            "config::billing.timeout::Publisher",
            "Publisher"
        )
        .is_some());
        assert!(edge("publishes_event", "Publisher::publish", "InvoiceCreated").is_some());
        assert!(edge(
            "publishes_event",
            "TypedPublisher::publishTyped",
            "InvoiceCreated"
        )
        .is_some());
        assert!(edge("publishes_event", "TypedPublisher::noise", "WrongEvent").is_none());
        assert!(edge("consumes_event", "InvoiceCreated", "Listener::receive").is_some());
        assert!(edge("consumes_event", "InvoiceCreated", "Listener::inferred").is_some());
        assert!(edge(
            "feign_calls",
            "CatalogClient::getProduct",
            "feign::catalog::CatalogClient::getProduct"
        )
        .is_some());
        assert!(edge("grpc_calls", "HelloClient::call", "grpc::Hello::sayHello").is_some());
        assert!(
            edges
                .iter()
                .filter(|edge| edge.kind != "calls")
                .all(|edge| edge.resolution_kind != 5),
            "{edges:?}"
        );

        let plain = r#"class Plain { Plain(Orders orders) {} } interface Orders {}"#;
        let (plain_nodes, plain_calls) = parse_code("src/Plain.java", plain, "java").unwrap();
        assert!(resolve_calls_local(&plain_nodes, &plain_calls)
            .iter()
            .all(|edge| edge.kind != "injected_into"));
        assert!(edges
            .iter()
            .all(|edge| !edge.target_id.ends_with("Outer::Nested")));

        let mut missing_endpoint = RawCall::new(
            "src/App.java::CatalogClient::getProduct".to_string(),
            "getProduct".to_string(),
            1,
            0,
        );
        missing_endpoint.relationship_kind = "feign_calls".to_string();
        missing_endpoint.target_qualified_hint = Some("feign::catalog::missing".to_string());
        missing_endpoint.resolution_hint = Some(6);
        let (missing_edges, missing_unresolved) =
            resolve_calls_global(&[missing_endpoint], &SymbolIndex::from_nodes(&nodes));
        assert!(missing_edges.is_empty());
        assert_eq!(missing_unresolved.len(), 1);
        assert_eq!(missing_unresolved[0].kind, "feign_calls");

        let mut duplicate_name = RawCall::new(
            "src/App.java::ApiController".to_string(),
            "getProduct".to_string(),
            1,
            0,
        );
        duplicate_name.relationship_kind = "injected_into".to_string();
        duplicate_name.resolution_hint = Some(6);
        let (duplicate_edges, _) =
            resolve_calls_global(&[duplicate_name], &SymbolIndex::from_nodes(&nodes));
        assert!(duplicate_edges.iter().all(|edge| edge.resolution_kind != 6));
    }

    #[test]
    fn test_parse_c_code() {
        let c_code = r#"
// Point struct.
struct Point {
    int x;
    int y;
};

// Helper function.
int helper(int value) {
    return value + 1;
}

// Main entry point.
int main(void) {
    return helper(41);
}
"#;

        let (nodes, calls) = parse_code("src/main.c", c_code, "c").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        let struct_node = nodes
            .iter()
            .find(|n| n.name == "Point" && n.kind == "struct")
            .unwrap();
        assert_eq!(struct_node.id, "src/main.c::Point");
        assert_eq!(struct_node.doc_comment.as_deref(), Some("// Point struct."));

        let helper = nodes
            .iter()
            .find(|n| n.name == "helper" && n.kind == "function")
            .unwrap();
        assert_eq!(helper.id, "src/main.c::helper");
        assert_eq!(helper.doc_comment.as_deref(), Some("// Helper function."));

        let main = nodes
            .iter()
            .find(|n| n.name == "main" && n.kind == "function")
            .unwrap();
        assert_eq!(main.id, "src/main.c::main");

        let edge_main_helper = edges
            .iter()
            .find(|e| e.source_id == main.id && e.target_id == helper.id)
            .unwrap();
        assert_eq!(edge_main_helper.kind, "calls");
    }

    #[test]
    fn test_parse_cpp_code() {
        let cpp_code = r#"
namespace demo {
// Point class.
class Point {
public:
    int sum() {
        return helper();
    }

    int helper() {
        return 42;
    }
};

int run() {
    Point point;
    return point.sum();
}
}
"#;

        let (nodes, calls) = parse_code("src/point.cpp", cpp_code, "cpp").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        let namespace = nodes
            .iter()
            .find(|n| n.name == "demo" && n.kind == "namespace")
            .unwrap();
        assert_eq!(namespace.id, "src/point.cpp::demo");

        let class_node = nodes
            .iter()
            .find(|n| n.name == "Point" && n.kind == "class")
            .unwrap();
        assert_eq!(class_node.id, "src/point.cpp::demo::Point");
        assert_eq!(class_node.doc_comment.as_deref(), Some("// Point class."));

        let sum_method = nodes
            .iter()
            .find(|n| n.name == "sum" && n.kind == "method")
            .unwrap();
        assert_eq!(sum_method.id, "src/point.cpp::demo::Point::sum");

        let helper_method = nodes
            .iter()
            .find(|n| n.name == "helper" && n.kind == "method")
            .unwrap();
        assert_eq!(helper_method.id, "src/point.cpp::demo::Point::helper");

        let run = nodes
            .iter()
            .find(|n| n.name == "run" && n.kind == "function")
            .unwrap();
        assert_eq!(run.id, "src/point.cpp::demo::run");

        let edge_sum_helper = edges
            .iter()
            .find(|e| e.source_id == sum_method.id && e.target_id == helper_method.id)
            .unwrap();
        assert_eq!(edge_sum_helper.kind, "calls");

        let edge_run_sum = edges
            .iter()
            .find(|e| e.source_id == run.id && e.target_id == sum_method.id)
            .unwrap();
        assert_eq!(edge_run_sum.kind, "calls");
    }

    #[test]
    fn test_parse_zig_code() {
        let zig_code = r#"
/// Point type.
const Point = struct {
    x: i32,
    y: i32,

    /// Sum fields.
    fn sum(self: Point) i32 {
        return self.helper();
    }

    fn helper(self: Point) i32 {
        return self.x + self.y;
    }
};

fn makePoint() Point {
    return Point{ .x = 1, .y = 2 };
}

pub fn main() void {
    const point = makePoint();
    _ = point.sum();
}
"#;

        let (nodes, calls) = parse_code("src/main.zig", zig_code, "zig").unwrap();
        let edges = resolve_calls_local(&nodes, &calls);

        let struct_node = nodes
            .iter()
            .find(|n| n.name == "Point" && n.kind == "struct")
            .unwrap();
        assert_eq!(struct_node.id, "src/main.zig::Point");
        assert_eq!(struct_node.doc_comment.as_deref(), Some("/// Point type."));

        let sum_method = nodes
            .iter()
            .find(|n| n.name == "sum" && n.kind == "method")
            .unwrap();
        assert_eq!(sum_method.id, "src/main.zig::Point::sum");
        assert_eq!(sum_method.doc_comment.as_deref(), Some("/// Sum fields."));

        let helper_method = nodes
            .iter()
            .find(|n| n.name == "helper" && n.kind == "method")
            .unwrap();
        assert_eq!(helper_method.id, "src/main.zig::Point::helper");

        let make_point = nodes
            .iter()
            .find(|n| n.name == "makePoint" && n.kind == "function")
            .unwrap();
        assert_eq!(make_point.id, "src/main.zig::makePoint");

        let main = nodes
            .iter()
            .find(|n| n.name == "main" && n.kind == "function")
            .unwrap();
        assert_eq!(main.id, "src/main.zig::main");

        let edge_sum_helper = edges
            .iter()
            .find(|e| e.source_id == sum_method.id && e.target_id == helper_method.id)
            .unwrap();
        assert_eq!(edge_sum_helper.kind, "calls");

        let edge_main_make_point = edges
            .iter()
            .find(|e| e.source_id == main.id && e.target_id == make_point.id)
            .unwrap();
        assert_eq!(edge_main_make_point.kind, "calls");

        let edge_main_sum = edges
            .iter()
            .find(|e| e.source_id == main.id && e.target_id == sum_method.id)
            .unwrap();
        assert_eq!(edge_main_sum.kind, "calls");
    }

    #[test]
    fn test_parse_cpp_out_of_line_method() {
        // An out-of-line method defined inside its namespace should inherit the
        // namespace prefix so it matches the in-class declaration's qname.
        let cpp_code = r#"
namespace demo {
class Point {
public:
    int sum();
};

int Point::sum() {
    return 42;
}
}
"#;

        let (nodes, _calls) = parse_code("src/point.cpp", cpp_code, "cpp").unwrap();

        let sum_method = nodes
            .iter()
            .find(|n| n.name == "sum" && n.kind == "method")
            .unwrap();
        assert_eq!(sum_method.id, "src/point.cpp::demo::Point::sum");
    }

    #[test]
    fn test_parse_zig_keyword_in_string_is_not_a_type() {
        // The container-kind heuristic must not treat a string literal (or a
        // plain value) containing "struct"/"enum"/"union" as a type symbol.
        let zig_code = r#"
const message = "this mentions a struct and an enum";
const Real = struct {
    x: i32,
};
"#;

        let (nodes, _calls) = parse_code("src/main.zig", zig_code, "zig").unwrap();

        assert!(
            nodes.iter().all(|n| n.name != "message"),
            "string-valued const should not be indexed as a type"
        );
        assert!(
            nodes.iter().any(|n| n.name == "Real" && n.kind == "struct"),
            "genuine struct declaration should still be indexed"
        );
    }
}