Skip to main content

reflex/parsers/
java.rs

1//! Java language parser using Tree-sitter
2//!
3//! Extracts symbols from Java source code:
4//! - Classes (regular, abstract, final)
5//! - Interfaces
6//! - Enums
7//! - Records (Java 14+)
8//! - Methods (with class scope, visibility)
9//! - Fields (public, private, protected, static)
10//! - Constructors
11//! - Annotations
12//! - Local variables (inside method bodies)
13
14use crate::models::{Language, SearchResult, Span, SymbolKind};
15use anyhow::{Context, Result};
16use streaming_iterator::StreamingIterator;
17use tree_sitter::{Parser, QueryCursor};
18
19/// Parse Java source code and extract symbols
20pub fn parse(path: &str, source: &str) -> Result<Vec<SearchResult>> {
21    let mut parser = Parser::new();
22    let language = tree_sitter_java::LANGUAGE;
23
24    parser
25        .set_language(&language.into())
26        .context("Failed to set Java language")?;
27
28    let tree = parser
29        .parse(source, None)
30        .context("Failed to parse Java source")?;
31
32    let root_node = tree.root_node();
33    let table = SYMBOL_QUERIES.run(&language.into(), &root_node, source)?;
34
35    let mut symbols = Vec::new();
36
37    // Extract different types of symbols using Tree-sitter queries
38    symbols.extend(extract_classes(source, &table)?);
39    symbols.extend(extract_interfaces(source, &table)?);
40    symbols.extend(extract_enums(source, &table)?);
41    symbols.extend(extract_annotations(source, &table)?);
42    symbols.extend(extract_class_methods(source, &table)?);
43    symbols.extend(extract_interface_methods(source, &table)?);
44    symbols.extend(extract_fields(source, &table)?);
45    symbols.extend(extract_constructors(source, &table)?);
46    symbols.extend(extract_local_variables(source, &table)?);
47
48    // Add file path to all symbols
49    for symbol in &mut symbols {
50        symbol.path = path.to_string();
51        symbol.lang = Language::Java;
52    }
53
54    Ok(symbols)
55}
56
57/// Extract class declarations
58fn extract_classes(
59    source: &str,
60    table: &crate::parsers::MatchTable<'_>,
61) -> Result<Vec<SearchResult>> {
62    extract_symbols(source, table, 0, SymbolKind::Class, None)
63}
64
65/// Extract interface declarations
66fn extract_interfaces(
67    source: &str,
68    table: &crate::parsers::MatchTable<'_>,
69) -> Result<Vec<SearchResult>> {
70    extract_symbols(source, table, 1, SymbolKind::Interface, None)
71}
72
73/// Extract enum declarations
74fn extract_enums(
75    source: &str,
76    table: &crate::parsers::MatchTable<'_>,
77) -> Result<Vec<SearchResult>> {
78    extract_symbols(source, table, 2, SymbolKind::Enum, None)
79}
80
81/// Extract annotations: BOTH definitions and uses
82/// Definitions: @interface Test { ... }
83/// Uses: @Test public void testMethod()
84fn extract_annotations(
85    source: &str,
86    table: &crate::parsers::MatchTable<'_>,
87) -> Result<Vec<SearchResult>> {
88    let mut symbols = Vec::new();
89
90    // Part 1: Extract annotation type DEFINITIONS (@interface)
91
92    symbols.extend(extract_symbols(
93        source,
94        table,
95        4,
96        SymbolKind::Attribute,
97        None,
98    )?);
99
100    // Part 2: Extract annotation USES (@Test, @Override, etc.)
101
102    symbols.extend(extract_symbols(
103        source,
104        table,
105        3,
106        SymbolKind::Attribute,
107        None,
108    )?);
109
110    Ok(symbols)
111}
112
113/// Extract method declarations from classes
114fn extract_class_methods(
115    source: &str,
116    table: &crate::parsers::MatchTable<'_>,
117) -> Result<Vec<SearchResult>> {
118    let query = table.query();
119    let matches = table.sub(5);
120
121    let mut symbols = Vec::new();
122
123    for match_ in matches {
124        let mut scope_name = None;
125        let mut scope_type = None;
126        let mut method_name = None;
127        let mut method_node = None;
128
129        for capture in &match_.captures {
130            let capture_name: &str = query.capture_names()[capture.index as usize];
131            match capture_name {
132                "class_name" => {
133                    scope_name = Some(
134                        capture
135                            .node
136                            .utf8_text(source.as_bytes())
137                            .unwrap_or("")
138                            .to_string(),
139                    );
140                    scope_type = Some("class");
141                }
142                "enum_name" => {
143                    scope_name = Some(
144                        capture
145                            .node
146                            .utf8_text(source.as_bytes())
147                            .unwrap_or("")
148                            .to_string(),
149                    );
150                    scope_type = Some("enum");
151                }
152                "method_name" => {
153                    method_name = Some(
154                        capture
155                            .node
156                            .utf8_text(source.as_bytes())
157                            .unwrap_or("")
158                            .to_string(),
159                    );
160                    // Find the parent method_declaration node
161                    let mut current = capture.node;
162                    while let Some(parent) = current.parent() {
163                        if parent.kind() == "method_declaration" {
164                            method_node = Some(parent);
165                            break;
166                        }
167                        current = parent;
168                    }
169                }
170                _ => {}
171            }
172        }
173
174        if let (Some(scope_name), Some(scope_type), Some(method_name), Some(node)) =
175            (scope_name, scope_type, method_name, method_node)
176        {
177            let scope = format!("{} {}", scope_type, scope_name);
178            let span = node_to_span(&node);
179            let preview = extract_preview(source, &node);
180
181            symbols.push(SearchResult::new(
182                String::new(),
183                Language::Java,
184                SymbolKind::Method,
185                Some(method_name),
186                span,
187                Some(scope),
188                preview,
189            ));
190        }
191    }
192
193    Ok(symbols)
194}
195
196/// Extract field declarations from classes
197fn extract_fields(
198    source: &str,
199    table: &crate::parsers::MatchTable<'_>,
200) -> Result<Vec<SearchResult>> {
201    let query = table.query();
202    let matches = table.sub(6);
203
204    let mut symbols = Vec::new();
205
206    for match_ in matches {
207        let mut scope_name = None;
208        let mut scope_type = None;
209        let mut field_name = None;
210        let mut field_node = None;
211
212        for capture in &match_.captures {
213            let capture_name: &str = query.capture_names()[capture.index as usize];
214            match capture_name {
215                "class_name" => {
216                    scope_name = Some(
217                        capture
218                            .node
219                            .utf8_text(source.as_bytes())
220                            .unwrap_or("")
221                            .to_string(),
222                    );
223                    scope_type = Some("class");
224                }
225                "enum_name" => {
226                    scope_name = Some(
227                        capture
228                            .node
229                            .utf8_text(source.as_bytes())
230                            .unwrap_or("")
231                            .to_string(),
232                    );
233                    scope_type = Some("enum");
234                }
235                "field_name" => {
236                    field_name = Some(
237                        capture
238                            .node
239                            .utf8_text(source.as_bytes())
240                            .unwrap_or("")
241                            .to_string(),
242                    );
243                    // Find the parent field_declaration node
244                    let mut current = capture.node;
245                    while let Some(parent) = current.parent() {
246                        if parent.kind() == "field_declaration" {
247                            field_node = Some(parent);
248                            break;
249                        }
250                        current = parent;
251                    }
252                }
253                _ => {}
254            }
255        }
256
257        if let (Some(scope_name), Some(scope_type), Some(field_name), Some(node)) =
258            (scope_name, scope_type, field_name, field_node)
259        {
260            let scope = format!("{} {}", scope_type, scope_name);
261            let span = node_to_span(&node);
262            let preview = extract_preview(source, &node);
263
264            symbols.push(SearchResult::new(
265                String::new(),
266                Language::Java,
267                SymbolKind::Variable,
268                Some(field_name),
269                span,
270                Some(scope),
271                preview,
272            ));
273        }
274    }
275
276    Ok(symbols)
277}
278
279/// Extract constructor declarations
280fn extract_constructors(
281    source: &str,
282    table: &crate::parsers::MatchTable<'_>,
283) -> Result<Vec<SearchResult>> {
284    let query = table.query();
285    let matches = table.sub(7);
286
287    let mut symbols = Vec::new();
288
289    for match_ in matches {
290        let mut class_name = None;
291        let mut constructor_name = None;
292        let mut constructor_node = None;
293
294        for capture in &match_.captures {
295            let capture_name: &str = query.capture_names()[capture.index as usize];
296            match capture_name {
297                "class_name" => {
298                    class_name = Some(
299                        capture
300                            .node
301                            .utf8_text(source.as_bytes())
302                            .unwrap_or("")
303                            .to_string(),
304                    );
305                }
306                "constructor_name" => {
307                    constructor_name = Some(
308                        capture
309                            .node
310                            .utf8_text(source.as_bytes())
311                            .unwrap_or("")
312                            .to_string(),
313                    );
314                    // Find the parent constructor_declaration node
315                    let mut current = capture.node;
316                    while let Some(parent) = current.parent() {
317                        if parent.kind() == "constructor_declaration" {
318                            constructor_node = Some(parent);
319                            break;
320                        }
321                        current = parent;
322                    }
323                }
324                _ => {}
325            }
326        }
327
328        if let (Some(class_name), Some(constructor_name), Some(node)) =
329            (class_name, constructor_name, constructor_node)
330        {
331            let scope = format!("class {}", class_name);
332            let span = node_to_span(&node);
333            let preview = extract_preview(source, &node);
334
335            symbols.push(SearchResult::new(
336                String::new(),
337                Language::Java,
338                SymbolKind::Method,
339                Some(constructor_name),
340                span,
341                Some(scope),
342                preview,
343            ));
344        }
345    }
346
347    Ok(symbols)
348}
349
350/// Extract method declarations from interfaces
351fn extract_interface_methods(
352    source: &str,
353    table: &crate::parsers::MatchTable<'_>,
354) -> Result<Vec<SearchResult>> {
355    let query = table.query();
356    let matches = table.sub(8);
357
358    let mut symbols = Vec::new();
359
360    for match_ in matches {
361        let mut interface_name = None;
362        let mut method_name = None;
363        let mut method_node = None;
364
365        for capture in &match_.captures {
366            let capture_name: &str = query.capture_names()[capture.index as usize];
367            match capture_name {
368                "interface_name" => {
369                    interface_name = Some(
370                        capture
371                            .node
372                            .utf8_text(source.as_bytes())
373                            .unwrap_or("")
374                            .to_string(),
375                    );
376                }
377                "method_name" => {
378                    method_name = Some(
379                        capture
380                            .node
381                            .utf8_text(source.as_bytes())
382                            .unwrap_or("")
383                            .to_string(),
384                    );
385                    // Find the parent method_declaration node
386                    let mut current = capture.node;
387                    while let Some(parent) = current.parent() {
388                        if parent.kind() == "method_declaration" {
389                            method_node = Some(parent);
390                            break;
391                        }
392                        current = parent;
393                    }
394                }
395                _ => {}
396            }
397        }
398
399        if let (Some(interface_name), Some(method_name), Some(node)) =
400            (interface_name, method_name, method_node)
401        {
402            let scope = format!("interface {}", interface_name);
403            let span = node_to_span(&node);
404            let preview = extract_preview(source, &node);
405
406            symbols.push(SearchResult::new(
407                String::new(),
408                Language::Java,
409                SymbolKind::Method,
410                Some(method_name),
411                span,
412                Some(scope),
413                preview,
414            ));
415        }
416    }
417
418    Ok(symbols)
419}
420
421/// Extract local variable declarations from method bodies
422fn extract_local_variables(
423    source: &str,
424    table: &crate::parsers::MatchTable<'_>,
425) -> Result<Vec<SearchResult>> {
426    extract_symbols(source, table, 9, SymbolKind::Variable, None)
427}
428
429/// Generic symbol extraction helper
430fn extract_symbols(
431    source: &str,
432    table: &crate::parsers::MatchTable<'_>,
433    sub: usize,
434    kind: SymbolKind,
435    scope: Option<String>,
436) -> Result<Vec<SearchResult>> {
437    let query = table.query();
438    let matches = table.sub(sub);
439
440    let mut symbols = Vec::new();
441
442    for match_ in matches {
443        // Find the name capture and the full node
444        let mut name = None;
445        let mut full_node = None;
446
447        for capture in &match_.captures {
448            let capture_name: &str = query.capture_names()[capture.index as usize];
449            if capture_name == "name" {
450                name = Some(
451                    capture
452                        .node
453                        .utf8_text(source.as_bytes())
454                        .unwrap_or("")
455                        .to_string(),
456                );
457            } else {
458                // Assume any other capture is the full node
459                full_node = Some(capture.node);
460            }
461        }
462
463        if let (Some(name), Some(node)) = (name, full_node) {
464            let span = node_to_span(&node);
465            let preview = extract_preview(source, &node);
466
467            symbols.push(SearchResult::new(
468                String::new(),
469                Language::Java,
470                kind.clone(),
471                Some(name),
472                span,
473                scope.clone(),
474                preview,
475            ));
476        }
477    }
478
479    Ok(symbols)
480}
481
482/// Convert a Tree-sitter node to a Span
483fn node_to_span(node: &tree_sitter::Node) -> Span {
484    let start = node.start_position();
485    let end = node.end_position();
486
487    Span::new(
488        start.row + 1, // Convert 0-indexed to 1-indexed
489        start.column,
490        end.row + 1,
491        end.column,
492    )
493}
494
495/// Extract a preview (7 lines) around the symbol
496fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
497    // Starts at the node, not at byte 0: see `crate::parsers::preview`.
498    crate::parsers::preview::extract_preview_for_node(source, node)
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn test_parse_class() {
507        let source = r#"
508public class User {
509    private String name;
510    private int age;
511}
512        "#;
513
514        let symbols = parse("test.java", source).unwrap();
515
516        let class_symbols: Vec<_> = symbols
517            .iter()
518            .filter(|s| matches!(s.kind, SymbolKind::Class))
519            .collect();
520
521        assert_eq!(class_symbols.len(), 1);
522        assert_eq!(class_symbols[0].symbol.as_deref(), Some("User"));
523    }
524
525    #[test]
526    fn test_parse_class_with_methods() {
527        let source = r#"
528public class Calculator {
529    public int add(int a, int b) {
530        return a + b;
531    }
532
533    public int subtract(int a, int b) {
534        return a - b;
535    }
536}
537        "#;
538
539        let symbols = parse("test.java", source).unwrap();
540
541        let method_symbols: Vec<_> = symbols
542            .iter()
543            .filter(|s| matches!(s.kind, SymbolKind::Method))
544            .collect();
545
546        assert_eq!(method_symbols.len(), 2);
547        assert!(
548            method_symbols
549                .iter()
550                .any(|s| s.symbol.as_deref() == Some("add"))
551        );
552        assert!(
553            method_symbols
554                .iter()
555                .any(|s| s.symbol.as_deref() == Some("subtract"))
556        );
557
558        // Check scope
559        for _method in method_symbols {
560            // Removed: scope field no longer exists: assert_eq!(method.scope.as_ref().unwrap(), "class Calculator");
561        }
562    }
563
564    #[test]
565    fn test_parse_interface() {
566        let source = r#"
567public interface Drawable {
568    void draw();
569    void resize(int width, int height);
570}
571        "#;
572
573        let symbols = parse("test.java", source).unwrap();
574
575        let interface_symbols: Vec<_> = symbols
576            .iter()
577            .filter(|s| matches!(s.kind, SymbolKind::Interface))
578            .collect();
579
580        assert_eq!(interface_symbols.len(), 1);
581        assert_eq!(interface_symbols[0].symbol.as_deref(), Some("Drawable"));
582    }
583
584    #[test]
585    fn test_parse_enum() {
586        let source = r#"
587public enum Status {
588    ACTIVE,
589    INACTIVE,
590    PENDING
591}
592        "#;
593
594        let symbols = parse("test.java", source).unwrap();
595
596        let enum_symbols: Vec<_> = symbols
597            .iter()
598            .filter(|s| matches!(s.kind, SymbolKind::Enum))
599            .collect();
600
601        assert_eq!(enum_symbols.len(), 1);
602        assert_eq!(enum_symbols[0].symbol.as_deref(), Some("Status"));
603    }
604
605    #[test]
606    fn test_parse_fields() {
607        let source = r#"
608public class Config {
609    private static final int MAX_SIZE = 100;
610    private String hostname;
611    public int port;
612}
613        "#;
614
615        let symbols = parse("test.java", source).unwrap();
616
617        let field_symbols: Vec<_> = symbols
618            .iter()
619            .filter(|s| matches!(s.kind, SymbolKind::Variable))
620            .collect();
621
622        assert_eq!(field_symbols.len(), 3);
623        assert!(
624            field_symbols
625                .iter()
626                .any(|s| s.symbol.as_deref() == Some("MAX_SIZE"))
627        );
628        assert!(
629            field_symbols
630                .iter()
631                .any(|s| s.symbol.as_deref() == Some("hostname"))
632        );
633        assert!(
634            field_symbols
635                .iter()
636                .any(|s| s.symbol.as_deref() == Some("port"))
637        );
638    }
639
640    #[test]
641    fn test_parse_constructor() {
642        let source = r#"
643public class User {
644    private String name;
645
646    public User(String name) {
647        this.name = name;
648    }
649
650    public User() {
651        this("Anonymous");
652    }
653}
654        "#;
655
656        let symbols = parse("test.java", source).unwrap();
657
658        let constructor_symbols: Vec<_> = symbols
659            .iter()
660            .filter(|s| matches!(s.kind, SymbolKind::Method) && s.symbol.as_deref() == Some("User"))
661            .collect();
662
663        assert_eq!(constructor_symbols.len(), 2);
664    }
665
666    #[test]
667    fn test_parse_abstract_class() {
668        let source = r#"
669public abstract class Animal {
670    protected String name;
671
672    public abstract void makeSound();
673
674    public void sleep() {
675        System.out.println("Sleeping...");
676    }
677}
678        "#;
679
680        let symbols = parse("test.java", source).unwrap();
681
682        let class_symbols: Vec<_> = symbols
683            .iter()
684            .filter(|s| matches!(s.kind, SymbolKind::Class))
685            .collect();
686
687        assert_eq!(class_symbols.len(), 1);
688        assert_eq!(class_symbols[0].symbol.as_deref(), Some("Animal"));
689
690        let method_symbols: Vec<_> = symbols
691            .iter()
692            .filter(|s| matches!(s.kind, SymbolKind::Method))
693            .collect();
694
695        assert_eq!(method_symbols.len(), 2);
696        assert!(
697            method_symbols
698                .iter()
699                .any(|s| s.symbol.as_deref() == Some("makeSound"))
700        );
701        assert!(
702            method_symbols
703                .iter()
704                .any(|s| s.symbol.as_deref() == Some("sleep"))
705        );
706    }
707
708    #[test]
709    fn test_parse_nested_class() {
710        let source = r#"
711public class Outer {
712    private int outerField;
713
714    public static class Nested {
715        private int nestedField;
716
717        public void nestedMethod() {
718            // ...
719        }
720    }
721
722    public void outerMethod() {
723        // ...
724    }
725}
726        "#;
727
728        let symbols = parse("test.java", source).unwrap();
729
730        let class_symbols: Vec<_> = symbols
731            .iter()
732            .filter(|s| matches!(s.kind, SymbolKind::Class))
733            .collect();
734
735        assert_eq!(class_symbols.len(), 2);
736        assert!(
737            class_symbols
738                .iter()
739                .any(|s| s.symbol.as_deref() == Some("Outer"))
740        );
741        assert!(
742            class_symbols
743                .iter()
744                .any(|s| s.symbol.as_deref() == Some("Nested"))
745        );
746    }
747
748    #[test]
749    fn test_parse_interface_with_methods() {
750        let source = r#"
751public interface Repository<T> {
752    T findById(Long id);
753    List<T> findAll();
754    void save(T entity);
755    void delete(T entity);
756}
757        "#;
758
759        let symbols = parse("test.java", source).unwrap();
760
761        let interface_symbols: Vec<_> = symbols
762            .iter()
763            .filter(|s| matches!(s.kind, SymbolKind::Interface))
764            .collect();
765
766        assert_eq!(interface_symbols.len(), 1);
767
768        let method_symbols: Vec<_> = symbols
769            .iter()
770            .filter(|s| matches!(s.kind, SymbolKind::Method))
771            .collect();
772
773        assert_eq!(method_symbols.len(), 4);
774        assert!(
775            method_symbols
776                .iter()
777                .any(|s| s.symbol.as_deref() == Some("findById"))
778        );
779        assert!(
780            method_symbols
781                .iter()
782                .any(|s| s.symbol.as_deref() == Some("findAll"))
783        );
784        assert!(
785            method_symbols
786                .iter()
787                .any(|s| s.symbol.as_deref() == Some("save"))
788        );
789        assert!(
790            method_symbols
791                .iter()
792                .any(|s| s.symbol.as_deref() == Some("delete"))
793        );
794    }
795
796    #[test]
797    fn test_parse_enum_with_methods() {
798        let source = r#"
799public enum Day {
800    MONDAY, TUESDAY, WEDNESDAY;
801
802    public boolean isWeekend() {
803        return this == SATURDAY || this == SUNDAY;
804    }
805}
806        "#;
807
808        let symbols = parse("test.java", source).unwrap();
809
810        let enum_symbols: Vec<_> = symbols
811            .iter()
812            .filter(|s| matches!(s.kind, SymbolKind::Enum))
813            .collect();
814
815        assert_eq!(enum_symbols.len(), 1);
816
817        let method_symbols: Vec<_> = symbols
818            .iter()
819            .filter(|s| matches!(s.kind, SymbolKind::Method))
820            .collect();
821
822        assert_eq!(method_symbols.len(), 1);
823        assert_eq!(method_symbols[0].symbol.as_deref(), Some("isWeekend"));
824    }
825
826    #[test]
827    fn test_parse_mixed_symbols() {
828        let source = r#"
829package com.example;
830
831public interface UserService {
832    User findUser(Long id);
833}
834
835public class User {
836    private Long id;
837    private String name;
838
839    public User(Long id, String name) {
840        this.id = id;
841        this.name = name;
842    }
843
844    public String getName() {
845        return name;
846    }
847}
848
849public enum UserRole {
850    ADMIN, USER, GUEST
851}
852        "#;
853
854        let symbols = parse("test.java", source).unwrap();
855
856        // Should find: interface, class, enum, fields, constructor, methods
857        assert!(symbols.len() >= 7);
858
859        let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
860        assert!(kinds.contains(&&SymbolKind::Interface));
861        assert!(kinds.contains(&&SymbolKind::Class));
862        assert!(kinds.contains(&&SymbolKind::Enum));
863        assert!(kinds.contains(&&SymbolKind::Variable));
864        assert!(kinds.contains(&&SymbolKind::Method));
865    }
866
867    #[test]
868    fn test_parse_generic_class() {
869        let source = r#"
870public class Container<T> {
871    private T value;
872
873    public Container(T value) {
874        this.value = value;
875    }
876
877    public T getValue() {
878        return value;
879    }
880
881    public void setValue(T value) {
882        this.value = value;
883    }
884}
885        "#;
886
887        let symbols = parse("test.java", source).unwrap();
888
889        let class_symbols: Vec<_> = symbols
890            .iter()
891            .filter(|s| matches!(s.kind, SymbolKind::Class))
892            .collect();
893
894        assert_eq!(class_symbols.len(), 1);
895        assert_eq!(class_symbols[0].symbol.as_deref(), Some("Container"));
896
897        let method_symbols: Vec<_> = symbols
898            .iter()
899            .filter(|s| matches!(s.kind, SymbolKind::Method))
900            .collect();
901
902        assert!(method_symbols.len() >= 3);
903    }
904
905    #[test]
906    fn test_local_variables_included() {
907        let source = r#"
908public class Calculator {
909    private int globalCount = 10;
910
911    public int calculate(int x) {
912        int localVar = x * 2;
913        int anotherLocal = 5;
914        return localVar + anotherLocal + globalCount;
915    }
916}
917        "#;
918
919        let symbols = parse("test.java", source).unwrap();
920
921        let var_symbols: Vec<_> = symbols
922            .iter()
923            .filter(|s| matches!(s.kind, SymbolKind::Variable))
924            .collect();
925
926        // Should find both field (globalCount) and local variables (localVar, anotherLocal)
927        assert_eq!(var_symbols.len(), 3);
928        assert!(
929            var_symbols
930                .iter()
931                .any(|s| s.symbol.as_deref() == Some("globalCount"))
932        );
933        assert!(
934            var_symbols
935                .iter()
936                .any(|s| s.symbol.as_deref() == Some("localVar"))
937        );
938        assert!(
939            var_symbols
940                .iter()
941                .any(|s| s.symbol.as_deref() == Some("anotherLocal"))
942        );
943
944        // Check scopes: field should have scope, local vars should not
945        let _global_count = var_symbols
946            .iter()
947            .find(|s| s.symbol.as_deref() == Some("globalCount"))
948            .unwrap();
949        // Removed: scope field no longer exists: assert_eq!(global_count.scope.as_ref().unwrap(), "class Calculator");
950
951        let _local_var = var_symbols
952            .iter()
953            .find(|s| s.symbol.as_deref() == Some("localVar"))
954            .unwrap();
955        // Removed: scope field no longer exists: assert_eq!(local_var.scope, None);
956    }
957
958    #[test]
959    fn test_parse_annotation_type() {
960        let source = r#"
961public @interface Test {
962}
963
964@interface Author {
965    String name();
966    String date();
967}
968
969@interface Retention {
970    RetentionPolicy value();
971}
972        "#;
973
974        let symbols = parse("test.java", source).unwrap();
975
976        let annotation_symbols: Vec<_> = symbols
977            .iter()
978            .filter(|s| matches!(s.kind, SymbolKind::Attribute))
979            .collect();
980
981        // Should find annotation definitions
982        assert!(
983            annotation_symbols
984                .iter()
985                .any(|s| s.symbol.as_deref() == Some("Test"))
986        );
987        assert!(
988            annotation_symbols
989                .iter()
990                .any(|s| s.symbol.as_deref() == Some("Author"))
991        );
992        assert!(
993            annotation_symbols
994                .iter()
995                .any(|s| s.symbol.as_deref() == Some("Retention"))
996        );
997    }
998
999    #[test]
1000    fn test_parse_annotation_uses() {
1001        let source = r#"
1002@Test
1003public void testMethod() {
1004    assertEquals(1, 1);
1005}
1006
1007@Override
1008@Deprecated
1009public String toString() {
1010    return "example";
1011}
1012
1013@SuppressWarnings("unchecked")
1014public class MyClass {
1015    @Autowired
1016    private Service service;
1017
1018    @Test
1019    @DisplayName("Should work")
1020    public void anotherTest() {}
1021}
1022        "#;
1023
1024        let symbols = parse("test.java", source).unwrap();
1025
1026        let annotation_symbols: Vec<_> = symbols
1027            .iter()
1028            .filter(|s| matches!(s.kind, SymbolKind::Attribute))
1029            .collect();
1030
1031        // Should find annotation uses
1032        assert!(
1033            annotation_symbols
1034                .iter()
1035                .any(|s| s.symbol.as_deref() == Some("Test"))
1036        );
1037        assert!(
1038            annotation_symbols
1039                .iter()
1040                .any(|s| s.symbol.as_deref() == Some("Override"))
1041        );
1042        assert!(
1043            annotation_symbols
1044                .iter()
1045                .any(|s| s.symbol.as_deref() == Some("Deprecated"))
1046        );
1047        assert!(
1048            annotation_symbols
1049                .iter()
1050                .any(|s| s.symbol.as_deref() == Some("SuppressWarnings"))
1051        );
1052        assert!(
1053            annotation_symbols
1054                .iter()
1055                .any(|s| s.symbol.as_deref() == Some("Autowired"))
1056        );
1057        assert!(
1058            annotation_symbols
1059                .iter()
1060                .any(|s| s.symbol.as_deref() == Some("DisplayName"))
1061        );
1062
1063        // Should find Test twice (2 uses)
1064        let test_count = annotation_symbols
1065            .iter()
1066            .filter(|s| s.symbol.as_deref() == Some("Test"))
1067            .count();
1068        assert_eq!(test_count, 2);
1069    }
1070
1071    #[test]
1072    fn test_extract_java_imports() {
1073        let source = r#"
1074            import java.util.List;
1075            import java.util.ArrayList;
1076            import java.io.IOException;
1077            import org.springframework.stereotype.Service;
1078
1079            @Service
1080            public class UserService {
1081                private List<String> users = new ArrayList<>();
1082
1083                public void addUser(String name) throws IOException {
1084                    users.add(name);
1085                }
1086            }
1087        "#;
1088
1089        use crate::parsers::DependencyExtractor;
1090
1091        let deps = JavaDependencyExtractor::extract_dependencies(source).unwrap();
1092
1093        assert_eq!(deps.len(), 4, "Should extract 4 import statements");
1094        assert!(deps.iter().any(|d| d.imported_path == "java.util.List"));
1095        assert!(
1096            deps.iter()
1097                .any(|d| d.imported_path == "java.util.ArrayList")
1098        );
1099        assert!(
1100            deps.iter()
1101                .any(|d| d.imported_path == "java.io.IOException")
1102        );
1103        assert!(
1104            deps.iter()
1105                .any(|d| d.imported_path == "org.springframework.stereotype.Service")
1106        );
1107
1108        // Check stdlib classification
1109        let java_util_list = deps
1110            .iter()
1111            .find(|d| d.imported_path == "java.util.List")
1112            .unwrap();
1113        assert!(
1114            matches!(java_util_list.import_type, ImportType::Stdlib),
1115            "java.util imports should be classified as Stdlib"
1116        );
1117
1118        // Check external classification
1119        let spring_service = deps
1120            .iter()
1121            .find(|d| d.imported_path == "org.springframework.stereotype.Service")
1122            .unwrap();
1123        assert!(
1124            matches!(spring_service.import_type, ImportType::External),
1125            "org.springframework imports should be classified as External"
1126        );
1127    }
1128}
1129
1130// ============================================================================
1131// Dependency Extraction
1132// ============================================================================
1133
1134use crate::models::ImportType;
1135use crate::parsers::{DependencyExtractor, ImportInfo};
1136
1137const SYMQ_0: &str = r#"
1138        (class_declaration
1139            name: (identifier) @name) @class
1140    "#;
1141const SYMQ_1: &str = r#"
1142        (interface_declaration
1143            name: (identifier) @name) @interface
1144    "#;
1145const SYMQ_2: &str = r#"
1146        (enum_declaration
1147            name: (identifier) @name) @enum
1148    "#;
1149const SYMQ_3: &str = r#"
1150        (marker_annotation
1151            name: (identifier) @name) @annotation
1152
1153        (annotation
1154            name: (identifier) @name) @annotation
1155    "#;
1156const SYMQ_4: &str = r#"
1157        (annotation_type_declaration
1158            name: (identifier) @name) @annotation
1159    "#;
1160const SYMQ_5: &str = r#"
1161        (class_declaration
1162            name: (identifier) @class_name
1163            body: (class_body
1164                (method_declaration
1165                    name: (identifier) @method_name))) @class
1166
1167        (enum_declaration
1168            name: (identifier) @enum_name
1169            body: (enum_body
1170                (enum_body_declarations
1171                    (method_declaration
1172                        name: (identifier) @method_name)))) @enum
1173    "#;
1174const SYMQ_6: &str = r#"
1175        (class_declaration
1176            name: (identifier) @class_name
1177            body: (class_body
1178                (field_declaration
1179                    declarator: (variable_declarator
1180                        name: (identifier) @field_name)))) @class
1181
1182        (enum_declaration
1183            name: (identifier) @enum_name
1184            body: (enum_body
1185                (enum_body_declarations
1186                    (field_declaration
1187                        declarator: (variable_declarator
1188                            name: (identifier) @field_name))))) @enum
1189    "#;
1190const SYMQ_7: &str = r#"
1191        (class_declaration
1192            name: (identifier) @class_name
1193            body: (class_body
1194                (constructor_declaration
1195                    name: (identifier) @constructor_name))) @class
1196    "#;
1197const SYMQ_8: &str = r#"
1198        (interface_declaration
1199            name: (identifier) @interface_name
1200            body: (interface_body
1201                (method_declaration
1202                    name: (identifier) @method_name))) @interface
1203    "#;
1204const SYMQ_9: &str = r#"
1205        (local_variable_declaration
1206            declarator: (variable_declarator
1207                name: (identifier) @name)) @var
1208    "#;
1209
1210/// Every symbol query of this module, run as ONE query per file (see
1211/// `crate::parsers::LanguageQueries`).
1212static SYMBOL_QUERIES: crate::parsers::LanguageQueries = crate::parsers::LanguageQueries::new(&[
1213    SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5, SYMQ_6, SYMQ_7, SYMQ_8, SYMQ_9,
1214]);
1215
1216/// Java dependency extractor
1217pub struct JavaDependencyExtractor;
1218
1219impl DependencyExtractor for JavaDependencyExtractor {
1220    fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
1221        let mut parser = Parser::new();
1222        let language = tree_sitter_java::LANGUAGE;
1223
1224        parser
1225            .set_language(&language.into())
1226            .context("Failed to set Java language")?;
1227
1228        let tree = parser
1229            .parse(source, None)
1230            .context("Failed to parse Java source")?;
1231
1232        let root_node = tree.root_node();
1233
1234        let mut imports = Vec::new();
1235
1236        // Extract import statements
1237        imports.extend(extract_java_imports(source, &root_node)?);
1238
1239        Ok(imports)
1240    }
1241}
1242
1243/// Extract Java import statements
1244fn extract_java_imports(source: &str, root: &tree_sitter::Node) -> Result<Vec<ImportInfo>> {
1245    let language = tree_sitter_java::LANGUAGE;
1246
1247    let query_str = r#"
1248        (import_declaration
1249            [
1250                (scoped_identifier) @import_path
1251                (identifier) @import_path
1252            ])
1253    "#;
1254
1255    static QUERY_1: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
1256    let query = crate::parsers::cached_query(&QUERY_1, language, query_str)
1257        .context("Failed to create Java import query")?;
1258
1259    let mut cursor = QueryCursor::new();
1260    let mut matches = cursor.matches(query, *root, source.as_bytes());
1261
1262    let mut imports = Vec::new();
1263
1264    while let Some(match_) = matches.next() {
1265        for capture in match_.captures {
1266            let capture_name: &str = query.capture_names()[capture.index as usize];
1267            if capture_name == "import_path" {
1268                let mut path = capture
1269                    .node
1270                    .utf8_text(source.as_bytes())
1271                    .unwrap_or("")
1272                    .to_string();
1273                // `import a.b.*;` keeps its `.*`: the whole package, not a class `b`
1274                let wildcard = capture.node.parent().is_some_and(|decl| {
1275                    let mut walk = decl.walk();
1276                    decl.children(&mut walk).any(|c| c.kind() == "asterisk")
1277                });
1278                if wildcard {
1279                    path.push_str(".*");
1280                }
1281                let import_type = classify_java_import(&path);
1282                let line_number = capture.node.start_position().row + 1;
1283
1284                imports.push(ImportInfo {
1285                    imported_path: path,
1286                    import_type,
1287                    line_number,
1288                    imported_symbols: None, // Java imports are package-level
1289                });
1290            }
1291        }
1292    }
1293
1294    Ok(imports)
1295}
1296
1297/// Classify a Java import as internal, external, or stdlib
1298fn classify_java_import(import_path: &str) -> ImportType {
1299    classify_java_import_impl(import_path, None)
1300}
1301
1302/// Parse pom.xml or build.gradle to find Java package name
1303/// Similar to find_go_module_name() for Go projects
1304pub fn find_java_package_name(root: &std::path::Path) -> Option<String> {
1305    // Try Maven first (pom.xml)
1306    if let Some(package) = find_maven_package(root) {
1307        return Some(package);
1308    }
1309
1310    // Try Gradle second (build.gradle or build.gradle.kts)
1311    if let Some(package) = find_gradle_package(root) {
1312        return Some(package);
1313    }
1314
1315    // Fallback: scan package declarations in .java files
1316    find_package_from_sources(root)
1317}
1318
1319/// Parse pom.xml to extract <groupId>
1320fn find_maven_package(root: &std::path::Path) -> Option<String> {
1321    let pom_path = root.join("pom.xml");
1322    if !pom_path.exists() {
1323        return None;
1324    }
1325
1326    let content = std::fs::read_to_string(&pom_path).ok()?;
1327
1328    // Simple XML parsing for <groupId>
1329    for line in content.lines() {
1330        let trimmed = line.trim();
1331        if trimmed.starts_with("<groupId>") && trimmed.ends_with("</groupId>") {
1332            let start = "<groupId>".len();
1333            let end = trimmed.len() - "</groupId>".len();
1334            return Some(trimmed[start..end].to_string());
1335        }
1336    }
1337
1338    None
1339}
1340
1341/// Parse build.gradle or build.gradle.kts to extract group
1342fn find_gradle_package(root: &std::path::Path) -> Option<String> {
1343    // Try build.gradle (Groovy)
1344    if let Some(package) = find_gradle_package_in_file(&root.join("build.gradle")) {
1345        return Some(package);
1346    }
1347
1348    // Try build.gradle.kts (Kotlin)
1349    find_gradle_package_in_file(&root.join("build.gradle.kts"))
1350}
1351
1352fn find_gradle_package_in_file(gradle_path: &std::path::Path) -> Option<String> {
1353    if !gradle_path.exists() {
1354        return None;
1355    }
1356
1357    let content = std::fs::read_to_string(gradle_path).ok()?;
1358
1359    for line in content.lines() {
1360        let trimmed = line.trim();
1361
1362        // Groovy: group = 'org.neo4j'
1363        // Kotlin: group = "org.neo4j"
1364        if trimmed.starts_with("group")
1365            && let Some(equals_idx) = trimmed.find('=')
1366        {
1367            let value = &trimmed[equals_idx + 1..].trim();
1368            // Remove quotes
1369            let value = value.trim_matches(|c| c == '\'' || c == '"');
1370            return Some(value.to_string());
1371        }
1372    }
1373
1374    None
1375}
1376
1377/// Scan .java files to find common package prefix
1378fn find_package_from_sources(root: &std::path::Path) -> Option<String> {
1379    use std::collections::HashMap;
1380
1381    let mut package_counts: HashMap<String, usize> = HashMap::new();
1382
1383    // Walk the directory tree looking for .java files
1384    fn walk_dir(dir: &std::path::Path, package_counts: &mut HashMap<String, usize>, depth: usize) {
1385        // Limit depth to avoid excessive scanning
1386        if depth > 10 {
1387            return;
1388        }
1389
1390        let entries = match std::fs::read_dir(dir) {
1391            Ok(e) => e,
1392            Err(_) => return,
1393        };
1394
1395        for entry in entries.flatten() {
1396            let path = entry.path();
1397
1398            if path.is_dir() {
1399                walk_dir(&path, package_counts, depth + 1);
1400            } else if path.extension().and_then(|s| s.to_str()) == Some("java")
1401                && let Ok(content) = std::fs::read_to_string(&path)
1402            {
1403                // Extract package declaration
1404                for line in content.lines().take(20) {
1405                    // Check first 20 lines
1406                    let trimmed = line.trim();
1407                    if trimmed.starts_with("package ") && trimmed.ends_with(';') {
1408                        let package = &trimmed[8..trimmed.len() - 1].trim();
1409
1410                        // Extract base package (first 2 components: org.neo4j)
1411                        let parts: Vec<&str> = package.split('.').collect();
1412                        if parts.len() >= 2 {
1413                            let base_package = format!("{}.{}", parts[0], parts[1]);
1414                            *package_counts.entry(base_package).or_insert(0) += 1;
1415                        }
1416                        break;
1417                    }
1418                }
1419            }
1420        }
1421    }
1422
1423    walk_dir(root, &mut package_counts, 0);
1424
1425    // Find the most common package prefix
1426    package_counts
1427        .into_iter()
1428        .max_by_key(|(_, count)| *count)
1429        .map(|(package, _)| package)
1430}
1431
1432/// Reclassify a Java import using the project package prefix
1433/// Similar to reclassify_go_import() for Go
1434pub fn reclassify_java_import(import_path: &str, package_prefix: Option<&str>) -> ImportType {
1435    classify_java_import_impl(import_path, package_prefix)
1436}
1437
1438fn classify_java_import_impl(import_path: &str, package_prefix: Option<&str>) -> ImportType {
1439    // First check if this is an internal import (matches project package)
1440    if let Some(prefix) = package_prefix
1441        && import_path.starts_with(prefix)
1442    {
1443        return ImportType::Internal;
1444    }
1445
1446    // Java standard library packages (common ones)
1447    const STDLIB_PACKAGES: &[&str] = &[
1448        "java.lang",
1449        "java.util",
1450        "java.io",
1451        "java.nio",
1452        "java.net",
1453        "java.text",
1454        "java.math",
1455        "java.time",
1456        "java.sql",
1457        "java.security",
1458        "java.awt",
1459        "java.swing",
1460        "javax.swing",
1461        "javax.sql",
1462        "javax.crypto",
1463        "javax.net",
1464        "javax.xml",
1465        "javax.annotation",
1466        "javax.servlet",
1467        "org.w3c.dom",
1468        "org.xml.sax",
1469    ];
1470
1471    // Check if it starts with any stdlib package
1472    for stdlib_pkg in STDLIB_PACKAGES {
1473        if import_path.starts_with(stdlib_pkg) {
1474            return ImportType::Stdlib;
1475        }
1476    }
1477
1478    // Everything else is external
1479    ImportType::External
1480}
1481
1482// ============================================================================
1483// Monorepo Support - Java/Kotlin Dependency Resolution
1484// ============================================================================
1485
1486/// Represents a Java/Kotlin project in a monorepo
1487#[derive(Debug, Clone)]
1488pub struct JavaProject {
1489    /// Package name (groupId from Maven or group from Gradle)
1490    pub package_name: String,
1491    /// Relative path to project root (where pom.xml or build.gradle is)
1492    pub project_root: String,
1493    /// Absolute path to project root
1494    pub abs_project_root: String,
1495}
1496
1497/// Find all Maven/Gradle projects in the repository recursively
1498/// Similar to find_all_go_mods() for Go
1499pub fn find_all_maven_gradle_projects(root: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
1500    let mut config_files = Vec::new();
1501
1502    let walker = ignore::WalkBuilder::new(root)
1503        .follow_links(false)
1504        .git_ignore(true)
1505        .build();
1506
1507    for entry in walker {
1508        let entry = entry?;
1509        let path = entry.path();
1510
1511        if path.is_file() {
1512            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1513
1514            // Match pom.xml (Maven) or build.gradle/build.gradle.kts (Gradle)
1515            if filename == "pom.xml" || filename == "build.gradle" || filename == "build.gradle.kts"
1516            {
1517                config_files.push(path.to_path_buf());
1518                log::trace!("Found Java/Kotlin config: {}", path.display());
1519            }
1520        }
1521    }
1522
1523    log::debug!(
1524        "Found {} Java/Kotlin project config files",
1525        config_files.len()
1526    );
1527    Ok(config_files)
1528}
1529
1530/// Parse all Maven/Gradle projects and return JavaProject structs
1531/// Similar to parse_all_go_modules() for Go
1532pub fn parse_all_java_projects(root: &std::path::Path) -> Result<Vec<JavaProject>> {
1533    let config_files = find_all_maven_gradle_projects(root)?;
1534    parse_java_projects_from(root, &config_files)
1535}
1536
1537/// [`parse_all_java_projects`] for config files already found (in walk order).
1538pub fn parse_java_projects_from(
1539    root: &std::path::Path,
1540    config_files: &[std::path::PathBuf],
1541) -> Result<Vec<JavaProject>> {
1542    let mut projects = Vec::new();
1543
1544    let root_abs = root
1545        .canonicalize()
1546        .with_context(|| format!("Failed to canonicalize root path: {}", root.display()))?;
1547
1548    for config_path in config_files {
1549        // Get the directory containing the config file (project root)
1550        if let Some(project_dir) = config_path.parent() {
1551            // Parse the config file to get package name
1552            if let Some(package_name) = extract_package_from_config(config_path) {
1553                let project_abs = project_dir.canonicalize().with_context(|| {
1554                    format!(
1555                        "Failed to canonicalize project path: {}",
1556                        project_dir.display()
1557                    )
1558                })?;
1559
1560                let project_rel = project_abs
1561                    .strip_prefix(&root_abs)
1562                    .unwrap_or(project_dir)
1563                    .to_string_lossy()
1564                    .to_string();
1565
1566                projects.push(JavaProject {
1567                    package_name: package_name.clone(),
1568                    project_root: project_rel,
1569                    abs_project_root: project_abs.to_string_lossy().to_string(),
1570                });
1571
1572                log::trace!(
1573                    "Parsed Java/Kotlin project: {} at {}",
1574                    package_name,
1575                    project_dir.display()
1576                );
1577            }
1578        }
1579    }
1580
1581    log::info!("Parsed {} Java/Kotlin projects", projects.len());
1582    Ok(projects)
1583}
1584
1585/// Extract package name from pom.xml or build.gradle
1586fn extract_package_from_config(config_path: &std::path::Path) -> Option<String> {
1587    let filename = config_path.file_name()?.to_str()?;
1588
1589    match filename {
1590        "pom.xml" => {
1591            // Extract <groupId> from Maven pom.xml
1592            let content = std::fs::read_to_string(config_path).ok()?;
1593            for line in content.lines() {
1594                let trimmed = line.trim();
1595                if trimmed.starts_with("<groupId>") && trimmed.ends_with("</groupId>") {
1596                    let start = "<groupId>".len();
1597                    let end = trimmed.len() - "</groupId>".len();
1598                    return Some(trimmed[start..end].to_string());
1599                }
1600            }
1601            None
1602        }
1603        "build.gradle" | "build.gradle.kts" => {
1604            // Extract group from Gradle build file
1605            let content = std::fs::read_to_string(config_path).ok()?;
1606            for line in content.lines() {
1607                let trimmed = line.trim();
1608                if trimmed.starts_with("group")
1609                    && let Some(equals_idx) = trimmed.find('=')
1610                {
1611                    let value = &trimmed[equals_idx + 1..].trim();
1612                    let value = value.trim_matches(|c| c == '\'' || c == '"');
1613                    return Some(value.to_string());
1614                }
1615            }
1616            None
1617        }
1618        _ => None,
1619    }
1620}
1621
1622/// The package key (`jvm:<package>`) and member a Java or Kotlin import names.
1623///
1624/// The package ends at the first segment that starts with a capital letter, which
1625/// is the member: `a.b.C.Inner` and `static a.b.C.m` name class `C` of `a.b`. A
1626/// wildcard with no class names the whole package (`a.b.*`); with none and no
1627/// wildcard, the last segment is the member (a Kotlin top-level function).
1628pub fn jvm_import_key(import_path: &str) -> (String, Option<String>) {
1629    let (path, wildcard) = match import_path.strip_suffix(".*") {
1630        Some(path) => (path, true),
1631        None => (import_path, false),
1632    };
1633    let segments: Vec<&str> = path.split('.').collect();
1634    let class = segments
1635        .iter()
1636        .position(|s| s.starts_with(|c: char| c.is_uppercase()));
1637    let (package, member) = match class {
1638        Some(i) => (&segments[..i], Some(segments[i])),
1639        None if wildcard => (&segments[..], None),
1640        None => (&segments[..segments.len() - 1], segments.last().copied()),
1641    };
1642    (
1643        format!("jvm:{}", package.join(".")),
1644        member.map(str::to_string),
1645    )
1646}
1647
1648/// The `(jvm:<package>, member)` rows a Java or Kotlin file declares: its file
1649/// stem and every top-level name (types; Kotlin functions, properties, objects,
1650/// type aliases), under the package its `package` line names.
1651///
1652/// The package comes from the file, not its path: a package can be split across
1653/// Maven modules, and Kotlin files need not sit in their package's directory.
1654/// Top-level declarations are found by a line scan at column 0 (nested ones are
1655/// indented), which every formatter in use produces.
1656pub fn jvm_package_members(path: &str, source: &str) -> Vec<(String, String)> {
1657    let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path);
1658    let stem = file_name
1659        .split_once('.')
1660        .map_or(file_name, |(stem, _)| stem);
1661    let mut package = String::new();
1662    let mut names: Vec<String> = vec![stem.to_string()];
1663    let mut in_comment = false;
1664    for line in source.lines() {
1665        if in_comment {
1666            in_comment = !line.contains("*/");
1667            continue;
1668        }
1669        if line.is_empty() || line.starts_with(char::is_whitespace) {
1670            continue;
1671        }
1672        if line.starts_with("/*") {
1673            in_comment = !line.contains("*/");
1674            continue;
1675        }
1676        if let Some(rest) = line.strip_prefix("package ") {
1677            package = rest.trim().trim_end_matches(';').trim().replace('`', "");
1678            continue;
1679        }
1680        if let Some(name) = top_level_name(line)
1681            && !names.contains(&name)
1682        {
1683            names.push(name);
1684        }
1685    }
1686    let key = format!("jvm:{package}");
1687    // `""`: the whole package, what a wildcard import reaches
1688    std::iter::once(String::new())
1689        .chain(names)
1690        .map(|name| (key.clone(), name))
1691        .collect()
1692}
1693
1694/// The name a column-0 Java or Kotlin declaration line declares, if it is one.
1695fn top_level_name(line: &str) -> Option<String> {
1696    const MODIFIERS: &[&str] = &[
1697        "public",
1698        "private",
1699        "protected",
1700        "internal",
1701        "abstract",
1702        "final",
1703        "open",
1704        "sealed",
1705        "non-sealed",
1706        "static",
1707        "strictfp",
1708        "data",
1709        "inline",
1710        "value",
1711        "annotation",
1712        "inner",
1713        "expect",
1714        "actual",
1715        "const",
1716        "suspend",
1717        "operator",
1718        "infix",
1719        "tailrec",
1720        "external",
1721        "lateinit",
1722        "override",
1723        "enum",
1724    ];
1725    let mut tokens = line.split_whitespace().peekable();
1726    loop {
1727        let token = tokens.next()?;
1728        match token {
1729            "@interface" | "class" | "interface" | "record" | "object" | "typealias" => {
1730                return identifier(tokens.next()?);
1731            }
1732            // Java `enum Mode {`, Kotlin `enum class Color`
1733            "enum" if tokens.peek() != Some(&"class") => return identifier(tokens.next()?),
1734            "fun" if tokens.peek() == Some(&"interface") => {
1735                tokens.next();
1736                return identifier(tokens.next()?);
1737            }
1738            "fun" | "val" | "var" => {
1739                let rest = tokens.collect::<Vec<_>>().join(" ");
1740                return callable_name(&rest);
1741            }
1742            t if t.starts_with('@') || MODIFIERS.contains(&t) => continue,
1743            _ => return None,
1744        }
1745    }
1746}
1747
1748/// The name in a Kotlin `fun` / `val` declaration after the keyword: type
1749/// parameters and an extension receiver are skipped (`<T> List<T>.second(): T`).
1750fn callable_name(rest: &str) -> Option<String> {
1751    let mut rest = rest.trim_start();
1752    if rest.starts_with('<') {
1753        let mut depth = 0;
1754        let end = rest.char_indices().find_map(|(i, c)| {
1755            match c {
1756                '<' => depth += 1,
1757                '>' => depth -= 1,
1758                _ => {}
1759            }
1760            (depth == 0).then_some(i)
1761        })?;
1762        rest = rest[end + 1..].trim_start();
1763    }
1764    let end = rest.find(['(', ':', '=', ' ']).unwrap_or(rest.len());
1765    identifier(rest[..end].rsplit('.').next()?)
1766}
1767
1768/// The identifier at the start of `token` (`Point(val` → `Point`).
1769fn identifier(token: &str) -> Option<String> {
1770    let name: String = token
1771        .trim_matches('`')
1772        .chars()
1773        .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
1774        .collect();
1775    (!name.is_empty()).then_some(name)
1776}
1777
1778#[cfg(test)]
1779mod monorepo_tests {
1780    use super::*;
1781    use std::fs;
1782    use tempfile::TempDir;
1783
1784    #[test]
1785    fn test_extract_package_from_pom_xml() {
1786        let temp = TempDir::new().unwrap();
1787        let pom_path = temp.path().join("pom.xml");
1788
1789        fs::write(
1790            &pom_path,
1791            r#"
1792<?xml version="1.0" encoding="UTF-8"?>
1793<project>
1794    <groupId>com.example.myapp</groupId>
1795    <artifactId>my-application</artifactId>
1796</project>
1797        "#,
1798        )
1799        .unwrap();
1800
1801        let package = extract_package_from_config(&pom_path);
1802        assert_eq!(package, Some("com.example.myapp".to_string()));
1803    }
1804
1805    #[test]
1806    fn test_extract_package_from_gradle() {
1807        let temp = TempDir::new().unwrap();
1808        let gradle_path = temp.path().join("build.gradle");
1809
1810        fs::write(
1811            &gradle_path,
1812            r#"
1813group = 'org.example.myproject'
1814version = '1.0.0'
1815        "#,
1816        )
1817        .unwrap();
1818
1819        let package = extract_package_from_config(&gradle_path);
1820        assert_eq!(package, Some("org.example.myproject".to_string()));
1821    }
1822
1823    #[test]
1824    fn test_extract_package_from_gradle_kts() {
1825        let temp = TempDir::new().unwrap();
1826        let gradle_path = temp.path().join("build.gradle.kts");
1827
1828        fs::write(
1829            &gradle_path,
1830            r#"
1831group = "com.acme.tools"
1832version = "2.0.0"
1833        "#,
1834        )
1835        .unwrap();
1836
1837        let package = extract_package_from_config(&gradle_path);
1838        assert_eq!(package, Some("com.acme.tools".to_string()));
1839    }
1840
1841    #[test]
1842    fn jvm_import_split() {
1843        let key = |p: &str| jvm_import_key(p);
1844        let pkg = |p: &str, m: Option<&str>| (format!("jvm:{p}"), m.map(str::to_string));
1845        assert_eq!(key("a.b.C"), pkg("a.b", Some("C")));
1846        assert_eq!(key("a.b.C.Inner"), pkg("a.b", Some("C")));
1847        assert_eq!(key("a.b.C.method"), pkg("a.b", Some("C")));
1848        assert_eq!(key("a.b.*"), pkg("a.b", None));
1849        assert_eq!(key("a.b.C.*"), pkg("a.b", Some("C")));
1850        // A Kotlin top-level function, or a lower-case class name
1851        assert_eq!(key("a.b.greet"), pkg("a.b", Some("greet")));
1852        assert_eq!(key("Foo"), pkg("", Some("Foo")));
1853    }
1854
1855    #[test]
1856    fn jvm_members_are_the_package_and_top_level_names() {
1857        let java = "// header\npackage org.acme.util;\n\nimport x.Y;\n\n@Deprecated\npublic final class Numbers {\n    class Inner {}\n}\nclass Helper {}\nenum Mode { A }\nrecord Pair(int a) {}\n@interface Marker {}\n";
1858        assert_eq!(
1859            jvm_package_members("app/src/main/java/org/acme/util/Numbers.java", java),
1860            ["", "Numbers", "Helper", "Mode", "Pair", "Marker"]
1861                .iter()
1862                .map(|m| ("jvm:org.acme.util".to_string(), m.to_string()))
1863                .collect::<Vec<_>>()
1864        );
1865        let kotlin = "@file:JvmName(\"Misc\")\npackage org.acme.app.helpers\n\nimport a.B\n\nfun greet() {}\ninternal fun <T> List<T>.second(): T = this[1]\nval answer: Int = 42\nprivate const val LIMIT = 3\ndata class Point(val x: Int)\nsealed interface Shape\nobject Registry {\n    fun nested() {}\n}\ntypealias Name = String\nenum class Color { RED }\nfun interface Action { fun run() }\n";
1866        assert_eq!(
1867            jvm_package_members("src/main/kotlin/Misc.kt", kotlin),
1868            [
1869                "", "Misc", "greet", "second", "answer", "LIMIT", "Point", "Shape", "Registry",
1870                "Name", "Color", "Action"
1871            ]
1872            .iter()
1873            .map(|m| ("jvm:org.acme.app.helpers".to_string(), m.to_string()))
1874            .collect::<Vec<_>>()
1875        );
1876        // The default package
1877        assert_eq!(
1878            jvm_package_members("Foo.java", "class Foo {}\n"),
1879            vec![
1880                ("jvm:".to_string(), String::new()),
1881                ("jvm:".to_string(), "Foo".to_string())
1882            ]
1883        );
1884    }
1885
1886    #[test]
1887    fn wildcard_keeps_star() {
1888        let imports = JavaDependencyExtractor::extract_dependencies(
1889            "import org.acme.util.*;\nimport static org.acme.Numbers.*;\nimport org.acme.Strings;\n",
1890        )
1891        .unwrap();
1892        let paths: Vec<&str> = imports.iter().map(|i| i.imported_path.as_str()).collect();
1893        assert_eq!(
1894            paths,
1895            ["org.acme.util.*", "org.acme.Numbers.*", "org.acme.Strings"]
1896        );
1897    }
1898}