tramlines-md 0.5.0

Checks markdown documents against a schema, and derives the scaffold a schema implies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! A rule's `example` against the rule that carries it, and a format's
//! against the format (grammar `section`, `block`, `unit`,
//! `frontmatter-constraint`, `format`).
//!
//! The instance voice: text of the kind a rule demands. A scaffold
//! is built from these, and checking each one where it stands catches the
//! example on an optional rule that no scaffold reaches, and the example a
//! later edit to its rule left behind.

use super::{At, Host, NullHost, label};
use crate::{
    Finding, Locator, RepoPath,
    grammar::{
        Block, DerivationSource, FmFormat, Format, FormatMatch, FormatRegistry, FormatSource,
        FrontmatterConstraint, KeyDerivation, Label, Schema, Section, Shape, Text, Unit, Words,
        captured, carries_labels, refused_masked, squash,
    },
    markdown::{self, BlockKind, is_slug, is_url},
};

/// What one example failed, as the reason alone.
type Problem = Option<String>;

/// The schema every example of one schema is reported on.
struct Examples<'a> {
    schema: &'a Schema,
    path: &'a RepoPath,
    out: Vec<Finding>,
    /// The examples that failed.
    failed: Failed,
    /// The schema, which a finding of a rule's example names.
    locator: Locator,
    /// Where in the schema the rule being read sits.
    at: At,
    /// The labels of the schema in the words of the host.
    labels: Words,
}

/// Every `example` a schema carries, against the rule it sits on. The
/// finding of a rule's example names the schema `id` and the rule. The
/// label of an example is held to the keys of the schema's labels, as a
/// host that gives no words for them holds it.
pub fn check(schema: &Schema, path: &RepoPath, id: &str) -> Vec<Finding> {
    check_examples(schema, &NullHost, path, id).0
}

/// The examples that failed their rules: the text of each, and the line
/// of each rule whose example failed.
#[derive(Debug, Default)]
pub(super) struct Failed {
    pub texts: Vec<String>,
    pub rules: Vec<usize>,
}

/// The findings of `check`, and the examples that failed, the label of
/// each example held to the words that `host` gives.
// sokf-implements: TL_64
// sokf-implements: TL_65
// sokf-implements: TL_73
// sokf-implements: TL_127
pub(super) fn check_examples(
    schema: &Schema,
    host: &dyn Host,
    path: &RepoPath,
    id: &str,
) -> (Vec<Finding>, Failed) {
    let mut e = Examples {
        schema,
        path,
        out: Vec::new(),
        failed: Failed::default(),
        locator: Locator::schema(id),
        at: At::default(),
        labels: label::words_of(schema, host),
    };
    for (key, constraint) in &schema.core.frontmatter {
        if let Some(text) = &constraint.example {
            e.at = At {
                named: Some(format!("key `{key}`")),
                ..At::default()
            };
            e.said_of(
                text,
                constraint.common.line,
                "TL_64",
                frontmatter(key, constraint),
            );
        }
    }
    for section in &schema.sections {
        e.at = At {
            region: Some(format!("section \"{}\"", section.label())),
            rule_id: section.rule_id.clone(),
            ..At::default()
        };
        if let Some(text) = &section.heading.example {
            e.said_of(text, section.common.line, "TL_64", heading(section));
            if let (Some(kd), Some(key)) = (&section.heading.key_derives_from, &section.heading.key)
            {
                let got = captured(&section.heading.shape, key, &squash(text)).map(|c| c.key);
                let problem = derived(schema, kd, got);
                e.said_of(text, section.common.line, "TL_127", problem);
            }
        }
        e.blocks(section.blocks.as_deref());
    }
    if let Some(preamble) = &schema.preamble {
        e.at = At {
            region: Some("preamble".to_string()),
            ..At::default()
        };
        e.blocks(preamble.blocks.as_deref());
    }
    // A format names itself in its finding.
    e.at = At::default();
    // An entry of a farther layer sits in another file, so its finding
    // goes on the schema's own line and says which layer wrote it. A
    // formats file that the caller names, and a formats file of a pack, is
    // checked on that file, with `check_formats`; its failed examples still
    // stand for the scaffold.
    // sokf-implements: MD-6_AC-8
    for (name, (format, source)) in &schema.core.formats.entries {
        let own = matches!(source, FormatSource::Schema(_));
        let layer = if own {
            String::new()
        } else {
            format!(" ({})", source.label())
        };
        for (criterion, message, text, line) in format_examples(name, format, &layer) {
            let at = if own { line } else { schema.core.line };
            if let Some(text) = text.filter(|t| !t.is_empty()) {
                e.failed.texts.push(text);
            }
            // sokf-implements: MD-6_AC-8
            if !matches!(source, FormatSource::File(_) | FormatSource::Pack(_)) {
                e.out
                    .push(Finding::error(path.clone(), Some(at), criterion, message));
            }
        }
    }
    (e.out, e.failed)
}

