compmd 0.11.0

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
//! Stage 4b, evaluating (spec §8, §9, §11, §12.3): the expanded tree. Every `compmd` definition, `if`, `each`,
//! `value` and interpolation is replaced by what it produces; `box`, the input components and host-language
//! components stay as nodes, their params evaluated. Then the layout checks (W114, W119) run on the result.
//!
//! What validating refused is treated as absent (spec §10.3), and not reported again: a refused param is not given,
//! an unknown path is shown as written, a component that can't render renders its fallback.

mod blocks;
mod components;
mod contrast;
mod destinations;
mod env;
mod flow;
mod fonts;
mod image_box;
mod layout;
mod limits;
mod origins;
mod params;
mod text;

use crate::cel::{Error, Program, Value, Values};
use crate::context::RenderContext;
use crate::diagnostic::{Code, Diagnostic, Location, Mode, Stage};
use crate::expanded::{self, Content, Root};
use crate::lines::Lines;
use crate::load::Loaded;
use crate::md::Md;
use crate::resolve::{DocumentId, Renderer, Resolved};
use crate::tree::{self, Move, Node};
use crate::validate::Validated;
use crate::validate::scope::Scope;
use crate::validate::universal::Universal;
pub(crate) use blocks::splice;
use blocks::{Block, rooted};
use env::Env;
pub(crate) use limits::Used;
use std::collections::HashMap;
use std::ops;
use std::rc::Rc;

/// The size of the expanded tree every processor renders (spec §8.5).
pub const LIMIT: usize = 100_000;

/// The iterations and invocations every processor does in one expansion (spec §8.5).
pub const WORK: usize = 1_000_000;

/// What expanding needs besides the document, its data and the render context.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
    /// Whether every expanded node gets its `origin` (the `origins` feature, spec §12.3).
    pub origins: bool,
    /// The most nodes the expanded tree may have; beyond it, F034 (spec §8.5).
    pub limit: usize,
    /// The most iterations (of `each` and template slots) and invocations (of components, `each` and template
    /// slots among them) expanding may do; beyond it, F034 (spec §8.5).
    pub work: usize,
    /// Whether errors fail the result (spec §10.1): [`Processor::failed`](crate::Processor#method.failed).
    pub mode: Mode,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            origins: false,
            limit: LIMIT,
            work: WORK,
            mode: Mode::default(),
        }
    }
}

/// The result of expanding: the expanded tree and the diagnostics of stage 4b.
#[derive(Clone, Debug)]
pub(crate) struct Expanded {
    /// The expanded tree.
    pub(crate) root: Root,
    /// The diagnostics of stage 4b.
    pub(crate) diagnostics: Vec<Diagnostic>,
    /// What each top-level block of the processed document gave, so that an edit expands only the blocks it
    /// changes; `None` when text that two blocks gave was joined, which an edit can't take apart.
    pub(crate) blocks: Option<Vec<Block>>,
    /// What the expansion replaced in the expanded tree before it: `None` when it replaced all of it.
    pub(crate) replaced: Option<Replaced>,
    /// What it spent of its limits.
    pub(crate) used: Used,
}

/// The top-level nodes of an expanded tree that an edit replaced, how many replace them, and how far the nodes after
/// them moved.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Replaced {
    pub(crate) nodes: ops::Range<usize>,
    pub(crate) inserted: usize,
    pub(crate) by: Move,
}

/// A diagnostic evaluating found, with its code, document and place when it is reported once (spec §10.4).
#[derive(Clone, Debug)]
struct Report {
    once: Option<(Code, DocumentId, Location)>,
    diagnostic: Diagnostic,
}

/// Expands a document, stage 4b of spec §11: the expanded tree of `resolved`'s processed document, with what
/// `validated` refused left out, `loaded`'s inputs and data, and `context`'s time and zone.
pub(crate) fn expand(
    resolved: &Resolved,
    validated: &Validated,
    loaded: &Loaded,
    context: &RenderContext,
    options: &Options,
) -> Expanded {
    let mut expander = Expander::new(resolved, validated, loaded, context, options);
    let env = Env::document(&expander, resolved.main);
    let mut children = Vec::new();
    let mut blocks = Vec::new();
    for block in &resolved.document(resolved.main).root.children {
        let (nodes, given) = expander.block(block, &env);
        children.extend(nodes);
        blocks.push(given);
    }
    rooted(resolved, children, blocks, loaded, None, expander.used())
}

