compmd 0.13.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
//! Interpolation (spec §8.1): a value written as text, a slot placed where a body says, and URLs with their values
//! percent-encoded; an interpolation that never gives a URL its scheme (W109). Adjacent text is joined.

use super::Expander;
use super::destinations::{self, Destination};
use super::env::Env;
use super::origins;
use crate::cel::Value;
use crate::diagnostic::{Code, Location};
use crate::expanded::{self, Content};
use crate::tree::{self, Image, Interpolation, Link, Node, StringPart, start_of};
use std::fmt::Write as _;

/// The schemes an interpolated URL may have (spec §8.1).
const SCHEMES: [&str; 3] = ["https", "http", "mailto"];

/// The path that places an invocation's fallback in its body (spec §7.2).
const FALLBACK: &str = "md.fallback";

impl<'r> Expander<'r> {
    /// An interpolation in a body: `md.slot` places slot content in a definition that declares the slot; any other
    /// path, its value as text, in a paragraph of its own when it stands alone.
    pub(super) fn interpolation(
        &mut self,
        interpolation: &'r Interpolation,
        env: &Env<'r>,
        out: &mut Vec<expanded::Node>,
    ) {
        let path = interpolation.path.as_str();
        if let Some(slot) = slot_name(path)
            && env.scope.knows(path)
        {
            return self.slot(slot, interpolation.block, env, out);
        }
        if path == FALLBACK && env.scope.knows(path) {
            return self.placed_fallback(interpolation.block, env, out);
        }
        let start = interpolation
            .position
            .map(|position| position.start)
            .unwrap_or_default();
        let at = self.lines[&env.document].path_at(start);
        let Some(text) = self.path_text(path, at, env) else {
            return;
        };
        let text = self.made(Content::Text(super::literal(&text)), None);
        if interpolation.block {
            let paragraph = Content::Paragraph(tree::Parent {
                children: vec![text],
                position: None,
            });
            let origin = env
                .origin
                .or_else(|| origins::range(&Node::Interpolation(interpolation.clone())));
            let made = self.made(paragraph, origin);
            out.push(made);
        } else {
            out.push(text);
        }
    }

    /// The text a path at `at` writes, `None` for `null`: an unknown path is shown as written (F014, from validating),
    /// and a value that can't be written, F024 at the path.
    pub(super) fn path_text(&mut self, path: &str, at: Location, env: &Env<'r>) -> Option<String> {
        let written = format!("{{{{{path}}}}}");
        if !env.scope.knows(path) {
            return Some(written);
        }
        match self.evaluate(path, env) {
            Ok(value) => match value.written() {
                Ok(text) => {
                    self.evaluated_at(env, at, Some(&value));
                    text
                }
                Err(why) => {
                    self.evaluated_at(env, at, None);
                    self.report(
                        Code::F024,
                        env,
                        at,
                        format!("`{path}` can't be written: {why}"),
                    );
                    Some(written)
                }
            },
            Err(error) => {
                self.evaluated_at(env, at, None);
                self.report(
                    Code::F024,
                    env,
                    at,
                    format!("`{path}`: {}", error.message()),
                );
                Some(written)
            }
        }
    }

    /// The invocation's fallback, placed by `{{md.fallback}}` (spec §7.2): its inline content, expanded in the
    /// caller's environment, in a paragraph of its own when it stands alone.
    fn placed_fallback(&mut self, block: bool, env: &Env<'r>, out: &mut Vec<expanded::Node>) {
        let Some(slots) = env.slots.clone() else {
            return;
        };
        let children = self.inline(slots.fallback, &slots.env);
        if block {
            let paragraph = Content::Paragraph(tree::Parent {
                children,
                position: None,
            });
            let made = self.made(paragraph, env.origin);
            out.push(made);
        } else {
            out.extend(children);
        }
    }

    /// A slot placed by `{{md.slot}}` or `{{md.slot.<name>}}`: its content, expanded in the caller's environment; a
    /// template slot once per element (spec §7.5). Inline, a slot that is one paragraph gives its text.
    fn slot(&mut self, name: &str, block: bool, env: &Env<'r>, out: &mut Vec<expanded::Node>) {
        let Some(slots) = env.slots.clone() else {
            return;
        };
        let content = if name == "default" {
            slots.default.clone()
        } else {
            slots
                .named
                .iter()
                .find(|slot| names_slot(name, &slot.name))
                .map(|slot| vec![slot.children.as_slice()])
                .unwrap_or_default()
        };
        let mut placed = match slots
            .templates
            .iter()
            .find(|template| names_slot(name, &template.slot))
        {
            Some(template) => self
                .iterate(template.items.len(), |this, index| {
                    let inner = slots.env.iteration(&template.name, &template.items, index);
                    this.parts(&content, &inner)
                })
                .concat(),
            None => self.parts(&content, &slots.env),
        };
        match placed.as_mut_slice() {
            [single] if !block && matches!(single.content, Content::Paragraph(_)) => {
                out.extend(
                    single
                        .content
                        .children_mut()
                        .map(std::mem::take)
                        .unwrap_or_default(),
                );
            }
            _ => out.extend(placed),
        }
    }

