codeprism_lang_java/
parser.rs1use 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#[derive(Debug, Clone)]
11pub struct ParseContext {
12 pub repo_id: String,
14 pub file_path: PathBuf,
16 pub old_tree: Option<Tree>,
18 pub content: String,
20}
21
22#[derive(Debug)]
24pub struct ParseResult {
25 pub tree: Tree,
27 pub nodes: Vec<Node>,
29 pub edges: Vec<Edge>,
31}
32
33pub struct JavaParser {
35 parser: Parser,
37}
38
39impl JavaParser {
40 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 pub fn detect_language(path: &Path) -> Language {
52 match path.extension().and_then(|s| s.to_str()) {
54 Some("java") => Language::Java,
55 _ => Language::Java, }
57 }
58
59 pub fn parse(&mut self, context: &ParseContext) -> Result<ParseResult> {
61 let language = Self::detect_language(&context.file_path);
62
63 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 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}