compmd 0.7.1

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
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
//! Block nodes, and CompMD's containers, slots and leaves built from the component lines among one parent's
//! children (spec §4, §10.3). A container opens and closes among the children of one CommonMark parent, so it nests
//! with lists and quotes (spec §4.1).

mod component_lines;

use super::Converter;
use super::definitions::CODE;
use super::params;
use super::source::right;
use crate::diagnostic::{Code, Diagnostic, Location};
use crate::tree::{
    Alert, Align, Blockquote, Code as CodeBlock, Container, FootnoteDefinition, Heading, Info,
    Interpolation, Leaf, LinkDefinition, List as ListNode, ListItem, Literal, Math, Node, Param,
    ParamValue, Parent, Point, Position, StringPart, Table, Void, Yaml, start_of,
};
use markdown::mdast;
use std::collections::HashSet;

/// The text alternative a rendered code block takes (spec §7.7).
const ALT: &str = "alt";

/// Where a param starts.
fn param_start(param: &Param) -> Location {
    start_of(param.position)
}

/// A container open around a nested parent, as that parent sees it.
#[derive(Clone)]
pub(super) struct Outer {
    name: String,
    opener: Point,
}

/// Which containers of the outer parents a closer in a nested parent closed (F032).
type Closed = HashSet<usize>;

/// A container being built.
struct Open {
    container: Container,
    opener: Point,
    /// Where each named slot's line is.
    slot_lines: Vec<Point>,
    /// The named slot content goes to now, or the default slot.
    current: Option<usize>,
    /// A closer in a nested list item or quote named it (F032): it closes at its parent's end without F004.
    closed_inside: bool,
}

impl Open {
    fn content(&mut self) -> &mut Vec<Node> {
        match self.current {
            Some(slot) => &mut self.container.slots[slot].children,
            None => &mut self.container.children,
        }
    }
}

/// Who takes the params of a continuation line: the opener or leaf right before it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Owner {
    Nobody,
    Opener,
    Leaf,
}

/// What building one parent's children keeps track of.
struct Scope<'o> {
    /// The containers open around this parent, outermost first.
    outer: &'o [Outer],
    /// The containers open in this parent, innermost last.
    open: Vec<Open>,
    out: Vec<Node>,
    closed_outer: Closed,
    owner: Owner,
    /// The line the previous child ends on, when it is a paragraph (W108).
    paragraph_end: Option<usize>,
}

impl Scope<'_> {
    fn push(&mut self, node: Node) {
        match self.open.last_mut() {
            Some(open) => open.content().push(node),
            None => self.out.push(node),
        }
    }

    fn last_leaf(&mut self) -> Option<&mut Leaf> {
        let last = match self.open.last_mut() {
            Some(open) => open.content().last_mut(),
            None => self.out.last_mut(),
        };
        match last {
            Some(Node::ComponentLeaf(leaf)) => Some(leaf),
            _ => None,
        }
    }

    fn close(&mut self, open: Open) {
        let mut container = open.container;
        container.auto_closed = container.close_position.is_none();
        self.push(Node::ComponentContainer(container));
    }

    /// The containers open around a parent nested in this one.
    fn nested(&self) -> Vec<Outer> {
        let own = self.open.iter().map(|open| Outer {
            name: open.container.name.clone(),
            opener: open.opener,
        });
        self.outer.iter().cloned().chain(own).collect()
    }
}

/// Where a unit of the document's blocks starts (incremental processing): the blocks and diagnostics before it.
pub(super) struct Mark {
    pub(super) nodes: usize,
    pub(super) diagnostics: usize,
    pub(super) start: Point,
    /// Where the block before it ends.
    pub(super) after: Point,
}

/// Where the units of the document's blocks start, and where its last block ends.
#[derive(Default)]
pub(super) struct Marks {
    pub(super) starts: Vec<Mark>,
    pub(super) end: Point,
}

/// A component line, as the fork found it.
struct ComponentLine {
    text: Vec<char>,
    position: Option<Position>,
    start: Point,
}

