compmd 0.10.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
//! A document's frontmatter (spec §2.1, §2.2), read before the document is parsed: YAML 1.2 core without tags,
//! anchors, aliases or repeated keys, or TOML (F033), a major version this processor implements (F001), and
//! CompMD's keys under `md` (W110, W111).

use super::params::string_parts;
use super::toml;
use super::yaml::{self, Mark, Refused};
use crate::diagnostic::{Code, Diagnostic, Location};
use crate::nearest::nearest;
use serde_json::{Map, Value};

/// The version of the spec this processor implements.
const MAJOR: u64 = 1;
const MINOR: u64 = 0;

/// The keys under `md` (spec §2.1), each with what it holds.
pub(crate) const MD_KEYS: [(&str, &str); 10] = [
    (
        "version",
        "the CompMD version: `1`, or a string with a minor version such as `\"1.1\"`",
    ),
    (
        "import",
        "component and font imports, each a `from` and the `names` and `fonts` it takes",
    ),
    (
        "export",
        "component and font exports: the `names` and `fonts` other documents may import",
    ),
    (
        "fonts",
        "fonts of the document's own, each by name with its `files` and a `fallback`",
    ),
    (
        "data",
        "data imports, each a `from` and the name `as` gives it under `md.data`",
    ),
    (
        "inputs",
        "values the reader can change, read as `md.input.<name>`",
    ),
    (
        "lang",
        "the document's language, a BCP 47 tag; `en` by default",
    ),
    (
        "dir",
        "the text direction, `ltr`, `rtl` or `auto`; by default the direction of `lang`'s script",
    ),
    (
        "tz",
        "the time zone of `md.today()`, an IANA name such as `Europe/Berlin`",
    ),
    (
        "syntax",
        "opt-in syntax the document uses, such as `[wiki-links]`",
    ),
];

/// The names of [`MD_KEYS`].
fn md_key_names() -> impl Iterator<Item = &'static str> + Clone {
    MD_KEYS.iter().map(|(name, _)| *name)
}

/// The opt-in syntax this processor knows (spec §2.3).
pub(crate) const SYNTAX_NAMES: [&str; 1] = ["wiki-links"];

/// What a frontmatter is written in (spec §2.1).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Format {
    /// YAML, between `---` lines.
    Yaml,
    /// TOML, between `+++` lines.
    Toml,
}

impl Format {
    /// The fence's line, without trailing white space.
    fn fence(self) -> &'static str {
        match self {
            Self::Yaml => "---",
            Self::Toml => "+++",
        }
    }
}

/// A frontmatter as written: its format, and its text, which starts on line 2.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Found<'t> {
    pub(crate) format: Format,
    pub(crate) text: &'t str,
}

/// The frontmatter at the start of `text`: a `---` (or `+++`) line, its text, and a closing line of the same, as the
/// fork of markdown-rs finds it.
pub(crate) fn find(text: &str) -> Option<Found<'_>> {
    let mut lines = lines(text);
    let (_, opener) = lines.next()?;
    let format = [Format::Yaml, Format::Toml]
        .into_iter()
        .find(|format| is_fence(opener, *format))?;
    let start = lines.clone().next().map_or(text.len(), |(start, _)| start);
    let mut end = start;
    for (line_start, line) in lines {
        if is_fence(line, format) {
            return Some(Found {
                format,
                text: &text[start..end.max(start)],
            });
        }
        end = line_start + line.len();
    }
    None
}

fn is_fence(line: &str, format: Format) -> bool {
    line.strip_prefix(format.fence())
        .is_some_and(|rest| rest.bytes().all(|b| b == b' ' || b == b'\t'))
}

/// Each line of `text` with the byte index where it starts, without its line ending.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> + Clone {
    let mut start = 0;
    std::iter::from_fn(move || {
        if start >= text.len() {
            return None;
        }
        let rest = &text[start..];
        let end = rest.find(['\n', '\r']).unwrap_or(rest.len());
        let ending = match &rest.as_bytes()[end..] {
            [b'\r', b'\n', ..] => 2,
            [] => 0,
            _ => 1,
        };
        let line = (start, &rest[..end]);
        start += end + ending;
        Some(line)
    })
}

