|
2 | 2 |
|
3 | 3 | use crate::ast::{ASTNode, NodeType, NodeMetadata}; |
4 | 4 | use crate::language::Language; |
| 5 | +use crate::language_config::{LanguageConfig, LANGUAGE_CONFIGS}; |
5 | 6 | use crate::parser::{ParseError, ParseResult, Parser}; |
6 | 7 | use std::collections::HashMap; |
| 8 | +use once_cell::sync::Lazy; |
7 | 9 |
|
8 | 10 | /// Tree-sitter based parser implementation |
9 | 11 | pub struct TreeSitterParser { |
10 | 12 | parsers: HashMap<Language, tree_sitter::Parser>, |
11 | 13 | } |
12 | 14 |
|
| 15 | +/// Global language configurations |
| 16 | +static LANGUAGE_CONFIGS: Lazy<HashMap<Language, fn() -> tree_sitter::Language>> = Lazy::new(|| { |
| 17 | + let mut configs = HashMap::new(); |
| 18 | + configs.insert(Language::Java, || tree_sitter_java::language()); |
| 19 | + configs.insert(Language::Python, || tree_sitter_python::language()); |
| 20 | + configs.insert(Language::JavaScript, || tree_sitter_javascript::language()); |
| 21 | + configs.insert(Language::Cpp, || tree_sitter_cpp::language()); |
| 22 | + configs.insert(Language::C, || tree_sitter_c::language()); |
| 23 | + configs |
| 24 | +}); |
| 25 | + |
13 | 26 | impl TreeSitterParser { |
14 | 27 | pub fn new() -> Result<Self, ParseError> { |
15 | 28 | let mut parsers = HashMap::new(); |
16 | | - |
| 29 | + |
17 | 30 | // Initialize parsers for supported languages |
18 | | - // Note: This is a placeholder - actual tree-sitter integration would be more complex |
19 | | - |
| 31 | + for (&language, language_fn) in LANGUAGE_CONFIGS.iter() { |
| 32 | + let mut parser = tree_sitter::Parser::new(); |
| 33 | + parser.set_language(language_fn()) |
| 34 | + .map_err(|e| ParseError::TreeSitterError(format!("Failed to set language {:?}: {}", language, e)))?; |
| 35 | + parsers.insert(language, parser); |
| 36 | + } |
| 37 | + |
20 | 38 | Ok(Self { parsers }) |
21 | 39 | } |
| 40 | + |
| 41 | + /// Get available languages |
| 42 | + pub fn supported_languages() -> Vec<Language> { |
| 43 | + LANGUAGE_CONFIGS.keys().cloned().collect() |
| 44 | + } |
22 | 45 |
|
23 | 46 | fn convert_tree_sitter_node(&self, node: &tree_sitter::Node, source: &str) -> ASTNode { |
24 | | - let node_type = self.map_node_type(node.kind()); |
| 47 | + let node_kind = node.kind(); |
| 48 | + let node_type = self.map_node_type(node_kind); |
25 | 49 | let text = node.utf8_text(source.as_bytes()).unwrap_or(""); |
26 | | - |
| 50 | + |
| 51 | + let mut attributes = HashMap::new(); |
| 52 | + |
| 53 | + // Extract name/identifier information based on node type |
| 54 | + self.extract_node_attributes(node, source, &mut attributes); |
| 55 | + |
| 56 | + // Add basic node information |
| 57 | + attributes.insert("kind".to_string(), node_kind.to_string()); |
| 58 | + if !text.trim().is_empty() && text.len() < 100 { // Avoid storing very long text |
| 59 | + attributes.insert("text".to_string(), text.trim().to_string()); |
| 60 | + } |
| 61 | + |
27 | 62 | let metadata = NodeMetadata { |
28 | | - line: node.start_position().row, |
29 | | - column: node.start_position().column, |
| 63 | + line: node.start_position().row + 1, // Convert to 1-based line numbers |
| 64 | + column: node.start_position().column + 1, // Convert to 1-based column numbers |
30 | 65 | original_text: text.to_string(), |
31 | | - attributes: HashMap::new(), |
| 66 | + attributes, |
32 | 67 | }; |
33 | | - |
| 68 | + |
34 | 69 | let mut ast_node = ASTNode::new(node_type, metadata); |
35 | | - |
36 | | - // Convert children |
| 70 | + |
| 71 | + // Convert children, filtering out some noise nodes |
37 | 72 | for i in 0..node.child_count() { |
38 | 73 | if let Some(child) = node.child(i) { |
39 | | - ast_node.add_child(self.convert_tree_sitter_node(&child, source)); |
| 74 | + // Skip certain noise nodes like punctuation |
| 75 | + if !self.should_skip_node(child.kind()) { |
| 76 | + ast_node.add_child(self.convert_tree_sitter_node(&child, source)); |
| 77 | + } |
40 | 78 | } |
41 | 79 | } |
42 | | - |
| 80 | + |
43 | 81 | ast_node |
44 | 82 | } |
| 83 | + |
| 84 | + /// Check if a node should be skipped during AST conversion |
| 85 | + fn should_skip_node(&self, kind: &str) -> bool { |
| 86 | + matches!(kind, |
| 87 | + "(" | ")" | "{" | "}" | "[" | "]" | ";" | "," | "." | |
| 88 | + "whitespace" | "comment" // We handle comments separately |
| 89 | + ) |
| 90 | + } |
| 91 | + |
| 92 | + /// Collect parse errors from the tree |
| 93 | + fn collect_parse_errors(&self, node: &tree_sitter::Node, source: &str, errors: &mut Vec<String>) { |
| 94 | + if node.is_error() { |
| 95 | + let text = node.utf8_text(source.as_bytes()).unwrap_or("<error>"); |
| 96 | + errors.push(format!( |
| 97 | + "Parse error at line {}, column {}: {}", |
| 98 | + node.start_position().row + 1, |
| 99 | + node.start_position().column + 1, |
| 100 | + text |
| 101 | + )); |
| 102 | + } |
| 103 | + |
| 104 | + if node.is_missing() { |
| 105 | + errors.push(format!( |
| 106 | + "Missing node at line {}, column {}", |
| 107 | + node.start_position().row + 1, |
| 108 | + node.start_position().column + 1 |
| 109 | + )); |
| 110 | + } |
| 111 | + |
| 112 | + // Recursively check children |
| 113 | + for i in 0..node.child_count() { |
| 114 | + if let Some(child) = node.child(i) { |
| 115 | + self.collect_parse_errors(&child, source, errors); |
| 116 | + } |
| 117 | + } |
| 118 | + } |
45 | 119 |
|
46 | 120 | fn map_node_type(&self, kind: &str) -> NodeType { |
47 | | - match kind { |
48 | | - "program" | "source_file" => NodeType::Program, |
49 | | - "class_declaration" | "class_definition" => NodeType::Class, |
50 | | - "function_declaration" | "function_definition" | "method_declaration" => NodeType::Function, |
51 | | - "if_statement" => NodeType::IfStatement, |
52 | | - "while_statement" => NodeType::WhileLoop, |
53 | | - "for_statement" => NodeType::ForLoop, |
54 | | - "block" | "compound_statement" => NodeType::Block, |
55 | | - "binary_expression" => NodeType::BinaryExpression, |
56 | | - "unary_expression" => NodeType::UnaryExpression, |
57 | | - "call_expression" => NodeType::CallExpression, |
58 | | - "identifier" => NodeType::Identifier, |
59 | | - "string_literal" | "number_literal" | "boolean_literal" => NodeType::Literal, |
60 | | - "comment" => NodeType::Comment, |
61 | | - _ => NodeType::Unknown, |
| 121 | + use crate::language_config::NODE_TYPE_MAPPINGS; |
| 122 | + NODE_TYPE_MAPPINGS.get(kind) |
| 123 | + .copied() |
| 124 | + .unwrap_or(NodeType::Unknown) |
| 125 | + } |
| 126 | + |
| 127 | + /// Extract attributes from a tree-sitter node |
| 128 | + fn extract_node_attributes(&self, node: &tree_sitter::Node, source: &str, attributes: &mut HashMap<String, String>) { |
| 129 | + let node_kind = node.kind(); |
| 130 | + |
| 131 | + // Try to extract name/identifier from common field names |
| 132 | + for field_name in &["name", "identifier", "declarator", "property"] { |
| 133 | + if let Some(name_node) = node.child_by_field_name(field_name) { |
| 134 | + if let Ok(name) = name_node.utf8_text(source.as_bytes()) { |
| 135 | + attributes.insert("name".to_string(), name.to_string()); |
| 136 | + break; |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + // Special handling for different node types |
| 142 | + match node_kind { |
| 143 | + "call_expression" => { |
| 144 | + // Extract function name from call expression |
| 145 | + if let Some(function_node) = node.child_by_field_name("function") { |
| 146 | + if let Ok(name) = function_node.utf8_text(source.as_bytes()) { |
| 147 | + attributes.insert("function_name".to_string(), name.to_string()); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // Extract arguments count |
| 152 | + let args_count = node.children(&mut node.walk()) |
| 153 | + .filter(|child| child.kind() == "arguments") |
| 154 | + .map(|args_node| args_node.child_count()) |
| 155 | + .next() |
| 156 | + .unwrap_or(0); |
| 157 | + attributes.insert("args_count".to_string(), args_count.to_string()); |
| 158 | + } |
| 159 | + |
| 160 | + "method_declaration" | "function_declaration" | "function_definition" => { |
| 161 | + // Extract parameter count |
| 162 | + if let Some(params_node) = node.child_by_field_name("parameters") { |
| 163 | + let param_count = params_node.child_count(); |
| 164 | + attributes.insert("param_count".to_string(), param_count.to_string()); |
| 165 | + } |
| 166 | + |
| 167 | + // Extract return type if available |
| 168 | + if let Some(type_node) = node.child_by_field_name("type") { |
| 169 | + if let Ok(return_type) = type_node.utf8_text(source.as_bytes()) { |
| 170 | + attributes.insert("return_type".to_string(), return_type.to_string()); |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + "variable_declaration" | "field_declaration" => { |
| 176 | + // Extract variable type |
| 177 | + if let Some(type_node) = node.child_by_field_name("type") { |
| 178 | + if let Ok(var_type) = type_node.utf8_text(source.as_bytes()) { |
| 179 | + attributes.insert("type".to_string(), var_type.to_string()); |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + "class_declaration" | "class_definition" => { |
| 185 | + // Extract superclass if available |
| 186 | + if let Some(superclass_node) = node.child_by_field_name("superclass") { |
| 187 | + if let Ok(superclass) = superclass_node.utf8_text(source.as_bytes()) { |
| 188 | + attributes.insert("superclass".to_string(), superclass.to_string()); |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + _ => {} |
62 | 194 | } |
63 | 195 | } |
64 | 196 | } |
65 | 197 |
|
66 | 198 | impl Parser for TreeSitterParser { |
67 | 199 | fn parse(&self, content: &str, language: Language) -> Result<ParseResult, ParseError> { |
68 | | - // Placeholder implementation |
69 | | - // In a real implementation, this would use the appropriate tree-sitter parser |
70 | | - Err(ParseError::UnsupportedLanguage(language)) |
| 200 | + let parser = self.parsers.get(&language) |
| 201 | + .ok_or_else(|| ParseError::UnsupportedLanguage(language.clone()))?; |
| 202 | + |
| 203 | + // Parse the content |
| 204 | + let tree = parser.parse(content, None) |
| 205 | + .ok_or_else(|| ParseError::ParseFailed("Failed to parse content".to_string()))?; |
| 206 | + |
| 207 | + let root_node = tree.root_node(); |
| 208 | + |
| 209 | + // Convert tree-sitter tree to our AST |
| 210 | + let ast = self.convert_tree_sitter_node(&root_node, content); |
| 211 | + |
| 212 | + // Collect any parse errors |
| 213 | + let mut errors = Vec::new(); |
| 214 | + let mut warnings = Vec::new(); |
| 215 | + |
| 216 | + if root_node.has_error() { |
| 217 | + self.collect_parse_errors(&root_node, content, &mut errors); |
| 218 | + } |
| 219 | + |
| 220 | + Ok(ParseResult { |
| 221 | + ast, |
| 222 | + language, |
| 223 | + errors, |
| 224 | + warnings, |
| 225 | + }) |
71 | 226 | } |
72 | | - |
| 227 | + |
73 | 228 | fn parse_file<P: AsRef<std::path::Path>>(&self, path: P) -> Result<ParseResult, ParseError> { |
74 | 229 | let content = std::fs::read_to_string(&path)?; |
75 | 230 | let language = crate::language::LanguageDetector::detect(&path, &content); |
76 | 231 | self.parse(&content, language) |
77 | 232 | } |
78 | | - |
| 233 | + |
79 | 234 | fn supported_languages(&self) -> Vec<Language> { |
80 | | - vec![ |
81 | | - Language::Java, |
82 | | - Language::Python, |
83 | | - Language::JavaScript, |
84 | | - Language::Cpp, |
85 | | - Language::CSharp, |
86 | | - ] |
| 235 | + Self::supported_languages() |
87 | 236 | } |
88 | 237 | } |
0 commit comments