Skip to main content

ktrs_parser/builder/
sink.rs

1//! [`TreeSink`]: the tree builder `tree.rs` binds into, shared by a file and all of its
2//! chameleons so each lazy node is built in place instead of being copied out of a sub-tree.
3
4use ktrs_syntax::{MissedTokens, Parse, SyntaxKind, TreeBuilder};
5
6use super::chameleon_cache::ChameleonCache;
7use super::psi_builder::PsiBuilder;
8
9#[derive(Default)]
10pub struct TreeSink {
11    tree: TreeBuilder,
12    cache: Option<ChameleonCache>,
13    pub(super) errors: Vec<String>,
14    pub(super) missed_tokens: Vec<MissedTokens>,
15}
16
17impl TreeSink {
18    pub fn new() -> TreeSink {
19        TreeSink::default()
20    }
21
22    /// A sink sized for the tree of `builder`'s file, chameleons included.
23    pub(crate) fn for_file(builder: &PsiBuilder, cache: Option<ChameleonCache>) -> TreeSink {
24        // Chameleons re-cut the file's own lexemes, so leaves <= lexemes; nodes are fewer in practice.
25        let elements = 2 * builder.lexeme_count() + 1;
26        TreeSink { tree: TreeBuilder::with_capacity(elements, builder.text.len()), cache, ..TreeSink::default() }
27    }
28
29    pub fn with_cache(cache: ChameleonCache) -> TreeSink {
30        TreeSink { cache: Some(cache), ..TreeSink::default() }
31    }
32
33    pub fn take_cache(&mut self) -> Option<ChameleonCache> {
34        self.cache.take()
35    }
36
37    pub fn finish(self) -> Parse {
38        Parse { tree: self.tree.finish().into(), error_messages: self.errors, missed_tokens: self.missed_tokens }
39    }
40
41    /// Emits the expanded chameleon `kind` over `text`: the cached subtree if there is one, else
42    /// whatever `build` emits (one root node of `kind`), remembered when it added no errors.
43    pub fn chameleon(&mut self, kind: SyntaxKind, text: &str, build: impl FnOnce(&mut TreeSink)) {
44        let Some(cache) = &self.cache else { return build(self) };
45        if let Some(subtree) = cache.get(kind, text) {
46            self.tree.push_tree(subtree);
47            return;
48        }
49        let (root, errors, missed) = (self.tree.len(), self.errors.len(), self.missed_tokens.len());
50        build(self);
51        if self.errors.len() == errors && self.missed_tokens.len() == missed {
52            let subtree = self.tree.extract(root);
53            self.cache.as_mut().expect("checked above").insert(subtree);
54        }
55    }
56
57    pub(super) fn len(&self) -> ktrs_syntax::ElementId {
58        self.tree.len()
59    }
60
61    pub(super) fn token(&mut self, kind: SyntaxKind, text: &str) {
62        self.tree.token(kind, text);
63    }
64
65    pub(super) fn start_node(&mut self, kind: SyntaxKind) {
66        self.tree.start_node(kind);
67    }
68
69    pub(super) fn finish_node(&mut self) {
70        self.tree.finish_node();
71    }
72}