Skip to main content

tramlines_core/grammar/
meta.rs

1//! The parsed grammar: its `meta` vocabulary and the `schema` rule maps,
2//! with what a format grammar and a host's extension add.
3
4use std::collections::BTreeMap;
5
6use super::{bool_of, embedded, str_of};
7use crate::{Error, Result, Spanned, Yaml, yaml};
8
9/// The `meta.types` of the grammar.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum TypeName {
12    /// A string.
13    String,
14    /// An integer.
15    Integer,
16    /// A boolean.
17    Boolean,
18    /// A list of `of`.
19    List,
20    /// A keyed map of `of`.
21    Map,
22    /// One instance of `of`.
23    Object,
24    /// A string or a list of strings.
25    StringOrList,
26    /// A string or a map.
27    StringOrMap,
28    /// A string, or `{ from: <frontmatter key> }` standing for the key's
29    /// value.
30    Text,
31    /// A `text`, or one instance of the rule map `of`.
32    TextOrRule,
33    /// A map of lifecycle dimensions to a state or a list of states, or a
34    /// list of such maps.
35    Condition,
36    /// `true`, `false`, or a `condition`.
37    BooleanOrCondition,
38}
39
40impl TypeName {
41    /// The type the grammar names `s`.
42    pub fn parse(s: &str) -> Option<Self> {
43        Some(match s {
44            "string" => TypeName::String,
45            "integer" => TypeName::Integer,
46            "boolean" => TypeName::Boolean,
47            "list" => TypeName::List,
48            "map" => TypeName::Map,
49            "object" => TypeName::Object,
50            "string-or-list" => TypeName::StringOrList,
51            "string-or-map" => TypeName::StringOrMap,
52            "text" => TypeName::Text,
53            "text-or-rule" => TypeName::TextOrRule,
54            "condition" => TypeName::Condition,
55            "boolean-or-condition" => TypeName::BooleanOrCondition,
56            _ => return None,
57        })
58    }
59}
60
61/// One key of a rule map, as `meta.keys` describes it.
62#[derive(Debug, Clone, PartialEq)]
63pub struct KeyDef {
64    /// The value's type.
65    pub type_: TypeName,
66    /// The item, value or instance shape: a type, a scalar format or a rule
67    /// map name.
68    pub of: Option<String>,
69    /// Whether a schema must carry the key.
70    pub required: bool,
71    /// The values the key admits, as text.
72    pub enum_: Vec<String>,
73    /// A scalar format or a reference: `regex`, `slug`, `language-tag`,
74    /// `rule-id`, `format-name`.
75    pub format: Option<String>,
76    /// Keys that must be present beside this one.
77    pub requires_keys: Vec<String>,
78    /// Block kinds the enclosing block must be one of.
79    pub requires_kind: Vec<String>,
80    /// What the key means.
81    pub doc: String,
82}
83
84/// One rule map under `schema`, or `schema` itself.
85#[derive(Debug, Clone, PartialEq, Default)]
86pub struct RuleMap {
87    /// What the map is.
88    pub doc: String,
89    /// The keys, in grammar order.
90    pub keys: Vec<(String, KeyDef)>,
91    /// Exactly one of these keys must be present.
92    pub exactly_one_of: Vec<String>,
93    /// At least one of these keys must be present.
94    pub at_least_one_of: Vec<String>,
95    /// Whether the map accepts the `rule-common` keys.
96    pub common: bool,
97}
98
99impl RuleMap {
100    /// The definition of `key`.
101    pub fn key(&self, key: &str) -> Option<&KeyDef> {
102        self.keys.iter().find(|(k, _)| k == key).map(|(_, d)| d)
103    }
104}
105
106// sokf:begin grammar
107/// The parsed grammar file.
108#[derive(Debug, Clone, PartialEq)]
109pub struct Grammar {
110    /// The name of the grammar: `tramlines`, then the name of the format
111    /// grammar laid on it.
112    pub name: String,
113    /// The grammar version.
114    pub version: String,
115    /// The `schema` vocabulary.
116    pub schema: RuleMap,
117    /// The rule maps under `schema`, by name.
118    pub rules: BTreeMap<String, RuleMap>,
119    /// The `rule-common` keys.
120    pub rule_common: RuleMap,
121    /// The sections an extension adds beside `schema`, by name, as written.
122    pub sections: BTreeMap<String, Spanned>,
123}
124// sokf:end grammar
125
126impl Grammar {
127    /// The rule map named `name`.
128    pub fn rule(&self, name: &str) -> Option<&RuleMap> {
129        if name == "schema" {
130            return Some(&self.schema);
131        }
132        self.rules.get(name)
133    }
134
135    /// Whether `name` is a rule map that accepts the `rule-common` keys.
136    pub fn accepts_common(&self, name: &str) -> bool {
137        self.rule(name).is_some_and(|m| m.common)
138    }
139
140    /// A section an extension adds, by name.
141    // sokf:begin grammar-extend
142    pub fn section(&self, name: &str) -> Option<&Spanned> {
143        // sokf:end grammar-extend
144        self.sections.get(name)
145    }
146
147    /// Lay a format grammar on this one, the core grammar: it names
148    /// itself with `grammar` and its base with `base`, and adds keys, rule
149    /// maps, values of an enum, block kinds a key requires, text of a
150    /// `doc`, and the constraint groups of any rule map. A format grammar
151    /// that changes what the core grammar says is a defect of the build.
152    // sokf-implements: TL_2
153    // sokf-implements: TL_3
154    // sokf-implements: TL_4
155    // sokf-implements: CORE-2_AC-1
156    // sokf-implements: CORE-2_AC-2
157    // sokf:begin grammar-base
158    pub fn base(&mut self, text: &str) -> Result<()> {
159        // sokf:end grammar-base
160        self.transact(|g| g.lay_base(text))
161    }
162
163    /// Lay a layer with `lay` on a copy of the grammar. A layer that fails
164    /// leaves the grammar as it was, so no half-laid layer reaches the
165    /// validator.
166    fn transact(&mut self, lay: impl FnOnce(&mut Grammar) -> Result<()>) -> Result<()> {
167        let mut next = self.clone();
168        lay(&mut next)?;
169        *self = next;
170        Ok(())
171    }
172
173    fn lay_base(&mut self, text: &str) -> Result<()> {
174        let fail = |m: String| Error::Internal(format!("format grammar: {m}"));
175        let root = yaml::parse(text, 1).map_err(|e| fail(e.to_string()))?;
176        let Some(name) = root.get("grammar").and_then(|e| e.as_str()) else {
177            return Err(fail("no `grammar` name".into()));
178        };
179        let name = name.to_string();
180        // sokf-implements: CORE-2_AC-3
181        match root.get("base").and_then(|e| e.as_str()) {
182            Some(base) if base == self.name => {}
183            other => {
184                return Err(fail(format!("`base` is {other:?}, not `{}`", self.name)));
185            }
186        }
187        for (key, value) in root.as_map().unwrap_or(&[]) {
188            match key.value.as_str() {
189                "grammar" | "base" | "doc" => {}
190                // sokf-implements: CORE-2_AC-6
191                "version" => {
192                    if let Some(v) = value.scalar_text() {
193                        self.version = v;
194                    }
195                }
196                "meta" => return Err(fail("`meta` is the core grammar's".into())),
197                "schema" => self.extend_schema(value, true).map_err(fail)?,
198                // sokf-implements: CORE-2_AC-4
199                other => return Err(fail(format!("unknown section `{other}`"))),
200            }
201        }
202        self.check_references().map_err(fail)?;
203        // sokf-implements: CORE-2_AC-5
204        self.name = name;
205        Ok(())
206    }
207
208    /// Add a host's extension, which names itself with `extension` and
209    /// names the format grammar it extends with `extends`: keys, rule maps
210    /// and sections of its own; on a key of the grammar, more `enum`
211    /// values, more block kinds it `requires`, and more `doc`. An extension
212    /// that changes what the grammar says is a defect of the build.
213    // sokf-implements: TL_5
214    // sokf-implements: TL_6
215    // sokf-implements: TL_7
216    // sokf-implements: TL_8
217    // sokf-implements: CORE-3_AC-1
218    // sokf-implements: CORE-3_AC-2
219    // sokf-implements: CORE-3_AC-5
220    // sokf:begin grammar-extend
221    pub fn extend(&mut self, text: &str) -> Result<()> {
222        // sokf:end grammar-extend
223        self.transact(|g| g.lay_extension(text))
224    }
225
226    fn lay_extension(&mut self, text: &str) -> Result<()> {
227        let fail = |m: String| Error::Internal(format!("schema extension: {m}"));
228        let root = yaml::parse(text, 1).map_err(|e| fail(e.to_string()))?;
229        if root.get("extension").and_then(|e| e.as_str()).is_none() {
230            return Err(fail("no `extension` name".into()));
231        }
232        match root.get("extends").and_then(|e| e.as_str()) {
233            Some(name) if name == self.name => {}
234            other => {
235                return Err(fail(format!("extends {other:?}, not `{}`", self.name)));
236            }
237        }
238        for (name, value) in root.as_map().unwrap_or(&[]) {
239            match name.value.as_str() {
240                "extension" | "extends" | "version" | "doc" => {}
241                "meta" => return Err(fail("`meta` is the core grammar's".into())),
242                "schema" => self.extend_schema(value, false).map_err(fail)?,
243                // sokf-implements: CORE-3_AC-4
244                other if self.sections.contains_key(other) => {
245                    return Err(fail(format!("section `{other}` twice")));
246                }
247                other => {
248                    self.sections.insert(other.to_string(), value.clone());
249                }
250            }
251        }
252        self.check_references().map_err(fail)
253    }
254
255    /// Refuse an `of` that names neither a scalar nor a rule map, so that
256    /// the validator, which follows each one, never meets one that names
257    /// nothing: the fault is the grammar's, and no schema can mend it.
258    fn check_references(&self) -> std::result::Result<(), String> {
259        let maps = [("schema", &self.schema), ("rule-common", &self.rule_common)]
260            .into_iter()
261            .chain(self.rules.iter().map(|(n, m)| (n.as_str(), m)));
262        for (name, map) in maps {
263            for (key, def) in &map.keys {
264                match def.of.as_deref() {
265                    None | Some("string" | "integer" | "boolean" | "string-or-list") => {}
266                    Some(of) if self.rule(of).is_some() => {}
267                    Some(of) => {
268                        return Err(format!(
269                            "`{name}.{key}` holds `{of}`, which the grammar does not define"
270                        ));
271                    }
272                }
273            }
274        }
275        Ok(())
276    }
277
278    /// Add `node`, a `schema` section, to this grammar's. A format grammar
279    /// may also add text to a `doc` and constraint groups to a rule map; a
280    /// host extension may not.
281    fn extend_schema(&mut self, node: &Spanned, format: bool) -> std::result::Result<(), String> {
282        for (name, value) in node.as_map().unwrap_or(&[]) {
283            match name.value.as_str() {
284                "keys" => extend_keys(&mut self.schema, value, "schema")?,
285                "doc" | "exactly-one-of" | "at-least-one-of" if format => {
286                    add_to_map(&mut self.schema, name.value.as_str(), value);
287                }
288                "doc" | "exactly-one-of" | "at-least-one-of" | "rule-common" => {
289                    return Err(format!("`schema.{}` is the core grammar's", name.value));
290                }
291                map => {
292                    if let Some(core) = self.rules.get_mut(map) {
293                        for (k, v) in value.as_map().unwrap_or(&[]) {
294                            match k.value.as_str() {
295                                "keys" => extend_keys(core, v, map)?,
296                                "doc" | "exactly-one-of" | "at-least-one-of" if format => {
297                                    add_to_map(core, k.value.as_str(), v);
298                                }
299                                other => {
300                                    return Err(format!("`{map}.{other}` is the core grammar's"));
301                                }
302                            }
303                        }
304                    } else {
305                        let added = rule_map(value).map_err(|e| e.to_string())?;
306                        self.rules.insert(map.to_string(), added);
307                    }
308                }
309            }
310        }
311        Ok(())
312    }
313
314    /// The definition of `key` in rule map `name`, common keys included.
315    pub fn key_def(&self, name: &str, key: &str) -> Option<&KeyDef> {
316        self.rule(name).and_then(|m| m.key(key)).or_else(|| {
317            if self.accepts_common(name) {
318                self.rule_common.key(key)
319            } else {
320                None
321            }
322        })
323    }
324}
325
326/// Append the text of a layer's `doc` to `doc`.
327fn append_doc(doc: &mut String, more: &Spanned) {
328    let more = more.as_str().unwrap_or("").trim();
329    *doc = format!("{doc} {more}").trim().to_string();
330}
331
332/// Add a format grammar's `doc` text or constraint group to `map`.
333fn add_to_map(map: &mut RuleMap, key: &str, value: &Spanned) {
334    match key {
335        "doc" => append_doc(&mut map.doc, value),
336        "exactly-one-of" => map.exactly_one_of.extend(string_list(Some(value))),
337        _ => map.at_least_one_of.extend(string_list(Some(value))),
338    }
339}
340
341/// Add an extension's `keys` to a core rule map: a new key whole; on a
342/// core key, only more `enum` values, more required kinds and more `doc`.
343fn extend_keys(map: &mut RuleMap, keys: &Spanned, name: &str) -> std::result::Result<(), String> {
344    for (key, def) in keys.as_map().unwrap_or(&[]) {
345        let Some(core) = map.keys.iter_mut().find(|(k, _)| *k == key.value) else {
346            map.keys
347                .push((key.value.clone(), key_def(def).map_err(|e| e.to_string())?));
348            continue;
349        };
350        let core = &mut core.1;
351        for (k, v) in def.as_map().unwrap_or(&[]) {
352            match k.value.as_str() {
353                "enum" => core.enum_.extend(
354                    v.as_seq()
355                        .unwrap_or(&[])
356                        .iter()
357                        .filter_map(Spanned::scalar_text),
358                ),
359                "requires" if matches!(v.value, Yaml::Map(_)) => core.requires_kind.extend(
360                    v.get("kind")
361                        .and_then(Spanned::as_str_or_list)
362                        .unwrap_or_default(),
363                ),
364                "doc" => append_doc(&mut core.doc, v),
365                other => {
366                    return Err(format!(
367                        "`{name}.{}` changes the core grammar's `{other}`",
368                        key.value
369                    ));
370                }
371            }
372        }
373    }
374    Ok(())
375}
376
377// sokf-implements: CORE-1_AC-1
378// sokf:begin grammar-load
379/// Parse the embedded core grammar, onto which a format grammar is merged.
380pub fn load_core_grammar() -> Result<Grammar> {
381    parse_grammar(embedded::grammar_text())
382}
383// sokf:end grammar-load
384
385/// Parse a core grammar file.
386// sokf-implements: CORE-1_AC-2
387// sokf-implements: CORE-1_AC-3
388// sokf:begin grammar-load
389pub fn parse_grammar(text: &str) -> Result<Grammar> {
390    // sokf:end grammar-load
391    let root = yaml::parse(text, 1).map_err(|e| Error::Internal(format!("grammar: {e}")))?;
392    let name = root
393        .get("grammar")
394        .and_then(|v| v.as_str())
395        .ok_or_else(|| Error::Internal("grammar: no `grammar` name".into()))?
396        .to_string();
397    let version = root
398        .get("version")
399        .and_then(Spanned::scalar_text)
400        .ok_or_else(|| Error::Internal("grammar: no version".into()))?;
401    let schema_node = root
402        .get("schema")
403        .ok_or_else(|| Error::Internal("grammar: no schema section".into()))?;
404    let schema = rule_map(schema_node)?;
405    let mut rules = BTreeMap::new();
406    let mut rule_common = RuleMap::default();
407    for (key, value) in schema_node.as_map().unwrap_or(&[]) {
408        match key.value.as_str() {
409            "doc" | "keys" | "exactly-one-of" | "at-least-one-of" | "common" => {}
410            "rule-common" => rule_common = rule_map(value)?,
411            name => {
412                rules.insert(name.to_string(), rule_map(value)?);
413            }
414        }
415    }
416    let grammar = Grammar {
417        name,
418        version,
419        schema,
420        rules,
421        rule_common,
422        sections: BTreeMap::new(),
423    };
424    grammar
425        .check_references()
426        .map_err(|e| Error::Internal(format!("grammar: {e}")))?;
427    Ok(grammar)
428}
429
430fn rule_map(node: &Spanned) -> Result<RuleMap> {
431    let mut map = RuleMap {
432        doc: doc_of(node),
433        ..RuleMap::default()
434    };
435    if let Some(keys) = node.get("keys") {
436        for (name, def) in keys.as_map().unwrap_or(&[]) {
437            map.keys.push((name.value.clone(), key_def(def)?));
438        }
439    }
440    map.exactly_one_of = string_list(node.get("exactly-one-of"));
441    map.at_least_one_of = string_list(node.get("at-least-one-of"));
442    map.common = bool_of(node, "common");
443    Ok(map)
444}
445
446fn key_def(node: &Spanned) -> Result<KeyDef> {
447    let type_ = match node.get("type").and_then(|t| t.as_str()) {
448        Some(t) => TypeName::parse(t)
449            .ok_or_else(|| Error::Internal(format!("grammar: unknown type `{t}`")))?,
450        None => TypeName::String,
451    };
452    let mut requires_keys = Vec::new();
453    let mut requires_kind = Vec::new();
454    if let Some(r) = node.get("requires") {
455        match &r.value {
456            Yaml::Seq(_) => requires_keys = string_list(Some(r)),
457            Yaml::Map(_) => {
458                requires_kind = r
459                    .get("kind")
460                    .and_then(Spanned::as_str_or_list)
461                    .unwrap_or_default();
462            }
463            _ => {}
464        }
465    }
466    Ok(KeyDef {
467        type_,
468        of: str_of(node, "of"),
469        required: bool_of(node, "required"),
470        enum_: node
471            .get("enum")
472            .and_then(|e| e.as_seq())
473            .map(|items| items.iter().filter_map(Spanned::scalar_text).collect())
474            .unwrap_or_default(),
475        format: str_of(node, "format"),
476        requires_keys,
477        requires_kind,
478        doc: doc_of(node),
479    })
480}
481
482/// The `doc` of a grammar node, trimmed, or empty.
483fn doc_of(node: &Spanned) -> String {
484    str_of(node, "doc").unwrap_or_default().trim().to_string()
485}
486
487fn string_list(node: Option<&Spanned>) -> Vec<String> {
488    node.and_then(Spanned::as_str_or_list).unwrap_or_default()
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    const FORMAT: &str = "grammar: fmt\nbase: tramlines\nversion: '0.2'\ndoc: A format.\nschema:\n  doc: More.\n  at-least-one-of: [body]\n  keys:\n    body:\n      type: list\n      of: part\n  part:\n    common: true\n    keys:\n      text:\n        type: string\n  frontmatter-constraint:\n    exactly-one-of: [const, enum]\n    keys:\n      format:\n        enum: [email]\n";
496
497    // sokf-tests: TL_1
498    #[test]
499    fn loads_the_core_grammar() {
500        let g = load_core_grammar().unwrap();
501        assert_eq!(g.name, "tramlines");
502        assert_eq!(g.version, "0.1");
503        assert!(g.schema.key("line-limit").unwrap().required);
504        assert!(g.schema.key("frontmatter").is_some());
505        assert!(g.schema.key("sections").is_none());
506        assert!(
507            g.schema.at_least_one_of.is_empty(),
508            "{:?}",
509            g.schema.at_least_one_of
510        );
511        assert!(g.rule("section").is_none());
512        assert!(g.rule("frontmatter-constraint").is_some());
513        assert!(g.rule_common.key("severity").is_some());
514    }
515
516    // sokf-tests: TL_2
517    // sokf-tests: TL_3
518    #[test]
519    fn a_format_grammar_adds_keys_rule_maps_and_constraint_groups() {
520        let mut g = load_core_grammar().unwrap();
521        g.base(FORMAT).unwrap();
522        assert_eq!(g.name, "fmt");
523        assert_eq!(g.version, "0.2");
524        assert!(g.schema.doc.ends_with("More."));
525        assert_eq!(g.schema.at_least_one_of, vec!["body"]);
526        assert!(g.schema.key("body").is_some());
527        assert!(g.accepts_common("part"));
528        let fm = g.rule("frontmatter-constraint").unwrap();
529        assert_eq!(fm.exactly_one_of, vec!["const", "enum"]);
530        assert!(
531            fm.key("format")
532                .unwrap()
533                .enum_
534                .contains(&"email".to_string())
535        );
536    }
537
538    // sokf-tests: TL_4
539    #[test]
540    fn a_format_grammar_that_changes_the_core_is_refused() {
541        let base = |text: &str| load_core_grammar().unwrap().base(text);
542        assert!(base("base: tramlines\n").is_err());
543        assert!(base("grammar: fmt\nbase: other\n").is_err());
544        assert!(base("grammar: fmt\nbase: tramlines\nmeta: {}\n").is_err());
545        assert!(base("grammar: fmt\nbase: tramlines\nextra: {}\n").is_err());
546        assert!(
547            base("grammar: fmt\nbase: tramlines\nschema:\n  keys:\n    line-limit:\n      type: string\n")
548                .is_err()
549        );
550        assert!(base("grammar: fmt\nbase: tramlines\nschema:\n  rule-common: {}\n").is_err());
551    }
552
553    // sokf-tests: TL_5
554    // sokf-tests: TL_6
555    // sokf-tests: TL_7
556    // sokf-tests: TL_8
557    #[test]
558    fn a_host_extension_only_adds_to_its_format_grammar() {
559        let mut g = load_core_grammar().unwrap();
560        g.base(FORMAT).unwrap();
561        let mut h = g.clone();
562        h.extend("extension: host\nextends: fmt\nschema:\n  keys:\n    links:\n      type: list\n  part:\n    keys:\n      text:\n        doc: Also this.\nnotes:\n  a: 1\n")
563            .unwrap();
564        assert!(h.schema.key("links").is_some());
565        assert!(h.section("notes").is_some());
566        let refused = |text: &str| g.clone().extend(text);
567        assert!(refused("extends: fmt\n").is_err());
568        assert!(refused("extension: host\nextends: tramlines\n").is_err());
569        assert!(refused("extension: host\nextends: fmt\nmeta: {}\n").is_err());
570        assert!(
571            refused("extension: host\nextends: fmt\nschema:\n  at-least-one-of: [links]\n")
572                .is_err()
573        );
574        assert!(
575            refused(
576                "extension: host\nextends: fmt\nschema:\n  part:\n    exactly-one-of: [text]\n"
577            )
578            .is_err()
579        );
580        assert!(refused("extension: host\nextends: fmt\nschema:\n  part:\n    keys:\n      text:\n        type: integer\n").is_err());
581        assert!(refused("extension: host\nextends: fmt\nnotes: {}\nnotes: {}\n").is_err());
582    }
583
584    #[test]
585    fn a_grammar_whose_of_names_nothing_is_refused() {
586        let mut g = load_core_grammar().unwrap();
587        let format = "grammar: fmt\nbase: tramlines\nversion: '0.2'\nschema:\n  keys:\n    body:\n      type: list\n      of: nothing\n";
588        let before = g.clone();
589        let e = g.base(format).unwrap_err().to_string();
590        assert!(e.contains("`schema.body` holds `nothing`"), "{e}");
591        // A layer that fails leaves the grammar as it was.
592        assert_eq!(g, before);
593        let core = "grammar: x\nversion: '1'\nschema:\n  keys:\n    a:\n      type: list\n      of: nothing\n";
594        assert!(parse_grammar(core).is_err());
595    }
596
597    #[test]
598    fn refuses_a_broken_grammar() {
599        assert!(parse_grammar("grammar: x\n").is_err());
600        assert!(parse_grammar("version: '1'\nschema: {}\n").is_err());
601        assert!(
602            parse_grammar("grammar: x\nversion: '1'\nschema:\n  keys:\n    a:\n      type: nope\n")
603                .is_err()
604        );
605        assert!(parse_grammar("a: &x 1\n").is_err());
606        let g = parse_grammar("grammar: x\nversion: '1'\nschema:\n  keys:\n    a: {}\n").unwrap();
607        assert_eq!(g.schema.key("a").unwrap().type_, TypeName::String);
608        assert!(TypeName::parse("nope").is_none());
609    }
610}