tramlines-md 0.6.0

Checks markdown documents against a schema, and derives the scaffold a schema implies. Unstable: its interface can change in any release.
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
//! The grammar of a block's units and of a fence's lines (`TLMD_52` to `TLMD_57`):
//! productions take what their shape matches, a guard selects, a counter
//! counts and takes nothing, and a unit no rule takes is reported against
//! the production it follows furthest.

use super::{
    Checker,
    blocks::{check_unit, noun, shape_failure_of, unit_noun},
    claim::at_unit,
    label::Read,
    quoted,
};
use crate::{
    grammar::{Block as Rule, RuleCommon, Shape, Unit as UnitRule, squash},
    markdown::{Block, BlockDetail, Unit},
    text,
};

/// The content lines of a code block, each with the file line it sits on,
/// without its indent: the indent of a line is layout, as an item's marker
/// is (`TLMD_6`). A blank line is layout too, and no line at all. A
/// fenced block opens with a marker line; an indented one does not.
// sokf-implements: TLMD_82
fn content_lines(block: &Block) -> Vec<(usize, &str)> {
    let first = match block.detail {
        BlockDetail::Code { fence, .. } if fence > 0 => block.line + 1,
        _ => block.line,
    };
    match block.units.first() {
        Some(u) => u
            .text
            .lines()
            .enumerate()
            .map(|(i, text)| (first + i, text.trim_start()))
            .filter(|(_, text)| !text.trim().is_empty())
            .collect(),
        None => Vec::new(),
    }
}

/// The `lines` rules of a code block's unit rule, over its content lines:
/// the rules are the grammar of the fence, and a line no rule takes is an
/// error unless the rule opens itself with `lines-open`.
// sokf-implements: TLMD_83
// sokf-implements: TLMD_84
// sokf-implements: TLMD_86
// sokf-implements: TLMD_87
pub(super) fn check_lines(
    c: &mut Checker<'_>,
    block: &Block,
    unit_rule: &UnitRule,
    rule: &Rule,
    section: Option<usize>,
) {
    let Some(rules) = &unit_rule.lines else {
        return;
    };
    let units: Vec<Unit> = content_lines(block)
        .into_iter()
        .map(|(line, text)| Unit::leaf(text.to_string(), line, line))
        .collect();
    // A key a line carries has its anchor before the block (TLMD_106), and
    // so does a line that breaks its rule.
    let held = c.lines_block.replace(block.line);
    let taken = apply_rules(c, &units, rules, rule, section, block.line, "lines");
    if !unit_rule.lines_open {
        untaken(
            c,
            &units,
            &taken,
            rules,
            rule,
            &unit_rule.common,
            ("the fence", "line"),
            "lines-open",
        );
    }
    c.lines_block = held;
}

