Skip to main content

rouge_syntax/
incremental.rs

1use crate::HighlightId;
2use crate::{
3    SyntaxError,
4    language::{LANGUAGES, Language, LanguageId, resolve_hint, shebang_id},
5    spans::{Injection, Span},
6    symbols::TagsGrammar,
7};
8use arborium_theme::tag_for_capture;
9cfg_select! {
10    target_arch = "wasm32" => {
11        use std::rc::Rc as SharedGrammar;
12    }
13    _ => {
14        use std::sync::Arc as SharedGrammar;
15    }
16}
17use std::{borrow::Cow, collections::HashSet, fmt, ops::Add, sync::OnceLock};
18use tree_sitter::{
19    InputEdit, Language as TreeLanguage, Node, Parser, Point, Query, QueryCursor,
20    StreamingIterator, Tree,
21};
22
23const PARSER_CHUNK_BYTES: usize = 16 << 10;
24
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct SyntaxWorkStats {
27    pub parser_input_bytes: usize,
28    pub queried_bytes: usize,
29    pub full_parses: usize,
30    pub incremental_parses: usize,
31    pub projected_bytes: usize,
32    pub projected_lines: usize,
33    pub reused_lines: usize,
34    pub compared_nodes: usize,
35}
36
37impl SyntaxWorkStats {
38    #[must_use]
39    pub const fn parses(&self) -> usize {
40        self.full_parses + self.incremental_parses
41    }
42}
43
44impl Add for SyntaxWorkStats {
45    type Output = Self;
46
47    fn add(self, other: Self) -> Self {
48        Self {
49            parser_input_bytes: self.parser_input_bytes + other.parser_input_bytes,
50            queried_bytes: self.queried_bytes + other.queried_bytes,
51            full_parses: self.full_parses + other.full_parses,
52            incremental_parses: self.incremental_parses + other.incremental_parses,
53            projected_bytes: self.projected_bytes + other.projected_bytes,
54            projected_lines: self.projected_lines + other.projected_lines,
55            reused_lines: self.reused_lines + other.reused_lines,
56            compared_nodes: self.compared_nodes + other.compared_nodes,
57        }
58    }
59}
60
61type Compiled = OnceLock<Option<SharedGrammar<Grammar>>>;
62
63cfg_select! {
64    target_arch = "wasm32" => {
65        fn with_registry<T>(read: impl FnOnce(&[Compiled]) -> T) -> T {
66            thread_local! {
67                static REGISTRY: [Compiled; LANGUAGES.len()] = const { [const { OnceLock::new() }; LANGUAGES.len()] };
68            }
69            REGISTRY.with(|registry| read(registry))
70        }
71    }
72    _ => {
73        fn with_registry<T>(read: impl FnOnce(&[Compiled]) -> T) -> T {
74            static REGISTRY: [Compiled; LANGUAGES.len()] = [const { OnceLock::new() }; LANGUAGES.len()];
75            read(&REGISTRY)
76        }
77    }
78}
79
80pub(crate) fn grammar(language: LanguageId) -> Option<SharedGrammar<Grammar>> {
81    with_registry(|registry| {
82        registry[language.index()]
83            .get_or_init(|| compile(language.language()))
84            .clone()
85    })
86}
87
88fn compile(&Language { name, spec, .. }: &Language) -> Option<SharedGrammar<Grammar>> {
89    let (language, highlights, injections) = spec();
90    let highlights = if name == "solidity" {
91        Cow::Owned(highlights.replace(
92            "(struct_expression type: ((expression (identifier)) @type .))",
93            "(struct_expression type: (expression (identifier)) @type .)",
94        ))
95    } else {
96        Cow::Borrowed(highlights)
97    };
98    let query_words: HashSet<Box<str>> = [highlights.as_ref(), injections]
99        .into_iter()
100        .flat_map(query_words)
101        .map(String::into_boxed_str)
102        .collect();
103    let queried_kinds = (0..language.node_kind_count())
104        .map(|_| OnceLock::new())
105        .collect();
106    let highlights = Query::new(&language, &highlights).ok()?;
107    let injections = Query::new(&language, injections).ok()?;
108    let tags = TagsGrammar::new(name, &language).ok()?;
109    let non_local = [&highlights, &injections]
110        .into_iter()
111        .any(|query| (0..query.pattern_count()).any(|index| query.is_pattern_non_local(index)));
112    let captures = highlights
113        .capture_names()
114        .iter()
115        .map(|name| CaptureRole::of(name))
116        .collect();
117    let error_prefix = !non_local && !query_words.contains("ERROR") && !query_words.contains("_");
118    Some(SharedGrammar::new(Grammar {
119        language,
120        highlights,
121        captures,
122        injections,
123        non_local,
124        error_prefix,
125        query_words,
126        queried_kinds,
127        tags,
128    }))
129}
130
131/// Shared state for one append across a document and its injections.
132pub(crate) struct AppendContext<'a> {
133    pub stats: &'a mut SyntaxWorkStats,
134    /// Line starts of the root stream, for Tree-sitter edit positions.
135    pub line_starts: &'a [usize],
136}
137
138pub(crate) struct IncrementalDocument {
139    parser: Option<Parser>,
140    tree: Option<Tree>,
141    grammar: SharedGrammar<Grammar>,
142    length: usize,
143    spans: Vec<Span>,
144    injections: Vec<InjectedDocument>,
145    boundaries: Vec<(u32, u32)>,
146}
147
148impl IncrementalDocument {
149    /// Creates an empty document, or `None` when no grammar is bundled.
150    pub(crate) fn new(language: LanguageId) -> Option<Self> {
151        grammar(language).map(|grammar| Self {
152            parser: None,
153            tree: None,
154            grammar,
155            length: 0,
156            spans: Vec::new(),
157            injections: Vec::new(),
158            boundaries: Vec::new(),
159        })
160    }
161
162    pub(crate) const fn tree(&self) -> Option<&Tree> {
163        self.tree.as_ref()
164    }
165
166    pub(crate) fn grammar(&self) -> &Grammar {
167        &self.grammar
168    }
169
170    /// Appends the bytes of `source` beyond the previous length. `base` is the
171    /// document's offset within the root stream.
172    pub(crate) fn append(
173        &mut self,
174        source: &str,
175        base: usize,
176        depth: usize,
177        cx: &mut AppendContext<'_>,
178    ) -> Result<usize, SyntaxError> {
179        if source.len() == self.length && self.tree.is_some() {
180            return Ok(source.len());
181        }
182        let tree = self.parse_tree(source, base, cx)?;
183        let mut start = if self.tree.is_none() || self.grammar.non_local {
184            0
185        } else {
186            self.length
187        };
188        if let Some(previous) = &self.tree {
189            for change in previous.changed_ranges(&tree) {
190                let refined = if change.start_byte == 0 {
191                    self.grammar
192                        .error_prefix(previous.root_node(), tree.root_node(), cx.stats)
193                } else {
194                    None
195                };
196                start = start.min(refined.unwrap_or(change.start_byte));
197            }
198        }
199        // A capture ending exactly at the edit point may be an unterminated
200        // token that the appended text extends, so widen to it as well.
201        loop {
202            let first = self
203                .boundaries
204                .partition_point(|&(end, _)| (end as usize) < start);
205            let earlier = self.boundaries[first..]
206                .iter()
207                .map(|&(_, begin)| begin as usize)
208                .min()
209                .unwrap_or(start);
210            if earlier >= start {
211                break;
212            }
213            start = earlier;
214        }
215        let (mut spans, mut injections) = loop {
216            let result = query(&self.grammar, &tree, source, start, cx.stats);
217            let capture_start = result
218                .0
219                .iter()
220                .map(|span| span.start as usize)
221                .chain(result.1.iter().map(|injection| injection.start as usize))
222                .min()
223                .unwrap_or(start);
224            if capture_start < start {
225                start = capture_start;
226            } else {
227                break result;
228            }
229        };
230        self.update_boundaries(start, &spans, &injections);
231        spans.retain(|span| span.highlight.is_some());
232        spans.sort_by_key(|span| span.start);
233        injections.sort_by_key(|injection| injection.start);
234        let kept = self
235            .spans
236            .partition_point(|span| (span.start as usize) < start);
237        self.spans.truncate(kept);
238        self.spans.extend(spans);
239        self.update_injections(source, base, start, injections, depth, cx)?;
240        self.tree = Some(tree);
241        self.length = source.len();
242        Ok(start)
243    }
244
245    fn update_boundaries(&mut self, start: usize, spans: &[Span], injections: &[Injection]) {
246        let kept = self
247            .boundaries
248            .partition_point(|&(end, _)| end as usize <= start);
249        self.boundaries.truncate(kept);
250        let mut added: Vec<(u32, u32)> = spans
251            .iter()
252            .map(|span| (span.end, span.start))
253            .chain(
254                injections
255                    .iter()
256                    .map(|injection| (injection.end, injection.start)),
257            )
258            .collect();
259        added.sort_unstable();
260        for (end, begin) in added {
261            match self.boundaries.last_mut() {
262                Some(last) if last.0 == end => last.1 = last.1.min(begin),
263                _ => self.boundaries.push((end, begin)),
264            }
265        }
266    }
267
268    fn parse_tree(
269        &mut self,
270        source: &str,
271        base: usize,
272        cx: &mut AppendContext<'_>,
273    ) -> Result<Tree, SyntaxError> {
274        if self.parser.is_none() {
275            let mut parser = Parser::new();
276            parser.set_language(&self.grammar.language)?;
277            self.parser = Some(parser);
278        }
279        if let Some(tree) = &mut self.tree {
280            let old_end = end_point(cx.line_starts, base, self.length);
281            tree.edit(&InputEdit {
282                start_byte: self.length,
283                old_end_byte: self.length,
284                new_end_byte: source.len(),
285                start_position: old_end,
286                old_end_position: old_end,
287                new_end_position: end_point(cx.line_starts, base, source.len()),
288            });
289            cx.stats.incremental_parses += 1;
290        } else {
291            cx.stats.full_parses += 1;
292        }
293        let bytes = source.as_bytes();
294        let stats = &mut *cx.stats;
295        self.parser
296            .as_mut()
297            .expect("initialized parser")
298            .parse_with_options(
299                &mut |offset, _| {
300                    let end = offset.saturating_add(PARSER_CHUNK_BYTES).min(bytes.len());
301                    let input = &bytes[offset.min(bytes.len())..end];
302                    stats.parser_input_bytes += input.len();
303                    input
304                },
305                self.tree.as_ref(),
306                None,
307            )
308            .ok_or(SyntaxError::NoTree)
309    }
310
311    fn update_injections(
312        &mut self,
313        source: &str,
314        base: usize,
315        start: usize,
316        injections: Vec<Injection>,
317        depth: usize,
318        cx: &mut AppendContext<'_>,
319    ) -> Result<(), SyntaxError> {
320        let kept = self
321            .injections
322            .partition_point(|entry| entry.offset < start);
323        let mut previous = self.injections.split_off(kept);
324        if depth > 0 {
325            for injection in injections {
326                let from = injection.start as usize;
327                let to = injection.end as usize;
328                let Some(text) = source.get(from..to).filter(|text| !text.is_empty()) else {
329                    continue;
330                };
331                let Some(language) = injection.language.or_else(|| shebang_id(text)) else {
332                    continue;
333                };
334                let reused = previous
335                    .iter()
336                    .position(|entry| {
337                        entry.offset == from
338                            && entry.language == language
339                            && text.len() >= entry.document.length
340                    })
341                    .map(|index| previous.swap_remove(index));
342                let mut entry = match reused {
343                    Some(entry) => entry,
344                    None => match Self::new(language) {
345                        Some(document) => InjectedDocument {
346                            offset: from,
347                            language,
348                            document,
349                        },
350                        None => continue,
351                    },
352                };
353                entry.document.append(text, base + from, depth - 1, cx)?;
354                self.injections.push(entry);
355            }
356        }
357        Ok(())
358    }
359
360    pub(crate) fn spans_from(&self, start: usize, output: &mut Vec<Span>) {
361        let first = self
362            .spans
363            .partition_point(|span| (span.start as usize) < start);
364        output.extend_from_slice(&self.spans[first..]);
365        let first = self
366            .injections
367            .partition_point(|entry| entry.offset < start);
368        for injection in &self.injections[first..] {
369            let offset = u32::try_from(injection.offset).expect("source limit fits u32");
370            let from = output.len();
371            injection.document.spans_from(0, output);
372            for span in &mut output[from..] {
373                span.start += offset;
374                span.end += offset;
375            }
376        }
377    }
378}
379
380impl Clone for IncrementalDocument {
381    fn clone(&self) -> Self {
382        Self {
383            parser: None,
384            tree: self.tree.clone(),
385            grammar: SharedGrammar::clone(&self.grammar),
386            length: self.length,
387            spans: self.spans.clone(),
388            injections: self.injections.clone(),
389            boundaries: self.boundaries.clone(),
390        }
391    }
392}
393
394impl fmt::Debug for IncrementalDocument {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        f.debug_struct("IncrementalDocument")
397            .field("length", &self.length)
398            .finish_non_exhaustive()
399    }
400}
401
402#[derive(Clone)]
403struct InjectedDocument {
404    offset: usize,
405    language: LanguageId,
406    document: IncrementalDocument,
407}
408
409#[derive(Clone, Copy)]
410enum CaptureRole {
411    Skip,
412    Highlight(Option<HighlightId>),
413}
414
415impl CaptureRole {
416    fn of(name: &str) -> Self {
417        if name.starts_with('_') || name.starts_with("injection.") {
418            Self::Skip
419        } else {
420            Self::Highlight(tag_for_capture(name).and_then(HighlightId::from_tag))
421        }
422    }
423}
424
425pub(crate) struct Grammar {
426    language: TreeLanguage,
427    highlights: Query,
428    captures: Box<[CaptureRole]>,
429    injections: Query,
430    non_local: bool,
431    error_prefix: bool,
432    query_words: HashSet<Box<str>>,
433    queried_kinds: Box<[OnceLock<bool>]>,
434    tags: Option<TagsGrammar>,
435}
436
437impl Grammar {
438    pub(crate) const fn tags(&self) -> Option<&TagsGrammar> {
439        self.tags.as_ref()
440    }
441
442    fn error_prefix(
443        &self,
444        before: Node<'_>,
445        after: Node<'_>,
446        stats: &mut SyntaxWorkStats,
447    ) -> Option<usize> {
448        if !self.error_prefix {
449            return None;
450        }
451        let before = self.error_root(before)?;
452        let after = self.error_root(after)?;
453        let mut end = before.start_byte().min(after.start_byte());
454        let mut left = before.walk();
455        let mut right = after.walk();
456        for (before, after) in before.children(&mut left).zip(after.children(&mut right)) {
457            if !same_subtree(before, after, stats) {
458                break;
459            }
460            end = before.end_byte().min(after.end_byte());
461        }
462        Some(end)
463    }
464
465    fn error_root<'a>(&self, node: Node<'a>) -> Option<Node<'a>> {
466        if node.is_error() {
467            Some(node)
468        } else if !self.queries_kind(node) && node.child_count() == 1 {
469            node.child(0).filter(Node::is_error)
470        } else {
471            None
472        }
473    }
474
475    fn queries_kind(&self, node: Node<'_>) -> bool {
476        let queried = || self.query_words.contains(node.kind());
477        self.queried_kinds
478            .get(usize::from(node.kind_id()))
479            .map_or_else(queried, |cell| *cell.get_or_init(queried))
480    }
481}
482
483fn same_subtree(before: Node<'_>, after: Node<'_>, stats: &mut SyntaxWorkStats) -> bool {
484    stats.compared_nodes += 1;
485    if before.byte_range() != after.byte_range() || before.has_changes() || after.has_changes() {
486        return false;
487    }
488    if before.id() == after.id() {
489        return true;
490    }
491    if before.kind_id() != after.kind_id() || before.child_count() != after.child_count() {
492        return false;
493    }
494    let mut left = before.walk();
495    let mut right = after.walk();
496    before
497        .children(&mut left)
498        .zip(after.children(&mut right))
499        .enumerate()
500        .all(|(index, (left, right))| {
501            let Ok(index) = u32::try_from(index) else {
502                return false;
503            };
504            before.field_name_for_child(index) == after.field_name_for_child(index)
505                && same_subtree(left, right, stats)
506        })
507}
508
509/// Row and column of byte `len` within a document that starts at `base` in
510/// the root stream whose line starts are `line_starts`.
511fn end_point(line_starts: &[usize], base: usize, len: usize) -> Point {
512    let first = line_starts.partition_point(|&start| start <= base);
513    let last = line_starts.partition_point(|&start| start <= base + len);
514    let column = line_starts[first..last]
515        .last()
516        .map_or(len, |&start| base + len - start);
517    Point::new(last - first, column)
518}
519
520fn query(
521    grammar: &Grammar,
522    tree: &Tree,
523    source: &str,
524    start: usize,
525    stats: &mut SyntaxWorkStats,
526) -> (Vec<Span>, Vec<Injection>) {
527    let mut cursor = QueryCursor::new();
528    cursor.set_byte_range(start..source.len());
529    stats.queried_bytes += source.len() - start;
530    let mut matches = cursor.matches(&grammar.highlights, tree.root_node(), source.as_bytes());
531    let mut spans = Vec::new();
532    while let Some(found) = matches.next() {
533        for capture in found.captures() {
534            let CaptureRole::Highlight(highlight) = grammar.captures[capture.index as usize] else {
535                continue;
536            };
537            spans.push(Span {
538                start: u32::try_from(capture.node.start_byte()).expect("source limit fits u32"),
539                end: u32::try_from(capture.node.end_byte()).expect("source limit fits u32"),
540                highlight,
541                pattern_index: u32::try_from(found.pattern_index).expect("query pattern fits u32"),
542            });
543        }
544    }
545    stats.queried_bytes += source.len() - start;
546    let mut matches = cursor.matches(&grammar.injections, tree.root_node(), source.as_bytes());
547    let mut injections = Vec::new();
548    while let Some(found) = matches.next() {
549        let mut content = None;
550        let mut language = None;
551        for property in grammar.injections.property_settings(found.pattern_index) {
552            if property.key.as_ref() == "injection.language" {
553                language = property.value.as_deref();
554            }
555        }
556        for capture in found.captures() {
557            match grammar.injections.capture_names()[capture.index as usize] {
558                "injection.content" => content = Some(capture.node),
559                "injection.language" if language.is_none() => {
560                    language = capture.node.utf8_text(source.as_bytes()).ok();
561                }
562                _ => {}
563            }
564        }
565        if let (Some(node), Some(language)) = (content, language) {
566            injections.push(Injection {
567                start: u32::try_from(node.start_byte()).expect("source limit fits u32"),
568                end: u32::try_from(node.end_byte()).expect("source limit fits u32"),
569                language: resolve_hint(language),
570            });
571        }
572    }
573    (spans, injections)
574}
575
576fn query_words(query: &str) -> Vec<String> {
577    let mut words = Vec::new();
578    let mut chars = query.chars().peekable();
579    while let Some(c) = chars.next() {
580        match c {
581            ';' => {
582                for c in chars.by_ref() {
583                    if c == '\n' {
584                        break;
585                    }
586                }
587            }
588            '"' => {
589                let mut word = String::new();
590                while let Some(c) = chars.next() {
591                    match c {
592                        '\\' => word.extend(chars.next()),
593                        '"' => break,
594                        c => word.push(c),
595                    }
596                }
597                words.push(word);
598            }
599            c if is_word(c) => {
600                let mut word = String::from(c);
601                while let Some(&c) = chars.peek().filter(|c| is_word(**c)) {
602                    word.push(c);
603                    chars.next();
604                }
605                words.push(word);
606            }
607            _ => {}
608        }
609    }
610    words
611}
612
613fn is_word(c: char) -> bool {
614    c.is_alphanumeric() || c == '_'
615}