Skip to main content

fig_schema/
check.rs

1//! A whole-document check: every node of a parsed [`Value`] tree against the
2//! rule that governs it — [`Schema::check`] and the [`Verdict`]s it returns.
3//!
4//! An embedder that validates one edit at a time ([`FieldRule::validate`]
5//! per keystroke) gets, from the same schema, the answer to "is this document
6//! valid" — which nothing in the toolchain gives today: `fig check` says
7//! whether a file parses, and this says whether what it parsed is what the
8//! schema expects.
9//!
10//! The three rules of the walk that are choices rather than consequences are
11//! on [`Schema::check`] itself, since this module is private and its docs do
12//! not reach an embedder.
13
14use std::fmt;
15
16use fig::Value;
17
18use crate::field::{FieldRule, FieldType, Schema};
19use crate::path::{Seg, render_path};
20use crate::vocab::{Validate, Validation};
21
22/// One thing a check has to say about a document: which node, and what is
23/// wrong with it — or that it could not be checked. A clean document has none.
24///
25/// `#[non_exhaustive]`: a verdict gains context (a span, once fig exposes one)
26/// the same way an [`Issue`](crate::Issue) does. Read the fields; build one
27/// only through [`Schema::check`].
28#[derive(Debug, Clone, PartialEq)]
29#[non_exhaustive]
30pub struct Verdict {
31    /// The node, as a concrete path. Kept as segments rather than rendered so
32    /// an editor can find the row again; [`Verdict::at`] is the text.
33    pub path: Vec<Seg>,
34    /// What was found.
35    pub kind: VerdictKind,
36}
37
38/// The kind of a [`Verdict`].
39///
40/// `#[non_exhaustive]`: a check learns new things to say as the crate grows,
41/// so a `match` needs a `_` arm.
42#[derive(Debug, Clone, PartialEq)]
43#[non_exhaustive]
44pub enum VerdictKind {
45    /// The node does not have the type its rule declares — by
46    /// [`FieldType::admits`], so a `float` field holding an integer is not
47    /// one of these.
48    TypeMismatch {
49        /// The rule's [`FieldRule::ty`].
50        expected: FieldType,
51        /// [`FieldType::of`] the node.
52        found: FieldType,
53    },
54    /// The rule's constraint had something to say. Never [`Validation::Ok`],
55    /// which is not a verdict: a warning, a rejection, or a rejection carrying
56    /// [`IssueKind::Unchecked`](crate::IssueKind::Unchecked), which
57    /// [`Verdict::is_unchecked`] singles out.
58    Constraint(Validation),
59}
60
61impl Verdict {
62    /// The node as a dotted path — `audience[1]`, `meta.author`, and the empty
63    /// string for the root. Spelled by [`render_path`], so it agrees with a
64    /// [`Finding`](crate::Finding) and with fig's own `Warning`.
65    pub fn at(&self) -> String {
66        render_path(&self.path)
67    }
68
69    /// Whether this says the document is *wrong*: a type mismatch, or a
70    /// rejection that is not merely [unchecked](Verdict::is_unchecked). A
71    /// warning is neither — it changes only what a reader sees.
72    pub fn is_error(&self) -> bool {
73        match &self.kind {
74            VerdictKind::TypeMismatch { .. } => true,
75            VerdictKind::Constraint(validation) => validation.is_reject() && !self.is_unchecked(),
76        }
77    }
78
79    /// Whether this says the node was *not checked* — its constraint is of a
80    /// kind the validator does not know, so it failed closed. Not an error
81    /// about the document, and not a warning either: a reader reports it
82    /// under its own heading, and a run with nothing else amiss is neither
83    /// valid nor invalid. See [`IssueKind::Unchecked`](crate::IssueKind::Unchecked).
84    pub fn is_unchecked(&self) -> bool {
85        match &self.kind {
86            VerdictKind::Constraint(validation) => {
87                validation.issue().is_some_and(|issue| issue.is_unchecked())
88            }
89            VerdictKind::TypeMismatch { .. } => false,
90        }
91    }
92}
93
94impl fmt::Display for Verdict {
95    /// The English default, without the path — a reader puts that where its
96    /// report wants it.
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match &self.kind {
99            VerdictKind::TypeMismatch { expected, found } => {
100                write!(f, "expected {expected}, found {found}")
101            }
102            VerdictKind::Constraint(validation) => match validation.issue() {
103                Some(issue) => issue.fmt(f),
104                // Never built — `Ok` is not a verdict — but `Validation` is
105                // exhaustive and the arm has to say something.
106                None => f.write_str("ok"),
107            },
108        }
109    }
110}
111
112impl<C: Validate> Schema<C> {
113    /// Check a whole parsed document against this schema: every node, against
114    /// the rule [`Schema::rule_for`] names for it, twice — its shape against
115    /// the rule's [`ty`](FieldRule::ty), then its value against the rule's
116    /// constraint. What comes back is only what is wrong or unchecked, in
117    /// post-order, so a clean document yields nothing.
118    ///
119    /// Three rules of the walk are choices rather than consequences, and each
120    /// could have gone the other way:
121    ///
122    /// - **A node no rule governs is not a verdict.** A schema governs what it
123    ///   names. A check that fired on a document's own `title`/`author` —
124    ///   keys the schema never mentions — is one people stop running.
125    /// - **The same issue about the same value is reported once, at the
126    ///   deepest path.** [`validate_enum`](crate::validate_enum) validates a
127    ///   sequence element-wise, so a rule at `audience` and a rule at
128    ///   `audience[]` — an embedder emits both, so a field is governed whether
129    ///   written as a scalar or a list — would otherwise report one
130    ///   misspelling twice. The walk is post-order, and a container's issue is
131    ///   dropped when a descendant already reported an equal one.
132    /// - **An empty document is valid.** The model has no notion of a
133    ///   *required* field: a [`FieldRule`] says what a value must be if there
134    ///   is one, and nothing says there must be one. So a check never reports
135    ///   a missing field, and a document with nothing in it has nothing wrong
136    ///   with it.
137    ///
138    /// One limit besides: a mapping entry whose key is not text has no [`Seg`]
139    /// to address it, so no rule can govern it and it is not walked.
140    ///
141    /// ```
142    /// use fig::Value;
143    /// use fig_schema::{FieldRule, FieldType, PathPat, Schema, Term, Validate, Validation, validate_enum};
144    ///
145    /// struct Vocabulary(Vec<Term>);
146    /// impl Validate for Vocabulary {
147    ///     fn validate(&self, value: &Value) -> Validation {
148    ///         validate_enum(&self.0, true, value)
149    ///     }
150    /// }
151    ///
152    /// let schema = Schema::new(vec![
153    ///     FieldRule::new(PathPat::each_item_of("audience"))
154    ///         .ty(FieldType::Str)
155    ///         .constraint(Vocabulary(vec![Term::value("public"), Term::value("family")])),
156    ///     FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
157    /// ]);
158    ///
159    /// let document = fig::Document::parse(
160    ///     b"audience: [public, famly]\ncount: three\ntitle: untouched\n",
161    ///     fig_yaml::format().unwrap(),
162    /// ).unwrap();
163    /// let verdicts = schema.check(&document.to_value().unwrap());
164    ///
165    /// let report: Vec<String> = verdicts.iter().map(|v| format!("{}: {v}", v.at())).collect();
166    /// assert_eq!(report, [
167    ///     "audience[1]: “famly” is not a known value — did you mean “family”?",
168    ///     "count: expected int, found str",
169    /// ]);
170    /// assert!(verdicts.iter().all(|v| v.is_error()));
171    /// ```
172    pub fn check(&self, document: &Value) -> Vec<Verdict> {
173        let mut verdicts = Vec::new();
174        let mut path = Vec::new();
175        self.walk(document, &mut path, &mut verdicts);
176        verdicts
177    }
178
179    /// One node, post-order: the children first, so that when this node's own
180    /// constraint speaks, what its descendants said is already in `verdicts`
181    /// and a repeat can be dropped.
182    fn walk(&self, node: &Value, path: &mut Vec<Seg>, verdicts: &mut Vec<Verdict>) {
183        let before = verdicts.len();
184        match node {
185            Value::Seq(items) => {
186                for (i, item) in items.iter().enumerate() {
187                    path.push(Seg::Index(i));
188                    self.walk(item, path, verdicts);
189                    path.pop();
190                }
191            }
192            Value::Map(entries) => {
193                for (key, value) in entries {
194                    let Some(key) = key.as_str() else { continue };
195                    path.push(Seg::Key(key.to_owned()));
196                    self.walk(value, path, verdicts);
197                    path.pop();
198                }
199            }
200            _ => {}
201        }
202
203        let Some(rule) = self.rule_for(path) else {
204            return;
205        };
206        let descendants = &verdicts[before..];
207        let mut own = judge(rule, node, descendants);
208        for kind in own.drain(..) {
209            verdicts.push(Verdict {
210                path: path.clone(),
211                kind,
212            });
213        }
214    }
215}
216
217/// What `rule` says about `node`: a type mismatch if its shape is wrong, and
218/// the constraint's answer if that is not `Ok` — each unless the same thing is
219/// already among the `descendants`' verdicts, in which case this is the
220/// container-level echo of an item-wise check and is dropped.
221///
222/// For a constraint that is an *equal issue*: [`validate_enum`](crate::validate_enum)
223/// carries an item's issue up to the list. For a type it is *any* mismatch
224/// below: a type admits a list whose every item fits, so a list that does not
225/// fit is one with an item that does not, and that item has already said so
226/// at its own path.
227fn judge<C: Validate>(
228    rule: &FieldRule<C>,
229    node: &Value,
230    descendants: &[Verdict],
231) -> Vec<VerdictKind> {
232    let mut kinds = Vec::new();
233    if let Some(expected) = rule.ty {
234        let item_already_said = descendants
235            .iter()
236            .any(|v| matches!(v.kind, VerdictKind::TypeMismatch { .. }));
237        if !expected.admits(node) && !item_already_said {
238            kinds.push(VerdictKind::TypeMismatch {
239                expected,
240                found: FieldType::of(node),
241            });
242        }
243    }
244    let validation = rule.validate(node);
245    let Some(issue) = validation.issue() else {
246        return kinds;
247    };
248    let already_said = descendants.iter().any(|v| match &v.kind {
249        VerdictKind::Constraint(v) => v.issue() == Some(issue),
250        VerdictKind::TypeMismatch { .. } => false,
251    });
252    if !already_said {
253        kinds.push(VerdictKind::Constraint(validation));
254    }
255    kinds
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::path::PathPat;
262    use crate::vocab::{Issue, IssueKind, Term, validate_enum};
263
264    /// The embedder's constraint type, with the two kinds a check tells apart:
265    /// one it can answer and one it cannot.
266    #[derive(Debug, Clone)]
267    enum Constraint {
268        Vocabulary(Vec<Term>),
269        Unknown(&'static str),
270    }
271
272    impl Validate for Constraint {
273        fn validate(&self, value: &Value) -> Validation {
274            match self {
275                Constraint::Vocabulary(terms) => validate_enum(terms, true, value),
276                Constraint::Unknown(kind) => Validation::Reject(Issue::unchecked("", *kind)),
277            }
278        }
279    }
280
281    fn audience() -> Constraint {
282        Constraint::Vocabulary(vec![
283            Term::value("public"),
284            Term::value("family"),
285            Term::value("archived").retired(true),
286        ])
287    }
288
289    fn parse(yaml: &str) -> Value {
290        fig::Document::parse(yaml.as_bytes(), fig_yaml::format().unwrap())
291            .unwrap()
292            .to_value()
293            .unwrap()
294    }
295
296    fn report(schema: &Schema<Constraint>, yaml: &str) -> Vec<String> {
297        schema
298            .check(&parse(yaml))
299            .iter()
300            .map(|v| format!("{}: {v}", v.at()))
301            .collect()
302    }
303
304    #[test]
305    fn a_clean_document_has_nothing_said_about_it() {
306        let schema = Schema::new(vec![
307            FieldRule::new(PathPat::each_item_of("audience"))
308                .ty(FieldType::Str)
309                .constraint(audience()),
310            FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
311        ]);
312        assert!(report(&schema, "audience: [public, family]\ncount: 3\n").is_empty());
313    }
314
315    #[test]
316    fn a_node_no_rule_governs_is_not_a_verdict() {
317        let schema = Schema::new(vec![
318            FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
319        ]);
320        // `title` and `meta` are the document's own business.
321        assert!(report(&schema, "title: x\nmeta: {author: [1, 2]}\ncount: 1\n").is_empty());
322    }
323
324    #[test]
325    fn an_empty_document_is_valid_because_nothing_is_required() {
326        let schema = Schema::new(vec![
327            FieldRule::new(PathPat::key("count"))
328                .ty(FieldType::Int)
329                .constraint(audience()),
330        ]);
331        assert!(schema.check(&Value::Map(vec![])).is_empty());
332        assert!(schema.check(&Value::Null).is_empty());
333    }
334
335    #[test]
336    fn a_shape_that_is_not_the_rules_type_is_a_mismatch() {
337        let schema = Schema::new(vec![
338            FieldRule::new(PathPat::key("count"))
339                .ty(FieldType::Int)
340                .constraint_opt(None),
341            FieldRule::new(PathPat::key("ratio")).ty(FieldType::Float),
342            FieldRule::new(PathPat::key("tags")).ty(FieldType::Seq),
343        ]);
344        assert_eq!(
345            report(&schema, "count: three\nratio: 2\ntags: one\n"),
346            [
347                "count: expected int, found str",
348                "tags: expected seq, found str"
349            ]
350        );
351        let verdicts = schema.check(&parse("count: three\n"));
352        assert_eq!(
353            verdicts[0].kind,
354            VerdictKind::TypeMismatch {
355                expected: FieldType::Int,
356                found: FieldType::Str,
357            }
358        );
359        assert!(verdicts[0].is_error());
360        assert!(!verdicts[0].is_unchecked());
361    }
362
363    #[test]
364    fn a_rejection_is_an_error_and_a_warning_is_not() {
365        let schema = Schema::new(vec![
366            FieldRule::new(PathPat::each_item_of("audience"))
367                .ty(FieldType::Str)
368                .constraint(audience()),
369        ]);
370        let verdicts = schema.check(&parse("audience: [famly, archived]\n"));
371        assert_eq!(verdicts.len(), 2);
372
373        assert_eq!(verdicts[0].at(), "audience[0]");
374        assert!(verdicts[0].is_error());
375        let VerdictKind::Constraint(Validation::Reject(issue)) = &verdicts[0].kind else {
376            panic!("expected a rejection");
377        };
378        assert_eq!(issue.suggestion.as_deref(), Some("family"));
379
380        assert_eq!(verdicts[1].at(), "audience[1]");
381        assert!(!verdicts[1].is_error());
382        assert!(!verdicts[1].is_unchecked());
383        assert!(matches!(
384            &verdicts[1].kind,
385            VerdictKind::Constraint(Validation::Warn(issue)) if issue.kind == IssueKind::Retired
386        ));
387    }
388
389    #[test]
390    fn the_same_issue_is_reported_once_at_the_deepest_path() {
391        // An embedder governs the field both ways, so a scalar and a list are
392        // both checked. `validate_enum` on the list repeats each item's issue
393        // at the container, and the container's copy is the one dropped.
394        let schema = Schema::new(vec![
395            FieldRule::new(PathPat::key("audience"))
396                .ty(FieldType::Seq)
397                .constraint(audience()),
398            FieldRule::new(PathPat::each_item_of("audience"))
399                .ty(FieldType::Str)
400                .constraint(audience()),
401        ]);
402        assert_eq!(
403            report(&schema, "audience: [public, famly]\n"),
404            ["audience[1]: “famly” is not a known value — did you mean “family”?"]
405        );
406        // The container's rule still speaks for itself when it has something
407        // of its own to say.
408        assert_eq!(
409            report(&schema, "audience: famly\n"),
410            [
411                "audience: expected seq, found str",
412                "audience: “famly” is not a known value — did you mean “family”?",
413            ]
414        );
415    }
416
417    #[test]
418    fn a_containers_type_mismatch_is_dropped_when_an_item_already_reported_one() {
419        let schema = Schema::new(vec![
420            FieldRule::new(PathPat::key("tags"))
421                .ty(FieldType::Map)
422                .constraint_opt(None),
423            FieldRule::new(PathPat::each_item_of("tags")).ty(FieldType::Map),
424        ]);
425        // `map` admits a list of maps, so `tags: [x]` fails only because `x`
426        // is not one — and `x` has already said so at its own path.
427        assert_eq!(
428            report(&schema, "tags: [x]\n"),
429            ["tags[0]: expected map, found str"]
430        );
431        // With no item rule the container is the one that speaks.
432        let schema = Schema::new(vec![
433            FieldRule::new(PathPat::key("tags"))
434                .ty(FieldType::Map)
435                .constraint_opt(None),
436        ]);
437        assert_eq!(
438            report(&schema, "tags: [x]\n"),
439            ["tags: expected map, found seq"]
440        );
441    }
442
443    #[test]
444    fn a_field_declared_once_is_governed_as_a_scalar_and_as_a_list() {
445        // An embedder declares `audience: str` once, and a document writes it
446        // either way. This is the convention `validate_enum` already follows.
447        let schema = Schema::new(vec![
448            FieldRule::new(PathPat::key("audience"))
449                .ty(FieldType::Str)
450                .constraint(audience()),
451        ]);
452        assert!(report(&schema, "audience: public\n").is_empty());
453        assert!(report(&schema, "audience: [public, family]\n").is_empty());
454        assert_eq!(
455            report(&schema, "audience: [public, 3]\n"),
456            ["audience: expected str, found seq"]
457        );
458    }
459
460    #[test]
461    fn a_date_field_admits_the_string_a_dateless_format_parses() {
462        let schema = Schema::new(vec![
463            FieldRule::new(PathPat::key("created"))
464                .ty(FieldType::Extended(fig::ExtKind::LocalDate))
465                .constraint_opt(None),
466        ]);
467        assert!(report(&schema, "created: 1979-05-27\n").is_empty());
468        assert_eq!(
469            report(&schema, "created: yesterday\n"),
470            ["created: expected date, found str"]
471        );
472    }
473
474    #[test]
475    fn an_unknown_constraint_kind_is_unchecked_rather_than_wrong() {
476        let schema = Schema::new(vec![
477            FieldRule::new(PathPat::key("part_of"))
478                .ty(FieldType::Ref)
479                .constraint(Constraint::Unknown("workspace-reference")),
480        ]);
481        let verdicts = schema.check(&parse("part_of: ../index.md\n"));
482        assert_eq!(verdicts.len(), 1);
483        assert!(verdicts[0].is_unchecked());
484        // Fail-closed: it is still a rejection, so an editor that does not
485        // look further will not commit it...
486        assert!(matches!(
487            &verdicts[0].kind,
488            VerdictKind::Constraint(v) if v.is_reject()
489        ));
490        // ...but it is not an error about the document.
491        assert!(!verdicts[0].is_error());
492        assert_eq!(
493            verdicts[0].to_string(),
494            "a “workspace-reference” constraint, which this validator cannot check"
495        );
496    }
497
498    #[test]
499    fn the_walk_reaches_nested_paths_and_the_root() {
500        let schema = Schema::new(vec![
501            FieldRule::new(PathPat(vec![
502                crate::SegPat::Key("items".into()),
503                crate::SegPat::EachItem,
504                crate::SegPat::Key("n".into()),
505            ]))
506            .ty(FieldType::Int)
507            .constraint_opt(None),
508            FieldRule::new(PathPat(vec![])).ty(FieldType::Map),
509        ]);
510        assert_eq!(
511            report(&schema, "items:\n  - n: 1\n  - n: two\n"),
512            ["items[1].n: expected int, found str"]
513        );
514        // The root is a node like any other, at the empty path. (Not an empty
515        // list, which is vacuously a list of maps and so fits.)
516        let verdicts = schema.check(&Value::Seq(vec![Value::Int(1)]));
517        assert_eq!(verdicts.len(), 1);
518        assert_eq!(verdicts[0].at(), "");
519        assert!(verdicts[0].path.is_empty());
520    }
521
522    #[test]
523    fn a_mapping_entry_with_a_non_text_key_is_not_walked() {
524        let schema: Schema<Constraint> = Schema::new(vec![
525            FieldRule::new(PathPat(vec![crate::SegPat::AnyDepth])).ty(FieldType::Str),
526        ]);
527        let document = Value::Map(vec![
528            (Value::Int(1), Value::Int(1)),
529            (Value::Str("k".into()), Value::Str("v".into())),
530        ]);
531        // `**` governs everything addressable; the `1:` entry is not.
532        let verdicts = schema.check(&document);
533        assert_eq!(verdicts.len(), 1);
534        assert_eq!(verdicts[0].at(), "");
535    }
536}