compmd 0.12.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
use super::super::tests::{CARD, CARET, hint, hint_with, range, texts};
use serde_json::{Value, json};

const BOOKS: &str = "---\ntitle: Reading\nshelf: {name: Home}\nmd:\n  data:\n    - from: ./books.csv\n      as: books\n      schema: {title: string, pages: number, read: boolean}\n  inputs:\n    since: number = 1970\n---\n\n";

fn books(body: &str) -> Value {
    hint_with(
        &format!("{BOOKS}{body}"),
        &[("books.csv", "title,pages,read\nDune,412,true\n")],
    )
}

#[test]
fn each_step_of_a_path_names_what_it_is() {
    let data = books(&format!("{{{{md.data.boo{CARET}ks}}}}\n"));
    assert_eq!(data["range"], range(13, 11, 16));
    let subject = &data["subject"];
    assert_eq!(
        (&subject["kind"], &subject["path"]),
        (&json!("path"), &json!("md.data.books"))
    );
    let name = &subject["name"];
    assert_eq!(name["about"], "data from `./books.csv`");
    assert_eq!(name["type"], "list(map(string, dyn))");
    assert_eq!(
        name["fields"],
        json!(["pages: double", "read: bool", "title: string"])
    );
    assert_eq!(
        texts(&data),
        [
            "books",
            "size",
            "all",
            "exists",
            "exists_one",
            "filter",
            "map"
        ],
        "a record's fields, then what a map is called with"
    );
    let md = books(&format!("{{{{m{CARET}d.doc.title}}}}\n"));
    assert_eq!(md["subject"]["path"], "md");
    assert!(
        md["subject"]["name"]["about"]
            .as_str()
            .is_some_and(|about| about.contains("`doc`"))
    );
    let title = books(&format!("{{{{ md.doc.ti{CARET}tle }}}}\n"));
    assert_eq!(
        (
            &title["subject"]["name"]["about"],
            &title["subject"]["name"]["type"]
        ),
        (&json!("the frontmatter's `title`"), &json!("string"))
    );
    assert_eq!(texts(&title)[..2], ["shelf", "title"]);
    let field = books(&format!("{{{{md.doc.shelf.na{CARET}me}}}}\n"));
    assert_eq!(
        field["subject"]["name"]["about"],
        "the frontmatter's `shelf.name`"
    );
    let input = books(&format!("{{{{md.input.sin{CARET}ce}}}}\n"));
    assert_eq!(
        input["subject"]["name"]["about"],
        "the input `since`, a number"
    );
    let colon = hint(&format!(
        "---\nreading: {{page:120}}\n---\n\n{{{{md.doc.reading.pa{CARET}ge}}}}\n"
    ));
    assert_eq!(
        colon["subject"]["name"]["about"],
        "`reading` has a key `page:120`; a colon needs a space after it to give `page` a value"
    );
    let unknown = books(&format!("{{{{md.doc.nothin{CARET}g}}}}\n"));
    assert_eq!(unknown["subject"]["name"].get("type"), None);
    assert_eq!(unknown["diagnostics"][0]["code"], "F014");
}

#[test]
fn after_md_the_names_and_the_functions_are_offered() {
    let json = books(&format!("{{{{md.{CARET}"));
    let names = texts(&json);
    for name in ["data", "doc", "input", "version", "sortBy", "today"] {
        assert!(names.contains(&name), "{name} in {names:?}");
    }
    assert_eq!(json["range"], range(13, 6, 6));
    for (path, about) in [
        ("md.doc", "the frontmatter's own keys"),
        ("md.data", "the data the frontmatter imports"),
        ("md.input", "the inputs the reader sets"),
        (
            "md.version",
            "the CompMD version the document is written in",
        ),
        ("md.lang", "the document's language, a BCP 47 tag"),
        ("md.tz", "the render's time zone"),
    ] {
        let json = books(&format!("{{{{{path}{CARET}}}}}\n"));
        assert_eq!(json["subject"]["name"]["about"], about, "{path}");
    }
    assert_eq!(
        books(&format!("{{{{md.doc.title}}}} {CARET}b\n")),
        Value::Null,
        "past the interpolation"
    );
    assert_eq!(
        books(&format!("\\{{{{md.do{CARET}c}}}}\n")),
        Value::Null,
        "escaped"
    );
}

