Skip to main content

tramlines_core/grammar/
shape.rs

1//! The shape of one unit (`TL_22` to `TL_26`): exact `text`, a `template` with typed
2//! holes, or a `pattern` regex, one key per meaning wherever a rule
3//! declares a shape. Every shape reads the unit's text squashed, each run
4//! of whitespace one space.
5
6use regex::{Captures, Regex};
7
8use super::{LineTemplate, RegexCache, Text, TypeRegistry, template};
9use crate::{Problem, Spanned, text};
10
11/// A unit's shape.
12#[derive(Debug, Clone)]
13pub enum Shape {
14    /// `text`: what the text must equal, or the frontmatter key whose value
15    /// it must equal.
16    Text(Text),
17    /// `template`: the text written with typed holes.
18    Template(LineTemplate),
19    /// `pattern`: a regex the text must match somewhere.
20    Pattern(Regex),
21}
22
23impl Shape {
24    /// The shape's regex, whose named groups are the keys it can capture;
25    /// none for `text`.
26    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    /// Whether `text`, squashed, has this shape. `value` resolves a
35    /// `{ from: <key> }` text to the frontmatter value, squashed.
36    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    /// The groups the shape captures from `text`.
46    pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
47        self.regex()?.captures(text)
48    }
49
50    /// Whether the shape holds a group named `name`.
51    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    /// Why `text` does not have this shape, as a finding continues a
57    /// sentence that opens with the text: `does not match …` or `fails at
58    /// column …`. `text` names the shape of a literal.
59    pub fn failure(&self, text: &str) -> String {
60        self.failure_quoting(text, &Quote::same(text))
61    }
62
63    /// As `failure`, for a `text` that a format grammar read in another
64    /// spelling: the column and the text found of a template come from
65    /// `quote`, the text as written.
66    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    /// The shape as a format grammar reads it: each literal text read
76    /// through `read`, which reads a text in the grammar's spelling, a
77    /// template read whole with each hole as a placeholder, and a pattern
78    /// and a frontmatter key as they are.
79    #[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    /// How far into `text` the shape matched before it failed, for the
89    /// furthest-failure choice between shapes: a template and a text know,
90    /// a regex does not.
91    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    /// The shape as a finding or a label names it.
100    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
110// sokf:begin shape-of
111/// The shape a rule map declares, from its `text`, `template` or `pattern`,
112/// or `None` where it declares none. Two are refused: a rule has one shape.
113/// `text` may be `{ from: <key> }` where `from` is allowed.
114// sokf-implements: TL_22
115// sokf-implements: TL_118
116pub 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}
154// sokf:end shape-of
155
156/// A string as a `heading` short form, or as `text` a template may hold:
157/// a template when it has a hole, else exact text.
158pub 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
166/// Whether `s` holds a `${`, not escaped as `$${`.
167pub 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/// A text squashed, each run of whitespace one space and the ends trimmed,
179/// with the byte offset in the original text of each byte of the result
180/// and one past the end, so a position found in the squashed text maps
181/// back to the text as written.
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct Squashed {
184    /// The squashed text.
185    pub text: String,
186    /// `map[i]` is the offset in the original text of byte `i`.
187    pub map: Vec<usize>,
188}
189
190// sokf-implements: TL_23
191// sokf-implements: TLMD_6
192impl Squashed {
193    /// `text` squashed.
194    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    /// `text`, whose byte `i` stands for byte `map[i]` of another text,
218    /// squashed, each byte of the result mapped to that other text. `map`
219    /// holds one entry past the end of `text`.
220    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    /// The offset in the original text of offset `i` of the squashed one.
230    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/// How a finding quotes a text that a shape read in another spelling: the
239/// text as written, and the offset in it of each offset of the text as
240/// read, up to one past its end.
241#[derive(Clone, Copy)]
242pub struct Quote<'a> {
243    /// The text as written.
244    pub text: &'a str,
245    /// The offset in `text` of an offset of the text as read.
246    pub at: &'a dyn Fn(usize) -> usize,
247}
248
249impl<'a> Quote<'a> {
250    /// A text quoted as it was read.
251    pub fn same(text: &'a str) -> Quote<'a> {
252        Quote { text, at: &|i| i }
253    }
254
255    /// The offset in the text as written of offset `i` of the text as
256    /// read, on a character boundary.
257    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
271/// `text` with each run of whitespace one space and the ends trimmed.
272pub 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        // The text holds the whole squashed literal, `a b`, and goes on.
294        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        // `a  _b_` read from `a  *b*`: the same length, mapped one to one,
310        // and `x` read from `\\x`, the backslash dropped.
311        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    // sokf-tests: TL_23
320    // sokf-tests: TL_24
321    proptest! {
322        #![proptest_config(ProptestConfig::with_cases(256))]
323
324        /// The squashed text is `squash`, and each of its bytes maps back
325        /// to the same byte of the text as written, a space to a space.
326        #[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}