/// A rule list over units, which is the grammar of the block (`TLMD_52` to
/// `TLMD_57`). A production, a rule with a shape and no guard, takes the units
/// its shape matches, each unit the first such rule; a rule with a guard
/// takes what its guard selects and checks it, unless it only counts; a
/// rule with neither takes every unit. `min` and `max` bound what each rule
/// took, or counted. Returns which units some rule took.
// sokf-implements: TLMD_83
// sokf-implements: TLMD_84
// sokf-implements: TLMD_86
// sokf-implements: TLMD_52
// sokf-implements: TLMD_54
// sokf-implements: TLMD_55
// sokf-implements: TLMD_56
fn apply_rules(
    c: &mut Checker<'_>,
    units: &[Unit],
    rules: &[UnitRule],
    rule: &Rule,
    section: Option<usize>,
    at: usize,
    noun: &str,
) -> Vec<bool> {
    // Each unit's production: the first whose shape it has.
    let production: Vec<Option<usize>> = units
        .iter()
        .map(|u| {
            rules
                .iter()
                .position(|r| r.is_production() && satisfies_shape(c, u, r, rule))
        })
        .collect();
    // The rule that judges each unit's label: its production, else the
    // first rule that selects it and checks it, else the first rule that
    // takes every unit.
    let judge: Vec<Option<usize>> = units
        .iter()
        .zip(&production)
        .map(|(u, p)| {
            p.or_else(|| {
                rules.iter().position(|r| {
                    !r.is_counter()
                        && match &r.select {
                            Some(s) => s.is_match(&c.read(u, rule, Some(r)).squashed.text),
                            None => !r.has_shape(),
                        }
                })
            })
        })
        .collect();
    let mut taken = vec![false; units.len()];
    for (ri, guarded) in rules.iter().enumerate() {
        let selected: Vec<usize> = (0..units.len())
            .filter(|&i| match &guarded.select {
                // A guard reads the unit without its label (TLMD_248).
                Some(s) => s.is_match(&c.read(&units[i], rule, Some(guarded)).squashed.text),
                None if guarded.has_shape() => production[i] == Some(ri),
                None => true,
            })
            .collect();
        let what = match (&guarded.select, &guarded.shape, &guarded.format) {
            (Some(s), _, _) | (None, Some(Shape::Pattern(s)), _) => {
                format!("the {noun} matching {}", text::code(s.as_str()))
            }
            (None, Some(Shape::Template(t)), _) => {
                format!("the {noun} of the template {}", text::code(&t.source))
            }
            (None, Some(shape @ Shape::Text(_)), _) => {
                format!("the {noun} reading {}", text::code(&shape.label()))
            }
            (None, None, Some(name)) => format!("the {noun} of the format `{name}`"),
            (None, None, None) => format!("the block's {noun}"),
        };
        // The count is the rule's own finding, so it names the rule.
        // sokf-implements: TL_73
        c.located(at_unit(&c.at, guarded), |c| {
            count(c, guarded, &selected, units, at, &what);
        });
        // A counter counts and takes nothing, so it never hides a unit the
        // productions would report.
        if guarded.is_counter() {
            continue;
        }
        for i in selected {
            taken[i] = true;
            // `check_unit` files a capture under the line rule's `key-of`,
            // else the block's, so a key from a line is reachable by
            // `for-each-key-of`.
            // sokf-implements: TLMD_88
            // sokf-implements: TLMD_89
            check_unit(
                c,
                &units[i],
                guarded,
                rule,
                section,
                judge[i].map(|j| &rules[j]),
            );
        }
    }
    taken
}

/// The findings of the count of `guarded`, which `selected` holds of `units`:
/// below its `min` (`TLMD_93`), or above a hard `max` (`TLMD_159`). `at` is the
/// line of the block, and `what` names the units that the rule counts.
fn count(
    c: &mut Checker<'_>,
    guarded: &UnitRule,
    selected: &[usize],
    units: &[Unit],
    at: usize,
    what: &str,
) {
    let n = selected.len();
    if n < guarded.min {
        c.emit(
            &guarded.common,
            Some(at),
            "TLMD_93",
            format!(
                "{what}: at least {} {} needed; there {} {n}",
                guarded.min,
                text::is_are(guarded.min),
                text::is_are(n)
            ),
        );
    }
    // A soft limit is never checked.
    if let Some(limit) = &guarded.max
        && let Some(max) = limit.hard()
        && n > max
    {
        // The first one over the limit is the one to look at, so a
        // `max` of zero names the unit it bans.
        let line = selected.get(max).map_or(at, |&i| units[i].line);
        // sokf-implements: TLMD_159
        c.emit(
            &guarded.common,
            Some(line),
            "TLMD_159",
            text::at_limit(
                format!(
                    "{what}: at most {max} {} allowed; there {} {n}",
                    text::is_are(max),
                    text::is_are(n)
                ),
                &limit.when_at_limit,
            ),
        );
    }
}

