repotoire 0.8.1

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
//! Java parser using tree-sitter
//!
//! Extracts classes, interfaces, methods, imports, and call relationships from Java source code.

use crate::models::{Class, Function};
use crate::parsers::{ImportInfo, ParseResult};
use anyhow::{Context, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::Path;
use std::sync::OnceLock;
use tree_sitter::{Node, Parser, Query, QueryCursor, StreamingIterator};

thread_local! {
    static JAVA_PARSER: RefCell<Parser> = RefCell::new({
        let mut p = Parser::new();
        p.set_language(&tree_sitter_java::LANGUAGE.into()).expect("Java language");
        p
    });
}

const JAVA_IMPORT_QUERY_STR: &str = r#"
    (import_declaration
        (scoped_identifier) @import_path
    )
    (import_declaration
        (identifier) @import_path
    )
"#;

static JAVA_IMPORT_QUERY: OnceLock<Query> = OnceLock::new();

/// Parse a Java file and extract all code entities
#[allow(dead_code)]
pub fn parse(path: &Path) -> Result<ParseResult> {
    let source = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read file: {}", path.display()))?;

    parse_source(&source, path)
}

/// Parse Java source code directly (useful for testing)
pub fn parse_source(source: &str, path: &Path) -> Result<ParseResult> {
    parse_source_with_tree(source, path).map(|(r, _)| r)
}

/// Parse Java source code and return both the ParseResult and the tree-sitter Tree.
pub fn parse_source_with_tree(
    source: &str,
    path: &Path,
) -> Result<(ParseResult, tree_sitter::Tree)> {
    let tree = JAVA_PARSER
        .with(|cell| cell.borrow_mut().parse(source, None))
        .context("Failed to parse Java source")?;

    let root = tree.root_node();
    let extractor = JavaExtractor::new(source.as_bytes(), path);
    let result = extractor.run(root)?;
    Ok((result, tree))
}

/// Stateful walker over a parsed Java tree.
///
/// Holds the immutable inputs (source bytes, file path) and the mutable
/// `ParseResult` accumulator as fields, so visitor methods don't have
/// to thread a `(node, source, path, result)` tuple through every
/// recursion. Each `extract_*` method appends to `self.result`; the
/// caller drives the pipeline via [`Self::run`] and consumes the final
/// result.
struct JavaExtractor<'a> {
    source: &'a [u8],
    path: &'a Path,
    result: ParseResult,
}

impl<'a> JavaExtractor<'a> {
    fn new(source: &'a [u8], path: &'a Path) -> Self {
        Self {
            source,
            path,
            result: ParseResult::default(),
        }
    }

    /// Run the full extraction pipeline against the given tree root and
    /// return the accumulated [`ParseResult`].
    fn run(mut self, root: Node<'_>) -> Result<ParseResult> {
        self.extract_classes_and_interfaces(&root)?;
        self.extract_imports(&root)?;
        self.extract_calls(&root)?;
        Ok(self.result)
    }
}

impl<'a> JavaExtractor<'a> {
    /// Extract class and interface definitions from the AST
    fn extract_classes_and_interfaces(&mut self, root: &Node) -> Result<()> {
        self.extract_classes_recursive(root, None);
        Ok(())
    }

    /// Recursively extract classes (handles nested classes)
    fn extract_classes_recursive(&mut self, node: &Node, parent_class: Option<&str>) {
        for child in node.children(&mut node.walk()) {
            match child.kind() {
                "class_declaration" => {
                    if let Some(class) = self.parse_class_node(&child, parent_class) {
                        let class_name = class.name.clone();
                        // Extract methods from the class
                        self.extract_class_methods(&child, &class_name);
                        self.result.classes.push(class);

                        // Handle nested classes
                        if let Some(body) = child.child_by_field_name("body") {
                            self.extract_classes_recursive(&body, Some(&class_name));
                        }
                    }
                }
                "interface_declaration" => {
                    if let Some(iface) = self.parse_interface_node(&child, parent_class) {
                        let iface_name = iface.name.clone();
                        // Extract methods from the interface
                        self.extract_interface_methods(&child, &iface_name);
                        self.result.classes.push(iface);
                    }
                }
                "enum_declaration" => {
                    if let Some(enum_class) = self.parse_enum_node(&child, parent_class) {
                        let enum_name = enum_class.name.clone();
                        self.extract_class_methods(&child, &enum_name);
                        self.result.classes.push(enum_class);
                    }
                }
                "record_declaration" => {
                    if let Some(record) = self.parse_record_node(&child, parent_class) {
                        let record_name = record.name.clone();
                        self.extract_class_methods(&child, &record_name);
                        self.result.classes.push(record);
                    }
                }
                _ => {
                    // Continue searching in other nodes
                    self.extract_classes_recursive(&child, parent_class);
                }
            }
        }
    }
}