/// Expands one document.
struct Expander<'r> {
    resolved: &'r Resolved,
    validated: &'r Validated,
    options: &'r Options,
    /// Each document's `md`, without `loop`, and its `md.` functions.
    md: HashMap<DocumentId, (Value, Md<'r>)>,
    /// Each document's lines, for where in it an interpolation's path is.
    lines: HashMap<DocumentId, Lines<'r>>,
    /// The programs of the paths and defaults this render evaluates; validating keeps those of expressions.
    programs: HashMap<String, Result<Rc<Program>, Error>>,
    /// The depth of the last heading expanded, in output order, which relative headings follow (spec §7.2).
    last_heading: u8,
    /// Whether `last_heading` is still the one the block being expanded started with, and whether the block read it
    /// while it was.
    heading_kept: bool,
    heading_read: bool,
    /// The nodes made so far, against the limit.
    made: usize,
    /// The iterations and invocations done so far, against the work limit.
    worked: usize,
    /// The invocations under way, against the nesting limit (spec §8.5); and whether one crossed it, so the
    /// invocations in what it renders instead aren't reported again.
    invocations: usize,
    too_deep: bool,
    /// The expansions under way (`each`, template slots, invocations), innermost last, with where each is; and,
    /// once the limit is crossed, how many were under way then.
    expanding: Vec<(DocumentId, Location)>,
    crossed: Option<usize>,
    /// What evaluating the block being expanded reported.
    reports: Vec<Report>,
    /// The expanded roots of the processed document's examples, by where each fence starts.
    examples: &'r HashMap<usize, Root>,
}

impl<'r> Expander<'r> {
    fn new(
        resolved: &'r Resolved,
        validated: &'r Validated,
        loaded: &'r Loaded,
        context: &'r RenderContext,
        options: &'r Options,
    ) -> Self {
        let md = resolved
            .ids()
            .map(|id| {
                let settings = &resolved.document(id).settings;
                let mut md = context.md(settings).data(loaded.data(id));
                if id == resolved.main {
                    md = md.input(&loaded.inputs);
                }
                (id, (md.into(), context.functions(settings)))
            })
            .collect();
        let lines = resolved
            .ids()
            .map(|id| (id, resolved.document(id).lines()))
            .collect();
        Self {
            resolved,
            validated,
            options,
            md,
            lines,
            programs: HashMap::new(),
            last_heading: 0,
            heading_kept: true,
            heading_read: false,
            made: 0,
            worked: 0,
            invocations: 0,
            too_deep: false,
            expanding: Vec::new(),
            crossed: None,
            reports: Vec::new(),
            examples: &loaded.examples,
        }
    }

    /// The depth of the last heading, which a body with relative headings reads.
    fn heading_depth(&mut self) -> u8 {
        self.heading_read |= self.heading_kept;
        self.last_heading
    }

    /// `md` of the document `id`.
    fn md(&self, id: DocumentId) -> Value {
        self.md[&id].0.clone()
    }

    /// The variables a document's body starts with: its `md`.
    fn values(&self, id: DocumentId) -> Values {
        Values::default().with("md", self.md(id))
    }

