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    /// Enclosing type/class/trait name for a method (e.g. `ContextAssembler` for
16    /// `ContextAssembler::build`); `None` for free functions.
17    pub container: Option<String>,
18}
19
20pub struct RawEdge {
21    pub src_name: Option<String>,
22    pub dst_name: String,
23    pub kind: EdgeKind,
24    /// Enclosing container of the call site (e.g. the `impl`/module the call is
25    /// inside), used to disambiguate a call to a name defined more than once in
26    /// the same file. `None` when the call is at file scope.
27    pub src_container: Option<String>,
28}
29
30pub fn extract(lang: &str, source: &str) -> Option<(Vec<RawSymbol>, Vec<RawEdge>)> {
31    let support = support_for(lang)?;
32    let mut parser = Parser::new();
33    parser.set_language(&support.language()).ok()?;
34    let tree = parser.parse(source, None)?;
35    let query = support.query();
36    let mut symbols = Vec::new();
37    let mut edges = Vec::new();
38    walk(query, &tree, source.as_bytes(), &mut symbols, &mut edges);
39    Some((symbols, edges))
40}
41
42fn kind_from_suffix(suffix: &str) -> Option<SymbolKind> {
43    match suffix {
44        "function" => Some(SymbolKind::Function),
45        "method" => Some(SymbolKind::Method),
46        "class" => Some(SymbolKind::Class),
47        "struct" => Some(SymbolKind::Struct),
48        "enum" => Some(SymbolKind::Enum),
49        "trait" => Some(SymbolKind::Trait),
50        "interface" => Some(SymbolKind::Interface),
51        "module" => Some(SymbolKind::Module),
52        _ => None,
53    }
54}
55
56fn enclosing_symbol_name<'a>(
57    mut node: tree_sitter::Node<'a>,
58    query: &tree_sitter::Query,
59    source: &[u8],
60) -> Option<String> {
61    // Walk up to the nearest node that a def.function or def.method capture matches.
62    // We detect this by checking if any capture on the query named def.function/def.method
63    // targets this node type. Instead of re-running the query, we walk parents and check
64    // node kinds that represent function/method definitions.
65    let def_kinds = [
66        "function_item",        // rust
67        "function_definition",  // python
68        "function_declaration", // ts/js
69        "method_definition",    // ts/js
70        "arrow_function",       // ts/js (anonymous, no name — skip)
71    ];
72
73    // Get the capture names from the query so we can check if def.function / def.method exist
74    let cap_names: Vec<&str> = query.capture_names().iter().map(|s| s.as_ref()).collect();
75    let has_def_function = cap_names.contains(&"def.function");
76    let has_def_method = cap_names.contains(&"def.method");
77
78    if !has_def_function && !has_def_method {
79        return None;
80    }
81
82    while let Some(parent) = node.parent() {
83        let kind = parent.kind();
84        if def_kinds.contains(&kind) {
85            // Try to get child named "name"
86            if let Some(name_node) = parent.child_by_field_name("name") {
87                let name = name_node.utf8_text(source).ok()?.to_string();
88                return Some(name);
89            }
90        }
91        node = parent;
92    }
93    None
94}
95
96/// Walk up from a node to its nearest enclosing container (type/class/trait/
97/// module) and return that container's name, or `None` at file scope.
98///
99/// Used two ways: for a *definition's* name node it gives the method's owning
100/// type; for a *call site* it gives the scope the call lives in. Matching the two
101/// disambiguates a name defined more than once in the same file. Covers Rust
102/// `impl Type`/`impl Trait for Type` (the `type` field) and `mod name`, plus
103/// class-like containers in ts/js/python (the `name` field).
104fn container_of(name_node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
105    let mut node = name_node;
106    while let Some(parent) = node.parent() {
107        match parent.kind() {
108            // Rust: `impl ContextAssembler { ... }` / `impl Trait for T { ... }`.
109            // The `type` field is the type receiving the methods.
110            "impl_item" => {
111                if let Some(ty) = parent.child_by_field_name("type") {
112                    return ty.utf8_text(source).ok().map(str::to_string);
113                }
114            }
115            // Rust module: `mod second { ... }`.
116            "mod_item" => {
117                if let Some(n) = parent.child_by_field_name("name") {
118                    return n.utf8_text(source).ok().map(str::to_string);
119                }
120            }
121            // ts/js/python class-like containers name themselves via `name`.
122            "class_declaration" | "class_definition" | "class" | "interface_declaration" => {
123                if let Some(n) = parent.child_by_field_name("name") {
124                    return n.utf8_text(source).ok().map(str::to_string);
125                }
126            }
127            _ => {}
128        }
129        node = parent;
130    }
131    None
132}
133
134fn walk(
135    query: &tree_sitter::Query,
136    tree: &tree_sitter::Tree,
137    source: &[u8],
138    symbols: &mut Vec<RawSymbol>,
139    edges: &mut Vec<RawEdge>,
140) {
141    let mut cursor = QueryCursor::new();
142    let mut matches = cursor.matches(query, tree.root_node(), source);
143
144    while let Some(m) = matches.next() {
145        for cap in m.captures {
146            let cap_name = &query.capture_names()[cap.index as usize];
147            let node = cap.node;
148
149            if let Some(suffix) = cap_name.strip_prefix("def.") {
150                let Some(kind) = kind_from_suffix(suffix) else {
151                    continue;
152                };
153                // The capture is on the name node; get the parent for line span.
154                let def_node = node.parent().unwrap_or(node);
155                let name = node.utf8_text(source).unwrap_or("").to_string();
156                if name.is_empty() {
157                    continue;
158                }
159                // Signature: first line of the definition node
160                let start_byte = def_node.start_byte();
161                let end_byte = def_node.end_byte();
162                let def_text = std::str::from_utf8(&source[start_byte..end_byte]).unwrap_or("");
163                let signature = def_text.lines().next().map(|l| l.trim().to_string());
164
165                let start_line = def_node.start_position().row as u32 + 1;
166                let end_line = def_node.end_position().row as u32 + 1;
167
168                // A definition can match more than one query pattern (e.g. a Rust
169                // method inside an `impl` matches both `function_item` and the
170                // `impl_item`-method pattern). Dedup by span, keeping the more
171                // specific kind (Method over Function) so it is counted once.
172                if let Some(existing) = symbols
173                    .iter_mut()
174                    .find(|s: &&mut RawSymbol| s.name == name && s.start_line == start_line)
175                {
176                    if kind == SymbolKind::Method && existing.kind == SymbolKind::Function {
177                        existing.kind = SymbolKind::Method;
178                        // Backfill the container now that we know it's a method:
179                        // the earlier `function_item` capture set it to None.
180                        existing.container = container_of(node, source);
181                    }
182                    continue;
183                }
184
185                // Every definition carries its nearest enclosing container: a
186                // method gets its `impl` type, a function inside a module gets the
187                // module, a file-scope function gets `None`. This qualified identity
188                // lets same-name defs in one file be told apart, and matches the
189                // container recorded on call-site edges for scope-aware resolution.
190                let container = container_of(node, source);
191
192                symbols.push(RawSymbol {
193                    name,
194                    kind,
195                    start_line,
196                    end_line,
197                    signature,
198                    container,
199                });
200            } else if cap_name.starts_with("call.") {
201                let dst_name = node.utf8_text(source).unwrap_or("").to_string();
202                if dst_name.is_empty() {
203                    continue;
204                }
205                let src_name = enclosing_symbol_name(node, query, source);
206                let src_container = container_of(node, source);
207                edges.push(RawEdge {
208                    src_name,
209                    dst_name,
210                    kind: EdgeKind::Calls,
211                    src_container,
212                });
213            } else if cap_name.starts_with("import.") {
214                let dst_name = node.utf8_text(source).unwrap_or("").to_string();
215                if dst_name.is_empty() {
216                    continue;
217                }
218                edges.push(RawEdge {
219                    src_name: None,
220                    dst_name,
221                    kind: EdgeKind::Imports,
222                    src_container: None,
223                });
224            }
225        }
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn extracts_rust_functions_and_calls() {
235        let src = "fn helper() {}\nfn main() { helper(); }\n";
236        let (symbols, edges) = extract("rust", src).expect("rust supported");
237        let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
238        assert!(names.contains(&"helper"));
239        assert!(names.contains(&"main"));
240        assert!(edges
241            .iter()
242            .any(|e| e.dst_name == "helper" && e.src_name.as_deref() == Some("main")));
243    }
244
245    #[test]
246    fn impl_methods_are_not_duplicated() {
247        // A method inside an impl block matches both the `function_item` and the
248        // `impl_item`-method query patterns; it must be extracted exactly once,
249        // and as a Method (the more specific kind), not a plain Function.
250        let src = "struct S;\nimpl S {\n    fn method(&self) {}\n}\n";
251        let (symbols, _edges) = extract("rust", src).unwrap();
252        let methods: Vec<_> = symbols.iter().filter(|s| s.name == "method").collect();
253        assert_eq!(methods.len(), 1, "impl method must not be double-counted");
254        assert_eq!(methods[0].kind, SymbolKind::Method);
255    }
256
257    #[test]
258    fn extracts_python_defs() {
259        let src = "def a():\n    b()\ndef b():\n    pass\n";
260        let (symbols, edges) = extract("python", src).unwrap();
261        assert!(symbols.iter().any(|s| s.name == "a"));
262        assert!(edges
263            .iter()
264            .any(|e| e.dst_name == "b" && e.src_name.as_deref() == Some("a")));
265    }
266
267    #[test]
268    fn extracts_typescript_functions() {
269        let src = "function f() { g(); }\nfunction g() {}\n";
270        let (symbols, edges) = extract("typescript", src).unwrap();
271        assert!(symbols.iter().any(|s| s.name == "f"));
272        assert!(edges
273            .iter()
274            .any(|e| e.dst_name == "g" && e.src_name.as_deref() == Some("f")));
275    }
276}