/// The example of each format of `registry` that `source` wrote, against
/// its format, reported on `path` at the line of the format or its variant.
// sokf-implements: TL_43
// sokf-implements: TL_65
pub fn check_formats(
    registry: &FormatRegistry,
    source: &FormatSource,
    path: &RepoPath,
) -> Vec<Finding> {
    registry
        .entries
        .iter()
        .filter(|(_, (_, s))| s == source)
        .flat_map(|(name, (format, _))| {
            format_examples(name, format, "")
                .into_iter()
                .map(|(criterion, message, _, line)| {
                    Finding::error(path.clone(), Some(line), criterion, message)
                })
        })
        .collect()
}

/// The failures of the examples of the format `name`: each criterion, its
/// message, the text of an example that failed its shape, and the line of
/// the format, or of the variant whose example it is. `layer` names a
/// farther layer in the message.
fn format_examples(
    name: &str,
    format: &Format,
    layer: &str,
) -> Vec<(&'static str, String, Option<String>, usize)> {
    let mut out = Vec::new();
    let line_of = |variant: Option<&str>| {
        variant
            .and_then(|v| format.raw.get("variants")?.get(v))
            .map_or(format.raw.line, |node| node.line)
    };
    // An example is written as its line stands, a fence's indent and all;
    // every shape reads it squashed (TL_23). A variant's example speaks for
    // its own variant, so it is held to that one first.
    let examples: Vec<(Option<(&str, &Shape)>, &str)> = match &format.example {
        Some(example) => vec![(None, example.as_str())],
        None => format
            .variants
            .iter()
            .map(|(vi, v)| (Some((vi.as_str(), &v.shape)), v.example.as_str()))
            .collect(),
    };
    for (own, line) in examples {
        let text = squash(line);
        // A format names no kind of block, so its example reads as a line
        // of prose, whose code spans its bans leave out.
        // sokf-implements: TLMD_111
        let code = markdown::code_spans_in(&text);
        let checked = format.check_masked(&text, &markdown::mask_code(&text, &code), "line");
        let problem = match (own, checked) {
            (Some((vi, shape)), _) if !shape.matches(&text, |_| None) => Some(format!(
                "the example `{line}` of variant `{vi}` of format `{name}`{layer} does not match its own variant: it {}",
                shape.failure(&text)
            )),
            // The failure of a format shows its examples, which here are
            // the one that failed, so the example check leaves them out.
            (_, FormatMatch::Fail(reason) | FormatMatch::Refused(reason)) => {
                let reason = reason
                    .rsplit_once("; a line of this kind reads ")
                    .map_or(reason.as_str(), |(why, _)| why);
                Some(format!("the example `{line}` of format `{name}`{layer} {reason}"))
            }
            // The example speaks for the key as well as the shape, so one
            // that captures no key fails its format.
            // sokf-implements: TL_65
            (_, FormatMatch::Ok(None)) => format.key.as_ref().map(|key| {
                format!(
                    "the example `{line}` of format `{name}`{layer} carries no key: the format captures `{key}`"
                )
            }),
            (_, FormatMatch::Ok(Some(_))) => None,
        };
        if let Some(message) = problem {
            out.push(("TL_65", message, Some(text), line_of(own.map(|(vi, _)| vi))));
        }
    }
    // Each variant's example tells it from the others, so a line is the
    // variant it reads as, and a failure names the one it meant. An example
    // that fails its own variant is reported above.
    // sokf-implements: TL_43
    // sokf-implements: TLMD_58
    for (i, (vi, variant)) in format.variants.iter().enumerate() {
        let text = squash(&variant.example);
        if !variant.shape.matches(&text, |_| None) {
            continue;
        }
        for (j, (vj, other)) in format.variants.iter().enumerate() {
            if i != j && other.shape.matches(&text, |_| None) {
                out.push((
                    "TL_43",
                    format!(
                        "the example of variant `{vi}` of format `{name}`{layer} also matches variant `{vj}`: each variant's example matches its own variant only"
                    ),
                    None,
                    line_of(Some(vi)),
                ));
            }
        }
    }
    out
}

