Skip to main content

instruction_md/
types.rs

1//! The authored tree (§2) — `{format, metadata, body}`, the shape `instruction.schema.json` validates — and the
2//! reader's sidecar: diagnostics (§18), identities and parameters, which the tree itself does not carry.
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::Arc;
7
8use serde_json::{Map, Value};
9
10use crate::js::num;
11
12/// The authored tree's format.
13pub const TREE_FORMAT: &str = "instruction/1";
14
15/// A JSON object: a directive's attributes, a metadata region, a structured body's mapping.
16pub type Object = Map<String, Value>;
17
18/// A directive's attributes: strings, numbers, booleans and lists.
19pub type Attrs = Object;
20
21/// The order a loaded value's mappings were written in, which a JSON map does not keep: the top mapping's keys under
22/// "", and those of each mapping it holds under the key that holds it.
23#[derive(Clone, Debug, Default, PartialEq)]
24pub(crate) struct KeyOrder(pub(crate) HashMap<String, Vec<String>>);
25
26impl KeyOrder {
27    /// The path of a mapping below a top-level key: the key, then each key under it, apart by U+001F.
28    pub(crate) fn path(key: &str, rest: &[&str]) -> String {
29        let mut p = key.to_string();
30        for k in rest {
31            p.push('\u{1f}');
32            p.push_str(k);
33        }
34        p
35    }
36
37    /// The mapping's keys in the order written (any the order does not know, sorted, after).
38    pub(crate) fn keys(&self, path: &str, m: &Object) -> Vec<String> {
39        let mut out: Vec<String> = Vec::with_capacity(m.len());
40        if let Some(written) = self.0.get(path) {
41            for k in written {
42                if m.contains_key(k) && !out.contains(k) {
43                    out.push(k.clone());
44                }
45            }
46        }
47        for k in m.keys() {
48            if !out.contains(k) {
49                out.push(k.clone());
50            }
51        }
52        out
53    }
54}
55
56/// An authored (or resolved) tree.
57#[derive(Clone, Debug, Default, PartialEq)]
58pub struct Document {
59    pub format: String,
60    /// The document's URI, when it has one.
61    pub uri: String,
62    pub metadata: Metadata,
63    pub body: Vec<Node>,
64    /// the tree as decoded, when it was: what its digest covers
65    pub(crate) raw: Option<Value>,
66}
67
68/// The document's front matter and backmatter, each a YAML mapping.
69#[derive(Clone, Debug, Default, PartialEq)]
70pub struct Metadata {
71    pub front: Object,
72    pub back: Object,
73    pub(crate) front_order: KeyOrder,
74}
75
76/// What a node is: a Markdown segment or a directive.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
78pub enum NodeType {
79    Markdown,
80    Directive,
81}
82
83impl NodeType {
84    pub fn as_str(self) -> &'static str {
85        match self {
86            NodeType::Markdown => "markdown",
87            NodeType::Directive => "directive",
88        }
89    }
90}
91
92/// A directive's form (§5): `:::kind … :::`, `::kind{…}`, a keyword line (`MUST: …`) or an alert (`> [!TIP]`).
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94pub enum Form {
95    Container,
96    Leaf,
97    Keyword,
98    Alert,
99}
100
101impl Form {
102    pub fn as_str(self) -> &'static str {
103        match self {
104            Form::Container => "container",
105            Form::Leaf => "leaf",
106            Form::Keyword => "keyword",
107            Form::Alert => "alert",
108        }
109    }
110
111    pub fn parse(s: &str) -> Option<Form> {
112        Some(match s {
113            "container" => Form::Container,
114            "leaf" => Form::Leaf,
115            "keyword" => Form::Keyword,
116            "alert" => Form::Alert,
117            _ => return None,
118        })
119    }
120}
121
122impl fmt::Display for Form {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str(self.as_str())
125    }
126}
127
128/// A node of the tree: a Markdown segment (its `source`) or a directive.
129#[derive(Clone, Debug, PartialEq)]
130pub struct Node {
131    pub node_type: NodeType,
132    /// A directive's kind (`must`, `policy`, `charts:metric`); empty for Markdown.
133    pub kind: String,
134    /// A directive's form; `None` for Markdown.
135    pub form: Option<Form>,
136    pub attrs: Attrs,
137    /// A Markdown-bodied directive's parsed body; a literal body (an example's, a verbatim one) is one Markdown node.
138    /// `None`: the directive has no such body (a leaf, a structured body); empty: an empty one.
139    pub children: Option<Vec<Node>>,
140    /// A structured or literal-format body (YAML, JSON, CSV, text, HTML, code).
141    pub value: Option<StructuredValue>,
142    /// A Markdown node's text, or the full source of a directive this reader does not interpret.
143    pub source: String,
144    pub range: Option<Range>,
145    /// A resolved node's composition path (§2, §14.1): `root`, `root/personal`.
146    pub instance: String,
147
148    pub(crate) prose: bool,
149    pub(crate) keyword: Option<String>,
150    pub(crate) reason: Option<Range>,
151    /// a container's body in the source it was read from
152    pub(crate) body: Option<Span>,
153}
154
155/// A span of a source the reader read: the source is shared, not copied, by every node that has one.
156#[derive(Clone)]
157pub(crate) struct Span {
158    pub(crate) text: Arc<str>,
159    pub(crate) start: usize,
160    pub(crate) end: usize,
161}
162
163impl Span {
164    pub(crate) fn as_str(&self) -> &str {
165        self.text.get(self.start..self.end).unwrap_or("")
166    }
167}
168
169impl fmt::Debug for Span {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        fmt::Debug::fmt(self.as_str(), f)
172    }
173}
174
175impl PartialEq for Span {
176    fn eq(&self, other: &Self) -> bool {
177        self.as_str() == other.as_str()
178    }
179}
180
181impl Node {
182    /// A Markdown node.
183    pub fn markdown(source: impl Into<String>) -> Node {
184        Node {
185            node_type: NodeType::Markdown,
186            kind: String::new(),
187            form: None,
188            attrs: Attrs::new(),
189            children: None,
190            value: None,
191            source: source.into(),
192            range: None,
193            instance: String::new(),
194            prose: false,
195            keyword: None,
196            reason: None,
197            body: None,
198        }
199    }
200
201    /// A directive node.
202    pub fn directive(kind: impl Into<String>, form: Form, attrs: Attrs) -> Node {
203        Node { node_type: NodeType::Directive, kind: kind.into(), form: Some(form), attrs, ..Node::markdown("") }
204    }
205
206    pub fn is_markdown(&self) -> bool {
207        self.node_type == NodeType::Markdown
208    }
209
210    pub fn is_directive(&self) -> bool {
211        self.node_type == NodeType::Directive
212    }
213
214    /// The keyword a keyword rule or an alert was written with (`ALWAYS`, `AVOID`, `MUST NOT`); the tree keeps its
215    /// normalized kind. Set by the reader.
216    pub fn keyword(&self) -> Option<&str> {
217        self.keyword.as_deref()
218    }
219
220    /// The lines of a rule's `BECAUSE:` reason, which the tree keeps as the rule's `because`. Set by the reader.
221    pub fn reason_range(&self) -> Option<Range> {
222        self.reason
223    }
224
225    /// Is this Markdown node parsed prose (not an example's or a verbatim body's quoted text)? Set by the reader.
226    pub fn is_prose(&self) -> bool {
227        self.prose
228    }
229
230    /// The exact source text of a container's body, as the reader read it: every line between the opening fence's
231    /// line and the closing fence's (each with its line ending, comments and all; empty for an empty body), or to the
232    /// end of the source when the container is not closed. `None` for any other node, and for a node not read from
233    /// source (built, or decoded from a tree's JSON).
234    ///
235    /// ```
236    /// use instruction_md::{read, ReadOptions};
237    ///
238    /// let r = read(":::skill{id=plan}\nPlan the day.\n<!-- kept -->\n:::\n", &ReadOptions::default());
239    /// assert_eq!(r.document.body[0].body_source(), Some("Plan the day.\n<!-- kept -->\n"));
240    /// ```
241    pub fn body_source(&self) -> Option<&str> {
242        self.body.as_ref().map(Span::as_str)
243    }
244
245    /// The node's children, or none.
246    pub fn children(&self) -> &[Node] {
247        self.children.as_deref().unwrap_or(&[])
248    }
249
250    /// A string attribute.
251    pub fn attr_str(&self, key: &str) -> Option<&str> {
252        self.attrs.get(key).and_then(Value::as_str)
253    }
254
255    /// The node as instruction.schema.json has it.
256    pub fn to_json(&self) -> Value {
257        let mut m = Map::new();
258        m.insert("type".into(), self.node_type.as_str().into());
259        if self.is_markdown() {
260            m.insert("source".into(), self.source.clone().into());
261        } else {
262            m.insert("kind".into(), self.kind.clone().into());
263            m.insert("form".into(), self.form.map_or("container", Form::as_str).into());
264            m.insert("attrs".into(), Value::Object(self.attrs.clone()));
265        }
266        if let Some(r) = self.range {
267            m.insert("range".into(), r.to_json());
268        }
269        if self.is_directive() {
270            if let Some(children) = &self.children {
271                m.insert("children".into(), Value::Array(children.iter().map(Node::to_json).collect()));
272            }
273            if let Some(v) = &self.value {
274                m.insert("value".into(), v.to_json());
275            }
276            if !self.source.is_empty() {
277                m.insert("source".into(), self.source.clone().into());
278            }
279        }
280        if !self.instance.is_empty() {
281            m.insert("instance".into(), self.instance.clone().into());
282        }
283        Value::Object(m)
284    }
285
286    /// Reads a node of a tree.
287    pub fn from_json(v: &Value) -> Result<Node, String> {
288        let o = v.as_object().ok_or("a node is an object")?;
289        let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or("").to_string();
290        let node_type = match o.get("type").and_then(Value::as_str) {
291            Some("markdown") => NodeType::Markdown,
292            Some("directive") => NodeType::Directive,
293            _ => return Err("a node's type is markdown or directive".into()),
294        };
295        let form = match o.get("form").and_then(Value::as_str) {
296            Some(f) => Some(Form::parse(f).ok_or_else(|| format!("unknown form {f}"))?),
297            None if node_type == NodeType::Directive => Some(Form::Container),
298            None => None,
299        };
300        let children = match o.get("children") {
301            Some(Value::Array(list)) => Some(list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?),
302            _ => None,
303        };
304        let value = match o.get("value") {
305            Some(v @ Value::Object(_)) => Some(StructuredValue::from_json(v)),
306            _ => None,
307        };
308        Ok(Node {
309            node_type,
310            kind: s("kind"),
311            form: if node_type == NodeType::Directive { form } else { None },
312            attrs: o.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(),
313            children,
314            value,
315            source: s("source"),
316            range: o.get("range").and_then(Range::from_json),
317            instance: s("instance"),
318            prose: false,
319            keyword: None,
320            reason: None,
321            body: None,
322        })
323    }
324}
325
326/// A structured body: its format, its text and, when it parsed, its data.
327#[derive(Clone, Debug, PartialEq)]
328pub struct StructuredValue {
329    pub format: String,
330    pub source: String,
331    /// The parsed data; `None` when the body did not parse (a parsed `null` is `Some(Value::Null)`).
332    pub data: Option<Value>,
333    pub(crate) order: KeyOrder,
334}
335
336impl StructuredValue {
337    pub fn to_json(&self) -> Value {
338        let mut m = Map::new();
339        m.insert("format".into(), self.format.clone().into());
340        m.insert("source".into(), self.source.clone().into());
341        if let Some(d) = &self.data {
342            m.insert("data".into(), d.clone());
343        }
344        Value::Object(m)
345    }
346
347    pub fn from_json(v: &Value) -> StructuredValue {
348        let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
349        StructuredValue { format: s("format"), source: s("source"), data: v.get("data").cloned(), order: KeyOrder::default() }
350    }
351}
352
353/// A span of source lines, 1-based and inclusive.
354#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
355pub struct Range {
356    pub start: u32,
357    pub end: u32,
358}
359
360impl Range {
361    pub fn new(start: u32, end: u32) -> Range {
362        Range { start, end }
363    }
364
365    pub fn line(n: u32) -> Range {
366        Range { start: n, end: n }
367    }
368
369    pub fn to_json(self) -> Value {
370        let mut m = Map::new();
371        m.insert("start".into(), self.start.into());
372        m.insert("end".into(), self.end.into());
373        Value::Object(m)
374    }
375
376    fn from_json(v: &Value) -> Option<Range> {
377        let n = |k: &str| v.get(k).and_then(Value::as_f64).map(|f| f.clamp(0.0, u32::MAX as f64) as u32);
378        Some(Range { start: n("start")?, end: n("end")? })
379    }
380}
381
382/// A diagnostic's severity.
383#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
384pub enum Severity {
385    Error,
386    Warning,
387    Info,
388}
389
390impl Severity {
391    pub fn as_str(self) -> &'static str {
392        match self {
393            Severity::Error => "error",
394            Severity::Warning => "warning",
395            Severity::Info => "info",
396        }
397    }
398}
399
400impl fmt::Display for Severity {
401    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402        f.write_str(self.as_str())
403    }
404}
405
406/// A problem found in a source (§18): a stable code (`unclosed-directive`, `invalid-attributes`, …), its severity, a
407/// message for a person, and where.
408#[derive(Clone, Debug, PartialEq)]
409pub struct Diagnostic {
410    pub code: &'static str,
411    pub severity: Severity,
412    pub message: String,
413    /// The source it was found in, when that is not the document itself (a base or an include).
414    pub uri: String,
415    pub range: Option<Range>,
416    pub target: String,
417    pub remedy: String,
418}
419
420impl Diagnostic {
421    pub(crate) fn new(code: &'static str, severity: Severity, message: impl Into<String>, line: u32) -> Diagnostic {
422        Diagnostic {
423            code,
424            severity,
425            message: message.into(),
426            uri: String::new(),
427            range: (line > 0).then(|| Range::line(line)),
428            target: String::new(),
429            remedy: String::new(),
430        }
431    }
432
433    /// The line it starts on, when it has one.
434    pub fn line(&self) -> Option<u32> {
435        self.range.map(|r| r.start)
436    }
437
438    pub fn is_error(&self) -> bool {
439        self.severity == Severity::Error
440    }
441
442    /// The diagnostic as JSON (§18).
443    pub fn to_json(&self) -> Value {
444        let mut m = Map::new();
445        m.insert("code".into(), self.code.into());
446        m.insert("severity".into(), self.severity.as_str().into());
447        m.insert("message".into(), self.message.clone().into());
448        if !self.uri.is_empty() {
449            m.insert("uri".into(), self.uri.clone().into());
450        }
451        if let Some(r) = self.range {
452            m.insert("range".into(), r.to_json());
453        }
454        if !self.target.is_empty() {
455            m.insert("target".into(), self.target.clone().into());
456        }
457        if !self.remedy.is_empty() {
458            m.insert("remedy".into(), self.remedy.clone().into());
459        }
460        Value::Object(m)
461    }
462}
463
464impl fmt::Display for Diagnostic {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        if !self.uri.is_empty() {
467            write!(f, "{}:", self.uri)?;
468        }
469        if let Some(r) = self.range {
470            write!(f, "{}: ", r.start)?;
471        }
472        write!(f, "{} {}: {}", self.severity, self.code, self.message)
473    }
474}
475
476/// An explicit identity (§5.3): a directive's or keyword's id, or a heading's `{#id}`.
477#[derive(Clone, Debug, PartialEq, Eq)]
478pub struct Identity {
479    pub id: String,
480    pub kind: String,
481    pub line: u32,
482}
483
484impl Identity {
485    pub fn to_json(&self) -> Value {
486        let mut m = Map::new();
487        m.insert("id".into(), self.id.clone().into());
488        m.insert("kind".into(), self.kind.clone().into());
489        m.insert("line".into(), self.line.into());
490        Value::Object(m)
491    }
492}
493
494/// A declared parameter (§12), from the front matter or a `::param` leaf.
495#[derive(Clone, Debug, PartialEq, Default)]
496pub struct Parameter {
497    pub name: String,
498    pub param_type: String,
499    pub required: bool,
500    pub values: Option<Vec<String>>,
501    /// The default and the example, when there is one (a null one is a value).
502    pub default: Option<Value>,
503    pub example: Option<Value>,
504    pub description: Option<String>,
505    pub source: Option<String>,
506    /// Where it was declared: 0 for the front matter, else its param leaf's line.
507    pub line: u32,
508}
509
510impl Parameter {
511    /// The parameter as the reference writes it: `declaredAt` is "front-matter" or the leaf's line.
512    pub fn to_json(&self) -> Value {
513        let mut m = Map::new();
514        m.insert("name".into(), self.name.clone().into());
515        m.insert("type".into(), self.param_type.clone().into());
516        m.insert("required".into(), self.required.into());
517        if let Some(v) = &self.values {
518            m.insert("values".into(), v.clone().into());
519        }
520        m.insert("declaredAt".into(), if self.line == 0 { "front-matter".into() } else { self.line.into() });
521        if let Some(v) = &self.default {
522            m.insert("default".into(), v.clone());
523        }
524        if let Some(v) = &self.example {
525            m.insert("example".into(), v.clone());
526        }
527        if let Some(v) = &self.description {
528            m.insert("description".into(), v.clone().into());
529        }
530        if let Some(v) = &self.source {
531            m.insert("source".into(), v.clone().into());
532        }
533        Value::Object(m)
534    }
535}
536
537impl Document {
538    /// A tree of the body, with empty metadata.
539    pub fn new(body: Vec<Node>) -> Document {
540        Document { format: TREE_FORMAT.into(), body, ..Document::default() }
541    }
542
543    /// The tree as instruction.schema.json has it.
544    pub fn to_json(&self) -> Value {
545        let mut m = Map::new();
546        m.insert("format".into(), self.format.clone().into());
547        if !self.uri.is_empty() {
548            m.insert("uri".into(), self.uri.clone().into());
549        }
550        let mut meta = Map::new();
551        meta.insert("front".into(), Value::Object(self.metadata.front.clone()));
552        meta.insert("back".into(), Value::Object(self.metadata.back.clone()));
553        m.insert("metadata".into(), Value::Object(meta));
554        m.insert("body".into(), Value::Array(self.body.iter().map(Node::to_json).collect()));
555        Value::Object(m)
556    }
557
558    /// Reads a tree from its JSON (a missing metadata region is empty).
559    pub fn from_json(v: &Value) -> Result<Document, String> {
560        let o = v.as_object().ok_or("a tree is an object")?;
561        let metadata = o.get("metadata");
562        let region = |k: &str| metadata.and_then(|m| m.get(k)).and_then(Value::as_object).cloned().unwrap_or_default();
563        let front = region("front");
564        let mut order = KeyOrder::default();
565        // (a JSON map keeps no order: the mappings' keys as written are not known here, so they read sorted)
566        order.0.insert(String::new(), front.keys().cloned().collect());
567        let body = match o.get("body") {
568            Some(Value::Array(list)) => list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?,
569            _ => Vec::new(),
570        };
571        Ok(Document {
572            format: o.get("format").and_then(Value::as_str).unwrap_or("").to_string(),
573            uri: o.get("uri").and_then(Value::as_str).unwrap_or("").to_string(),
574            metadata: Metadata { front, back: region("back"), front_order: order },
575            body,
576            raw: Some(v.clone()),
577        })
578    }
579
580    /// The tree as a JSON value: as it was decoded, when it was, else as it is written.
581    pub(crate) fn json_value(&self) -> Value {
582        self.raw.clone().unwrap_or_else(|| self.to_json())
583    }
584}
585
586/// A number value (as the reader's values are), for building documents and parameters.
587pub fn number(f: f64) -> Value {
588    num(f)
589}