use std::time::{Instant, SystemTime, UNIX_EPOCH};
use tree_sitter::{Node as TsNode, Parser, Tree};
use crate::extraction::complexity::{count_complexity, JAVA_COMPLEXITY};
use crate::types::{
generate_node_id, Edge, EdgeKind, ExtractionResult, Node, NodeKind, UnresolvedRef, Visibility,
};
pub struct JavaExtractor;
struct ExtractionState {
nodes: Vec<Node>,
edges: Vec<Edge>,
unresolved_refs: Vec<UnresolvedRef>,
errors: Vec<String>,
node_stack: Vec<(String, String)>,
file_path: String,
source: Vec<u8>,
timestamp: u64,
class_depth: usize,
inside_interface: bool,
}
impl ExtractionState {
fn new(file_path: &str, source: &str) -> Self {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
Self {
nodes: Vec::new(),
edges: Vec::new(),
unresolved_refs: Vec::new(),
errors: Vec::new(),
node_stack: Vec::new(),
file_path: file_path.to_string(),
source: source.as_bytes().to_vec(),
timestamp,
class_depth: 0,
inside_interface: false,
}
}
fn qualified_prefix(&self) -> String {
let mut parts = vec![self.file_path.clone()];
for (name, _) in &self.node_stack {
parts.push(name.clone());
}
parts.join("::")
}
fn parent_node_id(&self) -> Option<&str> {
self.node_stack.last().map(|(_, id)| id.as_str())
}
fn node_text(&self, node: TsNode<'_>) -> String {
node.utf8_text(&self.source)
.unwrap_or("<invalid utf8>")
.to_string()
}
}
impl JavaExtractor {
pub fn extract_java(file_path: &str, source: &str) -> ExtractionResult {
let start = Instant::now();
let mut state = ExtractionState::new(file_path, source);
let tree = match Self::parse_source(source) {
Ok(tree) => tree,
Err(msg) => {
state.errors.push(msg);
return Self::build_result(state, start);
}
};
let file_node = Node {
id: generate_node_id(file_path, &NodeKind::File, file_path, 0),
kind: NodeKind::File,
name: file_path.to_string(),
qualified_name: file_path.to_string(),
file_path: file_path.to_string(),
start_line: 0,
end_line: source.lines().count().saturating_sub(1) as u32,
start_column: 0,
end_column: 0,
signature: None,
docstring: None,
visibility: Visibility::Pub,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
let file_node_id = file_node.id.clone();
state.nodes.push(file_node);
state.node_stack.push((file_path.to_string(), file_node_id));
let root = tree.root_node();
Self::visit_children(&mut state, root);
state.node_stack.pop();
Self::build_result(state, start)
}
fn parse_source(source: &str) -> Result<Tree, String> {
let mut parser = Parser::new();
let language = crate::extraction::ts_provider::language("java");
parser
.set_language(&language)
.map_err(|e| format!("failed to load Java grammar: {e}"))?;
parser
.parse(source, None)
.ok_or_else(|| "tree-sitter parse returned None".to_string())
}
fn visit_children(state: &mut ExtractionState, node: TsNode<'_>) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
Self::visit_node(state, child);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn visit_node(state: &mut ExtractionState, node: TsNode<'_>) {
match node.kind() {
"package_declaration" => Self::visit_package(state, node),
"import_declaration" => Self::visit_import(state, node),
"class_declaration" => Self::visit_class(state, node),
"interface_declaration" => Self::visit_interface(state, node),
"enum_declaration" => Self::visit_enum(state, node),
"annotation_type_declaration" => Self::visit_annotation_type(state, node),
"method_declaration" => Self::visit_method(state, node),
"constructor_declaration" => Self::visit_constructor(state, node),
"field_declaration" => Self::visit_field(state, node),
"static_initializer" => Self::visit_static_initializer(state, node),
"marker_annotation" | "annotation" => {
}
_ => {
Self::visit_children(state, node);
}
}
}
fn visit_package(state: &mut ExtractionState, node: TsNode<'_>) {
let text = state.node_text(node);
let pkg_name = text
.trim()
.strip_prefix("package ")
.unwrap_or(&text)
.trim_end_matches(';')
.trim()
.to_string();
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), pkg_name);
let id = generate_node_id(&state.file_path, &NodeKind::Package, &pkg_name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Package,
name: pkg_name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(text.trim().to_string()),
docstring: None,
visibility: Visibility::Pub,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
fn visit_import(state: &mut ExtractionState, node: TsNode<'_>) {
let text = state.node_text(node);
let path = text
.trim()
.strip_prefix("import ")
.unwrap_or(&text)
.trim()
.strip_prefix("static ")
.unwrap_or(text.trim().strip_prefix("import ").unwrap_or(&text).trim())
.trim_end_matches(';')
.trim()
.to_string();
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), path);
let id = generate_node_id(&state.file_path, &NodeKind::Use, &path, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Use,
name: path.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(text.trim().to_string()),
docstring: None,
visibility: Visibility::Private,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
state.unresolved_refs.push(UnresolvedRef {
from_node_id: id,
reference_name: path,
reference_kind: EdgeKind::Uses,
line: start_line,
column: start_column,
file_path: state.file_path.clone(),
});
}
fn visit_class(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let kind = if state.class_depth > 0 {
NodeKind::InnerClass
} else {
NodeKind::Class
};
let id = generate_node_id(&state.file_path, &kind, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind,
name: name.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
Self::extract_superclass(state, node, &id);
Self::extract_super_interfaces(state, node, &id);
Self::extract_type_parameters(state, node, &id);
state.node_stack.push((name, id));
state.class_depth += 1;
if let Some(body) = node.child_by_field_name("body") {
Self::visit_children(state, body);
}
state.class_depth -= 1;
state.node_stack.pop();
}
fn visit_interface(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::Interface, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Interface,
name: name.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
Self::extract_type_parameters(state, node, &id);
let prev_inside_interface = state.inside_interface;
state.inside_interface = true;
state.node_stack.push((name, id));
state.class_depth += 1;
if let Some(body) = node.child_by_field_name("body") {
Self::visit_children(state, body);
}
state.class_depth -= 1;
state.node_stack.pop();
state.inside_interface = prev_inside_interface;
}
fn visit_enum(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::Enum, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Enum,
name: name.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
state.node_stack.push((name, id));
if let Some(body) = node.child_by_field_name("body") {
Self::extract_enum_constants(state, body);
}
state.node_stack.pop();
}
fn extract_enum_constants(state: &mut ExtractionState, body: TsNode<'_>) {
let mut cursor = body.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "enum_constant" {
Self::extract_single_enum_constant(state, child);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_single_enum_constant(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::EnumVariant, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::EnumVariant,
name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(state.node_text(node).trim().to_string()),
docstring: None,
visibility: Visibility::Pub,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
fn visit_annotation_type(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::Annotation, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Annotation,
name: name.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
fn visit_method(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let has_abstract_modifier = Self::has_modifier(node, state, "abstract");
let has_body =
node.child_by_field_name("body").is_some() || Self::has_child_of_kind(node, "block");
let is_abstract = has_abstract_modifier || (state.inside_interface && !has_body);
let kind = if is_abstract {
NodeKind::AbstractMethod
} else {
NodeKind::Method
};
let id = generate_node_id(&state.file_path, &kind, &name, start_line);
let metrics = count_complexity(node, &JAVA_COMPLEXITY, &state.source);
let graph_node = Node {
id: id.clone(),
kind,
name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: metrics.branches,
loops: metrics.loops,
returns: metrics.returns,
max_nesting: metrics.max_nesting,
unsafe_blocks: metrics.unsafe_blocks,
unchecked_calls: metrics.unchecked_calls,
assertions: metrics.assertions,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
Self::extract_annotations_from_modifiers(state, node, &id);
Self::extract_type_refs(state, node, &id);
if has_body {
Self::extract_call_sites(state, node, &id);
}
}
fn visit_constructor(state: &mut ExtractionState, node: TsNode<'_>) {
let name = Self::extract_name(state, node).unwrap_or_else(|| "<anonymous>".to_string());
let visibility = Self::extract_java_visibility(node, state);
let docstring = Self::extract_java_docstring(state, node);
let signature = Self::extract_declaration_signature(state, node);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::Constructor, &name, start_line);
let metrics = count_complexity(node, &JAVA_COMPLEXITY, &state.source);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Constructor,
name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature,
docstring,
visibility,
is_async: false,
branches: metrics.branches,
loops: metrics.loops,
returns: metrics.returns,
max_nesting: metrics.max_nesting,
unsafe_blocks: metrics.unsafe_blocks,
unchecked_calls: metrics.unchecked_calls,
assertions: metrics.assertions,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id.clone(),
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
Self::extract_type_refs(state, node, &id);
Self::extract_call_sites(state, node, &id);
}
fn visit_field(state: &mut ExtractionState, node: TsNode<'_>) {
let visibility = Self::extract_java_visibility(node, state);
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let signature_text = state.node_text(node).trim().to_string();
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "variable_declarator" {
let field_name = child
.child_by_field_name("name")
.map(|n| state.node_text(n))
.unwrap_or_else(|| {
Self::extract_name(state, child)
.unwrap_or_else(|| "<anonymous>".to_string())
});
let qualified_name = format!("{}::{}", state.qualified_prefix(), field_name);
let id = generate_node_id(
&state.file_path,
&NodeKind::Field,
&field_name,
start_line,
);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::Field,
name: field_name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(signature_text.clone()),
docstring: None,
visibility: visibility.clone(),
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn visit_static_initializer(state: &mut ExtractionState, node: TsNode<'_>) {
let start_line = node.start_position().row as u32;
let end_line = node.end_position().row as u32;
let start_column = node.start_position().column as u32;
let end_column = node.end_position().column as u32;
let name = format!("<static_init>:{start_line}");
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(&state.file_path, &NodeKind::InitBlock, &name, start_line);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::InitBlock,
name,
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some("static { ... }".to_string()),
docstring: None,
visibility: Visibility::Private,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
if let Some(parent_id) = state.parent_node_id() {
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
}
fn extract_name(state: &ExtractionState, node: TsNode<'_>) -> Option<String> {
node.child_by_field_name("name").map(|n| state.node_text(n))
}
fn extract_java_visibility(node: TsNode<'_>, state: &ExtractionState) -> Visibility {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "modifiers" {
let text = state.node_text(child);
if text.contains("public") {
return Visibility::Pub;
} else if text.contains("protected") {
return Visibility::PubCrate;
} else if text.contains("private") {
return Visibility::Private;
}
return Visibility::Private;
}
if !cursor.goto_next_sibling() {
break;
}
}
}
Visibility::Private
}
fn has_modifier(node: TsNode<'_>, state: &ExtractionState, modifier: &str) -> bool {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "modifiers" {
let text = state.node_text(child);
return text.split_whitespace().any(|w| w == modifier);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
false
}
fn has_child_of_kind(node: TsNode<'_>, kind: &str) -> bool {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
if cursor.node().kind() == kind {
return true;
}
if !cursor.goto_next_sibling() {
break;
}
}
}
false
}
fn extract_declaration_signature(state: &ExtractionState, node: TsNode<'_>) -> Option<String> {
let text = state.node_text(node);
if let Some(brace_pos) = text.find('{') {
Some(text[..brace_pos].trim().to_string())
} else {
Some(text.trim_end_matches(';').trim().to_string())
}
}
fn extract_java_docstring(state: &ExtractionState, node: TsNode<'_>) -> Option<String> {
let mut current = node.prev_named_sibling();
while let Some(sibling) = current {
match sibling.kind() {
"block_comment" => {
let text = state.node_text(sibling);
if text.starts_with("/**") {
return Some(Self::clean_javadoc(&text));
}
current = sibling.prev_named_sibling();
}
"line_comment" => {
current = sibling.prev_named_sibling();
}
_ => break,
}
}
None
}
fn clean_javadoc(comment: &str) -> String {
let trimmed = comment.trim();
let inner = if trimmed.starts_with("/**") && trimmed.ends_with("*/") {
&trimmed[3..trimmed.len() - 2]
} else {
trimmed
};
inner
.lines()
.map(|line| {
let l = line.trim();
l.strip_prefix("* ")
.or_else(|| l.strip_prefix('*'))
.unwrap_or(l)
})
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_string()
}
fn extract_superclass(state: &mut ExtractionState, node: TsNode<'_>, class_id: &str) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "superclass" {
let mut inner_cursor = child.walk();
if inner_cursor.goto_first_child() {
loop {
let inner_child = inner_cursor.node();
if inner_child.is_named()
&& inner_child.kind() != "extends"
&& inner_child.kind() != "superclass"
{
let type_name = state.node_text(inner_child);
state.unresolved_refs.push(UnresolvedRef {
from_node_id: class_id.to_string(),
reference_name: type_name,
reference_kind: EdgeKind::Extends,
line: inner_child.start_position().row as u32,
column: inner_child.start_position().column as u32,
file_path: state.file_path.clone(),
});
break;
}
if !inner_cursor.goto_next_sibling() {
break;
}
}
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_super_interfaces(state: &mut ExtractionState, node: TsNode<'_>, class_id: &str) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "super_interfaces" {
Self::extract_type_list_as_implements(state, child, class_id);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_type_list_as_implements(
state: &mut ExtractionState,
node: TsNode<'_>,
class_id: &str,
) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.is_named()
&& (child.kind() == "type_identifier" || child.kind() == "generic_type")
{
let type_name = state.node_text(child);
state.unresolved_refs.push(UnresolvedRef {
from_node_id: class_id.to_string(),
reference_name: type_name,
reference_kind: EdgeKind::Implements,
line: child.start_position().row as u32,
column: child.start_position().column as u32,
file_path: state.file_path.clone(),
});
} else if child.kind() == "type_list" {
Self::extract_type_list_as_implements(state, child, class_id);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_type_parameters(state: &mut ExtractionState, node: TsNode<'_>, parent_id: &str) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "type_parameters" {
Self::extract_type_params_from_list(state, child, parent_id);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_type_params_from_list(
state: &mut ExtractionState,
node: TsNode<'_>,
parent_id: &str,
) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "type_parameter" {
let param_name = state.node_text(child);
let name = param_name.split_whitespace().next().unwrap_or(¶m_name);
let start_line = child.start_position().row as u32;
let end_line = child.end_position().row as u32;
let start_column = child.start_position().column as u32;
let end_column = child.end_position().column as u32;
let qualified_name = format!("{}::{}", state.qualified_prefix(), name);
let id = generate_node_id(
&state.file_path,
&NodeKind::GenericParam,
name,
start_line,
);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::GenericParam,
name: name.to_string(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(param_name.trim().to_string()),
docstring: None,
visibility: Visibility::Private,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
state.edges.push(Edge {
source: parent_id.to_string(),
target: id,
kind: EdgeKind::Contains,
line: Some(start_line),
});
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_annotations_from_modifiers(
state: &mut ExtractionState,
node: TsNode<'_>,
target_id: &str,
) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "modifiers" {
Self::extract_annotations_from_node(state, child, target_id);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_annotations_from_node(
state: &mut ExtractionState,
node: TsNode<'_>,
target_id: &str,
) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.kind() == "marker_annotation" || child.kind() == "annotation" {
let annot_name = Self::extract_annotation_name(state, child);
let start_line = child.start_position().row as u32;
let end_line = child.end_position().row as u32;
let start_column = child.start_position().column as u32;
let end_column = child.end_position().column as u32;
let qualified_name = format!("{}::@{}", state.qualified_prefix(), annot_name);
let id = generate_node_id(
&state.file_path,
&NodeKind::AnnotationUsage,
&annot_name,
start_line,
);
let graph_node = Node {
id: id.clone(),
kind: NodeKind::AnnotationUsage,
name: annot_name.clone(),
qualified_name,
file_path: state.file_path.clone(),
start_line,
end_line,
start_column,
end_column,
signature: Some(state.node_text(child).trim().to_string()),
docstring: None,
visibility: Visibility::Private,
is_async: false,
branches: 0,
loops: 0,
returns: 0,
max_nesting: 0,
unsafe_blocks: 0,
unchecked_calls: 0,
assertions: 0,
updated_at: state.timestamp,
};
state.nodes.push(graph_node);
state.unresolved_refs.push(UnresolvedRef {
from_node_id: id.clone(),
reference_name: annot_name,
reference_kind: EdgeKind::Annotates,
line: start_line,
column: start_column,
file_path: state.file_path.clone(),
});
state.edges.push(Edge {
source: id,
target: target_id.to_string(),
kind: EdgeKind::Annotates,
line: Some(start_line),
});
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_annotation_name(state: &ExtractionState, node: TsNode<'_>) -> String {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.is_named()
&& (child.kind() == "identifier" || child.kind() == "scoped_identifier")
{
return state.node_text(child);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
let text = state.node_text(node);
text.trim_start_matches('@').to_string()
}
fn extract_type_refs(state: &mut ExtractionState, node: TsNode<'_>, fn_node_id: &str) {
let java_builtins: &[&str] = &[
"void",
"int",
"long",
"short",
"byte",
"char",
"float",
"double",
"boolean",
"String",
"Object",
"Integer",
"Long",
"Short",
"Byte",
"Character",
"Float",
"Double",
"Boolean",
"Void",
];
let mut cursor = node.walk();
if !cursor.goto_first_child() {
return;
}
loop {
let child = cursor.node();
match child.kind() {
"formal_parameters" => {
Self::extract_type_refs(state, child, fn_node_id);
}
"formal_parameter" | "spread_parameter" => {
Self::collect_java_type_ids(state, child, fn_node_id, java_builtins);
}
"type_identifier" | "generic_type" => {
Self::collect_java_type_ids(state, child, fn_node_id, java_builtins);
}
_ => {}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
fn collect_java_type_ids(
state: &mut ExtractionState,
node: TsNode<'_>,
fn_node_id: &str,
builtins: &[&str],
) {
if node.kind() == "type_identifier" {
let type_name = state.node_text(node);
if !builtins.contains(&type_name.as_str()) {
state.unresolved_refs.push(UnresolvedRef {
from_node_id: fn_node_id.to_string(),
reference_name: type_name,
reference_kind: EdgeKind::Uses,
line: node.start_position().row as u32,
column: node.start_position().column as u32,
file_path: state.file_path.clone(),
});
}
return;
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
Self::collect_java_type_ids(state, cursor.node(), fn_node_id, builtins);
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_call_sites(state: &mut ExtractionState, node: TsNode<'_>, fn_node_id: &str) {
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
match child.kind() {
"method_invocation" => {
let callee_name = Self::extract_method_invocation_name(state, child);
state.unresolved_refs.push(UnresolvedRef {
from_node_id: fn_node_id.to_string(),
reference_name: callee_name,
reference_kind: EdgeKind::Calls,
line: child.start_position().row as u32,
column: child.start_position().column as u32,
file_path: state.file_path.clone(),
});
Self::extract_call_sites(state, child, fn_node_id);
}
"object_creation_expression" => {
let type_name = Self::extract_object_creation_type(state, child);
state.unresolved_refs.push(UnresolvedRef {
from_node_id: fn_node_id.to_string(),
reference_name: format!("new {type_name}"),
reference_kind: EdgeKind::Calls,
line: child.start_position().row as u32,
column: child.start_position().column as u32,
file_path: state.file_path.clone(),
});
Self::extract_call_sites(state, child, fn_node_id);
}
"method_declaration" | "constructor_declaration" | "class_declaration" => {}
_ => {
Self::extract_call_sites(state, child, fn_node_id);
}
}
if !cursor.goto_next_sibling() {
break;
}
}
}
}
fn extract_method_invocation_name(state: &ExtractionState, node: TsNode<'_>) -> String {
if let Some(name_node) = node.child_by_field_name("name") {
let name = state.node_text(name_node);
if let Some(obj_node) = node.child_by_field_name("object") {
let obj = state.node_text(obj_node);
return format!("{obj}.{name}");
}
return name;
}
let text = state.node_text(node);
text.split('(').next().unwrap_or(&text).trim().to_string()
}
fn extract_object_creation_type(state: &ExtractionState, node: TsNode<'_>) -> String {
if let Some(type_node) = node.child_by_field_name("type") {
return state.node_text(type_node);
}
let mut cursor = node.walk();
if cursor.goto_first_child() {
loop {
let child = cursor.node();
if child.is_named()
&& (child.kind() == "type_identifier"
|| child.kind() == "generic_type"
|| child.kind() == "scoped_type_identifier")
{
return state.node_text(child);
}
if !cursor.goto_next_sibling() {
break;
}
}
}
"<unknown>".to_string()
}
fn build_result(state: ExtractionState, start: Instant) -> ExtractionResult {
ExtractionResult {
nodes: state.nodes,
edges: state.edges,
unresolved_refs: state.unresolved_refs,
errors: state.errors,
duration_ms: start.elapsed().as_millis() as u64,
}
}
}
impl crate::extraction::LanguageExtractor for JavaExtractor {
fn extensions(&self) -> &[&str] {
&["java"]
}
fn language_name(&self) -> &str {
"Java"
}
fn extract(&self, file_path: &str, source: &str) -> ExtractionResult {
JavaExtractor::extract_java(file_path, source)
}
}