impl Examples<'_> {
    /// `say`, for the example `text`, which is kept where it failed.
    fn said_of(&mut self, text: &str, line: usize, criterion: &'static str, problem: Problem) {
        let text = squash(text);
        if problem.is_some() {
            self.failed.rules.push(line);
            if !text.is_empty() {
                self.failed.texts.push(text);
            }
        }
        self.say(line, criterion, problem);
    }

    fn say(&mut self, line: usize, criterion: &'static str, problem: Problem) {
        if let Some(reason) = problem {
            let locator = self.at.locate(&self.locator);
            self.out.push(
                Finding::error(self.path.clone(), Some(line), criterion, reason).at(&locator),
            );
        }
    }

    /// Read `f` with the place narrowed to `rule_id` or to the block at
    /// `pos`, as the check names a block's rule, and put it back after: a
    /// block names its own `rule-id` or its place, and a unit rule its own
    /// `rule-id` or its block's.
    fn inside(&mut self, pos: Option<usize>, rule_id: Option<&String>, f: impl FnOnce(&mut Self)) {
        let mut at = self.at.clone();
        at.blocks.extend(pos);
        if pos.is_some() || rule_id.is_some() {
            at.rule_id = rule_id.cloned();
        }
        let held = std::mem::replace(&mut self.at, at);
        f(self);
        self.at = held;
    }

    /// Every block of a list, and the unit rules under each.
    fn blocks(&mut self, rules: Option<&[Block]>) {
        for block in rules.unwrap_or(&[]) {
            self.inside(Some(block.pos), block.rule_id.as_ref(), |e| e.block(block));
        }
    }

    /// One block, and the unit rules under it.
    fn block(&mut self, block: &Block) {
        // The rules of a fence or of an HTML block govern its lines, whose
        // backticks are text and open no code span.
        let lines = matches!(block.kind, BlockKind::Code | BlockKind::Html);
        // A block's example stands for one of its units, so it is held
        // to the rules that would take it: those that state no text of
        // their own. A block whose rules each carry an example, and one
        // that declares no unit rule at all, answer to nothing here.
        let consumers = consumers(block);
        for (i, text) in block.examples.iter().enumerate() {
            for rule in &consumers {
                let problem = item(i, &block.examples, self.unit(block, rule, text, lines));
                self.said_of(text, block.common.line, "TL_64", problem);
                let problem = item(
                    i,
                    &block.examples,
                    derived_unit(self.schema, &self.labels, block, rule, text),
                );
                self.said_of(text, block.common.line, "TL_127", problem);
            }
            // A block with no unit rule holds its units to its own `label`.
            if block.units().next().is_none() {
                let (bare, found) = self.label_of(block, None, text);
                let problem = self.label_problem(block, None, text, &bare, found.as_ref());
                self.said_of(
                    text,
                    block.common.line,
                    "TL_64",
                    item(i, &block.examples, problem),
                );
            }
        }
        for rule in block.units() {
            self.units(block, rule, lines);
        }
        if let Some(rules) = &block.rules {
            self.grammar(block, rules);
        }
        self.blocks(block.blocks.as_deref());
    }

    /// One unit rule, the rules under its `lines`, and an item's blocks.
    /// `lines` says that the rule governs the lines of a fence or of an
    /// HTML block.
    fn units(&mut self, block: &Block, rule: &Unit, lines: bool) {
        for (i, text) in rule.examples.iter().enumerate() {
            let problem = item(i, &rule.examples, self.unit(block, rule, text, lines));
            self.inside(None, rule.rule_id.as_ref(), |e| {
                e.said_of(text, rule.common.line, "TL_64", problem);
            });
        }
        // The example that the scaffold writes for the rule, its own or else
        // its format's, carries the key that derives.
        let examples = examples_of(self.schema, rule);
        for (i, text) in examples.iter().enumerate() {
            let problem = item(
                i,
                &examples,
                derived_unit(self.schema, &self.labels, block, rule, text),
            );
            self.inside(None, rule.rule_id.as_ref(), |e| {
                e.said_of(text, rule.common.line, "TL_127", problem);
            });
        }
        for line in rule.lines.iter().flatten() {
            self.units(block, line, lines);
        }
        if let Some(lines) = &rule.lines {
            self.grammar(block, lines);
        }
        self.blocks(rule.blocks.as_deref());
    }

    /// A rule list is a grammar, so each production's example is taken by
    /// its own rule and by no earlier one.
    // sokf-implements: TLMD_58
    // sokf-implements: TL_43
    // sokf-implements: TLMD_58
    fn grammar(&mut self, block: &Block, rules: &[Unit]) {
        for (i, rule) in rules.iter().enumerate() {
            if !rule.is_production() {
                continue;
            }
            let examples = examples_of(self.schema, rule);
            for (n, text) in examples.iter().enumerate() {
                if let Some(earlier) = rules[..i].iter().position(|r| {
                    r.is_production() && has_shape(self.schema, &self.labels, block, r, text)
                }) {
                    let problem = Some(format!(
                        "the example `{text}` is taken by the rule at line {} first, so this rule takes nothing: order the rules from the narrowest",
                        rules[earlier].common.line
                    ));
                    // The finding is about the later rule, so it names it.
                    // sokf-implements: TL_73
                    self.inside(None, rule.rule_id.as_ref(), |e| {
                        e.say(rule.common.line, "TLMD_58", item(n, &examples, problem));
                    });
                }
            }
        }
    }
}