impl Converter<'_, '_> {
    /// The children of one parent, which ends at `end`, with the containers in `outer` open around it. Returns them
    /// and which of `outer` a closer in them closed. With `marks`, notes where each unit of them starts: a unit ends
    /// where a blank line follows and no container is open, unless a continuation line comes next.
    pub(super) fn blocks(
        &mut self,
        nodes: Vec<mdast::Node>,
        end: Point,
        outer: &[Outer],
        mut marks: Option<&mut Marks>,
    ) -> (Vec<Node>, Closed) {
        let mut scope = Scope {
            outer,
            open: Vec::new(),
            out: Vec::new(),
            closed_outer: Closed::new(),
            owner: Owner::Nobody,
            paragraph_end: None,
        };
        let mut before: Option<&markdown::unist::Point> = None;
        let positions: Vec<Option<markdown::unist::Position>> =
            nodes.iter().map(|node| node.position().cloned()).collect();
        for (node, position) in nodes.into_iter().zip(&positions) {
            if let (Some(marks), Some(position)) = (marks.as_deref_mut(), position) {
                let starts = before.is_none_or(|before| {
                    scope.open.is_empty()
                        && blank_between(self.source.text(), before.offset, position.start.offset)
                        && !is_continuation(&node)
                });
                if starts {
                    let start = self.source.point(position.start.offset);
                    marks.starts.push(Mark {
                        nodes: scope.out.len(),
                        diagnostics: self.diagnostics.len(),
                        start,
                        after: before.map_or(start, |before| self.source.point(before.offset)),
                    });
                }
                marks.end = self.source.point(position.end.offset);
                before = Some(&position.end);
            }
            if let mdast::Node::CompmdRaw(raw) = node {
                let position = self.source.position(raw.position.as_ref());
                let line = ComponentLine {
                    text: raw.value.chars().collect(),
                    start: position.map_or(end, |position| position.start),
                    position,
                };
                scope.owner = self.component_line(&line, &mut scope);
                scope.paragraph_end = None;
                continue;
            }
            let paragraph_end = matches!(node, mdast::Node::Paragraph(_))
                .then(|| {
                    node.position()
                        .map(|position| self.source.point(position.end.offset).line)
                })
                .flatten();
            let nested = scope.nested();
            let (converted, closed) = self.block(node, &nested);
            for index in closed {
                match index.checked_sub(outer.len()) {
                    Some(own) => scope.open[own].closed_inside = true,
                    None => {
                        scope.closed_outer.insert(index);
                    }
                }
            }
            if let Some(converted) = converted {
                scope.push(converted);
            }
            scope.owner = Owner::Nobody;
            scope.paragraph_end = paragraph_end;
        }
        while let Some(open) = scope.open.pop() {
            if !open.closed_inside {
                self.diagnostics.push(
                    Diagnostic::new(
                        Code::F004,
                        open.opener.into(),
                        format!("`::: {}` isn't closed", open.container.name),
                    )
                    .with_related(Location::from(end), "closed here"),
                );
            }
            scope.close(open);
        }
        (scope.out, scope.closed_outer)
    }

    /// One block, with the containers in `outer` open around it.
    fn block(&mut self, node: mdast::Node, outer: &[Outer]) -> (Option<Node>, Closed) {
        let mut closed = Closed::new();
        let mut children =
            |this: &mut Self, nodes: Vec<mdast::Node>, position: Option<Position>| {
                let end = position.map_or(super::START, |position| position.end);
                let (children, inner) = this.blocks(nodes, end, outer, None);
                closed.extend(inner);
                children
            };
        let node = match node {
            mdast::Node::Blockquote(quote) => {
                let position = self.source.position(quote.position.as_ref());
                let mut blockquote = Blockquote {
                    children: children(self, quote.children, position),
                    alert: None,
                    position,
                };
                if self.syntax.compmd {
                    mark_alert(&mut blockquote);
                }
                Node::Blockquote(blockquote)
            }
            mdast::Node::List(list) => {
                let mut items = Vec::new();
                for item in list.children {
                    let (item, inner) = self.block(item, outer);
                    closed.extend(inner);
                    items.extend(item);
                }
                Node::List(ListNode {
                    ordered: list.ordered,
                    start: list.start,
                    spread: list.spread,
                    children: items,
                    position: self.source.position(list.position.as_ref()),
                })
            }
            mdast::Node::ListItem(item) => {
                let position = self.source.position(item.position.as_ref());
                Node::ListItem(ListItem {
                    spread: item.spread,
                    checked: item.checked,
                    children: children(self, item.children, position),
                    position,
                })
            }
            mdast::Node::FootnoteDefinition(footnote) => {
                let position = self.source.position(footnote.position.as_ref());
                Node::FootnoteDefinition(FootnoteDefinition {
                    identifier: footnote.identifier,
                    label: footnote.label,
                    children: children(self, footnote.children, position),
                    position,
                })
            }
            other => return (self.leaf_block(other), closed),
        };
        (Some(node), closed)
    }

