Skip to main content

tramlines_core/grammar/
model.rs

1//! The schema keys every format shares, lowered: the frontmatter, the
2//! lifecycle, the formats, the examples and the bans of a schema, and the
3//! keys every rule map carries.
4
5use std::collections::BTreeMap;
6
7use serde::Serialize;
8
9use super::{FormatRegistry, IdTemplate, Shape};
10use crate::{Severity, Spanned};
11
12/// The scope of a captured key.
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub enum Scope {
15    /// Unique within the document.
16    Document,
17    /// Unique within a scope the host names and checks, as `knowledge`.
18    Host(String),
19}
20
21impl Scope {
22    /// The scope a `unique` value names; absent means the document.
23    pub fn parse(s: Option<&str>) -> Scope {
24        match s {
25            None | Some("document") => Scope::Document,
26            Some(host) => Scope::Host(host.to_string()),
27        }
28    }
29}
30
31/// One map of a condition: lifecycle dimension to admitted states.
32#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
33pub struct Only(pub BTreeMap<String, Vec<String>>);
34
35impl Only {
36    /// Whether the rule applies to a document in `states`: for every
37    /// dimension named, the document's states intersect the admitted ones.
38    pub fn admits(&self, states: &States) -> bool {
39        self.0.iter().all(|(dim, admitted)| {
40            states
41                .0
42                .get(dim)
43                .is_some_and(|have| have.iter().any(|s| admitted.contains(s)))
44        })
45    }
46
47    /// Whether some document's states admit both this rule and `other`:
48    /// each dimension both name admits a state in common.
49    pub fn overlaps(&self, other: &Only) -> bool {
50        self.0.iter().all(|(dim, admitted)| {
51            other
52                .0
53                .get(dim)
54                .is_none_or(|theirs| theirs.iter().any(|s| admitted.contains(s)))
55        })
56    }
57
58    /// Whether the rule is gated at all.
59    pub fn is_gated(&self) -> bool {
60        !self.0.is_empty()
61    }
62
63    /// `k=v,v2 k2=v`, as an `only` marker writes it.
64    pub fn render(&self) -> String {
65        self.0
66            .iter()
67            .map(|(k, v)| format!("{k}={}", v.join(",")))
68            .collect::<Vec<_>>()
69            .join(" ")
70    }
71}
72
73/// A condition on the lifecycle states (grammar `condition`): the maps of
74/// a list, of which any one that admits the states is enough. A map alone
75/// is a list of one. No map at all is no condition, which admits every
76/// state, as a rule with no `only` applies in every state. Build one with
77/// [`Condition::new`], which sorts the maps and keeps each once, so that
78/// two lists of the same maps make one value.
79/// Two conditions are equal where they hold the same maps, whatever the
80/// order of the maps and of the states of each.
81#[derive(Debug, Clone, Default)]
82pub struct Condition(pub Vec<Only>);
83
84impl PartialEq for Condition {
85    fn eq(&self, other: &Self) -> bool {
86        self.0 == other.0 || self.normal() == other.normal()
87    }
88}
89
90impl Eq for Condition {}
91
92impl Condition {
93    /// The condition of `maps`, in order and each once, whatever the order
94    /// of the states of each map. A map that names no dimension admits
95    /// every state, so a list that holds one is no condition.
96    // sokf-implements: CORE-6_AC-11
97    pub fn new(maps: impl IntoIterator<Item = Only>) -> Self {
98        let maps: Vec<Only> = maps.into_iter().collect();
99        if maps.iter().any(|only| only.0.is_empty()) {
100            return Condition::default();
101        }
102        // Each map once by its normal form, in the order of those forms,
103        // each kept as written.
104        let mut keyed: Vec<(Vec<Only>, Only)> = maps
105            .into_iter()
106            .map(|only| (Condition(vec![only.clone()]).normal(), only))
107            .collect();
108        keyed.sort_by(|a, b| a.0.cmp(&b.0));
109        keyed.dedup_by(|a, b| a.0 == b.0);
110        Condition(keyed.into_iter().map(|(_, only)| only).collect())
111    }
112
113    /// The maps, each with its states in order and each once, in order
114    /// and each once: the form that equality compares.
115    fn normal(&self) -> Vec<Only> {
116        let mut maps: Vec<Only> = self
117            .0
118            .iter()
119            .map(|only| {
120                Only(
121                    only.0
122                        .iter()
123                        .map(|(dim, states)| {
124                            let mut states = states.clone();
125                            states.sort();
126                            states.dedup();
127                            (dim.clone(), states)
128                        })
129                        .collect(),
130                )
131            })
132            .collect();
133        maps.sort();
134        maps.dedup();
135        maps
136    }
137
138    /// Whether some map of the condition admits `states`, or the condition
139    /// names no map. A map admits the states where, for each dimension that
140    /// it names, every state of the document that `lifecycle` declares is
141    /// one that the map admits. A dimension for which the document holds
142    /// no declared state counts as admitted, so a fault in the state of a
143    /// document is reported once, on its frontmatter, and not again by each
144    /// part that the condition makes optional. A map that names a dimension
145    /// that `lifecycle` does not declare admits no document.
146    // sokf-implements: CORE-6_AC-12
147    pub fn admits_known(&self, states: &States, lifecycle: &[LifecycleDimension]) -> bool {
148        self.0.is_empty()
149            || self.0.iter().any(|only| {
150                only.0.iter().all(|(dim, admitted)| {
151                    let Some(declared) = lifecycle.iter().find(|d| &d.key == dim) else {
152                        return false;
153                    };
154                    let mut known = states
155                        .0
156                        .get(dim)
157                        .into_iter()
158                        .flatten()
159                        .filter(|s| declared.states.contains(s))
160                        .peekable();
161                    known.peek().is_none() || known.all(|s| admitted.contains(s))
162                })
163            })
164    }
165
166    /// Whether some map of the condition admits `states`, or the
167    /// condition names no map.
168    // sokf-implements: TL_135
169    pub fn admits(&self, states: &States) -> bool {
170        self.0.is_empty() || self.0.iter().any(|only| only.admits(states))
171    }
172
173    /// Whether this condition and `other` both admit some document's
174    /// states: some map of the one overlaps some map of the other.
175    pub fn overlaps(&self, other: &Condition) -> bool {
176        self.0.is_empty()
177            || other.0.is_empty()
178            || self.0.iter().any(|a| other.0.iter().any(|b| a.overlaps(b)))
179    }
180
181    /// Whether the condition restricts the states at all.
182    pub fn is_gated(&self) -> bool {
183        !self.0.is_empty()
184    }
185
186    /// `k=v,v2 k2=v | k3=v`, as an `only` marker writes it: each map as
187    /// [`Only::render`] writes it, joined by ` | `.
188    pub fn render(&self) -> String {
189        self.0
190            .iter()
191            .map(Only::render)
192            .collect::<Vec<_>>()
193            .join(" | ")
194    }
195}
196
197impl From<Only> for Condition {
198    /// The condition of one map, as [`Condition::new`] builds it.
199    fn from(only: Only) -> Self {
200        Condition::new([only])
201    }
202}
203
204/// A document's lifecycle states: one per dimension, or a set for an
205/// example.
206#[derive(Debug, Clone, Default, PartialEq, Eq)]
207pub struct States(pub BTreeMap<String, Vec<String>>);
208
209/// Grammar `rule-common` plus `only`.
210#[derive(Debug, Clone, Default, PartialEq, Eq)]
211pub struct RuleCommon {
212    /// Error or warning.
213    pub severity: Severity,
214    /// When the rule applies.
215    pub only: Condition,
216    /// The rule's line in the schema.
217    pub line: usize,
218}
219
220/// A grammar `text` value: a literal, or a frontmatter key whose value
221/// stands in for it. Frontmatter is the authority; a repair rewrites the
222/// body.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub enum Text {
225    /// The string as written.
226    Literal(String),
227    /// `{ from: <key> }`.
228    From(String),
229}
230
231/// Grammar `key-derivation`.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct KeyDerivation {
234    /// Where the allowed prefixes come from.
235    pub source: DerivationSource,
236    /// The literal ending the prefix.
237    pub separator: String,
238}
239
240/// Where a `key-derivation` takes its prefixes (grammar exactly-one-of).
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub enum DerivationSource {
243    /// `rule`: the keys that rule captured.
244    Rule(String),
245    /// `from`: the value of a frontmatter key, the one prefix.
246    From(String),
247}
248
249impl KeyDerivation {
250    /// The source as a finding names it: ``set `x` `` or ``the frontmatter `x` ``.
251    pub fn source_label(&self) -> String {
252        match &self.source {
253            DerivationSource::Rule(r) => format!("set `{r}`"),
254            DerivationSource::From(k) => format!("the frontmatter `{k}`"),
255        }
256    }
257
258    /// The prefix of `prefixes` that `key` derives from: the longest that
259    /// `key` starts with, followed by the separator. A prefix can contain
260    /// the separator, so the key is never split at its first one.
261    // sokf-implements: TL_126
262    pub fn prefix_of<'a>(
263        &self,
264        key: &str,
265        prefixes: impl IntoIterator<Item = &'a str>,
266    ) -> Option<&'a str> {
267        prefixes
268            .into_iter()
269            .filter(|p| {
270                key.strip_prefix(p)
271                    .is_some_and(|rest| rest.starts_with(&self.separator))
272            })
273            .max_by_key(|p| p.len())
274    }
275}
276
277/// `format` of a frontmatter constraint.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum FmFormat {
280    /// An absolute URL.
281    Url,
282    /// A slug: lower-case letters and digits joined by single hyphens.
283    Slug,
284    /// A format the host names and checks, as `document-id`.
285    Host(String),
286}
287
288impl FmFormat {
289    /// The format's name in the grammar.
290    pub fn name(&self) -> &str {
291        match self {
292            FmFormat::Url => "url",
293            FmFormat::Slug => "slug",
294            FmFormat::Host(name) => name,
295        }
296    }
297}
298
299// sokf:begin limit
300/// Whether a limit is checked: grammar `limit` declares `soft` or `hard`.
301// sokf-implements: MD-13_AC-3
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
303#[serde(rename_all = "kebab-case")]
304pub enum LimitKind {
305    /// The usual length: never checked.
306    Soft,
307    /// The most a part holds: a part that holds more is an error.
308    Hard,
309}
310
311/// Grammar `limit`: how many units, lines, or elements a part holds at
312/// most, and the schema's text that tells the writer what to do with
313/// more.
314#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
315pub struct Limit {
316    /// `soft` or `hard`.
317    pub kind: LimitKind,
318    /// The number that `soft` or `hard` states.
319    pub count: usize,
320    /// `when-at-limit`: what the writer does at the limit, as the schema
321    /// writes it.
322    pub when_at_limit: String,
323}
324
325impl Limit {
326    /// The count that the engine checks and bounds by: a hard limit's, and
327    /// none for a soft limit.
328    // sokf-implements: TL_139
329    // sokf-implements: CORE-6_AC-14
330    pub fn hard(&self) -> Option<usize> {
331        (self.kind == LimitKind::Hard).then_some(self.count)
332    }
333}
334// sokf:end limit
335
336/// Grammar `frontmatter-constraint`.
337#[derive(Debug, Clone)]
338pub struct FrontmatterConstraint {
339    /// The common keys.
340    pub common: RuleCommon,
341    /// `const`.
342    pub const_: Option<String>,
343    /// `template` or `pattern`: the value's shape.
344    pub shape: Option<Shape>,
345    /// `enum`.
346    pub enum_: Option<Vec<String>>,
347    /// `format`.
348    pub format: Option<FmFormat>,
349    /// The id a new document is filled with, from the `id` key's template.
350    pub id_template: Option<IdTemplate>,
351    /// `list`.
352    pub list: bool,
353    /// `min`.
354    pub min: Option<usize>,
355    /// `max`: the limit on the number of elements.
356    pub max: Option<Limit>,
357    /// `optional`.
358    pub optional: bool,
359    /// `example`: a value of the kind this key demands.
360    pub example: Option<String>,
361    /// `guidance`: what the example cannot say, written on a comment line before the key.
362    pub guidance: Option<String>,
363}
364
365impl FrontmatterConstraint {
366    /// The value that the schema fixes for the key in a scaffold at
367    /// `states`: its `const`, else the `id` template rendered with its
368    /// sequence at one and the slug `example`, else its `example`.
369    pub fn fixed_value(&self, states: &States) -> Option<String> {
370        if let Some(v) = &self.const_ {
371            return Some(v.clone());
372        }
373        if let Some(t) = &self.id_template
374            && let Ok(v) = t.render_with(1, t.has_slug().then_some("example"), states)
375        {
376            return Some(v);
377        }
378        self.example.clone()
379    }
380
381    /// The value that a scaffold at `states` writes for a declared key:
382    /// [`FrontmatterConstraint::fixed_value`], else the first value of its
383    /// `enum`.
384    pub fn scaffold_value(&self, states: &States) -> Option<String> {
385        self.fixed_value(states)
386            .or_else(|| self.enum_.as_ref()?.first().cloned())
387    }
388}
389
390/// Grammar `lifecycle-dimension`.
391#[derive(Debug, Clone, PartialEq)]
392pub struct LifecycleDimension {
393    /// `key`.
394    pub key: String,
395    /// `states`.
396    pub states: Vec<String>,
397    /// `guidance`: what the states mean, written on a comment line before the key.
398    pub guidance: Option<String>,
399    /// The line in the schema.
400    pub line: usize,
401    /// The keys a host's extension adds, as written: the host lowers what
402    /// it adds.
403    pub extensions: BTreeMap<String, Spanned>,
404}
405
406impl LifecycleDimension {
407    /// The state that a scaffold at `states` writes for the dimension: the
408    /// first that `states` gives it, else its first state.
409    pub fn state_in<'a>(&'a self, states: &'a States) -> Option<&'a String> {
410        states
411            .0
412            .get(&self.key)
413            .and_then(|s| s.first())
414            .or_else(|| self.states.first())
415    }
416}
417
418/// Grammar `example`.
419#[derive(Debug, Clone)]
420pub struct Example {
421    /// `document`.
422    pub document: String,
423    /// The line in the schema.
424    pub line: usize,
425}
426
427// sokf:begin core-schema
428/// The part of a lowered schema that every format shares: grammar
429/// `schema`, the keys of the core grammar.
430#[derive(Debug, Clone)]
431pub struct CoreSchema {
432    /// `line-limit`; zero or less declares no limit.
433    pub line_limit: i64,
434    /// `lifecycle`.
435    pub lifecycle: Vec<LifecycleDimension>,
436    /// `frontmatter`, in schema order.
437    pub frontmatter: Vec<(String, FrontmatterConstraint)>,
438    /// `frontmatter-open`.
439    pub frontmatter_open: bool,
440    /// `prohibited-patterns`: what no line of the body may match.
441    pub prohibited_patterns: Vec<super::Prohibition>,
442    /// The registry as this schema sees it.
443    pub formats: FormatRegistry,
444    /// `guidance`: what the schema says that no example can.
445    pub guidance: Option<String>,
446    /// `language`: the BCP 47 tag of the language of the schema's text.
447    pub language: Option<String>,
448    /// `examples`.
449    pub examples: Vec<Example>,
450    /// The line of the schema where it is written.
451    pub line: usize,
452    /// The line of each key of the schema, by the key.
453    pub key_lines: BTreeMap<String, usize>,
454}
455// sokf:end core-schema
456
457impl CoreSchema {
458    /// A schema that demands nothing.
459    pub fn demand_nothing() -> CoreSchema {
460        CoreSchema {
461            line_limit: 0,
462            lifecycle: vec![],
463            frontmatter: vec![],
464            frontmatter_open: true,
465            prohibited_patterns: vec![],
466            formats: FormatRegistry::default(),
467            guidance: None,
468            language: None,
469            examples: vec![],
470            line: 0,
471            key_lines: BTreeMap::new(),
472        }
473    }
474
475    /// A document's lifecycle states, one per dimension its frontmatter
476    /// carries.
477    pub fn states(&self, frontmatter: Option<&Spanned>) -> States {
478        let mut states = States::default();
479        for dim in &self.lifecycle {
480            if let Some(value) = frontmatter
481                .and_then(|f| f.get(&dim.key))
482                .and_then(Spanned::scalar_text)
483            {
484                states.0.insert(dim.key.clone(), vec![value]);
485            }
486        }
487        states
488    }
489
490    /// The `type` const, where the `type` key declares one.
491    pub fn type_const(&self) -> Option<&str> {
492        self.constraint("type")?.const_.as_deref()
493    }
494
495    /// The constraint the schema declares on the frontmatter `key`.
496    // sokf:begin core-schema
497    pub fn constraint(&self, key: &str) -> Option<&FrontmatterConstraint> {
498        // sokf:end core-schema
499        // sokf-implements: CORE-6_AC-9
500        self.frontmatter
501            .iter()
502            .find(|(k, _)| k == key)
503            .map(|(_, c)| c)
504    }
505
506    /// The id template, if `frontmatter.id.template` is declared.
507    pub fn id_template(&self) -> Option<&IdTemplate> {
508        self.constraint("id")?.id_template.as_ref()
509    }
510
511    /// The lifecycle dimension with `key`.
512    pub fn dimension(&self, key: &str) -> Option<&LifecycleDimension> {
513        self.lifecycle.iter().find(|d| d.key == key)
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520
521    // sokf-tests: TL_126
522    #[test]
523    fn a_key_derives_from_the_longest_prefix_that_starts_it() {
524        let kd = KeyDerivation {
525            source: DerivationSource::From("code".into()),
526            separator: "-".into(),
527        };
528        assert_eq!(kd.prefix_of("CE-BUG-1", ["CE", "CE-BUG"]), Some("CE-BUG"));
529        assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BUG", "CE"]), Some("CE-BUG"));
530        assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BU"]), None);
531        assert_eq!(kd.prefix_of("CE-BUG", ["CE-BUG"]), None);
532        assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-FIX"]), None);
533    }
534
535    /// One map of a condition, from `dimension=state` pairs.
536    fn map(pairs: &[(&str, &str)]) -> Only {
537        Only(
538            pairs
539                .iter()
540                .map(|(k, v)| (k.to_string(), vec![v.to_string()]))
541                .collect(),
542        )
543    }
544
545    // A list matches where any of its maps does, two lists overlap where
546    // a map of each does, and no map at all is no condition.
547    // sokf-tests: TL_135
548    #[test]
549    fn a_condition_matches_where_any_of_its_maps_does() {
550        let either = Condition(vec![
551            map(&[("plan", "planned")]),
552            map(&[("state", "closed")]),
553        ]);
554        let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
555        assert!(either.admits(&at(&[("plan", "planned"), ("state", "open")])));
556        assert!(either.admits(&at(&[("plan", "unplanned"), ("state", "closed")])));
557        assert!(!either.admits(&at(&[("plan", "unplanned"), ("state", "open")])));
558        assert!(Condition::default().admits(&at(&[("state", "open")])));
559        assert!(either.overlaps(&Condition(vec![map(&[("state", "closed")])])));
560        assert!(!either.overlaps(&Condition(vec![map(&[
561            ("plan", "unplanned"),
562            ("state", "open")
563        ])])));
564        assert!(either.overlaps(&Condition::default()));
565        assert_eq!(either.render(), "plan=planned | state=closed");
566        assert_eq!(Condition::from(Only::default()), Condition::default());
567        let closed = map(&[("state", "closed")]);
568        let planned = map(&[("plan", "planned")]);
569        assert_eq!(
570            Condition::new([closed.clone(), planned.clone(), closed.clone()]),
571            Condition::new([planned.clone(), closed.clone()])
572        );
573        assert_eq!(
574            Condition::new([planned.clone(), Only::default()]),
575            Condition::default()
576        );
577        let two = |a: &str, b: &str| {
578            Only(BTreeMap::from([(
579                "state".to_string(),
580                vec![a.to_string(), b.to_string()],
581            )]))
582        };
583        assert_eq!(
584            Condition::new([two("open", "closed")]),
585            Condition::new([two("closed", "open")])
586        );
587        assert_eq!(
588            Condition::new([two("open", "closed"), two("closed", "open")]).0,
589            vec![two("open", "closed")]
590        );
591    }
592
593    // A dimension for which the document holds no declared state counts as
594    // admitted, a dimension that the lifecycle does not declare admits
595    // nothing, and a set of states is admitted only where each is.
596    // sokf-tests: CORE-6_AC-12
597    // sokf-tests: CORE-6_AC-11
598    #[test]
599    fn a_condition_counts_an_unknown_state_as_admitted() {
600        let lifecycle = [LifecycleDimension {
601            key: "plan".into(),
602            states: vec!["unplanned".into(), "planned".into()],
603            guidance: None,
604            line: 0,
605            extensions: BTreeMap::new(),
606        }];
607        let unplanned = Condition::new([map(&[("plan", "unplanned")])]);
608        let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
609        assert!(unplanned.admits_known(&at(&[("plan", "unplanned")]), &lifecycle));
610        assert!(!unplanned.admits_known(&at(&[("plan", "planned")]), &lifecycle));
611        assert!(unplanned.admits_known(&at(&[]), &lifecycle));
612        assert!(unplanned.admits_known(&at(&[("plan", "later")]), &lifecycle));
613        let both = States(BTreeMap::from([(
614            "plan".to_string(),
615            vec!["unplanned".to_string(), "planned".to_string()],
616        )]));
617        assert!(!unplanned.admits_known(&both, &lifecycle));
618        let unknown = Condition::new([map(&[("phase", "closed")])]);
619        assert!(!unknown.admits_known(&at(&[("plan", "planned")]), &lifecycle));
620        assert!(!Condition::from(Only::default()).is_gated());
621    }
622}