instruction-md 0.2.0

Read, check, resolve and verify instruction.md documents (the specification's first edition, instruction/1): the reader, the agent text, composition and signature verification
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! The authored tree (§2) — `{format, metadata, body}`, the shape `instruction.schema.json` validates — and the
//! reader's sidecar: diagnostics (§18), identities and parameters, which the tree itself does not carry.

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use serde_json::{Map, Value};

use crate::js::num;

/// The authored tree's format.
pub const TREE_FORMAT: &str = "instruction/1";

/// A JSON object: a directive's attributes, a metadata region, a structured body's mapping.
pub type Object = Map<String, Value>;

/// A directive's attributes: strings, numbers, booleans and lists.
pub type Attrs = Object;

/// The order a loaded value's mappings were written in, which a JSON map does not keep: the top mapping's keys under
/// "", and those of each mapping it holds under the key that holds it.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct KeyOrder(pub(crate) HashMap<String, Vec<String>>);

impl KeyOrder {
    /// The mapping's keys in the order written (any the order does not know, sorted, after).
    pub(crate) fn keys(&self, path: &str, m: &Object) -> Vec<String> {
        let mut out: Vec<String> = Vec::with_capacity(m.len());
        if let Some(written) = self.0.get(path) {
            for k in written {
                if m.contains_key(k) && !out.contains(k) {
                    out.push(k.clone());
                }
            }
        }
        for k in m.keys() {
            if !out.contains(k) {
                out.push(k.clone());
            }
        }
        out
    }
}

/// An authored (or resolved) tree.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Document {
    pub format: String,
    /// The document's URI, when it has one.
    pub uri: String,
    pub metadata: Metadata,
    pub body: Vec<Node>,
    /// the tree as decoded, when it was: what its digest covers
    pub(crate) raw: Option<Value>,
}

/// The document's front matter and backmatter, each a YAML mapping.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Metadata {
    pub front: Object,
    pub back: Object,
    pub(crate) front_order: KeyOrder,
}

/// What a node is: a Markdown segment or a directive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NodeType {
    Markdown,
    Directive,
}

impl NodeType {
    pub fn as_str(self) -> &'static str {
        match self {
            NodeType::Markdown => "markdown",
            NodeType::Directive => "directive",
        }
    }
}

/// A directive's form (§5): `:::kind … :::`, `::kind{…}`, a keyword line (`MUST: …`) or an alert (`> [!TIP]`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Form {
    Container,
    Leaf,
    Keyword,
    Alert,
}

impl Form {
    pub fn as_str(self) -> &'static str {
        match self {
            Form::Container => "container",
            Form::Leaf => "leaf",
            Form::Keyword => "keyword",
            Form::Alert => "alert",
        }
    }

    pub fn parse(s: &str) -> Option<Form> {
        Some(match s {
            "container" => Form::Container,
            "leaf" => Form::Leaf,
            "keyword" => Form::Keyword,
            "alert" => Form::Alert,
            _ => return None,
        })
    }
}

impl fmt::Display for Form {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A node of the tree: a Markdown segment (its `source`) or a directive.
#[derive(Clone, Debug, PartialEq)]
pub struct Node {
    pub node_type: NodeType,
    /// A directive's kind (`must`, `policy`, `charts:metric`); empty for Markdown.
    pub kind: String,
    /// A directive's form; `None` for Markdown.
    pub form: Option<Form>,
    pub attrs: Attrs,
    /// A Markdown-bodied directive's parsed body; a literal body (an example's, a verbatim one) is one Markdown node.
    /// `None`: the directive has no such body (a leaf, a structured body); empty: an empty one.
    pub children: Option<Vec<Node>>,
    /// A structured or literal-format body (YAML, JSON, CSV, text, HTML, code).
    pub value: Option<StructuredValue>,
    /// A Markdown node's text, or the full source of a directive this reader does not interpret.
    pub source: String,
    pub range: Option<Range>,
    /// A resolved node's composition path (§2, §14.1): `root`, `root/personal`.
    pub instance: String,