    /// A block that holds no blocks.
    fn leaf_block(&mut self, node: mdast::Node) -> Option<Node> {
        Some(match node {
            mdast::Node::Paragraph(paragraph) => {
                let position = self.source.position(paragraph.position.as_ref());
                let children = self.inlines(paragraph.children, false);
                match &children[..] {
                    [Node::Interpolation(only)] if self.syntax.compmd => {
                        Node::Interpolation(Interpolation {
                            path: only.path.clone(),
                            block: true,
                            position,
                        })
                    }
                    _ => Node::Paragraph(Parent { children, position }),
                }
            }
            mdast::Node::Heading(heading) => Node::Heading(Heading {
                depth: heading.depth,
                children: self.inlines(heading.children, false),
                position: self.source.position(heading.position.as_ref()),
            }),
            mdast::Node::Code(code) => return Some(self.code(code)),
            mdast::Node::Math(math) => Node::Math(Math {
                meta: math.meta,
                value: math.value,
                position: self.source.position(math.position.as_ref()),
            }),
            mdast::Node::Html(html) => {
                let position = self.source.position(html.position.as_ref());
                if self.syntax.compmd {
                    self.component_lines_in_html(&html.value, position);
                }
                Node::Html(Literal {
                    value: html.value,
                    position,
                })
            }
            mdast::Node::Table(table) => Node::Table(Table {
                align: table.align.into_iter().map(align).collect(),
                children: self.leaf_blocks(table.children),
                position: self.source.position(table.position.as_ref()),
            }),
            mdast::Node::TableRow(row) => Node::TableRow(Parent {
                children: self.leaf_blocks(row.children),
                position: self.source.position(row.position.as_ref()),
            }),
            mdast::Node::TableCell(cell) => Node::TableCell(Parent {
                children: self.inlines(cell.children, true),
                position: self.source.position(cell.position.as_ref()),
            }),
            mdast::Node::Definition(definition) => Node::Definition(LinkDefinition {
                url_parts: self.url_parts(&definition.url),
                identifier: definition.identifier,
                label: definition.label,
                url: definition.url,
                title: definition.title,
                position: self.source.position(definition.position.as_ref()),
            }),
            mdast::Node::ThematicBreak(rule) => Node::ThematicBreak(Void {
                position: self.source.position(rule.position.as_ref()),
            }),
            mdast::Node::Yaml(yaml) => Node::Yaml(Yaml {
                value: yaml.value,
                parsed: self.frontmatter.take(),
                position: self.source.position(yaml.position.as_ref()),
            }),
            other => return self.inline(other, false),
        })
    }

    fn leaf_blocks(&mut self, nodes: Vec<mdast::Node>) -> Vec<Node> {
        nodes
            .into_iter()
            .filter_map(|node| self.leaf_block(node))
            .collect()
    }

    /// A fenced code block: a component definition when its info string has `component=` (spec §7), display math
    /// when its language is `math` (spec §2.3).
    fn code(&mut self, code: mdast::Code) -> Node {
        let position = self.source.position(code.position.as_ref());
        let mut info = None;
        if self.syntax.compmd {
            if let Some(definition) = self.definition(&code, position) {
                return definition;
            }
            if code.lang.as_deref() == Some("math") {
                return Node::Math(Math {
                    meta: None,
                    value: code.value,
                    position,
                });
            }
            if code.lang.is_some() {
                info = Some(self.info(&code.value, position));
            }
        }
        Node::Code(CodeBlock {
            lang: code.lang,
            meta: code.meta,
            value: code.value,
            position,
            info,
        })
    }

    /// The block at `position`, whose text is `text`, as a code renderer's invocation (spec §7.7): its text as `code`,
    /// the param list after its language, and `alt`. What is wrong with them is kept, not reported: the block is
    /// content unless a code renderer renders it.
    fn info(&mut self, text: &str, position: Option<Position>) -> Info {
        let before = self.diagnostics.len();
        let mut params = Vec::new();
        let start = position.map_or(super::START, |position| position.start);
        let (line, line_start) = self.source.line(start.line).unwrap_or(("", start));
        let chars: Vec<char> = line.chars().collect();
        if let Some(brace) = chars.iter().position(|c| *c == '{') {
            let list = params::braced(&chars, brace);
            self.add_params_at(&mut params, list, |index| right(line_start, index));
        }
        let mut problems = self.diagnostics.split_off(before);
        let mut alt = None;
        params.retain(|param| match param.key.as_deref() {
            Some(CODE) => {
                problems.push(Diagnostic::new(
                    Code::F017,
                    param_start(param),
                    "`code` is the block's text, so it can't be given here; ignored",
                ));
                false
            }
            Some(ALT) => {
                match param.value {
                    ParamValue::Bare(_) | ParamValue::String(_) => alt = Some(param.clone()),
                    _ => problems.push(Diagnostic::new(
                        Code::F009,
                        param_start(param),
                        "`alt` is text: write it bare or quoted; ignored",
                    )),
                }
                false
            }
            _ => true,
        });
        params.insert(
            0,
            Param {
                key: Some(CODE.to_string()),
                breakpoint: None,
                value: ParamValue::String(vec![StringPart::Text(Literal {
                    value: text.to_string(),
                    position: None,
                })]),
                position: None,
            },
        );
        Info {
            params,
            alt,
            problems,
        }
    }