/// Whether `unit` of `block` has `rule`'s shape, its own or its format's,
/// silently, read without its label.
fn satisfies_shape(c: &Checker<'_>, unit: &Unit, rule: &UnitRule, block: &Rule) -> bool {
    let read = c.read(unit, block, Some(rule));
    rule.fits(c.schema.formats_of(rule), &read.squashed.text, |k| {
        c.front_reading(k, rule)
    })
}

/// Each unit no rule took, reported: against the production it follows
/// furthest, with where it fails and that rule's example, or as matching
/// no rule where the block has no production.
// sokf-implements: TLMD_57
#[expect(
    clippy::too_many_arguments,
    reason = "each is a part of the report of a unit that no rule takes"
)]
fn untaken(
    c: &mut Checker<'_>,
    units: &[Unit],
    taken: &[bool],
    rules: &[UnitRule],
    block: &Rule,
    common: &RuleCommon,
    (whose, unit_is): (&str, &str),
    open: &str,
) {
    for (unit, seen) in units.iter().zip(taken) {
        if *seen {
            continue;
        }
        let text = squash(&unit.text);
        // The first of the productions the text follows furthest, where it
        // follows one at all; a text that follows none matches no rule. Each
        // production reads the text without the label that it finds.
        let best = rules
            .iter()
            .filter(|r| r.is_production())
            .map(|r| (r, c.read(unit, block, Some(r))))
            .fold(None::<(&UnitRule, Read, usize)>, |best, (r, read)| {
                let n = reach(c, r, &read.squashed.text);
                match best {
                    Some((_, _, m)) if m >= n => best,
                    _ => Some((r, read, n)),
                }
            })
            .filter(|(_, _, n)| *n > 0)
            .map(|(r, read, _)| (r, read));
        if let Some((r, read)) = best {
            // The column of the failure counts in the text without the
            // label, which the finding quotes as written.
            let reason = shape_failure(c, r, &read, unit_is);
            c.emit(
                &r.common,
                Some(unit.line),
                "TLMD_57",
                format!(
                    "{} matches no rule of {whose}; the nearest {reason}",
                    quoted(&read.shown.text)
                ),
            );
        } else {
            // No production reaches into the text, as none does whose
            // shape is a pattern, so the finding names the form that
            // the writer meant, by the examples, before the advice to
            // the schema's author.
            let meant = meant(c, unit, rules, block, unit_is);
            c.emit(
                common,
                Some(unit.line),
                if open == "lines-open" {
                    "TLMD_87"
                } else {
                    "TLMD_53"
                },
                format!(
                    "{} matches no rule of {whose}{meant}; declare it or set `{open}`",
                    quoted(&text)
                ),
            );
        }
        c.broke(unit);
    }
}

/// The form that a unit which no production reaches into was meant to
/// have, as the finding words it after the unit: the production whose
/// example shares the longest beginning with the unit, both read without
/// their labels, with why the unit fails it and its example; else, where
/// several share the longest, or none shares a beginning, the example of
/// each of them; and nothing where no production has an example.
// sokf-implements: TLMD_273
fn meant(c: &Checker<'_>, unit: &Unit, rules: &[UnitRule], block: &Rule, unit_is: &str) -> String {
    let examples = |r: &UnitRule| -> Vec<String> {
        let own: Vec<&str> = r.examples.iter().map(String::as_str).collect();
        let list = if own.is_empty() {
            r.format_in(c.schema.formats_of(r))
                .map(|f| f.examples())
                .unwrap_or_default()
        } else {
            own
        };
        list.iter()
            .map(|e| {
                c.schema
                    .unlabelled(&c.labels, block, Some(r), &r.read_text(e))
                    .0
            })
            .collect()
    };
    let productions: Vec<(&UnitRule, Read, Vec<String>)> = rules
        .iter()
        .filter(|r| r.is_production())
        .map(|r| (r, c.read(unit, block, Some(r)), examples(r)))
        .filter(|(_, _, e)| !e.is_empty())
        .collect();
    let shared = |read: &Read, e: &[String]| {
        e.iter()
            .map(|e| common_prefix(&read.squashed.text, e))
            .max()
            .unwrap_or(0)
    };
    let reach: Vec<usize> = productions.iter().map(|p| shared(&p.1, &p.2)).collect();
    let most = reach.iter().copied().max().unwrap_or(0);
    let nearest: Vec<&(&UnitRule, Read, Vec<String>)> = productions
        .iter()
        .zip(&reach)
        .filter(|(_, n)| **n == most)
        .map(|(p, _)| p)
        .collect();
    if let [(r, read, _)] = nearest.as_slice()
        && most > 0
    {
        format!("; the nearest {}", shape_failure(c, r, read, unit_is))
    } else {
        let shown: Vec<String> = nearest
            .iter()
            .filter_map(|(r, _, _)| {
                r.example().or_else(|| {
                    r.format_in(c.schema.formats_of(r))
                        .and_then(|f| f.examples().first().copied())
                })
            })
            .filter(|e| !e.is_empty())
            .map(text::code)
            .collect();
        if shown.is_empty() {
            String::new()
        } else {
            format!(
                "; {} {unit_is} of this kind reads {}",
                text::article(unit_is),
                shown.join(", or reads ")
            )
        }
    }
}