impl<'a> JavaExtractor<'a> {
    /// Parse a class declaration into a Class struct
    fn parse_class_node(&self, node: &Node, parent: Option<&str>) -> Option<Class> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let full_name = if let Some(parent_name) = parent {
            format!("{}.{}", parent_name, name)
        } else {
            name.clone()
        };

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!("{}::{}:{}", self.path.display(), full_name, line_start);

        // Extract superclass
        let mut bases = Vec::new();
        if let Some(superclass) = node.child_by_field_name("superclass") {
            if let Ok(text) = superclass.utf8_text(self.source) {
                // Remove 'extends ' prefix if present
                let base = text.trim_start_matches("extends ").trim().to_string();
                if !base.is_empty() {
                    bases.push(base);
                }
            }
        }

        // Extract implemented interfaces
        if let Some(interfaces) = node.child_by_field_name("interfaces") {
            for child in interfaces.children(&mut interfaces.walk()) {
                if child.kind() == "type_identifier" || child.kind() == "generic_type" {
                    if let Ok(text) = child.utf8_text(self.source) {
                        bases.push(text.to_string());
                    }
                }
            }
        }

        // Extract method names from body
        let methods = extract_method_names(node, self.source);

        let doc_comment = extract_doc_comment(node, self.source);
        let annotations = extract_annotations(node, self.source);

        Some(Class {
            name: full_name,
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            methods,
            field_count: 0,
            bases,
            doc_comment,
            annotations,
        })
    }

    /// Parse an interface declaration into a Class struct
    fn parse_interface_node(&self, node: &Node, parent: Option<&str>) -> Option<Class> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let full_name = if let Some(parent_name) = parent {
            format!("{}.{}", parent_name, name)
        } else {
            name.clone()
        };

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!(
            "{}::interface::{}:{}",
            self.path.display(),
            full_name,
            line_start
        );

        // Extract extended interfaces
        let mut bases = Vec::new();
        for child in node.children(&mut node.walk()) {
            if child.kind() == "extends_interfaces" {
                for grandchild in child.children(&mut child.walk()) {
                    if grandchild.kind() == "type_identifier" || grandchild.kind() == "generic_type"
                    {
                        if let Ok(text) = grandchild.utf8_text(self.source) {
                            bases.push(text.to_string());
                        }
                    }
                }
            }
        }

        let methods = extract_method_names(node, self.source);
        let doc_comment = extract_doc_comment(node, self.source);
        let annotations = extract_annotations(node, self.source);

        Some(Class {
            name: full_name,
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            methods,
            field_count: 0,
            bases,
            doc_comment,
            annotations,
        })
    }

    /// Parse an enum declaration into a Class struct
    fn parse_enum_node(&self, node: &Node, parent: Option<&str>) -> Option<Class> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let full_name = if let Some(parent_name) = parent {
            format!("{}.{}", parent_name, name)
        } else {
            name.clone()
        };

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!(
            "{}::enum::{}:{}",
            self.path.display(),
            full_name,
            line_start
        );

        let methods = extract_method_names(node, self.source);
        let doc_comment = extract_doc_comment(node, self.source);
        let annotations = extract_annotations(node, self.source);

        Some(Class {
            name: full_name,
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            methods,
            field_count: 0,
            bases: vec![],
            doc_comment,
            annotations,
        })
    }

    /// Parse a record declaration into a Class struct
    fn parse_record_node(&self, node: &Node, parent: Option<&str>) -> Option<Class> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let full_name = if let Some(parent_name) = parent {
            format!("{}.{}", parent_name, name)
        } else {
            name.clone()
        };

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!(
            "{}::record::{}:{}",
            self.path.display(),
            full_name,
            line_start
        );

        let methods = extract_method_names(node, self.source);
        let doc_comment = extract_doc_comment(node, self.source);
        let annotations = extract_annotations(node, self.source);

        Some(Class {
            name: full_name,
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            methods,
            field_count: 0,
            bases: vec![],
            doc_comment,
            annotations,
        })
    }
}