/// A problem with one text of an `example` list, with the position of the
/// text in the list where the list holds more than one, so that the author
/// knows which text fails.
fn item(i: usize, examples: &[String], problem: Problem) -> Problem {
    let reason = problem?;
    if examples.len() > 1 {
        Some(format!("item {} of `example`: {reason}", i + 1))
    } else {
        Some(reason)
    }
}

/// The texts a rule's example gives: its own, or else its format's first.
fn examples_of(schema: &Schema, rule: &Unit) -> Vec<String> {
    if !rule.examples.is_empty() {
        return rule.examples.clone();
    }
    rule.format
        .as_ref()
        .and_then(|n| schema.core.formats.get(n))
        .map(|f| vec![f.first_example().to_string()])
        .unwrap_or_default()
}

/// Whether `text`, an example of a unit of `block`, has `rule`'s shape,
/// its own or its format's, read without its label in `words`.
fn has_shape(schema: &Schema, words: &Words, block: &Block, rule: &Unit, text: &str) -> bool {
    let (bare, _) = schema.unlabelled(words, block, Some(rule), text);
    rule.fits(&schema.core.formats, &bare, |_| None)
}

impl Examples<'_> {
    /// The example `text` of a unit of `block` that `rule` governs, as the
    /// rule reads it: squashed, without the label that it carries, and the
    /// label (`TLMD_257`).
    fn label_of(
        &self,
        block: &Block,
        rule: Option<&Unit>,
        text: &str,
    ) -> (String, Option<crate::grammar::Found>) {
        self.schema.unlabelled(&self.labels, block, rule, text)
    }

    /// The label `found` that the example `text` carries, as `bare` reads
    /// without it, against what `rule` of `block` declares and the words of
    /// the host, as a unit's label is held to them (`TLMD_257`).
    // sokf-implements: TLMD_257
    // sokf-implements: MD-6_AC-10
    fn label_problem(
        &self,
        block: &Block,
        rule: Option<&Unit>,
        text: &str,
        bare: &str,
        found: Option<&crate::grammar::Found>,
    ) -> Problem {
        if self.labels.is_empty() || !carries_labels(block.kind) {
            return None;
        }
        let listed = self.labels.listed();
        match (block.label_of(rule), found) {
            (Some(Label::Required), None) => Some(format!(
                "the example `{text}` carries no label, and its rule requires one: {listed}"
            )),
            (None, Some(f)) => Some(format!(
                "the example `{bare}` carries the label `[{}]`, and its rule declares no `label`",
                f.words
            )),
            (Some(_), Some(f)) if !self.labels.accepts(&f.words) => Some(format!(
                "the label `[{}]` of the example `{bare}` is none of the labels of the schema: {listed}",
                f.words
            )),
            _ => None,
        }
    }

    /// The example `text` of a unit of `block` against `rule`, as `unit`
    /// holds it, read without its label, and then its label.
    fn unit(&self, block: &Block, rule: &Unit, text: &str, lines: bool) -> Problem {
        if lines {
            return unit(self.schema, rule, text, &squash(text), lines);
        }
        let (bare, found) = self.label_of(block, Some(rule), text);
        // A failure quotes the text that its column counts in.
        let shown = if found.is_some() { bare.as_str() } else { text };
        unit(self.schema, rule, shown, &bare, lines)
            .or_else(|| self.label_problem(block, Some(rule), text, &bare, found.as_ref()))
    }
}