/// The example a shape failure shows: the failure is built from the rule,
/// and the example is the rule's one voice.
// sokf-implements: CLI-7_AC-2
// sokf-implements: TL_74
pub(super) fn reads(what: &str, example: Option<&str>) -> String {
    example
        .filter(|e| !e.is_empty())
        .map_or_else(String::new, |e| {
            format!(
                "; {} {what} of this kind reads {}",
                text::article(what),
                text::code(e)
            )
        })
}

/// The length in bytes of the longest beginning that `a` and `b` share,
/// ending at a character of both.
fn common_prefix(a: &str, b: &str) -> usize {
    a.char_indices()
        .zip(b.chars())
        .find(|((_, x), y)| x != y)
        .map_or_else(|| a.len().min(b.len()), |((i, _), _)| i)
}

/// How far `text` follows `rule`'s shape before it fails.
pub(super) fn reach(c: &Checker<'_>, rule: &UnitRule, text: &str) -> usize {
    rule.reach(c.schema.formats_of(rule), text)
}

/// Why the unit that `read` holds does not have `rule`'s shape, with the
/// example it shows.
fn shape_failure(c: &Checker<'_>, rule: &UnitRule, read: &Read, unit_is: &str) -> String {
    let text = read.squashed.text.as_str();
    match (&rule.shape, &rule.format) {
        (Some(_), _) => format!(
            "{}{}",
            shape_failure_of(rule, read).unwrap_or_default(),
            reads(unit_is, rule.example())
        ),
        (None, Some(name)) => match rule
            .format_in(c.schema.formats_of(rule))
            .map(|f| read.quoting(|q| f.matching_quoting(text, unit_is, q)))
        {
            Some(Err(reason)) => reason,
            _ => format!("format `{name}`"),
        },
        (None, None) => String::new(),
    }
}

/// A block's `rules`: as `lines`, and a unit no rule takes is an error
/// unless the block opens itself with `units-open`.
// sokf-implements: TLMD_53
pub(super) fn check_rules(
    c: &mut Checker<'_>,
    block: &Block,
    rules: &[UnitRule],
    rule: &Rule,
    section: Option<usize>,
) {
    let taken = apply_rules(
        c,
        &block.units,
        rules,
        rule,
        section,
        block.line,
        noun(rule.kind),
    );
    // A unit that no rule takes in an open block carries the block's label.
    if rule.units_open {
        for (unit, _) in block.units.iter().zip(&taken).filter(|(_, t)| !**t) {
            let read = c.read(unit, rule, None);
            if c.check_label(unit, rule, None, &read, true) {
                c.broke(unit);
            }
        }
    } else {
        untaken(
            c,
            &block.units,
            &taken,
            rules,
            rule,
            &rule.common,
            ("the block", unit_noun(c, rule.kind)),
            "units-open",
        );
    }
}