codeprism_lang_java/
parser.rs

1//! Java parser implementation
2
3use crate::ast_mapper::AstMapper;
4use crate::error::{Error, Result};
5use crate::types::{Edge, Language, Node};
6use std::path::{Path, PathBuf};
7use tree_sitter::{Parser, Tree};
8
9/// Parse context for Java files
10#[derive(Debug, Clone)]
11pub struct ParseContext {
12    /// Repository ID
13    pub repo_id: String,
14    /// File path being parsed
15    pub file_path: PathBuf,
16    /// Previous tree for incremental parsing
17    pub old_tree: Option<Tree>,
18    /// File content
19    pub content: String,
20}
21
22/// Parse result containing nodes and edges
23#[derive(Debug)]
24pub struct ParseResult {
25    /// The parsed tree
26    pub tree: Tree,
27    /// Extracted nodes
28    pub nodes: Vec<Node>,
29    /// Extracted edges
30    pub edges: Vec<Edge>,
31}
32
33/// Java parser
34pub struct JavaParser {
35    /// Tree-sitter parser for Java
36    parser: Parser,
37}
38
39impl JavaParser {
40    /// Create a new Java parser
41    pub fn new() -> Self {
42        let mut parser = Parser::new();
43        parser
44            .set_language(&tree_sitter_java::LANGUAGE.into())
45            .expect("Failed to load Java grammar");
46
47        Self { parser }
48    }
49
50    /// Get the language for a file based on its extension
51    pub fn detect_language(path: &Path) -> Language {
52        // All Java files are Java language
53        match path.extension().and_then(|s| s.to_str()) {
54            Some("java") => Language::Java,
55            _ => Language::Java, // Default to Java
56        }
57    }
58
59    /// Parse a Java file
60    pub fn parse(&mut self, context: &ParseContext) -> Result<ParseResult> {
61        let language = Self::detect_language(&context.file_path);
62
63        // Parse the file
64        let tree = self
65            .parser
66            .parse(&context.content, context.old_tree.as_ref())
67            .ok_or_else(|| Error::parse(&context.file_path, "Failed to parse file"))?;
68
69        // Extract nodes and edges
70        let mapper = AstMapper::new(
71            &context.repo_id,
72            context.file_path.clone(),
73            language,
74            &context.content,
75        );
76
77        let (nodes, edges) = mapper.extract(&tree)?;
78
79        Ok(ParseResult { tree, nodes, edges })
80    }
81}
82
83impl Default for JavaParser {
84    fn default() -> Self {
85        Self::new()
86    }
87}