BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / input / syntax_context.rs

syntax_context.rs

syntax_context.rs 9.9 KiB Download Raw
1use std::rc::Rc;
2
3#[cfg(feature = "tree-sitter")]
4use gpui_base::input::Rope;
5use gpui_base::input::SyntaxContextProvider;
6
7/// A syntax-context provider for `language`, or `None` when no grammar is
8/// compiled in (unknown language, plain text, or feature disabled).
9#[cfg(feature = "tree-sitter")]
10pub(crate) fn syntax_context_provider(language: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
11 use crate::highlighter::LanguageRegistry;
12
13 let grammar = LanguageRegistry::singleton().grammar(language).ok()?;
14 TreeSitterSyntaxContext::new(grammar)
15 .map(|provider| Rc::new(provider) as Rc<dyn SyntaxContextProvider>)
16}
17
18/// No tree-sitter support: no provider, engine falls back to heuristics.
19#[cfg(not(feature = "tree-sitter"))]
20pub(crate) fn syntax_context_provider(_language: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
21 None
22}
23
24/// Tree-sitter backed syntax context for editing decisions.
25///
26/// Caches the tree for unchanged text and classifies an offset by
27/// walking the named node and its ancestors for `string` / `comment` kinds.
28/// Generic across grammars: no per-language queries needed for this coarse
29/// classification.
30#[cfg(feature = "tree-sitter")]
31struct TreeSitterSyntaxContext {
32 parser: std::cell::RefCell<tree_sitter::Parser>,
33 /// The last queried text and its tree, or `None` when that text's parse
34 /// ran out of budget. Cloning a `Rope` shares its storage, so the cache
35 /// holds no second copy of the document.
36 tree: std::cell::RefCell<Option<(Rope, Option<tree_sitter::Tree>)>>,
37}
38
39#[cfg(feature = "tree-sitter")]
40impl TreeSitterSyntaxContext {
41 /// Synchronous parse budget per query; mirrors the highlighter's sync path.
42 const PARSE_BUDGET: std::time::Duration = std::time::Duration::from_millis(5);
43
44 fn new(language: tree_sitter::Language) -> Option<Self> {
45 let mut parser = tree_sitter::Parser::new();
46 parser.set_language(&language).ok()?;
47 Some(Self {
48 parser: std::cell::RefCell::new(parser),
49 tree: std::cell::RefCell::new(None),
50 })
51 }
52
53 /// Whether the comment starting at `start` opens with `#` or `//`.
54 fn starts_line_comment(text: &Rope, start: usize) -> bool {
55 match text.get_byte(start) {
56 Some(b'#') => true,
57 Some(b'/') => text.get_byte(start + 1) == Some(b'/'),
58 _ => false,
59 }
60 }
61
62 fn classify(kind: &str) -> Option<gpui_base::input::SyntaxContext> {
63 let lower = kind.to_lowercase();
64 if lower == "interpolation" || lower == "template_substitution" {
65 Some(gpui_base::input::SyntaxContext::Code)
66 } else if lower.contains("comment") {
67 Some(gpui_base::input::SyntaxContext::Comment)
68 } else if lower.contains("string") {
69 Some(gpui_base::input::SyntaxContext::String)
70 } else {
71 None
72 }
73 }
74}
75
76#[cfg(feature = "tree-sitter")]
77impl SyntaxContextProvider for TreeSitterSyntaxContext {
78 fn context_at(&self, text: &Rope, offset: usize) -> gpui_base::input::SyntaxContext {
79 use std::ops::ControlFlow;
80
81 let offset = offset.min(text.len());
82 let mut cached = self.tree.borrow_mut();
83 if cached
84 .as_ref()
85 .is_none_or(|(cached_text, _)| cached_text != text)
86 {
87 let start = std::time::Instant::now();
88 let mut progress = |_: &tree_sitter::ParseState| -> ControlFlow<()> {
89 if start.elapsed() > Self::PARSE_BUDGET {
90 ControlFlow::Break(())
91 } else {
92 ControlFlow::Continue(())
93 }
94 };
95 let options = tree_sitter::ParseOptions::new().progress_callback(&mut progress);
96 let mut parser = self.parser.borrow_mut();
97 // No InputEdit is available here, so an old tree cannot be reused
98 // after the source changes.
99 let tree = parser.parse_with_options(
100 &mut |byte_offset, _| crate::highlighter::parse_input_bytes(text, byte_offset),
101 None,
102 Some(options),
103 );
104 if tree.is_none() {
105 // A timed-out parse must not resume against a different source.
106 parser.reset();
107 }
108 // Remember a timed-out text too, so repeated queries on it answer
109 // `Code` at once instead of spending the budget again.
110 *cached = Some((text.clone(), tree));
111 }
112 let Some((_, Some(tree))) = cached.as_ref() else {
113 return gpui_base::input::SyntaxContext::Code;
114 };
115 let mut node = tree.root_node().descendant_for_byte_range(offset, offset);
116 // At the very end the range may match nothing; try the last byte.
117 if node.is_none() && offset > 0 {
118 node = tree
119 .root_node()
120 .descendant_for_byte_range(offset - 1, offset - 1);
121 }
122 let mut current = node;
123 while let Some(n) = current {
124 if n.is_named() {
125 if let Some(context) = Self::classify(n.kind()) {
126 // String delimiters delimit the scope: inserting at its start
127 // is outside, while inserting before its end is inside.
128 if context == gpui_base::input::SyntaxContext::String
129 && offset == n.start_byte()
130 && matches!(
131 n.kind(),
132 "string"
133 | "string_literal"
134 | "raw_string_literal"
135 | "template_string"
136 | "string_start"
137 )
138 {
139 return gpui_base::input::SyntaxContext::Code;
140 }
141 return context;
142 }
143 }
144 current = n.parent();
145 }
146 // A zero-width query at a line comment's end may select the enclosing
147 // node. Insertion there still extends the comment, unlike insertion
148 // after a block comment's closing delimiter.
149 if offset > 0 && !matches!(text.byte(offset - 1), b'\n' | b'\r') {
150 let mut previous = tree
151 .root_node()
152 .descendant_for_byte_range(offset - 1, offset);
153 while let Some(node) = previous {
154 if node.end_byte() == offset
155 && Self::classify(node.kind()) == Some(gpui_base::input::SyntaxContext::Comment)
156 {
157 if node.kind() == "line_comment"
158 || (node.kind() == "comment"
159 && Self::starts_line_comment(text, node.start_byte()))
160 {
161 return gpui_base::input::SyntaxContext::Comment;
162 }
163 }
164 previous = node.parent();
165 }
166 }
167 gpui_base::input::SyntaxContext::Code
168 }
169}
170
171#[cfg(all(test, feature = "tree-sitter"))]
172mod tests {
173 use super::*;
174
175 fn json_provider() -> Rc<dyn SyntaxContextProvider> {
176 syntax_context_provider("json").expect("json grammar must be compiled in")
177 }
178
179 #[cfg(all(feature = "tree-sitter-python", feature = "tree-sitter-rust"))]
180 #[test]
181 fn comment_end_tracks_insertion_context() {
182 use gpui_base::input::{Rope, SyntaxContext};
183 for (language, source, offset, expected) in [
184 ("python", "# note", 6, SyntaxContext::Comment),
185 ("python", "# note\n", 6, SyntaxContext::Comment),
186 ("python", "# note\n", 7, SyntaxContext::Code),
187 ("rust", "// note", 7, SyntaxContext::Comment),
188 ("rust", "/// note\n", 8, SyntaxContext::Comment),
189 ("rust", "/// note\n", 9, SyntaxContext::Code),
190 ("rust", "/* note */", 10, SyntaxContext::Code),
191 ] {
192 let provider = syntax_context_provider(language).unwrap();
193 assert_eq!(
194 provider.context_at(&Rope::from_str(source), offset),
195 expected,
196 "{source:?} at {offset}"
197 );
198 }
199 }
200
201 #[cfg(feature = "tree-sitter-cmake")]
202 #[test]
203 fn closed_bracket_comment_is_not_a_line_comment() {
204 use gpui_base::input::{Rope, SyntaxContext};
205 let provider = syntax_context_provider("cmake").unwrap();
206 let text = Rope::from_str("#[[ note ]]");
207 assert_eq!(provider.context_at(&text, text.len()), SyntaxContext::Code);
208 }
209
210 #[test]
211 fn json_string_content_is_string_context() {
212 use gpui_base::input::{Rope, SyntaxContext};
213
214 let provider = json_provider();
215 // {"key": "value"} — offset inside "value".
216 let text = Rope::from_str(r#"{"key": "value"}"#);
217 assert_eq!(
218 provider.context_at(&text, 10),
219 SyntaxContext::String,
220 "inside string literal"
221 );
222 }
223
224 #[test]
225 fn json_punctuation_is_code_context() {
226 use gpui_base::input::{Rope, SyntaxContext};
227
228 let provider = json_provider();
229 let text = Rope::from_str(r#"{"key": "value"}"#);
230 assert_eq!(
231 provider.context_at(&text, 0),
232 SyntaxContext::Code,
233 "opening brace"
234 );
235 assert_eq!(
236 provider.context_at(&text, 7),
237 SyntaxContext::Code,
238 "colon between pairs"
239 );
240 }
241
242 #[test]
243 fn test_changed_source_matches_fresh_provider() {
244 use gpui_base::input::{Rope, SyntaxContext};
245 let provider = json_provider();
246 let old = Rope::from_str(r#"{"key": "value"}"#);
247 assert_eq!(provider.context_at(&old, 10), SyntaxContext::String);
248 let new = Rope::from_str(r#"{"key": 1234567}"#);
249 let fresh = json_provider().context_at(&new, 10);
250 assert_eq!(fresh, SyntaxContext::Code);
251 assert_eq!(provider.context_at(&new, 10), fresh);
252 }
253
254 #[test]
255 fn unknown_language_has_no_provider() {
256 assert!(syntax_context_provider("not-a-language").is_none());
257 }
258}