Skip to main content

hemplate_parser/
lib.rs

1#![warn(missing_docs)]
2//! hemplate-parser: Tree-sitter based parser for hemplate templates.
3
4use tree_sitter::{LanguageError, Tree};
5use tree_sitter_hemplate::LANGUAGE;
6
7/// A reusable hemplate parser for latency-sensitive or repeated parsing.
8///
9/// Constructing and configuring tree-sitter is materially more expensive than parsing small
10/// templates. Keep one parser per sequential parsing context, such as an editor document store.
11pub struct TemplateParser {
12    parser: tree_sitter::Parser,
13}
14
15impl TemplateParser {
16    /// Construct a parser configured for the hemplate grammar.
17    pub fn new() -> Result<Self, LanguageError> {
18        let mut parser = tree_sitter::Parser::new();
19        parser.set_language(&LANGUAGE.into())?;
20        Ok(Self { parser })
21    }
22
23    /// Parse source text, optionally using an edited previous tree for incremental parsing.
24    pub fn parse(&mut self, input: &str, old_tree: Option<&Tree>) -> Option<Tree> {
25        self.parser.parse(input, old_tree)
26    }
27}
28
29/// Parse one hemplate template into a tree-sitter `Tree`.
30///
31/// This convenience function configures a fresh parser. Repeated or latency-sensitive callers
32/// should retain a [`TemplateParser`] instead.
33pub fn parse_template<T: AsRef<str> + ?Sized>(input: &T, old_tree: Option<&Tree>) -> Option<Tree> {
34    TemplateParser::new().ok()?.parse(input.as_ref(), old_tree)
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn reusable_parser_parses_sequential_templates() {
43        let mut parser = TemplateParser::new().expect("hemplate grammar must load");
44        let first = parser.parse("<p>first</p>", None).expect("first parse");
45        let second = parser
46            .parse("<section>second</section>", None)
47            .expect("second parse");
48
49        assert_eq!(first.root_node().end_byte(), "<p>first</p>".len());
50        assert_eq!(
51            second.root_node().end_byte(),
52            "<section>second</section>".len()
53        );
54    }
55}