    /// What a document's body sees.
    fn scope(&self, id: DocumentId) -> Scope<'r> {
        Scope::body(self.resolved, id)
    }

    /// Evaluates an expression written in `env`'s document, with the program validating parsed; interpolation paths
    /// and declared defaults, which validating doesn't parse, are parsed here once.
    fn evaluate(&mut self, source: &str, env: &Env) -> Result<Value, Error> {
        let program = match self.validated.program(source) {
            Some(program) => Rc::clone(program),
            None => self
                .programs
                .entry(source.to_string())
                .or_insert_with(|| Program::parse(source).map(Rc::new))
                .clone()?,
        };
        program.evaluate(&env.values, &self.md[&env.document].1)
    }

    /// Reports a diagnostic found in `env`'s document, once per code and place.
    fn report(&mut self, code: Code, env: &Env, at: Location, message: impl Into<String>) {
        self.reports.push(Report {
            once: Some((code, env.document, at)),
            diagnostic: Diagnostic::new(code, at, message)
                .in_stage(Stage::Evaluate)
                .in_file(self.resolved.file(env.document)),
        });
    }

    /// A list of nodes expanded, adjacent text joined.
    fn list(&mut self, nodes: &'r [Node], env: &Env<'r>) -> Vec<expanded::Node> {
        let mut out = Vec::new();
        for node in nodes {
            self.node(node, env, &mut out);
        }
        text::joined(out)
    }

    /// Inline nodes expanded without joining text, as a fallback keeps them.
    fn inline(&mut self, nodes: &'r [Node], env: &Env<'r>) -> Vec<expanded::Node> {
        let mut out = Vec::new();
        for node in nodes {
            self.node(node, env, &mut out);
        }
        out
    }

    /// A node expanded into `out`: what it produces, or for an mdast node, itself with its children expanded and a
    /// heading at its computed depth.
    fn node(&mut self, node: &'r Node, env: &Env<'r>, out: &mut Vec<expanded::Node>) {
        let content = match node {
            Node::Yaml(_)
            | Node::Toml(_)
            | Node::ComponentDefinition(_)
            | Node::ComponentSignature(_)
            | Node::ComponentSlot(_) => return,
            Node::Interpolation(interpolation) => {
                return self.interpolation(interpolation, env, out);
            }
            Node::ComponentContainer(container) => {
                let invocation = components::Invocation::container(node, container);
                return self.component(invocation, env, out);
            }
            Node::ComponentLeaf(leaf) => {
                return self.component(components::Invocation::leaf(node, leaf), env, out);
            }
            Node::ComponentInline(leaf) => {
                return self.component(components::Invocation::inline(node, leaf), env, out);
            }
            Node::Link(link) => return self.link(link, node, env, out),
            Node::Image(image) => return self.image(image, node, env, out),
            Node::Blockquote(quote) => Content::Blockquote(tree::Blockquote {
                children: self.list(&quote.children, env),
                alert: quote.alert,
                position: None,
            }),
            Node::Break(_) => Content::Break(tree::Void::default()),
            Node::Code(code) => match self.code(node, code, env) {
                Ok(content) => content,
                Err(invocation) => return self.component(invocation, env, out),
            },
            Node::Definition(definition) => {
                Content::Definition(self.definition(definition, node, env))
            }
            Node::Delete(delete) => Content::Delete(self.parent(&delete.children, env)),
            Node::Emphasis(emphasis) => Content::Emphasis(self.parent(&emphasis.children, env)),
            Node::FootnoteDefinition(footnote) => {
                Content::FootnoteDefinition(self.footnote(footnote, env))
            }
            Node::FootnoteReference(reference) => Content::FootnoteReference(tree::Reference {
                position: None,
                ..reference.clone()
            }),
            Node::Heading(heading) => Content::Heading(self.heading(heading, env)),
            Node::Html(html) => Content::Html(literal(&html.value)),
            Node::ImageReference(image) => Content::ImageReference(tree::ImageReference {
                position: None,
                ..image.clone()
            }),
            Node::InlineCode(code) => Content::InlineCode(literal(&code.value)),
            Node::InlineMath(math) => Content::InlineMath(literal(&math.value)),
            Node::LinkReference(link) => Content::LinkReference(tree::LinkReference {
                children: self.list(&link.children, env),
                reference_type: link.reference_type,
                identifier: link.identifier.clone(),
                label: link.label.clone(),
                position: None,
            }),
            Node::List(list) => Content::List(tree::List {
                ordered: list.ordered,
                start: list.start,
                spread: list.spread,
                children: self.list(&list.children, env),
                position: None,
            }),
            Node::ListItem(item) => Content::ListItem(tree::ListItem {
                spread: item.spread,
                checked: item.checked,
                children: self.list(&item.children, env),
                position: None,
            }),
            Node::Math(math) => Content::Math(tree::Math {
                position: None,
                ..math.clone()
            }),
            Node::Paragraph(paragraph) => Content::Paragraph(self.parent(&paragraph.children, env)),
            Node::Strong(strong) => Content::Strong(self.parent(&strong.children, env)),
            Node::Table(table) => Content::Table(tree::Table {
                align: table.align.clone(),
                children: self.list(&table.children, env),
                position: None,
            }),
            Node::TableCell(cell) => Content::TableCell(self.parent(&cell.children, env)),
            Node::TableRow(row) => Content::TableRow(self.parent(&row.children, env)),
            Node::Text(text) => Content::Text(literal(&text.value)),
            Node::ThematicBreak(_) => Content::ThematicBreak(tree::Void::default()),
            Node::WikiLink(link) => Content::WikiLink(tree::WikiLink {
                position: None,
                ..link.clone()
            }),
        };
        let made = self.made(content, origins::of(node, env));
        out.push(made);
    }

    /// A footnote definition with its content expanded.
    fn footnote(
        &mut self,
        footnote: &'r tree::FootnoteDefinition,
        env: &Env<'r>,
    ) -> tree::FootnoteDefinition<expanded::Node> {
        tree::FootnoteDefinition {
            identifier: footnote.identifier.clone(),
            label: footnote.label.clone(),
            children: self.list(&footnote.children, env),
            position: None,
        }
    }

    /// A code block: as the invocation of the code renderer that draws it (spec §7.7), unless it is `render=source`;
    /// an example (spec §7.8); or a code block.
    fn code(
        &mut self,
        node: &'r Node,
        code: &'r tree::Code,
        env: &Env<'r>,
    ) -> Result<Content, components::Invocation<'r>> {
        match (self.renderer(code, env), code.info.as_ref()) {
            (Some(_), Some(info)) if !info.render.draws() => Ok(Content::Code(expanded::Code {
                render: Some(info.render),
                ..plain_code(code)
            })),
            (Some(name), _) => Err(components::Invocation::code(node, code, name)),
            (None, _) => Ok(self
                .example(code, env)
                .unwrap_or_else(|| Content::Code(plain_code(code)))),
        }
    }

    /// `code` as an example (spec §7.8), when it is one of the processed document's: what it shows, its box's params,
    /// and its expanded root.
    fn example(&mut self, code: &'r tree::Code, env: &Env<'r>) -> Option<Content> {
        let info = code.info.as_ref()?;
        if code.lang.as_deref() != Some("compmd")
            || env.document != self.resolved.main
            || !info.render.draws()
        {
            return None;
        }
        let root = self.examples.get(&code.position?.start.offset)?;
        let given: Vec<&'r tree::Param> = info
            .params
            .iter()
            .filter(|param| {
                let key = params::key_of(param);
                (key == "class" || key == "id" || Universal::from_name(key).is_some())
                    && !self.validated.refuses_param(env.document, param)
            })
            .collect();
        let evaluated = self.evaluated(&given, None, env);
        Some(Content::Code(expanded::Code {
            render: Some(info.render),
            params: params::boxed(Vec::new(), evaluated),
            document: Some(Box::new(root.clone())),
            ..plain_code(code)
        }))
    }

    /// The name of the code renderer that renders `code` in `env`'s document, when one alone does (spec §7.7).
    fn renderer(&self, code: &tree::Code, env: &Env<'r>) -> Option<&'r str> {
        code.info.as_ref()?;
        let renderers = &self.resolved.document(env.document).renderers;
        match renderers.get(code.lang.as_deref()?)? {
            Renderer::Component(name, _) => Some(name),
            Renderer::Ambiguous(_) => None,
        }
    }

    /// A link reference definition, its URL's interpolations filled in; empty when they would give it a scheme it
    /// may not have (W109).
    fn definition(
        &mut self,
        definition: &tree::LinkDefinition,
        node: &Node,
        env: &Env<'r>,
    ) -> tree::LinkDefinition {
        tree::LinkDefinition {
            url: self
                .checked_url(&definition.url, definition.url_parts.as_deref(), node, env)
                .unwrap_or_default(),
            url_parts: None,
            position: None,
            ..definition.clone()
        }
    }

    /// A node with children and nothing else, its children expanded.
    fn parent(&mut self, children: &'r [Node], env: &Env<'r>) -> tree::Parent<expanded::Node> {
        tree::Parent {
            children: self.list(children, env),
            position: None,
        }
    }

    /// A heading at its computed depth: in a body with relative headings, below the heading the invocation is under
    /// (spec §7.2). Relative headings after it follow it.
    fn heading(
        &mut self,
        heading: &'r tree::Heading,
        env: &Env<'r>,
    ) -> tree::Heading<expanded::Node> {
        let depth = env
            .shift
            .map_or(heading.depth, |base| (base + heading.depth).min(6));
        let children = self.list(&heading.children, env);
        self.last_heading = depth;
        self.heading_kept = false;
        tree::Heading {
            depth,
            children,
            position: None,
        }
    }
}

/// A text-only node.
fn literal(value: &str) -> tree::Literal {
    tree::Literal {
        value: value.to_string(),
        position: None,
    }
}

/// A code block as content, as no code renderer renders it.
fn plain_code(code: &tree::Code) -> expanded::Code {
    expanded::Code {
        lang: code.lang.clone(),
        meta: code.meta.clone(),
        value: code.value.clone(),
        component: None,
        alt: None,
        render: None,
        params: Vec::new(),
        document: None,
    }
}