/// A unit rule's example against that rule's text constraints. A guard
/// comes first: a rule governs what it selects, so an example the guard
/// passes over stands for a unit the rule never reads. `lines` says that
/// the example stands for a line of a fence or of an HTML block. `bare` is
/// the example squashed, without its label, which the rule reads.
fn unit(schema: &Schema, rule: &Unit, text: &str, bare: &str, lines: bool) -> Problem {
    let squashed = bare.to_string();
    if let Some(select) = &rule.select
        && !select.is_match(&squashed)
    {
        return Some(format!(
            "the example `{text}` does not match `select-pattern` `{}`, so this rule would not govern it",
            select.as_str()
        ));
    }
    if let Some(shape) = &rule.shape
        && !matches!(shape, Shape::Text(Text::From(_)))
        && !shape.matches(&squashed, |_| None)
    {
        return Some(format!("the example `{text}` {}", shape.failure(&squashed)));
    }
    // The example stands for a unit, so the bans of its rule and of its
    // format leave out its code spans, as a unit's do; a line holds none.
    // sokf-implements: TLMD_111
    let format = rule.format_in(&schema.core.formats);
    let code = if lines || !rule.bans_in(&schema.core.formats) {
        Vec::new()
    } else {
        markdown::code_spans_in(&squashed)
    };
    let masked = markdown::mask_code(&squashed, &code);
    if let Some(reason) =
        refused_masked(&squashed, &masked, &rule.prohibited_patterns, "line", None)
    {
        return Some(format!("the example `{text}` is refused: {reason}"));
    }
    if let Some(name) = &rule.format {
        match format.map(|f| (f, f.check_masked(&squashed, &masked, "line"))) {
            Some((_, FormatMatch::Fail(reason) | FormatMatch::Refused(reason))) => {
                return Some(format!("the example `{text}` {reason}"));
            }
            Some((f, FormatMatch::Ok(None))) if f.key.is_some() && !rule.key_optional => {
                return Some(format!(
                    "the example `{text}` carries no key: the format `{name}` captures `{}`",
                    f.key.clone().unwrap_or_default()
                ));
            }
            _ => {}
        }
    }
    if let Some(k) = &rule.key
        && !rule.key_optional
        && let Some(shape) = &rule.shape
        && captured(shape, k, &squashed).is_none()
    {
        return Some(format!("the example `{text}` captures no `key` `{k}`"));
    }
    None
}

