Debian Codegraph @

Xtree-house/highlighter/src/highlighter.rs

raw symbols SCIP
1 use std::borrow::Cow;
2 use std::cmp;
3 use std::fmt;
4 use std::mem::replace;
5 use std::num::NonZeroU32;
6 use std::ops::RangeBounds;
7 use std::slice;
8 use std::sync::Arc;
9
10 use crate::config::{LanguageConfig, LanguageLoader};
11 use crate::locals::ScopeCursor;
12 use crate::query_iter::{MatchedNode, QueryIter, QueryIterEvent, QueryLoader};
13 use crate::{Injection, Language, Layer, Syntax};
14 use arc_swap::ArcSwap;
15 use hashbrown::{HashMap, HashSet};
16 use ropey::RopeSlice;
17 use tree_sitter::{
18 query::{self, InvalidPredicateError, Query, UserPredicate},
19 Capture, Grammar,
20 };
21 use tree_sitter::{Pattern, QueryMatch};
22
23 /// Contains the data needed to highlight code written in a particular language.
24 ///
25 /// This struct is immutable and can be shared between threads.
26 #[derive(Debug)]
27 pub struct HighlightQuery {
28 pub query: Query,
29 highlight_indices: ArcSwap<Vec<Option<Highlight>>>,
30 #[allow(dead_code)]
31 /// Patterns that do not match when the node is a local.
32 non_local_patterns: HashSet<Pattern>,
33 local_reference_capture: Option<Capture>,
34 /// The first pattern index that belongs to the locals query (i.e. the number of patterns
35 /// from the highlights query). Any pattern with index >= this value is from `locals.scm`.
36 first_locals_pattern: Pattern,
37 }
38
39 impl HighlightQuery {
40 pub(crate) fn new(
41 grammar: Grammar,
42 highlight_query_text: &str,
43 local_query_text: &str,
44 ) -> Result<Self, query::ParseError> {
45 // Concatenate the highlights and locals queries.
46 let mut query_source =
47 String::with_capacity(highlight_query_text.len() + local_query_text.len());
48 query_source.push_str(highlight_query_text);
49 query_source.push_str(local_query_text);
50
51 let mut non_local_patterns = HashSet::new();
52 let mut query = Query::new(grammar, &query_source, |pattern, predicate| {
53 match predicate {
54 // Allow the `(#set! local.scope-inherits <bool>)` property to be parsed.
55 // This information is not used by this query though, it's used in the
56 // injection query instead.
57 UserPredicate::SetProperty {
58 key: "local.scope-inherits",
59 ..
60 } => (),
61 // TODO: `(#is(-not)? local)` applies to the entire pattern. Ideally you
62 // should be able to supply capture(s?) which are each checked.
63 UserPredicate::IsPropertySet {
64 negate: true,
65 key: "local",
66 val: None,
67 } => {
68 non_local_patterns.insert(pattern);
69 }
70 _ => return Err(InvalidPredicateError::unknown(predicate)),
71 }
72 Ok(())
73 })?;
74
75 // Patterns with a start byte inside the highlights query source belong to
76 // highlights.scm; everything at or after belongs to locals.scm. Must be computed
77 // before disabling captures, which can invalidate `start_byte_for_pattern`.
78 let first_locals_pattern = query
79 .patterns()
80 .find(|&p| query.start_byte_for_pattern(p) >= highlight_query_text.len())
81 .unwrap_or(Pattern::SENTINEL);
82
83 // The highlight query only cares about local.reference captures. All scope and definition
84 // captures can be disabled.
85 query.disable_capture("local.scope");
86 let local_definition_captures: Vec<_> = query
87 .captures()
88 .filter(|&(_, name)| name.starts_with("local.definition."))
89 .map(|(_, name)| Box::<str>::from(name))
90 .collect();
91 for name in local_definition_captures {
92 query.disable_capture(&name);
93 }
94
95 Ok(Self {
96 highlight_indices: ArcSwap::from_pointee(vec![None; query.num_captures() as usize]),
97 non_local_patterns,
98 local_reference_capture: query.get_capture("local.reference"),
99 first_locals_pattern,
100 query,
101 })
102 }
103
104 /// Configures the list of recognized highlight names.
105 ///
106 /// Tree-sitter syntax-highlighting queries specify highlights in the form of dot-separated
107 /// highlight names like `punctuation.bracket` and `function.method.builtin`. Consumers of
108 /// these queries can choose to recognize highlights with different levels of specificity.
109 /// For example, the string `function.builtin` will match against `function.builtin.constructor`
110 /// but will not match `function.method.builtin` and `function.method`.
111 ///
112 /// The closure provided to this function should therefore try to first lookup the full
113 /// name. If no highlight was found for that name it should [`rsplit_once('.')`](str::rsplit_once)
114 /// and retry until a highlight has been found. If none of the parent scopes are defined
115 /// then `Highlight::NONE` should be returned.
116 ///
117 /// When highlighting, results are returned as `Highlight` values, configured by this function.
118 /// The meaning of these indices is up to the user of the implementation. The highlighter
119 /// treats the indices as entirely opaque.
120 pub(crate) fn configure(&self, f: &mut impl FnMut(&str) -> Option<Highlight>) {
121 let highlight_indices = self
122 .query
123 .captures()
124 .map(|(_, capture_name)| f(capture_name))
125 .collect();
126 self.highlight_indices.store(Arc::new(highlight_indices));
127 }
128 }
129
130 /// Indicates which highlight should be applied to a region of source code.
131 ///
132 /// This type is represented as a non-max u32 - a u32 which cannot be `u32::MAX`. This is checked
133 /// at runtime with assertions in `Highlight::new`.
134 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
135 pub struct Highlight(NonZeroU32);
136
137 impl Highlight {
138 pub const MAX: u32 = u32::MAX - 1;
139
140 pub const fn new(inner: u32) -> Self {
141 assert!(inner != u32::MAX);
142 // SAFETY: must be non-zero because `inner` is not `u32::MAX`.
143 Self(unsafe { NonZeroU32::new_unchecked(inner ^ u32::MAX) })
144 }
145
146 pub const fn get(&self) -> u32 {
147 self.0.get() ^ u32::MAX
148 }
149
150 pub const fn idx(&self) -> usize {
151 self.get() as usize
152 }
153 }
154
155 impl fmt::Debug for Highlight {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.debug_tuple("Highlight").field(&self.get()).finish()
158 }
159 }
160
161 #[derive(Debug)]
162 struct HighlightedNode {
163 end: u32,
164 highlight: Highlight,
165 }
166
167 #[derive(Debug, Default)]
168 pub struct LayerData {
169 parent_highlights: usize,
170 dormant_highlights: Vec<HighlightedNode>,
171 }
172
173 pub struct Highlighter<'a, 'tree, Loader: LanguageLoader> {
174 query: QueryIter<'a, 'tree, HighlightQueryLoader<&'a Loader>, ()>,
175 next_query_event: Option<QueryIterEvent<'tree, ()>>,
176 /// The stack of currently active highlights.
177 /// The ranges of the highlights stack, so each highlight in the Vec must have a starting
178 /// point `>=` the starting point of the next highlight in the Vec and and ending point `<=`
179 /// the ending point of the next highlight in the Vec.
180 ///
181 /// For a visual:
182 ///
183 /// ```text
184 /// | C |
185 /// | B |
186 /// | A |
187 /// ```
188 ///
189 /// would be `vec![A, B, C]`.
190 active_highlights: Vec<HighlightedNode>,
191 next_highlight_end: u32,
192 next_highlight_start: u32,
193 active_config: Option<&'a LanguageConfig>,
194 // Snapshots of the active config's `ArcSwap`-backed lookup tables, refreshed only when
195 // `active_config` changes (on injection enter/exit).
196 active_highlight_indices: Option<Arc<Vec<Option<Highlight>>>>,
197 active_local_definition_captures: Option<Arc<HashMap<Capture, Highlight>>>,
198 // The current layer and per-layer state could be tracked on the QueryIter itself (see
199 // `QueryIter::current_layer` and `QueryIter::layer_state`) however the highlighter peeks the
200 // query iter. The query iter is always one event ahead, so it will enter/exit injections
201 // before we get a chance to in the highlighter. So instead we track these on the highlighter.
202 // Also see `Self::advance_query_iter`.
203 current_layer: Layer,
204 layer_states: HashMap<Layer, LayerData>,
205 }
206
207 pub struct HighlightList<'a>(slice::Iter<'a, HighlightedNode>);
208
209 impl Iterator for HighlightList<'_> {
210 type Item = Highlight;
211
212 fn next(&mut self) -> Option<Highlight> {
213 self.0.next().map(|node| node.highlight)
214 }
215
216 fn size_hint(&self) -> (usize, Option<usize>) {
217 self.0.size_hint()
218 }
219 }
220
221 impl DoubleEndedIterator for HighlightList<'_> {
222 fn next_back(&mut self) -> Option<Self::Item> {
223 self.0.next_back().map(|node| node.highlight)
224 }
225 }
226
227 impl ExactSizeIterator for HighlightList<'_> {
228 fn len(&self) -> usize {
229 self.0.len()
230 }
231 }
232
233 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
234 pub enum HighlightEvent {
235 /// Reset the active set of highlights to the given ones.
236 Refresh,
237 /// Add more highlights which build on the existing highlights.
238 Push,
239 }
240
241 impl<'a, 'tree: 'a, Loader: LanguageLoader> Highlighter<'a, 'tree, Loader> {
242 pub fn new(
243 syntax: &'tree Syntax,
244 src: RopeSlice<'a>,
245 loader: &'a Loader,
246 range: impl RangeBounds<u32>,
247 ) -> Self {
248 let mut query = QueryIter::new(syntax, src, HighlightQueryLoader(loader), range);
249 let active_language = query.current_language();
250 let active_config = query.loader().0.get_config(active_language);
251 let mut res = Highlighter {
252 active_config: None,
253 active_highlight_indices: None,
254 active_local_definition_captures: None,
255 next_query_event: None,
256 current_layer: query.current_layer(),
257 layer_states: Default::default(),
258 active_highlights: Vec::new(),
259 next_highlight_end: u32::MAX,
260 next_highlight_start: 0,
261 query,
262 };
263 res.set_active_config(active_config);
264 res.advance_query_iter();
265 res
266 }
267
268 // Set the active language config and snapshot its lookup tables.
269 fn set_active_config(&mut self, config: Option<&'a LanguageConfig>) {
270 self.active_config = config;
271 // The snapshots are read on the per-match hot path, so they are loaded once here
272 // rather than re-loading the `ArcSwap`s for every captured node.
273 self.active_highlight_indices =
274 config.map(|config| config.highlight_query.highlight_indices.load_full());
275 self.active_local_definition_captures =
276 config.map(|config| config.injection_query.local_definition_captures.load_full());
277 }
278
279 pub fn active_highlights(&self) -> HighlightList<'_> {
280 HighlightList(self.active_highlights.iter())
281 }
282
283 pub fn next_event_offset(&self) -> u32 {
284 self.next_highlight_start.min(self.next_highlight_end)
285 }
286
287 pub fn advance(&mut self) -> (HighlightEvent, HighlightList<'_>) {
288 let mut refresh = false;
289
290 let pos = self.next_event_offset();
291 if self.next_highlight_end == pos {
292 self.process_highlight_end(pos);
293 refresh = true;
294 }
295
296 // Capture the boundary after any ended highlights are removed. Highlights
297 // at indices below this are from prior advance() calls and must not be
298 // replaced or removed by the current one. When refresh=true we return
299 // active_highlights.iter() anyway, so this value only matters for the
300 // search window in start_highlight and the Push slice when refresh=false.
301 let prev_stack_size = self.active_highlights.len();
302
303 let mut first_highlight = true;
304 let mut local_ref_candidate: Option<(u32, Highlight)> = None;
305 while self.next_highlight_start == pos {
306 let Some(query_event) = self.advance_query_iter() else {
307 break;
308 };
309 match query_event {
310 QueryIterEvent::EnterInjection(injection) => self.enter_injection(injection.layer),
311 QueryIterEvent::Match(node) => self.start_highlight(
312 node,
313 &mut first_highlight,
314 prev_stack_size,
315 &mut local_ref_candidate,
316 ),
317 QueryIterEvent::ExitInjection { injection, state } => {
318 // `state` is returned if the layer is finished according to the `QueryIter`.
319 // The highlighter should only consider a layer finished, though, when it also
320 // has no remaining ranges to highlight. If the injection is combined and has
321 // highlight(s) past this injection's range then we should deactivate it
322 // (saving the highlights for the layer's next injection range) rather than
323 // removing it.
324 let layer_is_finished = state.is_some()
325 && self
326 .current_layer_highlights()
327 .iter()
328 .all(|h| h.end <= injection.range.end);
329 if layer_is_finished {
330 self.layer_states.remove(&injection.layer);
331 } else {
332 self.deactivate_layer(injection);
333 refresh = true;
334 }
335 let active_language = self.query.syntax().layer(self.current_layer).language;
336 let config = self.query.loader().0.get_config(active_language);
337 self.set_active_config(config);
338 }
339 }
340 }
341 // Commit any local reference candidate not cancelled by a discard pattern.
342 if let Some((end, highlight)) = local_ref_candidate {
343 let node = HighlightedNode { end, highlight };
344 let search_start = prev_stack_size.min(self.active_highlights.len());
345 let insert_position = self.active_highlights[search_start..]
346 .iter()
347 .rposition(|h| h.end <= end)
348 .map(|rel_idx| rel_idx + search_start);
349 match insert_position {
350 Some(idx) => match self.active_highlights[idx].end.cmp(&end) {
351 cmp::Ordering::Equal => self.active_highlights[idx] = node,
352 cmp::Ordering::Less => self.active_highlights.insert(idx, node),
353 cmp::Ordering::Greater => unreachable!(),
354 },
355 None => self.active_highlights.extend(Some(node)),
356 }
357 }
358
359 self.next_highlight_end = self
360 .active_highlights
361 .last()
362 .map_or(u32::MAX, |node| node.end);
363
364 if refresh {
365 (
366 HighlightEvent::Refresh,
367 HighlightList(self.active_highlights.iter()),
368 )
369 } else {
370 (
371 HighlightEvent::Push,
372 HighlightList(self.active_highlights[prev_stack_size..].iter()),
373 )
374 }
375 }
376
377 fn advance_query_iter(&mut self) -> Option<QueryIterEvent<'tree, ()>> {
378 // Track the current layer **before** calling `QueryIter::next`. The QueryIter moves
379 // to the next event with `QueryIter::next` but we're treating that event as peeked - it
380 // hasn't occurred yet - so the current layer is the one the query iter was on _before_
381 // `QueryIter::next`.
382 self.current_layer = self.query.current_layer();
383 let event = replace(&mut self.next_query_event, self.query.next());
384 self.next_highlight_start = self
385 .next_query_event
386 .as_ref()
387 .map_or(u32::MAX, |event| event.start_byte());
388 event
389 }
390
391 fn process_highlight_end(&mut self, pos: u32) {
392 let i = self
393 .active_highlights
394 .iter()
395 .rposition(|highlight| highlight.end != pos)
396 .map_or(0, |i| i + 1);
397 self.active_highlights.truncate(i);
398 }
399
400 fn current_layer_highlights(&self) -> &[HighlightedNode] {
401 let parent_start = self
402 .layer_states
403 .get(&self.current_layer)
404 .map(|layer| layer.parent_highlights)
405 .unwrap_or_default()
406 .min(self.active_highlights.len());
407 &self.active_highlights[parent_start..]
408 }
409
410 fn enter_injection(&mut self, layer: Layer) {
411 debug_assert_eq!(layer, self.current_layer);
412 let active_language = self.query.syntax().layer(layer).language;
413 let config = self.query.loader().0.get_config(active_language);
414 self.set_active_config(config);
415
416 let state = self.layer_states.entry(layer).or_default();
417 state.parent_highlights = self.active_highlights.len();
418 self.active_highlights.append(&mut state.dormant_highlights);
419 }
420
421 fn deactivate_layer(&mut self, injection: Injection) {
422 let LayerData {
423 mut parent_highlights,
424 ref mut dormant_highlights,
425 ..
426 } = self.layer_states.get_mut(&injection.layer).unwrap();
427 parent_highlights = parent_highlights.min(self.active_highlights.len());
428 dormant_highlights.extend(self.active_highlights.drain(parent_highlights..));
429 self.process_highlight_end(injection.range.end);
430 }
431
432 fn start_highlight(
433 &mut self,
434 node: MatchedNode,
435 first_highlight: &mut bool,
436 prev_stack_size: usize,
437 local_ref_candidate: &mut Option<(u32, Highlight)>,
438 ) {
439 let range = node.node.byte_range();
440 // `<QueryIter as Iterator>::next` skips matches with empty ranges.
441 debug_assert!(
442 !range.is_empty(),
443 "QueryIter should not emit matches with empty ranges"
444 );
445
446 let config = self
447 .active_config
448 .expect("must have an active config to emit matches");
449
450 let is_local_reference =
451 Some(node.capture) == config.highlight_query.local_reference_capture;
452
453 // Captures from the locals.scm tier (pattern >= first_locals_pattern) that are not
454 // @local.reference act as discards: they cancel any pending local reference candidate
455 // for this node and leave the highlights.scm highlight intact.
456 if node.pattern >= config.highlight_query.first_locals_pattern && !is_local_reference {
457 if local_ref_candidate.is_some_and(|(end, _)| end == range.end) {
458 *local_ref_candidate = None;
459 }
460 return;
461 }
462
463 let highlight = if is_local_reference {
464 // If this capture was a `@local.reference` from the locals queries, look up the
465 // text of the node in the current locals cursor and use that highlight.
466 let text: Cow<str> = self
467 .query
468 .source()
469 .byte_slice(range.start as usize..range.end as usize)
470 .into();
471 let Some(definition) = self
472 .query
473 .syntax()
474 .layer(self.current_layer)
475 .locals
476 .lookup_reference(node.scope, &text)
477 .filter(|def| range.start >= def.range.end)
478 else {
479 return;
480 };
481 let highlight = self
482 .active_local_definition_captures
483 .as_ref()
484 .expect("must have an active config to emit matches")
485 .get(&definition.capture)
486 .copied();
487 // Store as a candidate rather than replacing immediately. A later discard
488 // pattern in locals.scm can cancel this before it takes effect.
489 if let Some(h) = highlight {
490 *local_ref_candidate = Some((range.end, h));
491 }
492 return;
493 } else {
494 self.active_highlight_indices
495 .as_deref()
496 .expect("must have an active config to emit matches")[node.capture.idx()]
497 };
498
499 let highlight = highlight.map(|highlight| HighlightedNode {
500 end: range.end,
501 highlight,
502 });
503
504 // If multiple patterns match this exact node, prefer the last one which matched.
505 // This matches the precedence of Neovim, Zed, and tree-sitter-cli.
506 if !*first_highlight {
507 // NOTE: `!*first_highlight` implies that the start positions are the same.
508 // Only search within highlights added during this advance() call. Highlights
509 // before `prev_stack_size` belong to ancestor nodes from prior advance() calls
510 // and must not be replaced or removed by a descendant's captures.
511 let search_start = prev_stack_size.min(self.active_highlights.len());
512 let insert_position = self.active_highlights[search_start..]
513 .iter()
514 .rposition(|h| h.end <= range.end)
515 .map(|rel_idx| rel_idx + search_start);
516 if let Some(idx) = insert_position {
517 match self.active_highlights[idx].end.cmp(&range.end) {
518 // If there is a prior highlight for this start..end range, replace it.
519 cmp::Ordering::Equal => {
520 if let Some(highlight) = highlight {
521 self.active_highlights[idx] = highlight;
522 } else {
523 self.active_highlights.remove(idx);
524 }
525 }
526 // Captures are emitted in the order that they are finished. Insert any
527 // highlights which start at the same position into the active highlights so
528 // that the ordering invariant remains satisfied.
529 cmp::Ordering::Less => {
530 if let Some(highlight) = highlight {
531 self.active_highlights.insert(idx, highlight)
532 }
533 }
534 // By definition of our `rposition` predicate:
535 cmp::Ordering::Greater => unreachable!(),
536 }
537 } else {
538 self.active_highlights.extend(highlight);
539 }
540 } else if let Some(highlight) = highlight {
541 self.active_highlights.push(highlight);
542 *first_highlight = false;
543 }
544
545 // `active_highlights` must be a stack of highlight events the highlights stack on the
546 // prior highlights in the Vec. Each highlight's range must be a subset of the highlight's
547 // range before it.
548 debug_assert!(
549 // The assertion is actually true for the entire stack but combined injections
550 // throw a wrench in things: the highlight can end after the current injection.
551 // The highlight is removed from `active_highlights` as the injection layer ends
552 // so the wider assertion would be true in practice. We don't track the injection
553 // end right here though so we can't assert on it.
554 self.current_layer_highlights().is_sorted_by_key(|h| cmp::Reverse(h.end)),
555 "unsorted highlights on layer {:?}: {:?}\nall active highlights must be sorted by `end` descending",
556 self.current_layer,
557 self.active_highlights,
558 );
559 }
560 }
561
562 pub(crate) struct HighlightQueryLoader<T>(T);
563
564 impl<'a, T: LanguageLoader> QueryLoader<'a> for HighlightQueryLoader<&'a T> {
565 fn get_query(&mut self, lang: Language) -> Option<&'a Query> {
566 self.0
567 .get_config(lang)
568 .map(|config| &config.highlight_query.query)
569 }
570
571 fn are_predicates_satisfied(
572 &self,
573 lang: Language,
574 mat: &QueryMatch<'_, '_>,
575 source: RopeSlice<'_>,
576 locals_cursor: &ScopeCursor<'_>,
577 ) -> bool {
578 let highlight_query = &self
579 .0
580 .get_config(lang)
581 .expect("must have a config to emit matches")
582 .highlight_query;
583
584 // Highlight queries should reject the match when a pattern is marked with
585 // `(#is-not? local)` and any capture in the pattern matches a definition in scope.
586 //
587 // TODO: in the future we should propose that `#is-not? local` takes one or more
588 // captures as arguments. Ideally we would check that the captured node is also captured
589 // by a `local.reference` capture from the locals query but that's really messy to pass
590 // around that information. For now we assume that all matches in the pattern are also
591 // captured as `local.reference` in the locals, which covers most cases.
592 if highlight_query.local_reference_capture.is_some()
593 && highlight_query.non_local_patterns.contains(&mat.pattern())
594 {
595 let has_local_reference = mat.matched_nodes().any(|n| {
596 let range = n.node.byte_range();
597 let text: Cow<str> = source
598 .byte_slice(range.start as usize..range.end as usize)
599 .into();
600 locals_cursor
601 .locals
602 .lookup_reference(locals_cursor.current_scope(), &text)
603 .is_some_and(|def| range.start >= def.range.start)
604 });
605 if has_local_reference {
606 return false;
607 }
608 }
609
610 true
611 }
612 }