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
//! The blocks of a section in the scaffold: each block's units, its
//! guidance and its marker, and the refusal of a block that the next one
//! would join.

use super::{Deriver, guide};
use crate::{
    check::is_run,
    grammar::{Block, Lang, LifecycleDimension, States},
    markdown::BlockKind,
    text,
};

impl Deriver<'_> {
    pub(super) fn blocks(&mut self, rules: Option<&[Block]>, out: &mut Vec<String>) {
        let rules = rules.unwrap_or(&[]);
        self.meetings(rules);
        // The kinds of the required blocks that a skeleton leaves out: a
        // later block of such a kind would stand where the check expects
        // the block left out, and be read as that one, so it is left out
        // too, and the check reports both as missing.
        let mut left_out: Vec<BlockKind> = Vec::new();
        let mut i = 0;
        while i < rules.len() {
            // A run of optional blocks is one region: a label and the list
            // under it are one decision, not two.
            if rules[i].optional_at(self.states, &self.schema.core.lifecycle) && !self.in_optional {
                let mut j = i;
                while j < rules.len()
                    && rules[j].optional_at(self.states, &self.schema.core.lifecycle)
                {
                    j += 1;
                }
                // sokf-implements: MD-17_AC-5
                // sokf-implements: TLMD_306
                if self.skeleton() {
                    i = j;
                    continue;
                }
                self.optional_region(out, |d, out| {
                    for block in &rules[i..j] {
                        d.one_block(block, out);
                    }
                });
                i = j;
                continue;
            }
            // sokf-implements: TLMD_311
            let kind = rules[i].first_position(self.states).map(|b| b.kind);
            if self.skeleton() && kind.is_some_and(|k| left_out.contains(&k)) {
                i += 1;
                continue;
            }
            let before = out.len();
            self.one_block(&rules[i], out);
            let required =
                rules[i].common.only.admits(self.states) && rules[i].hard_max() != Some(0);
            if self.skeleton()
                && required
                && out.len() == before
                && let Some(k) = kind
            {
                left_out.push(k);
            }
            i += 1;
        }
    }

    fn one_block(&mut self, block: &Block, out: &mut Vec<String>) {
        // A block the states exclude is not this scaffold's, and one
        // whose hard `max` admits no unit bans rather than demands.
        let optional = block.optional_at(self.states, &self.schema.core.lifecycle);
        if !block.common.only.admits(self.states)
            || block.hard_max() == Some(0)
            || (optional && self.skeleton())
        {
            return;
        }
        // An optional block is written where the derivation can write it,
        // and left out where a rule inside it offers nothing, as an
        // optional section is.
        // sokf-implements: TLMD_123
        self.attempt(optional, out, |d, out| d.block(block, out));
    }

    /// Write `block`, and record its text as the block's example, unless a
    /// refusal inside it stands, as a section records its own.
    fn block(&mut self, block: &Block, out: &mut Vec<String>) {
        let start = out.len();
        let refused = self.refusals.len();
        self.write_block(block, out);
        if self.refusals.len() == refused {
            let lines = out[start..].to_vec();
            self.record_block(block, &lines);
        }
    }

    fn write_block(&mut self, block: &Block, out: &mut Vec<String>) {
        // The host's words and the `when-at-limit` of each limit, and the
        // messages of the block's bans, follow its guidance, as the host's
        // guide gives them.
        // sokf-implements: TLMD_195
        // sokf-implements: TLMD_231
        // sokf-implements: MD-7_AC-14
        let text = guide::block_text(self.schema, self.host, block);
        self.guidance(text.as_deref(), out);
        if block.kind == BlockKind::Group {
            // A group's `rule-id` names the keys captured inside it, as the
            // check files them.
            let inner = block.rule_id.clone().or(self.group_rule.clone());
            let held = std::mem::replace(&mut self.group_rule, inner);
            for _ in 0..block.min.max(1) {
                self.marker(&block.common, out);
                self.blocks(block.blocks.as_deref(), out);
            }
            self.group_rule = held;
            return;
        }
        let units = self.units_of(block);
        // A skeleton writes a block only where the schema fixes a unit of
        // it, or the block has no unit, as a thematic break has none.
        // sokf-implements: MD-17_AC-5
        // sokf-implements: TLMD_308
        if self.skeleton()
            && (units.is_empty() || example_header(block))
            && block.kind != BlockKind::ThematicBreak
        {
            return;
        }
        // Each fence of a code block is a block of its own, so each one
        // carries its own `only` marker, which the match below writes.
        if block.kind != BlockKind::Code {
            self.marker(&block.common, out);
        }
        match block.kind {
            BlockKind::Prose => {
                for text in units {
                    out.push(text);
                    out.push(String::new());
                }
            }
            BlockKind::BulletList => {
                for text in units {
                    out.push(format!("- {text}"));
                }
                out.push(String::new());
            }
            BlockKind::NumberedList => {
                for (i, text) in units.iter().enumerate() {
                    out.push(format!("{}. {text}", i + 1));
                }
                out.push(String::new());
            }
            BlockKind::Blockquote => {
                for (i, text) in units.iter().enumerate() {
                    if i > 0 {
                        out.push(">".to_string());
                    }
                    out.push(format!("> {text}"));
                }
                out.push(String::new());
            }
            BlockKind::Table => self.table(block, units, out),
            // A fence of three backticks, or the `fence` of the block where
            // that is more, or one more than the longest run of backticks
            // in the example where that is more still, so that the example
            // never ends the block early.
            // sokf-implements: TLMD_265
            // sokf-implements: MD-7_AC-16
            BlockKind::Code => {
                let tag = match &block.lang {
                    Some(Lang::Tags(tags)) => tags.first().cloned().unwrap_or_default(),
                    Some(Lang::Any) | None => "text".to_string(),
                };
                for text in units {
                    let longest = text
                        .split(|c| c != '`')
                        .map(str::len)
                        .max()
                        .unwrap_or_default();
                    let fence = "`".repeat(block.fence.max(3).max(longest + 1));
                    self.marker(&block.common, out);
                    out.push(format!("{fence}{tag}"));
                    out.extend(text.lines().map(str::to_string));
                    out.push(fence.clone());
                    out.push(String::new());
                }
            }
            BlockKind::ThematicBreak => {
                out.push("---".to_string());
                out.push(String::new());
            }
            // A block that names a file takes its example like any other: the
            // target it names is a placeholder, reported in the new document
            // until the author replaces it. With no example, `units_of` has
            // already refused it.
            BlockKind::Html | BlockKind::Image | BlockKind::Region | BlockKind::References => {
                for text in units {
                    out.extend(text.lines().map(str::to_string));
                }
                out.push(String::new());
            }
            BlockKind::Group => unreachable!("a group is taken above"),
            BlockKind::Heading => unreachable!("no schema declares a heading block"),
        }
        self.follows(block);
    }

    /// The rows of a table: its header, its separator and its units. A
    /// table with no declared columns names the header of its scaffold
    /// under `example-columns`, so that the separator has one `---` for
    /// each cell of the header.
    // sokf-implements: TLMD_206
    // sokf-implements: MD-7_AC-13
    fn table(&self, block: &Block, units: Vec<String>, out: &mut Vec<String>) {
        let header = if self.skeleton() {
            None
        } else {
            block.example_columns.as_deref()
        };
        let columns = header.or(block.columns.as_deref()).unwrap_or_default();
        // A `|` in a name would end its cell, so the header escapes it, as
        // a GFM table writes a pipe inside a cell.
        let names: Vec<String> = columns.iter().map(|c| c.replace('|', "\\|")).collect();
        out.push(format!("| {} |", names.join(" | ")));
        out.push(format!(
            "| {} |",
            columns
                .iter()
                .map(|_| "---")
                .collect::<Vec<_>>()
                .join(" | ")
        ));
        for text in units {
            out.push(format!("| {text} |"));
        }
        out.push(String::new());
    }

    /// Refuse the derivation where a position whose units have no shape
    /// of their own can stand directly before a position of its kind: the
    /// two are one block in a document, the first takes all of it, and no
    /// count divides a run. The positions between them, where there are
    /// any, are optional, so a document can leave them out. A group that
    /// can repeat, and closes with such a position and opens with its kind,
    /// meets itself. A later group whose opening has a shape and is
    /// followed by a block of another kind takes the end of the run by that
    /// shape (`TLMD_193`), so the position before it meets nothing.
    // sokf-implements: MD-7_AC-11
    // sokf-implements: TLMD_149
    fn meetings(&mut self, rules: &[Block]) {
        let states = self.states;
        let lifecycle = &self.schema.core.lifecycle[..];
        // A block whose hard `max` of zero bans it is written nowhere, so a
        // document leaves it out as it leaves out an optional one, but the
        // check still reads it as a position that takes the block after a run.
        let admitted: Vec<&Block> = rules
            .iter()
            .filter(|b| b.common.only.admits(states))
            .collect();
        let banned = |b: &Block| b.hard_max() == Some(0);
        let mut met: Vec<&Block> = Vec::new();
        for (i, b) in admitted.iter().enumerate() {
            if banned(b) {
                continue;
            }
            for last in closings(b, states, lifecycle) {
                if !is_run(last.kind) || !takes_more(last) {
                    continue;
                }
                let later = &admitted[i + 1..];
                // The check reserves the end of a run only for the position
                // that takes the run in the list of the later group, never
                // across the end of a group that the run closes.
                let own = std::ptr::eq(last, *b);
                let opened = |next: &Block| {
                    openings(next, states, lifecycle).iter().any(|o| {
                        o.kind == last.kind && !(own && reserved(later, next, o, states, lifecycle))
                    })
                };
                // The next repetition of a group is no later group, so no
                // reservation takes the end of the run for it.
                let mut meets = b.kind == BlockKind::Group
                    && b.hard_max().is_none_or(|m| m > 1)
                    && openings(b, states, lifecycle)
                        .iter()
                        .any(|o| o.kind == last.kind);
                for next in &admitted[i + 1..] {
                    if meets {
                        break;
                    }
                    if banned(next) {
                        continue;
                    }
                    meets = opened(next);
                    if !next.optional_at(states, lifecycle) {
                        break;
                    }
                }
                if meets && !met.iter().any(|m| std::ptr::eq(*m, last)) {
                    met.push(last);
                }
            }
        }
        for last in met {
            let kind = last.kind.name();
            self.refuse_on(
                last.common.line,
                "TLMD_149",
                format!(
                    "{} `{kind}` block whose units have no shape of their own can stand directly before another `{kind}` block, which a document reads as one block, so the first takes all of it; give the units of the first block a shape that the units of the second do not have, or put the second under a heading of its own",
                    text::article(kind)
                ),
            );
        }
    }

    /// Record the block just written, whose kind tells an item what its
    /// nested blocks open with.
    fn follows(&mut self, block: &Block) {
        self.kinds.push(block.kind);
    }
}