/// The example `text` of a unit of `block` that `rule` governs against
/// the rule's `key-derives-from`, read without its label in `words`.
fn derived_unit(schema: &Schema, words: &Words, block: &Block, rule: &Unit, text: &str) -> Problem {
    let kd = rule.key_derives_from.as_ref()?;
    let (bare, _) = schema.unlabelled(words, block, Some(rule), text);
    derived(schema, kd, rule.key_in(&schema.core.formats, &bare))
}

/// The key of an example, `key`, against the example of the parent that
/// `kd` names: the key starts with the value that the scaffold writes for
/// the frontmatter key from the schema, or with a key of the example of
/// the rule, followed by the separator. The scaffold splices its prefix in
/// there, so an example that starts with another contradicts its schema. A
/// key the example does not carry is a fault of its own, and a parent whose
/// value the schema does not state has no example to start with.
fn derived(schema: &Schema, kd: &KeyDerivation, key: Option<String>) -> Problem {
    let key = key?;
    let sep = &kd.separator;
    let parents = schema.parent_examples(kd);
    let of = match &kd.source {
        DerivationSource::From(k) => {
            format!("the value that the scaffold writes for the frontmatter `{k}`")
        }
        DerivationSource::Rule(r) => format!("a key of the example of rule `{r}`"),
    };
    if parents.is_empty()
        || kd
            .prefix_of(&key, parents.iter().map(String::as_str))
            .is_some()
    {
        return None;
    }
    let named: Vec<String> = parents.iter().map(|p| format!("`{p}`")).collect();
    Some(format!(
        "the key `{key}` of the example does not start with {}, {of}, followed by the separator `{sep}`",
        named.join(" or ")
    ))
}

/// The unit rules of `block` that would take the block's own `example`:
/// the ones that state no text of their own, which is the order the
/// derivation reads (`text`, then `example`, then a format's, then the
/// block's).
fn consumers(block: &Block) -> Vec<&Unit> {
    block
        .units()
        .filter(|r| {
            !matches!(r.shape, Some(Shape::Text(_))) && r.examples.is_empty() && r.format.is_none()
        })
        .collect()
}

/// A section's example against its heading's shape.
fn heading(section: &Section) -> Problem {
    let text = section.heading.example.as_ref()?;
    let shape = &section.heading.shape;
    if matches!(shape, Shape::Text(_)) || shape.matches(&squash(text), |_| None) {
        return None;
    }
    Some(format!(
        "the example `{text}` {}",
        shape.failure(&squash(text))
    ))
}

/// A frontmatter constraint's example against that constraint. The two
/// repository-dependent formats are left alone, as they are in a scaffold.
fn frontmatter(key: &str, constraint: &FrontmatterConstraint) -> Problem {
    let text = constraint.example.as_ref()?;
    let said = |reason: String| Some(format!("the example of `{key}` {reason}"));
    if let Some(c) = &constraint.const_
        && c != text
    {
        return said(format!("is not the `const` `{c}`"));
    }
    if let Some(shape) = &constraint.shape
        && constraint.id_template.is_none()
        && !shape.matches(&squash(text), |_| None)
    {
        return said(shape.failure(&squash(text)));
    }
    if let Some(values) = &constraint.enum_
        && !values.contains(text)
    {
        return said(format!("is not one of `{}`", values.join("`, `")));
    }
    match constraint.format {
        Some(FmFormat::Slug) if !is_slug(text) => return said("is not a slug".into()),
        Some(FmFormat::Url) if !is_url(text) => return said("is not a URL".into()),
        _ => {}
    }
    if let Some(template) = &constraint.id_template
        && !template.matches(text)
    {
        return said("does not match the id template".into());
    }
    None
}