Skip to main content

tramlines_core/grammar/
format.rs

1//! One line format: its shapes, its bans, and how a line matches it
2//! (`TL_42`, `TL_74` to `TL_81`).
3
4use regex::Regex;
5
6use super::{Quote, RegexCache, Segment, Shape, TypeRegistry, shape_of, template};
7use crate::{Problem, Spanned, text};
8
9/// One shape of a variant format (grammar `format-variant`).
10#[derive(Debug, Clone)]
11pub struct FormatVariant {
12    /// The shape.
13    pub shape: Shape,
14    /// One conforming line, which a failure of this shape shows.
15    pub example: String,
16}
17
18/// A line format (grammar `format`), its shapes compiled against the types
19/// its layer sees.
20#[derive(Debug, Clone)]
21pub struct Format {
22    /// The shape of a format without variants.
23    pub shape: Option<Shape>,
24    /// The named shapes of a variant format, in the order a line tries them.
25    pub variants: Vec<(String, FormatVariant)>,
26    /// The name of the hole or group that captures the line's key.
27    pub key: Option<String>,
28    /// `prohibited-patterns`: what no bound line may match.
29    pub prohibited: Vec<Prohibition>,
30    /// One conforming line of a format without variants.
31    pub example: Option<String>,
32    /// The entry as written, for a printed registry and a layer on top.
33    pub raw: Spanned,
34    /// Whether its layer wrote the entry as a patch, which `raw` holds
35    /// merged onto the farther entry.
36    pub patched: bool,
37}
38
39/// A key a shape captured, and the offset where the shape's match began,
40/// which is where the key's anchor goes.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Captured {
43    /// The key.
44    pub key: String,
45    /// The start of the match.
46    pub start: usize,
47}
48
49/// The key `name` that `shape` captures from `text`.
50pub fn captured(shape: &Shape, name: &str, text: &str) -> Option<Captured> {
51    let caps = shape.captures(text)?;
52    Some(Captured {
53        key: caps.name(name)?.as_str().to_string(),
54        start: caps.get(0).map_or(0, |m| m.start()),
55    })
56}
57
58/// The outcome of matching a line against a format.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum FormatMatch {
61    /// The line conforms; its key, if the format captures one.
62    Ok(Option<Captured>),
63    /// The line does not have the shape, with the reason.
64    Fail(String),
65    /// The line has the shape and matches a ban, with the reason.
66    Refused(String),
67}
68
69impl Format {
70    /// The format as a format grammar reads it: each shape read through
71    /// `read`, as `Shape::read_with` reads it, and the rest as it is.
72    // sokf-implements: TL_141
73    #[must_use]
74    pub fn read_with(&self, read: &dyn Fn(&str) -> String) -> Format {
75        Format {
76            shape: self.shape.as_ref().map(|s| s.read_with(read)),
77            variants: self
78                .variants
79                .iter()
80                .map(|(name, v)| {
81                    (
82                        name.clone(),
83                        FormatVariant {
84                            shape: v.shape.read_with(read),
85                            example: v.example.clone(),
86                        },
87                    )
88                })
89                .collect(),
90            ..self.clone()
91        }
92    }
93
94    /// Every example the format carries: its own, or each variant's.
95    pub fn examples(&self) -> Vec<&str> {
96        match &self.example {
97            Some(e) => vec![e.as_str()],
98            None => self
99                .variants
100                .iter()
101                .map(|(_, v)| v.example.as_str())
102                .collect(),
103        }
104    }
105
106    /// Each shape of the format: its one shape, unnamed, or each variant's,
107    /// by the variant's name.
108    pub(crate) fn shapes(&self) -> impl Iterator<Item = (Option<&str>, &Shape)> {
109        self.shape.iter().map(|s| (None, s)).chain(
110            self.variants
111                .iter()
112                .map(|(name, v)| (Some(name.as_str()), &v.shape)),
113        )
114    }
115
116    /// How far `text` follows the format before it fails: the furthest
117    /// that any of its shapes reaches.
118    pub fn reach(&self, text: &str) -> usize {
119        self.shapes().map(|(_, s)| s.reach(text)).max().unwrap_or(0)
120    }
121
122    /// Whether a template of the format holds a hole of one of `types`.
123    pub(super) fn uses_any(&self, types: &[&str]) -> bool {
124        self.hole_types().any(|ty| types.contains(&ty))
125    }
126
127    /// Each of `types` that a hole of a template of the format names, once,
128    /// in the order of the holes.
129    pub(super) fn uses<'t>(&self, types: &[&'t str]) -> Vec<&'t str> {
130        let mut used = Vec::new();
131        for ty in self.hole_types() {
132            if let Some(&name) = types.iter().find(|n| **n == ty)
133                && !used.contains(&name)
134            {
135                used.push(name);
136            }
137        }
138        used
139    }
140
141    /// The type of each hole of each template of the format, in order.
142    fn hole_types(&self) -> impl Iterator<Item = &str> {
143        self.shapes()
144            .filter_map(|(_, shape)| match shape {
145                Shape::Template(t) => Some(t),
146                _ => None,
147            })
148            .flat_map(|t| t.segments.iter())
149            .filter_map(|s| match s {
150                Segment::Hole { ty, .. } => Some(ty.as_str()),
151                Segment::Literal(_) => None,
152            })
153    }
154
155    /// The first example, which stands for the format where one is needed.
156    pub fn first_example(&self) -> &str {
157        self.example
158            .as_deref()
159            .or_else(|| self.variants.first().map(|(_, v)| v.example.as_str()))
160            .unwrap_or("")
161    }
162
163    /// Match `text`, squashed, against the format. A failure is built from
164    /// what the format holds, never from a sentence written to explain it:
165    /// where the shape fails and its example, or what a ban matched and the
166    /// example of the shape the line took.
167    // sokf-implements: TL_42
168    // sokf-implements: TL_74
169    // sokf-implements: TL_80
170    pub fn check(&self, text: &str) -> FormatMatch {
171        self.check_as(text, "line")
172    }
173
174    /// As `check`, for a unit that a failure calls `noun`, such as `item`.
175    pub fn check_as(&self, text: &str, noun: &str) -> FormatMatch {
176        self.check_masked(text, text, noun)
177    }
178
179    /// As `check_as`, where the bans read `masked`: `text` with what they
180    /// leave out, such as a code span, overwritten byte for byte, so that
181    /// every offset of `text` stays where it was. A failure quotes the
182    /// span as `text` holds it.
183    pub fn check_masked(&self, text: &str, masked: &str, noun: &str) -> FormatMatch {
184        self.check_quoting(text, masked, noun, &Quote::same(text))
185    }
186
187    /// As `check_masked`, for a text that a format grammar read in another
188    /// spelling: a failure quotes `quote`, the text as written.
189    pub fn check_quoting(
190        &self,
191        text: &str,
192        masked: &str,
193        noun: &str,
194        quote: &Quote<'_>,
195    ) -> FormatMatch {
196        let (shape, example) = match self.matching_quoting(text, noun, quote) {
197            Ok(m) => m,
198            Err(reason) => return FormatMatch::Fail(reason),
199        };
200        if let Some(reason) =
201            refused_quoting(text, masked, &self.prohibited, noun, Some(example), quote)
202        {
203            return FormatMatch::Refused(reason);
204        }
205        FormatMatch::Ok(self.key.as_ref().and_then(|k| captured(shape, k, text)))
206    }
207
208    /// The shape `text` has and its example, where it has one: the check
209    /// alone, with no failure built.
210    pub fn shape_for(&self, text: &str) -> Option<(&Shape, &str)> {
211        match &self.shape {
212            Some(shape) => shape
213                .matches(text, |_| None)
214                .then(|| (shape, self.example.as_deref().unwrap_or(""))),
215            None => self
216                .variants
217                .iter()
218                .find(|(_, v)| v.shape.matches(text, |_| None))
219                .map(|(_, v)| (&v.shape, v.example.as_str())),
220        }
221    }
222
223    /// Whether `text` has the format's shape and passes its bans, silently.
224    pub fn conforms(&self, text: &str) -> bool {
225        self.conforms_masked(text, text)
226    }
227
228    /// As `conforms`, where the bans read `masked`, as for `check_masked`.
229    pub fn conforms_masked(&self, text: &str, masked: &str) -> bool {
230        self.shape_for(text).is_some()
231            && !self.prohibited.iter().any(|b| b.pattern.is_match(masked))
232    }
233
234    /// The shape `text` has and its example, or why it has none. A variant
235    /// format tries its variants in order; where none matches, the one the
236    /// line follows furthest is the one it meant (`TL_42`).
237    // sokf-implements: TL_42
238    pub fn matching(&self, text: &str) -> std::result::Result<(&Shape, &str), String> {
239        self.matching_as(text, "line")
240    }
241
242    /// As `matching`, for a unit that a failure calls `noun`.
243    pub fn matching_as(
244        &self,
245        text: &str,
246        noun: &str,
247    ) -> std::result::Result<(&Shape, &str), String> {
248        self.matching_quoting(text, noun, &Quote::same(text))
249    }
250
251    /// As `matching_as`, for a text that a format grammar read in another
252    /// spelling: a failure quotes `quote`, the text as written.
253    pub fn matching_quoting(
254        &self,
255        text: &str,
256        noun: &str,
257        quote: &Quote<'_>,
258    ) -> std::result::Result<(&Shape, &str), String> {
259        if let Some(found) = self.shape_for(text) {
260            return Ok(found);
261        }
262        if let Some(shape) = &self.shape {
263            return Err(format!(
264                "{}{}",
265                shape.failure_quoting(text, quote),
266                reads(noun, self.example.as_deref(), " or ")
267            ));
268        }
269        let reach: Vec<usize> = self
270            .variants
271            .iter()
272            .map(|(_, v)| v.shape.reach(text))
273            .collect();
274        let best = reach.iter().copied().max().unwrap_or(0);
275        let at: Vec<&(String, FormatVariant)> = self
276            .variants
277            .iter()
278            .zip(&reach)
279            .filter(|(_, r)| **r == best)
280            .map(|(v, _)| v)
281            .collect();
282        match at.as_slice() {
283            [] => Err("has no variants to match".into()),
284            [(name, v)] => Err(format!(
285                "does not match the `{name}` form: it {}{}",
286                v.shape.failure_quoting(text, quote),
287                reads(noun, [v.example.as_str()], " or ")
288            )),
289            many => {
290                // A regex does not say where it fails; a template does.
291                let at = if best > 0 {
292                    format!(
293                        ": each fails at column {}",
294                        template::column(quote.text, quote.offset(best))
295                    )
296                } else {
297                    String::new()
298                };
299                // Each form it names is one it may have meant, so each
300                // shows its example.
301                Err(format!(
302                    "matches none of the forms {}{at}{}",
303                    text::code_list(many.iter().map(|(n, _)| n), ", "),
304                    reads(noun, many.iter().map(|(_, v)| v.example.as_str()), " or ")
305                ))
306            }
307        }
308    }
309}
310
311/// The failure of the first ban in `bans` that `text` matches: the span it
312/// matched, the pattern, and, where the ban sits on a rule, that rule's
313/// example. A ban needs no sentence of its own, because its pattern is
314/// exactly what the author wrote.
315// sokf-implements: TL_75
316// sokf-implements: TL_76
317// sokf-implements: TL_81
318pub fn refused(text: &str, bans: &[Prohibition], example: Option<&str>) -> Option<String> {
319    refused_as(text, bans, "line", example)
320}
321
322/// As `refused`, for a unit that the failure calls `noun`. The reason names
323/// the span that a ban matched and gives the ban's message, which states
324/// the rule, rather than its pattern.
325// sokf-implements: TL_75
326// sokf-implements: TL_76
327pub fn refused_as(
328    text: &str,
329    bans: &[Prohibition],
330    noun: &str,
331    example: Option<&str>,
332) -> Option<String> {
333    refused_masked(text, text, bans, noun, example)
334}
335
336/// As `refused_as`, where the bans read `masked`, as for
337/// `Format::check_masked`. Where `masked` has the length of `text`, the
338/// span quotes `text`, from the start of the character where the match
339/// starts to the end of the one where it ends; otherwise it quotes
340/// `masked`.
341// sokf-implements: TL_75
342// sokf-implements: TL_81
343pub fn refused_masked(
344    text: &str,
345    masked: &str,
346    bans: &[Prohibition],
347    noun: &str,
348    example: Option<&str>,
349) -> Option<String> {
350    refused_quoting(text, masked, bans, noun, example, &Quote::same(text))
351}
352
353/// As `refused_masked`, for a `text` that a format grammar read in another
354/// spelling: the span quotes `quote`, the text as written, from the place
355/// of the start of the match to the place of its end.
356// sokf-implements: TL_75
357pub fn refused_quoting(
358    text: &str,
359    masked: &str,
360    bans: &[Prohibition],
361    noun: &str,
362    example: Option<&str>,
363    quote: &Quote<'_>,
364) -> Option<String> {
365    bans.iter().find_map(|ban| {
366        let found = ban.pattern.find(masked)?;
367        let span = if text.len() == masked.len() {
368            let written = quote.text;
369            let start = quote.offset(found.start());
370            let end = written.ceil_char_boundary((quote.at)(found.end()).min(written.len()));
371            &written[start..end.max(start)]
372        } else {
373            found.as_str()
374        };
375        let message = ban.message.trim_end();
376        Some(match example.filter(|e| !e.is_empty()) {
377            Some(e) => {
378                let mut article = text::article(noun).to_string();
379                article[..1].make_ascii_uppercase();
380                format!(
381                    "{} is refused: {message} {article} {noun} of this kind reads {}",
382                    text::code(span),
383                    text::code(e)
384                )
385            }
386            None => format!("{} is refused: {message}", text::code(span)),
387        })
388    })
389}
390
391/// `Prohibition` is one entry of `prohibited-patterns`: a pattern that no
392/// governed text may match, and the message that states the rule as a fact
393/// about the part.
394#[derive(Debug, Clone)]
395pub struct Prohibition {
396    /// `pattern`: the regex.
397    pub pattern: Regex,
398    /// `message`: the rule, in one sentence.
399    pub message: String,
400}
401
402/// `prohibitions` reads the entries of `prohibited-patterns` under `node`.
403/// The grammar checks that each entry is a map of a `pattern` that compiles
404/// and a `message`, so an entry that is not is skipped.
405pub fn prohibitions(node: &Spanned, regexes: &RegexCache) -> Vec<Prohibition> {
406    node.get("prohibited-patterns")
407        .and_then(|b| b.as_seq())
408        .unwrap_or(&[])
409        .iter()
410        .filter_map(|ban| {
411            let pattern = regexes.get(ban.get("pattern")?.as_str()?).ok()?;
412            let message = ban.get("message")?.as_str()?.to_string();
413            Some(Prohibition { pattern, message })
414        })
415        .collect()
416}
417
418/// One shape of a format or a variant: `text`, `template` or `pattern`,
419/// exactly one, `text` a string.
420fn format_shape(
421    node: &Spanned,
422    types: &TypeRegistry,
423    regexes: &RegexCache,
424) -> std::result::Result<Shape, Problem> {
425    if node.get("text").is_some_and(|t| t.as_str().is_none()) {
426        return Err(Problem::new("TL_101", "a format's `text` is a string"));
427    }
428    // sokf-implements: TL_105
429    shape_of(node, types, regexes)?.ok_or_else(|| {
430        Problem::new(
431            "TL_105",
432            "a shape is one of `text`, `template` or `pattern`",
433        )
434    })
435}
436
437/// Lower a validated `format` entry against the types its layer sees. The
438/// problems are `(line, message)`: a shape that does not compile, an
439/// example where variants speak, none where they do not, and a key no
440/// shape captures.
441// sokf-implements: TL_42
442pub(super) fn lower_format(
443    entry: &Spanned,
444    types: &TypeRegistry,
445    regexes: &RegexCache,
446) -> std::result::Result<Format, Vec<(usize, Problem)>> {
447    let mut problems = Vec::new();
448    let mut variants = Vec::new();
449    if let Some(v) = entry.get("variants") {
450        for (name, variant) in v.as_map().unwrap_or(&[]) {
451            match format_shape(variant, types, regexes) {
452                Ok(shape) => variants.push((
453                    name.value.clone(),
454                    FormatVariant {
455                        shape,
456                        example: variant
457                            .get("example")
458                            .and_then(|d| d.as_str())
459                            .unwrap_or_default()
460                            .to_string(),
461                    },
462                )),
463                Err(e) => problems.push((
464                    variant.line,
465                    e.prefixed(&format!("variant `{}`: ", name.value)),
466                )),
467            }
468        }
469    }
470    let shape = if entry.get("variants").is_some() {
471        None
472    } else {
473        match format_shape(entry, types, regexes) {
474            Ok(s) => Some(s),
475            Err(e) => {
476                problems.push((entry.line, e));
477                None
478            }
479        }
480    };
481    let example = entry
482        .get("example")
483        .and_then(|d| d.as_str())
484        .map(str::to_string);
485    // sokf-implements: TL_40
486    // sokf-implements: TL_110
487    match (&example, entry.get("variants")) {
488        (Some(_), Some(_)) => problems.push((
489            entry.line,
490            Problem::new(
491                "TL_110",
492                "a format with `variants` has no `example` of its own: each variant's example speaks for its shape",
493            ),
494        )),
495        (None, None) => problems.push((
496            entry.line,
497            Problem::new("TL_40", "a format with one shape carries an `example`"),
498        )),
499        _ => {}
500    }
501    let format = Format {
502        shape,
503        variants,
504        key: entry
505            .get("key")
506            .and_then(|k| k.as_str())
507            .map(str::to_string),
508        prohibited: prohibitions(entry, regexes),
509        example,
510        raw: entry.clone(),
511        patched: false,
512    };
513    if let Some(k) = &format.key {
514        for (name, s) in format.shapes() {
515            if !s.has_group(k) {
516                let whose =
517                    name.map_or_else(|| "the shape".to_string(), |n| format!("variant `{n}`"));
518                problems.push((
519                    entry.line,
520                    Problem::new(
521                        "TL_31",
522                        format!("`key` `{k}` names no hole or named group of {whose}"),
523                    ),
524                ));
525            }
526        }
527    }
528    if !problems.is_empty() {
529        return Err(problems);
530    }
531    Ok(format)
532}
533
534/// The examples that a failure shows, after the words that name the unit,
535/// each that is not empty as one code span (`TL_142`), joined by `sep`, and
536/// nothing where no example is left.
537pub(crate) fn reads<'a>(
538    noun: &str,
539    examples: impl IntoIterator<Item = &'a str>,
540    sep: &str,
541) -> String {
542    let shown: Vec<String> = examples
543        .into_iter()
544        .filter(|e| !e.is_empty())
545        .map(text::code)
546        .collect();
547    if shown.is_empty() {
548        return String::new();
549    }
550    format!(
551        "; {} {noun} of this kind reads {}",
552        text::article(noun),
553        shown.join(sep)
554    )
555}