Skip to main content

instruction_md/
check.rs

1//! The inline checks (§11.1, §12), over the prose the reader found: an inline kind this specification or the
2//! document's extensions do not define, a missing required attribute or label, a typed reference to an id the
3//! document does not have or to one of another kind, a citation of a source the backmatter does not record, an
4//! undeclared parameter, a footnote without its definition. [`check`] is the reader's diagnostics with these, in
5//! source order — what an editor shows and what a renderer reports.
6
7use serde_json::Value;
8
9use crate::attributes::parse_attributes;
10use crate::inline::{TokenType, inline_tokens};
11use crate::js::{js_trim, truthy};
12use crate::read::{ReadOptions, Reading, read, sort_diagnostics};
13use crate::registry::{self, inline_attr_spec, inline_required, registry, typed_reference};
14use crate::types::{Diagnostic, Severity};
15
16/// Where a typed reference's target is.
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum Target {
19    /// In this document: the id, the kind of what has it, and whether that is the kind the reference says (any, for
20    /// ref; any resource kind, for resource).
21    Local { id: String, kind: String, matches: bool },
22    /// Named as #id, and nothing in this document has it.
23    Missing { id: String },
24    /// Elsewhere: a named reference's URI, or the reference itself.
25    External { uri: String },
26}
27
28/// Resolves a typed reference's ref against the document (§11.1): #id, an included #alias/id, a named reference, a
29/// URI.
30pub fn resolve_target(r: &Reading, kind: &str, reference: &str) -> Target {
31    if let Some(id) = reference.strip_prefix('#')
32        && !reference.contains('/')
33    {
34        let Some(found) = r.identity(id) else {
35            return Target::Missing { id: id.to_string() };
36        };
37        let matches = kind == "ref"
38            || found.kind == kind
39            || kind == "resource" && registry::kind(&found.kind).is_some_and(|k| k.family == "resource");
40        return Target::Local { id: id.to_string(), kind: found.kind.clone(), matches };
41    }
42    let named =
43        r.document.metadata.front.get("references").and_then(|refs| refs.get(reference)).and_then(|n| n.get("uri")).and_then(Value::as_str);
44    Target::External { uri: named.unwrap_or(reference).to_string() }
45}
46
47/// A document's diagnostics: the reader's and the inline checks', in source order.
48pub fn check(text: &str, opts: &ReadOptions) -> Vec<Diagnostic> {
49    check_reading(&read(text, opts))
50}
51
52/// [`check`] of a document already read.
53pub fn check_reading(r: &Reading) -> Vec<Diagnostic> {
54    let mut out = r.diagnostics.clone();
55    out.extend(inline_diagnostics(r));
56    out.extend(workflows_diagnostics(r));
57    sort_diagnostics(&mut out, false);
58    out
59}
60
61/// Each `:::workflow{dialect="instruction/workflow"}` body's diagnostics ([`crate::workflow`]), in document order:
62/// its parsed YAML or JSON (the reader reports a body that doesn't parse or isn't a mapping), placed on the body's
63/// lines. Another dialect is its own.
64pub fn workflows_diagnostics(r: &Reading) -> Vec<Diagnostic> {
65    let mut out = Vec::new();
66    let extensions = r.document.metadata.front.get("extensions").and_then(Value::as_object);
67    crate::objects::walk(&r.document.body, &mut |n, _| {
68        if n.kind == "workflow"
69            && crate::js::is_str(n.attrs.get("dialect"), crate::workflow::WORKFLOW_DIALECT)
70            && let (Some(data), Some(range)) = (n.value.as_ref().and_then(|v| v.data.as_ref()), n.range)
71        {
72            // the body's lines: between the opener and the closing fence (which an unclosed container lacks)
73            let (start, end) = (range.start as usize, range.end as usize);
74            let closed = end > start && r.lines.get(end - 1).is_some_and(|l| is_closing_fence(l));
75            let last = if closed { end - 1 } else { end };
76            let lines: Vec<(u32, &str)> = r
77                .lines
78                .get(start..last.min(r.lines.len()))
79                .unwrap_or(&[])
80                .iter()
81                .enumerate()
82                .map(|(i, t)| ((start + 1 + i) as u32, t.as_str()))
83                .collect();
84            let at = lines.first().map_or(range.start, |l| l.0);
85            out.extend(crate::workflow::check(data, &lines, at, extensions));
86        }
87        true
88    });
89    out
90}
91
92/// `^:{3,}[ \t]*$`
93fn is_closing_fence(l: &str) -> bool {
94    let rest = l.trim_start_matches(':');
95    l.len() - rest.len() >= 3 && rest.bytes().all(|b| b == b' ' || b == b'\t')
96}
97
98/// The inline checks' diagnostics, prose node by prose node.
99pub fn inline_diagnostics(r: &Reading) -> Vec<Diagnostic> {
100    let mut out = Vec::new();
101    let front = &r.document.metadata.front;
102    let extensions = front.get("extensions").and_then(Value::as_object);
103    let sources: Vec<&str> = match r.document.metadata.back.get("sources") {
104        Some(Value::Array(list)) => list.iter().filter_map(|s| s.get("id").and_then(Value::as_str)).collect(),
105        _ => Vec::new(),
106    };
107    for node in &r.prose_order {
108        let breaks: Vec<usize> = node.source.match_indices('\n').map(|(i, _)| i).collect();
109        for t in inline_tokens(&node.source) {
110            // the node's first line plus the line breaks before the token
111            let at = node.range.map_or(1, |rg| rg.start) + breaks.partition_point(|&b| b < t.start) as u32;
112            let mut diag = |code: &'static str, severity: Severity, message: String| out.push(Diagnostic::new(code, severity, message, at));
113            match t.token_type {
114                TokenType::Param => {
115                    if r.parameter(&t.name).is_none() {
116                        diag(
117                            "parameter-optional",
118                            Severity::Warning,
119                            format!("${{{}}} is not a declared parameter, so it stays as written", t.name),
120                        );
121                    }
122                    continue;
123                }
124                TokenType::Footnote => {
125                    if !r.footnotes.contains_key(&t.label) {
126                        diag(
127                            "footnote-missing",
128                            Severity::Warning,
129                            format!("the footnote [^{}] has no definition, so it stays as text", t.label),
130                        );
131                    }
132                    continue;
133                }
134                TokenType::Directive => {}
135                _ => continue,
136            }
137            let where_ = format!(":{}[…]", t.kind);
138            if let Some((alias, _)) = t.kind.split_once(':') {
139                if !truthy(extensions.and_then(|e| e.get(alias))) {
140                    diag(
141                        "extension-unavailable",
142                        Severity::Error,
143                        format!("{where_}: the extension alias \"{alias}\" is not declared in the front matter's extensions"),
144                    );
145                }
146                continue;
147            }
148            if !registry().inline.contains_key(&t.kind) {
149                diag(
150                    "unknown-kind",
151                    Severity::Error,
152                    format!("{where_} is not an inline kind of this specification; it is kept as written"),
153                );
154                continue;
155            }
156            let mut attrs = crate::types::Attrs::new();
157            if let Some(list) = &t.attributes {
158                let kind = t.kind.clone();
159                let spec_of = move |k: &str| inline_attr_spec(&kind, k);
160                let (parsed, problems) = parse_attributes(list, &spec_of, true);
161                attrs = parsed;
162                for p in problems {
163                    diag("invalid-attributes", Severity::Error, format!("{where_}: {p}"));
164                }
165            }
166            if let Some(need) = inline_required(&t.kind) {
167                match attrs.get(need) {
168                    None => diag("invalid-attributes", Severity::Error, format!("{where_} needs {need}=…")),
169                    Some(Value::String(s)) if s.is_empty() => {
170                        diag("invalid-attributes", Severity::Error, format!("{where_} needs {need}=…"))
171                    }
172                    _ => {}
173                }
174            }
175            if js_trim(&t.label).is_empty() {
176                diag("invalid-attributes", Severity::Error, format!("{where_}: its label is required, the text a reader sees"));
177            }
178            let reference = match attrs.get("ref") {
179                Some(Value::String(s)) if !s.is_empty() => s.clone(),
180                _ => continue,
181            };
182            if t.kind == "cite" {
183                if !sources.contains(&reference.as_str()) {
184                    diag("reference-optional", Severity::Warning, format!("{where_}: the backmatter's sources record no \"{reference}\""));
185                }
186                continue;
187            }
188            if !typed_reference(&t.kind) && t.kind != "ref" {
189                continue;
190            }
191            match resolve_target(r, &t.kind, &reference) {
192                Target::Missing { id } => {
193                    diag("reference-optional", Severity::Warning, format!("{where_}: nothing in this document has the id \"{id}\""))
194                }
195                Target::Local { id, kind, matches: false } => {
196                    diag("reference-kind", Severity::Error, format!("{where_} names #{id}, which is a {kind}, not a {}", t.kind))
197                }
198                _ => {}
199            }
200        }
201    }
202    out
203}