Expand description
fig-schema — the schema layer: what a field expects — its type, its
allowed values, and how to present it — layered over fig’s schema-free
value tree.
fig parses bytes → fig::Value and edits losslessly; it has no notion of
“what is valid here”. This crate adds that knowledge as a generic,
embedder-agnostic engine. It never learns the word “prov” or “flower”: a
consumer (prov, for frontmatter fields; flower, for a metadata editor)
defines its own constraint type — an enum covering whatever kinds of
constraint it needs (a controlled vocabulary, a reference into a
workspace, …) — and implements Validate on it. FieldRule/Schema
are generic over that type, so the path-matching and commit-time
validation plumbing is written once, here, and reused by every embedder.
A schema is also a document. load_schema reads one written to the
schema document format — docs/schema-format.md, a fig document in any of
fig’s languages, composed from others by include and from vocabulary
documents by constraint.from — into a Schema<Constraint>, where
Constraint is this crate’s own type: a vocabulary, or an
Other kind it does not know, which validates to
unchecked rather than pretending. An embedder maps that into its own
constraint type with Schema::map_constraints and keeps the seam; the
fig-schema binary checks documents against it with no embedder at all.
What’s genuinely reusable, and lives here as concrete types rather than being left to the embedder:
-
PathPat/SegPat— pattern-matching a fig path, including “every item of this list” (SegPat::EachItem) and “this subtree” (SegPat::AnyDepth);PathPat::parsereads one from the format’s grammar (audience[],meta.**) andrender_pathis its inverse. -
FieldType— the expected type, type-directed coercion of an edit buffer (FieldType::coerce), whether a parsed value already has the type (FieldType::admits), and the name the format spells it by (FieldType::from_name). -
Term/Cardinality/validate_enum— a controlled vocabulary and the logic to check a value against one (closed-vocabulary rejection, open-vocabulary near-miss warnings). Cardinality (one vs. many) is pure data shape, useful even to a constraint this crate doesn’t otherwise model (a relation/reference field, for instance). -
VocabularyDoc/parse_vocabulary— load a term set from the sharedvocabulary: { field, values }/terms:document convention, so independent embedders can point at the same vocabulary document without either depending on the other. -
lint_vocabulary/Finding— judge such a document rather than read it.parse_vocabularyis permissive by design (a key it cannot read is a key it skips), which leaves a set of ways a document can say something nothing acts on —values: cloesdloading as an open vocabulary being the one with teeth. This is where an author is told.load_schemareports the same kind of finding over a schema document, and thefig-schemabinary in this crate is a front end for both, reachable asfig schema lintwherever fig is installed. -
load_schema/Loaded/LoadError— aSchemafrom a document, with anOriginon every rule saying which document and which entry it was read from, so the precedence include order decided is visible rather than inferred. -
Presentation/Icon/Tint— renderer-neutral display hints, carried on every rule but never interpreted here. -
Consequence/Severity— what changing a field costs, so a host can warn before committing an expensive or irreversible edit. A separate fact from aTint, which says only how loudly to draw the field. -
Issue/IssueKind— why a value failed, as data rather than prose, so the embedder owns the wording.Issue’sDisplayrenders a reasonable English default for embedders that don’t care.IssueKind::Uncheckedis the one that says a value was not checked rather than that it is wrong — a constraint of a kind the validator does not know fails closed, and this is how a reader tells the two apart. -
Schema::check/Verdict— the whole-document check: every node against the rule that governs it, its shape against the rule’s type (FieldType::admits) and its value against the rule’s constraint. Whatfig checkdoes not answer: not whether a file parses, but whether what it parsed is valid.fig-schema checkis this over a file and a discovered schema;explainandcompleteareSchema::rules_forand a rule’s terms, rendered.
The public structs are #[non_exhaustive], so they are built from a
constructor plus chainable setters (FieldRule::new, Term::value,
Presentation::default) rather than a struct literal. That is what lets a
later release add a hint without costing every embedder a major version.
§Example
use fig::Value;
use fig_schema::{
Consequence, FieldRule, FieldType, PathPat, Presentation, Schema, Seg, Severity,
Term, Validate, Validation, validate_enum,
};
// The embedder's own constraint type — the seam this crate is built around.
struct Vocabulary { values: Vec<Term>, closed: bool }
impl Validate for Vocabulary {
fn validate(&self, value: &Value) -> Validation {
validate_enum(&self.values, self.closed, value)
}
}
let schema = Schema::new(vec![
FieldRule::new(PathPat::each_item_of("audience"))
.ty(FieldType::Str)
.constraint(Vocabulary {
values: vec![Term::value("public"), Term::value("family")],
closed: true,
})
.present(Presentation::default().title("Audience"))
.on_change(
Consequence::when("public", "Anyone with the link will be able to read this.")
.severity(Severity::Confirm),
),
]);
// Find the rule governing `audience[0]`, then check a candidate against it.
let path = [Seg::Key("audience".into()), Seg::Index(0)];
let rule = schema.rule_for(&path).expect("a rule governs this path");
assert!(rule.validate(&Value::Str("public".into())).is_ok());
// Valid, but not free — ask before committing it.
assert_eq!(
rule.severity_of(&Value::Str("public".into())),
Some(Severity::Confirm),
);
assert_eq!(rule.severity_of(&Value::Str("family".into())), None);
let rejected = rule.validate(&Value::Str("familly".into()));
assert!(rejected.is_reject());
assert_eq!(
rejected.issue().unwrap().suggestion.as_deref(),
Some("family"),
);Structs§
- Consequence
- A cost of changing a field, declared on the rule that governs it.
- Field
Rule - One field rule: which node(s) it governs, the type it expects, an optional
constraint of the embedder’s own type
C, and how to present it. - Finding
- One thing the lint has to say about a vocabulary document.
- Issue
- Why a value failed to validate.
- Load
Error - Why a document could not be loaded as a schema. Names the document, where
in it, and what was wrong; the
Displayis one sentence for a person. - Loaded
- What
load_schemareturns: the schema, and what the loader noticed on the way that is worth telling the author without refusing the document. - Origin
- Which document a rule was read from, and where in it — what makes
precedence visible. A schema composed from several documents decides
which rule wins a path by include order, and a person asking “why did this
rule govern, and what did it shadow” needs each rule to say where it came
from.
fig-schema explainprints one per matching rule. - PathPat
- A path pattern. Unlike a concrete
Segpath it can reach every element of a sequence (SegPat::EachItem), every entry of a mapping (SegPat::AnyKey), or a whole subtree (SegPat::AnyDepth), so a rule can constrain each item of a list field (tags:,audience:) or everything beneath a key. - Presentation
- Presentation hints for one field rule.
- Schema
- A set of field rules. Matched against a row’s fig path to find what governs it.
- Term
- One term of a controlled vocabulary.
- Verdict
- One thing a check has to say about a document: which node, and what is wrong with it — or that it could not be checked. A clean document has none.
- Vocabulary
Doc - A controlled vocabulary loaded from its own document: the
fieldit governs, whether its value set is closed, and the terms themselves — ready to hand tovalidate_enum.
Enums§
- Cardinality
- Whether a reference or list-shaped field holds one entry or many. Pure data
shape — reused by an embedder’s own reference/relation constraint (prov’s
spanning/cardinalityconcepts, for instance) without this crate needing to know what a “relation” is. - Constraint
- This crate’s own constraint type: what a schema document’s
constraintloads as. One variant for the kind the format defines and one for every kind it does not. - Field
Type - The type a field expects. Drives type-directed parsing and widget choice.
- Finding
Kind - The kind of a
Finding. - Icon
- A semantic icon hint. Frontends map to their own symbol set.
- Issue
Kind - The kind of an
Issue. - Load
Error Kind - The kind of a
LoadError. - Pattern
Error - Why a string is not a path pattern. Every variant carries the byte offset into the text where the problem starts.
- Seg
- One step of a fig path: a mapping key or a sequence index. Owned (unlike
fig::Segment<'a>, which borrows), so a path can outlive a single FFI call. - SegPat
- One step of a
PathPat. - Severity
- What the host should do about a consequence — the interaction, not a
measure of how bad it is. Mirrors
Validation’s Ok/Warn/Reject: the crate names the response, the embedder renders it. - Tint
- A semantic tint hint. Frontends map to theme-adaptive colours.
- Validation
- The result of validating a value against a field’s constraint at commit time.
- Verdict
Kind - The kind of a
Verdict.
Traits§
- Validate
- A field constraint that knows how to check a candidate value. An embedder
implements this on its own constraint type (an enum with a vocabulary
variant, a reference variant, whatever it needs);
crate::FieldRule::validatedispatches to it generically.
Functions§
- guards_
without_ terms - Guards that name a value the vocabulary doesn’t have — a lint, run when an embedder loads its schema, not part of validation.
- lint_
vocabulary - Lint a vocabulary document, given its top-level value. An empty result is a clean document.
- load_
schema - Load the schema document at
path, following everyincludeand everyconstraint.fromfrom there, withreadas the way from a path to theValueit holds. - parse_
vocabulary - Parse a vocabulary document from its top-level value: a
vocabulary: { field, values }marker plus aterms:mapping, each entry either a bare key (a live term with no metadata) or a{ label?, description?, retired? }mapping. ReturnsNonewhenvaluecarries novocabularymarker — i.e. it is not a vocabulary document. - render_
path - A concrete path as text: keys joined by
., an index as[i], and the empty string for the document root —meta.author,audience[1],items[0].title. This is how fig’s ownWarningaddresses a node and how aFindingdoes, so the three agree. - validate_
enum - Validate
valueagainst a controlled vocabulary — the reusable logic behind any embedder’s vocabulary-shaped constraint. - value_
at - The node a concrete
pathaddresses invalue, if there is one — a key looked up in a mapping (last-wins on duplicates, asValue::getis), an index in a sequence, and nothing anywhere else.