/// Whether `block` is a table whose header only `example-columns` names,
/// an example that a skeleton doesn't write.
fn example_header(block: &Block) -> bool {
    block.kind == BlockKind::Table && block.columns.as_deref().is_none_or(<[String]>::is_empty)
}

/// The blocks that `b` can end with at `states`: `b` itself, or for a
/// group, what its last admitted inner block can end with, and what the
/// block before it can end with while the blocks after are optional.
fn closings<'b>(
    b: &'b Block,
    states: &'b States,
    lifecycle: &[LifecycleDimension],
) -> Vec<&'b Block> {
    ends(b, states, lifecycle, true)
}

/// The blocks that `b` can open with at `states`, as `closings` reads the
/// end of a group.
fn openings<'b>(
    b: &'b Block,
    states: &'b States,
    lifecycle: &[LifecycleDimension],
) -> Vec<&'b Block> {
    ends(b, states, lifecycle, false)
}

/// The blocks that `b` can open with, or close with where `last`: for a
/// group, those of each inner block from that end, up to and with the
/// first that is not optional.
fn ends<'b>(
    b: &'b Block,
    states: &'b States,
    lifecycle: &[LifecycleDimension],
    last: bool,
) -> Vec<&'b Block> {
    if b.kind != BlockKind::Group {
        return vec![b];
    }
    let mut inner: Vec<&Block> = b.admitted(states).collect();
    if last {
        inner.reverse();
    }
    let mut out = Vec::new();
    for i in inner {
        out.extend(ends(i, states, lifecycle, last));
        if !i.optional_at(states, lifecycle) {
            break;
        }
    }
    out
}

