1use std::collections::{BTreeMap, BTreeSet};
26use std::fmt;
27use std::path::{Path, PathBuf};
28
29use fig::Value;
30
31use crate::consequence::{Consequence, Severity};
32use crate::field::{FieldRule, FieldType, Origin, Schema};
33use crate::lint::{
34 Finding, FindingKind, finding, lint_terms, lint_values, lint_vocabulary, sketch, unknown_keys,
35};
36use crate::path::{PathPat, PatternError, SegPat};
37use crate::present::{Icon, Presentation, Tint};
38use crate::vocab::{
39 Issue, Term, Validate, Validation, VocabularyDoc, parse_terms, parse_vocabulary, validate_enum,
40};
41
42#[derive(Debug, Clone, PartialEq)]
57#[non_exhaustive]
58pub enum Constraint {
59 Vocabulary {
61 terms: Vec<Term>,
63 closed: bool,
66 },
67 Other {
73 kind: String,
75 spec: Value,
78 },
79}
80
81impl Constraint {
82 pub fn kind(&self) -> &str {
85 match self {
86 Constraint::Vocabulary { .. } => "vocabulary",
87 Constraint::Other { kind, .. } => kind,
88 }
89 }
90
91 pub fn terms(&self) -> Option<&[Term]> {
94 match self {
95 Constraint::Vocabulary { terms, .. } => Some(terms),
96 Constraint::Other { .. } => None,
97 }
98 }
99}
100
101impl Validate for Constraint {
102 fn validate(&self, value: &Value) -> Validation {
103 match self {
104 Constraint::Vocabulary { terms, closed } => validate_enum(terms, *closed, value),
105 Constraint::Other { kind, .. } => {
106 Validation::Reject(Issue::unchecked(sketch(value), kind))
107 }
108 }
109 }
110}
111
112impl fmt::Display for Constraint {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 match self {
117 Constraint::Vocabulary { terms, closed } => {
118 let retired = terms.iter().filter(|t| t.retired).count();
119 write!(
120 f,
121 "vocabulary, {}, {} term{}",
122 if *closed { "closed" } else { "open" },
123 terms.len(),
124 if terms.len() == 1 { "" } else { "s" },
125 )?;
126 if retired > 0 {
127 write!(f, " ({retired} retired)")?;
128 }
129 Ok(())
130 }
131 Constraint::Other { kind, .. } => {
132 write!(f, "{kind} — a kind this crate cannot check")
133 }
134 }
135 }
136}
137
138#[derive(Debug, Clone)]
144#[non_exhaustive]
145pub struct Loaded {
146 pub schema: Schema<Constraint>,
148 pub findings: Vec<Finding>,
153}
154
155#[derive(Debug, Clone, PartialEq)]
161#[non_exhaustive]
162pub struct LoadError {
163 pub document: PathBuf,
166 pub at: String,
169 pub kind: LoadErrorKind,
171}
172
173#[derive(Debug, Clone, PartialEq)]
178#[non_exhaustive]
179pub enum LoadErrorKind {
180 Unreadable {
183 path: PathBuf,
185 message: String,
187 },
188 NotASchema,
191 BothMarkers,
194 SpecUnknown {
196 spelling: String,
198 },
199 Missing {
202 key: String,
204 },
205 EntryIsBoth,
207 NotText {
210 key: String,
212 spelling: String,
214 },
215 NotAMapping {
218 spelling: String,
220 },
221 NotAList {
223 spelling: String,
225 },
226 PatternUnreadable {
229 text: String,
231 error: PatternError,
233 },
234 UnknownType {
236 name: String,
238 suggestion: Option<&'static str>,
240 },
241 UnknownSeverity {
243 spelling: String,
245 },
246 FromAndInline,
248 NotAVocabulary {
250 path: PathBuf,
252 },
253 Cycle {
255 chain: Vec<PathBuf>,
258 },
259}
260
261impl fmt::Display for LoadError {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 write!(f, "{}", self.document.display())?;
264 if !self.at.is_empty() {
265 write!(f, " {}", self.at)?;
266 }
267 write!(f, ": {}", self.kind)
268 }
269}
270
271impl fmt::Display for LoadErrorKind {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 match self {
274 LoadErrorKind::Unreadable { path, message } => {
275 write!(f, "{} could not be read: {message}", path.display())
276 }
277 LoadErrorKind::NotASchema => f.write_str(
278 "neither a `schema` nor a `vocabulary` key at the top level, so this is \
279 not a schema document and not a vocabulary document",
280 ),
281 LoadErrorKind::BothMarkers => f.write_str(
282 "both a `schema` and a `vocabulary` key; a document is one or the other",
283 ),
284 LoadErrorKind::SpecUnknown { spelling } => write!(
285 f,
286 "`spec: {spelling}` is a version of the schema format this crate does not \
287 read; it reads spec 1",
288 ),
289 LoadErrorKind::Missing { key } => write!(f, "`{key}` is missing"),
290 LoadErrorKind::EntryIsBoth => {
291 f.write_str("an entry is a rule (`at`) or an include (`include`), not both")
292 }
293 LoadErrorKind::NotText { key, spelling } => {
294 write!(f, "`{key}: {spelling}` is not text")
295 }
296 LoadErrorKind::NotAMapping { spelling } => {
297 write!(f, "`{spelling}` is not a mapping")
298 }
299 LoadErrorKind::NotAList { spelling } => write!(f, "`{spelling}` is not a list"),
300 LoadErrorKind::PatternUnreadable { text, error } => {
301 write!(f, "`{text}` is not a path pattern: {error}")
302 }
303 LoadErrorKind::UnknownType { name, suggestion } => {
304 write!(f, "`{name}` is not a type this format defines")?;
305 match suggestion {
306 Some(meant) => write!(f, " — did you mean `{meant}`?"),
307 None => f.write_str(
308 " (null, bool, int, float, str, ref, date, datetime, \
309 local-datetime, time, enum, char, map, seq)",
310 ),
311 }
312 }
313 LoadErrorKind::UnknownSeverity { spelling } => write!(
314 f,
315 "`severity: {spelling}` is none of notice, confirm, confirm_explicitly",
316 ),
317 LoadErrorKind::FromAndInline => f.write_str(
318 "a vocabulary is loaded `from` a document or written inline as \
319 `values`/`terms`, not both",
320 ),
321 LoadErrorKind::NotAVocabulary { path } => write!(
322 f,
323 "{} is not a vocabulary document, and `from` names one",
324 path.display()
325 ),
326 LoadErrorKind::Cycle { chain } => {
327 f.write_str("includes form a cycle: ")?;
328 for (i, document) in chain.iter().enumerate() {
329 if i > 0 {
330 f.write_str(" → ")?;
331 }
332 write!(f, "{}", document.display())?;
333 }
334 Ok(())
335 }
336 }
337 }
338}
339
340impl std::error::Error for LoadError {}
341
342const RULE_KEYS: &[&str] = &[
344 "at",
345 "type",
346 "constraint",
347 "title",
348 "description",
349 "icon",
350 "tint",
351 "on_change",
352];
353
354const VOCABULARY_CONSTRAINT_KEYS: &[&str] = &["kind", "from", "values", "terms"];
357
358const CONSEQUENCE_KEYS: &[&str] = &["when", "severity", "message"];
360
361pub fn load_schema<R>(path: impl AsRef<Path>, read: R) -> Result<Loaded, LoadError>
425where
426 R: FnMut(&Path) -> Result<Value, String>,
427{
428 let mut loader = Loader {
429 read,
430 rules: Vec::new(),
431 repeated: Vec::new(),
432 findings: Vec::new(),
433 loading: Vec::new(),
434 loaded: BTreeSet::new(),
435 vocabularies: BTreeMap::new(),
436 };
437 loader.include(path.as_ref(), None)?;
438 loader.shadowed_rules();
439 Ok(Loaded {
440 schema: Schema::new(loader.rules),
441 findings: loader.findings,
442 })
443}
444
445struct Loader<R> {
450 read: R,
451 rules: Vec<FieldRule<Constraint>>,
452 repeated: Vec<bool>,
456 findings: Vec<Finding>,
457 loading: Vec<PathBuf>,
458 loaded: BTreeSet<PathBuf>,
459 vocabularies: BTreeMap<PathBuf, VocabularyDoc>,
460}
461
462enum Kind {
464 Schema,
465 Vocabulary,
466 Both,
467 Neither,
468}
469
470fn kind_of(value: &Value) -> Kind {
471 match (
472 value.get("schema").is_some(),
473 value.get("vocabulary").is_some(),
474 ) {
475 (true, true) => Kind::Both,
476 (true, false) => Kind::Schema,
477 (false, true) => Kind::Vocabulary,
478 (false, false) => Kind::Neither,
479 }
480}
481
482fn resolve(document: &Path, target: &str) -> PathBuf {
491 use std::path::Component;
492
493 let joined = match document.parent() {
494 Some(directory) => directory.join(target),
495 None => PathBuf::from(target),
496 };
497 let mut out = PathBuf::new();
498 for component in joined.components() {
499 match component {
500 Component::CurDir => {}
501 Component::ParentDir => {
502 match out.components().next_back() {
505 Some(Component::Normal(_)) => {
506 out.pop();
507 }
508 _ => out.push(component),
509 }
510 }
511 other => out.push(other),
512 }
513 }
514 out
515}
516
517impl<R> Loader<R>
518where
519 R: FnMut(&Path) -> Result<Value, String>,
520{
521 fn note(&mut self, document: &Path, at: impl Into<String>, kind: FindingKind) {
522 let mut finding = finding(kind, at);
523 finding.document = Some(document.to_path_buf());
524 self.findings.push(finding);
525 }
526
527 fn adopt(&mut self, document: &Path, findings: Vec<Finding>) {
529 for mut finding in findings {
530 finding.document = Some(document.to_path_buf());
531 self.findings.push(finding);
532 }
533 }
534
535 fn include(&mut self, path: &Path, referrer: Option<(&Path, &str)>) -> Result<(), LoadError> {
538 if self.loading.iter().any(|loading| loading == path) {
539 let mut chain = self.loading.clone();
540 chain.push(path.to_path_buf());
541 let (document, at) = referrer.unwrap_or((path, ""));
542 return Err(LoadError {
543 document: document.to_path_buf(),
544 at: at.to_owned(),
545 kind: LoadErrorKind::Cycle { chain },
546 });
547 }
548 let repeat = self.loaded.contains(path);
549 if let Some((document, at)) = referrer
550 && repeat
551 {
552 self.note(document, at, FindingKind::IncludedTwice);
553 }
554
555 let value = (self.read)(path).map_err(|message| {
556 let (document, at) = referrer.unwrap_or((path, ""));
557 LoadError {
558 document: document.to_path_buf(),
559 at: at.to_owned(),
560 kind: LoadErrorKind::Unreadable {
561 path: path.to_path_buf(),
562 message,
563 },
564 }
565 })?;
566
567 self.loading.push(path.to_path_buf());
568 let result = match kind_of(&value) {
569 Kind::Both => Err(LoadError {
570 document: path.to_path_buf(),
571 at: String::new(),
572 kind: LoadErrorKind::BothMarkers,
573 }),
574 Kind::Neither => Err(LoadError {
575 document: path.to_path_buf(),
576 at: String::new(),
577 kind: LoadErrorKind::NotASchema,
578 }),
579 Kind::Vocabulary => self.vocabulary_document(path, &value, repeat),
580 Kind::Schema => self.schema_document(path, &value, repeat),
581 };
582 self.loading.pop();
583 self.loaded.insert(path.to_path_buf());
584 result
585 }
586
587 fn vocabulary_document(
589 &mut self,
590 path: &Path,
591 value: &Value,
592 repeat: bool,
593 ) -> Result<(), LoadError> {
594 let findings = lint_vocabulary(value);
595 self.adopt(path, findings);
596 let Some(doc) = parse_vocabulary(value) else {
597 let kind = match value
600 .get("vocabulary")
601 .and_then(|marker| marker.get("field"))
602 {
603 None => LoadErrorKind::Missing {
604 key: "field".into(),
605 },
606 Some(field) => LoadErrorKind::NotText {
607 key: "field".into(),
608 spelling: sketch(field),
609 },
610 };
611 return Err(LoadError {
612 document: path.to_path_buf(),
613 at: "vocabulary.field".into(),
614 kind,
615 });
616 };
617 let at = pattern(path, "vocabulary.field", &doc.field)?;
618 self.rules.push(
619 FieldRule::new(at)
620 .constraint(Constraint::Vocabulary {
621 terms: doc.terms,
622 closed: doc.closed,
623 })
624 .origin(Origin::new(path, "vocabulary")),
625 );
626 self.repeated.push(repeat);
627 Ok(())
628 }
629
630 fn schema_document(
632 &mut self,
633 path: &Path,
634 value: &Value,
635 repeat: bool,
636 ) -> Result<(), LoadError> {
637 let marker = value.get("schema").expect("kind_of saw the marker");
638 if marker.as_mapping().is_none() {
639 return Err(LoadError {
640 document: path.to_path_buf(),
641 at: "schema".into(),
642 kind: LoadErrorKind::NotAMapping {
643 spelling: sketch(marker),
644 },
645 });
646 }
647 match marker.get("spec") {
648 None => {
649 return Err(LoadError {
650 document: path.to_path_buf(),
651 at: "schema".into(),
652 kind: LoadErrorKind::Missing { key: "spec".into() },
653 });
654 }
655 Some(spec) if spec.as_i64() == Some(1) && !spec.is_f64() => {}
658 Some(spec) => {
659 return Err(LoadError {
660 document: path.to_path_buf(),
661 at: "schema.spec".into(),
662 kind: LoadErrorKind::SpecUnknown {
663 spelling: sketch(spec),
664 },
665 });
666 }
667 }
668
669 let entries = match value.get("rules") {
670 None => return Ok(()),
671 Some(rules) => match rules.as_seq() {
672 Some(entries) => entries,
673 None => {
674 return Err(LoadError {
675 document: path.to_path_buf(),
676 at: "rules".into(),
677 kind: LoadErrorKind::NotAList {
678 spelling: sketch(rules),
679 },
680 });
681 }
682 },
683 };
684
685 for (index, entry) in entries.iter().enumerate() {
686 let at = format!("rules[{index}]");
687 if entry.as_mapping().is_none() {
688 return Err(LoadError {
689 document: path.to_path_buf(),
690 at,
691 kind: LoadErrorKind::NotAMapping {
692 spelling: sketch(entry),
693 },
694 });
695 }
696 match (entry.get("include"), entry.get("at")) {
697 (Some(_), Some(_)) => {
698 return Err(LoadError {
699 document: path.to_path_buf(),
700 at,
701 kind: LoadErrorKind::EntryIsBoth,
702 });
703 }
704 (None, None) => {
705 return Err(LoadError {
706 document: path.to_path_buf(),
707 at,
708 kind: LoadErrorKind::Missing { key: "at".into() },
709 });
710 }
711 (Some(include), None) => {
712 let target = text(path, &format!("{at}.include"), "include", include)?;
713 unknown_keys(entry, &["include"], &at, &mut self.findings);
714 self.name_findings_since(path);
715 let resolved = resolve(path, target);
716 self.include(&resolved, Some((path, &format!("{at}.include"))))?;
717 }
718 (None, Some(_)) => {
719 let rule = self.rule(path, &at, entry)?;
720 self.rules.push(rule);
721 self.repeated.push(repeat);
722 }
723 }
724 }
725 Ok(())
726 }
727
728 fn name_findings_since(&mut self, document: &Path) {
730 for finding in self.findings.iter_mut().rev() {
731 if finding.document.is_some() {
732 break;
733 }
734 finding.document = Some(document.to_path_buf());
735 }
736 }
737
738 fn rule(
740 &mut self,
741 document: &Path,
742 at: &str,
743 entry: &Value,
744 ) -> Result<FieldRule<Constraint>, LoadError> {
745 let pattern_text = text(
746 document,
747 &format!("{at}.at"),
748 "at",
749 entry.get("at").expect("the caller saw it"),
750 )?;
751 let pat = pattern(document, &format!("{at}.at"), pattern_text)?;
752
753 let ty = match entry.get("type") {
754 None => None,
755 Some(name) => {
756 let name = text(document, &format!("{at}.type"), "type", name)?;
757 Some(FieldType::from_name(name).ok_or_else(|| LoadError {
758 document: document.to_path_buf(),
759 at: format!("{at}.type"),
760 kind: LoadErrorKind::UnknownType {
761 name: name.to_owned(),
762 suggestion: FieldType::suggest_name(name),
763 },
764 })?)
765 }
766 };
767
768 let constraint = match entry.get("constraint") {
769 None => None,
770 Some(spec) => Some(self.constraint(document, at, &pat, spec)?),
771 };
772
773 let mut present = Presentation::default();
774 for key in ["title", "description"] {
775 if let Some(held) = entry.get(key) {
776 match held.as_str() {
777 Some(text) if key == "title" => present = present.title(text),
778 Some(text) => present = present.description(text),
779 None => self.note(
780 document,
781 format!("{at}.{key}"),
782 FindingKind::NotAString {
783 key: key.to_owned(),
784 },
785 ),
786 }
787 }
788 }
789 if let Some(icon) = entry.get("icon") {
790 match icon.as_str() {
791 Some(name) => present = present.icon(Icon::from_name(name)),
792 None => self.note(
793 document,
794 format!("{at}.icon"),
795 FindingKind::NotAString { key: "icon".into() },
796 ),
797 }
798 }
799 if let Some(tint) = entry.get("tint") {
800 match tint.as_str().and_then(Tint::from_name) {
801 Some(tint) => present = present.tint(tint),
802 None => self.note(
803 document,
804 format!("{at}.tint"),
805 FindingKind::TintUnreadable {
806 spelling: sketch(tint),
807 },
808 ),
809 }
810 }
811
812 let (on_change, as_list) = self.consequences(document, at, entry.get("on_change"))?;
813 if let Some(Constraint::Vocabulary { terms, .. }) = &constraint {
814 for (index, consequence) in on_change.iter().enumerate() {
815 let Some(Value::Str(guard)) = &consequence.when else {
816 continue;
817 };
818 if terms.iter().any(|term| term.value == *guard) {
819 continue;
820 }
821 let where_ = if as_list {
822 format!("{at}.on_change[{index}].when")
823 } else {
824 format!("{at}.on_change.when")
825 };
826 self.note(
827 document,
828 where_,
829 FindingKind::GuardWithoutTerm {
830 value: guard.clone(),
831 },
832 );
833 }
834 }
835
836 unknown_keys(entry, RULE_KEYS, at, &mut self.findings);
837 self.name_findings_since(document);
838
839 Ok(FieldRule::new(pat)
840 .ty(ty)
841 .constraint_opt(constraint)
842 .present(present)
843 .on_change_all(on_change)
844 .origin(Origin::new(document, at)))
845 }
846
847 fn constraint(
849 &mut self,
850 document: &Path,
851 at: &str,
852 rule_at: &PathPat,
853 spec: &Value,
854 ) -> Result<Constraint, LoadError> {
855 let here = format!("{at}.constraint");
856 if spec.as_mapping().is_none() {
857 return Err(LoadError {
858 document: document.to_path_buf(),
859 at: here,
860 kind: LoadErrorKind::NotAMapping {
861 spelling: sketch(spec),
862 },
863 });
864 }
865 let kind = match spec.get("kind") {
866 None => {
867 return Err(LoadError {
868 document: document.to_path_buf(),
869 at: here,
870 kind: LoadErrorKind::Missing { key: "kind".into() },
871 });
872 }
873 Some(kind) => text(document, &format!("{here}.kind"), "kind", kind)?,
874 };
875 if kind != "vocabulary" {
876 return Ok(Constraint::Other {
877 kind: kind.to_owned(),
878 spec: spec.clone(),
879 });
880 }
881
882 unknown_keys(spec, VOCABULARY_CONSTRAINT_KEYS, &here, &mut self.findings);
883 self.name_findings_since(document);
884
885 let inline = spec.get("values").is_some() || spec.get("terms").is_some();
886 match spec.get("from") {
887 Some(_) if inline => Err(LoadError {
888 document: document.to_path_buf(),
889 at: here,
890 kind: LoadErrorKind::FromAndInline,
891 }),
892 Some(from) => {
893 let from_at = format!("{here}.from");
894 let target = text(document, &from_at, "from", from)?;
895 let resolved = resolve(document, target);
896 let doc = self.vocabulary_from(document, &from_at, &resolved)?;
897 let (terms, closed, field) = (doc.terms.clone(), doc.closed, doc.field.clone());
898 if !field_agrees(&field, rule_at) {
899 self.note(document, from_at, FindingKind::FieldDisagrees { field });
900 }
901 Ok(Constraint::Vocabulary { terms, closed })
902 }
903 None => {
904 let closed = lint_values(spec, &here, &mut self.findings);
905 lint_terms(spec, closed, &format!("{here}."), &mut self.findings);
906 self.name_findings_since(document);
907 Ok(Constraint::Vocabulary {
908 terms: parse_terms(spec),
909 closed,
910 })
911 }
912 }
913 }
914
915 fn vocabulary_from(
918 &mut self,
919 document: &Path,
920 at: &str,
921 target: &Path,
922 ) -> Result<&VocabularyDoc, LoadError> {
923 if !self.vocabularies.contains_key(target) {
924 let value = (self.read)(target).map_err(|message| LoadError {
925 document: document.to_path_buf(),
926 at: at.to_owned(),
927 kind: LoadErrorKind::Unreadable {
928 path: target.to_path_buf(),
929 message,
930 },
931 })?;
932 let Some(doc) = parse_vocabulary(&value) else {
933 return Err(LoadError {
934 document: document.to_path_buf(),
935 at: at.to_owned(),
936 kind: LoadErrorKind::NotAVocabulary {
937 path: target.to_path_buf(),
938 },
939 });
940 };
941 let findings = lint_vocabulary(&value);
942 self.adopt(target, findings);
943 self.vocabularies.insert(target.to_path_buf(), doc);
944 }
945 Ok(&self.vocabularies[target])
946 }
947
948 fn consequences(
952 &mut self,
953 document: &Path,
954 at: &str,
955 value: Option<&Value>,
956 ) -> Result<(Vec<Consequence>, bool), LoadError> {
957 let here = format!("{at}.on_change");
958 let Some(value) = value else {
959 return Ok((Vec::new(), false));
960 };
961 if value.as_mapping().is_some() {
962 return Ok((vec![self.consequence(document, &here, value)?], false));
963 }
964 let Some(items) = value.as_seq() else {
965 return Err(LoadError {
966 document: document.to_path_buf(),
967 at: here,
968 kind: LoadErrorKind::NotAMapping {
969 spelling: sketch(value),
970 },
971 });
972 };
973 let mut consequences = Vec::with_capacity(items.len());
974 for (index, item) in items.iter().enumerate() {
975 let item_at = format!("{here}[{index}]");
976 if item.as_mapping().is_none() {
977 return Err(LoadError {
978 document: document.to_path_buf(),
979 at: item_at,
980 kind: LoadErrorKind::NotAMapping {
981 spelling: sketch(item),
982 },
983 });
984 }
985 consequences.push(self.consequence(document, &item_at, item)?);
986 }
987 Ok((consequences, true))
988 }
989
990 fn consequence(
992 &mut self,
993 document: &Path,
994 at: &str,
995 mapping: &Value,
996 ) -> Result<Consequence, LoadError> {
997 let message = match mapping.get("message") {
998 None => {
999 return Err(LoadError {
1000 document: document.to_path_buf(),
1001 at: at.to_owned(),
1002 kind: LoadErrorKind::Missing {
1003 key: "message".into(),
1004 },
1005 });
1006 }
1007 Some(message) => text(document, &format!("{at}.message"), "message", message)?,
1008 };
1009 let severity = match mapping.get("severity") {
1010 None => Severity::Notice,
1011 Some(severity) => severity
1012 .as_str()
1013 .and_then(Severity::from_name)
1014 .ok_or_else(|| LoadError {
1015 document: document.to_path_buf(),
1016 at: format!("{at}.severity"),
1017 kind: LoadErrorKind::UnknownSeverity {
1018 spelling: sketch(severity),
1019 },
1020 })?,
1021 };
1022 unknown_keys(mapping, CONSEQUENCE_KEYS, at, &mut self.findings);
1023 self.name_findings_since(document);
1024
1025 let consequence = match mapping.get("when") {
1026 Some(when) => Consequence::when(when.clone(), message),
1027 None => Consequence::always(message),
1028 };
1029 Ok(consequence.severity(severity))
1030 }
1031
1032 fn shadowed_rules(&mut self) {
1035 let mut found = Vec::new();
1036 for (index, rule) in self.rules.iter().enumerate() {
1037 if self.repeated[index] {
1038 continue;
1039 }
1040 let Some(origin) = &rule.origin else { continue };
1041 let shadow = self.rules[..index]
1042 .iter()
1043 .find(|earlier| rule.at.is_subsumed_by(&earlier.at));
1044 if let Some(earlier) = shadow {
1045 let by = earlier
1046 .origin
1047 .as_ref()
1048 .map(ToString::to_string)
1049 .unwrap_or_else(|| earlier.at.to_string());
1050 found.push((
1051 origin.document.clone(),
1052 format!("{}.at", origin.at),
1053 FindingKind::Shadowed { by },
1054 ));
1055 }
1056 }
1057 for (document, at, kind) in found {
1058 self.note(&document, at, kind);
1059 }
1060 }
1061}
1062
1063fn text<'v>(document: &Path, at: &str, key: &str, value: &'v Value) -> Result<&'v str, LoadError> {
1065 value.as_str().ok_or_else(|| LoadError {
1066 document: document.to_path_buf(),
1067 at: at.to_owned(),
1068 kind: LoadErrorKind::NotText {
1069 key: key.to_owned(),
1070 spelling: sketch(value),
1071 },
1072 })
1073}
1074
1075fn pattern(document: &Path, at: &str, text: &str) -> Result<PathPat, LoadError> {
1077 PathPat::parse(text).map_err(|error| LoadError {
1078 document: document.to_path_buf(),
1079 at: at.to_owned(),
1080 kind: LoadErrorKind::PatternUnreadable {
1081 text: text.to_owned(),
1082 error,
1083 },
1084 })
1085}
1086
1087fn field_agrees(field: &str, at: &PathPat) -> bool {
1091 let Ok(field) = PathPat::parse(field) else {
1092 return false;
1093 };
1094 if field == *at {
1095 return true;
1096 }
1097 let mut items = field;
1098 items.0.push(SegPat::EachItem);
1099 items == *at
1100}
1101
1102#[cfg(test)]
1103mod tests {
1104 use super::*;
1105 use crate::path::Seg;
1106
1107 fn reader<'d>(
1110 documents: &'d [(&'d str, &'d str)],
1111 ) -> impl FnMut(&Path) -> Result<Value, String> + 'd {
1112 move |path: &Path| {
1113 let name = path.to_str().unwrap();
1114 let (_, text) = documents
1115 .iter()
1116 .find(|(known, _)| *known == name)
1117 .ok_or_else(|| format!("no such document: {name}"))?;
1118 let format = match path.extension().and_then(|e| e.to_str()) {
1119 Some("yaml") => fig_yaml::format().unwrap(),
1120 Some("toml") => fig_toml::format().unwrap(),
1121 Some("figl") => fig_figl::format().unwrap(),
1122 other => return Err(format!("no format for {other:?}")),
1123 };
1124 let document =
1125 fig::Document::parse(text.as_bytes(), format).map_err(|e| e.to_string())?;
1126 document.to_value().map_err(|e| e.to_string())
1127 }
1128 }
1129
1130 fn load(documents: &[(&str, &str)], top: &str) -> Result<Loaded, LoadError> {
1131 load_schema(top, reader(documents))
1132 }
1133
1134 fn key(k: &str) -> Seg {
1135 Seg::Key(k.into())
1136 }
1137
1138 const AUDIENCE: &str = "\
1139vocabulary: { field: audience, values: closed }
1140terms:
1141 public: { label: Public, description: Anyone with the link, tint: positive }
1142 family: {}
1143 archived: { retired: true }
1144";
1145
1146 const NOTE: &str = "\
1147schema: { spec: 1 }
1148rules:
1149 - at: audience[]
1150 type: str
1151 title: Audience
1152 icon: globe
1153 constraint: { kind: vocabulary, from: audience.yaml }
1154 on_change:
1155 when: public
1156 severity: confirm
1157 message: Anyone with the link will be able to read this.
1158 - at: audience
1159 constraint: { kind: vocabulary, from: audience.yaml }
1160 - at: part_of
1161 type: ref
1162 constraint: { kind: reference, relation: contents, cardinality: many }
1163 - include: base.yaml
1164 - at: meta.**
1165 type: str
1166";
1167
1168 const BASE: &str = "\
1169schema: { spec: 1 }
1170rules:
1171 - at: created
1172 type: date
1173 - at: count
1174 type: int
1175";
1176
1177 #[test]
1178 fn the_spec_example_loads_with_every_fact_in_place() {
1179 let loaded = load(
1180 &[
1181 ("schemas/note.yaml", NOTE),
1182 ("schemas/audience.yaml", AUDIENCE),
1183 ("schemas/base.yaml", BASE),
1184 ],
1185 "schemas/note.yaml",
1186 )
1187 .unwrap();
1188 assert_eq!(loaded.findings, Vec::new(), "{:?}", loaded.findings);
1189
1190 let rules = loaded.schema.rules();
1191 assert_eq!(rules.len(), 6);
1192
1193 let audience = &rules[0];
1195 assert_eq!(audience.at, PathPat::each_item_of("audience"));
1196 assert_eq!(audience.ty, Some(FieldType::Str));
1197 assert_eq!(audience.present.title.as_deref(), Some("Audience"));
1198 assert_eq!(audience.present.icon, Some(Icon::Globe));
1199 let Some(Constraint::Vocabulary { terms, closed }) = &audience.constraint else {
1200 panic!("a vocabulary");
1201 };
1202 assert!(closed);
1203 assert_eq!(terms.len(), 3);
1204 assert_eq!(terms[0].label.as_deref(), Some("Public"));
1205 assert_eq!(terms[0].tint, Some(Tint::Positive));
1206 assert!(terms[2].retired);
1207 assert_eq!(audience.on_change.len(), 1);
1208 assert_eq!(
1209 audience.on_change[0].when,
1210 Some(Value::Str("public".into()))
1211 );
1212 assert_eq!(audience.on_change[0].severity, Severity::Confirm);
1213 assert_eq!(
1214 audience.origin.as_ref().unwrap().to_string(),
1215 "schemas/note.yaml rules[0]"
1216 );
1217
1218 let Some(Constraint::Other { kind, spec }) = &rules[2].constraint else {
1220 panic!("an unknown kind");
1221 };
1222 assert_eq!(kind, "reference");
1223 assert_eq!(spec.get("relation"), Some(&Value::Str("contents".into())));
1224
1225 assert_eq!(rules[3].at, PathPat::key("created"));
1227 assert_eq!(
1228 rules[3].ty,
1229 Some(FieldType::Extended(fig::ExtKind::LocalDate))
1230 );
1231 assert_eq!(
1232 rules[3].origin.as_ref().unwrap().to_string(),
1233 "schemas/base.yaml rules[0]"
1234 );
1235 assert_eq!(rules[5].at, PathPat::subtree_of("meta"));
1236 assert_eq!(
1237 rules[5].origin.as_ref().unwrap().to_string(),
1238 "schemas/note.yaml rules[4]"
1239 );
1240 }
1241
1242 #[test]
1243 fn the_loaded_schema_checks_a_document() {
1244 let loaded = load(
1245 &[
1246 ("note.yaml", NOTE),
1247 ("audience.yaml", AUDIENCE),
1248 ("base.yaml", BASE),
1249 ],
1250 "note.yaml",
1251 )
1252 .unwrap();
1253 let document = fig::Document::parse(
1254 b"audience: [public, famly]\ncount: three\npart_of: ../index.md\ntitle: x\n",
1255 fig_yaml::format().unwrap(),
1256 )
1257 .unwrap()
1258 .to_value()
1259 .unwrap();
1260 let report: Vec<String> = loaded
1261 .schema
1262 .check(&document)
1263 .iter()
1264 .map(|v| format!("{}: {v}", v.at()))
1265 .collect();
1266 assert_eq!(
1267 report,
1268 [
1269 "audience[1]: “famly” is not a known value — did you mean “family”?",
1270 "count: expected int, found str",
1271 "part_of: a “reference” constraint, which this validator cannot check",
1272 ]
1273 );
1274 }
1275
1276 #[test]
1277 fn a_vocabulary_document_is_a_schema_document_holding_one_rule() {
1278 let loaded = load(&[("audience.yaml", AUDIENCE)], "audience.yaml").unwrap();
1279 assert!(loaded.findings.is_empty());
1280 let rules = loaded.schema.rules();
1281 assert_eq!(rules.len(), 1);
1282 assert_eq!(rules[0].at, PathPat::key("audience"));
1283 assert_eq!(rules[0].ty, None);
1284 assert!(matches!(
1285 rules[0].constraint,
1286 Some(Constraint::Vocabulary { closed: true, .. })
1287 ));
1288 assert_eq!(
1289 rules[0].origin.as_ref().unwrap().to_string(),
1290 "audience.yaml vocabulary"
1291 );
1292 let seq = Value::Seq(vec![Value::Str("nope".into())]);
1294 assert!(rules[0].validate(&seq).is_reject());
1295 }
1296
1297 #[test]
1298 fn a_vocabulary_document_can_be_included_and_its_lint_travels_with_it() {
1299 let loaded = load(
1300 &[
1301 (
1302 "s.yaml",
1303 "schema: { spec: 1 }\nrules:\n - include: v.yaml\n",
1304 ),
1305 (
1306 "v.yaml",
1307 "vocabulary: { field: a, values: cloesd }\nterms:\n x:\n",
1308 ),
1309 ],
1310 "s.yaml",
1311 )
1312 .unwrap();
1313 assert_eq!(loaded.schema.rules().len(), 1);
1314 assert_eq!(loaded.findings.len(), 1);
1315 assert!(matches!(
1316 loaded.findings[0].kind,
1317 FindingKind::ValuesUnreadable { .. }
1318 ));
1319 assert_eq!(
1320 loaded.findings[0].document.as_deref(),
1321 Some(Path::new("v.yaml"))
1322 );
1323 assert_eq!(loaded.findings[0].at, "vocabulary.values");
1324 }
1325
1326 #[test]
1327 fn an_inline_vocabulary_is_spelled_as_the_document_spells_it() {
1328 let loaded = load(
1329 &[(
1330 "s.yaml",
1331 "schema: { spec: 1 }\nrules:\n - at: status\n constraint:\n kind: vocabulary\n values: closed\n terms:\n open: { label: Open }\n done: {}\n old: { retired: true, tint: green }\n",
1332 )],
1333 "s.yaml",
1334 )
1335 .unwrap();
1336 let Some(Constraint::Vocabulary { terms, closed }) = &loaded.schema.rules()[0].constraint
1337 else {
1338 panic!("a vocabulary");
1339 };
1340 assert!(closed);
1341 assert_eq!(terms.len(), 3);
1342 assert_eq!(terms[0].label.as_deref(), Some("Open"));
1343 assert!(terms[2].retired);
1344 assert_eq!(loaded.findings.len(), 1);
1346 assert_eq!(
1347 loaded.findings[0].kind,
1348 FindingKind::TintUnreadable {
1349 spelling: "green".into()
1350 }
1351 );
1352 assert_eq!(loaded.findings[0].at, "rules[0].constraint.terms.old.tint");
1353 assert_eq!(
1354 loaded.findings[0].document.as_deref(),
1355 Some(Path::new("s.yaml"))
1356 );
1357 }
1358
1359 #[test]
1360 fn a_misspelled_inline_values_is_the_error_lint_exists_for() {
1361 let loaded = load(
1362 &[(
1363 "s.yaml",
1364 "schema: { spec: 1 }\nrules:\n - at: status\n constraint: { kind: vocabulary, values: cloesd, terms: { x: {} } }\n",
1365 )],
1366 "s.yaml",
1367 )
1368 .unwrap();
1369 assert!(matches!(
1370 loaded.schema.rules()[0].constraint,
1371 Some(Constraint::Vocabulary { closed: false, .. })
1372 ));
1373 assert_eq!(loaded.findings.len(), 1);
1374 assert!(loaded.findings[0].is_error());
1375 assert_eq!(loaded.findings[0].at, "rules[0].constraint.values");
1376 }
1377
1378 fn failing(documents: &[(&str, &str)], top: &str) -> LoadError {
1379 load(documents, top).expect_err("a load error")
1380 }
1381
1382 fn schema_with(rule: &str) -> String {
1383 format!("schema: {{ spec: 1 }}\nrules:\n - {rule}\n")
1384 }
1385
1386 #[test]
1387 fn what_the_loader_cannot_read_as_a_rule_is_an_error_not_a_weaker_rule() {
1388 let cases: &[(&str, &str, LoadErrorKind)] = &[
1389 (
1390 "at: x\n type: string",
1391 "rules[0].type",
1392 LoadErrorKind::UnknownType {
1393 name: "string".into(),
1394 suggestion: Some("str"),
1395 },
1396 ),
1397 (
1398 "at: x\n type: wibble",
1399 "rules[0].type",
1400 LoadErrorKind::UnknownType {
1401 name: "wibble".into(),
1402 suggestion: None,
1403 },
1404 ),
1405 (
1406 "at: x\n type: 3",
1407 "rules[0].type",
1408 LoadErrorKind::NotText {
1409 key: "type".into(),
1410 spelling: "3".into(),
1411 },
1412 ),
1413 (
1414 "type: str",
1415 "rules[0]",
1416 LoadErrorKind::Missing { key: "at".into() },
1417 ),
1418 (
1419 "at: x\n include: y.yaml",
1420 "rules[0]",
1421 LoadErrorKind::EntryIsBoth,
1422 ),
1423 (
1424 "at: [x]",
1425 "rules[0].at",
1426 LoadErrorKind::NotText {
1427 key: "at".into(),
1428 spelling: "a list".into(),
1429 },
1430 ),
1431 (
1432 "at: a..b",
1433 "rules[0].at",
1434 LoadErrorKind::PatternUnreadable {
1435 text: "a..b".into(),
1436 error: PatternError::EmptySegment { offset: 2 },
1437 },
1438 ),
1439 (
1440 "at: x\n constraint: vocabulary",
1441 "rules[0].constraint",
1442 LoadErrorKind::NotAMapping {
1443 spelling: "vocabulary".into(),
1444 },
1445 ),
1446 (
1447 "at: x\n constraint: { values: closed }",
1448 "rules[0].constraint",
1449 LoadErrorKind::Missing { key: "kind".into() },
1450 ),
1451 (
1452 "at: x\n constraint: { kind: vocabulary, from: v.yaml, values: closed }",
1453 "rules[0].constraint",
1454 LoadErrorKind::FromAndInline,
1455 ),
1456 (
1457 "at: x\n on_change: { when: a, severity: shout, message: m }",
1458 "rules[0].on_change.severity",
1459 LoadErrorKind::UnknownSeverity {
1460 spelling: "shout".into(),
1461 },
1462 ),
1463 (
1464 "at: x\n on_change: [{ when: a, severity: confirm }]",
1465 "rules[0].on_change[0]",
1466 LoadErrorKind::Missing {
1467 key: "message".into(),
1468 },
1469 ),
1470 (
1471 "at: x\n on_change: sure",
1472 "rules[0].on_change",
1473 LoadErrorKind::NotAMapping {
1474 spelling: "sure".into(),
1475 },
1476 ),
1477 ];
1478 for (rule, at, kind) in cases {
1479 let document = schema_with(rule);
1480 let error = failing(&[("s.yaml", &document)], "s.yaml");
1481 assert_eq!(error.at, *at, "{rule}");
1482 assert_eq!(error.kind, *kind, "{rule}");
1483 assert_eq!(error.document, Path::new("s.yaml"));
1484 }
1485 }
1486
1487 #[test]
1488 fn what_is_not_a_schema_document_is_said_plainly() {
1489 let error = failing(&[("s.yaml", "title: Notes\n")], "s.yaml");
1490 assert_eq!(error.kind, LoadErrorKind::NotASchema);
1491 assert_eq!(error.at, "");
1492
1493 let error = failing(
1494 &[("s.yaml", "schema: { spec: 1 }\nvocabulary: { field: a }\n")],
1495 "s.yaml",
1496 );
1497 assert_eq!(error.kind, LoadErrorKind::BothMarkers);
1498
1499 let error = failing(&[("s.yaml", "schema: { spec: 2 }\n")], "s.yaml");
1500 assert_eq!(
1501 error.kind,
1502 LoadErrorKind::SpecUnknown {
1503 spelling: "2".into()
1504 }
1505 );
1506 assert_eq!(error.at, "schema.spec");
1507
1508 let error = failing(&[("s.yaml", "schema: {}\n")], "s.yaml");
1509 assert_eq!(error.kind, LoadErrorKind::Missing { key: "spec".into() });
1510
1511 let error = failing(&[("s.yaml", "schema: 1\n")], "s.yaml");
1512 assert!(matches!(error.kind, LoadErrorKind::NotAMapping { .. }));
1513
1514 let error = failing(&[("s.yaml", "schema: { spec: 1 }\nrules: {}\n")], "s.yaml");
1515 assert!(matches!(error.kind, LoadErrorKind::NotAList { .. }));
1516
1517 let error = failing(&[("s.yaml", "schema: { spec: 1 }\nrules: [3]\n")], "s.yaml");
1518 assert!(matches!(error.kind, LoadErrorKind::NotAMapping { .. }));
1519 assert_eq!(error.at, "rules[0]");
1520
1521 let error = failing(&[("v.yaml", "vocabulary: { values: closed }\n")], "v.yaml");
1523 assert_eq!(
1524 error.kind,
1525 LoadErrorKind::Missing {
1526 key: "field".into()
1527 }
1528 );
1529 assert_eq!(error.at, "vocabulary.field");
1530 }
1531
1532 #[test]
1533 fn a_schema_with_no_rules_is_empty_and_legal() {
1534 let loaded = load(&[("s.yaml", "schema: { spec: 1 }\n")], "s.yaml").unwrap();
1535 assert!(loaded.schema.is_empty());
1536 assert!(loaded.findings.is_empty());
1537 }
1538
1539 #[test]
1540 fn a_spec_written_as_a_float_or_a_string_is_not_spec_1() {
1541 let error = failing(&[("s.yaml", "schema: { spec: 1.0 }\n")], "s.yaml");
1544 assert!(matches!(error.kind, LoadErrorKind::SpecUnknown { .. }));
1545 let error = failing(&[("s.yaml", "schema: { spec: '1' }\n")], "s.yaml");
1546 assert!(matches!(error.kind, LoadErrorKind::SpecUnknown { .. }));
1547 }
1548
1549 #[test]
1550 fn a_bad_reference_names_the_document_that_wrote_it() {
1551 let error = failing(
1553 &[(
1554 "s.yaml",
1555 "schema: { spec: 1 }\nrules:\n - include: gone.yaml\n",
1556 )],
1557 "s.yaml",
1558 );
1559 assert_eq!(error.document, Path::new("s.yaml"));
1560 assert_eq!(error.at, "rules[0].include");
1561 assert!(matches!(
1562 &error.kind,
1563 LoadErrorKind::Unreadable { path, .. } if path == Path::new("gone.yaml")
1564 ));
1565
1566 let from_base = schema_with("at: x\n constraint: { kind: vocabulary, from: b.yaml }");
1568 let error = failing(&[("s.yaml", &from_base), ("b.yaml", BASE)], "s.yaml");
1569 assert_eq!(error.at, "rules[0].constraint.from");
1570 assert_eq!(
1571 error.kind,
1572 LoadErrorKind::NotAVocabulary {
1573 path: "b.yaml".into()
1574 }
1575 );
1576
1577 let error = failing(
1579 &[
1580 (
1581 "s.yaml",
1582 "schema: { spec: 1 }\nrules:\n - include: t.yaml\n",
1583 ),
1584 ("t.yaml", "title: x\n"),
1585 ],
1586 "s.yaml",
1587 );
1588 assert_eq!(error.document, Path::new("t.yaml"));
1589 assert_eq!(error.kind, LoadErrorKind::NotASchema);
1590
1591 let error = failing(&[], "s.yaml");
1593 assert_eq!(error.document, Path::new("s.yaml"));
1594 assert_eq!(error.at, "");
1595 assert!(matches!(error.kind, LoadErrorKind::Unreadable { .. }));
1596 }
1597
1598 #[test]
1599 fn references_resolve_against_the_document_that_wrote_them() {
1600 let loaded = load(
1601 &[
1602 (
1603 "a/s.yaml",
1604 "schema: { spec: 1 }\nrules:\n - include: sub/b.yaml\n - include: /abs/c.yaml\n",
1605 ),
1606 (
1607 "a/sub/b.yaml",
1608 "schema: { spec: 1 }\nrules:\n - at: x\n constraint: { kind: vocabulary, from: ../v.yaml }\n",
1609 ),
1610 ("a/v.yaml", "vocabulary: { field: x }\nterms:\n t:\n"),
1611 ("/abs/c.yaml", "schema: { spec: 1 }\nrules:\n - at: y\n"),
1612 ],
1613 "a/s.yaml",
1614 )
1615 .unwrap();
1616 let origins: Vec<String> = loaded
1617 .schema
1618 .rules()
1619 .iter()
1620 .map(|r| r.origin.as_ref().unwrap().to_string())
1621 .collect();
1622 assert_eq!(origins, ["a/sub/b.yaml rules[0]", "/abs/c.yaml rules[0]"]);
1623 assert_eq!(
1625 loaded.schema.rules()[0]
1626 .constraint
1627 .as_ref()
1628 .map(Constraint::kind),
1629 Some("vocabulary")
1630 );
1631 }
1632
1633 #[test]
1634 fn resolution_folds_dots_lexically_and_keeps_an_absolute_path() {
1635 assert_eq!(
1636 resolve(Path::new("a/s.yaml"), "b.yaml"),
1637 Path::new("a/b.yaml")
1638 );
1639 assert_eq!(
1640 resolve(Path::new("a/sub/s.yaml"), "../v.yaml"),
1641 Path::new("a/v.yaml")
1642 );
1643 assert_eq!(
1644 resolve(Path::new("a/s.yaml"), "./v.yaml"),
1645 Path::new("a/v.yaml")
1646 );
1647 assert_eq!(resolve(Path::new("s.yaml"), "v.yaml"), Path::new("v.yaml"));
1648 assert_eq!(
1649 resolve(Path::new("s.yaml"), "../v.yaml"),
1650 Path::new("../v.yaml")
1651 );
1652 assert_eq!(
1653 resolve(Path::new("a/s.yaml"), "/abs/v.yaml"),
1654 Path::new("/abs/v.yaml")
1655 );
1656 }
1657
1658 #[test]
1659 fn a_cycle_is_an_error_naming_the_chain() {
1660 let error = failing(
1661 &[
1662 (
1663 "a.yaml",
1664 "schema: { spec: 1 }\nrules:\n - include: b.yaml\n",
1665 ),
1666 (
1667 "b.yaml",
1668 "schema: { spec: 1 }\nrules:\n - include: a.yaml\n",
1669 ),
1670 ],
1671 "a.yaml",
1672 );
1673 assert_eq!(error.document, Path::new("b.yaml"));
1674 assert_eq!(error.at, "rules[0].include");
1675 assert_eq!(
1676 error.kind,
1677 LoadErrorKind::Cycle {
1678 chain: vec!["a.yaml".into(), "b.yaml".into(), "a.yaml".into()]
1679 }
1680 );
1681 assert!(error.to_string().contains("a.yaml → b.yaml → a.yaml"));
1682
1683 let error = failing(
1685 &[(
1686 "a.yaml",
1687 "schema: { spec: 1 }\nrules:\n - include: a.yaml\n",
1688 )],
1689 "a.yaml",
1690 );
1691 assert!(matches!(error.kind, LoadErrorKind::Cycle { .. }));
1692 }
1693
1694 #[test]
1695 fn a_document_included_twice_is_spliced_twice_and_noted_once() {
1696 let loaded = load(
1697 &[
1698 (
1699 "s.yaml",
1700 "schema: { spec: 1 }\nrules:\n - include: b.yaml\n - at: z\n - include: b.yaml\n",
1701 ),
1702 ("b.yaml", BASE),
1703 ],
1704 "s.yaml",
1705 )
1706 .unwrap();
1707 assert_eq!(loaded.schema.rules().len(), 5);
1708 let kinds: Vec<&FindingKind> = loaded.findings.iter().map(|f| &f.kind).collect();
1709 assert_eq!(kinds, [&FindingKind::IncludedTwice]);
1711 assert_eq!(loaded.findings[0].at, "rules[2].include");
1712 assert!(!loaded.findings[0].is_error());
1713 }
1714
1715 #[test]
1716 fn a_from_named_twice_is_read_and_linted_once() {
1717 let mut reads = 0;
1718 let documents = [
1719 (
1720 "s.yaml",
1721 "schema: { spec: 1 }\nrules:\n - at: a[]\n constraint: { kind: vocabulary, from: v.yaml }\n - at: a\n constraint: { kind: vocabulary, from: v.yaml }\n",
1722 ),
1723 (
1724 "v.yaml",
1725 "vocabulary: { field: a, values: cloesd }\nterms:\n x:\n",
1726 ),
1727 ];
1728 let mut inner = reader(&documents);
1729 let loaded = load_schema("s.yaml", |path: &Path| {
1730 if path == Path::new("v.yaml") {
1731 reads += 1;
1732 }
1733 inner(path)
1734 })
1735 .unwrap();
1736 assert_eq!(reads, 1);
1737 assert_eq!(loaded.findings.len(), 1);
1738 }
1739
1740 #[test]
1741 fn what_the_loader_reads_permissively_is_a_note() {
1742 let loaded = load(
1743 &[
1744 (
1745 "s.yaml",
1746 "schema: { spec: 1 }\nrules:\n - at: a\n title: [no]\n icon: 3\n tint: mauve\n required: true\n constraint: { kind: vocabulary, from: v.yaml, extra: 1 }\n on_change: { message: m, urgency: high }\n",
1747 ),
1748 ("v.yaml", "vocabulary: { field: b }\nterms:\n x:\n"),
1749 ],
1750 "s.yaml",
1751 )
1752 .unwrap();
1753 let rule = &loaded.schema.rules()[0];
1754 assert_eq!(rule.present.title, None);
1755 assert_eq!(rule.present.icon, None);
1756 assert_eq!(rule.present.tint, None);
1757 let ats: Vec<(&str, bool)> = loaded
1758 .findings
1759 .iter()
1760 .map(|f| (f.at.as_str(), f.is_error()))
1761 .collect();
1762 assert_eq!(
1763 ats,
1764 [
1765 ("rules[0].constraint.extra", false),
1766 ("rules[0].constraint.from", false),
1767 ("rules[0].title", false),
1768 ("rules[0].icon", false),
1769 ("rules[0].tint", false),
1770 ("rules[0].on_change.urgency", false),
1771 ("rules[0].required", false),
1772 ]
1773 );
1774 assert_eq!(
1775 loaded.findings[1].kind,
1776 FindingKind::FieldDisagrees { field: "b".into() }
1777 );
1778 assert_eq!(
1779 loaded.findings[4].kind,
1780 FindingKind::TintUnreadable {
1781 spelling: "mauve".into()
1782 }
1783 );
1784 assert!(
1785 loaded
1786 .findings
1787 .iter()
1788 .all(|f| f.document.as_deref() == Some(Path::new("s.yaml")))
1789 );
1790 }
1791
1792 #[test]
1793 fn a_field_agrees_with_its_rule_at_the_key_or_at_its_items() {
1794 let at = PathPat::key("audience");
1795 assert!(field_agrees("audience", &at));
1796 assert!(field_agrees("audience", &PathPat::each_item_of("audience")));
1797 assert!(!field_agrees("tags", &at));
1798 assert!(!field_agrees("audience", &PathPat::subtree_of("audience")));
1799 assert!(!field_agrees("a..b", &at));
1800 }
1801
1802 #[test]
1803 fn a_guard_naming_no_term_is_the_error_guards_without_terms_exists_for() {
1804 let loaded = load(
1805 &[(
1806 "s.yaml",
1807 "schema: { spec: 1 }\nrules:\n - at: history\n constraint: { kind: vocabulary, terms: { off: {}, registry: {} } }\n on_change:\n - message: The archive is rewritten.\n - { when: none, message: History is discarded. }\n - { when: false, message: not text so not looked up }\n - { when: registry, message: fine }\n",
1808 )],
1809 "s.yaml",
1810 )
1811 .unwrap();
1812 assert_eq!(loaded.findings.len(), 1, "{:?}", loaded.findings);
1813 assert_eq!(
1814 loaded.findings[0].kind,
1815 FindingKind::GuardWithoutTerm {
1816 value: "none".into()
1817 }
1818 );
1819 assert_eq!(loaded.findings[0].at, "rules[0].on_change[1].when");
1820 assert!(loaded.findings[0].is_error());
1821
1822 let loaded = load(
1824 &[(
1825 "s.yaml",
1826 "schema: { spec: 1 }\nrules:\n - at: h\n constraint: { kind: vocabulary, terms: { off: {} } }\n on_change: { when: on, message: m }\n",
1827 )],
1828 "s.yaml",
1829 )
1830 .unwrap();
1831 assert_eq!(loaded.findings[0].at, "rules[0].on_change.when");
1832 let loaded = load(
1834 &[(
1835 "s.yaml",
1836 "schema: { spec: 1 }\nrules:\n - at: h\n constraint: { kind: reference }\n on_change: { when: on, message: m }\n",
1837 )],
1838 "s.yaml",
1839 )
1840 .unwrap();
1841 assert!(loaded.findings.is_empty());
1842 }
1843
1844 #[test]
1845 fn a_when_is_read_as_the_value_the_format_parsed() {
1846 let loaded = load(
1847 &[(
1848 "s.yaml",
1849 "schema: { spec: 1 }\nrules:\n - at: bin\n type: bool\n on_change: { when: false, severity: confirm_explicitly, message: Gone for good. }\n - at: n\n on_change: { when: 1, message: one }\n - at: any\n on_change: { message: anything }\n",
1850 )],
1851 "s.yaml",
1852 )
1853 .unwrap();
1854 let rules = loaded.schema.rules();
1855 assert_eq!(rules[0].on_change[0].when, Some(Value::Bool(false)));
1856 assert_eq!(rules[0].on_change[0].severity, Severity::ConfirmExplicitly);
1857 assert_eq!(rules[1].on_change[0].when, Some(Value::Int(1)));
1858 assert_eq!(rules[1].on_change[0].severity, Severity::Notice);
1859 assert_eq!(rules[2].on_change[0].when, None);
1860 assert_eq!(
1861 rules[2].severity_of(&Value::Str("x".into())),
1862 Some(Severity::Notice)
1863 );
1864 }
1865
1866 #[test]
1867 fn a_rule_an_earlier_rule_shadows_entirely_is_noted() {
1868 let loaded = load(
1869 &[(
1870 "s.yaml",
1871 "schema: { spec: 1 }\nrules:\n - at: '**'\n type: str\n - at: audience\n - at: meta.*\n",
1872 )],
1873 "s.yaml",
1874 )
1875 .unwrap();
1876 let shadowed: Vec<(&str, &FindingKind)> = loaded
1877 .findings
1878 .iter()
1879 .map(|f| (f.at.as_str(), &f.kind))
1880 .collect();
1881 assert_eq!(
1882 shadowed,
1883 [
1884 (
1885 "rules[1].at",
1886 &FindingKind::Shadowed {
1887 by: "s.yaml rules[0]".into()
1888 }
1889 ),
1890 (
1891 "rules[2].at",
1892 &FindingKind::Shadowed {
1893 by: "s.yaml rules[0]".into()
1894 }
1895 ),
1896 ]
1897 );
1898 assert!(loaded.findings.iter().all(|f| !f.is_error()));
1899
1900 let loaded = load(
1902 &[(
1903 "s.yaml",
1904 "schema: { spec: 1 }\nrules:\n - at: audience\n - at: '**'\n",
1905 )],
1906 "s.yaml",
1907 )
1908 .unwrap();
1909 assert!(loaded.findings.is_empty());
1910 }
1911
1912 #[test]
1913 fn a_figl_document_loads_the_same_as_its_yaml() {
1914 let figl = "\
1915schema.spec = 1
1916
1917rules[]
1918> at = audience[]
1919> type = str
1920> title = Audience
1921> constraint.kind = vocabulary
1922> constraint.from = audience.yaml
1923> on_change.when = public
1924> on_change.severity = confirm
1925> on_change.message = Anyone with the link will be able to read this.
1926+
1927> at = \"\"
1928> type = map
1929+
1930> at = \"[]\"
1931";
1932 let loaded = load(&[("s.figl", figl), ("audience.yaml", AUDIENCE)], "s.figl").unwrap();
1933 assert!(loaded.findings.is_empty(), "{:?}", loaded.findings);
1934 let rules = loaded.schema.rules();
1935 assert_eq!(rules.len(), 3);
1936 assert_eq!(rules[0].at, PathPat::each_item_of("audience"));
1937 assert_eq!(rules[0].on_change[0].severity, Severity::Confirm);
1938 assert_eq!(rules[1].at, PathPat(vec![]));
1939 assert_eq!(rules[2].at, PathPat(vec![SegPat::EachItem]));
1940 assert!(loaded.schema.rule_for(&[]).is_some());
1941 assert!(loaded.schema.rule_for(&[Seg::Index(0)]).is_some());
1942 }
1943
1944 #[test]
1945 fn an_unknown_kind_validates_to_unchecked_and_says_its_kind() {
1946 let constraint = Constraint::Other {
1947 kind: "reference".into(),
1948 spec: Value::Map(vec![]),
1949 };
1950 let result = constraint.validate(&Value::Str("../x.md".into()));
1951 assert!(result.is_reject());
1952 let issue = result.issue().unwrap();
1953 assert!(issue.is_unchecked());
1954 assert_eq!(issue.value, "../x.md");
1955 assert_eq!(constraint.kind(), "reference");
1956 assert_eq!(constraint.terms(), None);
1957 assert_eq!(
1958 constraint.to_string(),
1959 "reference — a kind this crate cannot check"
1960 );
1961
1962 let vocabulary = Constraint::Vocabulary {
1963 terms: vec![Term::value("a"), Term::value("b").retired(true)],
1964 closed: true,
1965 };
1966 assert_eq!(vocabulary.kind(), "vocabulary");
1967 assert_eq!(vocabulary.terms().map(<[Term]>::len), Some(2));
1968 assert_eq!(
1969 vocabulary.to_string(),
1970 "vocabulary, closed, 2 terms (1 retired)"
1971 );
1972 assert_eq!(
1973 Constraint::Vocabulary {
1974 terms: vec![Term::value("a")],
1975 closed: false
1976 }
1977 .to_string(),
1978 "vocabulary, open, 1 term"
1979 );
1980 }
1981
1982 #[test]
1983 fn an_embedder_maps_the_loaded_schema_into_its_own_constraint_type() {
1984 #[derive(Debug, PartialEq)]
1985 enum Mine {
1986 Vocabulary(usize),
1987 Reference,
1988 Unknown(String),
1989 }
1990 let loaded = load(
1991 &[
1992 ("note.yaml", NOTE),
1993 ("audience.yaml", AUDIENCE),
1994 ("base.yaml", BASE),
1995 ],
1996 "note.yaml",
1997 )
1998 .unwrap();
1999 let mine: Schema<Mine> = loaded.schema.map_constraints(|c| match c {
2000 Constraint::Vocabulary { terms, .. } => Mine::Vocabulary(terms.len()),
2001 Constraint::Other { kind, .. } if kind == "reference" => Mine::Reference,
2002 Constraint::Other { kind, .. } => Mine::Unknown(kind),
2003 });
2004 assert_eq!(mine.rules()[0].constraint, Some(Mine::Vocabulary(3)));
2005 assert_eq!(mine.rules()[2].constraint, Some(Mine::Reference));
2006 assert_eq!(
2007 mine.rules()[2].origin.as_ref().unwrap().to_string(),
2008 "note.yaml rules[2]"
2009 );
2010 }
2011
2012 #[test]
2013 fn every_load_error_renders_a_sentence() {
2014 for kind in [
2015 LoadErrorKind::Unreadable {
2016 path: "x".into(),
2017 message: "m".into(),
2018 },
2019 LoadErrorKind::NotASchema,
2020 LoadErrorKind::BothMarkers,
2021 LoadErrorKind::SpecUnknown {
2022 spelling: "x".into(),
2023 },
2024 LoadErrorKind::Missing { key: "x".into() },
2025 LoadErrorKind::EntryIsBoth,
2026 LoadErrorKind::NotText {
2027 key: "x".into(),
2028 spelling: "y".into(),
2029 },
2030 LoadErrorKind::NotAMapping {
2031 spelling: "x".into(),
2032 },
2033 LoadErrorKind::NotAList {
2034 spelling: "x".into(),
2035 },
2036 LoadErrorKind::PatternUnreadable {
2037 text: "x".into(),
2038 error: PatternError::UnclosedIndex { offset: 0 },
2039 },
2040 LoadErrorKind::UnknownType {
2041 name: "x".into(),
2042 suggestion: None,
2043 },
2044 LoadErrorKind::UnknownType {
2045 name: "x".into(),
2046 suggestion: Some("str"),
2047 },
2048 LoadErrorKind::UnknownSeverity {
2049 spelling: "x".into(),
2050 },
2051 LoadErrorKind::FromAndInline,
2052 LoadErrorKind::NotAVocabulary { path: "x".into() },
2053 LoadErrorKind::Cycle {
2054 chain: vec!["a".into(), "b".into()],
2055 },
2056 ] {
2057 let error = LoadError {
2058 document: "s.yaml".into(),
2059 at: "rules[0]".into(),
2060 kind: kind.clone(),
2061 };
2062 let rendered = error.to_string();
2063 assert!(rendered.starts_with("s.yaml rules[0]: "), "{rendered}");
2064 assert!(rendered.len() > 30, "{kind:?} renders only {rendered:?}");
2065 }
2066 let whole = LoadError {
2067 document: "s.yaml".into(),
2068 at: String::new(),
2069 kind: LoadErrorKind::NotASchema,
2070 };
2071 assert!(whole.to_string().starts_with("s.yaml: "));
2072 }
2073
2074 #[test]
2075 fn a_reader_error_is_carried_verbatim() {
2076 let error =
2077 load_schema("s.yaml", |_: &Path| Err("permission denied".to_owned())).unwrap_err();
2078 assert_eq!(
2079 error.kind,
2080 LoadErrorKind::Unreadable {
2081 path: "s.yaml".into(),
2082 message: "permission denied".into()
2083 }
2084 );
2085 assert!(error.to_string().contains("permission denied"));
2086 let _ = key("unused");
2087 }
2088}