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            is_anemic_domain_model: false,
376        })
377    }
378}
379
380/// Extract text from a tree-sitter node.
381fn node_text(node: tree_sitter::Node, source: &str) -> String {
382    source[node.byte_range()].to_string()
383}
384
385/// Derive a package path from a file path.
386fn derive_package_path(path: &Path) -> String {
387    path.parent()
388        .map(|p| p.to_string_lossy().replace('\\', "/"))
389        .unwrap_or_default()
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use std::path::PathBuf;
396
397    #[test]
398    fn test_parse_java_interface() {
399        let analyzer = JavaAnalyzer::new().unwrap();
400        let content = r#"
401package com.example.domain.user;
402
403public interface UserRepository {
404    void save(User user);
405    User findById(String id);
406}
407"#;
408        let path = PathBuf::from("src/main/java/com/example/domain/user/UserRepository.java");
409        let parsed = analyzer.parse_file(&path, content).unwrap();
410        let components = analyzer.extract_components(&parsed);
411
412        let repo = components.iter().find(|c| c.name == "UserRepository");
413        assert!(repo.is_some(), "should find UserRepository interface");
414        assert!(matches!(repo.unwrap().kind, ComponentKind::Port(_)));
415
416        if let ComponentKind::Port(ref info) = repo.unwrap().kind {
417            assert!(info.methods.iter().any(|m| m.name == "save"));
418            assert!(info.methods.iter().any(|m| m.name == "findById"));
419        }
420    }
421
422    #[test]
423    fn test_parse_java_class_with_implements() {
424        let analyzer = JavaAnalyzer::new().unwrap();
425        let content = r#"
426package com.example.infrastructure.postgres;
427
428public class PostgresUserRepository implements UserRepository {
429    private final DataSource dataSource;
430
431    public PostgresUserRepository(DataSource dataSource) {
432        this.dataSource = dataSource;
433    }
434
435    public void save(User user) {
436        // save implementation
437    }
438
439    public User findById(String id) {
440        return null;
441    }
442}
443"#;
444        let path = PathBuf::from(
445            "src/main/java/com/example/infrastructure/postgres/PostgresUserRepository.java",
446        );
447        let parsed = analyzer.parse_file(&path, content).unwrap();
448        let components = analyzer.extract_components(&parsed);
449
450        let repo = components
451            .iter()
452            .find(|c| c.name == "PostgresUserRepository");
453        assert!(repo.is_some(), "should find PostgresUserRepository");
454        // Name-based classification should match "Repository"
455        assert!(matches!(repo.unwrap().kind, ComponentKind::Repository));
456    }
457
458    #[test]
459    fn test_extract_imports() {
460        let analyzer = JavaAnalyzer::new().unwrap();
461        let content = r#"
462package com.example.application;
463
464import java.util.List;
465import com.example.domain.user.User;
466import com.example.domain.user.UserRepository;
467"#;
468        let path = PathBuf::from("src/main/java/com/example/application/UserService.java");
469        let parsed = analyzer.parse_file(&path, content).unwrap();
470        let deps = analyzer.extract_dependencies(&parsed);
471
472        // Should skip java.* imports
473        let paths: Vec<&str> = deps
474            .iter()
475            .filter_map(|d| d.import_path.as_deref())
476            .collect();
477        assert!(!paths.iter().any(|p| p.starts_with("java.")));
478        assert!(paths.iter().any(|p| p.contains("domain.user.User")));
479        assert!(paths
480            .iter()
481            .any(|p| p.contains("domain.user.UserRepository")));
482    }
483
484    #[test]
485    fn test_annotation_classification() {
486        let analyzer = JavaAnalyzer::new().unwrap();
487        let content = r#"
488package com.example.application;
489
490@Service
491public class UserService {
492    private final UserRepository repo;
493
494    public UserService(UserRepository repo) {
495        this.repo = repo;
496    }
497}
498"#;
499        let path = PathBuf::from("src/main/java/com/example/application/UserService.java");
500        let parsed = analyzer.parse_file(&path, content).unwrap();
501        let components = analyzer.extract_components(&parsed);
502
503        let svc = components.iter().find(|c| c.name == "UserService");
504        assert!(svc.is_some(), "should find UserService");
505        assert!(
506            matches!(svc.unwrap().kind, ComponentKind::Service),
507            "should be classified as Service by annotation"
508        );
509    }
510
511    #[test]
512    fn test_controller_annotation() {
513        let analyzer = JavaAnalyzer::new().unwrap();
514        let content = r#"
515package com.example.presentation;
516
517@Controller
518public class UserController {
519    public void getUser() {}
520}
521"#;
522        let path = PathBuf::from("src/main/java/com/example/presentation/UserController.java");
523        let parsed = analyzer.parse_file(&path, content).unwrap();
524        let components = analyzer.extract_components(&parsed);
525
526        let ctrl = components.iter().find(|c| c.name == "UserController");
527        assert!(ctrl.is_some(), "should find UserController");
528        assert!(
529            matches!(ctrl.unwrap().kind, ComponentKind::Adapter(_)),
530            "should be classified as Adapter by @Controller annotation"
531        );
532    }
533
534    #[test]
535    fn test_entity_class() {
536        let analyzer = JavaAnalyzer::new().unwrap();
537        let content = r#"
538package com.example.domain.user;
539
540public class User {
541    private String id;
542    private String name;
543    private String email;
544}
545"#;
546        let path = PathBuf::from("src/main/java/com/example/domain/user/User.java");
547        let parsed = analyzer.parse_file(&path, content).unwrap();
548        let components = analyzer.extract_components(&parsed);
549
550        let user = components.iter().find(|c| c.name == "User");
551        assert!(user.is_some(), "should find User");
552        assert!(matches!(user.unwrap().kind, ComponentKind::Entity(_)));
553    }
554}