    pub(crate) prose: bool,
    pub(crate) keyword: Option<String>,
    pub(crate) reason: Option<Range>,
    /// a container's body in the source it was read from
    pub(crate) body: Option<Span>,
}

/// A span of a source the reader read: the source is shared, not copied, by every node that has one.
#[derive(Clone)]
pub(crate) struct Span {
    pub(crate) text: Arc<str>,
    pub(crate) start: usize,
    pub(crate) end: usize,
}

impl Span {
    pub(crate) fn as_str(&self) -> &str {
        self.text.get(self.start..self.end).unwrap_or("")
    }
}

impl fmt::Debug for Span {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl PartialEq for Span {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}

impl Node {
    /// A Markdown node.
    pub fn markdown(source: impl Into<String>) -> Node {
        Node {
            node_type: NodeType::Markdown,
            kind: String::new(),
            form: None,
            attrs: Attrs::new(),
            children: None,
            value: None,
            source: source.into(),
            range: None,
            instance: String::new(),
            prose: false,
            keyword: None,
            reason: None,
            body: None,
        }
    }

    /// A directive node.
    pub fn directive(kind: impl Into<String>, form: Form, attrs: Attrs) -> Node {
        Node { node_type: NodeType::Directive, kind: kind.into(), form: Some(form), attrs, ..Node::markdown("") }
    }

    pub fn is_markdown(&self) -> bool {
        self.node_type == NodeType::Markdown
    }

    pub fn is_directive(&self) -> bool {
        self.node_type == NodeType::Directive
    }

    /// The keyword a keyword rule or an alert was written with (`ALWAYS`, `AVOID`, `MUST NOT`); the tree keeps its
    /// normalized kind. Set by the reader.
    pub fn keyword(&self) -> Option<&str> {
        self.keyword.as_deref()
    }

    /// The lines of a rule's `BECAUSE:` reason, which the tree keeps as the rule's `because`. Set by the reader.
    pub fn reason_range(&self) -> Option<Range> {
        self.reason
    }

    /// Is this Markdown node parsed prose (not an example's or a verbatim body's quoted text)? Set by the reader.
    pub fn is_prose(&self) -> bool {
        self.prose
    }

    /// The exact source text of a container's body, as the reader read it: every line between the opening fence's
    /// line and the closing fence's (each with its line ending, comments and all; empty for an empty body), or to the
    /// end of the source when the container is not closed. `None` for any other node, and for a node not read from
    /// source (built, or decoded from a tree's JSON).
    ///
    /// ```
    /// use instruction_md::{read, ReadOptions};
    ///
    /// let r = read(":::skill{id=plan}\nPlan the day.\n<!-- kept -->\n:::\n", &ReadOptions::default());
    /// assert_eq!(r.document.body[0].body_source(), Some("Plan the day.\n<!-- kept -->\n"));
    /// ```
    pub fn body_source(&self) -> Option<&str> {
        self.body.as_ref().map(Span::as_str)
    }

    /// The node's children, or none.
    pub fn children(&self) -> &[Node] {
        self.children.as_deref().unwrap_or(&[])
    }

    /// A string attribute.
    pub fn attr_str(&self, key: &str) -> Option<&str> {
        self.attrs.get(key).and_then(Value::as_str)
    }

    /// The node as instruction.schema.json has it.
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("type".into(), self.node_type.as_str().into());
        if self.is_markdown() {
            m.insert("source".into(), self.source.clone().into());
        } else {
            m.insert("kind".into(), self.kind.clone().into());
            m.insert("form".into(), self.form.map_or("container", Form::as_str).into());
            m.insert("attrs".into(), Value::Object(self.attrs.clone()));
        }
        if let Some(r) = self.range {
            m.insert("range".into(), r.to_json());
        }
        if self.is_directive() {
            if let Some(children) = &self.children {
                m.insert("children".into(), Value::Array(children.iter().map(Node::to_json).collect()));
            }
            if let Some(v) = &self.value {
                m.insert("value".into(), v.to_json());
            }
            if !self.source.is_empty() {
                m.insert("source".into(), self.source.clone().into());
            }
        }
        if !self.instance.is_empty() {
            m.insert("instance".into(), self.instance.clone().into());
        }
        Value::Object(m)
    }

