1use regex::{Captures, Regex};
7
8use super::{LineTemplate, RegexCache, Text, TypeRegistry, template};
9use crate::{Problem, Spanned, text};
10
11#[derive(Debug, Clone)]
13pub enum Shape {
14 Text(Text),
17 Template(LineTemplate),
19 Pattern(Regex),
21}
22
23impl Shape {
24 pub fn regex(&self) -> Option<&Regex> {
27 match self {
28 Shape::Text(_) => None,
29 Shape::Template(t) => Some(t.regex()),
30 Shape::Pattern(p) => Some(p),
31 }
32 }
33
34 pub fn matches(&self, text: &str, value: impl Fn(&str) -> Option<String>) -> bool {
37 match self {
38 Shape::Text(Text::Literal(want)) => squash(want) == text,
39 Shape::Text(Text::From(key)) => value(key).is_some_and(|v| squash(&v) == text),
40 Shape::Template(t) => t.is_match(text),
41 Shape::Pattern(p) => p.is_match(text),
42 }
43 }
44
45 pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
47 self.regex()?.captures(text)
48 }
49
50 pub fn has_group(&self, name: &str) -> bool {
52 self.regex()
53 .is_some_and(|r| r.capture_names().flatten().any(|n| n == name))
54 }
55
56 pub fn failure(&self, text: &str) -> String {
60 self.failure_quoting(text, &Quote::same(text))
61 }
62
63 pub fn failure_quoting(&self, text: &str, quote: &Quote<'_>) -> String {
67 match self {
68 Shape::Text(Text::Literal(want)) => format!("must read {}", text::code(&squash(want))),
69 Shape::Text(Text::From(key)) => format!("must equal the frontmatter `{key}`"),
70 Shape::Template(t) => format!("fails at {}", t.failure(text).quoted(quote)),
71 Shape::Pattern(p) => format!("does not match {}", text::code(p.as_str())),
72 }
73 }
74
75 #[must_use]
80 pub fn read_with(&self, read: &dyn Fn(&str) -> String) -> Shape {
81 match self {
82 Shape::Text(Text::Literal(want)) => Shape::Text(Text::Literal(read(want))),
83 Shape::Template(t) => Shape::Template(t.read_with(read).unwrap_or_else(|| t.clone())),
84 other => other.clone(),
85 }
86 }
87
88 pub fn reach(&self, text: &str) -> usize {
92 match self {
93 Shape::Template(t) => t.failure(text).reach,
94 Shape::Text(Text::Literal(want)) => template::common_prefix(&squash(want), text),
95 _ => 0,
96 }
97 }
98
99 pub fn label(&self) -> String {
101 match self {
102 Shape::Text(Text::Literal(t)) => t.clone(),
103 Shape::Text(Text::From(k)) => format!("<{k}>"),
104 Shape::Template(t) => t.source.clone(),
105 Shape::Pattern(p) => format!("/{}/", p.as_str()),
106 }
107 }
108}
109
110pub fn shape_of(
117 node: &Spanned,
118 types: &TypeRegistry,
119 regexes: &RegexCache,
120) -> Result<Option<Shape>, Problem> {
121 let declared: Vec<&str> = ["text", "template", "pattern"]
122 .into_iter()
123 .filter(|k| node.get(k).is_some())
124 .collect();
125 if declared.len() > 1 {
126 return Err(Problem::new(
127 "TL_22",
128 format!(
129 "`{}` and `{}` beside each other: a rule has one shape",
130 declared[0], declared[1]
131 ),
132 ));
133 }
134 if let Some(t) = node.get("text") {
135 return Ok(match t.as_str() {
136 Some(s) => Some(Shape::Text(Text::Literal(s.to_string()))),
137 None => t
138 .get("from")
139 .and_then(|f| f.as_str())
140 .map(|k| Shape::Text(Text::From(k.to_string()))),
141 });
142 }
143 if let Some(t) = node.get("template").and_then(|t| t.as_str()) {
144 return LineTemplate::parse(t, types).map(|t| Some(Shape::Template(t)));
145 }
146 if let Some(p) = node.get("pattern").and_then(|p| p.as_str()) {
147 return regexes
148 .get(p)
149 .map(|r| Some(Shape::Pattern(r)))
150 .map_err(|e| Problem::new("TL_118", e));
151 }
152 Ok(None)
153}
154pub fn text_or_template(s: &str, types: &TypeRegistry) -> Result<Shape, Problem> {
159 if has_hole(s) {
160 LineTemplate::parse(s, types).map(Shape::Template)
161 } else {
162 Ok(Shape::Text(Text::Literal(s.to_string())))
163 }
164}
165
166pub fn has_hole(s: &str) -> bool {
168 let mut rest = s;
169 while let Some(i) = rest.find("${") {
170 if i == 0 || !rest[..i].ends_with('$') {
171 return true;
172 }
173 rest = &rest[i + 2..];
174 }
175 false
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct Squashed {
184 pub text: String,
186 pub map: Vec<usize>,
188}
189
190impl Squashed {
193 pub fn new(text: &str) -> Squashed {
195 let mut out = String::with_capacity(text.len());
196 let mut map = Vec::with_capacity(text.len() + 1);
197 let mut pending: Option<usize> = None;
198 for (i, c) in text.char_indices() {
199 if c.is_whitespace() {
200 if !out.is_empty() && pending.is_none() {
201 pending = Some(i);
202 }
203 continue;
204 }
205 if let Some(at) = pending.take() {
206 out.push(' ');
207 map.push(at);
208 }
209 let start = out.len();
210 out.push(c);
211 map.extend((0..out.len() - start).map(|k| i + k));
212 }
213 map.push(text.trim_end().len());
214 Squashed { text: out, map }
215 }
216
217 pub fn mapped(text: &str, map: &[usize]) -> Squashed {
221 let own = Squashed::new(text);
222 let to = |i: usize| map.get(i).copied().unwrap_or(*map.last().unwrap_or(&0));
223 Squashed {
224 map: own.map.iter().map(|&i| to(i)).collect(),
225 text: own.text,
226 }
227 }
228
229 pub fn original(&self, i: usize) -> usize {
231 self.map
232 .get(i)
233 .copied()
234 .unwrap_or(*self.map.last().unwrap_or(&0))
235 }
236}
237
238#[derive(Clone, Copy)]
242pub struct Quote<'a> {
243 pub text: &'a str,
245 pub at: &'a dyn Fn(usize) -> usize,
247}
248
249impl<'a> Quote<'a> {
250 pub fn same(text: &'a str) -> Quote<'a> {
252 Quote { text, at: &|i| i }
253 }
254
255 pub fn offset(&self, i: usize) -> usize {
258 self.text
259 .floor_char_boundary((self.at)(i).min(self.text.len()))
260 }
261}
262
263impl std::fmt::Debug for Quote<'_> {
264 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265 f.debug_struct("Quote")
266 .field("text", &self.text)
267 .finish_non_exhaustive()
268 }
269}
270
271pub fn squash(text: &str) -> String {
273 text.split_whitespace().collect::<Vec<_>>().join(" ")
274}
275
276#[cfg(test)]
277mod tests {
278 use proptest::prelude::*;
279
280 use super::*;
281
282 #[test]
283 fn a_hole_is_a_dollar_brace_not_escaped() {
284 assert!(has_hole("a ${x}"));
285 assert!(has_hole("$${a} ${b}"));
286 assert!(!has_hole("$${a} and $5"));
287 assert!(!has_hole("plain"));
288 }
289
290 #[test]
291 fn a_literal_reaches_no_further_than_its_squashed_text() {
292 let shape = Shape::Text(Text::Literal("a b".into()));
293 assert_eq!(shape.reach("a bc"), 3);
295 assert_eq!(shape.reach("a b"), 3);
296 assert_eq!(shape.reach("a c"), 2);
297 }
298
299 #[test]
300 fn one_shape_per_rule() {
301 let node = crate::yaml::parse("text: a\npattern: b\n", 1).unwrap();
302 let e = shape_of(&node, &TypeRegistry::built_ins(), &RegexCache::new()).unwrap_err();
303 assert!(e.message.contains("one shape"), "{e:?}");
304 assert_eq!(e.criterion, "TL_22");
305 }
306
307 #[test]
308 fn a_mapped_text_squashes_and_maps_to_the_other_text() {
309 let s = Squashed::mapped("a _b_", &[0, 1, 2, 3, 4, 5, 6]);
312 assert_eq!(s.text, "a _b_");
313 assert_eq!(s.map, vec![0, 1, 3, 4, 5, 6]);
314 let s = Squashed::mapped(" x", &[0, 2, 3]);
315 assert_eq!(s.text, "x");
316 assert_eq!(s.map, vec![2, 3]);
317 }
318
319 proptest! {
322 #![proptest_config(ProptestConfig::with_cases(256))]
323
324 #[test]
327 fn a_squashed_text_maps_back(text in "[ a-z\\t\\n]{0,24}") {
328 let s = Squashed::new(&text);
329 prop_assert_eq!(&s.text, &squash(&text));
330 for (i, b) in s.text.bytes().enumerate() {
331 let o = s.original(i);
332 if b == b' ' {
333 prop_assert!(text.as_bytes()[o].is_ascii_whitespace());
334 } else {
335 prop_assert_eq!(text.as_bytes()[o], b);
336 }
337 }
338 }
339 }
340}