use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use fig::Value;
use crate::present::Tint;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Finding {
pub kind: FindingKind,
pub at: String,
pub document: Option<PathBuf>,
}
impl Finding {
pub fn is_error(&self) -> bool {
match &self.kind {
FindingKind::NotAVocabulary
| FindingKind::FieldEmpty
| FindingKind::ValuesUnreadable { .. }
| FindingKind::TermKeyNotAString
| FindingKind::RetiredUnreadable { .. }
| FindingKind::NothingOffered => true,
FindingKind::DuplicateTerm { disagree_retired } => *disagree_retired,
FindingKind::NoTerms { closed } => *closed,
FindingKind::GuardWithoutTerm { .. } => true,
FindingKind::UnknownKey { .. }
| FindingKind::TintNotRead
| FindingKind::TintUnreadable { .. }
| FindingKind::NotAString { .. }
| FindingKind::TermSpecIgnored
| FindingKind::CaseOnlyDuplicate { .. }
| FindingKind::FieldDisagrees { .. }
| FindingKind::IncludedTwice
| FindingKind::Shadowed { .. } => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FindingKind {
NotAVocabulary,
FieldEmpty,
ValuesUnreadable {
spelling: String,
},
TermKeyNotAString,
RetiredUnreadable {
spelling: String,
},
DuplicateTerm {
disagree_retired: bool,
},
NoTerms {
closed: bool,
},
NothingOffered,
UnknownKey {
key: String,
},
TintNotRead,
TintUnreadable {
spelling: String,
},
NotAString {
key: String,
},
TermSpecIgnored,
CaseOnlyDuplicate {
other: String,
},
FieldDisagrees {
field: String,
},
GuardWithoutTerm {
value: String,
},
IncludedTwice,
Shadowed {
by: String,
},
}
impl fmt::Display for Finding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
FindingKind::NotAVocabulary => f.write_str(
"no `vocabulary.field`, so this is not a vocabulary document — \
`parse_vocabulary` returns nothing for it",
),
FindingKind::FieldEmpty => {
f.write_str("`vocabulary.field` is empty, so no rule can name this vocabulary")
}
FindingKind::ValuesUnreadable { spelling } => write!(
f,
"`{spelling}` is read as neither `closed` nor `open`, so this \
vocabulary is OPEN and forbids nothing",
),
FindingKind::TermKeyNotAString => {
f.write_str("a term whose key is not text is skipped entirely")
}
FindingKind::RetiredUnreadable { spelling } => write!(
f,
"`retired: {spelling}` is not a bool, so this term is read as \
live and stays on offer",
),
FindingKind::DuplicateTerm { disagree_retired } => {
f.write_str("declared twice, so a picker offers it twice")?;
if *disagree_retired {
f.write_str(
" — and the copies disagree about `retired`, so the live \
one wins and the retirement never takes effect",
)?;
}
Ok(())
}
FindingKind::NoTerms { closed: true } => {
f.write_str("a closed vocabulary with no terms, which rejects every value there is")
}
FindingKind::NoTerms { closed: false } => {
f.write_str("no terms, so nothing is offered and no typo is ever caught")
}
FindingKind::NothingOffered => f.write_str(
"every term is retired and the vocabulary is closed, so no value \
can be entered afresh",
),
FindingKind::UnknownKey { key } => write!(f, "`{key}` is read by nothing"),
FindingKind::TintNotRead => f.write_str(
"`tint` is not read when a vocabulary is loaded from a document, \
so this term renders untinted",
),
FindingKind::TintUnreadable { spelling } => write!(
f,
"`tint: {spelling}` names no tint this crate knows (accent, neutral, \
positive, warning, danger), so it is dropped",
),
FindingKind::NotAString { key } => {
write!(f, "`{key}` is not text, so it is dropped")
}
FindingKind::TermSpecIgnored => f.write_str(
"this term's body is neither a mapping nor empty, so all of it is \
dropped and the term loads bare",
),
FindingKind::CaseOnlyDuplicate { other } => write!(
f,
"differs from `{other}` only by case; both are distinct values, \
and a reader cannot tell them apart",
),
FindingKind::FieldDisagrees { field } => write!(
f,
"this vocabulary document declares `field: {field}`, which is not \
the rule's `at`; the rule's wins and the document's is read by nothing",
),
FindingKind::GuardWithoutTerm { value } => write!(
f,
"`when: {value}` names no term of this rule's vocabulary, so the \
consequence never fires",
),
FindingKind::IncludedTwice => f.write_str(
"this document is already included, so this copy of its rules \
shadows nothing",
),
FindingKind::Shadowed { by } => write!(
f,
"every path this rule matches is matched by the earlier rule at \
{by}, so it can never govern anything",
),
}
}
}
const VOCABULARY_KEYS: &[&str] = &["field", "values"];
const TERM_KEYS: &[&str] = &["label", "description", "retired", "tint"];
pub fn lint_vocabulary(value: &Value) -> Vec<Finding> {
let mut findings = Vec::new();
let Some(marker) = value.get("vocabulary") else {
return vec![finding(FindingKind::NotAVocabulary, String::new())];
};
let Some(field) = marker.get("field").and_then(Value::as_str) else {
return vec![finding(FindingKind::NotAVocabulary, String::new())];
};
if field.is_empty() {
findings.push(finding(FindingKind::FieldEmpty, "vocabulary.field"));
}
let closed = lint_values(marker, "vocabulary", &mut findings);
unknown_keys(marker, VOCABULARY_KEYS, "vocabulary", &mut findings);
lint_terms(value, closed, "", &mut findings);
findings
}
pub(crate) fn lint_values(marker: &Value, at: &str, findings: &mut Vec<Finding>) -> bool {
let closed = marker.get("values").and_then(Value::as_str) == Some("closed");
if let Some(values) = marker.get("values") {
match values.as_str() {
Some("closed" | "open") => {}
Some(other) => findings.push(finding(
FindingKind::ValuesUnreadable {
spelling: other.to_owned(),
},
format!("{at}.values"),
)),
None => findings.push(finding(
FindingKind::ValuesUnreadable {
spelling: sketch(values),
},
format!("{at}.values"),
)),
}
}
closed
}
pub(crate) fn lint_terms(value: &Value, closed: bool, prefix: &str, findings: &mut Vec<Finding>) {
let Some(entries) = value.get("terms").and_then(Value::as_mapping) else {
findings.push(finding(
FindingKind::NoTerms { closed },
format!("{prefix}terms"),
));
return;
};
if entries.is_empty() {
findings.push(finding(
FindingKind::NoTerms { closed },
format!("{prefix}terms"),
));
return;
}
let mut seen: Vec<(String, bool)> = Vec::new();
for (key, spec) in entries {
let Some(name) = key.as_str() else {
findings.push(finding(
FindingKind::TermKeyNotAString,
format!("{prefix}terms"),
));
continue;
};
let at = format!("{prefix}terms.{name}");
let mapping = spec.as_mapping();
if mapping.is_none() && !spec.is_null() {
findings.push(finding(FindingKind::TermSpecIgnored, at.clone()));
}
for key in ["label", "description"] {
if matches!(spec.get(key), Some(held) if held.as_str().is_none()) {
findings.push(finding(
FindingKind::NotAString {
key: key.to_owned(),
},
format!("{at}.{key}"),
));
}
}
let retired = match spec.get("retired") {
None => false,
Some(held) => match held.as_bool() {
Some(retired) => retired,
None => {
findings.push(finding(
FindingKind::RetiredUnreadable {
spelling: sketch(held),
},
format!("{at}.retired"),
));
false
}
},
};
if let Some(tint) = spec.get("tint") {
let known = tint
.as_str()
.is_some_and(|name| Tint::from_name(name).is_some());
if !known {
findings.push(finding(
FindingKind::TintUnreadable {
spelling: sketch(tint),
},
format!("{at}.tint"),
));
}
}
unknown_keys(spec, TERM_KEYS, &at, findings);
if let Some((_, first_retired)) = seen.iter().find(|(value, _)| value == name) {
findings.push(finding(
FindingKind::DuplicateTerm {
disagree_retired: *first_retired != retired,
},
at,
));
}
seen.push((name.to_owned(), retired));
}
case_only_duplicates(&seen, prefix, findings);
if closed && !seen.is_empty() && seen.iter().all(|(_, retired)| *retired) {
findings.push(finding(
FindingKind::NothingOffered,
format!("{prefix}terms"),
));
}
}
fn case_only_duplicates(seen: &[(String, bool)], prefix: &str, findings: &mut Vec<Finding>) {
let mut folded: BTreeMap<String, &str> = BTreeMap::new();
for (value, retired) in seen {
if *retired {
continue;
}
let key = value.to_lowercase();
match folded.get(&key) {
Some(first) if *first == value => {}
Some(first) => findings.push(finding(
FindingKind::CaseOnlyDuplicate {
other: (*first).to_owned(),
},
format!("{prefix}terms.{value}"),
)),
None => {
folded.insert(key, value);
}
}
}
}
pub(crate) fn unknown_keys(mapping: &Value, known: &[&str], at: &str, findings: &mut Vec<Finding>) {
let Some(entries) = mapping.as_mapping() else {
return;
};
for (key, _) in entries {
let Some(key) = key.as_str() else { continue };
if !known.contains(&key) {
findings.push(finding(
FindingKind::UnknownKey {
key: key.to_owned(),
},
format!("{at}.{key}"),
));
}
}
}
pub(crate) fn finding(kind: FindingKind, at: impl Into<String>) -> Finding {
Finding {
kind,
at: at.into(),
document: None,
}
}
pub(crate) fn sketch(value: &Value) -> String {
match value {
Value::Null => "null".to_owned(),
Value::Bool(b) => b.to_string(),
Value::Int(i) => i.to_string(),
Value::Uint(u) => u.to_string(),
Value::Float(f) => f.to_string(),
Value::Str(s) => s.clone(),
Value::Seq(_) => "a list".to_owned(),
Value::Map(_) => "a mapping".to_owned(),
Value::Extended { text, .. } => text.clone(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lint(yaml: &str) -> Vec<Finding> {
let document = fig::Document::parse(yaml.as_bytes(), fig::Format::Yaml).unwrap();
lint_vocabulary(&document.to_value().unwrap())
}
fn kinds(yaml: &str) -> Vec<FindingKind> {
lint(yaml).into_iter().map(|f| f.kind).collect()
}
const CLEAN: &str = "vocabulary:\n field: audience\n values: closed\n\
terms:\n public:\n description: Anyone\n family: {}\n";
#[test]
fn a_correct_document_has_nothing_said_about_it() {
assert_eq!(lint(CLEAN), Vec::new());
}
#[test]
fn a_misspelled_values_is_the_finding_this_module_exists_for() {
let findings = lint("vocabulary:\n field: a\n values: cloesd\nterms:\n x:\n");
assert_eq!(
findings[0].kind,
FindingKind::ValuesUnreadable {
spelling: "cloesd".into()
}
);
assert!(findings[0].is_error());
assert_eq!(findings[0].at, "vocabulary.values");
assert!(matches!(
kinds("vocabulary:\n field: a\n values: Closed\nterms:\n x:\n")[..],
[FindingKind::ValuesUnreadable { .. }]
));
}
#[test]
fn an_absent_values_is_not_a_finding_because_open_is_its_documented_default() {
assert_eq!(lint("vocabulary:\n field: a\nterms:\n x:\n"), Vec::new());
}
#[test]
fn a_values_that_is_not_text_lands_in_the_same_finding() {
assert_eq!(
kinds("vocabulary:\n field: a\n values: true\nterms:\n x:\n"),
vec![FindingKind::ValuesUnreadable {
spelling: "true".into()
}]
);
}
#[test]
fn a_document_with_no_marker_is_reported_once_and_nothing_else_is() {
assert_eq!(
kinds("title: Notes\nterms:\n x:\n nonsense: 1\n"),
vec![FindingKind::NotAVocabulary]
);
assert_eq!(
kinds("vocabulary:\n values: closed\n"),
vec![FindingKind::NotAVocabulary]
);
}
#[test]
fn an_unreadable_retired_is_an_error_because_the_term_comes_out_live() {
let findings = lint(
"vocabulary:\n field: a\n values: closed\n\
terms:\n old:\n retired: \"true\"\n",
);
assert_eq!(
findings[0].kind,
FindingKind::RetiredUnreadable {
spelling: "true".into()
}
);
assert!(findings[0].is_error());
assert_eq!(findings[0].at, "terms.old.retired");
}
#[test]
fn an_unreadable_label_is_only_a_note_because_nothing_is_wrongly_accepted() {
let findings = lint(
"vocabulary:\n field: a\n values: closed\n\
terms:\n x:\n label: [a, b]\n",
);
assert_eq!(
findings[0].kind,
FindingKind::NotAString {
key: "label".into()
}
);
assert!(!findings[0].is_error());
}
#[test]
fn a_duplicate_is_a_note_until_the_copies_disagree_about_retirement() {
let findings = lint("vocabulary:\n field: a\n values: open\nterms:\n x:\n x:\n");
assert_eq!(
findings[0].kind,
FindingKind::DuplicateTerm {
disagree_retired: false
}
);
assert!(!findings[0].is_error());
let findings = lint(
"vocabulary:\n field: a\n values: open\n\
terms:\n x:\n retired: true\n x: {}\n",
);
let duplicate = findings
.iter()
.find(|f| matches!(f.kind, FindingKind::DuplicateTerm { .. }))
.expect("the duplicate is reported");
assert_eq!(
duplicate.kind,
FindingKind::DuplicateTerm {
disagree_retired: true
}
);
assert!(duplicate.is_error());
}
#[test]
fn an_empty_or_missing_terms_is_an_error_only_when_the_vocabulary_is_closed() {
assert_eq!(
kinds("vocabulary:\n field: a\n values: closed\nterms: {}\n"),
vec![FindingKind::NoTerms { closed: true }]
);
assert!(lint("vocabulary:\n field: a\n values: closed\n")[0].is_error());
assert!(!lint("vocabulary:\n field: a\n values: open\nterms: {}\n")[0].is_error());
}
#[test]
fn a_closed_vocabulary_of_only_retired_terms_offers_nothing() {
let findings = lint(
"vocabulary:\n field: a\n values: closed\n\
terms:\n old:\n retired: true\n",
);
assert_eq!(kinds_of(&findings), vec![FindingKind::NothingOffered]);
assert!(findings[0].is_error());
assert_eq!(
lint(
"vocabulary:\n field: a\n values: open\n\
terms:\n old:\n retired: true\n"
),
Vec::new()
);
assert_eq!(
kinds("vocabulary:\n field: a\n values: closed\nterms: {}\n"),
vec![FindingKind::NoTerms { closed: true }]
);
}
#[test]
fn a_key_nothing_reads_is_reported_where_the_key_set_is_actually_closed() {
assert_eq!(
kinds("vocabulary:\n field: a\n value: closed\nterms:\n x:\n"),
vec![FindingKind::UnknownKey {
key: "value".into()
}]
);
assert_eq!(
kinds("vocabulary:\n field: a\nterms:\n x:\n descripton: hi\n"),
vec![FindingKind::UnknownKey {
key: "descripton".into()
}]
);
}
#[test]
fn a_documents_own_frontmatter_is_not_linted() {
assert_eq!(
lint(
"title: Audience\nauthor: adammharris\npart_of: '[vocab](/v.md)'\n\
vocabulary:\n field: audience\n values: closed\nterms:\n public:\n"
),
Vec::new()
);
}
#[test]
fn a_tint_the_crate_cannot_name_is_dropped_and_said_so() {
assert_eq!(
lint(
"vocabulary:\n field: a\n values: closed\n\
terms:\n public:\n tint: positive\n"
),
Vec::new()
);
let findings = lint(
"vocabulary:\n field: a\n values: closed\n\
terms:\n public:\n tint: green\n",
);
assert_eq!(
kinds_of(&findings),
vec![FindingKind::TintUnreadable {
spelling: "green".into()
}]
);
assert_eq!(findings[0].at, "terms.public.tint");
assert!(!findings[0].is_error());
assert_eq!(
kinds("vocabulary:\n field: a\nterms:\n public:\n tint: 3\n"),
vec![FindingKind::TintUnreadable {
spelling: "3".into()
}]
);
}
#[test]
fn a_term_body_that_is_not_a_mapping_is_dropped_whole() {
assert_eq!(
kinds("vocabulary:\n field: a\n values: closed\nterms:\n public: Anyone\n"),
vec![FindingKind::TermSpecIgnored]
);
assert_eq!(
lint("vocabulary:\n field: a\n values: closed\nterms:\n a:\n b: {}\n"),
Vec::new()
);
}
#[test]
fn terms_differing_only_by_case_are_two_values_a_reader_cannot_tell_apart() {
let findings =
lint("vocabulary:\n field: a\n values: closed\nterms:\n Public:\n public:\n");
assert_eq!(
kinds_of(&findings),
vec![FindingKind::CaseOnlyDuplicate {
other: "Public".into()
}]
);
assert_eq!(findings[0].at, "terms.public");
assert!(!findings[0].is_error());
}
#[test]
fn an_exact_duplicate_is_not_also_reported_as_a_case_collision() {
assert_eq!(
kinds("vocabulary:\n field: a\n values: open\nterms:\n x:\n x:\n"),
vec![FindingKind::DuplicateTerm {
disagree_retired: false
}]
);
}
#[test]
fn an_empty_field_loads_and_then_cannot_be_named() {
let findings = lint("vocabulary:\n field: \"\"\n values: open\nterms:\n x:\n");
assert_eq!(kinds_of(&findings), vec![FindingKind::FieldEmpty]);
assert!(findings[0].is_error());
}
#[test]
fn every_finding_renders_a_sentence() {
for kind in [
FindingKind::NotAVocabulary,
FindingKind::FieldEmpty,
FindingKind::ValuesUnreadable {
spelling: "x".into(),
},
FindingKind::TermKeyNotAString,
FindingKind::RetiredUnreadable {
spelling: "x".into(),
},
FindingKind::DuplicateTerm {
disagree_retired: true,
},
FindingKind::DuplicateTerm {
disagree_retired: false,
},
FindingKind::NoTerms { closed: true },
FindingKind::NoTerms { closed: false },
FindingKind::NothingOffered,
FindingKind::UnknownKey { key: "x".into() },
FindingKind::TintNotRead,
FindingKind::TintUnreadable {
spelling: "x".into(),
},
FindingKind::NotAString { key: "x".into() },
FindingKind::TermSpecIgnored,
FindingKind::CaseOnlyDuplicate { other: "x".into() },
FindingKind::FieldDisagrees { field: "x".into() },
FindingKind::GuardWithoutTerm { value: "x".into() },
FindingKind::IncludedTwice,
FindingKind::Shadowed { by: "x".into() },
] {
let rendered = finding(kind.clone(), "at").to_string();
assert!(rendered.len() > 20, "{kind:?} renders only {rendered:?}");
assert_ne!(rendered, format!("{kind:?}"), "{kind:?} renders as itself");
}
}
fn kinds_of(findings: &[Finding]) -> Vec<FindingKind> {
findings.iter().map(|f| f.kind.clone()).collect()
}
}