impl<'a> JavaExtractor<'a> {
    /// Extract methods from a class body as Function entities
    fn extract_class_methods(&mut self, class_node: &Node, class_name: &str) {
        let body = class_node.child_by_field_name("body");
        let body_node = body.as_ref().unwrap_or(class_node);

        for child in body_node.children(&mut body_node.walk()) {
            if child.kind() == "method_declaration" {
                if let Some(func) = self.parse_method_node(&child, class_name) {
                    self.result.functions.push(func);
                }
            } else if child.kind() == "constructor_declaration" {
                if let Some(func) = self.parse_constructor_node(&child, class_name) {
                    self.result.functions.push(func);
                }
            }
        }
    }

    /// Extract methods from an interface body
    fn extract_interface_methods(&mut self, iface_node: &Node, iface_name: &str) {
        let body = iface_node.child_by_field_name("body");
        let body_node = body.as_ref().unwrap_or(iface_node);

        for child in body_node.children(&mut body_node.walk()) {
            if child.kind() == "method_declaration" {
                if let Some(func) = self.parse_method_node(&child, iface_name) {
                    self.result.functions.push(func);
                }
            }
        }
    }

    /// Parse a method declaration into a Function struct
    fn parse_method_node(&self, node: &Node, class_name: &str) -> Option<Function> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let params_node = node.child_by_field_name("parameters");
        let parameters = extract_parameters(params_node, self.source);

        let return_type = node
            .child_by_field_name("type")
            .and_then(|n| n.utf8_text(self.source).ok())
            .map(|s| s.to_string());

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!(
            "{}::{}.{}:{}",
            self.path.display(),
            class_name,
            name,
            line_start
        );

        let doc_comment = extract_doc_comment(node, self.source);
        let mut annotations = extract_annotations(node, self.source);
        if has_public_modifier(node, self.source) {
            annotations.push("exported".to_string());
        }

        Some(Function {
            name,
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            parameters,
            return_type,
            is_async: false,
            complexity: Some(calculate_complexity(node, self.source)),
            max_nesting: None,
            doc_comment,
            annotations,
        })
    }

    /// Parse a constructor declaration into a Function struct
    fn parse_constructor_node(&self, node: &Node, class_name: &str) -> Option<Function> {
        let name_node = node.child_by_field_name("name")?;
        let name = name_node.utf8_text(self.source).ok()?.to_string();

        let params_node = node.child_by_field_name("parameters");
        let parameters = extract_parameters(params_node, self.source);

        let line_start = node.start_position().row as u32 + 1;
        let line_end = node.end_position().row as u32 + 1;
        let qualified_name = format!(
            "{}::{}.<init>:{}",
            self.path.display(),
            class_name,
            line_start
        );

        let doc_comment = extract_doc_comment(node, self.source);
        let mut annotations = extract_annotations(node, self.source);
        if has_public_modifier(node, self.source) {
            annotations.push("exported".to_string());
        }

        Some(Function {
            name: format!("<init>:{}", name),
            qualified_name,
            file_path: self.path.to_path_buf(),
            line_start,
            line_end,
            parameters,
            return_type: Some(class_name.to_string()),
            is_async: false,
            complexity: Some(calculate_complexity(node, self.source)),
            max_nesting: None,
            doc_comment,
            annotations,
        })
    }
}

/// Extract method names from a class/interface body
fn extract_method_names(class_node: &Node, source: &[u8]) -> Vec<String> {
    let mut methods = Vec::new();

    let body = class_node.child_by_field_name("body");
    let body_node = body.as_ref().unwrap_or(class_node);

    for child in body_node.children(&mut body_node.walk()) {
        if child.kind() == "method_declaration" {
            if let Some(name_node) = child.child_by_field_name("name") {
                if let Ok(name) = name_node.utf8_text(source) {
                    methods.push(name.to_string());
                }
            }
        } else if child.kind() == "constructor_declaration" {
            if let Some(name_node) = child.child_by_field_name("name") {
                if let Ok(name) = name_node.utf8_text(source) {
                    methods.push(format!("<init>:{}", name));
                }
            }
        }
    }

    methods
}

