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