    /// Reads a node of a tree.
    pub fn from_json(v: &Value) -> Result<Node, String> {
        let o = v.as_object().ok_or("a node is an object")?;
        let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or("").to_string();
        let node_type = match o.get("type").and_then(Value::as_str) {
            Some("markdown") => NodeType::Markdown,
            Some("directive") => NodeType::Directive,
            _ => return Err("a node's type is markdown or directive".into()),
        };
        let form = match o.get("form").and_then(Value::as_str) {
            Some(f) => Some(Form::parse(f).ok_or_else(|| format!("unknown form {f}"))?),
            None if node_type == NodeType::Directive => Some(Form::Container),
            None => None,
        };
        let children = match o.get("children") {
            Some(Value::Array(list)) => Some(list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?),
            _ => None,
        };
        let value = match o.get("value") {
            Some(v @ Value::Object(_)) => Some(StructuredValue::from_json(v)),
            _ => None,
        };
        Ok(Node {
            node_type,
            kind: s("kind"),
            form: if node_type == NodeType::Directive { form } else { None },
            attrs: o.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(),
            children,
            value,
            source: s("source"),
            range: o.get("range").and_then(Range::from_json),
            instance: s("instance"),
            prose: false,
            keyword: None,
            reason: None,
            body: None,
        })
    }
}

/// A structured body: its format, its text and, when it parsed, its data.
#[derive(Clone, Debug, PartialEq)]
pub struct StructuredValue {
    pub format: String,
    pub source: String,
    /// The parsed data; `None` when the body did not parse (a parsed `null` is `Some(Value::Null)`).
    pub data: Option<Value>,
    pub(crate) order: KeyOrder,
}

impl StructuredValue {
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("format".into(), self.format.clone().into());
        m.insert("source".into(), self.source.clone().into());
        if let Some(d) = &self.data {
            m.insert("data".into(), d.clone());
        }
        Value::Object(m)
    }

    pub fn from_json(v: &Value) -> StructuredValue {
        let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
        StructuredValue { format: s("format"), source: s("source"), data: v.get("data").cloned(), order: KeyOrder::default() }
    }
}

/// A span of source lines, 1-based and inclusive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Range {
    pub start: u32,
    pub end: u32,
}

impl Range {
    pub fn new(start: u32, end: u32) -> Range {
        Range { start, end }
    }

    pub fn line(n: u32) -> Range {
        Range { start: n, end: n }
    }

    pub fn to_json(self) -> Value {
        let mut m = Map::new();
        m.insert("start".into(), self.start.into());
        m.insert("end".into(), self.end.into());
        Value::Object(m)
    }

    fn from_json(v: &Value) -> Option<Range> {
        let n = |k: &str| v.get(k).and_then(Value::as_f64).map(|f| f.clamp(0.0, u32::MAX as f64) as u32);
        Some(Range { start: n("start")?, end: n("end")? })
    }
}

/// A diagnostic's severity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Severity {
    Error,
    Warning,
    Info,
}

impl Severity {
    pub fn as_str(self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Info => "info",
        }
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A problem found in a source (§18): a stable code (`unclosed-directive`, `invalid-attributes`, …), its severity, a
/// message for a person, and where.
#[derive(Clone, Debug, PartialEq)]
pub struct Diagnostic {
    pub code: &'static str,
    pub severity: Severity,
    pub message: String,
    /// The source it was found in, when that is not the document itself (a base or an include).
    pub uri: String,
    pub range: Option<Range>,
    pub target: String,
    pub remedy: String,
}

impl Diagnostic {
    pub(crate) fn new(code: &'static str, severity: Severity, message: impl Into<String>, line: u32) -> Diagnostic {
        Diagnostic {
            code,
            severity,
            message: message.into(),
            uri: String::new(),
            range: (line > 0).then(|| Range::line(line)),
            target: String::new(),
            remedy: String::new(),
        }
    }

    /// The line it starts on, when it has one.
    pub fn line(&self) -> Option<u32> {
        self.range.map(|r| r.start)
    }

    pub fn is_error(&self) -> bool {
        self.severity == Severity::Error
    }

    /// The diagnostic as JSON (§18).
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("code".into(), self.code.into());
        m.insert("severity".into(), self.severity.as_str().into());
        m.insert("message".into(), self.message.clone().into());
        if !self.uri.is_empty() {
            m.insert("uri".into(), self.uri.clone().into());
        }
        if let Some(r) = self.range {
            m.insert("range".into(), r.to_json());
        }
        if !self.target.is_empty() {
            m.insert("target".into(), self.target.clone().into());
        }
        if !self.remedy.is_empty() {
            m.insert("remedy".into(), self.remedy.clone().into());
        }
        Value::Object(m)
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.uri.is_empty() {
            write!(f, "{}:", self.uri)?;
        }
        if let Some(r) = self.range {
            write!(f, "{}: ", r.start)?;
        }
        write!(f, "{} {}: {}", self.severity, self.code, self.message)
    }
}

