Skip to main content

tramlines_core/grammar/
template.rs

1//! Templates (`TL_24` to `TL_26`): the shape of one unit written as the unit itself,
2//! with typed holes, `${name:type}`, where it varies. A template compiles
3//! once to an anchored regex with one named group per named hole, and a
4//! failure names the column where the text stops matching.
5
6use 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
16/// The placeholder that stands for a hole while a format grammar reads the
17/// literals of a template whole: a private-use character, which is neither
18/// a space nor punctuation, so that it reads as a word does.
19pub const HOLE: char = '\u{E000}';
20
21/// One piece of a template.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Segment {
24    /// Text the unit carries as written.
25    Literal(String),
26    /// A hole: its name where it is captured, and its type.
27    Hole {
28        /// The name, which is the name of its group.
29        name: Option<String>,
30        /// The type's name.
31        ty: String,
32        /// The type, as the registry resolved it.
33        def: TypeDef,
34    },
35}
36
37impl Segment {
38    /// The segment as a failure names what it expected.
39    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/// Where a text stops matching a template, and what was expected there.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Failure {
64    /// The byte offset in the text where the fault is.
65    pub offset: usize,
66    /// What the template expected at the offset.
67    pub expected: String,
68    /// How far the text matches the template before it fails, which can
69    /// lie past the fault: of two shapes, the text meant the one it
70    /// follows furthest.
71    pub reach: usize,
72    /// The index in `Template::segments` of the segment that the fault
73    /// names first, or the number of segments where the text runs on past
74    /// the end of the template.
75    pub segment: usize,
76}
77
78impl Failure {
79    /// The failure as a finding says it: the column, one-based in
80    /// characters, what was expected and what was found.
81    pub fn describe(&self, text: &str) -> String {
82        self.quoted(&Quote::same(text))
83    }
84
85    /// As `describe`, for a text that a format grammar read in another
86    /// spelling: the column and the text found are those of `quote`, the
87    /// text as written, at the place of the fault.
88    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/// A compiled template.
105#[derive(Debug, Clone)]
106pub struct Template {
107    /// The template as written.
108    pub source: String,
109    /// Its pieces, in order.
110    pub segments: Vec<Segment>,
111    /// The pieces as the schema writes them, where a format grammar read
112    /// the template in another spelling through `read_with`, one for each
113    /// of `segments`; empty otherwise.
114    written: Vec<Segment>,
115    /// The anchored regex it compiles to.
116    regex: Regex,
117    /// `prefixes[i]` matches the first `i` segments at the start of a text;
118    /// compiled the first time a text fails, since most never do.
119    prefixes: OnceLock<Vec<Regex>>,
120}
121
122thread_local! {
123    /// Compiled regexes by source, so a template the layers compile again
124    /// for each schema costs one compilation per run, as a pattern does
125    /// through `RegexCache`.
126    static COMPILED: RefCell<HashMap<String, Regex>> = RefCell::new(HashMap::new());
127}
128
129/// `re` compiled, once per run and thread.
130pub(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    /// Parse and compile `source` against `types`. Refuses an unclosed
147    /// hole, a bad or repeated name, an unknown type, and a template with
148    /// no hole, which is text.
149    // sokf-implements: TL_24
150    // sokf-implements: TL_25
151    // sokf-implements: TL_118
152    // sokf-implements: TL_119
153    // sokf-implements: TL_120
154    // sokf-implements: TL_121
155    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    /// The template of `segments`, compiled, whose source is `source`.
243    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    /// The template as a format grammar reads it: its literals and a
265    /// placeholder for each hole, `HOLE`, read whole through `read`, then
266    /// split again at the placeholders, so that a literal is read in the
267    /// context of the template. The template keeps its source and its
268    /// literals as written, which a failure quotes. `None` where the
269    /// reading keeps no placeholder for each hole, or leaves a literal
270    /// empty, or the template no longer compiles.
271    // sokf-implements: TL_141
272    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    /// Whether a reading changed literal `i`.
316    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    /// Literal `i` from byte `from` on, quoted, as a failure names what it
324    /// expected: the literal as the schema writes it where a reading
325    /// changed it.
326    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    /// `prefixes[i]` matches the first `i` segments at the start of a text.
336    /// Each is a prefix of the template's own regex, which compiled.
337    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    /// The anchored regex, whose named groups are the named holes.
353    pub fn regex(&self) -> &Regex {
354        &self.regex
355    }
356
357    /// Whether `text` matches the template whole.
358    pub fn is_match(&self, text: &str) -> bool {
359        self.regex.is_match(text)
360    }
361
362    /// The names of the captured holes, in order.
363    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    /// Where `text` stops matching: the longest run of segments that
371    /// matches from its start, then the segment that does not.
372    // sokf-implements: TL_26
373    // sokf-implements: TL_74
374    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            // A literal end the hole before it reached inside the text, as
391            // a period in `1.2`, leaves the text short of the real end.
392            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            // A hole that ran to the end of a text that ends the template
403            // with literals leaves only those literals missing: the text
404            // stops short, so the fault is at its end, after any part of
405            // them that it carries.
406            (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            // A hole that ran to the end, where the literal after it could
414            // not be part of its value, ended the line at its own end: the
415            // line lacks only the rest of the template, so the fault is there.
416            (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            // A hole that ran to the end ate what the next segment wanted, so
422            // the failure is where the hole began, naming both.
423            (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            // A literal the text does not start to carry, after a hole: where
434            // the literal comes later, the text between is the value the
435            // writer meant for the hole, and the hole is what it fails.
436            (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            // A literal the text starts to carry fails where the two part,
445            // so of two templates that differ inside a literal the one the
446            // text follows further is the one it meant.
447            // A literal that a reading changed is quoted whole, as written,
448            // so the fault is where it starts.
449            (_, 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    /// The last hole, where only literals follow it to the end.
461    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    /// A text that stops short of the literal end of the template: the
470    /// last hole, from `start`, takes the rest of the text, less any part
471    /// of that end the text carries, so the fault is the rest of the end.
472    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        // A tail that a reading changed is quoted whole, as written.
489        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
513/// Whether the type `def` matches `value` whole.
514fn whole(def: &TypeDef, value: &str) -> bool {
515    compiled(&format!("^(?:{})$", def.regex())).is_ok_and(|r| r.is_match(value))
516}
517
518/// The one-based column, in characters, of the byte `offset` of `text`.
519pub(super) fn column(text: &str, offset: usize) -> usize {
520    text[..offset.min(text.len())].chars().count() + 1
521}
522
523/// The length in bytes of the longest common prefix of `a` and `b`, on a
524/// char boundary.
525pub(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        // Regex characters in the literal are text.
570        assert!(t("a.b ${}").is_match("a.b c"));
571        assert!(!t("a.b ${}").is_match("axb c"));
572    }
573
574    // sokf-tests: TL_25
575    // sokf-tests: TL_119
576    // sokf-tests: TL_120
577    // sokf-tests: TL_121
578    #[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    // sokf-tests: TL_26
597    // sokf-tests: TL_74
598    #[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        // A text that lacks only the end of the template stops short.
616        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        // A period inside the value does not end the template.
627        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        // A hole that can't take the rest of the template ends a short line.
633        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        // A hole the text gives a value it does not take is the fault.
639        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    // sokf-tests: TL_141
670    #[test]
671    fn a_template_read_again_matches_the_reading_and_quotes_as_written() {
672        // A reader that respells each `*` as `_`, as a format grammar can.
673        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        // The failure quotes the literal as written, from where it starts,
682        // and names its segment.
683        let f = tpl.failure("_Nope_: 4 _x_");
684        assert_eq!((f.offset, f.segment), (0, 0));
685        assert_eq!(f.expected, "`*Note*: `");
686        // A quote gives the column and the text of the text as written.
687        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(&quote),
695            "column 1: expected `*Note*: `, found `*Nope*: 4 *x*`"
696        );
697        // A reading that changes nothing gives the template back.
698        assert_eq!(t("a ${x}").read_with(&read), Some(t("a ${x}")));
699        // A reading that drops a hole gives none.
700        assert_eq!(t("a ${x}").read_with(&|_: &str| "a".to_string()), None);
701    }
702
703    /// A template of literals and holes of simple types, a line rendered
704    /// from it, and the value each hole took.
705    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                    // Two holes side by side split their text anyhow; a
723                    // literal between keeps each value its own.
724                    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    // sokf-tests: TL_24
743    // sokf-tests: TL_26
744    proptest! {
745        #![proptest_config(ProptestConfig::with_cases(256))]
746
747        /// A line rendered from a template, with values drawn from its hole
748        /// types, matches it and captures each value.
749        #[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        /// A changed literal fails at or before the column of the change,
761        /// and inside the line.
762        #[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            // Change the first letter of the tail.
772            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}