Skip to main content

tour_core/
visitor.rs

1use std::borrow::Cow;
2
3use crate::{Delimiter, Result};
4
5/// This trait represents a visitor that collect input sources through a [`Parser`][super::Parser].
6pub trait Visitor<'a>: Sized {
7    /// Collect static content.
8    fn visit_static(&mut self, source: &'a str) -> Result<()>;
9
10    /// Collect expression.
11    fn visit_expr(&mut self, source: &'a str, delim: Delimiter) -> Result<()>;
12
13    /// Final check on finish parsing.
14    fn finish(self) -> Result<Self>;
15}
16
17/// [`Visitor`] implementation that only collect static content.
18//
19// this is used in runtime template reloading
20pub struct StaticVisitor<'a> {
21    pub statics: Vec<Cow<'a,str>>
22}
23
24impl StaticVisitor<'_> {
25    /// Create new [`StaticVisitor`].
26    pub fn new() -> Self {
27        Self { statics: vec![] }
28    }
29
30    /// Convert statics into owned [`String`].
31    pub fn into_owned(self) -> StaticVisitor<'static> {
32        StaticVisitor {
33            statics: self
34                .statics
35                .into_iter()
36                .map(|e| Cow::Owned(e.into_owned()))
37                .collect(),
38        }
39    }
40}
41
42impl<'a> Visitor<'a> for StaticVisitor<'a> {
43    fn visit_static(&mut self, source: &'a str) -> Result<()> {
44        self.statics.push(Cow::Borrowed(source));
45        Ok(())
46    }
47
48    fn visit_expr(&mut self, _: &'a str, _: Delimiter) -> Result<()> {
49        Ok(())
50    }
51
52    fn finish(self) -> Result<Self> {
53        Ok(self)
54    }
55}
56
57impl Default for StaticVisitor<'_> {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62