fig_schema/lint.rs
1//! Reading a vocabulary document and judging it — the checks
2//! [`parse_vocabulary`](crate::parse_vocabulary) cannot make while it is
3//! parsing, because parsing a document is answering "what does this say" and
4//! linting it is answering "did the author mean that".
5//!
6//! The two questions come apart in one direction only. [`parse_vocabulary`] is
7//! deliberately permissive: an unreadable key is a key it does not read, a term
8//! it cannot name is a term it skips, and it reports neither, because a
9//! frontmatter engine loading a workspace at startup wants the terms it can
10//! have rather than an error. Every one of those silences is a place where the
11//! document says something and nothing acts on it, and the author is never told.
12//! This module is where they are told.
13//!
14//! The same division of labour extends to a schema document. Whatever
15//! [`load_schema`](crate::load_schema) reads permissively — a key in a rule
16//! nothing reads, a `tint` nothing maps, a vocabulary `field` that disagrees
17//! with the rule's `at` — it reports as a [`Finding`] of one of the kinds
18//! below, in the same list a vocabulary document's findings go in, with
19//! [`Finding::document`] saying which document. What it cannot read at all is
20//! a [`LoadError`](crate::LoadError) instead, because a validator fails closed.
21//!
22//! # Errors and notes
23//!
24//! A finding is an **error** when it changes what validation *does*, and a
25//! **note** when it changes only what a reader *sees*. That is the whole of the
26//! rule, and it is worth stating because the interesting cases are not obvious:
27//! a `retired:` the parser cannot read as a bool is an error, because the term
28//! comes out live and a value the author retired is accepted in silence; a
29//! `label:` it cannot read as a string is a note, because the picker shows the
30//! stored value and nothing is wrongly accepted.
31//!
32//! The flagship is [`FindingKind::ValuesUnreadable`]. `values: cloesd` parses,
33//! loads, and validates — as an **open** vocabulary, because
34//! [`parse_vocabulary`] asks only whether the spelling is exactly `closed`.
35//! Every value the author meant to forbid is then accepted with a warning, and
36//! nothing anywhere in this crate can notice: an open vocabulary that rejects
37//! nothing is indistinguishable from one that was meant to be open.
38//!
39//! # What is deliberately not checked
40//!
41//! Unknown keys at the *top level* of the document. A vocabulary document is a
42//! fig document like any other and may carry `title`, `author`, `part_of` and
43//! whatever else its repository's conventions ask for; flagging those would
44//! make the lint fire on correct documents, which is how a lint teaches people
45//! to stop running it. Unknown keys are checked only inside `vocabulary` and
46//! inside a term's spec, where the key set really is closed.
47
48use std::collections::BTreeMap;
49use std::fmt;
50use std::path::PathBuf;
51
52use fig::Value;
53
54use crate::present::Tint;
55
56/// One thing the lint has to say about a vocabulary document.
57///
58/// `#[non_exhaustive]`: a finding gains context (a span, a source document) the
59/// same way [`Issue`](crate::Issue) does. Read the fields; build one only
60/// through [`lint_vocabulary`].
61#[derive(Debug, Clone, PartialEq, Eq)]
62#[non_exhaustive]
63pub struct Finding {
64 /// What was found.
65 pub kind: FindingKind,
66 /// Where, as a fig path into the document (`terms.public.retired`). Empty
67 /// for a finding about the document as a whole.
68 ///
69 /// A path rather than a line and column because that is the most a caller
70 /// can be given: fig hands back a [`Value`] tree with no per-node spans, so
71 /// nothing downstream of a parse knows which line a key came from. It is
72 /// also how fig's own `Warning` addresses a node, so the two agree.
73 pub at: String,
74 /// Which document, when the finding is one of several documents' —
75 /// [`load_schema`](crate::load_schema) follows includes and `from`
76 /// references, and a finding in one of those names it here. `None` from
77 /// [`lint_vocabulary`], which judges the one document it was given.
78 pub document: Option<PathBuf>,
79}
80
81impl Finding {
82 /// Whether this changes what validation does, rather than only what a
83 /// reader sees. See the module docs for the rule; see each
84 /// [`FindingKind`] for why it falls where it does.
85 ///
86 /// Matched exhaustively despite [`FindingKind`] being `#[non_exhaustive]`,
87 /// which binds downstream and not here: a new kind should stop this
88 /// compiling until somebody decides which side of the rule it falls on.
89 /// Defaulting it to a note would be deciding by omission.
90 pub fn is_error(&self) -> bool {
91 match &self.kind {
92 FindingKind::NotAVocabulary
93 | FindingKind::FieldEmpty
94 | FindingKind::ValuesUnreadable { .. }
95 | FindingKind::TermKeyNotAString
96 | FindingKind::RetiredUnreadable { .. }
97 | FindingKind::NothingOffered => true,
98 FindingKind::DuplicateTerm { disagree_retired } => *disagree_retired,
99 FindingKind::NoTerms { closed } => *closed,
100 FindingKind::GuardWithoutTerm { .. } => true,
101 FindingKind::UnknownKey { .. }
102 | FindingKind::TintNotRead
103 | FindingKind::TintUnreadable { .. }
104 | FindingKind::NotAString { .. }
105 | FindingKind::TermSpecIgnored
106 | FindingKind::CaseOnlyDuplicate { .. }
107 | FindingKind::FieldDisagrees { .. }
108 | FindingKind::IncludedTwice
109 | FindingKind::Shadowed { .. } => false,
110 }
111 }
112}
113
114/// The kind of a [`Finding`].
115///
116/// `#[non_exhaustive]`: the crate learns new silences as it grows, so a `match`
117/// needs a `_` arm.
118#[derive(Debug, Clone, PartialEq, Eq)]
119#[non_exhaustive]
120pub enum FindingKind {
121 /// No `vocabulary.field`, so [`parse_vocabulary`](crate::parse_vocabulary)
122 /// returns `None` and this is not a vocabulary document at all. Nothing
123 /// else is checked once this is found — every later finding would be about
124 /// a document the parser never reads.
125 NotAVocabulary,
126 /// `vocabulary.field` is the empty string. It loads, and then nothing can
127 /// point a rule at it.
128 FieldEmpty,
129 /// `vocabulary.values` is present and is neither `closed` nor `open`.
130 ///
131 /// An error, and the one this module exists for: the parser asks only
132 /// whether the spelling is exactly `closed`, so `cloesd`, `Closed` and
133 /// `close` all load as an **open** vocabulary that forbids nothing.
134 ValuesUnreadable {
135 /// The spelling as written, so the message can quote it back.
136 spelling: String,
137 },
138 /// A key under `terms` that is not a string, which the parser skips
139 /// entirely — the term is not merely stripped of its metadata, it is gone.
140 TermKeyNotAString,
141 /// A term's `retired:` that is not a bool. An error: the parser reads it as
142 /// *not retired*, so a value the author withdrew keeps being offered.
143 RetiredUnreadable {
144 /// How it was written.
145 spelling: String,
146 },
147 /// The same term value declared more than once. Both survive, in
148 /// declaration order, so a picker offers the value twice.
149 ///
150 /// An error only when the copies disagree about `retired`: the first live
151 /// one wins the membership test, so a term that is retired in one entry and
152 /// live in another validates as live and the retirement never takes effect.
153 DuplicateTerm {
154 /// Whether the copies disagree about `retired`.
155 disagree_retired: bool,
156 },
157 /// The vocabulary declares no terms.
158 NoTerms {
159 /// Whether the vocabulary is closed, in which case it rejects every
160 /// value there is.
161 closed: bool,
162 },
163 /// A closed vocabulary in which every term is retired: no value can be
164 /// entered afresh, because the known ones are all withdrawn and every other
165 /// is rejected.
166 NothingOffered,
167 /// A key nothing reads, inside `vocabulary` or inside a term's spec. A
168 /// note: the document says something and the parser ignores it, but nothing
169 /// is wrongly accepted. `vocabulary.value = closed` is the shape that
170 /// stings, and it is a note here only because
171 /// [`ValuesUnreadable`](FindingKind::ValuesUnreadable) cannot see it.
172 UnknownKey {
173 /// The key as written.
174 key: String,
175 },
176 /// A term declared a `tint:` when [`parse_vocabulary`](crate::parse_vocabulary)
177 /// did not read one. **No longer produced**: the parser reads the key
178 /// since the release that shipped the schema document loader, and a
179 /// spelling it cannot map is [`TintUnreadable`](FindingKind::TintUnreadable).
180 /// The variant stays because removing one is a break for every `match`
181 /// downstream.
182 TintNotRead,
183 /// A `tint:` — on a term, or on a rule — spelled as none of `accent`,
184 /// `neutral`, `positive`, `warning`, `danger`. A note: the tint is dropped
185 /// and the field or term draws untinted, which is a presenter failing open.
186 TintUnreadable {
187 /// How it was written.
188 spelling: String,
189 },
190 /// A term's `label:` or `description:` that is not a string, which the
191 /// parser drops.
192 NotAString {
193 /// Which key.
194 key: String,
195 },
196 /// A term whose spec is a non-null scalar or a sequence — `public: Anyone`
197 /// rather than `public: { description: Anyone }`. Every lookup misses, so
198 /// it loads as a bare term and whatever was written is dropped.
199 TermSpecIgnored,
200 /// Two live terms whose values differ only by case. Both are real, distinct
201 /// values (membership is compared exactly), but a reader cannot tell them
202 /// apart in a picker and the near-miss suggestion between them is settled
203 /// by declaration order.
204 CaseOnlyDuplicate {
205 /// The term this one collides with.
206 other: String,
207 },
208 /// A rule's vocabulary was loaded `from` a document whose `field` names a
209 /// different path from the rule's `at`. The rule's `at` wins — that is
210 /// what `from` means — so this is a note: the document's own `field` is
211 /// read by nothing here.
212 FieldDisagrees {
213 /// The `field` the vocabulary document declares.
214 field: String,
215 },
216 /// An `on_change.when` naming a value the rule's vocabulary has no term
217 /// for. An error, and the reason [`guards_without_terms`](crate::guards_without_terms)
218 /// exists: the guard never fires, and the user commits the change the
219 /// author warned about hardest with no warning at all.
220 GuardWithoutTerm {
221 /// The value the guard names.
222 value: String,
223 },
224 /// An `include` of a document this schema already includes. Both copies
225 /// are spliced, and the second shadows nothing — so a note.
226 IncludedTwice,
227 /// A rule every one of whose paths an earlier rule also matches, so it can
228 /// never govern anything. A note, and the one finding that needs the whole
229 /// loaded schema rather than one document: `**` written before anything is
230 /// the usual way to get one.
231 Shadowed {
232 /// The rule that shadows it, by its origin.
233 by: String,
234 },
235}
236
237impl fmt::Display for Finding {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239 match &self.kind {
240 FindingKind::NotAVocabulary => f.write_str(
241 "no `vocabulary.field`, so this is not a vocabulary document — \
242 `parse_vocabulary` returns nothing for it",
243 ),
244 FindingKind::FieldEmpty => {
245 f.write_str("`vocabulary.field` is empty, so no rule can name this vocabulary")
246 }
247 FindingKind::ValuesUnreadable { spelling } => write!(
248 f,
249 "`{spelling}` is read as neither `closed` nor `open`, so this \
250 vocabulary is OPEN and forbids nothing",
251 ),
252 FindingKind::TermKeyNotAString => {
253 f.write_str("a term whose key is not text is skipped entirely")
254 }
255 FindingKind::RetiredUnreadable { spelling } => write!(
256 f,
257 "`retired: {spelling}` is not a bool, so this term is read as \
258 live and stays on offer",
259 ),
260 FindingKind::DuplicateTerm { disagree_retired } => {
261 f.write_str("declared twice, so a picker offers it twice")?;
262 if *disagree_retired {
263 f.write_str(
264 " — and the copies disagree about `retired`, so the live \
265 one wins and the retirement never takes effect",
266 )?;
267 }
268 Ok(())
269 }
270 FindingKind::NoTerms { closed: true } => {
271 f.write_str("a closed vocabulary with no terms, which rejects every value there is")
272 }
273 FindingKind::NoTerms { closed: false } => {
274 f.write_str("no terms, so nothing is offered and no typo is ever caught")
275 }
276 FindingKind::NothingOffered => f.write_str(
277 "every term is retired and the vocabulary is closed, so no value \
278 can be entered afresh",
279 ),
280 FindingKind::UnknownKey { key } => write!(f, "`{key}` is read by nothing"),
281 FindingKind::TintNotRead => f.write_str(
282 "`tint` is not read when a vocabulary is loaded from a document, \
283 so this term renders untinted",
284 ),
285 FindingKind::TintUnreadable { spelling } => write!(
286 f,
287 "`tint: {spelling}` names no tint this crate knows (accent, neutral, \
288 positive, warning, danger), so it is dropped",
289 ),
290 FindingKind::NotAString { key } => {
291 write!(f, "`{key}` is not text, so it is dropped")
292 }
293 FindingKind::TermSpecIgnored => f.write_str(
294 "this term's body is neither a mapping nor empty, so all of it is \
295 dropped and the term loads bare",
296 ),
297 FindingKind::CaseOnlyDuplicate { other } => write!(
298 f,
299 "differs from `{other}` only by case; both are distinct values, \
300 and a reader cannot tell them apart",
301 ),
302 FindingKind::FieldDisagrees { field } => write!(
303 f,
304 "this vocabulary document declares `field: {field}`, which is not \
305 the rule's `at`; the rule's wins and the document's is read by nothing",
306 ),
307 FindingKind::GuardWithoutTerm { value } => write!(
308 f,
309 "`when: {value}` names no term of this rule's vocabulary, so the \
310 consequence never fires",
311 ),
312 FindingKind::IncludedTwice => f.write_str(
313 "this document is already included, so this copy of its rules \
314 shadows nothing",
315 ),
316 FindingKind::Shadowed { by } => write!(
317 f,
318 "every path this rule matches is matched by the earlier rule at \
319 {by}, so it can never govern anything",
320 ),
321 }
322 }
323}
324
325/// The keys `vocabulary` is read for.
326const VOCABULARY_KEYS: &[&str] = &["field", "values"];
327
328/// The keys a term's spec is read for.
329const TERM_KEYS: &[&str] = &["label", "description", "retired", "tint"];
330
331/// Lint a vocabulary document, given its top-level value. An empty result is a
332/// clean document.
333///
334/// Takes the raw [`Value`] rather than a
335/// [`VocabularyDoc`](crate::VocabularyDoc) on purpose: almost everything worth
336/// reporting is something the parse *discarded*, so a lint over the parsed form
337/// could not see it. The unreadable `values:` spelling, the `retired:` that was
338/// not a bool, the key nothing read — none of them survive
339/// [`parse_vocabulary`](crate::parse_vocabulary).
340///
341/// ```
342/// use fig_schema::{lint_vocabulary, FindingKind};
343///
344/// let document = fig::Document::parse(
345/// b"vocabulary:\n field: audience\n values: cloesd\nterms:\n public:\n",
346/// fig_yaml::format().unwrap(),
347/// ).unwrap();
348///
349/// let findings = lint_vocabulary(&document.to_value().unwrap());
350/// assert_eq!(findings.len(), 1);
351/// assert!(findings[0].is_error());
352/// assert_eq!(findings[0].at, "vocabulary.values");
353/// ```
354pub fn lint_vocabulary(value: &Value) -> Vec<Finding> {
355 let mut findings = Vec::new();
356
357 // Everything below is about what the parser read out of this document, so
358 // there is nothing to say about one the parser declines. Reported and
359 // returned rather than reported and continued: a document with no
360 // `vocabulary` marker is usually not a vocabulary document at all, and
361 // burying that under a dozen notes about its other keys helps nobody.
362 let Some(marker) = value.get("vocabulary") else {
363 return vec![finding(FindingKind::NotAVocabulary, String::new())];
364 };
365 let Some(field) = marker.get("field").and_then(Value::as_str) else {
366 return vec![finding(FindingKind::NotAVocabulary, String::new())];
367 };
368 if field.is_empty() {
369 findings.push(finding(FindingKind::FieldEmpty, "vocabulary.field"));
370 }
371
372 let closed = lint_values(marker, "vocabulary", &mut findings);
373 unknown_keys(marker, VOCABULARY_KEYS, "vocabulary", &mut findings);
374
375 lint_terms(value, closed, "", &mut findings);
376 findings
377}
378
379/// The `values` key of `marker`, judged, and what the parser reads it as.
380///
381/// The parse is `== Some("closed")`, so every other spelling — including a
382/// missing key — is open. A *missing* one is legitimate and says nothing; a
383/// present one the parser does not recognize is a typo with teeth. `at` is
384/// the path of `marker` — `vocabulary` in a vocabulary document,
385/// `rules[2].constraint` for a vocabulary written inline in a rule.
386pub(crate) fn lint_values(marker: &Value, at: &str, findings: &mut Vec<Finding>) -> bool {
387 let closed = marker.get("values").and_then(Value::as_str) == Some("closed");
388 if let Some(values) = marker.get("values") {
389 match values.as_str() {
390 Some("closed" | "open") => {}
391 Some(other) => findings.push(finding(
392 FindingKind::ValuesUnreadable {
393 spelling: other.to_owned(),
394 },
395 format!("{at}.values"),
396 )),
397 // Not text at all (`values: true`, `values: [closed]`). Same
398 // consequence, so the same finding, spelled the way fig prints it.
399 None => findings.push(finding(
400 FindingKind::ValuesUnreadable {
401 spelling: sketch(values),
402 },
403 format!("{at}.values"),
404 )),
405 }
406 }
407 closed
408}
409
410/// The `terms:` half: every entry, and then the questions that need the whole
411/// set at once (duplicates, and whether anything is left on offer). `prefix`
412/// is the path of the mapping holding `terms` — empty for a vocabulary
413/// document, `rules[2].constraint.` for a vocabulary inline in a rule.
414pub(crate) fn lint_terms(value: &Value, closed: bool, prefix: &str, findings: &mut Vec<Finding>) {
415 let Some(entries) = value.get("terms").and_then(Value::as_mapping) else {
416 findings.push(finding(
417 FindingKind::NoTerms { closed },
418 format!("{prefix}terms"),
419 ));
420 return;
421 };
422 if entries.is_empty() {
423 findings.push(finding(
424 FindingKind::NoTerms { closed },
425 format!("{prefix}terms"),
426 ));
427 return;
428 }
429
430 // Declaration order, mirroring the parser's: `retired` here is what the
431 // parser would read, not what the document meant, because whether a
432 // retirement takes effect is exactly the question a duplicate raises.
433 let mut seen: Vec<(String, bool)> = Vec::new();
434
435 for (key, spec) in entries {
436 let Some(name) = key.as_str() else {
437 findings.push(finding(
438 FindingKind::TermKeyNotAString,
439 format!("{prefix}terms"),
440 ));
441 continue;
442 };
443 let at = format!("{prefix}terms.{name}");
444
445 // A bare `public:` (null) and an empty `public: {}` are both documented
446 // spellings of "a live term with no metadata". Anything else that is
447 // not a mapping — a string, a number, a list — is content the parser
448 // silently drops.
449 let mapping = spec.as_mapping();
450 if mapping.is_none() && !spec.is_null() {
451 findings.push(finding(FindingKind::TermSpecIgnored, at.clone()));
452 }
453
454 for key in ["label", "description"] {
455 // A `matches!` guard rather than a `let` chain, which is stable
456 // only from Rust 1.88 and would raise this crate's declared floor
457 // for one line of convenience.
458 if matches!(spec.get(key), Some(held) if held.as_str().is_none()) {
459 findings.push(finding(
460 FindingKind::NotAString {
461 key: key.to_owned(),
462 },
463 format!("{at}.{key}"),
464 ));
465 }
466 }
467
468 let retired = match spec.get("retired") {
469 None => false,
470 Some(held) => match held.as_bool() {
471 Some(retired) => retired,
472 None => {
473 findings.push(finding(
474 FindingKind::RetiredUnreadable {
475 spelling: sketch(held),
476 },
477 format!("{at}.retired"),
478 ));
479 false
480 }
481 },
482 };
483
484 // Read since the loader shipped; what is left to say is a spelling
485 // the crate cannot map, which loads as no tint at all.
486 if let Some(tint) = spec.get("tint") {
487 let known = tint
488 .as_str()
489 .is_some_and(|name| Tint::from_name(name).is_some());
490 if !known {
491 findings.push(finding(
492 FindingKind::TintUnreadable {
493 spelling: sketch(tint),
494 },
495 format!("{at}.tint"),
496 ));
497 }
498 }
499 unknown_keys(spec, TERM_KEYS, &at, findings);
500
501 if let Some((_, first_retired)) = seen.iter().find(|(value, _)| value == name) {
502 findings.push(finding(
503 FindingKind::DuplicateTerm {
504 disagree_retired: *first_retired != retired,
505 },
506 at,
507 ));
508 }
509 seen.push((name.to_owned(), retired));
510 }
511
512 case_only_duplicates(&seen, prefix, findings);
513
514 // Only worth saying when there is something to be on offer: an empty
515 // `terms:` already had its finding above, and reporting both would be the
516 // same sentence twice.
517 if closed && !seen.is_empty() && seen.iter().all(|(_, retired)| *retired) {
518 findings.push(finding(
519 FindingKind::NothingOffered,
520 format!("{prefix}terms"),
521 ));
522 }
523}
524
525/// Live terms that collide once case is folded away. Reported against the
526/// *later* of the pair, since that is the one a reader would be adding.
527fn case_only_duplicates(seen: &[(String, bool)], prefix: &str, findings: &mut Vec<Finding>) {
528 let mut folded: BTreeMap<String, &str> = BTreeMap::new();
529 for (value, retired) in seen {
530 if *retired {
531 continue;
532 }
533 let key = value.to_lowercase();
534 match folded.get(&key) {
535 // An exact duplicate is already reported as one; saying it also
536 // collides with itself under case folding is noise.
537 Some(first) if *first == value => {}
538 Some(first) => findings.push(finding(
539 FindingKind::CaseOnlyDuplicate {
540 other: (*first).to_owned(),
541 },
542 format!("{prefix}terms.{value}"),
543 )),
544 None => {
545 folded.insert(key, value);
546 }
547 }
548 }
549}
550
551/// Report every key of `mapping` that is not in `known`.
552///
553/// Reads the mapping directly rather than through [`Value::get`] because the
554/// question is which keys are *present*, not what one of them resolves to — and
555/// a duplicated key is therefore reported once per copy, which is the honest
556/// answer for a document that spells it twice.
557pub(crate) fn unknown_keys(mapping: &Value, known: &[&str], at: &str, findings: &mut Vec<Finding>) {
558 let Some(entries) = mapping.as_mapping() else {
559 return;
560 };
561 for (key, _) in entries {
562 let Some(key) = key.as_str() else { continue };
563 if !known.contains(&key) {
564 findings.push(finding(
565 FindingKind::UnknownKey {
566 key: key.to_owned(),
567 },
568 format!("{at}.{key}"),
569 ));
570 }
571 }
572}
573
574pub(crate) fn finding(kind: FindingKind, at: impl Into<String>) -> Finding {
575 Finding {
576 kind,
577 at: at.into(),
578 document: None,
579 }
580}
581
582/// How to quote a non-text value back at its author. Serializing through fig
583/// would be exact but can fail and needs a format chosen; a finding only needs
584/// enough for the author to recognize the line they wrote.
585pub(crate) fn sketch(value: &Value) -> String {
586 match value {
587 Value::Null => "null".to_owned(),
588 Value::Bool(b) => b.to_string(),
589 Value::Int(i) => i.to_string(),
590 Value::Uint(u) => u.to_string(),
591 Value::Float(f) => f.to_string(),
592 Value::Str(s) => s.clone(),
593 Value::Seq(_) => "a list".to_owned(),
594 Value::Map(_) => "a mapping".to_owned(),
595 Value::Extended { text, .. } => text.clone(),
596 }
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602
603 fn lint(yaml: &str) -> Vec<Finding> {
604 let document = fig::Document::parse(yaml.as_bytes(), fig_yaml::format().unwrap()).unwrap();
605 lint_vocabulary(&document.to_value().unwrap())
606 }
607
608 fn kinds(yaml: &str) -> Vec<FindingKind> {
609 lint(yaml).into_iter().map(|f| f.kind).collect()
610 }
611
612 const CLEAN: &str = "vocabulary:\n field: audience\n values: closed\n\
613 terms:\n public:\n description: Anyone\n family: {}\n";
614
615 #[test]
616 fn a_correct_document_has_nothing_said_about_it() {
617 assert_eq!(lint(CLEAN), Vec::new());
618 }
619
620 #[test]
621 fn a_misspelled_values_is_the_finding_this_module_exists_for() {
622 // `cloesd` parses, loads, and validates — as an OPEN vocabulary. Nothing
623 // else in the crate can notice, because an open vocabulary that rejects
624 // nothing looks exactly like one that was meant to be open.
625 let findings = lint("vocabulary:\n field: a\n values: cloesd\nterms:\n x:\n");
626 assert_eq!(
627 findings[0].kind,
628 FindingKind::ValuesUnreadable {
629 spelling: "cloesd".into()
630 }
631 );
632 assert!(findings[0].is_error());
633 assert_eq!(findings[0].at, "vocabulary.values");
634
635 // Capitalization is the same failure: the parse is an exact comparison.
636 assert!(matches!(
637 kinds("vocabulary:\n field: a\n values: Closed\nterms:\n x:\n")[..],
638 [FindingKind::ValuesUnreadable { .. }]
639 ));
640 }
641
642 #[test]
643 fn an_absent_values_is_not_a_finding_because_open_is_its_documented_default() {
644 assert_eq!(lint("vocabulary:\n field: a\nterms:\n x:\n"), Vec::new());
645 }
646
647 #[test]
648 fn a_values_that_is_not_text_lands_in_the_same_finding() {
649 assert_eq!(
650 kinds("vocabulary:\n field: a\n values: true\nterms:\n x:\n"),
651 vec![FindingKind::ValuesUnreadable {
652 spelling: "true".into()
653 }]
654 );
655 }
656
657 #[test]
658 fn a_document_with_no_marker_is_reported_once_and_nothing_else_is() {
659 // Not "and here are nine notes about your unrelated frontmatter".
660 assert_eq!(
661 kinds("title: Notes\nterms:\n x:\n nonsense: 1\n"),
662 vec![FindingKind::NotAVocabulary]
663 );
664 assert_eq!(
665 kinds("vocabulary:\n values: closed\n"),
666 vec![FindingKind::NotAVocabulary]
667 );
668 }
669
670 #[test]
671 fn an_unreadable_retired_is_an_error_because_the_term_comes_out_live() {
672 let findings = lint(
673 "vocabulary:\n field: a\n values: closed\n\
674 terms:\n old:\n retired: \"true\"\n",
675 );
676 assert_eq!(
677 findings[0].kind,
678 FindingKind::RetiredUnreadable {
679 spelling: "true".into()
680 }
681 );
682 assert!(findings[0].is_error());
683 assert_eq!(findings[0].at, "terms.old.retired");
684 }
685
686 #[test]
687 fn an_unreadable_label_is_only_a_note_because_nothing_is_wrongly_accepted() {
688 let findings = lint(
689 "vocabulary:\n field: a\n values: closed\n\
690 terms:\n x:\n label: [a, b]\n",
691 );
692 assert_eq!(
693 findings[0].kind,
694 FindingKind::NotAString {
695 key: "label".into()
696 }
697 );
698 assert!(!findings[0].is_error());
699 }
700
701 #[test]
702 fn a_duplicate_is_a_note_until_the_copies_disagree_about_retirement() {
703 // Both survive in declaration order, so a picker offers the value twice
704 // — untidy, but validation is unchanged.
705 let findings = lint("vocabulary:\n field: a\n values: open\nterms:\n x:\n x:\n");
706 assert_eq!(
707 findings[0].kind,
708 FindingKind::DuplicateTerm {
709 disagree_retired: false
710 }
711 );
712 assert!(!findings[0].is_error());
713
714 // Disagreeing is a different matter: `validate_term` looks for a live
715 // term first, so the retirement is simply never in effect.
716 let findings = lint(
717 "vocabulary:\n field: a\n values: open\n\
718 terms:\n x:\n retired: true\n x: {}\n",
719 );
720 let duplicate = findings
721 .iter()
722 .find(|f| matches!(f.kind, FindingKind::DuplicateTerm { .. }))
723 .expect("the duplicate is reported");
724 assert_eq!(
725 duplicate.kind,
726 FindingKind::DuplicateTerm {
727 disagree_retired: true
728 }
729 );
730 assert!(duplicate.is_error());
731 }
732
733 #[test]
734 fn an_empty_or_missing_terms_is_an_error_only_when_the_vocabulary_is_closed() {
735 // Closed and empty rejects every value there is.
736 assert_eq!(
737 kinds("vocabulary:\n field: a\n values: closed\nterms: {}\n"),
738 vec![FindingKind::NoTerms { closed: true }]
739 );
740 assert!(lint("vocabulary:\n field: a\n values: closed\n")[0].is_error());
741 // Open and empty is a folksonomy nobody has seeded — worth saying,
742 // not worth failing.
743 assert!(!lint("vocabulary:\n field: a\n values: open\nterms: {}\n")[0].is_error());
744 }
745
746 #[test]
747 fn a_closed_vocabulary_of_only_retired_terms_offers_nothing() {
748 let findings = lint(
749 "vocabulary:\n field: a\n values: closed\n\
750 terms:\n old:\n retired: true\n",
751 );
752 assert_eq!(kinds_of(&findings), vec![FindingKind::NothingOffered]);
753 assert!(findings[0].is_error());
754
755 // Open, the same set still warns rather than rejects, so it works.
756 assert_eq!(
757 lint(
758 "vocabulary:\n field: a\n values: open\n\
759 terms:\n old:\n retired: true\n"
760 ),
761 Vec::new()
762 );
763 // And it is not reported twice when `terms` is empty as well.
764 assert_eq!(
765 kinds("vocabulary:\n field: a\n values: closed\nterms: {}\n"),
766 vec![FindingKind::NoTerms { closed: true }]
767 );
768 }
769
770 #[test]
771 fn a_key_nothing_reads_is_reported_where_the_key_set_is_actually_closed() {
772 // `value` instead of `values` is the shape that stings: the vocabulary
773 // silently opens, and `ValuesUnreadable` cannot see it because there is
774 // no `values` to read.
775 assert_eq!(
776 kinds("vocabulary:\n field: a\n value: closed\nterms:\n x:\n"),
777 vec![FindingKind::UnknownKey {
778 key: "value".into()
779 }]
780 );
781 assert_eq!(
782 kinds("vocabulary:\n field: a\nterms:\n x:\n descripton: hi\n"),
783 vec![FindingKind::UnknownKey {
784 key: "descripton".into()
785 }]
786 );
787 }
788
789 #[test]
790 fn a_documents_own_frontmatter_is_not_linted() {
791 // A vocabulary document is a fig document like any other, and this
792 // repository's conventions put `title`/`author`/`part_of` on one. A lint
793 // that fired on every correct document is one people stop running.
794 assert_eq!(
795 lint(
796 "title: Audience\nauthor: adammharris\npart_of: '[vocab](/v.md)'\n\
797 vocabulary:\n field: audience\n values: closed\nterms:\n public:\n"
798 ),
799 Vec::new()
800 );
801 }
802
803 #[test]
804 fn a_tint_the_crate_cannot_name_is_dropped_and_said_so() {
805 // `tint` is read now, so a known spelling is silent...
806 assert_eq!(
807 lint(
808 "vocabulary:\n field: a\n values: closed\n\
809 terms:\n public:\n tint: positive\n"
810 ),
811 Vec::new()
812 );
813 // ...and one the crate cannot map loads as no tint, a note.
814 let findings = lint(
815 "vocabulary:\n field: a\n values: closed\n\
816 terms:\n public:\n tint: green\n",
817 );
818 assert_eq!(
819 kinds_of(&findings),
820 vec![FindingKind::TintUnreadable {
821 spelling: "green".into()
822 }]
823 );
824 assert_eq!(findings[0].at, "terms.public.tint");
825 assert!(!findings[0].is_error());
826 // Not text at all is the same finding.
827 assert_eq!(
828 kinds("vocabulary:\n field: a\nterms:\n public:\n tint: 3\n"),
829 vec![FindingKind::TintUnreadable {
830 spelling: "3".into()
831 }]
832 );
833 }
834
835 #[test]
836 fn a_term_body_that_is_not_a_mapping_is_dropped_whole() {
837 // `public: Anyone` reads as a bare live term; the author meant a
838 // description and nothing says otherwise.
839 assert_eq!(
840 kinds("vocabulary:\n field: a\n values: closed\nterms:\n public: Anyone\n"),
841 vec![FindingKind::TermSpecIgnored]
842 );
843 // The two documented bare spellings stay silent.
844 assert_eq!(
845 lint("vocabulary:\n field: a\n values: closed\nterms:\n a:\n b: {}\n"),
846 Vec::new()
847 );
848 }
849
850 #[test]
851 fn terms_differing_only_by_case_are_two_values_a_reader_cannot_tell_apart() {
852 let findings =
853 lint("vocabulary:\n field: a\n values: closed\nterms:\n Public:\n public:\n");
854 assert_eq!(
855 kinds_of(&findings),
856 vec![FindingKind::CaseOnlyDuplicate {
857 other: "Public".into()
858 }]
859 );
860 // Reported against the later one, which is the one being added.
861 assert_eq!(findings[0].at, "terms.public");
862 assert!(!findings[0].is_error());
863 }
864
865 #[test]
866 fn an_exact_duplicate_is_not_also_reported_as_a_case_collision() {
867 assert_eq!(
868 kinds("vocabulary:\n field: a\n values: open\nterms:\n x:\n x:\n"),
869 vec![FindingKind::DuplicateTerm {
870 disagree_retired: false
871 }]
872 );
873 }
874
875 #[test]
876 fn an_empty_field_loads_and_then_cannot_be_named() {
877 let findings = lint("vocabulary:\n field: \"\"\n values: open\nterms:\n x:\n");
878 assert_eq!(kinds_of(&findings), vec![FindingKind::FieldEmpty]);
879 assert!(findings[0].is_error());
880 }
881
882 #[test]
883 fn every_finding_renders_a_sentence() {
884 // `Display` is what the CLI prints. The match is exhaustive, so a new
885 // kind cannot be *missed*; what this catches is one added with an empty
886 // or placeholder sentence, which would ship a blank bullet to a
887 // terminal and compile perfectly.
888 for kind in [
889 FindingKind::NotAVocabulary,
890 FindingKind::FieldEmpty,
891 FindingKind::ValuesUnreadable {
892 spelling: "x".into(),
893 },
894 FindingKind::TermKeyNotAString,
895 FindingKind::RetiredUnreadable {
896 spelling: "x".into(),
897 },
898 FindingKind::DuplicateTerm {
899 disagree_retired: true,
900 },
901 FindingKind::DuplicateTerm {
902 disagree_retired: false,
903 },
904 FindingKind::NoTerms { closed: true },
905 FindingKind::NoTerms { closed: false },
906 FindingKind::NothingOffered,
907 FindingKind::UnknownKey { key: "x".into() },
908 FindingKind::TintNotRead,
909 FindingKind::TintUnreadable {
910 spelling: "x".into(),
911 },
912 FindingKind::NotAString { key: "x".into() },
913 FindingKind::TermSpecIgnored,
914 FindingKind::CaseOnlyDuplicate { other: "x".into() },
915 FindingKind::FieldDisagrees { field: "x".into() },
916 FindingKind::GuardWithoutTerm { value: "x".into() },
917 FindingKind::IncludedTwice,
918 FindingKind::Shadowed { by: "x".into() },
919 ] {
920 let rendered = finding(kind.clone(), "at").to_string();
921 assert!(rendered.len() > 20, "{kind:?} renders only {rendered:?}");
922 assert_ne!(rendered, format!("{kind:?}"), "{kind:?} renders as itself");
923 }
924 }
925
926 fn kinds_of(findings: &[Finding]) -> Vec<FindingKind> {
927 findings.iter().map(|f| f.kind.clone()).collect()
928 }
929}