Skip to main content

boundary_java/
lib.rs

1use std::path::Path;
2
3use anyhow::{Context, Result};
4use tree_sitter::{Language, Parser, Query, QueryCursor, StreamingIterator};
5
6use boundary_core::analyzer::{LanguageAnalyzer, ParsedFile};
7use boundary_core::types::*;
8
9/// Java language analyzer using tree-sitter.
10pub struct JavaAnalyzer {
11    language: Language,
12    interface_query: Query,
13    class_query: Query,
14    import_query: Query,
15    annotation_query: Query,
16}
17
18impl JavaAnalyzer {
19    pub fn new() -> Result<Self> {
20        let language: Language = tree_sitter_java::LANGUAGE.into();
21
22        let interface_query = Query::new(
23            &language,
24            r#"
25            (interface_declaration
26              name: (identifier) @name
27              body: (interface_body
28                (method_declaration
29                  name: (identifier) @method)*))
30            "#,
31        )
32        .context("failed to compile interface query")?;
33
34        let class_query = Query::new(
35            &language,
36            r#"
37            (class_declaration
38              name: (identifier) @name
39              interfaces: (super_interfaces
40                (type_list
41                  (type_identifier) @implements))?
42              body: (class_body))
43            "#,
44        )
45        .context("failed to compile class query")?;
46
47        let import_query = Query::new(
48            &language,
49            r#"
50            (import_declaration
51              (scoped_identifier) @path)
52            "#,
53        )
54        .context("failed to compile import query")?;
55
56        // Annotation on class declarations for classification hints
57        let annotation_query = Query::new(
58            &language,
59            r#"
60            (class_declaration
61              (modifiers
62                (marker_annotation
63                  name: (identifier) @annotation))
64              name: (identifier) @class_name)
65            "#,
66        )
67        .context("failed to compile annotation query")?;
68
69        Ok(Self {
70            language,
71            interface_query,
72            class_query,
73            import_query,
74            annotation_query,
75        })
76    }
77}
78
79impl LanguageAnalyzer for JavaAnalyzer {
80    fn language(&self) -> &'static str {
81        "java"
82    }
83
84    fn file_extensions(&self) -> &[&str] {
85        &["java"]
86    }
87
88    fn parse_file(&self, path: &Path, content: &str) -> Result<ParsedFile> {
89        let mut parser = Parser::new();
90        parser
91            .set_language(&self.language)
92            .context("failed to set Java language")?;
93        let tree = parser
94            .parse(content, None)
95            .context("failed to parse Java file")?;
96        Ok(ParsedFile {
97            path: path.to_path_buf(),
98            tree,
99            content: content.to_string(),
100        })
101    }
102
103    fn extract_components(&self, parsed: &ParsedFile) -> Vec<Component> {
104        let mut components = Vec::new();
105        let package_path = derive_package_path(&parsed.path);
106
107        // Extract interfaces (ports)
108        extract_interfaces(
109            &self.interface_query,
110            parsed,
111            &package_path,
112            &mut components,
113        );
114
115        // Extract classes
116        extract_classes(&self.class_query, parsed, &package_path, &mut components);
117
118        // Enrich with annotation info
119        enrich_with_annotations(
120            &self.annotation_query,
121            parsed,
122            &package_path,
123            &mut components,
124        );
125
126        components
127    }
128
129    fn extract_dependencies(&self, parsed: &ParsedFile) -> Vec<Dependency> {
130        let mut deps = Vec::new();
131        let package_path = derive_package_path(&parsed.path);
132        let from_id = ComponentId::new(&package_path, "<file>");
133
134        let mut cursor = QueryCursor::new();
135        let path_idx = self
136            .import_query
137            .capture_names()
138            .iter()
139            .position(|n| *n == "path")
140            .unwrap_or(0);
141
142        let mut matches = cursor.matches(
143            &self.import_query,
144            parsed.tree.root_node(),
145            parsed.content.as_bytes(),
146        );
147
148        while let Some(m) = matches.next() {
149            for capture in m.captures {
150                if capture.index as usize == path_idx {
151                    let node = capture.node;
152                    let import_path = node_text(node, &parsed.content);
153
154                    // Skip java.lang.* and standard library
155                    if import_path.starts_with("java.") || import_path.starts_with("javax.") {
156                        continue;
157                    }
158
159                    let to_id = ComponentId::new(&import_path, "<class>");
160
161                    deps.push(Dependency {
162                        from: from_id.clone(),
163                        to: to_id,
164                        kind: DependencyKind::Import,
165                        location: SourceLocation {
166                            file: parsed.path.clone(),
167                            line: node.start_position().row + 1,
168                            column: node.start_position().column + 1,
169                        },
170                        import_path: Some(import_path),
171                    });
172                }
173            }
174        }
175
176        deps
177    }
178}
179
180fn extract_interfaces(
181    query: &Query,
182    parsed: &ParsedFile,
183    package_path: &str,
184    components: &mut Vec<Component>,
185) {
186    let mut cursor = QueryCursor::new();
187    let name_idx = query
188        .capture_names()
189        .iter()
190        .position(|n| *n == "name")
191        .unwrap_or(0);
192    let method_idx = query.capture_names().iter().position(|n| *n == "method");
193
194    let mut matches = cursor.matches(query, parsed.tree.root_node(), parsed.content.as_bytes());
195
196    while let Some(m) = matches.next() {
197        let mut name = String::new();
198        let mut methods = Vec::new();
199        let mut start_row = 0;
200        let mut start_col = 0;
201
202        for capture in m.captures {
203            if capture.index as usize == name_idx {
204                name = node_text(capture.node, &parsed.content);
205                start_row = capture.node.start_position().row;
206                start_col = capture.node.start_position().column;
207            } else if Some(capture.index as usize) == method_idx {
208                methods.push(MethodInfo {
209                    name: node_text(capture.node, &parsed.content),
210                    parameters: String::new(),
211                    return_type: String::new(),
212                });
213            }
214        }
215
216        if name.is_empty() {
217            continue;
218        }
219
220        components.push(Component {
221            id: ComponentId::new(package_path, &name),
222            name: name.clone(),
223            kind: ComponentKind::Port(PortInfo { name, methods }),
224            layer: None,
225            location: SourceLocation {
226                file: parsed.path.clone(),
227                line: start_row + 1,
228                column: start_col + 1,
229            },
230            is_cross_cutting: false,
231            architecture_mode: ArchitectureMode::default(),
232        });
233    }
234}
235
236fn extract_classes(
237    query: &Query,
238    parsed: &ParsedFile,
239    package_path: &str,
240    components: &mut Vec<Component>,
241) {
242    let mut cursor = QueryCursor::new();
243    let name_idx = query
244        .capture_names()
245        .iter()
246        .position(|n| *n == "name")
247        .unwrap_or(0);
248    let implements_idx = query
249        .capture_names()
250        .iter()
251        .position(|n| *n == "implements");
252
253    let mut matches = cursor.matches(query, parsed.tree.root_node(), parsed.content.as_bytes());
254
255    while let Some(m) = matches.next() {
256        let mut name = String::new();
257        let mut implements = Vec::new();
258        let mut start_row = 0;
259        let mut start_col = 0;
260
261        for capture in m.captures {
262            if capture.index as usize == name_idx {
263                name = node_text(capture.node, &parsed.content);
264                start_row = capture.node.start_position().row;
265                start_col = capture.node.start_position().column;
266            } else if Some(capture.index as usize) == implements_idx {
267                implements.push(node_text(capture.node, &parsed.content));
268            }
269        }
270
271        if name.is_empty() {
272            continue;
273        }
274
275        let kind = classify_class_kind(&name, &implements);
276
277        components.push(Component {
278            id: ComponentId::new(package_path, &name),
279            name: name.clone(),
280            kind,
281            layer: None,
282            location: SourceLocation {
283                file: parsed.path.clone(),
284                line: start_row + 1,
285                column: start_col + 1,
286            },
287            is_cross_cutting: false,
288            architecture_mode: ArchitectureMode::default(),
289        });
290    }
291}
292
293/// Enrich class components with annotation-based classification.
294fn enrich_with_annotations(
295    query: &Query,
296    parsed: &ParsedFile,
297    package_path: &str,
298    components: &mut [Component],
299) {
300    let mut cursor = QueryCursor::new();
301    let annotation_idx = query
302        .capture_names()
303        .iter()
304        .position(|n| *n == "annotation");
305    let class_name_idx = query
306        .capture_names()
307        .iter()
308        .position(|n| *n == "class_name");
309
310    let mut matches = cursor.matches(query, parsed.tree.root_node(), parsed.content.as_bytes());
311
312    while let Some(m) = matches.next() {
313        let mut annotation = String::new();
314        let mut class_name = String::new();
315
316        for capture in m.captures {
317            if Some(capture.index as usize) == annotation_idx {
318                annotation = node_text(capture.node, &parsed.content);
319            }
320            if Some(capture.index as usize) == class_name_idx {
321                class_name = node_text(capture.node, &parsed.content);
322            }
323        }
324
325        if class_name.is_empty() || annotation.is_empty() {
326            continue;
327        }
328
329        let id = ComponentId::new(package_path, &class_name);
330        if let Some(comp) = components.iter_mut().find(|c| c.id == id) {
331            match annotation.as_str() {
332                "Repository" => {
333                    comp.kind = ComponentKind::Repository;
334                }
335                "Service" => {
336                    comp.kind = ComponentKind::Service;
337                }
338                "Controller" | "RestController" => {
339                    comp.kind = ComponentKind::Adapter(AdapterInfo {
340                        name: class_name,
341                        implements: vec![],
342                    });
343                }
344                _ => {}
345            }
346        }
347    }
348}
349
350/// Classify a class by its name suffix heuristic and implements clause.
351fn classify_class_kind(name: &str, implements: &[String]) -> ComponentKind {
352    let lower = name.to_lowercase();
353    if lower.ends_with("repository") || lower.ends_with("repo") {
354        ComponentKind::Repository
355    } else if lower.ends_with("service") || lower.ends_with("svc") {
356        ComponentKind::Service
357    } else if lower.ends_with("handler") || lower.ends_with("controller") {
358        ComponentKind::Adapter(AdapterInfo {
359            name: name.to_string(),
360            implements: implements.to_vec(),
361        })
362    } else if lower.ends_with("usecase") || lower.ends_with("interactor") {
363        ComponentKind::UseCase
364    } else if !implements.is_empty() {
365        ComponentKind::Adapter(AdapterInfo {
366            name: name.to_string(),
367            implements: implements.to_vec(),
368        })
369    } else {
370        ComponentKind::Entity(EntityInfo {
371            name: name.to_string(),
372            fields: vec![],
373            methods: Vec::new(),
374            is_active_record: false,
375        })
376    }
377}
378
379/// Extract text from a tree-sitter node.
380fn node_text(node: tree_sitter::Node, source: &str) -> String {
381    source[node.byte_range()].to_string()
382}
383
384/// Derive a package path from a file path.
385fn derive_package_path(path: &Path) -> String {
386    path.parent()
387        .map(|p| p.to_string_lossy().replace('\\', "/"))
388        .unwrap_or_default()
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394    use std::path::PathBuf;
395
396    #[test]
397    fn test_parse_java_interface() {
398        let analyzer = JavaAnalyzer::new().unwrap();
399        let content = r#"
400package com.example.domain.user;
401
402public interface UserRepository {
403    void save(User user);
404    User findById(String id);
405}
406"#;
407        let path = PathBuf::from("src/main/java/com/example/domain/user/UserRepository.java");
408        let parsed = analyzer.parse_file(&path, content).unwrap();
409        let components = analyzer.extract_components(&parsed);
410
411        let repo = components.iter().find(|c| c.name == "UserRepository");
412        assert!(repo.is_some(), "should find UserRepository interface");
413        assert!(matches!(repo.unwrap().kind, ComponentKind::Port(_)));
414
415        if let ComponentKind::Port(ref info) = repo.unwrap().kind {
416            assert!(info.methods.iter().any(|m| m.name == "save"));
417            assert!(info.methods.iter().any(|m| m.name == "findById"));
418        }
419    }
420
421    #[test]
422    fn test_parse_java_class_with_implements() {
423        let analyzer = JavaAnalyzer::new().unwrap();
424        let content = r#"
425package com.example.infrastructure.postgres;
426
427public class PostgresUserRepository implements UserRepository {
428    private final DataSource dataSource;
429
430    public PostgresUserRepository(DataSource dataSource) {
431        this.dataSource = dataSource;
432    }
433
434    public void save(User user) {
435        // save implementation
436    }
437
438    public User findById(String id) {
439        return null;
440    }
441}
442"#;
443        let path = PathBuf::from(
444            "src/main/java/com/example/infrastructure/postgres/PostgresUserRepository.java",
445        );
446        let parsed = analyzer.parse_file(&path, content).unwrap();
447        let components = analyzer.extract_components(&parsed);
448
449        let repo = components
450            .iter()
451            .find(|c| c.name == "PostgresUserRepository");
452        assert!(repo.is_some(), "should find PostgresUserRepository");
453        // Name-based classification should match "Repository"
454        assert!(matches!(repo.unwrap().kind, ComponentKind::Repository));
455    }
456
457    #[test]
458    fn test_extract_imports() {
459        let analyzer = JavaAnalyzer::new().unwrap();
460        let content = r#"
461package com.example.application;
462
463import java.util.List;
464import com.example.domain.user.User;
465import com.example.domain.user.UserRepository;
466"#;
467        let path = PathBuf::from("src/main/java/com/example/application/UserService.java");
468        let parsed = analyzer.parse_file(&path, content).unwrap();
469        let deps = analyzer.extract_dependencies(&parsed);
470
471        // Should skip java.* imports
472        let paths: Vec<&str> = deps
473            .iter()
474            .filter_map(|d| d.import_path.as_deref())
475            .collect();
476        assert!(!paths.iter().any(|p| p.starts_with("java.")));
477        assert!(paths.iter().any(|p| p.contains("domain.user.User")));
478        assert!(paths
479            .iter()
480            .any(|p| p.contains("domain.user.UserRepository")));
481    }
482
483    #[test]
484    fn test_annotation_classification() {
485        let analyzer = JavaAnalyzer::new().unwrap();
486        let content = r#"
487package com.example.application;
488
489@Service
490public class UserService {
491    private final UserRepository repo;
492
493    public UserService(UserRepository repo) {
494        this.repo = repo;
495    }
496}
497"#;
498        let path = PathBuf::from("src/main/java/com/example/application/UserService.java");
499        let parsed = analyzer.parse_file(&path, content).unwrap();
500        let components = analyzer.extract_components(&parsed);
501
502        let svc = components.iter().find(|c| c.name == "UserService");
503        assert!(svc.is_some(), "should find UserService");
504        assert!(
505            matches!(svc.unwrap().kind, ComponentKind::Service),
506            "should be classified as Service by annotation"
507        );
508    }
509
510    #[test]
511    fn test_controller_annotation() {
512        let analyzer = JavaAnalyzer::new().unwrap();
513        let content = r#"
514package com.example.presentation;
515
516@Controller
517public class UserController {
518    public void getUser() {}
519}
520"#;
521        let path = PathBuf::from("src/main/java/com/example/presentation/UserController.java");
522        let parsed = analyzer.parse_file(&path, content).unwrap();
523        let components = analyzer.extract_components(&parsed);
524
525        let ctrl = components.iter().find(|c| c.name == "UserController");
526        assert!(ctrl.is_some(), "should find UserController");
527        assert!(
528            matches!(ctrl.unwrap().kind, ComponentKind::Adapter(_)),
529            "should be classified as Adapter by @Controller annotation"
530        );
531    }
532
533    #[test]
534    fn test_entity_class() {
535        let analyzer = JavaAnalyzer::new().unwrap();
536        let content = r#"
537package com.example.domain.user;
538
539public class User {
540    private String id;
541    private String name;
542    private String email;
543}
544"#;
545        let path = PathBuf::from("src/main/java/com/example/domain/user/User.java");
546        let parsed = analyzer.parse_file(&path, content).unwrap();
547        let components = analyzer.extract_components(&parsed);
548
549        let user = components.iter().find(|c| c.name == "User");
550        assert!(user.is_some(), "should find User");
551        assert!(matches!(user.unwrap().kind, ComponentKind::Entity(_)));
552    }
553}