Skip to main content

vvv_engine/protocol/
template.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use crate::Match;
6
7use vvv_core::{CaptureValue, SourceText};
8
9/// Replacement text with meta-variable holes: `bar($$$ARGS)`, `$NAME_v2`.
10///
11/// Variables are `$NAME` (single capture) or `$$$NAME` (sequence capture);
12/// a name is `[A-Z_][A-Z0-9_]*`. Anything else is literal.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(transparent)]
15pub struct Template {
16    source: String,
17}
18
19#[derive(Debug, thiserror::Error, PartialEq, Eq)]
20pub enum TemplateError {
21    #[error("template refers to `${0}` but the match has no such capture")]
22    UnknownVariable(String),
23}
24
25#[derive(Debug, PartialEq, Eq)]
26enum Piece<'t> {
27    Literal(&'t str),
28    Variable(&'t str),
29}
30
31impl Template {
32    pub fn new(source: impl Into<String>) -> Self {
33        Self {
34            source: source.into(),
35        }
36    }
37
38    pub fn as_str(&self) -> &str {
39        &self.source
40    }
41
42    /// Fill the holes with the captures of `m`, reading sequence captures
43    /// from `source` so the original punctuation between items is kept.
44    pub fn expand(&self, m: &Match, source: &SourceText) -> Result<String, TemplateError> {
45        let mut out = String::with_capacity(self.source.len());
46        for piece in self.pieces() {
47            match piece {
48                Piece::Literal(text) => out.push_str(text),
49                Piece::Variable(name) => match m.capture(name) {
50                    Some(CaptureValue::Single(c)) => out.push_str(&c.text),
51                    Some(CaptureValue::Multiple(items)) => {
52                        if let (Some(first), Some(last)) = (items.first(), items.last()) {
53                            out.push_str(source.slice(first.span.union(&last.span)));
54                        }
55                    }
56                    None => return Err(TemplateError::UnknownVariable(name.to_owned())),
57                },
58            }
59        }
60        Ok(out)
61    }
62
63    fn pieces(&self) -> Vec<Piece<'_>> {
64        let src = self.source.as_str();
65        let mut pieces = Vec::new();
66        let mut literal_start = 0;
67        let mut i = 0;
68        while i < src.len() {
69            if src.as_bytes()[i] != b'$' {
70                i += 1;
71                continue;
72            }
73            let dollars = src[i..].bytes().take_while(|&b| b == b'$').count();
74            let name_start = i + dollars;
75            let name_len = Self::variable_name_len(&src[name_start..]);
76            if (dollars == 1 || dollars == 3) && name_len > 0 {
77                if literal_start < i {
78                    pieces.push(Piece::Literal(&src[literal_start..i]));
79                }
80                pieces.push(Piece::Variable(&src[name_start..name_start + name_len]));
81                i = name_start + name_len;
82                literal_start = i;
83            } else {
84                i = name_start.max(i + 1);
85            }
86        }
87        if literal_start < src.len() {
88            pieces.push(Piece::Literal(&src[literal_start..]));
89        }
90        pieces
91    }
92
93    fn variable_name_len(s: &str) -> usize {
94        let mut bytes = s.bytes();
95        match bytes.next() {
96            Some(b) if b.is_ascii_uppercase() || b == b'_' => {}
97            _ => return 0,
98        }
99        1 + bytes
100            .take_while(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || *b == b'_')
101            .count()
102    }
103}
104
105impl fmt::Display for Template {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.write_str(&self.source)
108    }
109}
110
111impl From<&str> for Template {
112    fn from(s: &str) -> Self {
113        Template::new(s)
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use std::collections::BTreeMap;
120
121    use super::*;
122    use crate::MatchId;
123    use vvv_core::{Capture, LanguageId, Position, Span};
124
125    fn fixture() -> (Match, SourceText) {
126        let source = SourceText::new("foo(a, b)");
127        let captures = BTreeMap::from([
128            (
129                "F".to_owned(),
130                CaptureValue::Single(Capture {
131                    span: Span::new(0, 3),
132                    text: "foo".into(),
133                }),
134            ),
135            (
136                "ARGS".to_owned(),
137                CaptureValue::Multiple(vec![
138                    Capture {
139                        span: Span::new(4, 5),
140                        text: "a".into(),
141                    },
142                    Capture {
143                        span: Span::new(5, 6),
144                        text: ",".into(),
145                    },
146                    Capture {
147                        span: Span::new(7, 8),
148                        text: "b".into(),
149                    },
150                ]),
151            ),
152            ("NONE".to_owned(), CaptureValue::Multiple(vec![])),
153        ]);
154        let m = Match {
155            id: MatchId::derive(&vvv_core::RelPath::from("x"), Span::new(0, 9), "foo(a, b)"),
156            path: "x".into(),
157            language: LanguageId::new("t"),
158            span: Span::new(0, 9),
159            start: Position::new(0, 0),
160            end: Position::new(0, 9),
161            kind: "call".into(),
162            text: "foo(a, b)".into(),
163            line: "foo(a, b)".into(),
164            captures,
165            symbol: None,
166            role: vvv_core::Role::Use,
167            address: None,
168        };
169        (m, source)
170    }
171
172    #[test]
173    fn tokenizes_variables_and_literals() {
174        let t = Template::new("$F_v2($$$ARGS) $ $$X $lower");
175        assert_eq!(
176            t.pieces(),
177            vec![
178                Piece::Variable("F_"),
179                Piece::Literal("v2("),
180                Piece::Variable("ARGS"),
181                Piece::Literal(") $ $$X $lower"),
182            ]
183        );
184    }
185
186    #[test]
187    fn expands_single_and_sequence_captures() {
188        let (m, src) = fixture();
189        let out = Template::new("bar($$$ARGS, $F)[$$$NONE]")
190            .expand(&m, &src)
191            .unwrap();
192        assert_eq!(out, "bar(a, b, foo)[]");
193    }
194
195    #[test]
196    fn unknown_variable_is_an_error() {
197        let (m, src) = fixture();
198        assert_eq!(
199            Template::new("$NOPE").expand(&m, &src),
200            Err(TemplateError::UnknownVariable("NOPE".into()))
201        );
202    }
203}