Skip to main content

arbor_core/
parser.rs

1//! Parser module - the heart of code analysis.
2//!
3//! This module wraps Tree-sitter and provides a clean API for parsing
4//! source files into CodeNodes. Language detection is automatic based
5//! on file extension.
6
7use crate::error::{ParseError, Result};
8use crate::fallback_parser;
9use crate::languages::{get_parser, LanguageParser};
10use crate::node::CodeNode;
11use crate::usages::FileUsages;
12use std::fs;
13use std::path::Path;
14
15/// Parses a source file and extracts all code nodes.
16///
17/// This is the main entry point for parsing. It handles:
18/// - Reading the file from disk
19/// - Detecting the language from the extension
20/// - Parsing with Tree-sitter
21/// - Extracting meaningful code entities
22///
23/// # Example
24///
25/// ```no_run
26/// use arbor_core::parse_file;
27/// use std::path::Path;
28///
29/// let nodes = parse_file(Path::new("src/lib.rs")).unwrap();
30/// println!("Found {} nodes", nodes.len());
31/// ```
32pub fn parse_file(path: &Path) -> Result<Vec<CodeNode>> {
33    // Read the source file
34    let source = fs::read_to_string(path).map_err(|e| ParseError::io(path, e))?;
35
36    if source.is_empty() {
37        // Empty __init__.py files are valid Python module indicators
38        if path
39            .file_name()
40            .map(|n| n == "__init__.py")
41            .unwrap_or(false)
42        {
43            return Ok(vec![]); // Return empty nodes, not an error
44        }
45        return Err(ParseError::EmptyFile(path.to_path_buf()));
46    }
47
48    let extension = path
49        .extension()
50        .and_then(|e| e.to_str())
51        .unwrap_or_default();
52
53    // Get the appropriate parser for this file type (tree-sitter path first)
54    let parser = detect_language(path);
55
56    if parser.is_none() {
57        if fallback_parser::is_fallback_supported_extension(extension) {
58            let file_path = path.to_string_lossy().to_string();
59            return Ok(fallback_parser::parse_fallback_source(
60                &source, &file_path, extension,
61            ));
62        }
63        return Err(ParseError::UnsupportedLanguage(path.to_path_buf()));
64    }
65
66    let parser = parser.unwrap();
67
68    // Use the file path as a string for node IDs
69    let file_path = path.to_string_lossy().to_string();
70
71    parse_source(&source, &file_path, parser.as_ref())
72}
73
74/// Parses source code directly (useful for testing or in-memory content).
75///
76/// You need to provide a language parser explicitly since there's no
77/// file extension to detect from.
78pub fn parse_source(
79    source: &str,
80    file_path: &str,
81    lang_parser: &dyn LanguageParser,
82) -> Result<Vec<CodeNode>> {
83    let tree = parse_tree(source, lang_parser)?;
84
85    // Extract nodes using the language-specific extractor
86    let nodes = lang_parser.extract_nodes(&tree, source, file_path);
87
88    Ok(nodes)
89}
90
91/// Builds the tree-sitter tree every extractor in this module reads.
92fn parse_tree(source: &str, lang_parser: &dyn LanguageParser) -> Result<tree_sitter::Tree> {
93    let mut parser = tree_sitter::Parser::new();
94    parser
95        .set_language(&lang_parser.language())
96        .map_err(|e| ParseError::ParserError(format!("Failed to set language: {}", e)))?;
97    parser
98        .parse(source, None)
99        .ok_or_else(|| ParseError::ParserError("Tree-sitter returned no tree".into()))
100}
101
102/// Parses source once and returns both the graph nodes and the SDK usages
103/// (see [`crate::usages`]). The nodes are exactly what [`parse_source`]
104/// returns; usages are `None` when the language has no usage extractor.
105pub fn parse_source_with_usages(
106    source: &str,
107    file_path: &str,
108    lang_parser: &dyn LanguageParser,
109) -> Result<(Vec<CodeNode>, Option<FileUsages>)> {
110    let tree = parse_tree(source, lang_parser)?;
111    let nodes = lang_parser.extract_nodes(&tree, source, file_path);
112    let usages = lang_parser.extract_usages(&tree, source, file_path);
113    Ok((nodes, usages))
114}
115
116/// SDK usages for in-memory source. `Ok(None)` when the language has no
117/// usage extractor (today: every language except Python). A file that
118/// mentions no tracked SDK is not parsed at all.
119pub fn parse_source_usages(
120    source: &str,
121    file_path: &str,
122    lang_parser: &dyn LanguageParser,
123) -> Result<Option<FileUsages>> {
124    let Some(language) = lang_parser.usages_language() else {
125        return Ok(None);
126    };
127    if !lang_parser.may_have_usages(source) {
128        return Ok(Some(FileUsages::new(file_path, language)));
129    }
130    let tree = parse_tree(source, lang_parser)?;
131    Ok(lang_parser.extract_usages(&tree, source, file_path))
132}
133
134/// SDK usages for a file on disk, with the path as written used in records.
135/// `Ok(None)` when the file has no usage extractor: its extension is not in
136/// [`crate::usages::is_usage_extension`] and, for a file without one, its
137/// first line is not a Python shebang. Other files are not read past that.
138pub fn parse_file_usages(path: &Path) -> Result<Option<FileUsages>> {
139    let extension = path
140        .extension()
141        .and_then(|e| e.to_str())
142        .unwrap_or_default();
143    let parser = if extension.is_empty() {
144        let mut head = [0u8; 256];
145        let read = fs::File::open(path)
146            .and_then(|mut file| std::io::Read::read(&mut file, &mut head))
147            .map_err(|e| ParseError::io(path, e))?;
148        if !crate::usages::is_python_shebang(&head[..read]) {
149            return Ok(None);
150        }
151        get_parser("py")
152    } else if crate::usages::is_usage_extension(extension) {
153        detect_language(path)
154    } else {
155        None
156    };
157    let Some(parser) = parser else {
158        return Ok(None);
159    };
160    let source = fs::read_to_string(path).map_err(|e| ParseError::io(path, e))?;
161    parse_source_usages(&source, &path.to_string_lossy(), parser.as_ref())
162}
163
164/// Detects the programming language from a file path.
165///
166/// Returns None if we don't support the file's extension.
167pub fn detect_language(path: &Path) -> Option<Box<dyn LanguageParser>> {
168    let extension = path.extension()?.to_str()?;
169    get_parser(extension)
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175    use crate::node::NodeKind;
176
177    #[test]
178    fn test_detect_language() {
179        assert!(detect_language(Path::new("foo.rs")).is_some());
180        assert!(detect_language(Path::new("bar.ts")).is_some());
181        assert!(detect_language(Path::new("baz.py")).is_some());
182        assert!(detect_language(Path::new("unknown.xyz")).is_none());
183    }
184
185    #[test]
186    fn test_parse_fallback_language_source() {
187        let source = r#"
188            fun calculateTax(price: Double): Double = price * 0.18
189            class TaxService
190        "#;
191
192        let dir = tempfile::tempdir().unwrap();
193        let path = dir.path().join("billing.kt");
194        std::fs::write(&path, source).unwrap();
195
196        let nodes = parse_file(&path).unwrap();
197        assert!(nodes.iter().any(|n| n.name == "calculateTax"));
198        assert!(nodes.iter().any(|n| n.name == "TaxService"));
199    }
200
201    #[test]
202    fn test_parse_rust_source() {
203        let source = r#"
204            fn hello_world() {
205                println!("Hello!");
206            }
207
208            pub struct User {
209                name: String,
210            }
211        "#;
212
213        let parser = get_parser("rs").unwrap();
214        let nodes = parse_source(source, "test.rs", parser.as_ref()).unwrap();
215
216        // Should find at least the function and struct
217        assert!(nodes
218            .iter()
219            .any(|n| n.name == "hello_world" && n.kind == NodeKind::Function));
220        assert!(nodes
221            .iter()
222            .any(|n| n.name == "User" && n.kind == NodeKind::Struct));
223    }
224
225    #[test]
226    fn usages_share_the_parse_and_leave_graph_nodes_unchanged() {
227        let source = "from openai import OpenAI\nclient = OpenAI()\n\ndef ask():\n    return client.chat.completions.create(model=\"gpt-4\", messages=[])\n";
228        let parser = get_parser("py").unwrap();
229        let plain = parse_source(source, "ask.py", parser.as_ref()).unwrap();
230        let (nodes, usages) = parse_source_with_usages(source, "ask.py", parser.as_ref()).unwrap();
231        assert_eq!(
232            serde_json::to_value(&nodes).unwrap(),
233            serde_json::to_value(&plain).unwrap(),
234            "usage extraction must not change graph nodes"
235        );
236        let usages = usages.expect("python has a usage extractor");
237        let call = &usages.calls[0];
238        assert_eq!(call.symbol.as_deref(), Some("ask"));
239        // The enclosing symbol is the graph's own name for that function.
240        assert!(nodes.iter().any(|n| n.qualified_name == "ask"));
241
242        let ts = get_parser("ts").unwrap();
243        assert!(parse_source_usages("const x = 1;", "x.ts", ts.as_ref())
244            .unwrap()
245            .is_none());
246    }
247
248    #[test]
249    fn parse_file_usages_reads_python_sources_only() {
250        let dir = tempfile::tempdir().unwrap();
251        let py = dir.path().join("llm.py");
252        std::fs::write(&py, "import anthropic\nanthropic.Anthropic().messages.create(model=\"claude-2.1\", max_tokens=1, messages=[])\n").unwrap();
253        let found = parse_file_usages(&py).unwrap().unwrap();
254        assert_eq!(found.calls.len(), 1);
255        assert_eq!(found.file, py.to_string_lossy());
256
257        let stub = dir.path().join("llm.pyi");
258        std::fs::write(&stub, "import anthropic\n").unwrap();
259        assert!(parse_file_usages(&stub).unwrap().is_none());
260        // Not read at all: the file does not exist.
261        assert!(parse_file_usages(&dir.path().join("main.rs"))
262            .unwrap()
263            .is_none());
264        let empty = dir.path().join("__init__.py");
265        std::fs::write(&empty, "").unwrap();
266        assert!(parse_file_usages(&empty).unwrap().unwrap().is_empty());
267
268        // An extensionless script counts when its shebang names Python.
269        let script = dir.path().join("summarize");
270        std::fs::write(&script, "#!/usr/bin/env python3\nimport anthropic\nanthropic.Anthropic().messages.create(model=\"claude-2.1\", max_tokens=1, messages=[])\n").unwrap();
271        assert_eq!(parse_file_usages(&script).unwrap().unwrap().calls.len(), 1);
272        let shell = dir.path().join("deploy");
273        std::fs::write(&shell, "#!/bin/sh\necho openai\n").unwrap();
274        assert!(parse_file_usages(&shell).unwrap().is_none());
275    }
276
277    #[test]
278    fn files_that_mention_no_sdk_are_not_parsed() {
279        let parser = get_parser("py").unwrap();
280        // Not even valid Python: the prefilter answers before the parser.
281        let found = parse_source_usages("def (:\n", "x.py", parser.as_ref())
282            .unwrap()
283            .unwrap();
284        assert!(found.is_empty());
285        assert!(!found.syntax_errors);
286        assert_eq!(found.language, "python");
287    }
288
289    #[test]
290    fn test_parse_typescript_source() {
291        let source = r#"
292            export function greet(name: string): string {
293                return `Hello, ${name}!`;
294            }
295
296            export class UserService {
297                validate() {}
298            }
299        "#;
300
301        let parser = get_parser("ts").unwrap();
302        let nodes = parse_source(source, "test.ts", parser.as_ref()).unwrap();
303
304        assert!(nodes
305            .iter()
306            .any(|n| n.name == "greet" && n.kind == NodeKind::Function));
307        assert!(nodes
308            .iter()
309            .any(|n| n.name == "UserService" && n.kind == NodeKind::Class));
310    }
311}