/// Extract parameter names from a formal parameters node
fn extract_parameters(params_node: Option<Node>, source: &[u8]) -> Vec<String> {
    let Some(node) = params_node else {
        return vec![];
    };

    let mut params = Vec::new();

    for child in node.children(&mut node.walk()) {
        if child.kind() == "formal_parameter" || child.kind() == "spread_parameter" {
            if let Some(name_node) = child.child_by_field_name("name") {
                if let Ok(text) = name_node.utf8_text(source) {
                    params.push(text.to_string());
                }
            }
        }
    }

    params
}

impl<'a> JavaExtractor<'a> {
    /// Extract import statements from the AST
    fn extract_imports(&mut self, root: &Node) -> Result<()> {
        let query = JAVA_IMPORT_QUERY.get_or_init(|| {
            Query::new(&tree_sitter_java::LANGUAGE.into(), JAVA_IMPORT_QUERY_STR)
                .expect("valid Java import query")
        });

        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(query, *root, self.source);

        while let Some(m) = matches.next() {
            for capture in m.captures.iter() {
                if let Ok(text) = capture.node.utf8_text(self.source) {
                    self.result
                        .imports
                        .push(ImportInfo::runtime(text.to_string()));
                }
            }
        }

        Ok(())
    }

    /// Extract method calls from the AST
    fn extract_calls(&mut self, root: &Node) -> Result<()> {
        let mut scope_map: HashMap<(u32, u32), String> = HashMap::new();

        for func in &self.result.functions {
            scope_map.insert(
                (func.line_start, func.line_end),
                func.qualified_name.clone(),
            );
        }

        self.extract_calls_recursive(root, &scope_map);

        Ok(())
    }

    /// Recursively extract calls from the AST
    fn extract_calls_recursive(&mut self, node: &Node, scope_map: &HashMap<(u32, u32), String>) {
        if node.kind() == "method_invocation" {
            let call_line = node.start_position().row as u32 + 1;
            // For top-level calls (outside any function), use the file path as the caller
            let caller = find_containing_scope(call_line, scope_map)
                .unwrap_or_else(|| self.path.display().to_string());

            if let Some(name_node) = node.child_by_field_name("name") {
                if let Ok(callee) = name_node.utf8_text(self.source) {
                    // Also try to get the object being called on
                    let full_callee = if let Some(obj_node) = node.child_by_field_name("object") {
                        if let Ok(obj) = obj_node.utf8_text(self.source) {
                            format!("{}.{}", obj, callee)
                        } else {
                            callee.to_string()
                        }
                    } else {
                        callee.to_string()
                    };

                    self.result.calls.push((caller, full_callee));
                }
            }
        }

        // Handle object creation expressions
        if node.kind() == "object_creation_expression" {
            let call_line = node.start_position().row as u32 + 1;
            // For top-level calls (outside any function), use the file path as the caller
            let caller = find_containing_scope(call_line, scope_map)
                .unwrap_or_else(|| self.path.display().to_string());

            if let Some(type_node) = node.child_by_field_name("type") {
                if let Ok(callee) = type_node.utf8_text(self.source) {
                    self.result.calls.push((caller, format!("new {}", callee)));
                }
            }
        }

        for child in node.children(&mut node.walk()) {
            self.extract_calls_recursive(&child, scope_map);
        }
    }
}

/// Find which scope contains a given line
fn find_containing_scope(line: u32, scope_map: &HashMap<(u32, u32), String>) -> Option<String> {
    super::find_containing_scope(line, scope_map)
}

