Skip to main content

code_analyze_mcp/languages/
java.rs

1/// Tree-sitter query for extracting Java elements (methods and classes).
2pub const ELEMENT_QUERY: &str = r"
3(method_declaration
4  name: (identifier) @method_name) @function
5(class_declaration
6  name: (identifier) @class_name) @class
7(interface_declaration
8  name: (identifier) @interface_name) @class
9(enum_declaration
10  name: (identifier) @enum_name) @class
11";
12
13/// Tree-sitter query for extracting function calls.
14pub const CALL_QUERY: &str = r"
15(method_invocation
16  name: (identifier) @call)
17";
18
19/// Tree-sitter query for extracting type references.
20pub const REFERENCE_QUERY: &str = r"
21(type_identifier) @type_ref
22";
23
24/// Tree-sitter query for extracting Java imports.
25pub const IMPORT_QUERY: &str = r"
26(import_declaration) @import_path
27";
28
29use tree_sitter::Node;
30
31/// Extract inheritance information from a Java class node.
32#[must_use]
33pub fn extract_inheritance(node: &Node, source: &str) -> Vec<String> {
34    let mut inherits = Vec::new();
35
36    // Extract superclass (extends)
37    if let Some(superclass) = node.child_by_field_name("superclass") {
38        for i in 0..superclass.named_child_count() {
39            if let Some(child) = superclass.named_child(u32::try_from(i).unwrap_or(u32::MAX))
40                && child.kind() == "type_identifier"
41            {
42                let text = &source[child.start_byte()..child.end_byte()];
43                inherits.push(format!("extends {text}"));
44            }
45        }
46    }
47
48    // Extract interfaces (implements)
49    if let Some(interfaces) = node.child_by_field_name("interfaces") {
50        for i in 0..interfaces.named_child_count() {
51            if let Some(type_list) = interfaces.named_child(u32::try_from(i).unwrap_or(u32::MAX)) {
52                for j in 0..type_list.named_child_count() {
53                    if let Some(type_node) =
54                        type_list.named_child(u32::try_from(j).unwrap_or(u32::MAX))
55                        && type_node.kind() == "type_identifier"
56                    {
57                        let text = &source[type_node.start_byte()..type_node.end_byte()];
58                        inherits.push(format!("implements {text}"));
59                    }
60                }
61            }
62        }
63    }
64
65    inherits
66}