    /// A link; one whose interpolated URL would get a scheme it may not have is its text alone (W109).
    pub(super) fn link(
        &mut self,
        link: &'r Link,
        node: &'r Node,
        env: &Env<'r>,
        out: &mut Vec<expanded::Node>,
    ) {
        let children = self.list(&link.children, env);
        let parts = link.url_parts.as_deref();
        match self.checked_url(&link.url, parts, node, env) {
            Some(url) => {
                let Destination { url, pack } = self.destination(url, parts, node, env);
                let content = Content::Link(Link {
                    children,
                    url,
                    title: link.title.clone(),
                    url_parts: None,
                    pack,
                    position: None,
                });
                let made = self.made(content, origins::of(node, env));
                out.push(made);
            }
            None => out.extend(children),
        }
    }

    /// An image; one whose interpolated URL would get a scheme it may not have is its alternative text (W109).
    pub(super) fn image(
        &mut self,
        image: &'r Image,
        node: &'r Node,
        env: &Env<'r>,
        out: &mut Vec<expanded::Node>,
    ) {
        let alt = self.image_alt(image, env);
        let parts = image.url_parts.as_deref();
        let content = match self.checked_url(&image.url, parts, node, env) {
            Some(url) => {
                let Destination { url, pack } = self.destination(url, parts, node, env);
                Content::Image(Image {
                    alt,
                    url,
                    url_parts: None,
                    alt_parts: None,
                    pack,
                    position: None,
                    ..image.clone()
                })
            }
            None => Content::Text(super::literal(&alt)),
        };
        let made = self.made(content, origins::of(node, env));
        out.push(made);
    }

    /// A URL with its interpolations filled in; `None`, with W109, when one before its first `:`, `/`, `?` or `#` as
    /// written gives it a scheme other than `https:`, `http:` or `mailto:` (spec §8.1).
    pub(super) fn checked_url(
        &mut self,
        written: &str,
        parts: Option<&[StringPart]>,
        node: &Node,
        env: &Env<'r>,
    ) -> Option<String> {
        let url = self.url(written, parts, env);
        let scheme = scheme(&url);
        if parts.is_some_and(interpolates_scheme)
            && scheme.is_some_and(|scheme| !SCHEMES.contains(&scheme.as_str()))
        {
            let at = start_of(node.position());
            self.report(
                Code::W109,
                env,
                at,
                "an interpolated URL may only be relative or `https:`, `http:` or `mailto:`; the link's text is shown without the link",
            );
            return None;
        }
        Some(url)
    }

    /// A link's or an image's URL as the expanded tree writes it (spec §8.6, §12.3), resolved against the document it
    /// is written in, or the caller's that gave the param it starts with; kept as written, with F026, when its path
    /// leaves its root.
    fn destination(
        &mut self,
        url: String,
        parts: Option<&[StringPart]>,
        node: &Node,
        env: &Env<'r>,
    ) -> Destination {
        let base = match parts {
            Some([StringPart::Interpolation(interpolation), ..]) => {
                env.base_of_name(&interpolation.path)
            }
            _ => env.document,
        };
        let main = &self.resolved.document(self.resolved.main).origin;
        let origin = &self.resolved.document(base).origin;
        if let Some(destination) = destinations::resolved(&url, origin, main) {
            return destination;
        }
        self.report(
            Code::F026,
            env,
            start_of(node.position()),
            format!("`{url}` leaves the root of `{origin}`, so it is kept as written"),
        );
        Destination { url, pack: false }
    }

    /// An image's alt text with its interpolations filled in, as text; `md.fallback` as the fallback's plain text
    /// (spec §7.2). An unknown path stays as written (F014, from validating).
    fn image_alt(&mut self, image: &'r Image, env: &Env<'r>) -> String {
        let Some(parts) = image.alt_parts.as_deref() else {
            return image.alt.clone();
        };
        let start = image
            .position
            .map(|position| position.start)
            .unwrap_or_default();
        let mut places = self.lines[&env.document].paths_from(start).into_iter();
        let mut alt = String::new();
        for part in parts {
            match part {
                StringPart::Text(text) => alt.push_str(&text.value),
                StringPart::Interpolation(interpolation)
                    if interpolation.path == FALLBACK && env.scope.knows(FALLBACK) =>
                {
                    places.next();
                    if let Some(slots) = env.slots.clone() {
                        let children = self.inline(slots.fallback, &slots.env);
                        alt.push_str(&plain_text(&children));
                    }
                }
                StringPart::Interpolation(interpolation) => {
                    let at = places.next().unwrap_or_else(|| start.into());
                    let text = self.path_text(&interpolation.path, at, env);
                    alt.push_str(&text.unwrap_or_default());
                }
            }
        }
        alt
    }

