Skip to main content

tramlines_md/markdown/
dialect.rs

1//! The marker names a host writes: the namespace of the engine's own
2//! markers, the host's region and trailer, and its reference scheme.
3
4use std::collections::BTreeMap;
5
6use crate::grammar::{Condition, Only};
7
8// sokf:begin dialect
9/// How a host spells the markers the parser recognises. The engine's own
10/// markers are `<ns>:only`, `<ns>:guidance` and `<ns>:optional`; a host
11/// may add one region, one trailer and one reference scheme.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Dialect {
14    /// The namespace every marker is written in, as `host`.
15    pub namespace: &'static str,
16    /// The host's region: `<!-- <ns>:<region> target -->` to
17    /// `<!-- /<ns>:<region> -->`, masked as one opaque block, as `include`.
18    pub region: Option<&'static str>,
19    /// The host's trailer: `<!-- <ns>:<trailer> -->`, the generated block
20    /// of reference definitions that ends a document, as `links`.
21    pub trailer: Option<&'static str>,
22    /// The host's reference scheme: a link label `<scheme>:<rest>` is a
23    /// reference the host resolves, as `host`.
24    pub scheme: Option<&'static str>,
25}
26// sokf:end dialect
27
28// sokf-implements: TLMD_17
29impl Default for Dialect {
30    /// The engine's markers alone, in the namespace `tramlines`.
31    fn default() -> Self {
32        Dialect {
33            namespace: "tramlines",
34            region: None,
35            trailer: None,
36            scheme: None,
37        }
38    }
39}
40
41/// The marker on a line, if any.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Marker {
44    /// `<!-- <ns>:<region> target -->`.
45    Open(String),
46    /// `<!-- /<ns>:<region> -->`.
47    Close,
48    /// `<!-- <ns>:<trailer> -->`.
49    Trailer,
50}
51
52/// The text inside an HTML comment line, if the line is one.
53pub(super) fn comment(line: &str) -> Option<&str> {
54    line.trim()
55        .strip_prefix("<!--")
56        .and_then(|s| s.strip_suffix("-->"))
57        .map(str::trim)
58}
59
60/// `text` starts with `<ns>:<name>`.
61fn names(text: &str, ns: &str, name: &str) -> bool {
62    text.strip_prefix(ns)
63        .and_then(|t| t.strip_prefix(':'))
64        .is_some_and(|t| t.starts_with(name))
65}
66
67impl Dialect {
68    /// `<ns>:<name>`, as a marker writes it.
69    pub fn spell(&self, name: &str) -> String {
70        format!("{}:{name}", self.namespace)
71    }
72
73    /// Recognise a region or trailer marker line. Whitespace inside the
74    /// comment is free; the line carries nothing else.
75    pub fn marker(&self, line: &str) -> Option<Marker> {
76        let inner = comment(line)?;
77        if let Some(region) = self.region {
78            if inner == format!("/{}", self.spell(region)) {
79                return Some(Marker::Close);
80            }
81            if let Some(target) = inner.strip_prefix(&self.spell(region)) {
82                let target = target.trim();
83                if target.is_empty() || target.contains(char::is_whitespace) {
84                    return None;
85                }
86                return Some(Marker::Open(target.to_string()));
87            }
88        }
89        if self.trailer.is_some_and(|t| inner == self.spell(t)) {
90            return Some(Marker::Trailer);
91        }
92        None
93    }
94
95    /// Whether a line is an `only` marker of grammar `example`, as an HTML
96    /// comment or a YAML comment.
97    pub fn is_only_marker(&self, line: &str) -> bool {
98        let only = format!("{} ", self.spell("only"));
99        if let Some(inner) = comment(line) {
100            return inner.starts_with(&only);
101        }
102        let t = line.trim();
103        match t.rfind('#') {
104            Some(i) => t[i + 1..].trim().starts_with(&only),
105            None => false,
106        }
107    }
108
109    /// Whether a line is a `guidance` marker: one HTML comment line, or one
110    /// YAML comment line, whose text starts `<ns>:guidance`. A scaffold
111    /// writes one before the part it guides; a governed document that keeps
112    /// one still has that part to write.
113    // sokf-implements: TLMD_158
114    pub fn is_guidance_marker(&self, line: &str) -> bool {
115        if let Some(inner) = comment(line) {
116            return names(inner, self.namespace, "guidance");
117        }
118        line.trim()
119            .strip_prefix('#')
120            .is_some_and(|rest| names(rest.trim_start(), self.namespace, "guidance"))
121    }
122
123    /// Whether a line opens an `optional` region: what lies between it and
124    /// its close is a part the schema does not demand, so a reader of the
125    /// scaffold keeps the part and drops the markers, or drops both. The
126    /// region is written open and closed, because its reader is a person
127    /// and nothing else tells them where it ends.
128    pub fn is_optional_marker(&self, line: &str) -> bool {
129        comment(line) == Some(self.spell("optional").as_str())
130    }
131
132    /// Whether a line closes an `optional` region.
133    pub fn is_optional_close(&self, line: &str) -> bool {
134        comment(line).and_then(|c| c.strip_prefix('/')) == Some(self.spell("optional").as_str())
135    }
136
137    /// Whether a line is either end of an `optional` region.
138    pub fn is_optional_mark(&self, line: &str) -> bool {
139        self.is_optional_marker(line) || self.is_optional_close(line)
140    }
141
142    /// Parse an `only k=v,v2 k2=v | k3=v` marker line into its condition:
143    /// each map, dimension to states, with the maps joined by ` | `. `None`
144    /// when the line is no marker or is malformed.
145    // sokf-implements: MD-3_AC-12
146    pub fn only_marker(&self, line: &str) -> Option<Condition> {
147        if !self.is_only_marker(line) {
148            return None;
149        }
150        let only = format!("{} ", self.spell("only"));
151        let i = line.find(&only)?;
152        let rest = line[i + only.len()..].trim_end_matches("-->").trim();
153        if rest.is_empty() {
154            return Some(Condition::default());
155        }
156        // A bar standing alone parts two maps; a bar inside a word is part
157        // of a state.
158        let words: Vec<&str> = rest.split_whitespace().collect();
159        let mut maps = Vec::new();
160        for part in words.split(|w| *w == "|") {
161            let mut map = BTreeMap::new();
162            for pair in part {
163                let (k, v) = pair.split_once('=')?;
164                // A dimension is a slug, so a bar in one is a bar that
165                // lacks its space.
166                if k.is_empty() || v.is_empty() || k.contains('|') {
167                    return None;
168                }
169                map.insert(k.to_string(), v.split(',').map(str::to_string).collect());
170            }
171            if map.is_empty() {
172                return None;
173            }
174            maps.push(Only(map));
175        }
176        Some(Condition::new(maps))
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    const HOST: Dialect = Dialect {
185        namespace: "host",
186        region: Some("include"),
187        trailer: Some("links"),
188        scheme: Some("host"),
189    };
190
191    // sokf-tests: MD-11_AC-2
192    #[test]
193    fn markers() {
194        let m = |l: &str| HOST.marker(l);
195        assert_eq!(m("<!-- host:include x -->"), Some(Marker::Open("x".into())));
196        assert_eq!(
197            m("  <!--host:include /a/b.rs#r-->"),
198            Some(Marker::Open("/a/b.rs#r".into()))
199        );
200        assert_eq!(m("<!-- /host:include -->"), Some(Marker::Close));
201        assert_eq!(m("<!-- host:links -->"), Some(Marker::Trailer));
202        assert_eq!(m("<!-- host:include -->"), None);
203        assert_eq!(m("<!-- host:include a b -->"), None);
204        assert_eq!(m("<!-- host:includes x -->"), None);
205        assert_eq!(m("text <!-- host:links -->"), None);
206        let plain = Dialect::default();
207        assert_eq!(plain.marker("<!-- host:include x -->"), None);
208        assert_eq!(plain.marker("<!-- tramlines:links -->"), None);
209    }
210
211    /// One map of a condition, from its dimensions and their states.
212    fn map(pairs: &[(&str, &[&str])]) -> Only {
213        Only(
214            pairs
215                .iter()
216                .map(|(k, v)| (k.to_string(), v.iter().map(ToString::to_string).collect()))
217                .collect(),
218        )
219    }
220
221    #[test]
222    fn only_markers() {
223        assert!(HOST.is_only_marker("<!-- host:only state=closed -->"));
224        assert!(HOST.is_only_marker("resolution: none # host:only state=closed"));
225        assert!(!HOST.is_only_marker("<!-- host:links -->"));
226        assert!(!HOST.is_only_marker("plain # comment"));
227        assert!(!HOST.is_only_marker("plain"));
228        assert!(HOST.is_optional_marker("<!-- host:optional -->"));
229        assert!(HOST.is_optional_close("<!-- /host:optional -->"));
230        assert!(HOST.is_optional_mark("<!-- /host:optional -->"));
231        assert!(!HOST.is_optional_marker("<!-- /host:optional -->"));
232        assert!(!HOST.is_optional_close("<!-- host:optional -->"));
233        assert!(!HOST.is_optional_marker("<!-- host:only state=closed -->"));
234        assert!(!HOST.is_optional_marker("<!-- host:optionally -->"));
235        assert!(!HOST.is_only_marker("<!-- host:optional -->"));
236        assert!(!Dialect::default().is_only_marker("<!-- host:only state=closed -->"));
237        assert!(Dialect::default().is_only_marker("<!-- tramlines:only state=closed -->"));
238        assert_eq!(
239            HOST.only_marker("<!-- host:only state=open,done kind=bug -->"),
240            Some(Condition(vec![map(&[
241                ("kind", &["bug"]),
242                ("state", &["open", "done"])
243            ])]))
244        );
245    }
246
247    // A condition of more than one map joins its maps with ` | `, and a
248    // marker with an empty map is malformed.
249    // sokf-tests: TLMD_121
250    // sokf-tests: MD-3_AC-12
251    #[test]
252    fn an_only_marker_joins_the_maps_of_a_condition() {
253        let two = HOST.only_marker("<!-- host:only plan=planned | state=closed kind=bug -->");
254        assert_eq!(
255            two,
256            Some(Condition(vec![
257                map(&[("kind", &["bug"]), ("state", &["closed"])]),
258                map(&[("plan", &["planned"])]),
259            ]))
260        );
261        // The maps come back in order, so a marker that lists them in
262        // another order agrees with its rule.
263        assert_eq!(
264            two.unwrap().render(),
265            "kind=bug state=closed | plan=planned"
266        );
267        assert_eq!(HOST.only_marker("<!-- host:only a=x | -->"), None);
268        assert_eq!(HOST.only_marker("<!-- host:only | a=x -->"), None);
269        assert_eq!(HOST.only_marker("<!-- host:only a=x || b=y -->"), None);
270        assert_eq!(HOST.only_marker("<!-- host:only a=x |b=y -->"), None);
271        assert_eq!(
272            HOST.only_marker("<!-- host:only state=a|b -->"),
273            Some(Condition(vec![map(&[("state", &["a|b"])])]))
274        );
275    }
276
277    #[test]
278    fn guidance_markers() {
279        assert!(HOST.is_guidance_marker("<!-- host:guidance Say what the part is for. -->"));
280        assert!(HOST.is_guidance_marker("  # host:guidance The states, in order."));
281        assert!(!HOST.is_guidance_marker("<!-- host:guidance spans"));
282        assert!(!HOST.is_guidance_marker("title: x # host:guidance trailing"));
283        assert!(!HOST.is_guidance_marker("<!-- host:only state=done -->"));
284    }
285}