Skip to main content

fig_schema/
field.rs

1//! The generic rule-matching engine: [`FieldRule`] and [`Schema`], both
2//! parameterized over the embedder's own constraint type `C`. This crate
3//! supplies the matching and type-coercion machinery; `C` is where an
4//! embedder plugs in what a constraint actually *is* (a controlled vocabulary,
5//! a reference into a workspace, or a sum of both) by implementing
6//! [`crate::Validate`] on it.
7
8use std::fmt;
9use std::path::PathBuf;
10
11use fig::{ExtKind, Value};
12
13use crate::consequence::Consequence;
14use crate::path::{PathPat, Seg};
15use crate::present::Presentation;
16use crate::vocab::{Validate, Validation};
17
18/// The type a field expects. Drives type-directed parsing and widget choice.
19///
20/// `#[non_exhaustive]`: fig gains [`ExtKind`]s and a schema gains field shapes
21/// in ordinary releases, so a `match` needs a `_` arm. Constructing a variant
22/// is unaffected.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum FieldType {
26    Null,
27    Bool,
28    Int,
29    Float,
30    Str,
31    /// A link into the workspace (stored textually, like `Str`, but a reference).
32    Ref,
33    /// A format-specific scalar carried verbatim — a TOML datetime, a ZON enum
34    /// or char literal. Coercing to one keeps the value's native type instead
35    /// of quoting it into a string, so a TOML `date = 1979-05-27` survives an
36    /// edit as a date rather than becoming `date = "1979-05-27"`.
37    Extended(ExtKind),
38    Map,
39    Seq,
40}
41
42impl FieldType {
43    /// The type a parsed `value` *has* — the shape half of a check, and the
44    /// counterpart of [`FieldType::coerce`], which reads text *into* a type.
45    /// Total: every [`Value`] has one. A [`Value::Uint`] is an [`Int`](Self::Int),
46    /// since that is only fig's spelling for an integer past `i64::MAX`.
47    ///
48    /// Never [`Ref`](Self::Ref): a reference is stored as text, and nothing in
49    /// the value says it is one. [`FieldType::admits`] is where `Ref` accepts a
50    /// string.
51    pub fn of(value: &Value) -> FieldType {
52        match value {
53            Value::Null => FieldType::Null,
54            Value::Bool(_) => FieldType::Bool,
55            Value::Int(_) | Value::Uint(_) => FieldType::Int,
56            Value::Float(_) => FieldType::Float,
57            Value::Str(_) => FieldType::Str,
58            Value::Extended { kind, .. } => FieldType::Extended(*kind),
59            Value::Seq(_) => FieldType::Seq,
60            Value::Map(_) => FieldType::Map,
61        }
62    }
63
64    /// Whether a parsed `value` already has this type — the question a
65    /// whole-document check asks at every governed node, which
66    /// [`FieldType::coerce`] does not: that reads an edit buffer *into* a
67    /// type, and this asks whether what the parser produced fits one.
68    ///
69    /// Mostly [`FieldType::of`] and equality, plus the widenings a reader
70    /// expects, each of which is a convention the rest of the crate already
71    /// follows rather than a choice made here:
72    ///
73    /// - **A type names the item, and a list of items has the type too.**
74    ///   `Str` admits `public` and `[public, family]` alike, one level deep —
75    ///   a list of strings and not a list of lists — because an embedder
76    ///   declares a field once and writes it as a scalar or a list as the
77    ///   document pleases, which is how [`validate_enum`](crate::validate_enum)
78    ///   already checks one. An empty list is a list of items every one of
79    ///   which fits, so it fits.
80    /// - [`Float`](Self::Float) admits an integer, and [`Ref`](Self::Ref)
81    ///   admits a string, since a reference is stored as one.
82    /// - [`Extended`](Self::Extended) admits an extended value of the same
83    ///   kind, **or a string shaped like one** — the same cheap guard
84    ///   [`FieldType::coerce`] uses when writing one. YAML, JSON and markdown
85    ///   frontmatter have no date literal, so `created: 1979-05-27` there is
86    ///   text, and a date field that refused it would fail every document in
87    ///   those formats against its own schema. The value stays a string; this
88    ///   says only that it could be the type it was declared.
89    pub fn admits(self, value: &Value) -> bool {
90        if self.admits_item(value) {
91            return true;
92        }
93        match value {
94            Value::Seq(items) => items.iter().all(|item| self.admits_item(item)),
95            _ => false,
96        }
97    }
98
99    /// [`FieldType::admits`] without the list rule: whether `value` itself
100    /// has this type.
101    fn admits_item(self, value: &Value) -> bool {
102        let found = FieldType::of(value);
103        match self {
104            FieldType::Float => matches!(found, FieldType::Float | FieldType::Int),
105            FieldType::Ref => found == FieldType::Str,
106            FieldType::Extended(kind) => match value {
107                Value::Str(text) => extended_text_fits(kind, text),
108                _ => found == self,
109            },
110            expected => found == expected,
111        }
112    }
113
114    /// Coerce an edit-buffer string to this type — the schema-directed
115    /// counterpart of shape-guessing. A value that doesn't fit the type falls
116    /// back to a string (the caller's own reparse is the final backstop);
117    /// container types are not scalar-edited, so they also pass through as text.
118    ///
119    /// The numeric types go through [`Value::parse_number`], so the text fig
120    /// itself writes reads back unchanged — including the `.inf`/`.nan`
121    /// spellings `str::parse::<f64>` rejects. Those still have no
122    /// representation in JSON or TOML, so an embedder targeting those formats
123    /// should reject them before they reach here.
124    pub fn coerce(self, s: &str) -> Value {
125        let t = s.trim();
126        match self {
127            // Only the null spellings mean null; anything else is real text the
128            // user typed, and silently dropping it would lose their edit.
129            FieldType::Null => match t {
130                "" | "~" => Value::Null,
131                _ if t.eq_ignore_ascii_case("null") => Value::Null,
132                _ => Value::Str(s.to_string()),
133            },
134            // The YAML 1.1 spellings are all accepted: the field is *declared*
135            // a bool, so `yes`/`on` are unambiguous here — the "Norway problem"
136            // is a hazard of untyped inference, which is exactly what a schema
137            // replaces. The coerced value is canonical either way.
138            FieldType::Bool => match t.to_ascii_lowercase().as_str() {
139                "true" | "yes" | "on" => Value::Bool(true),
140                "false" | "no" | "off" => Value::Bool(false),
141                _ => Value::Str(s.to_string()),
142            },
143            // fig's own parser owns the widening rule (`i64`, then `u64`).
144            // It falls back to a float when the text is neither, which for a
145            // field declared `Int` is not a fit — so that lands in the string
146            // fallback like any other miss.
147            FieldType::Int => match Value::parse_number(t, false) {
148                Ok(v) if !v.is_f64() => v,
149                _ => Value::Str(s.to_string()),
150            },
151            // Via fig's parser so the `.inf`/`.nan` spellings fig *writes* read
152            // back as floats. `str::parse::<f64>` rejects them, so a no-op edit
153            // of a field holding `.inf` used to commit the string `".inf"` back
154            // over the float.
155            FieldType::Float => {
156                Value::parse_number(t, true).unwrap_or_else(|_| Value::Str(s.to_string()))
157            }
158            FieldType::Extended(kind) => {
159                if extended_text_fits(kind, t) {
160                    Value::Extended {
161                        kind,
162                        text: t.to_string(),
163                    }
164                } else {
165                    Value::Str(s.to_string())
166                }
167            }
168            // A string/ref field keeps its literal text — the whole point of
169            // type-directed parsing: `"123"` in a `str` field stays a string.
170            FieldType::Str | FieldType::Ref | FieldType::Map | FieldType::Seq => {
171                Value::Str(s.to_string())
172            }
173        }
174    }
175}
176
177/// Every type the schema document format can name, with its name: the table
178/// [`FieldType::from_name`] reads and [`FieldType`]'s `Display` writes, so the
179/// two cannot drift. The names are the ones prov's `fields.<name>.type`
180/// already uses, so a schema document, a prov config and an editor spell a
181/// type one way.
182///
183/// Not every [`ExtKind`] is here: a kind with no row (`NumberSpecial`, and the
184/// plist date, a byte string) cannot be declared in a document, and displays as its fig name
185/// in kebab case instead.
186const NAMES: &[(&str, FieldType)] = &[
187    ("null", FieldType::Null),
188    ("bool", FieldType::Bool),
189    ("int", FieldType::Int),
190    ("float", FieldType::Float),
191    ("str", FieldType::Str),
192    ("ref", FieldType::Ref),
193    ("date", FieldType::Extended(ExtKind::LocalDate)),
194    ("datetime", FieldType::Extended(ExtKind::OffsetDateTime)),
195    (
196        "local-datetime",
197        FieldType::Extended(ExtKind::LocalDateTime),
198    ),
199    ("time", FieldType::Extended(ExtKind::LocalTime)),
200    ("enum", FieldType::Extended(ExtKind::EnumLiteral)),
201    ("char", FieldType::Extended(ExtKind::CharLiteral)),
202    ("map", FieldType::Map),
203    ("seq", FieldType::Seq),
204];
205
206impl FieldType {
207    /// The type a schema document's `type` key names — `int`, `str`, `date`,
208    /// `seq` — or `None` for a name the format does not define. The loader
209    /// treats that `None` as an error rather than a dropped type; see
210    /// [`FieldType::suggest_name`] for the sentence it adds.
211    ///
212    /// ```
213    /// use fig::ExtKind;
214    /// use fig_schema::FieldType;
215    ///
216    /// assert_eq!(FieldType::from_name("str"), Some(FieldType::Str));
217    /// assert_eq!(FieldType::from_name("date"), Some(FieldType::Extended(ExtKind::LocalDate)));
218    /// assert_eq!(FieldType::from_name("string"), None);
219    /// ```
220    pub fn from_name(name: &str) -> Option<FieldType> {
221        NAMES
222            .iter()
223            .find(|(known, _)| *known == name)
224            .map(|(_, ty)| *ty)
225    }
226
227    /// The name a person who wrote `name` most likely meant, for the error a
228    /// loader reports: `string` is answered with `str`, since that is figl's
229    /// own annotation name and the one most likely reached for; `boolean`,
230    /// `integer`, `list`, `array`, `object`, `dict` and `text` with the type
231    /// each is another word for. `None` when nothing is close.
232    pub fn suggest_name(name: &str) -> Option<&'static str> {
233        let lower = name.to_ascii_lowercase();
234        Some(match lower.as_str() {
235            "string" | "text" => "str",
236            "boolean" => "bool",
237            "integer" | "i64" | "u64" => "int",
238            "number" | "f64" | "double" => "float",
239            "list" | "array" | "sequence" => "seq",
240            "object" | "dict" | "mapping" | "table" => "map",
241            "reference" | "link" => "ref",
242            "local-date" => "date",
243            "offset-datetime" => "datetime",
244            "local-time" => "time",
245            _ => {
246                return NAMES
247                    .iter()
248                    .map(|(known, _)| *known)
249                    .find(|known| *known == lower);
250            }
251        })
252    }
253}
254
255impl fmt::Display for FieldType {
256    /// The type's name as the schema document format spells it — `int`,
257    /// `str`, `date`, `seq` — so a message reads the way the rule was written,
258    /// and [`FieldType::from_name`] reads it back. An extended kind the format
259    /// cannot name is its fig name in kebab case (`number-special`), or
260    /// `extended` for a kind newer than this crate.
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        if let Some((name, _)) = NAMES.iter().find(|(_, ty)| ty == self) {
263            return f.write_str(name);
264        }
265        f.write_str(match self {
266            FieldType::Extended(ExtKind::NumberSpecial) => "number-special",
267            FieldType::Extended(ExtKind::PlistDate) => "plist-date",
268            FieldType::Extended(ExtKind::Data) => "data",
269            // `ExtKind` is `#[non_exhaustive]`; see `extended_text_fits`.
270            _ => "extended",
271        })
272    }
273}
274
275/// Whether `text` is shaped like a literal of `kind`.
276///
277/// A [`Value::Extended`] is printed verbatim and *unquoted*, so garbage here
278/// would emit a document the format can't reparse (`date = not a date`). This
279/// is a cheap shape guard, not a parser: it rejects what obviously can't be a
280/// literal and leaves the rest to the format's own reader.
281fn extended_text_fits(kind: ExtKind, text: &str) -> bool {
282    if text.is_empty() {
283        return false;
284    }
285    match kind {
286        // Digits and the punctuation that separates them.
287        ExtKind::OffsetDateTime
288        | ExtKind::LocalDateTime
289        | ExtKind::LocalDate
290        | ExtKind::LocalTime => text.chars().all(|c| {
291            c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | '+' | 'T' | 't' | 'Z' | 'z' | ' ')
292        }),
293        // A bare identifier — the text excludes the leading dot.
294        ExtKind::EnumLiteral => {
295            let mut chars = text.chars();
296            chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
297                && chars.all(|c| c.is_alphanumeric() || c == '_')
298        }
299        // Stored as a decimal codepoint.
300        ExtKind::CharLiteral => text.chars().all(|c| c.is_ascii_digit()),
301        ExtKind::NumberSpecial => matches!(
302            text,
303            "Infinity" | "-Infinity" | "+Infinity" | "NaN" | "-NaN" | "+NaN"
304        ),
305        // `ExtKind` is `#[non_exhaustive]`: a fig version newer than this crate
306        // may add a kind we don't recognize yet. This is only a cheap shape
307        // guard (see the doc comment above), so defer to the format's own
308        // reader rather than reject a literal we simply don't have a rule for.
309        _ => true,
310    }
311}
312
313/// One field rule: which node(s) it governs, the type it expects, an optional
314/// constraint of the embedder's own type `C`, and how to present it.
315///
316/// `#[non_exhaustive]`: a rule gains ways to describe a field over time, so it
317/// is built from [`FieldRule::new`] and the chainable setters rather than a
318/// struct literal. Reading the fields is unchanged.
319///
320/// ```
321/// use fig_schema::{FieldRule, FieldType, PathPat, Presentation, Validate, Validation};
322/// # use fig::Value;
323/// # struct Vocab;
324/// # impl Validate for Vocab { fn validate(&self, _: &Value) -> Validation { Validation::Ok } }
325/// let rule = FieldRule::new(PathPat::each_item_of("audience"))
326///     .ty(FieldType::Str)
327///     .constraint(Vocab)
328///     .present(Presentation::default().title("Audience"));
329/// assert_eq!(rule.ty, Some(FieldType::Str));
330/// ```
331#[derive(Debug, Clone)]
332#[non_exhaustive]
333pub struct FieldRule<C> {
334    /// Which node(s) this governs (reaches list *elements*, not only scalars).
335    pub at: PathPat,
336    /// The expected type — drives type-directed parsing and widget choice.
337    pub ty: Option<FieldType>,
338    /// A value constraint, in whatever shape the embedder defines.
339    pub constraint: Option<C>,
340    /// Renderer-neutral presentation hints.
341    pub present: Presentation,
342    /// What changing this field costs, if anything — see [`Consequence`].
343    ///
344    /// Beside the presentation hints rather than inside them: a cost is a fact
345    /// about the field, not a way of drawing it, and a host that ignores every
346    /// other hint must still honour these.
347    pub on_change: Vec<Consequence>,
348    /// Where this rule was read from, when it was read from a document rather
349    /// than built in Rust — see [`Origin`].
350    pub origin: Option<Origin>,
351}
352
353/// Which document a rule was read from, and where in it — what makes
354/// precedence *visible*. A schema composed from several documents decides
355/// which rule wins a path by include order, and a person asking "why did this
356/// rule govern, and what did it shadow" needs each rule to say where it came
357/// from. `fig-schema explain` prints one per matching rule.
358///
359/// `None` on a [`FieldRule`] built in Rust; set by
360/// [`load_schema`](crate::load_schema) on every rule it reads.
361///
362/// `#[non_exhaustive]`: an origin gains detail (a line, once fig exposes one)
363/// the same way an [`Issue`](crate::Issue) does. Built with [`Origin::new`].
364#[derive(Debug, Clone, PartialEq, Eq)]
365#[non_exhaustive]
366pub struct Origin {
367    /// The document, as the loader was given it or resolved it — so an
368    /// included document is named relative to the one that included it.
369    pub document: PathBuf,
370    /// Where in that document, as a fig path: `rules[2]` for the third entry
371    /// of a schema document's `rules`, `vocabulary` for the one rule a
372    /// vocabulary document declares.
373    pub at: String,
374}
375
376impl Origin {
377    /// A rule read from `document` at the fig path `at`.
378    pub fn new(document: impl Into<PathBuf>, at: impl Into<String>) -> Self {
379        Self {
380            document: document.into(),
381            at: at.into(),
382        }
383    }
384}
385
386impl fmt::Display for Origin {
387    /// `vocab/audience.figl rules[0]` — the document, then the path.
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        write!(f, "{} {}", self.document.display(), self.at)
390    }
391}
392
393impl<C> FieldRule<C> {
394    /// A rule governing `at`, with no type, no constraint and no presentation
395    /// hints — the parts a caller adds with the setters below.
396    pub fn new(at: PathPat) -> Self {
397        Self {
398            at,
399            ty: None,
400            constraint: None,
401            present: Presentation::default(),
402            on_change: Vec::new(),
403            origin: None,
404        }
405    }
406
407    /// Set the expected type. Takes a [`FieldType`] or an `Option<FieldType>`,
408    /// so a caller reading a config that may not declare one can pass it
409    /// straight through.
410    pub fn ty(mut self, ty: impl Into<Option<FieldType>>) -> Self {
411        self.ty = ty.into();
412        self
413    }
414
415    /// Set the value constraint.
416    ///
417    /// This one takes a `C` rather than an `impl Into<Option<C>>` the way
418    /// [`FieldRule::ty`] does: with `C` otherwise unconstrained, `Into` cannot
419    /// tell `C` from `Option<C>` and the call fails to infer. Use
420    /// [`FieldRule::constraint_opt`] for a constraint that may be absent.
421    pub fn constraint(mut self, constraint: C) -> Self {
422        self.constraint = Some(constraint);
423        self
424    }
425
426    /// Set the value constraint from an optional one. `None` leaves the rule
427    /// imposing nothing, which is what a type-only rule wants.
428    pub fn constraint_opt(mut self, constraint: Option<C>) -> Self {
429        self.constraint = constraint;
430        self
431    }
432
433    /// Set the presentation hints.
434    pub fn present(mut self, present: Presentation) -> Self {
435        self.present = present;
436        self
437    }
438
439    /// Declare one more consequence of changing this field. Appends, so a rule
440    /// can carry a blanket cost and a value-specific one by calling this twice
441    /// — see [`FieldRule::consequences_of`].
442    pub fn on_change(mut self, consequence: Consequence) -> Self {
443        self.on_change.push(consequence);
444        self
445    }
446
447    /// Set the whole consequence list at once, for a caller building it from a
448    /// config rather than declaring it inline. Replaces rather than appends.
449    pub fn on_change_all(mut self, consequences: Vec<Consequence>) -> Self {
450        self.on_change = consequences;
451        self
452    }
453
454    /// Record where this rule was read from. The loader's; a rule built in
455    /// Rust has no origin to record.
456    pub fn origin(mut self, origin: Origin) -> Self {
457        self.origin = Some(origin);
458        self
459    }
460
461    /// The same rule with its constraint mapped into another type — how an
462    /// embedder turns a loaded [`Schema<Constraint>`](crate::Constraint) into
463    /// a schema over its own constraint type, keeping every other fact about
464    /// the rule as read.
465    pub fn map_constraint<D>(self, f: impl FnOnce(C) -> D) -> FieldRule<D> {
466        FieldRule {
467            at: self.at,
468            ty: self.ty,
469            constraint: self.constraint.map(f),
470            present: self.present,
471            on_change: self.on_change,
472            origin: self.origin,
473        }
474    }
475}
476
477impl<C: Validate> FieldRule<C> {
478    /// Validate a candidate `value` against this rule's constraint. A rule with
479    /// no constraint (or a type-only rule) imposes nothing here.
480    pub fn validate(&self, value: &Value) -> Validation {
481        match &self.constraint {
482            Some(c) => c.validate(value),
483            None => Validation::Ok,
484        }
485    }
486}
487
488/// A set of field rules. Matched against a row's fig path to find what governs
489/// it.
490#[derive(Debug, Clone)]
491pub struct Schema<C> {
492    rules: Vec<FieldRule<C>>,
493}
494
495impl<C> Default for Schema<C> {
496    fn default() -> Self {
497        Self { rules: Vec::new() }
498    }
499}
500
501impl<C> Schema<C> {
502    /// Build a schema from its rules.
503    pub fn new(rules: Vec<FieldRule<C>>) -> Self {
504        Self { rules }
505    }
506
507    /// The rules, in declaration order.
508    pub fn rules(&self) -> &[FieldRule<C>] {
509        &self.rules
510    }
511
512    /// The rules, owned — for concatenating schemas, or for mapping every
513    /// constraint into another type with [`FieldRule::map_constraint`].
514    pub fn into_rules(self) -> Vec<FieldRule<C>> {
515        self.rules
516    }
517
518    /// Every rule's constraint mapped into another type; see
519    /// [`FieldRule::map_constraint`].
520    pub fn map_constraints<D>(self, mut f: impl FnMut(C) -> D) -> Schema<D> {
521        Schema {
522            rules: self
523                .rules
524                .into_iter()
525                .map(|rule| rule.map_constraint(&mut f))
526                .collect(),
527        }
528    }
529
530    /// Whether the schema carries no rules (nothing to apply).
531    pub fn is_empty(&self) -> bool {
532        self.rules.is_empty()
533    }
534
535    /// The first rule whose pattern matches `path`, if any. Declaration order is
536    /// precedence, so a more specific rule should be listed before a broader one.
537    pub fn rule_for(&self, path: &[Seg]) -> Option<&FieldRule<C>> {
538        self.rules.iter().find(|r| r.at.matches(path))
539    }
540
541    /// Every rule whose pattern matches `path`, in precedence order — the
542    /// first is what [`Schema::rule_for`] returns, and the rest are the rules
543    /// it shadows. That is what makes precedence *visible*: a schema composed
544    /// from several documents decides it by include order, and this is how a
545    /// tool shows a person which later rule a path would otherwise have hit.
546    pub fn rules_for<'s, 'p: 's>(
547        &'s self,
548        path: &'p [Seg],
549    ) -> impl Iterator<Item = &'s FieldRule<C>> + 's {
550        self.rules.iter().filter(move |r| r.at.matches(path))
551    }
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557    use crate::vocab::Issue;
558
559    #[test]
560    fn type_directed_parse_keeps_a_string_field_a_string() {
561        assert_eq!(FieldType::Str.coerce("123"), Value::Str("123".into()));
562        assert_eq!(FieldType::Int.coerce("123"), Value::Int(123));
563        assert_eq!(FieldType::Bool.coerce("true"), Value::Bool(true));
564        // A non-fitting value falls back to a string (reparse is the backstop).
565        assert_eq!(FieldType::Int.coerce("abc"), Value::Str("abc".into()));
566    }
567
568    #[test]
569    fn a_null_field_keeps_text_it_cannot_read_as_null() {
570        assert_eq!(FieldType::Null.coerce(""), Value::Null);
571        assert_eq!(FieldType::Null.coerce("null"), Value::Null);
572        assert_eq!(FieldType::Null.coerce("NULL"), Value::Null);
573        assert_eq!(FieldType::Null.coerce("~"), Value::Null);
574        // Anything else is a real edit, and must not be silently dropped.
575        assert_eq!(
576            FieldType::Null.coerce("important data"),
577            Value::Str("important data".into())
578        );
579    }
580
581    #[test]
582    fn a_bool_field_accepts_the_yaml_spellings() {
583        for yes in ["true", "True", "TRUE", "yes", "Yes", "on"] {
584            assert_eq!(FieldType::Bool.coerce(yes), Value::Bool(true), "{yes}");
585        }
586        for no in ["false", "False", "FALSE", "no", "No", "off"] {
587            assert_eq!(FieldType::Bool.coerce(no), Value::Bool(false), "{no}");
588        }
589        assert_eq!(FieldType::Bool.coerce("maybe"), Value::Str("maybe".into()));
590    }
591
592    #[test]
593    fn a_float_field_reads_back_the_spellings_fig_writes() {
594        // fig serializes a non-finite float as YAML's `.inf`/`.nan`, so that is
595        // the text an edit buffer holds. `str::parse::<f64>` rejects it, which
596        // meant a no-op edit committed the *string* `".inf"` over the float.
597        let inf = FieldType::Float.coerce(".inf");
598        assert!(matches!(inf, Value::Float(f) if f.is_infinite() && f.is_sign_positive()));
599        let neg = FieldType::Float.coerce("-.inf");
600        assert!(matches!(neg, Value::Float(f) if f.is_infinite() && f.is_sign_negative()));
601        assert!(matches!(FieldType::Float.coerce(".nan"), Value::Float(f) if f.is_nan()));
602        // Rust's own spellings still work, and ordinary floats are unaffected.
603        assert!(matches!(FieldType::Float.coerce("inf"), Value::Float(f) if f.is_infinite()));
604        assert_eq!(FieldType::Float.coerce("1.5"), Value::Float(1.5));
605        assert_eq!(FieldType::Float.coerce("nope"), Value::Str("nope".into()));
606    }
607
608    #[test]
609    fn an_int_field_does_not_widen_to_a_float() {
610        // `Value::parse_number` widens to a float as a last resort; a field
611        // declared `Int` treats that as a miss, so the documented string
612        // fallback still applies rather than a silent change of type.
613        assert_eq!(FieldType::Int.coerce("3"), Value::Int(3));
614        assert_eq!(FieldType::Int.coerce("3.5"), Value::Str("3.5".into()));
615        // Past `i64::MAX` is the one place `Uint` is the canonical variant.
616        assert_eq!(
617            FieldType::Int.coerce("9223372036854775808"),
618            Value::Uint(9_223_372_036_854_775_808)
619        );
620    }
621
622    #[test]
623    fn an_extended_field_keeps_its_native_type() {
624        let ty = FieldType::Extended(ExtKind::LocalDate);
625        assert_eq!(
626            ty.coerce("1979-05-27"),
627            Value::Extended {
628                kind: ExtKind::LocalDate,
629                text: "1979-05-27".into(),
630            }
631        );
632        // Text that can't be a date literal would emit an unquoted, unparseable
633        // token, so it falls back to a string like any other bad coercion.
634        assert_eq!(ty.coerce("not a date"), Value::Str("not a date".into()));
635        assert_eq!(ty.coerce(""), Value::Str("".into()));
636    }
637
638    #[test]
639    fn extended_shape_guard_covers_every_kind() {
640        assert!(extended_text_fits(
641            ExtKind::OffsetDateTime,
642            "1979-05-27T07:32:00Z"
643        ));
644        assert!(extended_text_fits(ExtKind::LocalTime, "07:32:00.999"));
645        assert!(extended_text_fits(ExtKind::EnumLiteral, "foo_bar"));
646        assert!(!extended_text_fits(ExtKind::EnumLiteral, "9lives"));
647        assert!(!extended_text_fits(ExtKind::EnumLiteral, "has space"));
648        assert!(extended_text_fits(ExtKind::CharLiteral, "97"));
649        assert!(!extended_text_fits(ExtKind::CharLiteral, "a"));
650        assert!(extended_text_fits(ExtKind::NumberSpecial, "-Infinity"));
651        assert!(!extended_text_fits(ExtKind::NumberSpecial, "inf"));
652    }
653
654    // A minimal `Validate` impl exercises the generic engine end to end without
655    // pulling in a real embedder's constraint type.
656    #[derive(Debug, Clone)]
657    struct AlwaysReject;
658    impl Validate for AlwaysReject {
659        fn validate(&self, _value: &Value) -> Validation {
660            Validation::Reject(Issue::custom("", "no"))
661        }
662    }
663
664    #[test]
665    fn rule_validate_dispatches_to_the_embedder_constraint() {
666        let rule = FieldRule::new(PathPat::key("status"))
667            .ty(FieldType::Str)
668            .constraint(AlwaysReject);
669        assert!(rule.validate(&Value::Str("anything".into())).is_reject());
670    }
671
672    #[test]
673    fn rule_with_no_constraint_always_validates_ok() {
674        let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"));
675        assert_eq!(
676            rule.validate(&Value::Str("anything".into())),
677            Validation::Ok
678        );
679    }
680
681    #[test]
682    fn schema_rule_for_finds_first_match_in_declaration_order() {
683        let schema = Schema::new(vec![
684            FieldRule::new(PathPat::each_item_of("tags"))
685                .ty(FieldType::Str)
686                .constraint_opt(None::<AlwaysReject>),
687            FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
688        ]);
689        assert!(schema.rule_for(&[Seg::Key("title".into())]).is_some());
690        assert!(
691            schema
692                .rule_for(&[Seg::Key("tags".into()), Seg::Index(0)])
693                .is_some()
694        );
695        assert!(schema.rule_for(&[Seg::Key("missing".into())]).is_none());
696    }
697
698    #[test]
699    fn every_value_has_a_type_and_uint_is_an_int() {
700        assert_eq!(FieldType::of(&Value::Null), FieldType::Null);
701        assert_eq!(FieldType::of(&Value::Bool(true)), FieldType::Bool);
702        assert_eq!(FieldType::of(&Value::Int(1)), FieldType::Int);
703        assert_eq!(FieldType::of(&Value::Uint(u64::MAX)), FieldType::Int);
704        assert_eq!(FieldType::of(&Value::Float(1.5)), FieldType::Float);
705        assert_eq!(FieldType::of(&Value::Str("x".into())), FieldType::Str);
706        assert_eq!(
707            FieldType::of(&Value::Extended {
708                kind: ExtKind::LocalDate,
709                text: "1979-05-27".into()
710            }),
711            FieldType::Extended(ExtKind::LocalDate)
712        );
713        assert_eq!(FieldType::of(&Value::Seq(vec![])), FieldType::Seq);
714        assert_eq!(FieldType::of(&Value::Map(vec![])), FieldType::Map);
715    }
716
717    #[test]
718    fn admits_is_equality_plus_the_two_widenings() {
719        let text = Value::Str("123".into());
720        assert!(FieldType::Str.admits(&text));
721        // A reference is stored as text, so a string fits a `Ref` field...
722        assert!(FieldType::Ref.admits(&text));
723        // ...but not the other way round: `Ref` is never what a value *has*.
724        assert!(!FieldType::Int.admits(&text));
725
726        // A float field admits an integer, whichever way fig spelled it.
727        assert!(FieldType::Float.admits(&Value::Int(3)));
728        assert!(FieldType::Float.admits(&Value::Uint(u64::MAX)));
729        assert!(FieldType::Float.admits(&Value::Float(0.5)));
730        // An int field does not admit a float.
731        assert!(!FieldType::Int.admits(&Value::Float(3.0)));
732        assert!(FieldType::Int.admits(&Value::Uint(u64::MAX)));
733
734        assert!(FieldType::Null.admits(&Value::Null));
735        assert!(!FieldType::Str.admits(&Value::Null));
736        assert!(FieldType::Bool.admits(&Value::Bool(false)));
737        assert!(FieldType::Seq.admits(&Value::Seq(vec![])));
738        assert!(!FieldType::Seq.admits(&Value::Map(vec![])));
739        assert!(FieldType::Map.admits(&Value::Map(vec![])));
740    }
741
742    #[test]
743    fn an_extended_field_admits_its_own_kind_and_a_string_shaped_like_one() {
744        let date = Value::Extended {
745            kind: ExtKind::LocalDate,
746            text: "1979-05-27".into(),
747        };
748        let date_field = FieldType::Extended(ExtKind::LocalDate);
749        assert!(date_field.admits(&date));
750        assert!(!FieldType::Extended(ExtKind::LocalTime).admits(&date));
751        assert!(!FieldType::Str.admits(&date));
752        // YAML, JSON and markdown frontmatter have no date literal, so the same
753        // text parses there as a string — and a date field that refused it
754        // would fail every such document against its own schema.
755        assert!(date_field.admits(&Value::Str("1979-05-27".into())));
756        // Only a string *shaped* like one, by the guard `coerce` also uses.
757        assert!(!date_field.admits(&Value::Str("yesterday".into())));
758        assert!(!date_field.admits(&Value::Str("".into())));
759        assert!(!date_field.admits(&Value::Int(1979)));
760    }
761
762    #[test]
763    fn a_type_admits_a_list_of_its_items_one_level_deep() {
764        let strings = Value::Seq(vec![Value::Str("a".into()), Value::Str("b".into())]);
765        assert!(FieldType::Str.admits(&strings));
766        assert!(FieldType::Ref.admits(&strings));
767        assert!(!FieldType::Int.admits(&strings));
768        // A list of lists is not a list of items.
769        let nested = Value::Seq(vec![strings.clone()]);
770        assert!(!FieldType::Str.admits(&nested));
771        assert!(FieldType::Seq.admits(&nested));
772        // Every item has to fit, and an empty list vacuously does.
773        let mixed = Value::Seq(vec![Value::Str("a".into()), Value::Int(1)]);
774        assert!(!FieldType::Str.admits(&mixed));
775        assert!(!FieldType::Float.admits(&mixed));
776        assert!(FieldType::Str.admits(&Value::Seq(vec![])));
777        // The widenings apply item-wise too.
778        assert!(FieldType::Float.admits(&Value::Seq(vec![Value::Int(1), Value::Float(0.5)])));
779        assert!(
780            FieldType::Extended(ExtKind::LocalDate)
781                .admits(&Value::Seq(vec![Value::Str("1979-05-27".into())]))
782        );
783    }
784
785    #[test]
786    fn a_type_displays_as_the_format_spells_it_and_reads_back() {
787        assert_eq!(FieldType::Int.to_string(), "int");
788        assert_eq!(FieldType::Str.to_string(), "str");
789        assert_eq!(FieldType::Seq.to_string(), "seq");
790        // The extended kinds are spelled prov's way, not fig's.
791        assert_eq!(FieldType::Extended(ExtKind::LocalDate).to_string(), "date");
792        assert_eq!(
793            FieldType::Extended(ExtKind::OffsetDateTime).to_string(),
794            "datetime"
795        );
796        assert_eq!(
797            FieldType::Extended(ExtKind::LocalDateTime).to_string(),
798            "local-datetime"
799        );
800        assert_eq!(FieldType::Extended(ExtKind::LocalTime).to_string(), "time");
801        assert_eq!(
802            FieldType::Extended(ExtKind::EnumLiteral).to_string(),
803            "enum"
804        );
805        assert_eq!(
806            FieldType::Extended(ExtKind::CharLiteral).to_string(),
807            "char"
808        );
809        // A kind the format cannot name still has a spelling.
810        assert_eq!(
811            FieldType::Extended(ExtKind::NumberSpecial).to_string(),
812            "number-special"
813        );
814        // Every name in the table round-trips through `from_name`.
815        for (name, ty) in NAMES {
816            assert_eq!(FieldType::from_name(name), Some(*ty), "{name}");
817            assert_eq!(ty.to_string(), *name, "{ty:?}");
818        }
819        assert_eq!(FieldType::from_name("number-special"), None);
820        assert_eq!(FieldType::from_name("string"), None);
821    }
822
823    #[test]
824    fn a_misspelled_type_name_gets_the_one_meant() {
825        assert_eq!(FieldType::suggest_name("string"), Some("str"));
826        assert_eq!(FieldType::suggest_name("String"), Some("str"));
827        assert_eq!(FieldType::suggest_name("Int"), Some("int"));
828        assert_eq!(FieldType::suggest_name("boolean"), Some("bool"));
829        assert_eq!(FieldType::suggest_name("local-date"), Some("date"));
830        assert_eq!(FieldType::suggest_name("array"), Some("seq"));
831        assert_eq!(FieldType::suggest_name("wibble"), None);
832    }
833
834    #[test]
835    fn a_rule_can_say_where_it_came_from_and_change_its_constraint_type() {
836        let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"))
837            .ty(FieldType::Str)
838            .constraint(AlwaysReject)
839            .origin(Origin::new("schema.figl", "rules[0]"));
840        assert_eq!(
841            rule.origin.as_ref().map(ToString::to_string),
842            Some("schema.figl rules[0]".to_owned())
843        );
844        // A built rule has none.
845        assert_eq!(
846            FieldRule::<AlwaysReject>::new(PathPat::key("x")).origin,
847            None
848        );
849        // Mapping the constraint keeps everything else.
850        let mapped: FieldRule<&'static str> = rule.map_constraint(|_| "mine");
851        assert_eq!(mapped.constraint, Some("mine"));
852        assert_eq!(mapped.ty, Some(FieldType::Str));
853        assert!(mapped.origin.is_some());
854
855        let schema = Schema::new(vec![
856            FieldRule::new(PathPat::key("a")).constraint(AlwaysReject),
857        ]);
858        let mapped = schema.map_constraints(|_| 1u8);
859        assert_eq!(mapped.rules()[0].constraint, Some(1));
860        assert_eq!(mapped.into_rules().len(), 1);
861    }
862
863    #[test]
864    fn rules_for_lists_every_match_with_rule_for_first() {
865        let schema = Schema::new(vec![
866            FieldRule::new(PathPat(vec![
867                crate::SegPat::Key("meta".into()),
868                crate::SegPat::Key("id".into()),
869            ]))
870            .ty(FieldType::Int)
871            .constraint_opt(None::<AlwaysReject>),
872            FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
873            FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
874            FieldRule::new(PathPat(vec![crate::SegPat::AnyDepth])).ty(FieldType::Null),
875        ]);
876        let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
877        let matched: Vec<_> = schema.rules_for(&id).map(|r| r.ty).collect();
878        // The winner, then what it shadows, in declaration order; `title` is
879        // not among them.
880        assert_eq!(
881            matched,
882            vec![
883                Some(FieldType::Int),
884                Some(FieldType::Str),
885                Some(FieldType::Null)
886            ]
887        );
888        assert_eq!(schema.rule_for(&id).unwrap().ty, matched[0]);
889        assert_eq!(schema.rules_for(&[Seg::Key("nothing".into())]).count(), 1);
890    }
891
892    #[test]
893    fn a_specific_rule_takes_precedence_over_a_subtree_rule() {
894        let schema = Schema::new(vec![
895            FieldRule::new(PathPat(vec![
896                crate::SegPat::Key("meta".into()),
897                crate::SegPat::Key("id".into()),
898            ]))
899            .ty(FieldType::Int)
900            .constraint_opt(None::<AlwaysReject>),
901            FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
902        ]);
903        let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
904        assert_eq!(schema.rule_for(&id).unwrap().ty, Some(FieldType::Int));
905        let other = [Seg::Key("meta".into()), Seg::Key("author".into())];
906        assert_eq!(schema.rule_for(&other).unwrap().ty, Some(FieldType::Str));
907    }
908}