use std::fmt;
use fig::Value;
use crate::field::{FieldRule, FieldType, Schema};
use crate::path::{Seg, render_path};
use crate::vocab::{Validate, Validation};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Verdict {
pub path: Vec<Seg>,
pub kind: VerdictKind,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VerdictKind {
TypeMismatch {
expected: FieldType,
found: FieldType,
},
Constraint(Validation),
}
impl Verdict {
pub fn at(&self) -> String {
render_path(&self.path)
}
pub fn is_error(&self) -> bool {
match &self.kind {
VerdictKind::TypeMismatch { .. } => true,
VerdictKind::Constraint(validation) => validation.is_reject() && !self.is_unchecked(),
}
}
pub fn is_unchecked(&self) -> bool {
match &self.kind {
VerdictKind::Constraint(validation) => {
validation.issue().is_some_and(|issue| issue.is_unchecked())
}
VerdictKind::TypeMismatch { .. } => false,
}
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
VerdictKind::TypeMismatch { expected, found } => {
write!(f, "expected {expected}, found {found}")
}
VerdictKind::Constraint(validation) => match validation.issue() {
Some(issue) => issue.fmt(f),
None => f.write_str("ok"),
},
}
}
}
impl<C: Validate> Schema<C> {
pub fn check(&self, document: &Value) -> Vec<Verdict> {
let mut verdicts = Vec::new();
let mut path = Vec::new();
self.walk(document, &mut path, &mut verdicts);
verdicts
}
fn walk(&self, node: &Value, path: &mut Vec<Seg>, verdicts: &mut Vec<Verdict>) {
let before = verdicts.len();
match node {
Value::Seq(items) => {
for (i, item) in items.iter().enumerate() {
path.push(Seg::Index(i));
self.walk(item, path, verdicts);
path.pop();
}
}
Value::Map(entries) => {
for (key, value) in entries {
let Some(key) = key.as_str() else { continue };
path.push(Seg::Key(key.to_owned()));
self.walk(value, path, verdicts);
path.pop();
}
}
_ => {}
}
let Some(rule) = self.rule_for(path) else {
return;
};
let descendants = &verdicts[before..];
let mut own = judge(rule, node, descendants);
for kind in own.drain(..) {
verdicts.push(Verdict {
path: path.clone(),
kind,
});
}
}
}
fn judge<C: Validate>(
rule: &FieldRule<C>,
node: &Value,
descendants: &[Verdict],
) -> Vec<VerdictKind> {
let mut kinds = Vec::new();
if let Some(expected) = rule.ty {
let item_already_said = descendants
.iter()
.any(|v| matches!(v.kind, VerdictKind::TypeMismatch { .. }));
if !expected.admits(node) && !item_already_said {
kinds.push(VerdictKind::TypeMismatch {
expected,
found: FieldType::of(node),
});
}
}
let validation = rule.validate(node);
let Some(issue) = validation.issue() else {
return kinds;
};
let already_said = descendants.iter().any(|v| match &v.kind {
VerdictKind::Constraint(v) => v.issue() == Some(issue),
VerdictKind::TypeMismatch { .. } => false,
});
if !already_said {
kinds.push(VerdictKind::Constraint(validation));
}
kinds
}
#[cfg(test)]
mod tests {
use super::*;
use crate::path::PathPat;
use crate::vocab::{Issue, IssueKind, Term, validate_enum};
#[derive(Debug, Clone)]
enum Constraint {
Vocabulary(Vec<Term>),
Unknown(&'static str),
}
impl Validate for Constraint {
fn validate(&self, value: &Value) -> Validation {
match self {
Constraint::Vocabulary(terms) => validate_enum(terms, true, value),
Constraint::Unknown(kind) => Validation::Reject(Issue::unchecked("", *kind)),
}
}
}
fn audience() -> Constraint {
Constraint::Vocabulary(vec![
Term::value("public"),
Term::value("family"),
Term::value("archived").retired(true),
])
}
fn parse(yaml: &str) -> Value {
fig::Document::parse(yaml.as_bytes(), fig::Format::Yaml)
.unwrap()
.to_value()
.unwrap()
}
fn report(schema: &Schema<Constraint>, yaml: &str) -> Vec<String> {
schema
.check(&parse(yaml))
.iter()
.map(|v| format!("{}: {v}", v.at()))
.collect()
}
#[test]
fn a_clean_document_has_nothing_said_about_it() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::each_item_of("audience"))
.ty(FieldType::Str)
.constraint(audience()),
FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
]);
assert!(report(&schema, "audience: [public, family]\ncount: 3\n").is_empty());
}
#[test]
fn a_node_no_rule_governs_is_not_a_verdict() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
]);
assert!(report(&schema, "title: x\nmeta: {author: [1, 2]}\ncount: 1\n").is_empty());
}
#[test]
fn an_empty_document_is_valid_because_nothing_is_required() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("count"))
.ty(FieldType::Int)
.constraint(audience()),
]);
assert!(schema.check(&Value::Map(vec![])).is_empty());
assert!(schema.check(&Value::Null).is_empty());
}
#[test]
fn a_shape_that_is_not_the_rules_type_is_a_mismatch() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("count"))
.ty(FieldType::Int)
.constraint_opt(None),
FieldRule::new(PathPat::key("ratio")).ty(FieldType::Float),
FieldRule::new(PathPat::key("tags")).ty(FieldType::Seq),
]);
assert_eq!(
report(&schema, "count: three\nratio: 2\ntags: one\n"),
[
"count: expected int, found str",
"tags: expected seq, found str"
]
);
let verdicts = schema.check(&parse("count: three\n"));
assert_eq!(
verdicts[0].kind,
VerdictKind::TypeMismatch {
expected: FieldType::Int,
found: FieldType::Str,
}
);
assert!(verdicts[0].is_error());
assert!(!verdicts[0].is_unchecked());
}
#[test]
fn a_rejection_is_an_error_and_a_warning_is_not() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::each_item_of("audience"))
.ty(FieldType::Str)
.constraint(audience()),
]);
let verdicts = schema.check(&parse("audience: [famly, archived]\n"));
assert_eq!(verdicts.len(), 2);
assert_eq!(verdicts[0].at(), "audience[0]");
assert!(verdicts[0].is_error());
let VerdictKind::Constraint(Validation::Reject(issue)) = &verdicts[0].kind else {
panic!("expected a rejection");
};
assert_eq!(issue.suggestion.as_deref(), Some("family"));
assert_eq!(verdicts[1].at(), "audience[1]");
assert!(!verdicts[1].is_error());
assert!(!verdicts[1].is_unchecked());
assert!(matches!(
&verdicts[1].kind,
VerdictKind::Constraint(Validation::Warn(issue)) if issue.kind == IssueKind::Retired
));
}
#[test]
fn the_same_issue_is_reported_once_at_the_deepest_path() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("audience"))
.ty(FieldType::Seq)
.constraint(audience()),
FieldRule::new(PathPat::each_item_of("audience"))
.ty(FieldType::Str)
.constraint(audience()),
]);
assert_eq!(
report(&schema, "audience: [public, famly]\n"),
["audience[1]: “famly” is not a known value — did you mean “family”?"]
);
assert_eq!(
report(&schema, "audience: famly\n"),
[
"audience: expected seq, found str",
"audience: “famly” is not a known value — did you mean “family”?",
]
);
}
#[test]
fn a_containers_type_mismatch_is_dropped_when_an_item_already_reported_one() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("tags"))
.ty(FieldType::Map)
.constraint_opt(None),
FieldRule::new(PathPat::each_item_of("tags")).ty(FieldType::Map),
]);
assert_eq!(
report(&schema, "tags: [x]\n"),
["tags[0]: expected map, found str"]
);
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("tags"))
.ty(FieldType::Map)
.constraint_opt(None),
]);
assert_eq!(
report(&schema, "tags: [x]\n"),
["tags: expected map, found seq"]
);
}
#[test]
fn a_field_declared_once_is_governed_as_a_scalar_and_as_a_list() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("audience"))
.ty(FieldType::Str)
.constraint(audience()),
]);
assert!(report(&schema, "audience: public\n").is_empty());
assert!(report(&schema, "audience: [public, family]\n").is_empty());
assert_eq!(
report(&schema, "audience: [public, 3]\n"),
["audience: expected str, found seq"]
);
}
#[test]
fn a_date_field_admits_the_string_a_dateless_format_parses() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("created"))
.ty(FieldType::Extended(fig::ExtKind::LocalDate))
.constraint_opt(None),
]);
assert!(report(&schema, "created: 1979-05-27\n").is_empty());
assert_eq!(
report(&schema, "created: yesterday\n"),
["created: expected date, found str"]
);
}
#[test]
fn an_unknown_constraint_kind_is_unchecked_rather_than_wrong() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("part_of"))
.ty(FieldType::Ref)
.constraint(Constraint::Unknown("workspace-reference")),
]);
let verdicts = schema.check(&parse("part_of: ../index.md\n"));
assert_eq!(verdicts.len(), 1);
assert!(verdicts[0].is_unchecked());
assert!(matches!(
&verdicts[0].kind,
VerdictKind::Constraint(v) if v.is_reject()
));
assert!(!verdicts[0].is_error());
assert_eq!(
verdicts[0].to_string(),
"a “workspace-reference” constraint, which this validator cannot check"
);
}
#[test]
fn the_walk_reaches_nested_paths_and_the_root() {
let schema = Schema::new(vec![
FieldRule::new(PathPat(vec![
crate::SegPat::Key("items".into()),
crate::SegPat::EachItem,
crate::SegPat::Key("n".into()),
]))
.ty(FieldType::Int)
.constraint_opt(None),
FieldRule::new(PathPat(vec![])).ty(FieldType::Map),
]);
assert_eq!(
report(&schema, "items:\n - n: 1\n - n: two\n"),
["items[1].n: expected int, found str"]
);
let verdicts = schema.check(&Value::Seq(vec![Value::Int(1)]));
assert_eq!(verdicts.len(), 1);
assert_eq!(verdicts[0].at(), "");
assert!(verdicts[0].path.is_empty());
}
#[test]
fn a_mapping_entry_with_a_non_text_key_is_not_walked() {
let schema: Schema<Constraint> = Schema::new(vec![
FieldRule::new(PathPat(vec![crate::SegPat::AnyDepth])).ty(FieldType::Str),
]);
let document = Value::Map(vec![
(Value::Int(1), Value::Int(1)),
(Value::Str("k".into()), Value::Str("v".into())),
]);
let verdicts = schema.check(&document);
assert_eq!(verdicts.len(), 1);
assert_eq!(verdicts[0].at(), "");
}
}