/// Reads the frontmatter, YAML or TOML, with where each key and value is; `None` when CompMD processing doesn't
/// apply (F001, F033).
pub(crate) fn read(found: Found<'_>, diagnostics: &mut Vec<Diagnostic>) -> Option<yaml::Document> {
    let (parsed, written) = match found.format {
        Format::Yaml => (yaml::parse(found.text), "YAML 1.2 core"),
        Format::Toml => (toml::parse(found.text), "TOML"),
    };
    match parsed {
        Ok(document) => checked(document, diagnostics),
        Err(Refused(mark, why)) => {
            diagnostics.push(Diagnostic::new(
                Code::F033,
                Location::new(1 + mark.line, mark.column + 1),
                format!(
                    "the frontmatter isn't {written}: {why}; the document is read as plain Markdown"
                ),
            ));
            None
        }
    }
}

/// A host's metadata as a frontmatter (spec §2.1): the same keys, with no place in the text, so that what is said of
/// them is at line 1.
pub(crate) fn metadata(value: &Value, diagnostics: &mut Vec<Diagnostic>) -> Option<yaml::Document> {
    checked(
        yaml::Document {
            value: value.clone(),
            ..yaml::Document::default()
        },
        diagnostics,
    )
}

/// `document`, a frontmatter or a host's metadata, when CompMD processing applies to it (F001), with the warnings
/// on its `md` keys (W110, W111). A key or value with no place is at line 1.
fn checked(document: yaml::Document, diagnostics: &mut Vec<Diagnostic>) -> Option<yaml::Document> {
    let place = |marks: &std::collections::HashMap<String, Mark>, pointer: &str| {
        marks.get(pointer).map_or(Location::new(1, 1), |mark| {
            Location::new(1 + mark.line, mark.column + 1)
        })
    };
    let settings = document
        .value
        .get("md")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let version = settings.get("version");
    let Some((MAJOR, minor)) = version.map_or(Some((MAJOR, MINOR)), parse_version) else {
        let written = version.map_or_else(String::new, Value::to_string);
        diagnostics.push(Diagnostic::new(
            Code::F001,
            Location::new(1, 1),
            format!("unsupported version {written}: this processor implements CompMD {MAJOR}; the document is read as plain Markdown"),
        ));
        return None;
    };
    if minor > MINOR {
        diagnostics.push(Diagnostic::new(
            Code::W110,
            place(&document.values, "/md/version"),
            format!("the document declares version {MAJOR}.{minor}; this processor implements {MAJOR}.{MINOR}"),
        ));
    }
    for key in settings
        .keys()
        .filter(|key| !md_key_names().any(|known| known == key.as_str()))
    {
        let hint = nearest(key, md_key_names())
            .map_or_else(String::new, |known| format!("; did you mean `{known}`?"));
        diagnostics.push(Diagnostic::new(
            Code::W111,
            place(&document.keys, &format!("/md/{key}")),
            format!("unknown key `md.{key}`, ignored{hint}"),
        ));
    }
    if let Some(Value::Array(names)) = settings.get("syntax") {
        for (i, name) in names.iter().enumerate() {
            if !name
                .as_str()
                .is_some_and(|name| SYNTAX_NAMES.contains(&name))
            {
                diagnostics.push(Diagnostic::new(
                    Code::W111,
                    place(&document.values, &format!("/md/syntax/{i}")),
                    format!("unknown syntax {name} in `md.syntax`, ignored; known: `wiki-links`"),
                ));
            }
        }
    }
    Some(document)
}

/// The frontmatter as the tree writes it (spec §12.2): a mapping, each data import's `from` as parts.
pub(crate) fn tree_value(document: &yaml::Document) -> Value {
    let mut value = match &document.value {
        Value::Object(entries) => Value::Object(entries.clone()),
        _ => Value::Object(Map::new()),
    };
    if let Some(Value::Array(entries)) = value.pointer_mut("/md/data") {
        for entry in entries {
            if let Some(from) = entry.get("from").and_then(Value::as_str) {
                let parts = serde_json::to_value(string_parts(from)).expect("parts serialize");
                entry["from"] = parts;
            }
        }
    }
    value
}

/// `md.version`: `1`, `1.2` or `"1.2"`, as its major and minor version.
fn parse_version(value: &Value) -> Option<(u64, u64)> {
    let text = match value {
        Value::Number(number) => number.to_string(),
        Value::String(text) => text.clone(),
        _ => return None,
    };
    let (major, minor) = text.split_once('.').unwrap_or((&text, "0"));
    Some((major.parse().ok()?, minor.parse().ok()?))
}