    /// A URL with its interpolations filled in, each value percent-encoded where a URL can't hold it.
    fn url(&mut self, written: &str, parts: Option<&[StringPart]>, env: &Env<'r>) -> String {
        let Some(parts) = parts else {
            return written.to_string();
        };
        let mut url = String::new();
        for part in parts {
            match part {
                StringPart::Text(text) => url.push_str(&text.value),
                StringPart::Interpolation(interpolation) => {
                    let path = &interpolation.path;
                    let value = if env.scope.knows(path) {
                        self.evaluate(path, env).ok()
                    } else {
                        None
                    };
                    match value.as_ref().map(Value::written) {
                        Some(Ok(text)) => url.push_str(&url_safe(&text.unwrap_or_default())),
                        _ => {
                            let _ = write!(url, "{{{{{path}}}}}");
                        }
                    }
                }
            }
        }
        url
    }
}

/// Inline content as the text a reader reads: its text, its code and its wiki links' labels, without its marks; a
/// component's fallback, but not an image's alt text, raw HTML or math.
pub(super) fn plain_text(nodes: &[expanded::Node]) -> String {
    nodes
        .iter()
        .map(|node| match &node.content {
            Content::Text(text) | Content::InlineCode(text) => text.value.clone(),
            Content::WikiLink(link) => link.label.clone(),
            other => plain_text(other.children()),
        })
        .collect()
}

/// The slot `{{md.slot}}` or `{{md.slot.<name>}}` names.
fn slot_name(path: &str) -> Option<&str> {
    match path {
        "md.slot" => Some("default"),
        _ => path.strip_prefix("md.slot."),
    }
}

/// Whether the slot `name` of a path is the slot `slot` as written: a `-` in a slot's name is `_` in a path (spec
/// §5.1), `{{md.slot.side_panel}}` for `:: #side-panel`.
fn names_slot(name: &str, slot: &str) -> bool {
    slot.replace('-', "_") == name
}

/// Whether a URL written as `parts` has an interpolation before its first `:`, `/`, `?` or `#`, where it could give
/// the URL its scheme (spec §8.1).
fn interpolates_scheme(parts: &[StringPart]) -> bool {
    for part in parts {
        match part {
            StringPart::Interpolation(_) => return true,
            StringPart::Text(text) if text.value.contains([':', '/', '?', '#']) => return false,
            StringPart::Text(_) => {}
        }
    }
    false
}

/// A URL's scheme, lowercased, when it has one.
fn scheme(url: &str) -> Option<String> {
    let (scheme, _) = url.split_once(':')?;
    let mut chars = scheme.chars();
    let valid = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    valid.then(|| scheme.to_ascii_lowercase())
}

/// `text` with the characters a URL can't hold percent-encoded; `/`, `?` and `#` are kept.
fn url_safe(text: &str) -> String {
    let mut out = String::new();
    for c in text.chars() {
        if c.is_ascii_alphanumeric() || "-._~:/?#[]@!$&'()*+,;=%".contains(c) {
            out.push(c);
        } else {
            let mut bytes = [0; 4];
            for byte in c.encode_utf8(&mut bytes).bytes() {
                let _ = write!(out, "%{byte:02X}");
            }
        }
    }
    out
}

/// Adjacent text nodes joined into one; the joined node keeps an origin only when all its parts had the same.
pub(super) fn joined(nodes: Vec<expanded::Node>) -> Vec<expanded::Node> {
    let mut out: Vec<expanded::Node> = Vec::with_capacity(nodes.len());
    for node in nodes {
        if let (Some(last), Content::Text(text)) = (out.last_mut(), &node.content)
            && let Content::Text(joined) = &mut last.content
        {
            joined.value.push_str(&text.value);
            if last.origin != node.origin {
                last.origin = None;
            }
            continue;
        }
        out.push(node);
    }
    out
}

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

    #[test]
    fn urls_keep_their_structure() {
        assert_eq!(url_safe("acme/ray play?q=1#x"), "acme/ray%20play?q=1#x");
        assert_eq!(url_safe("é\"<>"), "%C3%A9%22%3C%3E");
    }

    #[test]
    fn schemes_are_letters_before_a_colon() {
        assert_eq!(scheme("JavaScript:alert(1)"), Some("javascript".into()));
        assert_eq!(scheme("https://a.org"), Some("https".into()));
        assert_eq!(scheme("./a:b"), None);
        assert_eq!(scheme("1a:b"), None);
        assert_eq!(scheme("docs/page"), None);
    }

    #[test]
    fn slots_are_named_by_their_path() {
        assert_eq!(slot_name("md.slot"), Some("default"));
        assert_eq!(slot_name("md.slot.footer"), Some("footer"));
        assert_eq!(slot_name("md.doc"), None);
    }

    #[test]
    fn a_path_names_a_slot_with_underscores_for_its_hyphens() {
        assert!(names_slot("side_panel", "side-panel"));
        assert!(names_slot("footer", "footer"));
        assert!(!names_slot("side_panel", "side"));
    }
}