use std::fmt;
use std::path::PathBuf;
use fig::{ExtKind, Value};
use crate::consequence::Consequence;
use crate::path::{PathPat, Seg};
use crate::present::Presentation;
use crate::vocab::{Validate, Validation};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldType {
Null,
Bool,
Int,
Float,
Str,
Ref,
Extended(ExtKind),
Map,
Seq,
}
impl FieldType {
pub fn of(value: &Value) -> FieldType {
match value {
Value::Null => FieldType::Null,
Value::Bool(_) => FieldType::Bool,
Value::Int(_) | Value::Uint(_) => FieldType::Int,
Value::Float(_) => FieldType::Float,
Value::Str(_) => FieldType::Str,
Value::Extended { kind, .. } => FieldType::Extended(*kind),
Value::Seq(_) => FieldType::Seq,
Value::Map(_) => FieldType::Map,
}
}
pub fn admits(self, value: &Value) -> bool {
if self.admits_item(value) {
return true;
}
match value {
Value::Seq(items) => items.iter().all(|item| self.admits_item(item)),
_ => false,
}
}
fn admits_item(self, value: &Value) -> bool {
let found = FieldType::of(value);
match self {
FieldType::Float => matches!(found, FieldType::Float | FieldType::Int),
FieldType::Ref => found == FieldType::Str,
FieldType::Extended(kind) => match value {
Value::Str(text) => extended_text_fits(kind, text),
_ => found == self,
},
expected => found == expected,
}
}
pub fn coerce(self, s: &str) -> Value {
let t = s.trim();
match self {
FieldType::Null => match t {
"" | "~" => Value::Null,
_ if t.eq_ignore_ascii_case("null") => Value::Null,
_ => Value::Str(s.to_string()),
},
FieldType::Bool => match t.to_ascii_lowercase().as_str() {
"true" | "yes" | "on" => Value::Bool(true),
"false" | "no" | "off" => Value::Bool(false),
_ => Value::Str(s.to_string()),
},
FieldType::Int => match Value::parse_number(t, false) {
Ok(v) if !v.is_f64() => v,
_ => Value::Str(s.to_string()),
},
FieldType::Float => {
Value::parse_number(t, true).unwrap_or_else(|_| Value::Str(s.to_string()))
}
FieldType::Extended(kind) => {
if extended_text_fits(kind, t) {
Value::Extended {
kind,
text: t.to_string(),
}
} else {
Value::Str(s.to_string())
}
}
FieldType::Str | FieldType::Ref | FieldType::Map | FieldType::Seq => {
Value::Str(s.to_string())
}
}
}
}
const NAMES: &[(&str, FieldType)] = &[
("null", FieldType::Null),
("bool", FieldType::Bool),
("int", FieldType::Int),
("float", FieldType::Float),
("str", FieldType::Str),
("ref", FieldType::Ref),
("date", FieldType::Extended(ExtKind::LocalDate)),
("datetime", FieldType::Extended(ExtKind::OffsetDateTime)),
(
"local-datetime",
FieldType::Extended(ExtKind::LocalDateTime),
),
("time", FieldType::Extended(ExtKind::LocalTime)),
("enum", FieldType::Extended(ExtKind::EnumLiteral)),
("char", FieldType::Extended(ExtKind::CharLiteral)),
("map", FieldType::Map),
("seq", FieldType::Seq),
];
impl FieldType {
pub fn from_name(name: &str) -> Option<FieldType> {
NAMES
.iter()
.find(|(known, _)| *known == name)
.map(|(_, ty)| *ty)
}
pub fn suggest_name(name: &str) -> Option<&'static str> {
let lower = name.to_ascii_lowercase();
Some(match lower.as_str() {
"string" | "text" => "str",
"boolean" => "bool",
"integer" | "i64" | "u64" => "int",
"number" | "f64" | "double" => "float",
"list" | "array" | "sequence" => "seq",
"object" | "dict" | "mapping" | "table" => "map",
"reference" | "link" => "ref",
"local-date" => "date",
"offset-datetime" => "datetime",
"local-time" => "time",
_ => {
return NAMES
.iter()
.map(|(known, _)| *known)
.find(|known| *known == lower);
}
})
}
}
impl fmt::Display for FieldType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some((name, _)) = NAMES.iter().find(|(_, ty)| ty == self) {
return f.write_str(name);
}
f.write_str(match self {
FieldType::Extended(ExtKind::NumberSpecial) => "number-special",
FieldType::Extended(ExtKind::PlistDate) => "plist-date",
FieldType::Extended(ExtKind::PlistData) => "plist-data",
_ => "extended",
})
}
}
fn extended_text_fits(kind: ExtKind, text: &str) -> bool {
if text.is_empty() {
return false;
}
match kind {
ExtKind::OffsetDateTime
| ExtKind::LocalDateTime
| ExtKind::LocalDate
| ExtKind::LocalTime => text.chars().all(|c| {
c.is_ascii_digit() || matches!(c, '-' | ':' | '.' | '+' | 'T' | 't' | 'Z' | 'z' | ' ')
}),
ExtKind::EnumLiteral => {
let mut chars = text.chars();
chars.next().is_some_and(|c| c.is_alphabetic() || c == '_')
&& chars.all(|c| c.is_alphanumeric() || c == '_')
}
ExtKind::CharLiteral => text.chars().all(|c| c.is_ascii_digit()),
ExtKind::NumberSpecial => matches!(
text,
"Infinity" | "-Infinity" | "+Infinity" | "NaN" | "-NaN" | "+NaN"
),
_ => true,
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FieldRule<C> {
pub at: PathPat,
pub ty: Option<FieldType>,
pub constraint: Option<C>,
pub present: Presentation,
pub on_change: Vec<Consequence>,
pub origin: Option<Origin>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Origin {
pub document: PathBuf,
pub at: String,
}
impl Origin {
pub fn new(document: impl Into<PathBuf>, at: impl Into<String>) -> Self {
Self {
document: document.into(),
at: at.into(),
}
}
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.document.display(), self.at)
}
}
impl<C> FieldRule<C> {
pub fn new(at: PathPat) -> Self {
Self {
at,
ty: None,
constraint: None,
present: Presentation::default(),
on_change: Vec::new(),
origin: None,
}
}
pub fn ty(mut self, ty: impl Into<Option<FieldType>>) -> Self {
self.ty = ty.into();
self
}
pub fn constraint(mut self, constraint: C) -> Self {
self.constraint = Some(constraint);
self
}
pub fn constraint_opt(mut self, constraint: Option<C>) -> Self {
self.constraint = constraint;
self
}
pub fn present(mut self, present: Presentation) -> Self {
self.present = present;
self
}
pub fn on_change(mut self, consequence: Consequence) -> Self {
self.on_change.push(consequence);
self
}
pub fn on_change_all(mut self, consequences: Vec<Consequence>) -> Self {
self.on_change = consequences;
self
}
pub fn origin(mut self, origin: Origin) -> Self {
self.origin = Some(origin);
self
}
pub fn map_constraint<D>(self, f: impl FnOnce(C) -> D) -> FieldRule<D> {
FieldRule {
at: self.at,
ty: self.ty,
constraint: self.constraint.map(f),
present: self.present,
on_change: self.on_change,
origin: self.origin,
}
}
}
impl<C: Validate> FieldRule<C> {
pub fn validate(&self, value: &Value) -> Validation {
match &self.constraint {
Some(c) => c.validate(value),
None => Validation::Ok,
}
}
}
#[derive(Debug, Clone)]
pub struct Schema<C> {
rules: Vec<FieldRule<C>>,
}
impl<C> Default for Schema<C> {
fn default() -> Self {
Self { rules: Vec::new() }
}
}
impl<C> Schema<C> {
pub fn new(rules: Vec<FieldRule<C>>) -> Self {
Self { rules }
}
pub fn rules(&self) -> &[FieldRule<C>] {
&self.rules
}
pub fn into_rules(self) -> Vec<FieldRule<C>> {
self.rules
}
pub fn map_constraints<D>(self, mut f: impl FnMut(C) -> D) -> Schema<D> {
Schema {
rules: self
.rules
.into_iter()
.map(|rule| rule.map_constraint(&mut f))
.collect(),
}
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn rule_for(&self, path: &[Seg]) -> Option<&FieldRule<C>> {
self.rules.iter().find(|r| r.at.matches(path))
}
pub fn rules_for<'s, 'p: 's>(
&'s self,
path: &'p [Seg],
) -> impl Iterator<Item = &'s FieldRule<C>> + 's {
self.rules.iter().filter(move |r| r.at.matches(path))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vocab::Issue;
#[test]
fn type_directed_parse_keeps_a_string_field_a_string() {
assert_eq!(FieldType::Str.coerce("123"), Value::Str("123".into()));
assert_eq!(FieldType::Int.coerce("123"), Value::Int(123));
assert_eq!(FieldType::Bool.coerce("true"), Value::Bool(true));
assert_eq!(FieldType::Int.coerce("abc"), Value::Str("abc".into()));
}
#[test]
fn a_null_field_keeps_text_it_cannot_read_as_null() {
assert_eq!(FieldType::Null.coerce(""), Value::Null);
assert_eq!(FieldType::Null.coerce("null"), Value::Null);
assert_eq!(FieldType::Null.coerce("NULL"), Value::Null);
assert_eq!(FieldType::Null.coerce("~"), Value::Null);
assert_eq!(
FieldType::Null.coerce("important data"),
Value::Str("important data".into())
);
}
#[test]
fn a_bool_field_accepts_the_yaml_spellings() {
for yes in ["true", "True", "TRUE", "yes", "Yes", "on"] {
assert_eq!(FieldType::Bool.coerce(yes), Value::Bool(true), "{yes}");
}
for no in ["false", "False", "FALSE", "no", "No", "off"] {
assert_eq!(FieldType::Bool.coerce(no), Value::Bool(false), "{no}");
}
assert_eq!(FieldType::Bool.coerce("maybe"), Value::Str("maybe".into()));
}
#[test]
fn a_float_field_reads_back_the_spellings_fig_writes() {
let inf = FieldType::Float.coerce(".inf");
assert!(matches!(inf, Value::Float(f) if f.is_infinite() && f.is_sign_positive()));
let neg = FieldType::Float.coerce("-.inf");
assert!(matches!(neg, Value::Float(f) if f.is_infinite() && f.is_sign_negative()));
assert!(matches!(FieldType::Float.coerce(".nan"), Value::Float(f) if f.is_nan()));
assert!(matches!(FieldType::Float.coerce("inf"), Value::Float(f) if f.is_infinite()));
assert_eq!(FieldType::Float.coerce("1.5"), Value::Float(1.5));
assert_eq!(FieldType::Float.coerce("nope"), Value::Str("nope".into()));
}
#[test]
fn an_int_field_does_not_widen_to_a_float() {
assert_eq!(FieldType::Int.coerce("3"), Value::Int(3));
assert_eq!(FieldType::Int.coerce("3.5"), Value::Str("3.5".into()));
assert_eq!(
FieldType::Int.coerce("9223372036854775808"),
Value::Uint(9_223_372_036_854_775_808)
);
}
#[test]
fn an_extended_field_keeps_its_native_type() {
let ty = FieldType::Extended(ExtKind::LocalDate);
assert_eq!(
ty.coerce("1979-05-27"),
Value::Extended {
kind: ExtKind::LocalDate,
text: "1979-05-27".into(),
}
);
assert_eq!(ty.coerce("not a date"), Value::Str("not a date".into()));
assert_eq!(ty.coerce(""), Value::Str("".into()));
}
#[test]
fn extended_shape_guard_covers_every_kind() {
assert!(extended_text_fits(
ExtKind::OffsetDateTime,
"1979-05-27T07:32:00Z"
));
assert!(extended_text_fits(ExtKind::LocalTime, "07:32:00.999"));
assert!(extended_text_fits(ExtKind::EnumLiteral, "foo_bar"));
assert!(!extended_text_fits(ExtKind::EnumLiteral, "9lives"));
assert!(!extended_text_fits(ExtKind::EnumLiteral, "has space"));
assert!(extended_text_fits(ExtKind::CharLiteral, "97"));
assert!(!extended_text_fits(ExtKind::CharLiteral, "a"));
assert!(extended_text_fits(ExtKind::NumberSpecial, "-Infinity"));
assert!(!extended_text_fits(ExtKind::NumberSpecial, "inf"));
}
#[derive(Debug, Clone)]
struct AlwaysReject;
impl Validate for AlwaysReject {
fn validate(&self, _value: &Value) -> Validation {
Validation::Reject(Issue::custom("", "no"))
}
}
#[test]
fn rule_validate_dispatches_to_the_embedder_constraint() {
let rule = FieldRule::new(PathPat::key("status"))
.ty(FieldType::Str)
.constraint(AlwaysReject);
assert!(rule.validate(&Value::Str("anything".into())).is_reject());
}
#[test]
fn rule_with_no_constraint_always_validates_ok() {
let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"));
assert_eq!(
rule.validate(&Value::Str("anything".into())),
Validation::Ok
);
}
#[test]
fn schema_rule_for_finds_first_match_in_declaration_order() {
let schema = Schema::new(vec![
FieldRule::new(PathPat::each_item_of("tags"))
.ty(FieldType::Str)
.constraint_opt(None::<AlwaysReject>),
FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
]);
assert!(schema.rule_for(&[Seg::Key("title".into())]).is_some());
assert!(
schema
.rule_for(&[Seg::Key("tags".into()), Seg::Index(0)])
.is_some()
);
assert!(schema.rule_for(&[Seg::Key("missing".into())]).is_none());
}
#[test]
fn every_value_has_a_type_and_uint_is_an_int() {
assert_eq!(FieldType::of(&Value::Null), FieldType::Null);
assert_eq!(FieldType::of(&Value::Bool(true)), FieldType::Bool);
assert_eq!(FieldType::of(&Value::Int(1)), FieldType::Int);
assert_eq!(FieldType::of(&Value::Uint(u64::MAX)), FieldType::Int);
assert_eq!(FieldType::of(&Value::Float(1.5)), FieldType::Float);
assert_eq!(FieldType::of(&Value::Str("x".into())), FieldType::Str);
assert_eq!(
FieldType::of(&Value::Extended {
kind: ExtKind::LocalDate,
text: "1979-05-27".into()
}),
FieldType::Extended(ExtKind::LocalDate)
);
assert_eq!(FieldType::of(&Value::Seq(vec![])), FieldType::Seq);
assert_eq!(FieldType::of(&Value::Map(vec![])), FieldType::Map);
}
#[test]
fn admits_is_equality_plus_the_two_widenings() {
let text = Value::Str("123".into());
assert!(FieldType::Str.admits(&text));
assert!(FieldType::Ref.admits(&text));
assert!(!FieldType::Int.admits(&text));
assert!(FieldType::Float.admits(&Value::Int(3)));
assert!(FieldType::Float.admits(&Value::Uint(u64::MAX)));
assert!(FieldType::Float.admits(&Value::Float(0.5)));
assert!(!FieldType::Int.admits(&Value::Float(3.0)));
assert!(FieldType::Int.admits(&Value::Uint(u64::MAX)));
assert!(FieldType::Null.admits(&Value::Null));
assert!(!FieldType::Str.admits(&Value::Null));
assert!(FieldType::Bool.admits(&Value::Bool(false)));
assert!(FieldType::Seq.admits(&Value::Seq(vec![])));
assert!(!FieldType::Seq.admits(&Value::Map(vec![])));
assert!(FieldType::Map.admits(&Value::Map(vec![])));
}
#[test]
fn an_extended_field_admits_its_own_kind_and_a_string_shaped_like_one() {
let date = Value::Extended {
kind: ExtKind::LocalDate,
text: "1979-05-27".into(),
};
let date_field = FieldType::Extended(ExtKind::LocalDate);
assert!(date_field.admits(&date));
assert!(!FieldType::Extended(ExtKind::LocalTime).admits(&date));
assert!(!FieldType::Str.admits(&date));
assert!(date_field.admits(&Value::Str("1979-05-27".into())));
assert!(!date_field.admits(&Value::Str("yesterday".into())));
assert!(!date_field.admits(&Value::Str("".into())));
assert!(!date_field.admits(&Value::Int(1979)));
}
#[test]
fn a_type_admits_a_list_of_its_items_one_level_deep() {
let strings = Value::Seq(vec![Value::Str("a".into()), Value::Str("b".into())]);
assert!(FieldType::Str.admits(&strings));
assert!(FieldType::Ref.admits(&strings));
assert!(!FieldType::Int.admits(&strings));
let nested = Value::Seq(vec![strings.clone()]);
assert!(!FieldType::Str.admits(&nested));
assert!(FieldType::Seq.admits(&nested));
let mixed = Value::Seq(vec![Value::Str("a".into()), Value::Int(1)]);
assert!(!FieldType::Str.admits(&mixed));
assert!(!FieldType::Float.admits(&mixed));
assert!(FieldType::Str.admits(&Value::Seq(vec![])));
assert!(FieldType::Float.admits(&Value::Seq(vec![Value::Int(1), Value::Float(0.5)])));
assert!(
FieldType::Extended(ExtKind::LocalDate)
.admits(&Value::Seq(vec![Value::Str("1979-05-27".into())]))
);
}
#[test]
fn a_type_displays_as_the_format_spells_it_and_reads_back() {
assert_eq!(FieldType::Int.to_string(), "int");
assert_eq!(FieldType::Str.to_string(), "str");
assert_eq!(FieldType::Seq.to_string(), "seq");
assert_eq!(FieldType::Extended(ExtKind::LocalDate).to_string(), "date");
assert_eq!(
FieldType::Extended(ExtKind::OffsetDateTime).to_string(),
"datetime"
);
assert_eq!(
FieldType::Extended(ExtKind::LocalDateTime).to_string(),
"local-datetime"
);
assert_eq!(FieldType::Extended(ExtKind::LocalTime).to_string(), "time");
assert_eq!(
FieldType::Extended(ExtKind::EnumLiteral).to_string(),
"enum"
);
assert_eq!(
FieldType::Extended(ExtKind::CharLiteral).to_string(),
"char"
);
assert_eq!(
FieldType::Extended(ExtKind::NumberSpecial).to_string(),
"number-special"
);
for (name, ty) in NAMES {
assert_eq!(FieldType::from_name(name), Some(*ty), "{name}");
assert_eq!(ty.to_string(), *name, "{ty:?}");
}
assert_eq!(FieldType::from_name("number-special"), None);
assert_eq!(FieldType::from_name("string"), None);
}
#[test]
fn a_misspelled_type_name_gets_the_one_meant() {
assert_eq!(FieldType::suggest_name("string"), Some("str"));
assert_eq!(FieldType::suggest_name("String"), Some("str"));
assert_eq!(FieldType::suggest_name("Int"), Some("int"));
assert_eq!(FieldType::suggest_name("boolean"), Some("bool"));
assert_eq!(FieldType::suggest_name("local-date"), Some("date"));
assert_eq!(FieldType::suggest_name("array"), Some("seq"));
assert_eq!(FieldType::suggest_name("wibble"), None);
}
#[test]
fn a_rule_can_say_where_it_came_from_and_change_its_constraint_type() {
let rule: FieldRule<AlwaysReject> = FieldRule::new(PathPat::key("status"))
.ty(FieldType::Str)
.constraint(AlwaysReject)
.origin(Origin::new("schema.figl", "rules[0]"));
assert_eq!(
rule.origin.as_ref().map(ToString::to_string),
Some("schema.figl rules[0]".to_owned())
);
assert_eq!(
FieldRule::<AlwaysReject>::new(PathPat::key("x")).origin,
None
);
let mapped: FieldRule<&'static str> = rule.map_constraint(|_| "mine");
assert_eq!(mapped.constraint, Some("mine"));
assert_eq!(mapped.ty, Some(FieldType::Str));
assert!(mapped.origin.is_some());
let schema = Schema::new(vec![
FieldRule::new(PathPat::key("a")).constraint(AlwaysReject),
]);
let mapped = schema.map_constraints(|_| 1u8);
assert_eq!(mapped.rules()[0].constraint, Some(1));
assert_eq!(mapped.into_rules().len(), 1);
}
#[test]
fn rules_for_lists_every_match_with_rule_for_first() {
let schema = Schema::new(vec![
FieldRule::new(PathPat(vec![
crate::SegPat::Key("meta".into()),
crate::SegPat::Key("id".into()),
]))
.ty(FieldType::Int)
.constraint_opt(None::<AlwaysReject>),
FieldRule::new(PathPat::key("title")).ty(FieldType::Str),
FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
FieldRule::new(PathPat(vec![crate::SegPat::AnyDepth])).ty(FieldType::Null),
]);
let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
let matched: Vec<_> = schema.rules_for(&id).map(|r| r.ty).collect();
assert_eq!(
matched,
vec![
Some(FieldType::Int),
Some(FieldType::Str),
Some(FieldType::Null)
]
);
assert_eq!(schema.rule_for(&id).unwrap().ty, matched[0]);
assert_eq!(schema.rules_for(&[Seg::Key("nothing".into())]).count(), 1);
}
#[test]
fn a_specific_rule_takes_precedence_over_a_subtree_rule() {
let schema = Schema::new(vec![
FieldRule::new(PathPat(vec![
crate::SegPat::Key("meta".into()),
crate::SegPat::Key("id".into()),
]))
.ty(FieldType::Int)
.constraint_opt(None::<AlwaysReject>),
FieldRule::new(PathPat::subtree_of("meta")).ty(FieldType::Str),
]);
let id = [Seg::Key("meta".into()), Seg::Key("id".into())];
assert_eq!(schema.rule_for(&id).unwrap().ty, Some(FieldType::Int));
let other = [Seg::Key("meta".into()), Seg::Key("author".into())];
assert_eq!(schema.rule_for(&other).unwrap().ty, Some(FieldType::Str));
}
}