Skip to main content

diffler_core/syntax/
scope.rs

1//! "What are we inside of": the chain of enclosing definitions (function,
2//! class, method, …) for a line, derived from a grammar's tags query. The
3//! result is plain data so the diff worker can compute it once and share it.
4
5use tree_sitter::{QueryCursor, StreamingIterator};
6
7use crate::syntax::registry::LanguageRegistry;
8use crate::syntax::{MAX_PARSE_BYTES, parse};
9
10/// Definition spans for a file, queried per line for the enclosing-definition
11/// breadcrumb.
12#[derive(Debug, Clone, Default)]
13pub struct ScopeIndex {
14    defs: Vec<Def>,
15}
16
17#[derive(Debug, Clone)]
18struct Def {
19    start_row: usize,
20    end_row: usize,
21    name: String,
22}
23
24impl ScopeIndex {
25    pub fn is_empty(&self) -> bool {
26        self.defs.is_empty()
27    }
28
29    /// Names of the definitions enclosing `line` (0-based), outermost first. A
30    /// line inside `class A` → `method` → body returns `["A", "method"]`.
31    pub fn crumbs(&self, line: usize) -> Vec<String> {
32        let mut hits: Vec<&Def> = self
33            .defs
34            .iter()
35            .filter(|d| d.start_row <= line && line <= d.end_row)
36            .collect();
37        hits.sort_by(|a, b| {
38            a.start_row
39                .cmp(&b.start_row)
40                .then(b.end_row.cmp(&a.end_row))
41        });
42        hits.into_iter().map(|d| d.name.clone()).collect()
43    }
44}
45
46impl LanguageRegistry {
47    /// Parse `content` and index its definition spans for scope lookup. Returns
48    /// an empty index when the language is unsupported, has no tags query, the
49    /// file is too large, or parsing fails — callers then show no breadcrumb.
50    pub fn scope_index(&self, path: &str, content: &str) -> ScopeIndex {
51        if content.len() > MAX_PARSE_BYTES {
52            return ScopeIndex::default();
53        }
54        let Some(entry) = self.for_path(path) else {
55            return ScopeIndex::default();
56        };
57        let Some(query) = entry.tags.as_ref() else {
58            return ScopeIndex::default();
59        };
60        let Some(tree) = parse(entry, content) else {
61            return ScopeIndex::default();
62        };
63
64        let names = query.capture_names();
65        let bytes = content.as_bytes();
66        let mut cursor = QueryCursor::new();
67        let mut matches = cursor.matches(query, tree.root_node(), bytes);
68        let mut defs = Vec::new();
69        while let Some(m) = matches.next() {
70            let mut span: Option<(usize, usize)> = None;
71            let mut name: Option<String> = None;
72            for cap in m.captures {
73                let cname = names.get(cap.index as usize).copied().unwrap_or("");
74                if cname.starts_with("definition.") {
75                    span = Some((cap.node.start_position().row, cap.node.end_position().row));
76                } else if cname == "name" {
77                    name = cap.node.utf8_text(bytes).ok().map(str::to_owned);
78                }
79            }
80            if let (Some((start_row, end_row)), Some(name)) = (span, name) {
81                defs.push(Def {
82                    start_row,
83                    end_row,
84                    name,
85                });
86            }
87        }
88        ScopeIndex { defs }
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95
96    #[test]
97    fn nested_python_scope_reads_class_then_method() {
98        let reg = LanguageRegistry::build();
99        let src = "class A:\n    def method(self):\n        x = 1\n        return x\n";
100        let crumbs = reg.scope_index("a.py", src).crumbs(2);
101        let names: Vec<&str> = crumbs.iter().map(String::as_str).collect();
102        assert_eq!(names, ["A", "method"]);
103    }
104
105    #[test]
106    fn rust_function_scope() {
107        let reg = LanguageRegistry::build();
108        let src = "fn outer() {\n    let y = 2;\n}\n";
109        let crumbs = reg.scope_index("a.rs", src).crumbs(1);
110        let names: Vec<&str> = crumbs.iter().map(String::as_str).collect();
111        assert_eq!(names, ["outer"]);
112    }
113
114    #[test]
115    fn scope_index_empty_for_unsupported_language() {
116        let reg = LanguageRegistry::build();
117        assert!(reg.scope_index("a.zzz-unknown", "whatever\n").is_empty());
118    }
119
120    #[test]
121    fn line_outside_any_definition_has_no_crumbs() {
122        let reg = LanguageRegistry::build();
123        let src = "import os\n\ndef f():\n    pass\n";
124        assert!(reg.scope_index("a.py", src).crumbs(0).is_empty());
125    }
126}