1use std::{cell::RefCell, collections::HashMap, sync::OnceLock};
7
8use regex::Regex;
9
10use super::{
11 Quote,
12 types::{TypeDef, TypeRegistry, is_hole_name},
13};
14use crate::{Problem, text};
15
16pub const HOLE: char = '\u{E000}';
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Segment {
24 Literal(String),
26 Hole {
28 name: Option<String>,
30 ty: String,
32 def: TypeDef,
34 },
35}
36
37impl Segment {
38 fn describe(&self) -> String {
40 match self {
41 Segment::Literal(l) => text::code(l),
42 Segment::Hole { ty, def, .. } => {
43 format!("{} `{ty}` ({})", text::article(ty), def.describe())
44 }
45 }
46 }
47
48 fn regex(&self) -> String {
49 match self {
50 Segment::Literal(l) => regex::escape(l),
51 Segment::Hole {
52 name: Some(n), def, ..
53 } => format!("(?P<{n}>{})", def.regex()),
54 Segment::Hole {
55 name: None, def, ..
56 } => def.regex(),
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Failure {
64 pub offset: usize,
66 pub expected: String,
68 pub reach: usize,
72 pub segment: usize,
76}
77
78impl Failure {
79 pub fn describe(&self, text: &str) -> String {
82 self.quoted(&Quote::same(text))
83 }
84
85 pub fn quoted(&self, quote: &Quote<'_>) -> String {
89 let text = quote.text;
90 let offset = quote.offset(self.offset);
91 let column = column(text, offset);
92 let rest = &text[offset..];
93 let found = if rest.is_empty() {
94 "the end".to_string()
95 } else if rest.chars().count() > 24 {
96 text::code(&format!("{}…", rest.chars().take(23).collect::<String>()))
97 } else {
98 text::code(rest)
99 };
100 format!("column {column}: expected {}, found {found}", self.expected)
101 }
102}
103
104#[derive(Debug, Clone)]
106pub struct Template {
107 pub source: String,
109 pub segments: Vec<Segment>,
111 written: Vec<Segment>,
115 regex: Regex,
117 prefixes: OnceLock<Vec<Regex>>,
120}
121
122thread_local! {
123 static COMPILED: RefCell<HashMap<String, Regex>> = RefCell::new(HashMap::new());
127}
128
129pub(super) fn compiled(re: &str) -> Result<Regex, regex::Error> {
131 if let Some(hit) = COMPILED.with(|c| c.borrow().get(re).cloned()) {
132 return Ok(hit);
133 }
134 let r = Regex::new(re)?;
135 COMPILED.with(|c| c.borrow_mut().insert(re.to_string(), r.clone()));
136 Ok(r)
137}
138
139impl PartialEq for Template {
140 fn eq(&self, other: &Self) -> bool {
141 self.source == other.source && self.segments == other.segments
142 }
143}
144
145impl Template {
146 pub fn parse(source: &str, types: &TypeRegistry) -> Result<Template, Problem> {
156 let mut segments = Vec::new();
157 let mut literal = String::new();
158 let mut rest = source;
159 let mut names: Vec<String> = Vec::new();
160 while let Some(c) = rest.chars().next() {
161 if let Some(after) = rest.strip_prefix("$${") {
162 literal.push_str("${");
163 rest = after;
164 continue;
165 }
166 let Some(after) = rest.strip_prefix("${") else {
167 literal.push(c);
168 rest = &rest[c.len_utf8()..];
169 continue;
170 };
171 let Some(end) = after.find('}') else {
172 return Err(Problem::new(
173 "TL_121",
174 format!(
175 "template {source} has an unclosed `${{`",
176 source = text::code(source)
177 ),
178 ));
179 };
180 let inside = &after[..end];
181 rest = &after[end + 1..];
182 let (name, ty) = match inside.split_once(':') {
183 Some((n, t)) => (n, t),
184 None => (inside, "text"),
185 };
186 let name = if name.is_empty() {
187 None
188 } else if !is_hole_name(name) {
189 return Err(Problem::new(
190 "TL_121",
191 format!(
192 "template {source}: hole name `{name}` must be letters, digits and `_`, not starting with a digit",
193 source = text::code(source)
194 ),
195 ));
196 } else if names.iter().any(|n| n == name) {
197 return Err(Problem::new(
198 "TL_119",
199 format!(
200 "template {source} names the hole `{name}` twice",
201 source = text::code(source)
202 ),
203 ));
204 } else {
205 names.push(name.to_string());
206 Some(name.to_string())
207 };
208 let ty = if ty.is_empty() { "text" } else { ty };
209 let Some(def) = types.get(ty) else {
210 return Err(Problem::new(
211 "TL_120",
212 format!(
213 "template {source}: no type `{ty}`",
214 source = text::code(source)
215 ),
216 ));
217 };
218 if !literal.is_empty() {
219 segments.push(Segment::Literal(std::mem::take(&mut literal)));
220 }
221 segments.push(Segment::Hole {
222 name,
223 ty: ty.to_string(),
224 def: def.clone(),
225 });
226 }
227 if !literal.is_empty() {
228 segments.push(Segment::Literal(literal));
229 }
230 if !segments.iter().any(|s| matches!(s, Segment::Hole { .. })) {
231 return Err(Problem::new(
232 "TL_25",
233 format!(
234 "template {source} has no hole; write it as `text`",
235 source = text::code(source)
236 ),
237 ));
238 }
239 Template::of(source, segments)
240 }
241
242 fn of(source: &str, segments: Vec<Segment>) -> Result<Template, Problem> {
244 let body: String = segments.iter().map(Segment::regex).collect();
245 let regex = compiled(&format!("^(?:{body})$")).map_err(|e| {
246 Problem::new(
247 "TL_118",
248 format!(
249 "template {source} does not compile: {}",
250 super::regex::reason(&e),
251 source = text::code(source)
252 ),
253 )
254 })?;
255 Ok(Template {
256 source: source.to_string(),
257 regex,
258 segments,
259 written: Vec::new(),
260 prefixes: OnceLock::new(),
261 })
262 }
263
264 pub fn read_with(&self, read: &dyn Fn(&str) -> String) -> Option<Template> {
273 let mut text = String::new();
274 for s in &self.segments {
275 match s {
276 Segment::Literal(l) => text.push_str(l),
277 Segment::Hole { .. } => text.push(HOLE),
278 }
279 }
280 let read = read(&text);
281 if read == text {
282 return Some(self.clone());
283 }
284 let mut parts = read.split(HOLE);
285 let mut segments = Vec::with_capacity(self.segments.len());
286 let mut literal = false;
287 for s in &self.segments {
288 match s {
289 Segment::Literal(_) => literal = true,
290 hole @ Segment::Hole { .. } => {
291 let part = parts.next()?;
292 if literal == part.is_empty() {
293 return None;
294 }
295 if literal {
296 segments.push(Segment::Literal(part.to_string()));
297 }
298 segments.push(hole.clone());
299 literal = false;
300 }
301 }
302 }
303 let last = parts.next()?;
304 if parts.next().is_some() || literal == last.is_empty() {
305 return None;
306 }
307 if literal {
308 segments.push(Segment::Literal(last.to_string()));
309 }
310 let mut out = Template::of(&self.source, segments).ok()?;
311 out.written.clone_from(&self.segments);
312 Some(out)
313 }
314
315 fn respelt(&self, i: usize) -> bool {
317 matches!(
318 (self.segments.get(i), self.written.get(i)),
319 (Some(Segment::Literal(l)), Some(Segment::Literal(w))) if w != l
320 )
321 }
322
323 fn literal_shown(&self, i: usize, from: usize) -> String {
327 match (self.segments.get(i), self.written.get(i)) {
328 (Some(Segment::Literal(l)), Some(Segment::Literal(w))) if w != l => text::code(w),
329 (Some(Segment::Literal(l)), _) => text::code(&l[from.min(l.len())..]),
330 (Some(hole), _) => hole.describe(),
331 (None, _) => "the end".to_string(),
332 }
333 }
334
335 fn prefixes(&self) -> &[Regex] {
338 self.prefixes.get_or_init(|| {
339 let mut body = String::new();
340 let mut out = vec![compiled("^").expect("an anchor compiles")];
341 for s in &self.segments {
342 body.push_str(&s.regex());
343 out.push(
344 compiled(&format!("^(?:{body})"))
345 .expect("a prefix of a template that compiled compiles"),
346 );
347 }
348 out
349 })
350 }
351
352 pub fn regex(&self) -> &Regex {
354 &self.regex
355 }
356
357 pub fn is_match(&self, text: &str) -> bool {
359 self.regex.is_match(text)
360 }
361
362 pub fn names(&self) -> impl Iterator<Item = &str> {
364 self.segments.iter().filter_map(|s| match s {
365 Segment::Hole { name: Some(n), .. } => Some(n.as_str()),
366 _ => None,
367 })
368 }
369
370 pub fn failure(&self, text: &str) -> Failure {
375 let n = self.segments.len();
376 let prefixes = self.prefixes();
377 let k = (0..=n)
378 .rev()
379 .find(|&i| prefixes[i].is_match(text))
380 .unwrap_or(0);
381 let end_of = |i: usize| prefixes[i].find(text).map_or(0, |m| m.end());
382 let at = |offset: usize, expected: String, reach: usize, segment: usize| Failure {
383 offset,
384 expected,
385 reach,
386 segment,
387 };
388 if k == n {
389 let end = end_of(n);
390 if let Some(h) = self.last_hole()
393 && let Some(f) = self.short_end(text, h, end_of(h))
394 {
395 return f;
396 }
397 return at(end, "the end".to_string(), end, n);
398 }
399 let end = end_of(k);
400 let prev = k.checked_sub(1).map(|p| &self.segments[p]);
401 match (prev, &self.segments[k]) {
402 (Some(Segment::Hole { .. }), _)
407 if end == text.len()
408 && self.last_hole() == Some(k - 1)
409 && let Some(f) = self.short_end(text, k - 1, end_of(k - 1)) =>
410 {
411 f
412 }
413 (Some(Segment::Hole { def, .. }), Segment::Literal(l))
417 if end == text.len() && !whole(def, &format!("{}{l}", &text[end_of(k - 1)..])) =>
418 {
419 at(text.len(), self.literal_shown(k, 0), text.len(), k)
420 }
421 (Some(Segment::Hole { .. }), _) if end == text.len() => at(
424 end_of(k - 1),
425 format!(
426 "{} then {}",
427 self.literal_shown(k - 1, 0),
428 self.literal_shown(k, 0)
429 ),
430 end,
431 k - 1,
432 ),
433 (Some(hole @ Segment::Hole { def, .. }), Segment::Literal(l))
437 if common_prefix(l, &text[end..]) == 0
438 && text[end..]
439 .find(l.as_str())
440 .is_some_and(|i| !whole(def, &text[end_of(k - 1)..end + i])) =>
441 {
442 at(end_of(k - 1), hole.describe(), end, k - 1)
443 }
444 (_, Segment::Literal(l)) => {
450 let shared = common_prefix(l, &text[end..]);
451 let offset = if self.respelt(k) { end } else { end + shared };
452 at(offset, self.literal_shown(k, shared), end + shared, k)
453 }
454 (_, hole) => at(end, hole.describe(), end, k),
455 }
456 }
457}
458
459impl Template {
460 fn last_hole(&self) -> Option<usize> {
462 let h = self
463 .segments
464 .iter()
465 .rposition(|s| matches!(s, Segment::Hole { .. }))?;
466 (h + 1 < self.segments.len()).then_some(h)
467 }
468
469 fn short_end(&self, text: &str, h: usize, start: usize) -> Option<Failure> {
473 let Segment::Hole { def, .. } = &self.segments[h] else {
474 return None;
475 };
476 let tail: String = self.segments[h + 1..]
477 .iter()
478 .map(|s| match s {
479 Segment::Literal(l) => l.as_str(),
480 Segment::Hole { .. } => "",
481 })
482 .collect();
483 let carried = (1..tail.len())
484 .rev()
485 .find(|&j| tail.is_char_boundary(j) && text.ends_with(&tail[..j]))
486 .unwrap_or(0);
487 let value = text.get(start..text.len() - carried)?;
488 let written: String = self
490 .written
491 .get(h + 1..)
492 .unwrap_or(&[])
493 .iter()
494 .map(|s| match s {
495 Segment::Literal(l) => l.as_str(),
496 Segment::Hole { .. } => "",
497 })
498 .collect();
499 let expected = if self.written.is_empty() || written == tail {
500 text::code(&tail[carried..])
501 } else {
502 text::code(&written)
503 };
504 whole(def, value).then(|| Failure {
505 offset: text.len(),
506 expected,
507 reach: text.len(),
508 segment: h + 1,
509 })
510 }
511}
512
513fn whole(def: &TypeDef, value: &str) -> bool {
515 compiled(&format!("^(?:{})$", def.regex())).is_ok_and(|r| r.is_match(value))
516}
517
518pub(super) fn column(text: &str, offset: usize) -> usize {
520 text[..offset.min(text.len())].chars().count() + 1
521}
522
523pub(super) fn common_prefix(a: &str, b: &str) -> usize {
526 a.char_indices()
527 .zip(b.chars())
528 .find(|((_, x), y)| x != y)
529 .map_or_else(|| a.len().min(b.len()), |((i, _), _)| i)
530}
531
532#[cfg(test)]
533mod tests {
534 use std::fmt::Write as _;
535
536 use proptest::prelude::*;
537
538 use super::*;
539 use crate::{grammar::FormatSource, yaml};
540
541 fn types() -> TypeRegistry {
542 let node = yaml::parse(
543 "code: '[A-Z]{1,10}'\nkind: [Performance, Capacity]\nlabel: '[^\"<]+'\n",
544 1,
545 )
546 .unwrap();
547 let (own, problems) =
548 TypeRegistry::from_yaml(&node, &FormatSource::Repo, &TypeRegistry::default());
549 assert!(problems.is_empty(), "{problems:?}");
550 TypeRegistry::built_ins().layered(&own)
551 }
552
553 fn t(src: &str) -> Template {
554 Template::parse(src, &types()).unwrap()
555 }
556
557 #[test]
558 fn parses_holes_escapes_and_literals() {
559 let tpl = t("${id:code}-${n:int} [x]: ${} $${a} costs $5 ${:kind}");
560 assert_eq!(tpl.names().collect::<Vec<_>>(), ["id", "n"]);
561 assert!(tpl.is_match("AB-12 [x]: any text ${a} costs $5 Capacity"));
562 assert!(!tpl.is_match("AB-12 [x]: any text ${a} costs $5 Speed"));
563 let caps = tpl
564 .regex()
565 .captures("AB-12 [x]: t ${a} costs $5 Performance")
566 .unwrap();
567 assert_eq!(&caps["id"], "AB");
568 assert_eq!(&caps["n"], "12");
569 assert!(t("a.b ${}").is_match("a.b c"));
571 assert!(!t("a.b ${}").is_match("axb c"));
572 }
573
574 #[test]
579 fn refuses_what_is_not_a_template() {
580 let ty = types();
581 for (bad, key, says) in [
582 ("no holes", "TL_25", "no hole"),
583 ("$${x}", "TL_25", "no hole"),
584 ("a ${x", "TL_121", "unclosed"),
585 ("${x:nope}", "TL_120", "no type `nope`"),
586 ("${x} ${x}", "TL_119", "twice"),
587 ("${1x}", "TL_121", "hole name"),
588 ("${a-b}", "TL_121", "hole name"),
589 ] {
590 let e = Template::parse(bad, &ty).unwrap_err();
591 assert!(e.message.contains(says), "{bad}: {e:?}");
592 assert_eq!(e.criterion, key, "{bad}");
593 }
594 }
595
596 #[test]
599 fn a_failure_names_the_column_and_what_was_expected() {
600 let tpl = t("${id:code} [event]: WHEN ${}, the ${} SHALL ${}.");
601 let text = "AB [state]: WHEN x, the y SHALL z.";
602 let f = tpl.failure(text);
603 assert_eq!(f.offset, 4);
604 assert_eq!(
605 f.describe(text),
606 "column 5: expected `event]: WHEN `, found `state]: WHEN x, the y S…`"
607 );
608 let text = "AB [event]: WHEN a user posts THEN the API SHALL go.";
609 let f = tpl.failure(text);
610 assert_eq!(f.offset, "AB [event]: WHEN ".len());
611 assert!(
612 f.expected.starts_with("a `text` (`.+`) then `, the `"),
613 "{f:?}"
614 );
615 let text = "AB [event]: WHEN x, the y SHALL z";
617 assert_eq!(
618 tpl.failure(text).describe(text),
619 "column 34: expected `.`, found the end"
620 );
621 let tpl = t("(${}.)");
622 assert_eq!(
623 tpl.failure("(x.").describe("(x."),
624 "column 4: expected `)`, found the end"
625 );
626 let tpl = t("${}.");
628 assert_eq!(
629 tpl.failure("Use version 1.2").describe("Use version 1.2"),
630 "column 16: expected `.`, found the end"
631 );
632 let tpl = t("${:code} x${:int}");
634 assert_eq!(
635 tpl.failure("AB").describe("AB"),
636 "column 3: expected ` x`, found the end"
637 );
638 let tpl = t("${:word} ${:slug} ${:int}");
640 let text = "x a--b 4";
641 let f = tpl.failure(text);
642 assert_eq!(
643 f.describe(text),
644 "column 3: expected a `slug` (`[a-z0-9]+(?:-[a-z0-9]+)*`), found `a--b 4`"
645 );
646 assert_eq!(f.reach, 3);
647 let tpl = t("${:int}.${:int} ${:kind}");
648 let text = "2.1 Speed";
649 let f = tpl.failure(text);
650 assert_eq!(
651 f.describe(text),
652 "column 5: expected a `kind` (one of `Performance`, `Capacity`), found `Speed`"
653 );
654 let tpl = t("x ${:int}");
655 assert_eq!(
656 tpl.failure("x 12 more").describe("x 12 more"),
657 "column 5: expected the end, found ` more`"
658 );
659 assert_eq!(
660 tpl.failure("y").describe("y"),
661 "column 1: expected `x `, found `y`"
662 );
663 assert_eq!(
664 tpl.failure("x").describe("x"),
665 "column 2: expected ` `, found the end"
666 );
667 }
668
669 #[test]
671 fn a_template_read_again_matches_the_reading_and_quotes_as_written() {
672 let read = |s: &str| s.replace('*', "_");
674 let written = t("*Note*: ${n:int} *x*");
675 let tpl = written
676 .read_with(&read)
677 .expect("the reading keeps each hole");
678 assert_eq!(tpl.source, "*Note*: ${n:int} *x*");
679 assert!(tpl.is_match("_Note_: 4 _x_"));
680 assert!(!tpl.is_match("*Note*: 4 *x*"));
681 let f = tpl.failure("_Nope_: 4 _x_");
684 assert_eq!((f.offset, f.segment), (0, 0));
685 assert_eq!(f.expected, "`*Note*: `");
686 let shown = "*Nope*: 4 *x*";
688 let at = |i: usize| i;
689 let quote = Quote {
690 text: shown,
691 at: &at,
692 };
693 assert_eq!(
694 f.quoted("e),
695 "column 1: expected `*Note*: `, found `*Nope*: 4 *x*`"
696 );
697 assert_eq!(t("a ${x}").read_with(&read), Some(t("a ${x}")));
699 assert_eq!(t("a ${x}").read_with(&|_: &str| "a".to_string()), None);
701 }
702
703 fn arb_line() -> impl Strategy<Value = (String, String, Vec<(String, String)>)> {
706 prop::collection::vec(
707 prop_oneof![
708 "[a-z:;,. ]{1,4}".prop_map(|l| (None, l)),
709 "[A-Z]{1,5}".prop_map(|v| (Some("code"), v)),
710 "[0-9]{1,3}".prop_map(|v| (Some("int"), v)),
711 ],
712 1..6,
713 )
714 .prop_filter("a template has a hole", |parts| {
715 parts.iter().any(|(ty, _)| ty.is_some())
716 })
717 .prop_map(|parts| {
718 let (mut src, mut line, mut values) = (String::new(), String::new(), Vec::new());
719 let mut last_hole = false;
720 for (i, (ty, v)) in parts.into_iter().enumerate() {
721 if let Some(ty) = ty {
722 if last_hole {
725 src.push('|');
726 line.push('|');
727 }
728 let _ = write!(src, "${{h{i}:{ty}}}");
729 line.push_str(&v);
730 values.push((format!("h{i}"), v));
731 last_hole = true;
732 } else {
733 src.push_str(&v);
734 line.push_str(&v);
735 last_hole = false;
736 }
737 }
738 (src, line, values)
739 })
740 }
741
742 proptest! {
745 #![proptest_config(ProptestConfig::with_cases(256))]
746
747 #[test]
750 fn a_rendered_line_matches_and_captures((src, line, values) in arb_line()) {
751 let tpl = t(&src);
752 let caps = tpl.regex().captures(&line);
753 prop_assert!(caps.is_some(), "{src} / {line}");
754 let caps = caps.unwrap();
755 for (name, value) in &values {
756 prop_assert_eq!(&caps[name.as_str()], value.as_str());
757 }
758 }
759
760 #[test]
763 fn a_changed_literal_fails_where_it_changed(
764 head in "[a-z]{1,6}",
765 tail in "[a-z]{1,6}",
766 value in "[A-Z]{1,5}",
767 ) {
768 let tpl = t(&format!("{head}: ${{v:code}} {tail}"));
769 let good = format!("{head}: {value} {tail}");
770 prop_assert!(tpl.is_match(&good));
771 let bad_tail: String = std::iter::once(if tail.starts_with('z') { 'y' } else { 'z' })
773 .chain(tail.chars().skip(1))
774 .collect();
775 let bad = format!("{head}: {value} {bad_tail}");
776 let changed = format!("{head}: {value} ").len();
777 let f = tpl.failure(&bad);
778 prop_assert!(f.offset <= changed && f.offset <= bad.len(), "{f:?}");
779 prop_assert!(!tpl.is_match(&bad));
780 }
781 }
782}