/// An explicit identity (§5.3): a directive's or keyword's id, or a heading's `{#id}`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Identity {
    pub id: String,
    pub kind: String,
    pub line: u32,
}

impl Identity {
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("id".into(), self.id.clone().into());
        m.insert("kind".into(), self.kind.clone().into());
        m.insert("line".into(), self.line.into());
        Value::Object(m)
    }
}

/// A declared parameter (§12), from the front matter or a `::param` leaf.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Parameter {
    pub name: String,
    pub param_type: String,
    pub required: bool,
    pub values: Option<Vec<String>>,
    /// The default and the example, when there is one (a null one is a value).
    pub default: Option<Value>,
    pub example: Option<Value>,
    pub description: Option<String>,
    pub source: Option<String>,
    /// Where it was declared: 0 for the front matter, else its param leaf's line.
    pub line: u32,
}

impl Parameter {
    /// The parameter as the reference writes it: `declaredAt` is "front-matter" or the leaf's line.
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("name".into(), self.name.clone().into());
        m.insert("type".into(), self.param_type.clone().into());
        m.insert("required".into(), self.required.into());
        if let Some(v) = &self.values {
            m.insert("values".into(), v.clone().into());
        }
        m.insert("declaredAt".into(), if self.line == 0 { "front-matter".into() } else { self.line.into() });
        if let Some(v) = &self.default {
            m.insert("default".into(), v.clone());
        }
        if let Some(v) = &self.example {
            m.insert("example".into(), v.clone());
        }
        if let Some(v) = &self.description {
            m.insert("description".into(), v.clone().into());
        }
        if let Some(v) = &self.source {
            m.insert("source".into(), v.clone().into());
        }
        Value::Object(m)
    }
}

impl Document {
    /// A tree of the body, with empty metadata.
    pub fn new(body: Vec<Node>) -> Document {
        Document { format: TREE_FORMAT.into(), body, ..Document::default() }
    }

    /// The tree as instruction.schema.json has it.
    pub fn to_json(&self) -> Value {
        let mut m = Map::new();
        m.insert("format".into(), self.format.clone().into());
        if !self.uri.is_empty() {
            m.insert("uri".into(), self.uri.clone().into());
        }
        let mut meta = Map::new();
        meta.insert("front".into(), Value::Object(self.metadata.front.clone()));
        meta.insert("back".into(), Value::Object(self.metadata.back.clone()));
        m.insert("metadata".into(), Value::Object(meta));
        m.insert("body".into(), Value::Array(self.body.iter().map(Node::to_json).collect()));
        Value::Object(m)
    }

    /// Reads a tree from its JSON (a missing metadata region is empty).
    pub fn from_json(v: &Value) -> Result<Document, String> {
        let o = v.as_object().ok_or("a tree is an object")?;
        let metadata = o.get("metadata");
        let region = |k: &str| metadata.and_then(|m| m.get(k)).and_then(Value::as_object).cloned().unwrap_or_default();
        let front = region("front");
        let mut order = KeyOrder::default();
        // (a JSON map keeps no order: the mappings' keys as written are not known here, so they read sorted)
        order.0.insert(String::new(), front.keys().cloned().collect());
        let body = match o.get("body") {
            Some(Value::Array(list)) => list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?,
            _ => Vec::new(),
        };
        Ok(Document {
            format: o.get("format").and_then(Value::as_str).unwrap_or("").to_string(),
            uri: o.get("uri").and_then(Value::as_str).unwrap_or("").to_string(),
            metadata: Metadata { front, back: region("back"), front_order: order },
            body,
            raw: Some(v.clone()),
        })
    }

    /// The tree as a JSON value: as it was decoded, when it was, else as it is written.
    pub(crate) fn json_value(&self) -> Value {
        self.raw.clone().unwrap_or_else(|| self.to_json())
    }
}

/// A number value (as the reader's values are), for building documents and parameters.
pub fn number(f: f64) -> Value {
    num(f)
}