/// Whether the group `next` takes the end of a run by the shape of its
/// opening `o` in every document, as `reserve_for` reserves it in the
/// check (`TLMD_193`): `o` is the group's first inner block, required and with
/// a shape, the group's second block is required and of another kind, and
/// no other position of `later`, the positions after the run, opens with
/// that kind and so takes the block after the run itself.
fn reserved(
    later: &[&Block],
    next: &Block,
    o: &Block,
    states: &States,
    lifecycle: &[LifecycleDimension],
) -> bool {
    let mut inner = next.admitted(states);
    let (Some(first), Some(second)) = (inner.next(), inner.next()) else {
        return false;
    };
    if next.kind != BlockKind::Group
        || !std::ptr::eq(first, o)
        || o.optional_at(states, lifecycle)
        || takes_more(o)
    {
        return false;
    }
    let Some(after) = second.first_position(states).map(|s| s.kind) else {
        return false;
    };
    !first.optional_at(states, lifecycle)
        && !second.optional_at(states, lifecycle)
        && after != o.kind
        && !later
            .iter()
            .filter(|p| !std::ptr::eq(**p, next))
            .any(|p| p.first_position(states).is_some_and(|f| f.kind == after))
}

/// Whether a block rule takes every unit of a run: no shape, format, ban,
/// guard or sequence can stop it at a unit, and no count divides a run.
fn takes_more(block: &Block) -> bool {
    block.sequence.is_none()
        && block.rules.is_none()
        && block.each.as_ref().is_none_or(|u| {
            u.shape.is_none() && u.format.is_none() && u.prohibited_patterns.is_empty()
        })
}