fig_schema/lib.rs
1//! `fig-schema` — the schema layer: what a field *expects* — its type, its
2//! allowed values, and how to present it — layered over [`fig`]'s schema-free
3//! value tree.
4//!
5//! fig parses bytes → [`fig::Value`] and edits losslessly; it has no notion of
6//! "what is valid here". This crate adds that knowledge as a **generic,
7//! embedder-agnostic** engine. It never learns the word "prov" or "flower": a
8//! consumer (prov, for frontmatter fields; flower, for a metadata editor)
9//! defines its own constraint type — an enum covering whatever kinds of
10//! constraint it needs (a controlled vocabulary, a reference into a
11//! workspace, …) — and implements [`Validate`] on it. [`FieldRule`]/[`Schema`]
12//! are generic over that type, so the path-matching and commit-time
13//! validation plumbing is written once, here, and reused by every embedder.
14//!
15//! A schema is also **a document**. [`load_schema`] reads one written to the
16//! schema document format — `docs/schema-format.md`, a fig document in any of
17//! fig's languages, composed from others by `include` and from vocabulary
18//! documents by `constraint.from` — into a [`Schema<Constraint>`], where
19//! [`Constraint`] is this crate's own type: a vocabulary, or an
20//! [`Other`](Constraint::Other) kind it does not know, which validates to
21//! *unchecked* rather than pretending. An embedder maps that into its own
22//! constraint type with [`Schema::map_constraints`] and keeps the seam; the
23//! `fig-schema` binary checks documents against it with no embedder at all.
24//!
25//! What's genuinely reusable, and lives here as concrete types rather than
26//! being left to the embedder:
27//!
28//! - [`PathPat`] / [`SegPat`] — pattern-matching a fig path, including "every
29//! item of this list" ([`SegPat::EachItem`]) and "this subtree"
30//! ([`SegPat::AnyDepth`]); [`PathPat::parse`] reads one from the format's
31//! grammar (`audience[]`, `meta.**`) and [`render_path`] is its inverse.
32//! - [`FieldType`] — the expected type, type-directed coercion of an edit
33//! buffer ([`FieldType::coerce`]), whether a parsed value already has the
34//! type ([`FieldType::admits`]), and the name the format spells it by
35//! ([`FieldType::from_name`]).
36//! - [`Term`] / [`Cardinality`] / [`validate_enum`] — a controlled vocabulary
37//! and the logic to check a value against one (closed-vocabulary rejection,
38//! open-vocabulary near-miss warnings). Cardinality (one vs. many) is pure
39//! data shape, useful even to a constraint this crate doesn't otherwise model
40//! (a relation/reference field, for instance).
41//! - [`VocabularyDoc`] / [`parse_vocabulary`] — load a term set from the
42//! shared `vocabulary: { field, values }` / `terms:` document convention, so
43//! independent embedders can point at the same vocabulary document without
44//! either depending on the other.
45//! - [`lint_vocabulary`] / [`Finding`] — judge such a document rather than read
46//! it. [`parse_vocabulary`] is permissive by design (a key it cannot read is
47//! a key it skips), which leaves a set of ways a document can say something
48//! nothing acts on — `values: cloesd` loading as an *open* vocabulary being
49//! the one with teeth. This is where an author is told. [`load_schema`]
50//! reports the same kind of finding over a schema document, and the
51//! `fig-schema` binary in this crate is a front end for both, reachable as
52//! `fig schema lint` wherever fig is installed.
53//! - [`load_schema`] / [`Loaded`] / [`LoadError`] — a [`Schema`] from a
54//! document, with an [`Origin`] on every rule saying which document and
55//! which entry it was read from, so the precedence include order decided is
56//! visible rather than inferred.
57//! - [`Presentation`] / [`Icon`] / [`Tint`] — renderer-neutral display hints,
58//! carried on every rule but never interpreted here.
59//! - [`Consequence`] / [`Severity`] — what changing a field *costs*, so a host
60//! can warn before committing an expensive or irreversible edit. A separate
61//! fact from a [`Tint`], which says only how loudly to draw the field.
62//!
63//! - [`Issue`] / [`IssueKind`] — why a value failed, as data rather than
64//! prose, so the embedder owns the wording. [`Issue`]'s `Display` renders a
65//! reasonable English default for embedders that don't care.
66//! [`IssueKind::Unchecked`] is the one that says a value was *not checked*
67//! rather than that it is wrong — a constraint of a kind the validator does
68//! not know fails closed, and this is how a reader tells the two apart.
69//! - [`Schema::check`] / [`Verdict`] — the whole-document check: every node
70//! against the rule that governs it, its shape against the rule's type
71//! ([`FieldType::admits`]) and its value against the rule's constraint.
72//! What `fig check` does not answer: not whether a file parses, but whether
73//! what it parsed is valid. `fig-schema check` is this over a file and a
74//! discovered schema; `explain` and `complete` are [`Schema::rules_for`]
75//! and a rule's terms, rendered.
76//!
77//! The public structs are `#[non_exhaustive]`, so they are built from a
78//! constructor plus chainable setters ([`FieldRule::new`], [`Term::value`],
79//! [`Presentation::default`]) rather than a struct literal. That is what lets a
80//! later release add a hint without costing every embedder a major version.
81//!
82//! # Example
83//!
84//! ```
85//! use fig::Value;
86//! use fig_schema::{
87//! Consequence, FieldRule, FieldType, PathPat, Presentation, Schema, Seg, Severity,
88//! Term, Validate, Validation, validate_enum,
89//! };
90//!
91//! // The embedder's own constraint type — the seam this crate is built around.
92//! struct Vocabulary { values: Vec<Term>, closed: bool }
93//!
94//! impl Validate for Vocabulary {
95//! fn validate(&self, value: &Value) -> Validation {
96//! validate_enum(&self.values, self.closed, value)
97//! }
98//! }
99//!
100//! let schema = Schema::new(vec![
101//! FieldRule::new(PathPat::each_item_of("audience"))
102//! .ty(FieldType::Str)
103//! .constraint(Vocabulary {
104//! values: vec![Term::value("public"), Term::value("family")],
105//! closed: true,
106//! })
107//! .present(Presentation::default().title("Audience"))
108//! .on_change(
109//! Consequence::when("public", "Anyone with the link will be able to read this.")
110//! .severity(Severity::Confirm),
111//! ),
112//! ]);
113//!
114//! // Find the rule governing `audience[0]`, then check a candidate against it.
115//! let path = [Seg::Key("audience".into()), Seg::Index(0)];
116//! let rule = schema.rule_for(&path).expect("a rule governs this path");
117//! assert!(rule.validate(&Value::Str("public".into())).is_ok());
118//!
119//! // Valid, but not free — ask before committing it.
120//! assert_eq!(
121//! rule.severity_of(&Value::Str("public".into())),
122//! Some(Severity::Confirm),
123//! );
124//! assert_eq!(rule.severity_of(&Value::Str("family".into())), None);
125//!
126//! let rejected = rule.validate(&Value::Str("familly".into()));
127//! assert!(rejected.is_reject());
128//! assert_eq!(
129//! rejected.issue().unwrap().suggestion.as_deref(),
130//! Some("family"),
131//! );
132//! ```
133
134mod check;
135mod consequence;
136mod field;
137mod lint;
138mod load;
139mod path;
140mod present;
141mod vocab;
142
143pub use check::{Verdict, VerdictKind};
144pub use consequence::{Consequence, Severity, guards_without_terms};
145pub use field::{FieldRule, FieldType, Origin, Schema};
146pub use lint::{Finding, FindingKind, lint_vocabulary};
147pub use load::{Constraint, LoadError, LoadErrorKind, Loaded, load_schema};
148pub use path::{PathPat, PatternError, Seg, SegPat, render_path, value_at};
149pub use present::{Icon, Presentation, Tint};
150pub use vocab::{
151 Cardinality, Issue, IssueKind, Term, Validate, Validation, VocabularyDoc, parse_vocabulary,
152 validate_enum,
153};