#[test]
fn after_a_dot_a_value_offers_what_its_type_is_called_with() {
    let after = |frontmatter: &str, path: &str| {
        hint(&format!(
            "---\n{frontmatter}\n---\n\n{{{{{path}.{CARET}}}}}\n"
        ))
    };
    let title = after("title: Notes", "md.doc.title");
    let names = texts(&title);
    for name in ["contains", "startsWith", "lowerAscii", "split", "size"] {
        assert!(names.contains(&name), "{name} in {names:?}");
    }
    assert!(!names.contains(&"join") && !names.contains(&"map"));
    let detail = title["completions"]
        .as_array()
        .and_then(|all| {
            all.iter()
                .find(|completion| completion["label"] == "startsWith")
        })
        .map(|completion| completion["detail"].clone());
    assert_eq!(
        detail,
        Some(json!("string.startsWith(prefix: string) → bool"))
    );
    let list = after("tags: [a, b]", "md.doc.tags");
    let tags = texts(&list);
    for name in ["join", "map", "filter", "size"] {
        assert!(tags.contains(&name), "{name} in {tags:?}");
    }
    assert!(!tags.contains(&"contains"));
    assert_eq!(
        texts(&after("count: 3", "md.doc.count")),
        Vec::<&str>::new(),
        "a number is called with nothing"
    );
}

#[test]
fn a_template_binds_its_name_and_md_loop() {
    let body = format!(
        "::: each {{in=(md.data.books) as=b}}\n{{{{b.ti{CARET}tle}}}}, {{{{md.loop.number}}}}\n::: /each\n"
    );
    let json = books(&body);
    assert_eq!(json["subject"]["name"]["type"], "string");
    assert_eq!(texts(&json)[..3], ["pages", "read", "title"]);
    let bound = books(&body.replacen("b.ti‸tle", "b‸.title", 1));
    assert_eq!(
        bound["subject"]["name"]["about"],
        "each element of `(md.data.books)`"
    );
    let number = books(
        &body
            .replacen('‸', "", 1)
            .replacen("md.loop.number", "md.loop.num‸ber", 1),
    );
    assert_eq!(
        (
            &number["subject"]["name"]["about"],
            &number["subject"]["name"]["type"]
        ),
        (
            &json!("the element's position, from 1, for display"),
            &json!("int")
        )
    );
    let one = books(&format!(
        "::: each {{in=[{{\"a\": 1}}] as=x}}\n{{{{x.{CARET}a}}}}\n::: /each\n"
    ));
    assert_eq!(one["subject"]["name"]["type"], "double", "a JSON list");
    let cel = books(&format!(
        "::: each {{in=([{{\"a\": 1}}]) as=x}}\n{{{{x.{CARET}a}}}}\n::: /each\n"
    ));
    assert_eq!(cel["subject"]["name"]["type"], "int", "a CEL list");
    let opener = books(&format!(
        "::: each {{in=(md.data.books) as=b}}\n{{{{b{CARET}}}}}\n:: #empty\n{{{{b}}}}\n::: /each\n"
    ));
    assert_eq!(
        opener["subject"]["name"]["about"],
        "each element of `(md.data.books)`"
    );
    let empty = books(&format!(
        "::: each {{in=(md.data.books) as=b}}\nB.\n:: #empty\n{{{{b{CARET}}}}}\n::: /each\n"
    ));
    assert_eq!(
        empty["subject"]["name"].get("about"),
        None,
        "`empty` binds nothing"
    );
}

#[test]
fn a_definitions_body_sees_its_params() {
    let json = hint(&CARD.replacen("{{title}}", "{{tit‸le}}", 1));
    let name = &json["subject"]["name"];
    assert_eq!(name["about"], "a param of `card`: The card's heading.");
    assert_eq!(name["type"], "string");
    let kind = hint(&CARD.replacen("{{title}}", "{{ki‸nd}}", 1));
    assert_eq!(kind["subject"]["name"]["about"], "a param of `card`");
}