/// Extract Javadoc comment preceding a declaration node.
///
/// Javadoc comments are `/** ... */` block comments immediately before a declaration.
/// Regular `/* */` and `//` comments are ignored.
fn extract_doc_comment(node: &Node, source: &[u8]) -> Option<String> {
    let mut sibling = node.prev_sibling();

    // Skip annotations to find the doc comment before them
    while let Some(sib) = sibling {
        if sib.kind() == "marker_annotation"
            || sib.kind() == "annotation"
            || sib.kind() == "modifiers"
        {
            // Check inside modifiers for block_comment (Javadoc)
            if sib.kind() == "modifiers" {
                for child in sib.children(&mut sib.walk()) {
                    if child.kind() == "block_comment" {
                        if let Ok(text) = child.utf8_text(source) {
                            if text.starts_with("/**") {
                                let doc = text
                                    .trim_start_matches("/**")
                                    .trim_end_matches("*/")
                                    .lines()
                                    .map(|line| {
                                        let trimmed = line.trim();
                                        trimmed
                                            .strip_prefix("* ")
                                            .unwrap_or(trimmed.strip_prefix('*').unwrap_or(trimmed))
                                    })
                                    .collect::<Vec<_>>()
                                    .join("\n")
                                    .trim()
                                    .to_string();
                                if !doc.is_empty() {
                                    return Some(doc);
                                }
                            }
                        }
                    }
                }
            }
            sibling = sib.prev_sibling();
            continue;
        }
        if sib.kind() == "block_comment" {
            if let Ok(text) = sib.utf8_text(source) {
                if text.starts_with("/**") {
                    let doc = text
                        .trim_start_matches("/**")
                        .trim_end_matches("*/")
                        .lines()
                        .map(|line| {
                            let trimmed = line.trim();
                            trimmed
                                .strip_prefix("* ")
                                .unwrap_or(trimmed.strip_prefix('*').unwrap_or(trimmed))
                        })
                        .collect::<Vec<_>>()
                        .join("\n")
                        .trim()
                        .to_string();
                    if !doc.is_empty() {
                        return Some(doc);
                    }
                }
            }
        }
        break;
    }

    None
}

/// Extract annotations from a declaration node.
///
/// Looks for `marker_annotation` (e.g., `@Override`) and `annotation` (e.g., `@SuppressWarnings("unchecked")`)
/// nodes that are siblings or inside a `modifiers` node preceding the declaration.
fn extract_annotations(node: &Node, source: &[u8]) -> Vec<String> {
    let mut annotations = Vec::new();

    // Check siblings before the declaration
    let mut sibling = node.prev_sibling();
    while let Some(sib) = sibling {
        match sib.kind() {
            "marker_annotation" | "annotation" => {
                if let Ok(text) = sib.utf8_text(source) {
                    annotations.push(text.to_string());
                }
                sibling = sib.prev_sibling();
            }
            "modifiers" => {
                // Annotations can be inside a modifiers node
                for child in sib.children(&mut sib.walk()) {
                    if child.kind() == "marker_annotation" || child.kind() == "annotation" {
                        if let Ok(text) = child.utf8_text(source) {
                            annotations.push(text.to_string());
                        }
                    }
                }
                sibling = sib.prev_sibling();
            }
            _ => break,
        }
    }

    // Also check direct children (some grammars nest annotations inside the declaration)
    for child in node.children(&mut node.walk()) {
        if child.kind() == "modifiers" {
            for grandchild in child.children(&mut child.walk()) {
                if grandchild.kind() == "marker_annotation" || grandchild.kind() == "annotation" {
                    if let Ok(text) = grandchild.utf8_text(source) {
                        if !annotations.contains(&text.to_string()) {
                            annotations.push(text.to_string());
                        }
                    }
                }
            }
        }
    }

    annotations
}

