1use std::fmt;
22
23use fig::Value;
24
25use crate::present::Tint;
26
27#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct Term {
43 pub value: String,
45 pub label: Option<String>,
47 pub description: Option<String>,
49 pub retired: bool,
54 pub tint: Option<Tint>,
56}
57
58impl Term {
59 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 pub fn label(mut self, label: impl Into<String>) -> Self {
72 self.label = Some(label.into());
73 self
74 }
75
76 pub fn label_opt(mut self, label: Option<impl Into<String>>) -> Self {
78 self.label = label.map(Into::into);
79 self
80 }
81
82 pub fn description(mut self, description: impl Into<String>) -> Self {
84 self.description = Some(description.into());
85 self
86 }
87
88 pub fn description_opt(mut self, description: Option<impl Into<String>>) -> Self {
90 self.description = description.map(Into::into);
91 self
92 }
93
94 pub fn retired(mut self, retired: bool) -> Self {
96 self.retired = retired;
97 self
98 }
99
100 pub fn tint(mut self, tint: impl Into<Option<Tint>>) -> Self {
102 self.tint = tint.into();
103 self
104 }
105
106 pub fn display_label(&self) -> &str {
109 self.label.as_deref().unwrap_or(&self.value)
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Cardinality {
119 One,
120 Many,
121}
122
123#[derive(Debug, Clone, PartialEq)]
130#[non_exhaustive]
131pub struct VocabularyDoc {
132 pub field: String,
134 pub closed: bool,
140 pub terms: Vec<Term>,
142}
143
144impl VocabularyDoc {
145 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
155pub 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
184pub(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 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#[derive(Debug, Clone, PartialEq, Eq)]
229#[non_exhaustive]
230pub struct Issue {
231 pub kind: IssueKind,
233 pub value: String,
235 pub suggestion: Option<String>,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
246#[non_exhaustive]
247pub enum IssueKind {
248 Unknown,
250 Retired,
252 Custom(String),
255 Unchecked(String),
266}
267
268impl Issue {
269 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 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 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 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 pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
310 self.suggestion = Some(suggestion.into());
311 self
312 }
313
314 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#[derive(Debug, Clone, PartialEq, Eq)]
344pub enum Validation {
345 Ok,
347 Warn(Issue),
350 Reject(Issue),
352}
353
354impl Validation {
355 pub fn is_ok(&self) -> bool {
357 matches!(self, Validation::Ok)
358 }
359
360 pub fn is_reject(&self) -> bool {
362 matches!(self, Validation::Reject(_))
363 }
364
365 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 fn rank(&self) -> u8 {
375 match self {
376 Validation::Ok => 0,
377 Validation::Warn(_) => 1,
378 Validation::Reject(_) => 2,
379 }
380 }
381}
382
383pub trait Validate {
415 fn validate(&self, value: &Value) -> Validation;
417}
418
419pub 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
447fn 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
466fn 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 .map(|(t, _)| t.value.clone())
484}
485
486fn suggestion_budget(len: usize) -> usize {
491 match len {
492 0..=2 => 0,
493 3..=4 => 1,
494 _ => 2,
495 }
496}
497
498fn 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 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 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 let warned = Value::Seq(vec![Value::Str("archived".into())]);
602 assert!(matches!(
603 validate_enum(&terms, true, &warned),
604 Validation::Warn(_)
605 ));
606 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 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 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 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}