    /// W116: a line inside an HTML block that starts with `::` is HTML, not a component line (spec §3.2).
    fn component_lines_in_html(&mut self, html: &str, position: Option<Position>) {
        let start = position.map_or(super::START, |position| position.start);
        for (i, line) in html.split('\n').enumerate().skip(1) {
            let indent = line.bytes().take_while(|b| *b == b' ').count();
            if indent <= 3 && line[indent..].starts_with("::") {
                self.diagnose(
                    Code::W116,
                    Location::new(start.line + i, indent + 1),
                    "this line is part of the HTML block above it, not a component line; put a blank line before it",
                );
            }
        }
    }
}

/// Whether the text between byte `from` and byte `to` is white space with a blank line in it.
fn blank_between(text: &str, from: usize, to: usize) -> bool {
    let gap = &text[from..to];
    let endings =
        gap.matches('\n').count() + gap.matches('\r').count() - gap.matches("\r\n").count();
    endings >= 2 && gap.chars().all(char::is_whitespace)
}

/// Whether `node` is a continuation line, `::: + params`, which belongs with the component line before it.
fn is_continuation(node: &mdast::Node) -> bool {
    matches!(node, mdast::Node::CompmdRaw(raw) if raw.value.strip_prefix(":::").is_some_and(|rest| rest.trim_start_matches([' ', '\t']).starts_with('+')))
}

fn align(kind: mdast::AlignKind) -> Option<Align> {
    match kind {
        mdast::AlignKind::Left => Some(Align::Left),
        mdast::AlignKind::Right => Some(Align::Right),
        mdast::AlignKind::Center => Some(Align::Center),
        mdast::AlignKind::None => None,
    }
}

/// `> [!NOTE]` on a quote's first line makes it an alert, without that line (spec §2.3).
fn mark_alert(quote: &mut Blockquote) {
    let Some(Node::Paragraph(first)) = quote.children.first_mut() else {
        return;
    };
    let Some(Node::Text(text)) = first.children.first_mut() else {
        return;
    };
    let Some((alert, marker_len)) = alert_marker(&text.value) else {
        return;
    };
    let rest = &text.value[marker_len..];
    if rest.is_empty() {
        first.children.remove(0);
    } else {
        if let Some(position) = &mut text.position {
            position.start = Point {
                line: position.start.line + 1,
                column: 1,
                offset: position.start.offset + text.value[..marker_len].chars().count(),
            };
        }
        text.value = rest.to_string();
    }
    if first.children.is_empty() {
        quote.children.remove(0);
    }
    quote.alert = Some(alert);
}

/// The alert `[!TYPE]` that starts `text` alone on its line, and the bytes it takes with its line ending.
fn alert_marker(text: &str) -> Option<(Alert, usize)> {
    let name_end = text.strip_prefix("[!")?.find(']')? + 2;
    let alert = match text[2..name_end].to_ascii_lowercase().as_str() {
        "note" => Alert::Note,
        "tip" => Alert::Tip,
        "important" => Alert::Important,
        "warning" => Alert::Warning,
        "caution" => Alert::Caution,
        _ => return None,
    };
    let after = &text[name_end + 1..];
    let spaces = after.len() - after.trim_start_matches([' ', '\t']).len();
    let rest = &after[spaces..];
    let ending = match rest.as_bytes() {
        [] => 0,
        [b'\n', ..] => 1,
        _ => return None,
    };
    Some((alert, name_end + 1 + spaces + ending))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn alert_markers_stand_alone_on_their_line() {
        assert_eq!(alert_marker("[!NOTE]"), Some((Alert::Note, 7)));
        assert_eq!(alert_marker("[!tip] \nRest"), Some((Alert::Tip, 8)));
        assert_eq!(alert_marker("[!Caution]\t"), Some((Alert::Caution, 11)));
        assert_eq!(alert_marker("[!WARNING] text"), None);
        assert_eq!(alert_marker("[!OTHER]"), None);
        assert_eq!(alert_marker("[!NOTE"), None);
        assert_eq!(alert_marker("text"), None);
    }
}