#[test]
fn an_expression_names_its_paths_and_functions() {
    let exists = books(&format!(
        "::: if {{when=(md.data.books.exi{CARET}sts(b, !b.read))}}\nYes.\n::: /if\n"
    ));
    let subject = &exists["subject"];
    assert_eq!(
        (&subject["kind"], &subject["name"]),
        (&json!("function"), &json!("exists"))
    );
    assert_eq!(
        subject["function"]["signatures"][0]["written"],
        "list | map.exists(x: name, predicate: bool) → bool"
    );
    assert_eq!(subject["function"]["kind"], "macro");
    assert_eq!(exists["range"], range(13, 29, 35));
    assert!(texts(&exists).contains(&"filter") && !texts(&exists).contains(&"has"));
    let detail = |found: &Value, label: &str| {
        found["completions"]
            .as_array()
            .and_then(|all| all.iter().find(|completion| completion["label"] == label))
            .map(|completion| completion["detail"].clone())
    };
    assert_eq!(
        detail(&exists, "size"),
        Some(json!("string | list | map.size() → int")),
        "a method's signature, after a `.`"
    );
    let local = books(&format!(
        "::: if {{when=(md.data.books.exists(b, !b.re{CARET}ad))}}\nYes.\n::: /if\n"
    ));
    assert_eq!(local["subject"]["name"]["type"], "bool");
    let var = books(&format!(
        "::: if {{when=(md.data.books.exists(b, !b{CARET}.read))}}\nYes.\n::: /if\n"
    ));
    assert_eq!(
        var["subject"]["name"]["about"],
        "each element of `md.data.books`"
    );
    let md = books(&format!(
        ":value[x]{{of=(md.cur{CARET}rency(1, \"USD\"))}}\n"
    ));
    assert_eq!(md["subject"]["name"], "md.currency");
    assert_eq!(
        md["subject"]["function"]["signatures"][0]["written"],
        "md.currency(n: number, code: string) → string"
    );
    assert_eq!(
        md["subject"]["function"]["examples"][0]["result"],
        "$120.00"
    );
    assert_eq!(
        detail(&md, "sortBy"),
        Some(json!("md.sortBy(list: list, field: string) → list"))
    );
    let size = books(&format!(
        ":value[x]{{of=(string(si{CARET}ze(md.data.books)))}}\n"
    ));
    assert_eq!(
        size["subject"]["function"]["description"],
        "The length of a string, in characters, a list or a map."
    );
    assert!(texts(&size).contains(&"has") && !texts(&size).contains(&"trim"));
    assert_eq!(
        detail(&size, "size"),
        Some(json!("size(value: string | list | map) → int")),
        "a function's signature, not a method's"
    );
    let unknown = books(&format!(":value[x]{{of=(nothin{CARET}g(1))}}\n"));
    assert_eq!(unknown["subject"].get("function"), None);
    let text = books(&format!(":value[x]{{of=(\"a b{CARET}\")}}\n"));
    assert_eq!(
        text["subject"]["kind"], "param",
        "inside a string, the param's hint"
    );
    let number = books(&format!(":value[x]{{of=(string(1{CARET}2))}}\n"));
    assert_eq!(number["subject"]["kind"], "param");
    let unclosed = books(&format!("::: if {{when=(md.input.si{CARET}nce"));
    assert_eq!(unclosed["subject"]["name"]["type"], "double");
    let quoted = books(&format!(
        "::: box {{title=\"In {{{{md.doc.tit{CARET}le}}}}\"}}\n::: /box\n"
    ));
    assert_eq!(
        quoted["subject"]["path"], "md.doc.title",
        "an interpolation in a string"
    );
}