/// Whether settings (a frontmatter, or a host's metadata) opt in to wiki links (spec §2.3).
pub(crate) fn wiki_links(settings: &Value) -> bool {
    settings
        .pointer("/md/syntax")
        .and_then(Value::as_array)
        .is_some_and(|names| names.iter().any(|name| name == "wiki-links"))
}

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

    fn read_all(yaml: &str) -> (Option<Value>, Vec<(Code, Location)>) {
        read_as(Format::Yaml, yaml)
    }

    fn read_as(format: Format, text: &str) -> (Option<Value>, Vec<(Code, Location)>) {
        let mut diagnostics = Vec::new();
        let parsed =
            read(Found { format, text }, &mut diagnostics).map(|document| tree_value(&document));
        let found = diagnostics
            .iter()
            .map(|d| (d.code, d.range.start))
            .collect();
        (parsed, found)
    }

    #[test]
    fn finds_frontmatter_between_fences() {
        let yaml = |text| {
            Some(Found {
                format: Format::Yaml,
                text,
            })
        };
        assert_eq!(find("---\na: 1\nb: 2\n---\ntext"), yaml("a: 1\nb: 2"));
        assert_eq!(find("--- \t\r\na: 1\r\n---  "), yaml("a: 1"));
        assert_eq!(find("---\n---\n"), yaml(""));
        assert_eq!(find("---\na: 1"), None);
        assert_eq!(find("----\n---"), None);
        assert_eq!(find(" ---\n---"), None);
        assert_eq!(find(""), None);
    }

    #[test]
    fn finds_toml_between_plus_fences() {
        let toml = |text| {
            Some(Found {
                format: Format::Toml,
                text,
            })
        };
        assert_eq!(find("+++\na = 1\n+++\ntext"), toml("a = 1"));
        assert_eq!(find("+++\na = 1\n---\n+++"), toml("a = 1\n---"));
        assert_eq!(find("+++\na = 1"), None);
        assert_eq!(find("---\na: 1\n+++"), None);
    }

    #[test]
    fn toml_reads_as_yaml_does() {
        assert_eq!(
            read_as(
                Format::Toml,
                "[md]\nversion = 1\nsyntax = [\"wiki-links\", \"tables\"]"
            ),
            (
                Some(json!({ "md": { "version": 1, "syntax": ["wiki-links", "tables"] } })),
                vec![(Code::W111, Location::new(4, 25))]
            )
        );
        assert_eq!(
            read_as(Format::Toml, "a = 1\na = 2"),
            (None, vec![(Code::F033, Location::new(3, 1))])
        );
    }

    #[test]
    fn version_1_and_later_minors() {
        assert_eq!(
            read_all("md:\n  version: 1"),
            (Some(json!({ "md": { "version": 1 } })), Vec::new())
        );
        assert_eq!(read_all("title: x").1, []);
        assert_eq!(
            read_all("md:\n  version: \"1.2\"").1,
            [(Code::W110, Location::new(3, 12))]
        );
    }

    #[test]
    fn other_majors_make_the_document_plain() {
        for version in ["2", "\"x\"", "[1]", "\"1.x\""] {
            assert_eq!(
                read_all(&format!("md:\n  version: {version}")),
                (None, vec![(Code::F001, Location::new(1, 1))]),
                "{version}"
            );
        }
    }

    #[test]
    fn refused_yaml_makes_the_document_plain() {
        assert_eq!(
            read_all("a: !!str 1"),
            (None, vec![(Code::F033, Location::new(2, 4))])
        );
    }

    #[test]
    fn unknown_keys_and_syntax_are_w111() {
        assert_eq!(
            read_all("md:\n  input: {}\n  syntax: [wiki-links, tables]").1,
            [
                (Code::W111, Location::new(3, 3)),
                (Code::W111, Location::new(4, 24))
            ]
        );
    }

    #[test]
    fn data_imports_split_from_into_parts() {
        let (parsed, _) =
            read_all("md:\n  data:\n    - from: ./a-{{md.input.year}}.csv\n    - name: x");
        assert_eq!(
            parsed.unwrap()["md"]["data"],
            json!([
                { "from": [
                    { "type": "text", "value": "./a-" },
                    { "type": "interpolation", "path": "md.input.year", "block": false },
                    { "type": "text", "value": ".csv" },
                ] },
                { "name": "x" },
            ])
        );
    }

    #[test]
    fn frontmatter_that_is_not_a_mapping_has_no_keys() {
        assert_eq!(read_all("just text").0, Some(json!({})));
    }

    #[test]
    fn wiki_links_are_opted_in_by_md_syntax() {
        assert!(wiki_links(&json!({ "md": { "syntax": ["wiki-links"] } })));
        assert!(!wiki_links(&json!({ "md": { "syntax": "wiki-links" } })));
        assert!(!wiki_links(&json!({})));
    }
}