Skip to main content

rinne_graph/
extract.rs

1//! Tree-sitter parse + query execution → raw symbols and name-only edges.
2
3use streaming_iterator::StreamingIterator;
4use tree_sitter::{Parser, QueryCursor};
5
6use crate::lang::support_for;
7use crate::model::{EdgeKind, SymbolKind};
8
9pub struct RawSymbol {
10    pub name: String,
11    pub kind: SymbolKind,
12    pub start_line: u32,
13    pub end_line: u32,
14    pub signature: Option<String>,
15}
16
17pub struct RawEdge {
18    pub src_name: Option<String>,
19    pub dst_name: String,
20    pub kind: EdgeKind,
21}
22
23pub fn extract(lang: &str, source: &str) -> Option<(Vec<RawSymbol>, Vec<RawEdge>)> {
24    let support = support_for(lang)?;
25    let mut parser = Parser::new();
26    parser.set_language(&support.language()).ok()?;
27    let tree = parser.parse(source, None)?;
28    let query = support.query();
29    let mut symbols = Vec::new();
30    let mut edges = Vec::new();
31    walk(query, &tree, source.as_bytes(), &mut symbols, &mut edges);
32    Some((symbols, edges))
33}
34
35fn kind_from_suffix(suffix: &str) -> Option<SymbolKind> {
36    match suffix {
37        "function" => Some(SymbolKind::Function),
38        "method" => Some(SymbolKind::Method),
39        "class" => Some(SymbolKind::Class),
40        "struct" => Some(SymbolKind::Struct),
41        "enum" => Some(SymbolKind::Enum),
42        "trait" => Some(SymbolKind::Trait),
43        "interface" => Some(SymbolKind::Interface),
44        "module" => Some(SymbolKind::Module),
45        _ => None,
46    }
47}
48
49fn enclosing_symbol_name<'a>(
50    mut node: tree_sitter::Node<'a>,
51    query: &tree_sitter::Query,
52    source: &[u8],
53) -> Option<String> {
54    // Walk up to the nearest node that a def.function or def.method capture matches.
55    // We detect this by checking if any capture on the query named def.function/def.method
56    // targets this node type. Instead of re-running the query, we walk parents and check
57    // node kinds that represent function/method definitions.
58    let def_kinds = [
59        "function_item",        // rust
60        "function_definition",  // python
61        "function_declaration", // ts/js
62        "method_definition",    // ts/js
63        "arrow_function",       // ts/js (anonymous, no name — skip)
64    ];
65
66    // Get the capture names from the query so we can check if def.function / def.method exist
67    let cap_names: Vec<&str> = query.capture_names().iter().map(|s| s.as_ref()).collect();
68    let has_def_function = cap_names.contains(&"def.function");
69    let has_def_method = cap_names.contains(&"def.method");
70
71    if !has_def_function && !has_def_method {
72        return None;
73    }
74
75    while let Some(parent) = node.parent() {
76        let kind = parent.kind();
77        if def_kinds.contains(&kind) {
78            // Try to get child named "name"
79            if let Some(name_node) = parent.child_by_field_name("name") {
80                let name = name_node.utf8_text(source).ok()?.to_string();
81                return Some(name);
82            }
83        }
84        node = parent;
85    }
86    None
87}
88
89fn walk(
90    query: &tree_sitter::Query,
91    tree: &tree_sitter::Tree,
92    source: &[u8],
93    symbols: &mut Vec<RawSymbol>,
94    edges: &mut Vec<RawEdge>,
95) {
96    let mut cursor = QueryCursor::new();
97    let mut matches = cursor.matches(query, tree.root_node(), source);
98
99    while let Some(m) = matches.next() {
100        for cap in m.captures {
101            let cap_name = &query.capture_names()[cap.index as usize];
102            let node = cap.node;
103
104            if let Some(suffix) = cap_name.strip_prefix("def.") {
105                let Some(kind) = kind_from_suffix(suffix) else {
106                    continue;
107                };
108                // The capture is on the name node; get the parent for line span.
109                let def_node = node.parent().unwrap_or(node);
110                let name = node.utf8_text(source).unwrap_or("").to_string();
111                if name.is_empty() {
112                    continue;
113                }
114                // Signature: first line of the definition node
115                let start_byte = def_node.start_byte();
116                let end_byte = def_node.end_byte();
117                let def_text = std::str::from_utf8(&source[start_byte..end_byte]).unwrap_or("");
118                let signature = def_text.lines().next().map(|l| l.trim().to_string());
119
120                let start_line = def_node.start_position().row as u32 + 1;
121                let end_line = def_node.end_position().row as u32 + 1;
122
123                // A definition can match more than one query pattern (e.g. a Rust
124                // method inside an `impl` matches both `function_item` and the
125                // `impl_item`-method pattern). Dedup by span, keeping the more
126                // specific kind (Method over Function) so it is counted once.
127                if let Some(existing) = symbols
128                    .iter_mut()
129                    .find(|s: &&mut RawSymbol| s.name == name && s.start_line == start_line)
130                {
131                    if kind == SymbolKind::Method && existing.kind == SymbolKind::Function {
132                        existing.kind = SymbolKind::Method;
133                    }
134                    continue;
135                }
136
137                symbols.push(RawSymbol {
138                    name,
139                    kind,
140                    start_line,
141                    end_line,
142                    signature,
143                });
144            } else if cap_name.starts_with("call.") {
145                let dst_name = node.utf8_text(source).unwrap_or("").to_string();
146                if dst_name.is_empty() {
147                    continue;
148                }
149                let src_name = enclosing_symbol_name(node, query, source);
150                edges.push(RawEdge {
151                    src_name,
152                    dst_name,
153                    kind: EdgeKind::Calls,
154                });
155            } else if cap_name.starts_with("import.") {
156                let dst_name = node.utf8_text(source).unwrap_or("").to_string();
157                if dst_name.is_empty() {
158                    continue;
159                }
160                edges.push(RawEdge {
161                    src_name: None,
162                    dst_name,
163                    kind: EdgeKind::Imports,
164                });
165            }
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn extracts_rust_functions_and_calls() {
176        let src = "fn helper() {}\nfn main() { helper(); }\n";
177        let (symbols, edges) = extract("rust", src).expect("rust supported");
178        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
179        assert!(names.contains(&"helper"));
180        assert!(names.contains(&"main"));
181        assert!(edges.iter().any(|e| e.dst_name == "helper" && e.src_name.as_deref() == Some("main")));
182    }
183
184    #[test]
185    fn impl_methods_are_not_duplicated() {
186        // A method inside an impl block matches both the `function_item` and the
187        // `impl_item`-method query patterns; it must be extracted exactly once,
188        // and as a Method (the more specific kind), not a plain Function.
189        let src = "struct S;\nimpl S {\n    fn method(&self) {}\n}\n";
190        let (symbols, _edges) = extract("rust", src).unwrap();
191        let methods: Vec<_> = symbols.iter().filter(|s| s.name == "method").collect();
192        assert_eq!(methods.len(), 1, "impl method must not be double-counted");
193        assert_eq!(methods[0].kind, SymbolKind::Method);
194    }
195
196    #[test]
197    fn extracts_python_defs() {
198        let src = "def a():\n    b()\ndef b():\n    pass\n";
199        let (symbols, edges) = extract("python", src).unwrap();
200        assert!(symbols.iter().any(|s| s.name == "a"));
201        assert!(edges.iter().any(|e| e.dst_name == "b" && e.src_name.as_deref() == Some("a")));
202    }
203
204    #[test]
205    fn extracts_typescript_functions() {
206        let src = "function f() { g(); }\nfunction g() {}\n";
207        let (symbols, edges) = extract("typescript", src).unwrap();
208        assert!(symbols.iter().any(|s| s.name == "f"));
209        assert!(edges.iter().any(|e| e.dst_name == "g" && e.src_name.as_deref() == Some("f")));
210    }
211}