#[test]
fn paths_through_fields_maps_and_lists() {
    let field = books(&format!("{{{{md.data.books.ti{CARET}tle}}}}\n"));
    assert_eq!(
        field["subject"]["name"]["about"],
        "the field `title` of `md.data.books`'s records"
    );
    assert_eq!(
        texts(&field),
        ["size", "all", "exists", "exists_one", "filter", "map"],
        "a list has no fields; of a list of records, no `join`"
    );
    let tags = hint(&format!(
        "---\ntags: [a, b]\n---\n\n{{{{md.doc.ta{CARET}gs}}}}\n"
    ));
    assert_eq!(tags["subject"]["name"]["type"], "list(string)");
    assert_eq!(tags["subject"]["name"].get("fields"), None);
    let text = books(&format!("{{{{md.doc.title.x{CARET}}}}}\n"));
    assert_eq!(
        text["subject"]["name"].get("type"),
        None,
        "a string has no fields"
    );
    let raw = hint_with(
        &format!(
            "---\nmd:\n  data:\n    - from: ./raw.json\n      as: raw\n---\n\n{{{{md.data.raw.a.b{CARET}}}}}\n"
        ),
        &[("raw.json", "{}")],
    );
    assert_eq!(
        raw["subject"]["name"]["type"], "dyn",
        "data without a schema"
    );
    let meta = hint(&format!(
        "```compmd component=chip\nparams:\n  meta: object\n---\n{{{{meta.x{CARET}}}}}\n```\n"
    ));
    assert_eq!(meta["subject"]["name"]["type"], "dyn", "a map's values");
    let slot = hint(&CARD.replacen("{{title}}", "{{md.slot.foo‸ter}}", 1));
    assert_eq!(
        slot["subject"]["name"]["about"],
        "the content of the slot `footer`"
    );
    let default = hint(&CARD.replacen("{{title}}", "{{md.sl‸ot}}", 1));
    assert_eq!(
        default["subject"]["name"]["about"],
        "the default slot's content"
    );
    let each = |path: &str| {
        books(&format!(
            "::: each {{in=(md.data.books) as=b}}\n{{{{md.loop.{path}{CARET}}}}}\n::: /each\n"
        ))["subject"]["name"]["about"]
            .clone()
    };
    assert_eq!(each("index"), "the element's position, from 0");
    assert_eq!(each("count"), "how many elements there are");
    assert_eq!(each("first"), "whether it is the first element");
    assert_eq!(each("last"), "whether it is the last element");
    assert_eq!(each("other"), Value::Null);
    let lp = books(&format!(
        "::: each {{in=(md.data.books) as=b}}\n{{{{md.lo{CARET}op}}}}\n::: /each\n"
    ));
    assert!(
        lp["subject"]["name"]["about"]
            .as_str()
            .is_some_and(|about| about.contains("`index`"))
    );
}

#[test]
fn templates_without_a_list_bind_dyn() {
    let unbound = books(&format!(
        "::: each {{in=(md.data.books)}}\n{{{{b{CARET}}}}}\n::: /each\n"
    ));
    assert_eq!(unbound["subject"]["name"].get("about"), None, "no `as`");
    let bare = books(&format!(
        "::: each {{in=rows as=r}}\n{{{{r{CARET}}}}}\n::: /each\n"
    ));
    assert_eq!(bare["subject"]["name"]["about"], "each element of `rows`");
    let missing = books(&format!("::: each {{as=r}}\n{{{{r{CARET}}}}}\n::: /each\n"));
    assert_eq!(missing["subject"]["name"]["about"], "each element of `in`");
    let number = books(&format!(
        "::: each {{in=(5) as=r}}\n{{{{r{CARET}}}}}\n::: /each\n"
    ));
    assert_eq!(number["subject"]["name"]["type"], "dyn");
    let after = books(&format!(
        "::: each {{in=(md.data.books) as=b}}\nB.\n::: /each\n\n{{{{b{CARET}}}}}\n"
    ));
    assert_eq!(
        after["subject"]["name"].get("about"),
        None,
        "past the closer"
    );
}

#[test]
fn macros_bind_their_names_inside_them_only() {
    let closed = books(&format!(
        ":value[x]{{of=(string(md.data.books.exists(b, b.read) && b{CARET}))}}\n"
    ));
    assert_eq!(closed["subject"]["name"].get("about"), None);
    let unnamed = books(&format!(":value[x]{{of=(md.data.books.exists(x{CARET}"));
    assert_eq!(unnamed["subject"]["name"].get("about"), None, "no `,` yet");
    let nested = books(&format!(
        ":value[x]{{of=(string(md.data.books.exists(b, md.data.books.exists(c, c.re{CARET}ad))))}}\n"
    ));
    assert_eq!(nested["subject"]["name"]["type"], "bool");
    let opening = books(&format!(":value[x]{{of={CARET}(md.today())}}\n"));
    assert_eq!(opening["subject"]["kind"], "param", "on the `(`");
}