Skip to main content

fig_schema/
vocab.rs

1//! Controlled vocabularies, the generic validation seam, and loading a term
2//! set from its document.
3//!
4//! This module knows what a vocabulary *term* is and how to check a value
5//! against a list of them ([`validate_enum`]) — that's the whole of what's
6//! genuinely value-shape about a "constraint". It deliberately does not define
7//! the constraint type a rule carries: whether a field's constraint is "a
8//! controlled vocabulary" or something else entirely (a reference into a
9//! workspace, a range, a pattern) is the embedder's call, expressed as its own
10//! type that implements [`Validate`]. See [`crate::FieldRule`]. (The crate's
11//! own [`Constraint`](crate::Constraint), in the loader, is what a *document*
12//! loads as, and an embedder maps it into its own type from there.)
13//!
14//! It also knows how to load a [`Term`] list from a document ([`parse_vocabulary`]):
15//! the `vocabulary: { field, values }` / `terms:` convention is common enough
16//! across embedders (a frontmatter engine's controlled fields, a batch
17//! renderer's metadata-driven config) that parsing it once here lets them
18//! share the same vocabulary document instead of each hand-rolling the same
19//! parse.
20
21use std::fmt;
22
23use fig::Value;
24
25use crate::present::Tint;
26
27/// One term of a controlled vocabulary.
28///
29/// `#[non_exhaustive]`: a term gains display and lifecycle facets over time, so
30/// it is built from [`Term::value`] and the chainable setters rather than a
31/// struct literal. Reading the fields is unchanged.
32///
33/// ```
34/// use fig_schema::Term;
35///
36/// let t = Term::value("archived").label("Archived").retired(true);
37/// assert_eq!(t.display_label(), "Archived");
38/// assert!(t.retired);
39/// ```
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct Term {
43    /// The stored value.
44    pub value: String,
45    /// A human display label (defaults to `value` — see [`Term::display_label`]).
46    pub label: Option<String>,
47    /// A human gloss / help text.
48    pub description: Option<String>,
49    /// Known but no longer offered: still valid where already present, excluded
50    /// from the picker's offered set. Validating one yields [`Validation::Warn`]
51    /// rather than [`Validation::Reject`], even under a closed vocabulary — see
52    /// [`validate_enum`].
53    pub retired: bool,
54    /// A per-value tint (e.g. `public` = positive/green).
55    pub tint: Option<Tint>,
56}
57
58impl Term {
59    /// A bare live term with just a value.
60    pub fn value(v: impl Into<String>) -> Self {
61        Self {
62            value: v.into(),
63            label: None,
64            description: None,
65            retired: false,
66            tint: None,
67        }
68    }
69
70    /// Set the display label.
71    pub fn label(mut self, label: impl Into<String>) -> Self {
72        self.label = Some(label.into());
73        self
74    }
75
76    /// Set the display label from an optional one. `None` leaves it unset.
77    pub fn label_opt(mut self, label: Option<impl Into<String>>) -> Self {
78        self.label = label.map(Into::into);
79        self
80    }
81
82    /// Set the human gloss.
83    pub fn description(mut self, description: impl Into<String>) -> Self {
84        self.description = Some(description.into());
85        self
86    }
87
88    /// Set the human gloss from an optional one. `None` leaves it unset.
89    pub fn description_opt(mut self, description: Option<impl Into<String>>) -> Self {
90        self.description = description.map(Into::into);
91        self
92    }
93
94    /// Mark the term [retired](Term::retired) — known, but no longer offered.
95    pub fn retired(mut self, retired: bool) -> Self {
96        self.retired = retired;
97        self
98    }
99
100    /// Set the per-value tint. Takes a [`Tint`] or an `Option<Tint>`.
101    pub fn tint(mut self, tint: impl Into<Option<Tint>>) -> Self {
102        self.tint = tint.into();
103        self
104    }
105
106    /// The text to display for this term: [`Term::label`] if set, otherwise the
107    /// stored [`Term::value`].
108    pub fn display_label(&self) -> &str {
109        self.label.as_deref().unwrap_or(&self.value)
110    }
111}
112
113/// Whether a reference or list-shaped field holds one entry or many. Pure data
114/// shape — reused by an embedder's own reference/relation constraint (prov's
115/// `spanning`/`cardinality` concepts, for instance) without this crate needing
116/// to know what a "relation" is.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Cardinality {
119    One,
120    Many,
121}
122
123/// A controlled vocabulary loaded from its own document: the `field` it
124/// governs, whether its value set is closed, and the terms themselves — ready
125/// to hand to [`validate_enum`].
126///
127/// `#[non_exhaustive]`: the document convention can gain declared facts, so
128/// build one with [`VocabularyDoc::new`]. Reading the fields is unchanged.
129#[derive(Debug, Clone, PartialEq)]
130#[non_exhaustive]
131pub struct VocabularyDoc {
132    /// The field this vocabulary governs (`audience`, `tags`).
133    pub field: String,
134    /// Whether the value set is closed (an unknown value is a hard
135    /// [`Validation::Reject`]) or open (a folksonomy — an unknown value only
136    /// [`Validation::Warn`]s, as a possible typo). Any `values` spelling other
137    /// than `"closed"` is open, matching [`validate_enum`]'s own permissive
138    /// default.
139    pub closed: bool,
140    /// The declared terms, in declaration order.
141    pub terms: Vec<Term>,
142}
143
144impl VocabularyDoc {
145    /// A vocabulary declared in code rather than loaded from a document.
146    pub fn new(field: impl Into<String>, closed: bool, terms: Vec<Term>) -> Self {
147        Self {
148            field: field.into(),
149            closed,
150            terms,
151        }
152    }
153}
154
155/// Parse a vocabulary document from its top-level value: a `vocabulary: {
156/// field, values }` marker plus a `terms:` mapping, each entry either a bare
157/// key (a live term with no metadata) or a `{ label?, description?, retired?
158/// }` mapping. Returns `None` when `value` carries no `vocabulary` marker —
159/// i.e. it is not a vocabulary document.
160///
161/// This is the shared file-format half of a controlled vocabulary: [`Term`]
162/// and [`validate_enum`] already say how to *check* a value; this says how to
163/// *load* the term set a document declares, so two independent embedders (a
164/// frontmatter engine, a batch renderer) can point at the same vocabulary
165/// document without either depending on the other.
166///
167/// Key lookup is [`Value::get`], so a duplicated key resolves last-wins, the
168/// same way fig itself reads one. A duplicated *term* is not a lookup and
169/// yields two [`Term`]s with the same value, in declaration order.
170///
171/// A term's `tint` is read, by [`Tint::from_name`]; a spelling that names no
172/// tint is no tint, which [`lint_vocabulary`](crate::lint_vocabulary) notes.
173pub fn parse_vocabulary(value: &Value) -> Option<VocabularyDoc> {
174    let marker = value.get("vocabulary")?;
175    let field = marker.get("field")?.as_str()?.to_string();
176    let closed = marker.get("values").and_then(Value::as_str) == Some("closed");
177    Some(VocabularyDoc {
178        field,
179        closed,
180        terms: parse_terms(value),
181    })
182}
183
184/// The `terms:` mapping of `container` as [`Term`]s — the half of
185/// [`parse_vocabulary`] a vocabulary written inline in a schema rule shares
186/// with a vocabulary document. No `terms`, or one that is not a mapping, is no
187/// terms.
188pub(crate) fn parse_terms(container: &Value) -> Vec<Term> {
189    let mut terms = Vec::new();
190    if let Some(entries) = container.get("terms").and_then(Value::as_mapping) {
191        for (key, spec) in entries {
192            let Some(name) = key.as_str() else { continue };
193            // A bare `term:` (null/scalar spec) has no keys to read, so every
194            // lookup below misses and it comes out a live term with no
195            // metadata — the same shape `Term::value` builds.
196            terms.push(Term {
197                value: name.to_string(),
198                label: spec
199                    .get("label")
200                    .and_then(Value::as_str)
201                    .map(str::to_string),
202                description: spec
203                    .get("description")
204                    .and_then(Value::as_str)
205                    .map(str::to_string),
206                retired: spec.get("retired").and_then(Value::as_bool) == Some(true),
207                tint: spec
208                    .get("tint")
209                    .and_then(Value::as_str)
210                    .and_then(Tint::from_name),
211            });
212        }
213    }
214    terms
215}
216
217/// Why a value failed to validate.
218///
219/// Structured rather than pre-rendered, for the same reason [`crate::Presentation`]
220/// carries semantic hints rather than colours: the embedder owns presentation.
221/// A frontend can localize the text, or offer [`Issue::suggestion`] as a
222/// one-tap correction instead of prose. [`Display`](std::fmt::Display) renders
223/// the English default.
224///
225/// `#[non_exhaustive]`: an issue can gain context (a span, a source) without
226/// costing downstream a major. Build one with [`Issue::unknown`],
227/// [`Issue::retired`] or [`Issue::custom`]; reading the fields is unchanged.
228#[derive(Debug, Clone, PartialEq, Eq)]
229#[non_exhaustive]
230pub struct Issue {
231    /// What went wrong.
232    pub kind: IssueKind,
233    /// The offending value, as text.
234    pub value: String,
235    /// A near miss from the vocabulary, when one is close enough to be worth
236    /// offering.
237    pub suggestion: Option<String>,
238}
239
240/// The kind of an [`Issue`].
241///
242/// `#[non_exhaustive]`: new failure kinds get their own variant as the crate
243/// grows, so a `match` needs a `_` arm. [`IssueKind::Custom`] already carries
244/// anything an embedder defines.
245#[derive(Debug, Clone, PartialEq, Eq)]
246#[non_exhaustive]
247pub enum IssueKind {
248    /// Not a member of the vocabulary.
249    Unknown,
250    /// A member, but [retired](Term::retired).
251    Retired,
252    /// An embedder-defined issue (a dangling reference, a range violation, …),
253    /// carrying its own rendered message.
254    Custom(String),
255    /// The value was not checked at all, because the constraint is of a kind
256    /// this validator does not know — named here, so a reader can say which.
257    ///
258    /// Always carried by a [`Validation::Reject`], never a
259    /// [`Validation::Warn`]: a validator that skipped a rule cannot answer
260    /// "valid", so it fails closed, and an editor that does not know the kind
261    /// must not commit the value. What this variant adds is that a reader who
262    /// *does* know it can tell *unchecked* from *wrong* — `fig-schema check`
263    /// files one under its own heading, and exits 3 rather than 1 when nothing
264    /// else is amiss. See [`Issue::unchecked`].
265    Unchecked(String),
266}
267
268impl Issue {
269    /// A value that is not in the vocabulary.
270    pub fn unknown(value: impl Into<String>) -> Self {
271        Self {
272            kind: IssueKind::Unknown,
273            value: value.into(),
274            suggestion: None,
275        }
276    }
277
278    /// A value that is in the vocabulary but [retired](Term::retired).
279    pub fn retired(value: impl Into<String>) -> Self {
280        Self {
281            kind: IssueKind::Retired,
282            value: value.into(),
283            suggestion: None,
284        }
285    }
286
287    /// An embedder-defined issue with its own message.
288    pub fn custom(value: impl Into<String>, message: impl Into<String>) -> Self {
289        Self {
290            kind: IssueKind::Custom(message.into()),
291            value: value.into(),
292            suggestion: None,
293        }
294    }
295
296    /// A value that could not be checked, because its constraint is of a
297    /// `kind` this validator does not know. Wrap it in [`Validation::Reject`]
298    /// — the fail-closed half of the rule is the caller's — and see
299    /// [`IssueKind::Unchecked`] for the other half.
300    pub fn unchecked(value: impl Into<String>, kind: impl Into<String>) -> Self {
301        Self {
302            kind: IssueKind::Unchecked(kind.into()),
303            value: value.into(),
304            suggestion: None,
305        }
306    }
307
308    /// Attach a near-miss suggestion.
309    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
310        self.suggestion = Some(suggestion.into());
311        self
312    }
313
314    /// Whether this says the value was *not checked* rather than that it is
315    /// wrong — see [`IssueKind::Unchecked`]. A rejection carrying one is still
316    /// a rejection; this is how a reader that wants to report the two
317    /// differently tells them apart.
318    pub fn is_unchecked(&self) -> bool {
319        matches!(self.kind, IssueKind::Unchecked(_))
320    }
321}
322
323impl fmt::Display for Issue {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        match &self.kind {
326            IssueKind::Custom(message) => f.write_str(message)?,
327            IssueKind::Unknown => write!(f, "“{}” is not a known value", self.value)?,
328            IssueKind::Retired => write!(f, "“{}” is retired and no longer offered", self.value)?,
329            IssueKind::Unchecked(kind) => write!(
330                f,
331                "a “{kind}” constraint, which this validator cannot check"
332            )?,
333        }
334        if let Some(suggestion) = &self.suggestion {
335            write!(f, " — did you mean “{suggestion}”?")?;
336        }
337        Ok(())
338    }
339}
340
341/// The result of validating a value against a field's constraint at commit
342/// time.
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub enum Validation {
345    /// The value is fine — apply it.
346    Ok,
347    /// A soft warning (an open vocabulary's unknown value, or a retired term);
348    /// apply, but surface it.
349    Warn(Issue),
350    /// A hard rejection (a closed vocabulary's unknown value); do not apply.
351    Reject(Issue),
352}
353
354impl Validation {
355    /// Whether the value passed cleanly, with nothing to surface.
356    pub fn is_ok(&self) -> bool {
357        matches!(self, Validation::Ok)
358    }
359
360    /// Whether the value must not be applied.
361    pub fn is_reject(&self) -> bool {
362        matches!(self, Validation::Reject(_))
363    }
364
365    /// The issue behind a warning or rejection, if any.
366    pub fn issue(&self) -> Option<&Issue> {
367        match self {
368            Validation::Ok => None,
369            Validation::Warn(issue) | Validation::Reject(issue) => Some(issue),
370        }
371    }
372
373    /// Severity order, for picking the worst result across a sequence.
374    fn rank(&self) -> u8 {
375        match self {
376            Validation::Ok => 0,
377            Validation::Warn(_) => 1,
378            Validation::Reject(_) => 2,
379        }
380    }
381}
382
383/// A field constraint that knows how to check a candidate value. An embedder
384/// implements this on its own constraint type (an enum with a vocabulary
385/// variant, a reference variant, whatever it needs); [`crate::FieldRule::validate`]
386/// dispatches to it generically.
387///
388/// ```
389/// use fig::Value;
390/// use fig_schema::{Term, Validate, Validation, validate_enum};
391///
392/// // The embedder's own constraint type — this crate never sees its shape.
393/// enum Constraint {
394///     Enum { values: Vec<Term>, closed: bool },
395///     Ref,
396/// }
397///
398/// impl Validate for Constraint {
399///     fn validate(&self, value: &Value) -> Validation {
400///         match self {
401///             Constraint::Enum { values, closed } => validate_enum(values, *closed, value),
402///             Constraint::Ref => Validation::Ok, // resolved against the workspace
403///         }
404///     }
405/// }
406///
407/// let visibility = Constraint::Enum {
408///     values: vec![Term::value("public"), Term::value("private")],
409///     closed: true,
410/// };
411/// assert!(visibility.validate(&Value::Str("public".into())).is_ok());
412/// assert!(visibility.validate(&Value::Str("secret".into())).is_reject());
413/// ```
414pub trait Validate {
415    /// Check `value` against this constraint.
416    fn validate(&self, value: &Value) -> Validation;
417}
418
419/// Validate `value` against a controlled vocabulary — the reusable logic
420/// behind any embedder's vocabulary-shaped constraint.
421///
422/// A sequence is validated element-wise, so a rule declared on a list field
423/// itself governs its items just as one declared with
424/// [`PathPat::each_item_of`](crate::PathPat::each_item_of) does; the most
425/// severe element result wins. Any other shape (a mapping, a number under an
426/// enum field) is left to the caller's own backstop — fig's reparse, typically.
427///
428/// A [retired](Term::retired) term warns rather than rejects: it is still a
429/// *known* value, so a document that already holds one stays committable.
430pub fn validate_enum(values: &[Term], closed: bool, value: &Value) -> Validation {
431    match value {
432        Value::Str(s) => validate_term(values, closed, s),
433        Value::Seq(items) => {
434            let mut worst = Validation::Ok;
435            for item in items {
436                let result = validate_enum(values, closed, item);
437                if result.rank() > worst.rank() {
438                    worst = result;
439                }
440            }
441            worst
442        }
443        _ => Validation::Ok,
444    }
445}
446
447/// Validate one string against the vocabulary.
448fn validate_term(values: &[Term], closed: bool, s: &str) -> Validation {
449    if values.iter().any(|t| !t.retired && t.value == s) {
450        return Validation::Ok;
451    }
452    if values.iter().any(|t| t.retired && t.value == s) {
453        return Validation::Warn(Issue::retired(s));
454    }
455    let mut issue = Issue::unknown(s);
456    if let Some(near) = nearest_term(values, s) {
457        issue = issue.with_suggestion(near);
458    }
459    if closed {
460        Validation::Reject(issue)
461    } else {
462        Validation::Warn(issue)
463    }
464}
465
466/// The live term closest to `value` by a small edit distance, compared
467/// case-insensitively — a lightweight near-miss suggestion. Declaration order
468/// breaks ties.
469fn nearest_term(terms: &[Term], value: &str) -> Option<String> {
470    let lower = value.to_lowercase();
471    let value_len = lower.chars().count();
472    terms
473        .iter()
474        .filter(|t| !t.retired)
475        .filter_map(|t| {
476            let candidate = t.value.to_lowercase();
477            let distance = edit_distance(&candidate, &lower);
478            let budget = suggestion_budget(candidate.chars().count().min(value_len));
479            (distance <= budget).then_some((t, distance))
480        })
481        .min_by_key(|(_, distance)| *distance)
482        // Only the winner is cloned; the vocabulary itself is left untouched.
483        .map(|(t, _)| t.value.clone())
484}
485
486/// How many typos still count as a near miss, for a word of `len` characters.
487/// Scaled to the *shorter* of the two words being compared: at a flat two
488/// typos every two-letter string is a near miss for every other, so a short
489/// vocabulary would otherwise suggest nonsense ("hi" → did you mean "no"?).
490fn suggestion_budget(len: usize) -> usize {
491    match len {
492        0..=2 => 0,
493        3..=4 => 1,
494        _ => 2,
495    }
496}
497
498/// Levenshtein distance — a tiny dependency-free implementation for near-miss
499/// suggestions (the vocabulary sets here are small).
500fn edit_distance(a: &str, b: &str) -> usize {
501    let a: Vec<char> = a.chars().collect();
502    let b: Vec<char> = b.chars().collect();
503    let mut prev: Vec<usize> = (0..=b.len()).collect();
504    let mut cur = vec![0usize; b.len() + 1];
505    for (i, &ca) in a.iter().enumerate() {
506        cur[0] = i + 1;
507        for (j, &cb) in b.iter().enumerate() {
508            let cost = if ca == cb { 0 } else { 1 };
509            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
510        }
511        std::mem::swap(&mut prev, &mut cur);
512    }
513    prev[b.len()]
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    #[test]
521    fn closed_vocabulary_rejects_unknown_accepts_known() {
522        let terms = vec![Term::value("public"), Term::value("private")];
523        assert_eq!(
524            validate_enum(&terms, true, &Value::Str("public".into())),
525            Validation::Ok
526        );
527        assert!(validate_enum(&terms, true, &Value::Str("familly".into())).is_reject());
528    }
529
530    #[test]
531    fn open_vocabulary_warns_with_a_near_miss() {
532        let terms = vec![Term::value("todo"), Term::value("done")];
533        let Validation::Warn(issue) = validate_enum(&terms, false, &Value::Str("todi".into()))
534        else {
535            panic!("expected a near-miss warning");
536        };
537        assert_eq!(issue.kind, IssueKind::Unknown);
538        assert_eq!(issue.suggestion.as_deref(), Some("todo"));
539    }
540
541    #[test]
542    fn a_closed_rejection_still_carries_a_suggestion() {
543        let terms = vec![Term::value("public"), Term::value("private")];
544        let Validation::Reject(issue) = validate_enum(&terms, true, &Value::Str("privat".into()))
545        else {
546            panic!("expected a rejection");
547        };
548        assert_eq!(issue.suggestion.as_deref(), Some("private"));
549    }
550
551    #[test]
552    fn retired_term_warns_rather_than_rejecting() {
553        // A document already holding a retired value stays committable: the
554        // term is known, merely no longer offered.
555        let terms = vec![Term::value("active"), Term::value("archived").retired(true)];
556        assert_eq!(
557            validate_enum(&terms, true, &Value::Str("active".into())),
558            Validation::Ok
559        );
560        let result = validate_enum(&terms, true, &Value::Str("archived".into()));
561        assert_eq!(result.issue().map(|i| &i.kind), Some(&IssueKind::Retired));
562        assert!(!result.is_reject());
563    }
564
565    #[test]
566    fn a_retired_term_is_never_suggested() {
567        let terms = vec![Term::value("archived").retired(true)];
568        let result = validate_enum(&terms, false, &Value::Str("archivd".into()));
569        assert_eq!(result.issue().and_then(|i| i.suggestion.as_deref()), None);
570    }
571
572    #[test]
573    fn short_terms_do_not_produce_nonsense_suggestions() {
574        // Two typos apart is the whole of a two-letter word.
575        let terms = vec![Term::value("no")];
576        let result = validate_enum(&terms, false, &Value::Str("hi".into()));
577        assert_eq!(result.issue().and_then(|i| i.suggestion.as_deref()), None);
578
579        let terms = vec![Term::value("a")];
580        let result = validate_enum(&terms, false, &Value::Str("zz".into()));
581        assert_eq!(result.issue().and_then(|i| i.suggestion.as_deref()), None);
582    }
583
584    #[test]
585    fn a_rule_on_the_list_itself_validates_each_item() {
586        let terms = vec![Term::value("public")];
587        let seq = Value::Seq(vec![
588            Value::Str("public".into()),
589            Value::Str("bogus".into()),
590        ]);
591        assert!(validate_enum(&terms, true, &seq).is_reject());
592
593        let all_good = Value::Seq(vec![Value::Str("public".into())]);
594        assert_eq!(validate_enum(&terms, true, &all_good), Validation::Ok);
595    }
596
597    #[test]
598    fn the_most_severe_element_result_wins() {
599        let terms = vec![Term::value("active"), Term::value("archived").retired(true)];
600        // A retired item alone warns...
601        let warned = Value::Seq(vec![Value::Str("archived".into())]);
602        assert!(matches!(
603            validate_enum(&terms, true, &warned),
604            Validation::Warn(_)
605        ));
606        // ...but an unknown item alongside it rejects the whole sequence.
607        let rejected = Value::Seq(vec![
608            Value::Str("archived".into()),
609            Value::Str("xyz".into()),
610        ]);
611        assert!(validate_enum(&terms, true, &rejected).is_reject());
612    }
613
614    #[test]
615    fn a_non_string_scalar_is_left_to_the_callers_backstop() {
616        let terms = vec![Term::value("public")];
617        assert_eq!(validate_enum(&terms, true, &Value::Int(3)), Validation::Ok);
618    }
619
620    #[test]
621    fn case_folding_is_not_ascii_only() {
622        let terms = vec![Term::value("Öffentlich")];
623        let result = validate_enum(&terms, false, &Value::Str("ÖFFENTLICH".into()));
624        assert_eq!(
625            result.issue().and_then(|i| i.suggestion.as_deref()),
626            Some("Öffentlich")
627        );
628    }
629
630    #[test]
631    fn issue_renders_an_english_default() {
632        assert_eq!(
633            Issue::unknown("xyz").to_string(),
634            "“xyz” is not a known value"
635        );
636        assert_eq!(
637            Issue::unknown("privat")
638                .with_suggestion("private")
639                .to_string(),
640            "“privat” is not a known value — did you mean “private”?"
641        );
642        assert_eq!(
643            Issue::retired("archived").to_string(),
644            "“archived” is retired and no longer offered"
645        );
646        assert_eq!(
647            Issue::custom("../nope", "no such note").to_string(),
648            "no such note"
649        );
650        assert_eq!(
651            Issue::unchecked("../note.md", "workspace-reference").to_string(),
652            "a “workspace-reference” constraint, which this validator cannot check"
653        );
654    }
655
656    #[test]
657    fn an_unchecked_issue_is_told_apart_from_a_wrong_one() {
658        let unchecked = Issue::unchecked("x", "workspace-reference");
659        assert!(unchecked.is_unchecked());
660        assert_eq!(
661            unchecked.kind,
662            IssueKind::Unchecked("workspace-reference".into())
663        );
664        assert!(!Issue::unknown("x").is_unchecked());
665        assert!(!Issue::custom("x", "no").is_unchecked());
666        // Still a rejection, because a validator that skipped a rule cannot
667        // answer "valid" — the fail-closed half of the rule.
668        assert!(Validation::Reject(unchecked).is_reject());
669    }
670
671    #[test]
672    fn display_label_falls_back_to_the_stored_value() {
673        assert_eq!(Term::value("public").display_label(), "public");
674        assert_eq!(
675            Term::value("public").label("Everyone").display_label(),
676            "Everyone"
677        );
678    }
679
680    fn parse(yaml: &str) -> Option<VocabularyDoc> {
681        let doc = fig::Document::parse(yaml.as_bytes(), fig_yaml::format().unwrap()).unwrap();
682        parse_vocabulary(&doc.to_value().unwrap())
683    }
684
685    #[test]
686    fn parses_a_closed_vocabulary_and_validates_against_it() {
687        let v = parse(
688            "vocabulary:\n  field: audience\n  values: closed\n\
689             terms:\n  public:\n    description: Anyone\n  friends: {}\n",
690        )
691        .expect("a vocabulary document");
692        assert_eq!(v.field, "audience");
693        assert!(v.closed);
694        assert_eq!(
695            v.terms
696                .iter()
697                .find(|t| t.value == "public")
698                .and_then(|t| t.description.as_deref()),
699            Some("Anyone")
700        );
701        assert!(validate_enum(&v.terms, v.closed, &Value::Str("public".into())).is_ok());
702        assert!(validate_enum(&v.terms, v.closed, &Value::Str("colleagues".into())).is_reject());
703    }
704
705    #[test]
706    fn an_open_vocabulary_warns_rather_than_rejects() {
707        let v =
708            parse("vocabulary:\n  field: tags\n  values: open\nterms:\n  todo: {}\n  done: {}\n")
709                .expect("a vocabulary document");
710        assert!(!v.closed);
711        let result = validate_enum(&v.terms, v.closed, &Value::Str("todi".into()));
712        assert!(matches!(result, Validation::Warn(_)));
713    }
714
715    #[test]
716    fn a_retired_term_is_known_but_not_accepted() {
717        let v = parse(
718            "vocabulary:\n  field: status\n  values: closed\n\
719             terms:\n  active: {}\n  archived_2024:\n    retired: true\n",
720        )
721        .expect("a vocabulary document");
722        assert!(validate_enum(&v.terms, v.closed, &Value::Str("active".into())).is_ok());
723        let result = validate_enum(&v.terms, v.closed, &Value::Str("archived_2024".into()));
724        assert_eq!(result.issue().map(|i| &i.kind), Some(&IssueKind::Retired));
725        assert!(!result.is_reject());
726    }
727
728    #[test]
729    fn a_bare_term_entry_is_a_live_term_with_no_metadata() {
730        let v = parse("vocabulary:\n  field: status\n  values: open\nterms:\n  active:\n")
731            .expect("a vocabulary document");
732        let t = v.terms.iter().find(|t| t.value == "active").unwrap();
733        assert_eq!(t.label, None);
734        assert_eq!(t.description, None);
735        assert!(!t.retired);
736    }
737
738    #[test]
739    fn a_duplicated_key_resolves_last_wins_the_way_fig_reads_it() {
740        // fig's own `Value::get` is last-wins on duplicates. This crate used to
741        // hand-roll a first-wins lookup, so it disagreed with fig about what
742        // the same bytes said.
743        let v = parse(
744            "vocabulary:\n  field: audience\n  field: tags\n  values: closed\nterms:\n  a:\n",
745        )
746        .expect("a vocabulary document");
747        assert_eq!(v.field, "tags");
748    }
749
750    #[test]
751    fn a_duplicated_term_is_not_a_lookup_and_stays_twice() {
752        // Terms are iterated, not looked up, so both survive in declaration
753        // order — a picker would offer the value twice.
754        let v = parse("vocabulary:\n  field: status\n  values: open\nterms:\n  a:\n  a:\n")
755            .expect("a vocabulary document");
756        assert_eq!(v.terms.iter().filter(|t| t.value == "a").count(), 2);
757    }
758
759    #[test]
760    fn a_document_without_the_marker_is_not_a_vocabulary() {
761        assert!(parse("title: Notes\n").is_none());
762    }
763
764    #[test]
765    fn a_terms_tint_is_read_and_an_unknown_spelling_is_none() {
766        let v = parse(
767            "vocabulary:\n  field: audience\nterms:\n  public:\n    tint: positive\n\
768             \x20 odd:\n    tint: green\n  plain: {}\n",
769        )
770        .expect("a vocabulary document");
771        assert_eq!(v.terms[0].tint, Some(Tint::Positive));
772        assert_eq!(v.terms[1].tint, None);
773        assert_eq!(v.terms[2].tint, None);
774    }
775}