/// Check if a method/constructor has the `public` visibility modifier
fn has_public_modifier(node: &Node, source: &[u8]) -> bool {
    for child in node.children(&mut node.walk()) {
        if child.kind() == "modifiers" {
            for grandchild in child.children(&mut child.walk()) {
                if let Ok(text) = grandchild.utf8_text(source) {
                    if text == "public" {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Calculate cyclomatic complexity of a method
fn calculate_complexity(node: &Node, _source: &[u8]) -> u32 {
    let mut complexity = 1;

    fn count_branches(node: &Node, complexity: &mut u32) {
        match node.kind() {
            "if_statement"
            | "while_statement"
            | "for_statement"
            | "enhanced_for_statement"
            | "do_statement" => {
                *complexity += 1;
            }
            "catch_clause" => {
                *complexity += 1;
            }
            "switch_expression_arm" | "switch_block_statement_group" => {
                *complexity += 1;
            }
            "ternary_expression" => {
                *complexity += 1;
            }
            "binary_expression" => {
                for child in node.children(&mut node.walk()) {
                    if child.kind() == "&&" || child.kind() == "||" {
                        *complexity += 1;
                    }
                }
            }
            "lambda_expression" => {
                *complexity += 1;
            }
            _ => {}
        }

        for child in node.children(&mut node.walk()) {
            count_branches(&child, complexity);
        }
    }

    count_branches(node, &mut complexity);
    complexity
}

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

    #[test]
    fn test_parse_simple_class() {
        let source = r#"
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
"#;
        let path = PathBuf::from("HelloWorld.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        assert_eq!(result.classes.len(), 1);
        let class = &result.classes[0];
        assert_eq!(class.name, "HelloWorld");
        assert!(class.methods.contains(&"main".to_string()));
    }

    #[test]
    fn test_parse_class_with_inheritance() {
        let source = r#"
public class Child extends Parent implements Runnable, Serializable {
    @Override
    public void run() {}
}
"#;
        let path = PathBuf::from("Child.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        assert_eq!(result.classes.len(), 1);
        let class = &result.classes[0];
        assert_eq!(class.name, "Child");
        assert!(class.bases.iter().any(|b| b.contains("Parent")));
    }

    #[test]
    fn test_parse_interface() {
        let source = r#"
public interface MyInterface {
    void doSomething();
    default void doDefault() {}
}
"#;
        let path = PathBuf::from("MyInterface.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        assert_eq!(result.classes.len(), 1);
        let iface = &result.classes[0];
        assert_eq!(iface.name, "MyInterface");
    }

    #[test]
    fn test_parse_imports() {
        let source = r#"
import java.util.List;
import java.util.Map;
import static java.lang.Math.PI;

public class Test {}
"#;
        let path = PathBuf::from("Test.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        assert!(result
            .imports
            .iter()
            .any(|i| i.path.contains("java.util.List")));
        assert!(result
            .imports
            .iter()
            .any(|i| i.path.contains("java.util.Map")));
    }

    #[test]
    fn test_parse_methods() {
        let source = r#"
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}
"#;
        let path = PathBuf::from("Calculator.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        assert_eq!(result.functions.len(), 2);
        assert!(result.functions.iter().any(|f| f.name == "add"));
        assert!(result.functions.iter().any(|f| f.name == "subtract"));
    }

    #[test]
    fn test_method_count_excludes_nested_lambdas() {
        // Issue #18: Parser should not count lambdas/anonymous classes as class methods
        let source = r#"
public class StreamProcessor {
    private List<String> items;
    
    public StreamProcessor() {
        this.items = new ArrayList<>();
    }
    
    public List<String> process() {
        // These lambdas should NOT be counted as methods
        return items.stream()
            .filter(item -> item != null)
            .map(item -> item.toUpperCase())
            .collect(Collectors.toList());
    }
    
    public void registerCallback(Consumer<String> callback) {
        // Lambda passed to method - not a class method
        items.forEach(item -> callback.accept(item));
    }
}
"#;
        let path = PathBuf::from("StreamProcessor.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        let class = &result.classes[0];
        assert_eq!(class.name, "StreamProcessor");

        // Should have exactly 3 methods: constructor, process, registerCallback
        // NOT: filter lambda, map lambda, forEach lambda
        assert_eq!(
            class.methods.len(),
            3,
            "Expected 3 methods, got {:?}",
            class.methods
        );
    }

    #[test]
    fn test_method_count_excludes_anonymous_classes() {
        let source = r#"
public class EventHandler {
    public void setup() {
        // Anonymous class - its methods should NOT count as EventHandler methods
        button.addListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleClick();
            }
        });
    }
    
    private void handleClick() {
        System.out.println("clicked");
    }
}
"#;
        let path = PathBuf::from("EventHandler.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        // Find the main class (not the anonymous one)
        let main_class = result
            .classes
            .iter()
            .find(|c| c.name == "EventHandler")
            .expect("Should find EventHandler class");

        // EventHandler should have 2 methods: setup, handleClick
        // NOT: actionPerformed (that belongs to anonymous ActionListener)
        assert_eq!(
            main_class.methods.len(),
            2,
            "Expected 2 methods (setup, handleClick), got {:?}",
            main_class.methods
        );
    }

    #[test]
    fn test_javadoc_extracted() {
        let source = r#"
/**
 * Calculates the sum of two numbers.
 * @param a first number
 * @param b second number
 * @return the sum
 */
public class Calculator {
    /**
     * Add two integers.
     */
    public int add(int a, int b) {
        return a + b;
    }
}
"#;
        let path = PathBuf::from("Calculator.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        let class = &result.classes[0];
        assert!(class.doc_comment.is_some(), "Class should have Javadoc");
        let doc = class
            .doc_comment
            .as_ref()
            .expect("class should have Javadoc");
        assert!(doc.contains("Calculates the sum"), "Got: {}", doc);

        let method = result
            .functions
            .iter()
            .find(|f| f.name == "add")
            .expect("should find add method");
        assert!(method.doc_comment.is_some(), "Method should have Javadoc");
        assert!(method
            .doc_comment
            .as_ref()
            .expect("method should have Javadoc")
            .contains("Add two integers"));
    }

    #[test]
    fn test_annotations_extracted() {
        let source = r#"
public class Service {
    @Override
    public String toString() {
        return "Service";
    }

    @Deprecated
    @SuppressWarnings("unchecked")
    public void oldMethod() {}

    public void noAnnotation() {}
}
"#;
        let path = PathBuf::from("Service.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        let to_string = result
            .functions
            .iter()
            .find(|f| f.name == "toString")
            .expect("should find toString");
        assert!(
            to_string.annotations.iter().any(|a| a.contains("Override")),
            "toString should have @Override, got: {:?}",
            to_string.annotations
        );

        let old_method = result
            .functions
            .iter()
            .find(|f| f.name == "oldMethod")
            .expect("should find oldMethod");
        assert!(
            old_method
                .annotations
                .iter()
                .any(|a| a.contains("Deprecated")),
            "oldMethod should have @Deprecated, got: {:?}",
            old_method.annotations
        );

        let no_ann = result
            .functions
            .iter()
            .find(|f| f.name == "noAnnotation")
            .expect("should find noAnnotation");
        assert_eq!(
            no_ann.annotations,
            vec!["exported"],
            "public noAnnotation should only have 'exported', got: {:?}",
            no_ann.annotations
        );

        // toString and oldMethod are also public, so they get "exported" too
        assert!(
            to_string.annotations.iter().any(|a| a == "exported"),
            "public toString should have 'exported', got: {:?}",
            to_string.annotations
        );
        assert!(
            old_method.annotations.iter().any(|a| a == "exported"),
            "public oldMethod should have 'exported', got: {:?}",
            old_method.annotations
        );
    }

    #[test]
    fn test_private_methods_not_exported() {
        let source = r#"
public class MyClass {
    public void publicMethod() {}
    private void privateMethod() {}
    protected void protectedMethod() {}
    void packagePrivateMethod() {}
}
"#;
        let path = PathBuf::from("MyClass.java");
        let result = parse_source(source, &path).expect("should parse Java source");

        let public_m = result
            .functions
            .iter()
            .find(|f| f.name == "publicMethod")
            .expect("should find publicMethod");
        assert!(
            public_m.annotations.contains(&"exported".to_string()),
            "public method should be exported"
        );

        let private_m = result
            .functions
            .iter()
            .find(|f| f.name == "privateMethod")
            .expect("should find privateMethod");
        assert!(
            !private_m.annotations.contains(&"exported".to_string()),
            "private method should not be exported"
        );

        let protected_m = result
            .functions
            .iter()
            .find(|f| f.name == "protectedMethod")
            .expect("should find protectedMethod");
        assert!(
            !protected_m.annotations.contains(&"exported".to_string()),
            "protected method should not be exported"
        );

        let package_m = result
            .functions
            .iter()
            .find(|f| f.name == "packagePrivateMethod")
            .expect("should find packagePrivateMethod");
        assert!(
            !package_m.annotations.contains(&"exported".to_string()),
            "package-private method should not be exported"
        );
    }
}