Skip to main content

pactum_annotations/
traits.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::hash::Hash;
3
4use crate::context::ValidationContext;
5use crate::error::FieldIssue;
6use crate::schema::ModelSchema;
7
8/// Mutate a value into canonical form before checks.
9pub trait Normalize {
10    fn normalize(&mut self);
11}
12
13/// Run field rules and cross-field constraints.
14pub trait Validate {
15    fn validate(&self) -> Result<(), Vec<FieldIssue>> {
16        self.validate_with(&ValidationContext::default())
17    }
18
19    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
20}
21
22/// Emit static schema for the catalog and IDL.
23pub trait DescribeModel {
24    fn model_schema() -> ModelSchema;
25}
26
27/// Result types supported by arbitrary `#[check(with = ...)]` functions and closures.
28pub trait CheckOutcome {
29    fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
30}
31
32impl CheckOutcome for bool {
33    fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
34        if self {
35            Vec::new()
36        } else {
37            vec![FieldIssue::new(field, code, reason)]
38        }
39    }
40}
41
42impl CheckOutcome for Result<(), &'static str> {
43    fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
44        match self {
45            Ok(()) => Vec::new(),
46            Err(msg) => vec![FieldIssue::new(field, code, msg)],
47        }
48    }
49}
50
51impl CheckOutcome for Result<(), String> {
52    fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
53        match self {
54            Ok(()) => Vec::new(),
55            Err(msg) => vec![FieldIssue::new(field, code, msg)],
56        }
57    }
58}
59
60impl CheckOutcome for Result<(), (&'static str, &'static str)> {
61    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
62        match self {
63            Ok(()) => Vec::new(),
64            Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
65        }
66    }
67}
68
69impl CheckOutcome for Result<(), (String, String)> {
70    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
71        match self {
72            Ok(()) => Vec::new(),
73            Err((code, msg)) => vec![FieldIssue::new(field, code, msg)],
74        }
75    }
76}
77
78impl CheckOutcome for Result<(), FieldIssue> {
79    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
80        match self {
81            Ok(()) => Vec::new(),
82            Err(mut v) => {
83                if v.field.is_empty() {
84                    v.field = field.to_string();
85                }
86                vec![v]
87            }
88        }
89    }
90}
91
92impl CheckOutcome for Result<(), Vec<FieldIssue>> {
93    fn into_issues(self, field: &str, _code: &str, _reason: &str) -> Vec<FieldIssue> {
94        match self {
95            Ok(()) => Vec::new(),
96            Err(vs) => vs
97                .into_iter()
98                .map(|mut v| {
99                    if v.field.is_empty() {
100                        v.field = field.to_string();
101                    }
102                    v
103                })
104                .collect(),
105        }
106    }
107}
108
109macro_rules! impl_noop_model_traits {
110    ($($ty:ty),*) => {
111        $(
112            impl Normalize for $ty {
113                fn normalize(&mut self) {}
114            }
115
116            impl Validate for $ty {
117                fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
118                    Ok(())
119                }
120            }
121        )*
122    };
123}
124
125impl_noop_model_traits!(
126    String, bool, char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
127);
128
129impl<T: Normalize> Normalize for Option<T> {
130    fn normalize(&mut self) {
131        if let Some(value) = self {
132            value.normalize();
133        }
134    }
135}
136
137impl<T: Validate> Validate for Option<T> {
138    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
139        match self {
140            Some(value) => value.validate_with(ctx),
141            None => Ok(()),
142        }
143    }
144}
145
146impl<T: Normalize> Normalize for Box<T> {
147    fn normalize(&mut self) {
148        (**self).normalize();
149    }
150}
151
152impl<T: Validate> Validate for Box<T> {
153    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
154        (**self).validate_with(ctx)
155    }
156}
157
158impl<T: Normalize> Normalize for Vec<T> {
159    fn normalize(&mut self) {
160        for item in self {
161            item.normalize();
162        }
163    }
164}
165
166impl<T: Validate> Validate for Vec<T> {
167    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
168        let mut issues = Vec::new();
169        for (index, item) in self.iter().enumerate() {
170            if let Err(inner) = item.validate_with(ctx) {
171                for mut issue in inner {
172                    if issue.field.is_empty() || issue.field == "body" {
173                        issue.field = format!("[{index}]");
174                    } else {
175                        issue.field = format!("[{index}].{}", issue.field);
176                    }
177                    issues.push(issue);
178                }
179            }
180        }
181        if issues.is_empty() {
182            Ok(())
183        } else {
184            Err(issues)
185        }
186    }
187}
188
189impl<T: Normalize> Normalize for BTreeSet<T> {
190    fn normalize(&mut self) {}
191}
192
193impl<T: Validate> Validate for BTreeSet<T> {
194    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
195        let mut issues = Vec::new();
196        for (index, item) in self.iter().enumerate() {
197            if let Err(inner) = item.validate_with(ctx) {
198                for mut issue in inner {
199                    if issue.field.is_empty() || issue.field == "body" {
200                        issue.field = format!("[{index}]");
201                    } else {
202                        issue.field = format!("[{index}].{}", issue.field);
203                    }
204                    issues.push(issue);
205                }
206            }
207        }
208        if issues.is_empty() {
209            Ok(())
210        } else {
211            Err(issues)
212        }
213    }
214}
215
216impl<T: Normalize> Normalize for HashSet<T> {
217    fn normalize(&mut self) {}
218}
219
220impl<T: Validate> Validate for HashSet<T> {
221    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
222        let mut issues = Vec::new();
223        for (index, item) in self.iter().enumerate() {
224            if let Err(inner) = item.validate_with(ctx) {
225                for mut issue in inner {
226                    if issue.field.is_empty() || issue.field == "body" {
227                        issue.field = format!("[{index}]");
228                    } else {
229                        issue.field = format!("[{index}].{}", issue.field);
230                    }
231                    issues.push(issue);
232                }
233            }
234        }
235        if issues.is_empty() {
236            Ok(())
237        } else {
238            Err(issues)
239        }
240    }
241}
242
243impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
244    fn normalize(&mut self) {
245        for value in self.values_mut() {
246            value.normalize();
247        }
248    }
249}
250
251impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
252    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
253        let mut issues = Vec::new();
254        for (key, value) in self {
255            if let Err(inner) = value.validate_with(ctx) {
256                for mut issue in inner {
257                    if issue.field.is_empty() || issue.field == "body" {
258                        issue.field = key.to_string();
259                    } else {
260                        issue.field = format!("{key}.{}", issue.field);
261                    }
262                    issues.push(issue);
263                }
264            }
265        }
266        if issues.is_empty() {
267            Ok(())
268        } else {
269            Err(issues)
270        }
271    }
272}
273
274impl<K: Eq + Hash, V: Normalize> Normalize for HashMap<K, V> {
275    fn normalize(&mut self) {
276        for value in self.values_mut() {
277            value.normalize();
278        }
279    }
280}
281
282impl<K: std::fmt::Display + Eq + Hash, V: Validate> Validate for HashMap<K, V> {
283    fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
284        let mut issues = Vec::new();
285        for (key, value) in self {
286            if let Err(inner) = value.validate_with(ctx) {
287                for mut issue in inner {
288                    if issue.field.is_empty() || issue.field == "body" {
289                        issue.field = key.to_string();
290                    } else {
291                        issue.field = format!("{key}.{}", issue.field);
292                    }
293                    issues.push(issue);
294                }
295            }
296        }
297        if issues.is_empty() {
298            Ok(())
299        } else {
300            Err(issues)
301        }
302    }
303}