Skip to main content

Schema

Struct Schema 

Source
pub struct Schema<C> { /* private fields */ }
Expand description

A set of field rules. Matched against a row’s fig path to find what governs it.

Implementations§

Source§

impl<C: Validate> Schema<C>

Source

pub fn check(&self, document: &Value) -> Vec<Verdict>

Check a whole parsed document against this schema: every node, against the rule Schema::rule_for names for it, twice — its shape against the rule’s ty, then its value against the rule’s constraint. What comes back is only what is wrong or unchecked, in post-order, so a clean document yields nothing.

Three rules of the walk are choices rather than consequences, and each could have gone the other way:

  • A node no rule governs is not a verdict. A schema governs what it names. A check that fired on a document’s own title/author — keys the schema never mentions — is one people stop running.
  • The same issue about the same value is reported once, at the deepest path. validate_enum validates a sequence element-wise, so a rule at audience and a rule at audience[] — an embedder emits both, so a field is governed whether written as a scalar or a list — would otherwise report one misspelling twice. The walk is post-order, and a container’s issue is dropped when a descendant already reported an equal one.
  • An empty document is valid. The model has no notion of a required field: a FieldRule says what a value must be if there is one, and nothing says there must be one. So a check never reports a missing field, and a document with nothing in it has nothing wrong with it.

One limit besides: a mapping entry whose key is not text has no Seg to address it, so no rule can govern it and it is not walked.

use fig::Value;
use fig_schema::{FieldRule, FieldType, PathPat, Schema, Term, Validate, Validation, validate_enum};

struct Vocabulary(Vec<Term>);
impl Validate for Vocabulary {
    fn validate(&self, value: &Value) -> Validation {
        validate_enum(&self.0, true, value)
    }
}

let schema = Schema::new(vec![
    FieldRule::new(PathPat::each_item_of("audience"))
        .ty(FieldType::Str)
        .constraint(Vocabulary(vec![Term::value("public"), Term::value("family")])),
    FieldRule::new(PathPat::key("count")).ty(FieldType::Int),
]);

let document = fig::Document::parse(
    b"audience: [public, famly]\ncount: three\ntitle: untouched\n",
    fig_yaml::format().unwrap(),
).unwrap();
let verdicts = schema.check(&document.to_value().unwrap());

let report: Vec<String> = verdicts.iter().map(|v| format!("{}: {v}", v.at())).collect();
assert_eq!(report, [
    "audience[1]: “famly” is not a known value — did you mean “family”?",
    "count: expected int, found str",
]);
assert!(verdicts.iter().all(|v| v.is_error()));
Source§

impl<C> Schema<C>

Source

pub fn new(rules: Vec<FieldRule<C>>) -> Self

Build a schema from its rules.

Source

pub fn rules(&self) -> &[FieldRule<C>]

The rules, in declaration order.

Source

pub fn into_rules(self) -> Vec<FieldRule<C>>

The rules, owned — for concatenating schemas, or for mapping every constraint into another type with FieldRule::map_constraint.

Source

pub fn map_constraints<D>(self, f: impl FnMut(C) -> D) -> Schema<D>

Every rule’s constraint mapped into another type; see FieldRule::map_constraint.

Source

pub fn is_empty(&self) -> bool

Whether the schema carries no rules (nothing to apply).

Source

pub fn rule_for(&self, path: &[Seg]) -> Option<&FieldRule<C>>

The first rule whose pattern matches path, if any. Declaration order is precedence, so a more specific rule should be listed before a broader one.

Source

pub fn rules_for<'s, 'p: 's>( &'s self, path: &'p [Seg], ) -> impl Iterator<Item = &'s FieldRule<C>> + 's

Every rule whose pattern matches path, in precedence order — the first is what Schema::rule_for returns, and the rest are the rules it shadows. That is what makes precedence visible: a schema composed from several documents decides it by include order, and this is how a tool shows a person which later rule a path would otherwise have hit.

Trait Implementations§

Source§

impl<C: Clone> Clone for Schema<C>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<C: Debug> Debug for Schema<C>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C> Default for Schema<C>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<C> Freeze for Schema<C>
where Vec<FieldRule<C>>: Freeze,

§

impl<C> RefUnwindSafe for Schema<C>

§

impl<C> Send for Schema<C>
where Vec<FieldRule<C>>: Send,

§

impl<C> Sync for Schema<C>
where Vec<FieldRule<C>>: Sync,

§

impl<C> Unpin for Schema<C>
where Vec<FieldRule<C>>: Unpin,

§

impl<C> UnsafeUnpin for Schema<C>

§

impl<C> UnwindSafe for Schema<C>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.