pactum-annotations 0.1.0

Declarative field normalization and validation for pactum contracts
Documentation
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::Hash;

use crate::context::ValidationContext;
use crate::error::FieldIssue;
use crate::schema::ModelSchema;

/// Mutate a value into canonical form before checks.
pub trait Normalize {
    fn normalize(&mut self);
}

/// Run field rules and cross-field constraints.
pub trait Validate {
    fn validate(&self) -> Result<(), Vec<FieldIssue>> {
        self.validate_with(&ValidationContext::default())
    }

    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
}

/// Emit static schema for the catalog and IDL.
pub trait DescribeModel {
    fn model_schema() -> ModelSchema;
}

/// Result types supported by arbitrary `#[check(with = ...)]` functions and closures.
pub trait CheckOutcome {
    fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
}

impl CheckOutcome for bool {
    fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
        if self {
            Vec::new()
        } else {
            vec![FieldIssue::new(field, code, reason)]
        }
    }
}

impl CheckOutcome for Result<(), &'static str> {
    fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err(msg) => vec![FieldIssue::new(field, code, msg)],
        }
    }
}

impl CheckOutcome for Result<(), String> {
    fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err(msg) => vec![FieldIssue::new(field, code, msg)],
        }
    }
}

impl CheckOutcome for Result<(), (&'static str, &'static str)> {
    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
        }
    }
}

impl CheckOutcome for Result<(), (String, String)> {
    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
        }
    }
}

impl CheckOutcome for Result<(), FieldIssue> {
    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err(mut v) => {
                if v.field.is_empty() {
                    v.field = field.to_string();
                }
                vec![v]
            }
        }
    }
}

impl CheckOutcome for Result<(), Vec<FieldIssue>> {
    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
        match self {
            Ok(()) => Vec::new(),
            Err(vs) => vs
                .into_iter()
                .map(|mut v| {
                    if v.field.is_empty() {
                        v.field = field.to_string();
                    }
                    v
                })
                .collect(),
        }
    }
}

macro_rules! impl_noop_model_traits {
    ($($ty:ty),*) => {
        $(
            impl Normalize for $ty {
                fn normalize(&mut self) {}
            }

            impl Validate for $ty {
                fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
                    Ok(())
                }
            }
        )*
    };
}

impl_noop_model_traits!(
    String, bool, char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

impl<T: Normalize> Normalize for Option<T> {
    fn normalize(&mut self) {
        if let Some(value) = self {
            value.normalize();
        }
    }
}

impl<T: Validate> Validate for Option<T> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        match self {
            Some(value) => value.validate_with(ctx),
            None => Ok(()),
        }
    }
}

impl<T: Normalize> Normalize for Box<T> {
    fn normalize(&mut self) {
        (**self).normalize();
    }
}

impl<T: Validate> Validate for Box<T> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        (**self).validate_with(ctx)
    }
}

impl<T: Normalize> Normalize for Vec<T> {
    fn normalize(&mut self) {
        for item in self {
            item.normalize();
        }
    }
}

impl<T: Validate> Validate for Vec<T> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        let mut issues = Vec::new();
        for (index, item) in self.iter().enumerate() {
            if let Err(inner) = item.validate_with(ctx) {
                for mut issue in inner {
                    if issue.field.is_empty() || issue.field == "body" {
                        issue.field = format!("[{index}]");
                    } else {
                        issue.field = format!("[{index}].{}", issue.field);
                    }
                    issues.push(issue);
                }
            }
        }
        if issues.is_empty() {
            Ok(())
        } else {
            Err(issues)
        }
    }
}

impl<T: Normalize> Normalize for BTreeSet<T> {
    fn normalize(&mut self) {}
}

impl<T: Validate> Validate for BTreeSet<T> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        let mut issues = Vec::new();
        for (index, item) in self.iter().enumerate() {
            if let Err(inner) = item.validate_with(ctx) {
                for mut issue in inner {
                    if issue.field.is_empty() || issue.field == "body" {
                        issue.field = format!("[{index}]");
                    } else {
                        issue.field = format!("[{index}].{}", issue.field);
                    }
                    issues.push(issue);
                }
            }
        }
        if issues.is_empty() {
            Ok(())
        } else {
            Err(issues)
        }
    }
}

impl<T: Normalize> Normalize for HashSet<T> {
    fn normalize(&mut self) {}
}

impl<T: Validate> Validate for HashSet<T> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        let mut issues = Vec::new();
        for (index, item) in self.iter().enumerate() {
            if let Err(inner) = item.validate_with(ctx) {
                for mut issue in inner {
                    if issue.field.is_empty() || issue.field == "body" {
                        issue.field = format!("[{index}]");
                    } else {
                        issue.field = format!("[{index}].{}", issue.field);
                    }
                    issues.push(issue);
                }
            }
        }
        if issues.is_empty() {
            Ok(())
        } else {
            Err(issues)
        }
    }
}

impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
    fn normalize(&mut self) {
        for value in self.values_mut() {
            value.normalize();
        }
    }
}

impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        let mut issues = Vec::new();
        for (key, value) in self {
            if let Err(inner) = value.validate_with(ctx) {
                for mut issue in inner {
                    if issue.field.is_empty() || issue.field == "body" {
                        issue.field = key.to_string();
                    } else {
                        issue.field = format!("{key}.{}", issue.field);
                    }
                    issues.push(issue);
                }
            }
        }
        if issues.is_empty() {
            Ok(())
        } else {
            Err(issues)
        }
    }
}

impl<K: Eq + Hash, V: Normalize> Normalize for HashMap<K, V> {
    fn normalize(&mut self) {
        for value in self.values_mut() {
            value.normalize();
        }
    }
}

impl<K: std::fmt::Display + Eq + Hash, V: Validate> Validate for HashMap<K, V> {
    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
        let mut issues = Vec::new();
        for (key, value) in self {
            if let Err(inner) = value.validate_with(ctx) {
                for mut issue in inner {
                    if issue.field.is_empty() || issue.field == "body" {
                        issue.field = key.to_string();
                    } else {
                        issue.field = format!("{key}.{}", issue.field);
                    }
                    issues.push(issue);
                }
            }
        }
        if issues.is_empty() {
            Ok(())
        } else {
            Err(issues)
        }
    }
}