Skip to main content

premortem/
validate.rs

1//! Validation trait and validators for configuration types.
2//!
3//! This module provides:
4//! - The `Validate` trait that configuration types implement
5//! - The `Validator` trait for composable validation functions
6//! - Built-in validators for common patterns (strings, numbers, paths, collections)
7//! - `ValidationContext` for source location lookup during validation
8//!
9//! # Stillwater Integration
10//!
11//! All validators integrate with stillwater's `Validation` type for error accumulation.
12//! Use `Validation::all()` to combine multiple validators and collect ALL errors.
13//!
14//! # Example
15//!
16//! ```ignore
17//! use premortem::{Validate, ConfigValidation, ConfigError, ConfigErrors};
18//! use premortem::validate::{validate_field, validators::*};
19//! use stillwater::Validation;
20//!
21//! struct ServerConfig {
22//!     host: String,
23//!     port: u16,
24//! }
25//!
26//! impl Validate for ServerConfig {
27//!     fn validate(&self) -> ConfigValidation<()> {
28//!         Validation::all((
29//!             validate_field(&self.host, "host", &[&NonEmpty]),
30//!             validate_field(&self.port, "port", &[&Range(1..=65535)]),
31//!         ))
32//!         .map(|_| ())
33//!     }
34//! }
35//! ```
36
37use std::cell::RefCell;
38use std::collections::HashMap;
39
40use stillwater::Validation;
41
42use crate::error::{ConfigError, ConfigErrors, ConfigValidation, SourceLocation};
43
44// ============================================================================
45// Validation Context (for source location lookup)
46// ============================================================================
47
48/// Map from config path to source location.
49pub type SourceLocationMap = HashMap<String, SourceLocation>;
50
51/// Context for validation with source location lookup.
52///
53/// This context is populated from `ConfigValues` during config building and
54/// made available to validation code via thread-local storage. This enables
55/// validation errors to include accurate source locations without changing
56/// the `Validate` trait signature.
57#[derive(Debug, Default)]
58pub struct ValidationContext {
59    locations: SourceLocationMap,
60}
61
62impl ValidationContext {
63    /// Create a new validation context with the given source locations.
64    pub fn new(locations: SourceLocationMap) -> Self {
65        Self { locations }
66    }
67
68    /// Look up the source location for a config path.
69    pub fn location_for(&self, path: &str) -> Option<&SourceLocation> {
70        self.locations.get(path)
71    }
72}
73
74// Thread-local storage for validation context.
75// This is pragmatic (per stillwater philosophy) - it avoids breaking the Validate trait API
76// while still enabling source location lookup from generated validation code.
77thread_local! {
78    static VALIDATION_CONTEXT: RefCell<Option<ValidationContext>> = const { RefCell::new(None) };
79    static PATH_PREFIX: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
80}
81
82/// Run a function with a validation context set.
83///
84/// The context is set for the duration of the function and cleared afterward.
85/// This is used by `ConfigBuilder` to provide source locations during validation.
86pub fn with_validation_context<F, R>(ctx: ValidationContext, f: F) -> R
87where
88    F: FnOnce() -> R,
89{
90    VALIDATION_CONTEXT.with(|cell| {
91        *cell.borrow_mut() = Some(ctx);
92    });
93    let result = f();
94    VALIDATION_CONTEXT.with(|cell| {
95        *cell.borrow_mut() = None;
96    });
97    result
98}
99
100/// Look up the source location for a config path from the current context.
101///
102/// Returns `None` if no context is set or if the path is not found.
103/// This is used by generated validation code to attach source locations to errors.
104///
105/// The lookup path is computed by prepending any active path prefixes (from nested
106/// validation) to the given field path.
107pub fn current_source_location(path: &str) -> Option<SourceLocation> {
108    // Build full path by prepending the current prefix
109    let full_path = PATH_PREFIX.with(|cell| {
110        let prefixes = cell.borrow();
111        if prefixes.is_empty() {
112            path.to_string()
113        } else {
114            format!("{}.{}", prefixes.join("."), path)
115        }
116    });
117
118    VALIDATION_CONTEXT.with(|cell| {
119        cell.borrow()
120            .as_ref()
121            .and_then(|ctx| ctx.location_for(&full_path).cloned())
122    })
123}
124
125/// Push a path prefix for nested validation.
126///
127/// Used by `validate_at` to track the current path context during nested struct validation.
128pub fn push_path_prefix(prefix: &str) {
129    PATH_PREFIX.with(|cell| {
130        cell.borrow_mut().push(prefix.to_string());
131    });
132}
133
134/// Pop a path prefix after nested validation completes.
135pub fn pop_path_prefix() {
136    PATH_PREFIX.with(|cell| {
137        cell.borrow_mut().pop();
138    });
139}
140
141/// Trait for validating configuration values.
142///
143/// Types implementing this trait can perform custom validation logic
144/// after deserialization. The validation uses stillwater's `Validation`
145/// type to accumulate all errors.
146///
147/// # Pure Core
148///
149/// Validators should be pure functions - no I/O allowed in the core validation.
150/// Path validators like `FileExists` perform I/O but are acceptable for
151/// configuration validation at startup time.
152pub trait Validate {
153    /// Validate this configuration value.
154    ///
155    /// Returns `ConfigValidation<()>` - either `Success(())` if validation
156    /// passes, or `Failure(ConfigErrors)` with all accumulated validation errors.
157    fn validate(&self) -> ConfigValidation<()>;
158
159    /// Validate with a path prefix for error context.
160    ///
161    /// This adds context to all errors, following stillwater's error trail pattern.
162    /// Used for nested struct validation.
163    ///
164    /// The path prefix is also pushed to thread-local storage so that source location
165    /// lookups during nested validation use the correct full path (e.g., "server.host"
166    /// instead of just "host").
167    ///
168    /// # Example
169    ///
170    /// ```ignore
171    /// // If inner validation produces error at path "host",
172    /// // validate_at("database") will produce error at path "database.host"
173    /// database_config.validate_at("database")
174    /// ```
175    fn validate_at(&self, path: &str) -> ConfigValidation<()> {
176        // Push prefix for source location lookups during nested validation
177        push_path_prefix(path);
178        let result = self.validate();
179        pop_path_prefix();
180
181        result.map_err(|errors| errors.with_path_prefix(path))
182    }
183}
184
185/// Blanket implementation for types that don't need validation.
186///
187/// Any type that doesn't implement `Validate` will automatically pass validation.
188/// This is implemented for the unit type as a no-op validator.
189impl Validate for () {
190    fn validate(&self) -> ConfigValidation<()> {
191        Validation::Success(())
192    }
193}
194
195/// Implementation for `Option<T>` where T: Validate.
196///
197/// None values pass validation; Some values delegate to the inner type.
198impl<T: Validate> Validate for Option<T> {
199    fn validate(&self) -> ConfigValidation<()> {
200        match self {
201            Some(inner) => inner.validate(),
202            None => Validation::Success(()),
203        }
204    }
205}
206
207/// Implementation for `Vec<T>` where T: Validate.
208///
209/// Validates all elements and accumulates errors using stillwater's traverse pattern.
210impl<T: Validate> Validate for Vec<T> {
211    fn validate(&self) -> ConfigValidation<()> {
212        if self.is_empty() {
213            return Validation::Success(());
214        }
215
216        // Use traverse pattern to validate each item with index context
217        let validations: Vec<ConfigValidation<()>> = self
218            .iter()
219            .enumerate()
220            .map(|(i, item)| item.validate_at(&format!("[{}]", i)))
221            .collect();
222        Validation::all_vec(validations).map(|_| ())
223    }
224}
225
226// Primitive types don't need validation
227macro_rules! impl_validate_noop {
228    ($($t:ty),*) => {
229        $(
230            impl Validate for $t {
231                fn validate(&self) -> ConfigValidation<()> {
232                    Validation::Success(())
233                }
234            }
235        )*
236    };
237}
238
239impl_validate_noop!(
240    bool, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, char, String
241);
242
243impl Validate for &str {
244    fn validate(&self) -> ConfigValidation<()> {
245        Validation::Success(())
246    }
247}
248
249impl Validate for std::path::PathBuf {
250    fn validate(&self) -> ConfigValidation<()> {
251        Validation::Success(())
252    }
253}
254
255// ============================================================================
256// Validator Trait
257// ============================================================================
258
259/// A validator function that checks a value and returns validation result.
260///
261/// Validators are pure functions: `&T -> ConfigValidation<()>`
262/// They return either Success(()) or Failure(ConfigErrors).
263///
264/// # Type Parameters
265///
266/// - `T`: The type being validated (can be unsized, e.g., `str`, `[T]`)
267pub trait Validator<T: ?Sized> {
268    /// Validate a value at the given path.
269    ///
270    /// Returns `Success(())` if valid, or `Failure(ConfigErrors)` with an error
271    /// that includes the path for context.
272    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()>;
273}
274
275/// Helper to create a validation failure with a single error.
276fn fail(error: ConfigError) -> ConfigValidation<()> {
277    Validation::Failure(ConfigErrors::single(error))
278}
279
280// ============================================================================
281// Predicate-Validator Bridge
282// ============================================================================
283
284use stillwater::predicate::Predicate;
285
286/// Adapter that converts a `Predicate<T>` into a `Validator<T>`.
287///
288/// This enables using stillwater's composable predicates within premortem's
289/// validation framework while maintaining source location tracking.
290///
291/// # Example
292///
293/// ```ignore
294/// use premortem::validate::from_predicate;
295/// use premortem::prelude::*;
296///
297/// let validator = from_predicate(
298///     not_empty().and(len_between(3, 20))
299/// );
300///
301/// // Use in validate_field
302/// validate_field(&username, "username", &[&validator])
303/// ```
304pub fn from_predicate<T>(predicate: impl Predicate<T>) -> impl Validator<T>
305where
306    T: ?Sized,
307{
308    PredicateValidator(predicate)
309}
310
311/// Internal adapter struct that implements Validator for any Predicate.
312struct PredicateValidator<P>(P);
313
314impl<T, P> Validator<T> for PredicateValidator<P>
315where
316    T: ?Sized,
317    P: Predicate<T>,
318{
319    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
320        if self.0.check(value) {
321            Validation::Success(())
322        } else {
323            // Get source location from thread-local context
324            let source_location = current_source_location(path);
325
326            Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
327                path: path.to_string(),
328                source_location,
329                value: None, // Predicates don't provide value formatting
330                message: "validation failed".to_string(),
331            }))
332        }
333    }
334}
335
336/// Validate a field using a predicate with custom error message.
337///
338/// This is a convenience function that combines predicate testing with
339/// premortem's error accumulation.
340///
341/// # Example
342///
343/// ```ignore
344/// use premortem::validate::validate_with_predicate;
345/// use premortem::prelude::*;
346///
347/// validate_with_predicate(
348///     &port,
349///     "port",
350///     between(1, 65535),
351///     "port must be between 1 and 65535"
352/// )
353/// ```
354pub fn validate_with_predicate<T>(
355    value: &T,
356    path: &str,
357    predicate: impl Predicate<T>,
358    message: impl Into<String>,
359) -> ConfigValidation<()>
360where
361    T: ?Sized,
362{
363    if predicate.check(value) {
364        Validation::Success(())
365    } else {
366        let source_location = current_source_location(path);
367
368        Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
369            path: path.to_string(),
370            source_location,
371            value: None,
372            message: message.into(),
373        }))
374    }
375}
376
377// ============================================================================
378// Validation Helper Functions
379// ============================================================================
380
381/// Validate a field against multiple validators using Validation::all().
382///
383/// This is the core composition pattern - run all validators and accumulate errors.
384/// Follows stillwater's "fail completely" philosophy.
385///
386/// # Example
387///
388/// ```ignore
389/// use premortem::validate::{validate_field, validators::*};
390///
391/// let result = validate_field(&host, "host", &[&NonEmpty, &MinLength(3)]);
392/// ```
393pub fn validate_field<T>(
394    value: &T,
395    path: &str,
396    validators: &[&dyn Validator<T>],
397) -> ConfigValidation<()>
398where
399    T: ?Sized,
400{
401    if validators.is_empty() {
402        return Validation::Success(());
403    }
404
405    let results: Vec<ConfigValidation<()>> =
406        validators.iter().map(|v| v.validate(value, path)).collect();
407
408    Validation::all_vec(results).map(|_| ())
409}
410
411/// Validate a nested struct with path context.
412///
413/// Delegates to the inner type's `validate_at` method.
414pub fn validate_nested<T: Validate>(value: &T, path: &str) -> ConfigValidation<()> {
415    value.validate_at(path)
416}
417
418/// Validate an optional nested struct.
419///
420/// None is always valid.
421pub fn validate_optional_nested<T: Validate>(
422    value: &Option<T>,
423    path: &str,
424) -> ConfigValidation<()> {
425    match value {
426        Some(v) => v.validate_at(path),
427        None => Validation::Success(()),
428    }
429}
430
431// ============================================================================
432// Built-in Validators
433// ============================================================================
434
435/// Built-in validators for common validation patterns.
436///
437/// All validators are zero-cost structs that implement the `Validator` trait.
438/// They can be composed using `validate_field()` for multiple checks on one field.
439pub mod validators {
440    use super::*;
441    use std::fmt::Display;
442    use std::ops::RangeInclusive;
443    use std::path::Path;
444
445    // ========================================================================
446    // String Validators
447    // ========================================================================
448
449    /// Validates that a string is not empty.
450    #[derive(Debug, Clone, Copy)]
451    pub struct NonEmpty;
452
453    impl Validator<str> for NonEmpty {
454        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
455            if value.is_empty() {
456                fail(ConfigError::ValidationError {
457                    path: path.to_string(),
458                    source_location: None,
459                    value: Some(String::new()),
460                    message: "value cannot be empty".to_string(),
461                })
462            } else {
463                Validation::Success(())
464            }
465        }
466    }
467
468    impl Validator<String> for NonEmpty {
469        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
470            <NonEmpty as Validator<str>>::validate(self, value.as_str(), path)
471        }
472    }
473
474    /// Validates that a string has at least the specified length.
475    #[derive(Debug, Clone, Copy)]
476    pub struct MinLength(pub usize);
477
478    impl Validator<str> for MinLength {
479        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
480            if value.len() < self.0 {
481                fail(ConfigError::ValidationError {
482                    path: path.to_string(),
483                    source_location: None,
484                    value: Some(value.to_string()),
485                    message: format!("length {} is less than minimum {}", value.len(), self.0),
486                })
487            } else {
488                Validation::Success(())
489            }
490        }
491    }
492
493    impl Validator<String> for MinLength {
494        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
495            <MinLength as Validator<str>>::validate(self, value.as_str(), path)
496        }
497    }
498
499    /// Validates that a string has at most the specified length.
500    #[derive(Debug, Clone, Copy)]
501    pub struct MaxLength(pub usize);
502
503    impl Validator<str> for MaxLength {
504        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
505            if value.len() > self.0 {
506                fail(ConfigError::ValidationError {
507                    path: path.to_string(),
508                    source_location: None,
509                    value: Some(value.to_string()),
510                    message: format!("length {} exceeds maximum {}", value.len(), self.0),
511                })
512            } else {
513                Validation::Success(())
514            }
515        }
516    }
517
518    impl Validator<String> for MaxLength {
519        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
520            <MaxLength as Validator<str>>::validate(self, value.as_str(), path)
521        }
522    }
523
524    /// Validates that a string length is within a range (inclusive).
525    #[derive(Debug, Clone)]
526    pub struct Length(pub RangeInclusive<usize>);
527
528    impl Validator<str> for Length {
529        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
530            let len = value.len();
531            if !self.0.contains(&len) {
532                fail(ConfigError::ValidationError {
533                    path: path.to_string(),
534                    source_location: None,
535                    value: Some(value.to_string()),
536                    message: format!(
537                        "length {} is not in range {}..={}",
538                        len,
539                        self.0.start(),
540                        self.0.end()
541                    ),
542                })
543            } else {
544                Validation::Success(())
545            }
546        }
547    }
548
549    impl Validator<String> for Length {
550        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
551            <Length as Validator<str>>::validate(self, value.as_str(), path)
552        }
553    }
554
555    /// Validates that a string matches a regular expression pattern.
556    ///
557    /// The pattern string is compiled on first use. For performance-critical
558    /// code, consider pre-compiling with `regex::Regex`.
559    #[derive(Debug, Clone)]
560    pub struct Pattern(pub String);
561
562    impl Pattern {
563        /// Create a new pattern validator.
564        pub fn new(pattern: impl Into<String>) -> Self {
565            Self(pattern.into())
566        }
567    }
568
569    impl Validator<str> for Pattern {
570        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
571            // Compile regex - in production, consider caching
572            match regex::Regex::new(&self.0) {
573                Ok(re) => {
574                    if re.is_match(value) {
575                        Validation::Success(())
576                    } else {
577                        fail(ConfigError::ValidationError {
578                            path: path.to_string(),
579                            source_location: None,
580                            value: Some(value.to_string()),
581                            message: format!("value does not match pattern '{}'", self.0),
582                        })
583                    }
584                }
585                Err(e) => fail(ConfigError::ValidationError {
586                    path: path.to_string(),
587                    source_location: None,
588                    value: Some(value.to_string()),
589                    message: format!("invalid pattern '{}': {}", self.0, e),
590                }),
591            }
592        }
593    }
594
595    impl Validator<String> for Pattern {
596        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
597            <Pattern as Validator<str>>::validate(self, value.as_str(), path)
598        }
599    }
600
601    /// Validates that a string is a valid email address.
602    ///
603    /// Uses a simplified RFC 5322-like pattern. For strict compliance,
604    /// consider using the `email_address` crate.
605    #[derive(Debug, Clone, Copy)]
606    pub struct Email;
607
608    impl Validator<str> for Email {
609        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
610            // Simple email validation pattern
611            // For strict RFC 5322, use email_address crate
612            let email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
613            let re = regex::Regex::new(email_pattern).expect("valid email regex");
614
615            if re.is_match(value) {
616                Validation::Success(())
617            } else {
618                fail(ConfigError::ValidationError {
619                    path: path.to_string(),
620                    source_location: None,
621                    value: Some(value.to_string()),
622                    message: "value is not a valid email address".to_string(),
623                })
624            }
625        }
626    }
627
628    impl Validator<String> for Email {
629        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
630            <Email as Validator<str>>::validate(self, value.as_str(), path)
631        }
632    }
633
634    /// Validates that a string is a valid URL.
635    #[derive(Debug, Clone, Copy)]
636    pub struct Url;
637
638    impl Validator<str> for Url {
639        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
640            // Simple URL pattern - for strict validation, use the url crate
641            let url_pattern = r"^(https?|ftp)://[^\s/$.?#].[^\s]*$";
642            let re = regex::Regex::new(url_pattern).expect("valid url regex");
643
644            if re.is_match(value) {
645                Validation::Success(())
646            } else {
647                fail(ConfigError::ValidationError {
648                    path: path.to_string(),
649                    source_location: None,
650                    value: Some(value.to_string()),
651                    message: "value is not a valid URL".to_string(),
652                })
653            }
654        }
655    }
656
657    impl Validator<String> for Url {
658        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
659            <Url as Validator<str>>::validate(self, value.as_str(), path)
660        }
661    }
662
663    // ========================================================================
664    // Numeric Validators
665    // ========================================================================
666
667    /// Validates that a numeric value is within a range (inclusive).
668    #[derive(Debug, Clone)]
669    pub struct Range<T>(pub RangeInclusive<T>);
670
671    impl<T> Validator<T> for Range<T>
672    where
673        T: PartialOrd + Display + Clone,
674    {
675        fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
676            if !self.0.contains(value) {
677                fail(ConfigError::ValidationError {
678                    path: path.to_string(),
679                    source_location: None,
680                    value: Some(value.to_string()),
681                    message: format!(
682                        "value {} is not in range {}..={}",
683                        value,
684                        self.0.start(),
685                        self.0.end()
686                    ),
687                })
688            } else {
689                Validation::Success(())
690            }
691        }
692    }
693
694    /// Validates that a numeric value is positive (> 0).
695    #[derive(Debug, Clone, Copy)]
696    pub struct Positive;
697
698    macro_rules! impl_positive_for_signed {
699        ($($t:ty),*) => {
700            $(
701                impl Validator<$t> for Positive {
702                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
703                        if *value > 0 {
704                            Validation::Success(())
705                        } else {
706                            fail(ConfigError::ValidationError {
707                                path: path.to_string(),
708                                source_location: None,
709                                value: Some(value.to_string()),
710                                message: "value must be positive".to_string(),
711                            })
712                        }
713                    }
714                }
715            )*
716        };
717    }
718
719    macro_rules! impl_positive_for_unsigned {
720        ($($t:ty),*) => {
721            $(
722                impl Validator<$t> for Positive {
723                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
724                        if *value > 0 {
725                            Validation::Success(())
726                        } else {
727                            fail(ConfigError::ValidationError {
728                                path: path.to_string(),
729                                source_location: None,
730                                value: Some(value.to_string()),
731                                message: "value must be positive".to_string(),
732                            })
733                        }
734                    }
735                }
736            )*
737        };
738    }
739
740    macro_rules! impl_positive_for_float {
741        ($($t:ty),*) => {
742            $(
743                impl Validator<$t> for Positive {
744                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
745                        if *value > 0.0 {
746                            Validation::Success(())
747                        } else {
748                            fail(ConfigError::ValidationError {
749                                path: path.to_string(),
750                                source_location: None,
751                                value: Some(value.to_string()),
752                                message: "value must be positive".to_string(),
753                            })
754                        }
755                    }
756                }
757            )*
758        };
759    }
760
761    impl_positive_for_signed!(i8, i16, i32, i64, i128, isize);
762    impl_positive_for_unsigned!(u8, u16, u32, u64, u128, usize);
763    impl_positive_for_float!(f32, f64);
764
765    /// Validates that a numeric value is negative (< 0).
766    #[derive(Debug, Clone, Copy)]
767    pub struct Negative;
768
769    macro_rules! impl_negative_for_signed {
770        ($($t:ty),*) => {
771            $(
772                impl Validator<$t> for Negative {
773                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
774                        if *value < 0 {
775                            Validation::Success(())
776                        } else {
777                            fail(ConfigError::ValidationError {
778                                path: path.to_string(),
779                                source_location: None,
780                                value: Some(value.to_string()),
781                                message: "value must be negative".to_string(),
782                            })
783                        }
784                    }
785                }
786            )*
787        };
788    }
789
790    macro_rules! impl_negative_for_float {
791        ($($t:ty),*) => {
792            $(
793                impl Validator<$t> for Negative {
794                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
795                        if *value < 0.0 {
796                            Validation::Success(())
797                        } else {
798                            fail(ConfigError::ValidationError {
799                                path: path.to_string(),
800                                source_location: None,
801                                value: Some(value.to_string()),
802                                message: "value must be negative".to_string(),
803                            })
804                        }
805                    }
806                }
807            )*
808        };
809    }
810
811    impl_negative_for_signed!(i8, i16, i32, i64, i128, isize);
812    impl_negative_for_float!(f32, f64);
813
814    /// Validates that a numeric value is non-zero.
815    #[derive(Debug, Clone, Copy)]
816    pub struct NonZero;
817
818    macro_rules! impl_nonzero_for_int {
819        ($($t:ty),*) => {
820            $(
821                impl Validator<$t> for NonZero {
822                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
823                        if *value != 0 {
824                            Validation::Success(())
825                        } else {
826                            fail(ConfigError::ValidationError {
827                                path: path.to_string(),
828                                source_location: None,
829                                value: Some(value.to_string()),
830                                message: "value cannot be zero".to_string(),
831                            })
832                        }
833                    }
834                }
835            )*
836        };
837    }
838
839    macro_rules! impl_nonzero_for_float {
840        ($($t:ty),*) => {
841            $(
842                impl Validator<$t> for NonZero {
843                    fn validate(&self, value: &$t, path: &str) -> ConfigValidation<()> {
844                        #[allow(clippy::float_cmp)]
845                        if *value != 0.0 {
846                            Validation::Success(())
847                        } else {
848                            fail(ConfigError::ValidationError {
849                                path: path.to_string(),
850                                source_location: None,
851                                value: Some(value.to_string()),
852                                message: "value cannot be zero".to_string(),
853                            })
854                        }
855                    }
856                }
857            )*
858        };
859    }
860
861    impl_nonzero_for_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
862    impl_nonzero_for_float!(f32, f64);
863
864    // ========================================================================
865    // Collection Validators
866    // ========================================================================
867
868    /// Validates that a collection is not empty.
869    #[derive(Debug, Clone, Copy)]
870    pub struct NonEmptyCollection;
871
872    impl<T> Validator<Vec<T>> for NonEmptyCollection {
873        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
874            if value.is_empty() {
875                fail(ConfigError::ValidationError {
876                    path: path.to_string(),
877                    source_location: None,
878                    value: Some("[]".to_string()),
879                    message: "collection cannot be empty".to_string(),
880                })
881            } else {
882                Validation::Success(())
883            }
884        }
885    }
886
887    impl<T> Validator<[T]> for NonEmptyCollection {
888        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
889            if value.is_empty() {
890                fail(ConfigError::ValidationError {
891                    path: path.to_string(),
892                    source_location: None,
893                    value: Some("[]".to_string()),
894                    message: "collection cannot be empty".to_string(),
895                })
896            } else {
897                Validation::Success(())
898            }
899        }
900    }
901
902    /// Validates that a collection has at least the specified number of elements.
903    #[derive(Debug, Clone, Copy)]
904    pub struct MinItems(pub usize);
905
906    impl<T> Validator<Vec<T>> for MinItems {
907        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
908            if value.len() < self.0 {
909                fail(ConfigError::ValidationError {
910                    path: path.to_string(),
911                    source_location: None,
912                    value: Some(format!("[{} items]", value.len())),
913                    message: format!(
914                        "collection has {} items, minimum is {}",
915                        value.len(),
916                        self.0
917                    ),
918                })
919            } else {
920                Validation::Success(())
921            }
922        }
923    }
924
925    impl<T> Validator<[T]> for MinItems {
926        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
927            if value.len() < self.0 {
928                fail(ConfigError::ValidationError {
929                    path: path.to_string(),
930                    source_location: None,
931                    value: Some(format!("[{} items]", value.len())),
932                    message: format!(
933                        "collection has {} items, minimum is {}",
934                        value.len(),
935                        self.0
936                    ),
937                })
938            } else {
939                Validation::Success(())
940            }
941        }
942    }
943
944    /// Validates that a collection has at most the specified number of elements.
945    #[derive(Debug, Clone, Copy)]
946    pub struct MaxItems(pub usize);
947
948    impl<T> Validator<Vec<T>> for MaxItems {
949        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
950            if value.len() > self.0 {
951                fail(ConfigError::ValidationError {
952                    path: path.to_string(),
953                    source_location: None,
954                    value: Some(format!("[{} items]", value.len())),
955                    message: format!(
956                        "collection has {} items, maximum is {}",
957                        value.len(),
958                        self.0
959                    ),
960                })
961            } else {
962                Validation::Success(())
963            }
964        }
965    }
966
967    impl<T> Validator<[T]> for MaxItems {
968        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
969            if value.len() > self.0 {
970                fail(ConfigError::ValidationError {
971                    path: path.to_string(),
972                    source_location: None,
973                    value: Some(format!("[{} items]", value.len())),
974                    message: format!(
975                        "collection has {} items, maximum is {}",
976                        value.len(),
977                        self.0
978                    ),
979                })
980            } else {
981                Validation::Success(())
982            }
983        }
984    }
985
986    /// Validates each item in a collection using the given validator.
987    ///
988    /// Uses stillwater's traverse pattern to accumulate ALL errors across ALL items.
989    #[derive(Debug, Clone)]
990    pub struct Each<V>(pub V);
991
992    impl<V, T> Validator<Vec<T>> for Each<V>
993    where
994        V: Validator<T>,
995    {
996        fn validate(&self, value: &Vec<T>, path: &str) -> ConfigValidation<()> {
997            if value.is_empty() {
998                return Validation::Success(());
999            }
1000
1001            let results: Vec<ConfigValidation<()>> = value
1002                .iter()
1003                .enumerate()
1004                .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
1005                .collect();
1006
1007            Validation::all_vec(results).map(|_| ())
1008        }
1009    }
1010
1011    impl<V, T> Validator<[T]> for Each<V>
1012    where
1013        V: Validator<T>,
1014    {
1015        fn validate(&self, value: &[T], path: &str) -> ConfigValidation<()> {
1016            if value.is_empty() {
1017                return Validation::Success(());
1018            }
1019
1020            let results: Vec<ConfigValidation<()>> = value
1021                .iter()
1022                .enumerate()
1023                .map(|(i, item)| self.0.validate(item, &format!("{}[{}]", path, i)))
1024                .collect();
1025
1026            Validation::all_vec(results).map(|_| ())
1027        }
1028    }
1029
1030    // ========================================================================
1031    // Path Validators
1032    // ========================================================================
1033
1034    /// Validates that a path points to an existing file.
1035    ///
1036    /// **Note**: This performs I/O (filesystem check). For strict pure core /
1037    /// imperative shell separation, consider using stillwater's `Effect` type.
1038    /// Kept here for convenience in config validation at startup.
1039    #[derive(Debug, Clone, Copy)]
1040    pub struct FileExists;
1041
1042    impl Validator<Path> for FileExists {
1043        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1044            if value.is_file() {
1045                Validation::Success(())
1046            } else {
1047                fail(ConfigError::ValidationError {
1048                    path: path.to_string(),
1049                    source_location: None,
1050                    value: Some(value.display().to_string()),
1051                    message: "file does not exist".to_string(),
1052                })
1053            }
1054        }
1055    }
1056
1057    impl Validator<std::path::PathBuf> for FileExists {
1058        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1059            <FileExists as Validator<Path>>::validate(self, value.as_path(), path)
1060        }
1061    }
1062
1063    impl Validator<str> for FileExists {
1064        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1065            <FileExists as Validator<Path>>::validate(self, Path::new(value), path)
1066        }
1067    }
1068
1069    impl Validator<String> for FileExists {
1070        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1071            <FileExists as Validator<str>>::validate(self, value.as_str(), path)
1072        }
1073    }
1074
1075    /// Validates that a path points to an existing directory.
1076    ///
1077    /// **Note**: This performs I/O (filesystem check).
1078    #[derive(Debug, Clone, Copy)]
1079    pub struct DirExists;
1080
1081    impl Validator<Path> for DirExists {
1082        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1083            if value.is_dir() {
1084                Validation::Success(())
1085            } else {
1086                fail(ConfigError::ValidationError {
1087                    path: path.to_string(),
1088                    source_location: None,
1089                    value: Some(value.display().to_string()),
1090                    message: "directory does not exist".to_string(),
1091                })
1092            }
1093        }
1094    }
1095
1096    impl Validator<std::path::PathBuf> for DirExists {
1097        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1098            <DirExists as Validator<Path>>::validate(self, value.as_path(), path)
1099        }
1100    }
1101
1102    impl Validator<str> for DirExists {
1103        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1104            <DirExists as Validator<Path>>::validate(self, Path::new(value), path)
1105        }
1106    }
1107
1108    impl Validator<String> for DirExists {
1109        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1110            <DirExists as Validator<str>>::validate(self, value.as_str(), path)
1111        }
1112    }
1113
1114    /// Validates that a path's parent directory exists.
1115    ///
1116    /// Useful for validating output file paths before writing.
1117    ///
1118    /// **Note**: This performs I/O (filesystem check).
1119    #[derive(Debug, Clone, Copy)]
1120    pub struct ParentExists;
1121
1122    impl Validator<Path> for ParentExists {
1123        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1124            match value.parent() {
1125                Some(parent) if parent.is_dir() || parent.as_os_str().is_empty() => {
1126                    Validation::Success(())
1127                }
1128                Some(_) => fail(ConfigError::ValidationError {
1129                    path: path.to_string(),
1130                    source_location: None,
1131                    value: Some(value.display().to_string()),
1132                    message: "parent directory does not exist".to_string(),
1133                }),
1134                None => fail(ConfigError::ValidationError {
1135                    path: path.to_string(),
1136                    source_location: None,
1137                    value: Some(value.display().to_string()),
1138                    message: "path has no parent directory".to_string(),
1139                }),
1140            }
1141        }
1142    }
1143
1144    impl Validator<std::path::PathBuf> for ParentExists {
1145        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1146            <ParentExists as Validator<Path>>::validate(self, value.as_path(), path)
1147        }
1148    }
1149
1150    impl Validator<str> for ParentExists {
1151        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1152            <ParentExists as Validator<Path>>::validate(self, Path::new(value), path)
1153        }
1154    }
1155
1156    impl Validator<String> for ParentExists {
1157        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1158            <ParentExists as Validator<str>>::validate(self, value.as_str(), path)
1159        }
1160    }
1161
1162    /// Validates that a path has the specified file extension.
1163    #[derive(Debug, Clone)]
1164    pub struct Extension(pub String);
1165
1166    impl Extension {
1167        /// Create a new extension validator.
1168        pub fn new(ext: impl Into<String>) -> Self {
1169            Self(ext.into())
1170        }
1171    }
1172
1173    impl Validator<Path> for Extension {
1174        fn validate(&self, value: &Path, path: &str) -> ConfigValidation<()> {
1175            match value.extension() {
1176                Some(ext) if ext == self.0.as_str() => Validation::Success(()),
1177                Some(ext) => fail(ConfigError::ValidationError {
1178                    path: path.to_string(),
1179                    source_location: None,
1180                    value: Some(value.display().to_string()),
1181                    message: format!(
1182                        "expected extension '{}', found '{}'",
1183                        self.0,
1184                        ext.to_string_lossy()
1185                    ),
1186                }),
1187                None => fail(ConfigError::ValidationError {
1188                    path: path.to_string(),
1189                    source_location: None,
1190                    value: Some(value.display().to_string()),
1191                    message: format!("expected extension '{}', found none", self.0),
1192                }),
1193            }
1194        }
1195    }
1196
1197    impl Validator<std::path::PathBuf> for Extension {
1198        fn validate(&self, value: &std::path::PathBuf, path: &str) -> ConfigValidation<()> {
1199            <Extension as Validator<Path>>::validate(self, value.as_path(), path)
1200        }
1201    }
1202
1203    impl Validator<str> for Extension {
1204        fn validate(&self, value: &str, path: &str) -> ConfigValidation<()> {
1205            <Extension as Validator<Path>>::validate(self, Path::new(value), path)
1206        }
1207    }
1208
1209    impl Validator<String> for Extension {
1210        fn validate(&self, value: &String, path: &str) -> ConfigValidation<()> {
1211            <Extension as Validator<str>>::validate(self, value.as_str(), path)
1212        }
1213    }
1214}
1215
1216// ============================================================================
1217// Custom Validator Support
1218// ============================================================================
1219
1220/// Create a custom validator from a pure function.
1221///
1222/// # Example
1223///
1224/// ```ignore
1225/// use premortem::validate::custom;
1226/// use premortem::{ConfigError, ConfigValidation};
1227/// use stillwater::Validation;
1228///
1229/// let even_validator = custom(|value: &i32, path: &str| {
1230///     if value % 2 == 0 {
1231///         Validation::Success(())
1232///     } else {
1233///         Validation::Failure(ConfigErrors::single(ConfigError::ValidationError {
1234///             path: path.to_string(),
1235///             source_location: None,
1236///             value: Some(value.to_string()),
1237///             message: "value must be even".to_string(),
1238///         }))
1239///     }
1240/// });
1241/// ```
1242pub fn custom<T, F>(f: F) -> impl Validator<T>
1243where
1244    F: Fn(&T, &str) -> ConfigValidation<()>,
1245{
1246    struct Custom<F>(F);
1247
1248    impl<T, F> Validator<T> for Custom<F>
1249    where
1250        F: Fn(&T, &str) -> ConfigValidation<()>,
1251    {
1252        fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
1253            (self.0)(value, path)
1254        }
1255    }
1256
1257    Custom(f)
1258}
1259
1260// ============================================================================
1261// Conditional Validation
1262// ============================================================================
1263
1264/// Validator that only runs when a condition is true.
1265///
1266/// Useful for "when X is set, Y must be valid" patterns.
1267///
1268/// # Example
1269///
1270/// ```ignore
1271/// use premortem::validate::{When, validators::NonEmpty};
1272///
1273/// // Only validate host is non-empty when use_remote is true
1274/// let conditional = When::new(NonEmpty, || config.use_remote);
1275/// ```
1276pub struct When<V, F> {
1277    validator: V,
1278    condition: F,
1279}
1280
1281impl<V, F> When<V, F> {
1282    /// Create a new conditional validator.
1283    pub fn new(validator: V, condition: F) -> Self {
1284        Self {
1285            validator,
1286            condition,
1287        }
1288    }
1289}
1290
1291impl<V, F, T> Validator<T> for When<V, F>
1292where
1293    V: Validator<T>,
1294    F: Fn() -> bool,
1295    T: ?Sized,
1296{
1297    fn validate(&self, value: &T, path: &str) -> ConfigValidation<()> {
1298        if (self.condition)() {
1299            self.validator.validate(value, path)
1300        } else {
1301            Validation::Success(())
1302        }
1303    }
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308    use super::validators::*;
1309    use super::*;
1310    use std::path::{Path, PathBuf};
1311
1312    // ========================================================================
1313    // Validate Trait Tests
1314    // ========================================================================
1315
1316    #[test]
1317    fn test_unit_validate() {
1318        let result = ().validate();
1319        assert!(result.is_success());
1320    }
1321
1322    #[test]
1323    fn test_option_validate_none() {
1324        let opt: Option<String> = None;
1325        let result = opt.validate();
1326        assert!(result.is_success());
1327    }
1328
1329    #[test]
1330    fn test_option_validate_some() {
1331        let opt = Some("value".to_string());
1332        let result = opt.validate();
1333        assert!(result.is_success());
1334    }
1335
1336    #[test]
1337    fn test_vec_validate_empty() {
1338        let v: Vec<String> = vec![];
1339        let result = v.validate();
1340        assert!(result.is_success());
1341    }
1342
1343    #[test]
1344    fn test_vec_validate_with_items() {
1345        let v = vec!["a".to_string(), "b".to_string()];
1346        let result = v.validate();
1347        assert!(result.is_success());
1348    }
1349
1350    #[test]
1351    fn test_primitive_validate() {
1352        assert!(42i32.validate().is_success());
1353        assert!((std::f64::consts::E).validate().is_success());
1354        assert!(true.validate().is_success());
1355        assert!("hello".to_string().validate().is_success());
1356    }
1357
1358    #[test]
1359    fn test_pathbuf_validate() {
1360        let path = PathBuf::from("/some/path");
1361        assert!(path.validate().is_success());
1362    }
1363
1364    // ========================================================================
1365    // validate_at Tests
1366    // ========================================================================
1367
1368    struct FailingConfig;
1369
1370    impl Validate for FailingConfig {
1371        fn validate(&self) -> ConfigValidation<()> {
1372            fail(ConfigError::ValidationError {
1373                path: "inner".to_string(),
1374                source_location: None,
1375                value: None,
1376                message: "always fails".to_string(),
1377            })
1378        }
1379    }
1380
1381    #[test]
1382    fn test_validate_at_prefixes_path() {
1383        let config = FailingConfig;
1384        let result = config.validate_at("outer");
1385        assert!(result.is_failure());
1386
1387        if let Validation::Failure(errors) = result {
1388            assert_eq!(errors.first().path(), Some("outer.inner"));
1389        }
1390    }
1391
1392    // ========================================================================
1393    // String Validator Tests
1394    // ========================================================================
1395
1396    #[test]
1397    fn test_non_empty_success() {
1398        let result = NonEmpty.validate("hello", "field");
1399        assert!(result.is_success());
1400    }
1401
1402    #[test]
1403    fn test_non_empty_failure() {
1404        let result = NonEmpty.validate("", "field");
1405        assert!(result.is_failure());
1406    }
1407
1408    #[test]
1409    fn test_min_length_success() {
1410        let result = MinLength(3).validate("hello", "field");
1411        assert!(result.is_success());
1412    }
1413
1414    #[test]
1415    fn test_min_length_failure() {
1416        let result = MinLength(10).validate("hi", "field");
1417        assert!(result.is_failure());
1418    }
1419
1420    #[test]
1421    fn test_max_length_success() {
1422        let result = MaxLength(10).validate("hello", "field");
1423        assert!(result.is_success());
1424    }
1425
1426    #[test]
1427    fn test_max_length_failure() {
1428        let result = MaxLength(3).validate("hello", "field");
1429        assert!(result.is_failure());
1430    }
1431
1432    #[test]
1433    fn test_length_success() {
1434        let result = Length(3..=10).validate("hello", "field");
1435        assert!(result.is_success());
1436    }
1437
1438    #[test]
1439    fn test_length_failure_too_short() {
1440        let result = Length(5..=10).validate("hi", "field");
1441        assert!(result.is_failure());
1442    }
1443
1444    #[test]
1445    fn test_length_failure_too_long() {
1446        let result = Length(1..=3).validate("hello", "field");
1447        assert!(result.is_failure());
1448    }
1449
1450    #[test]
1451    fn test_pattern_success() {
1452        let result = Pattern::new(r"^\d+$").validate("12345", "field");
1453        assert!(result.is_success());
1454    }
1455
1456    #[test]
1457    fn test_pattern_failure() {
1458        let result = Pattern::new(r"^\d+$").validate("abc", "field");
1459        assert!(result.is_failure());
1460    }
1461
1462    #[test]
1463    fn test_email_success() {
1464        let result = Email.validate("user@example.com", "email");
1465        assert!(result.is_success());
1466    }
1467
1468    #[test]
1469    fn test_email_failure() {
1470        let result = Email.validate("not-an-email", "email");
1471        assert!(result.is_failure());
1472    }
1473
1474    #[test]
1475    fn test_url_success() {
1476        let result = Url.validate("https://example.com", "url");
1477        assert!(result.is_success());
1478    }
1479
1480    #[test]
1481    fn test_url_failure() {
1482        let result = Url.validate("not-a-url", "url");
1483        assert!(result.is_failure());
1484    }
1485
1486    // ========================================================================
1487    // Numeric Validator Tests
1488    // ========================================================================
1489
1490    #[test]
1491    fn test_range_success() {
1492        let result = Range(1..=100).validate(&50i32, "field");
1493        assert!(result.is_success());
1494    }
1495
1496    #[test]
1497    fn test_range_failure_below() {
1498        let result = Range(10..=100).validate(&5i32, "field");
1499        assert!(result.is_failure());
1500    }
1501
1502    #[test]
1503    fn test_range_failure_above() {
1504        let result = Range(1..=10).validate(&50i32, "field");
1505        assert!(result.is_failure());
1506    }
1507
1508    #[test]
1509    fn test_positive_success() {
1510        assert!(Positive.validate(&42i32, "field").is_success());
1511        assert!(Positive.validate(&1u32, "field").is_success());
1512        assert!(Positive.validate(&0.5f64, "field").is_success());
1513    }
1514
1515    #[test]
1516    fn test_positive_failure() {
1517        assert!(Positive.validate(&-1i32, "field").is_failure());
1518        assert!(Positive.validate(&0i32, "field").is_failure());
1519        assert!(Positive.validate(&0u32, "field").is_failure());
1520        assert!(Positive.validate(&-0.5f64, "field").is_failure());
1521    }
1522
1523    #[test]
1524    fn test_negative_success() {
1525        assert!(Negative.validate(&-42i32, "field").is_success());
1526        assert!(Negative.validate(&-0.5f64, "field").is_success());
1527    }
1528
1529    #[test]
1530    fn test_negative_failure() {
1531        assert!(Negative.validate(&42i32, "field").is_failure());
1532        assert!(Negative.validate(&0i32, "field").is_failure());
1533        assert!(Negative.validate(&0.5f64, "field").is_failure());
1534    }
1535
1536    #[test]
1537    fn test_non_zero_success() {
1538        assert!(NonZero.validate(&42i32, "field").is_success());
1539        assert!(NonZero.validate(&-1i32, "field").is_success());
1540        assert!(NonZero.validate(&1u32, "field").is_success());
1541        assert!(NonZero.validate(&0.5f64, "field").is_success());
1542    }
1543
1544    #[test]
1545    fn test_non_zero_failure() {
1546        assert!(NonZero.validate(&0i32, "field").is_failure());
1547        assert!(NonZero.validate(&0u32, "field").is_failure());
1548        assert!(NonZero.validate(&0.0f64, "field").is_failure());
1549    }
1550
1551    // ========================================================================
1552    // Collection Validator Tests
1553    // ========================================================================
1554
1555    #[test]
1556    fn test_non_empty_collection_success() {
1557        let v = vec![1, 2, 3];
1558        let result = NonEmptyCollection.validate(&v, "items");
1559        assert!(result.is_success());
1560    }
1561
1562    #[test]
1563    fn test_non_empty_collection_failure() {
1564        let v: Vec<i32> = vec![];
1565        let result = NonEmptyCollection.validate(&v, "items");
1566        assert!(result.is_failure());
1567    }
1568
1569    #[test]
1570    fn test_min_items_success() {
1571        let v = vec![1, 2, 3];
1572        let result = MinItems(2).validate(&v, "items");
1573        assert!(result.is_success());
1574    }
1575
1576    #[test]
1577    fn test_min_items_failure() {
1578        let v = vec![1];
1579        let result = MinItems(3).validate(&v, "items");
1580        assert!(result.is_failure());
1581    }
1582
1583    #[test]
1584    fn test_max_items_success() {
1585        let v = vec![1, 2, 3];
1586        let result = MaxItems(5).validate(&v, "items");
1587        assert!(result.is_success());
1588    }
1589
1590    #[test]
1591    fn test_max_items_failure() {
1592        let v = vec![1, 2, 3, 4, 5];
1593        let result = MaxItems(3).validate(&v, "items");
1594        assert!(result.is_failure());
1595    }
1596
1597    #[test]
1598    fn test_each_success() {
1599        let v = vec![1, 2, 3];
1600        let result = Each(Positive).validate(&v, "items");
1601        assert!(result.is_success());
1602    }
1603
1604    #[test]
1605    fn test_each_failure_accumulates_errors() {
1606        let v = vec![1, -2, -3, 4];
1607        let result = Each(Positive).validate(&v, "items");
1608        assert!(result.is_failure());
1609
1610        if let Validation::Failure(errors) = result {
1611            // Should have 2 errors for -2 and -3
1612            assert_eq!(errors.len(), 2);
1613        }
1614    }
1615
1616    #[test]
1617    fn test_each_empty_collection() {
1618        let v: Vec<i32> = vec![];
1619        let result = Each(Positive).validate(&v, "items");
1620        assert!(result.is_success());
1621    }
1622
1623    // ========================================================================
1624    // Path Validator Tests
1625    // ========================================================================
1626
1627    #[test]
1628    fn test_extension_success() {
1629        let result = Extension::new("toml").validate(Path::new("config.toml"), "file");
1630        assert!(result.is_success());
1631    }
1632
1633    #[test]
1634    fn test_extension_failure_wrong() {
1635        let result = Extension::new("toml").validate(Path::new("config.json"), "file");
1636        assert!(result.is_failure());
1637    }
1638
1639    #[test]
1640    fn test_extension_failure_none() {
1641        let result = Extension::new("toml").validate(Path::new("config"), "file");
1642        assert!(result.is_failure());
1643    }
1644
1645    // ========================================================================
1646    // validate_field Tests
1647    // ========================================================================
1648
1649    #[test]
1650    fn test_validate_field_empty_validators() {
1651        let empty: &[&dyn Validator<str>] = &[];
1652        let result = validate_field("value", "field", empty);
1653        assert!(result.is_success());
1654    }
1655
1656    #[test]
1657    fn test_validate_field_single_validator() {
1658        let result = validate_field("hello", "field", &[&NonEmpty]);
1659        assert!(result.is_success());
1660    }
1661
1662    #[test]
1663    fn test_validate_field_multiple_validators_all_pass() {
1664        let result = validate_field("hello", "field", &[&NonEmpty, &MinLength(3)]);
1665        assert!(result.is_success());
1666    }
1667
1668    #[test]
1669    fn test_validate_field_accumulates_errors() {
1670        // Empty string fails both NonEmpty and MinLength
1671        let result = validate_field("", "field", &[&NonEmpty, &MinLength(3)]);
1672        assert!(result.is_failure());
1673
1674        if let Validation::Failure(errors) = result {
1675            assert_eq!(errors.len(), 2);
1676        }
1677    }
1678
1679    // ========================================================================
1680    // validate_nested Tests
1681    // ========================================================================
1682
1683    struct InnerConfig {
1684        value: i32,
1685    }
1686
1687    impl Validate for InnerConfig {
1688        fn validate(&self) -> ConfigValidation<()> {
1689            if self.value > 0 {
1690                Validation::Success(())
1691            } else {
1692                fail(ConfigError::ValidationError {
1693                    path: "value".to_string(),
1694                    source_location: None,
1695                    value: Some(self.value.to_string()),
1696                    message: "must be positive".to_string(),
1697                })
1698            }
1699        }
1700    }
1701
1702    #[test]
1703    fn test_validate_nested_success() {
1704        let inner = InnerConfig { value: 42 };
1705        let result = validate_nested(&inner, "config");
1706        assert!(result.is_success());
1707    }
1708
1709    #[test]
1710    fn test_validate_nested_failure() {
1711        let inner = InnerConfig { value: -1 };
1712        let result = validate_nested(&inner, "config");
1713        assert!(result.is_failure());
1714
1715        if let Validation::Failure(errors) = result {
1716            assert_eq!(errors.first().path(), Some("config.value"));
1717        }
1718    }
1719
1720    #[test]
1721    fn test_validate_optional_nested_none() {
1722        let opt: Option<InnerConfig> = None;
1723        let result = validate_optional_nested(&opt, "config");
1724        assert!(result.is_success());
1725    }
1726
1727    #[test]
1728    fn test_validate_optional_nested_some() {
1729        let opt = Some(InnerConfig { value: -1 });
1730        let result = validate_optional_nested(&opt, "config");
1731        assert!(result.is_failure());
1732    }
1733
1734    // ========================================================================
1735    // Custom Validator Tests
1736    // ========================================================================
1737
1738    #[test]
1739    fn test_custom_validator() {
1740        let even_validator = custom(|value: &i32, path: &str| {
1741            if value % 2 == 0 {
1742                Validation::Success(())
1743            } else {
1744                fail(ConfigError::ValidationError {
1745                    path: path.to_string(),
1746                    source_location: None,
1747                    value: Some(value.to_string()),
1748                    message: "value must be even".to_string(),
1749                })
1750            }
1751        });
1752
1753        assert!(even_validator.validate(&4, "num").is_success());
1754        assert!(even_validator.validate(&3, "num").is_failure());
1755    }
1756
1757    // ========================================================================
1758    // Conditional Validator Tests
1759    // ========================================================================
1760
1761    #[test]
1762    fn test_when_condition_true() {
1763        let validator = When::new(NonEmpty, || true);
1764        let result = validator.validate("", "field");
1765        assert!(result.is_failure());
1766    }
1767
1768    #[test]
1769    fn test_when_condition_false() {
1770        let validator = When::new(NonEmpty, || false);
1771        let result = validator.validate("", "field");
1772        assert!(result.is_success());
1773    }
1774
1775    // ========================================================================
1776    // Integration Tests
1777    // ========================================================================
1778
1779    struct DatabaseConfig {
1780        host: String,
1781        port: u16,
1782        pool_size: u32,
1783    }
1784
1785    impl Validate for DatabaseConfig {
1786        fn validate(&self) -> ConfigValidation<()> {
1787            let validations = vec![
1788                validate_field(&self.host, "host", &[&NonEmpty]),
1789                validate_field(&self.port, "port", &[&Range(1..=65535)]),
1790                validate_field(&self.pool_size, "pool_size", &[&Range(1..=100)]),
1791            ];
1792            Validation::all_vec(validations).map(|_| ())
1793        }
1794    }
1795
1796    #[test]
1797    fn test_database_config_valid() {
1798        let config = DatabaseConfig {
1799            host: "localhost".to_string(),
1800            port: 5432,
1801            pool_size: 10,
1802        };
1803        assert!(config.validate().is_success());
1804    }
1805
1806    #[test]
1807    fn test_database_config_accumulates_all_errors() {
1808        let config = DatabaseConfig {
1809            host: "".to_string(),
1810            port: 0,
1811            pool_size: 200,
1812        };
1813
1814        let result = config.validate();
1815        assert!(result.is_failure());
1816
1817        if let Validation::Failure(errors) = result {
1818            assert_eq!(errors.len(), 3);
1819        }
1820    }
1821
1822    // Test Vec validation with custom type
1823    #[test]
1824    fn test_vec_custom_validate() {
1825        let configs = vec![
1826            InnerConfig { value: 1 },
1827            InnerConfig { value: -1 },
1828            InnerConfig { value: -2 },
1829        ];
1830
1831        let result = configs.validate();
1832        assert!(result.is_failure());
1833
1834        // Should have accumulated 2 errors with indexed paths
1835        if let Validation::Failure(errors) = result {
1836            assert_eq!(errors.len(), 2);
1837            let paths: Vec<_> = errors.iter().filter_map(|e| e.path()).collect();
1838            assert!(paths.contains(&"[1].value"));
1839            assert!(paths.contains(&"[2].value"));
1840        }
1841    }
1842
1843    // ========================================================================
1844    // ValidationContext Tests
1845    // ========================================================================
1846
1847    #[test]
1848    fn test_validation_context_lookup() {
1849        let mut locations = SourceLocationMap::new();
1850        locations.insert(
1851            "host".to_string(),
1852            SourceLocation::new("config.toml").with_line(5),
1853        );
1854        locations.insert(
1855            "port".to_string(),
1856            SourceLocation::new("config.toml").with_line(6),
1857        );
1858
1859        let ctx = ValidationContext::new(locations);
1860
1861        let host_loc = ctx.location_for("host").unwrap();
1862        assert_eq!(host_loc.source, "config.toml");
1863        assert_eq!(host_loc.line, Some(5));
1864
1865        let port_loc = ctx.location_for("port").unwrap();
1866        assert_eq!(port_loc.line, Some(6));
1867
1868        // Non-existent path returns None
1869        assert!(ctx.location_for("missing").is_none());
1870    }
1871
1872    #[test]
1873    fn test_with_validation_context() {
1874        let mut locations = SourceLocationMap::new();
1875        locations.insert(
1876            "test_field".to_string(),
1877            SourceLocation::new("test.toml").with_line(10),
1878        );
1879
1880        let ctx = ValidationContext::new(locations);
1881
1882        // Before context is set, returns None
1883        assert!(current_source_location("test_field").is_none());
1884
1885        // Within context, returns location
1886        let result = with_validation_context(ctx, || {
1887            let loc = current_source_location("test_field");
1888            assert!(loc.is_some());
1889            let loc = loc.unwrap();
1890            assert_eq!(loc.source, "test.toml");
1891            assert_eq!(loc.line, Some(10));
1892            "success"
1893        });
1894
1895        assert_eq!(result, "success");
1896
1897        // After context is cleared, returns None again
1898        assert!(current_source_location("test_field").is_none());
1899    }
1900
1901    #[test]
1902    fn test_context_clears_on_completion() {
1903        let mut locations = SourceLocationMap::new();
1904        locations.insert("field".to_string(), SourceLocation::new("a.toml"));
1905
1906        let ctx = ValidationContext::new(locations);
1907        with_validation_context(ctx, || ());
1908
1909        // Context should be cleared
1910        assert!(current_source_location("field").is_none());
1911    }
1912
1913    #[test]
1914    fn test_path_prefix_for_nested_lookup() {
1915        let mut locations = SourceLocationMap::new();
1916        locations.insert(
1917            "server.host".to_string(),
1918            SourceLocation::new("config.toml").with_line(3),
1919        );
1920        locations.insert(
1921            "server.port".to_string(),
1922            SourceLocation::new("config.toml").with_line(4),
1923        );
1924        locations.insert(
1925            "database.host".to_string(),
1926            SourceLocation::new("config.toml").with_line(7),
1927        );
1928
1929        let ctx = ValidationContext::new(locations);
1930
1931        with_validation_context(ctx, || {
1932            // Without prefix, "host" doesn't find anything
1933            assert!(current_source_location("host").is_none());
1934
1935            // With "server" prefix, "host" finds "server.host"
1936            push_path_prefix("server");
1937            let loc = current_source_location("host");
1938            assert!(loc.is_some());
1939            let loc = loc.unwrap();
1940            assert_eq!(loc.source, "config.toml");
1941            assert_eq!(loc.line, Some(3));
1942
1943            // port also works with prefix
1944            let port_loc = current_source_location("port").unwrap();
1945            assert_eq!(port_loc.line, Some(4));
1946
1947            pop_path_prefix();
1948
1949            // After popping, "host" doesn't find anything again
1950            assert!(current_source_location("host").is_none());
1951
1952            // With "database" prefix
1953            push_path_prefix("database");
1954            let db_loc = current_source_location("host").unwrap();
1955            assert_eq!(db_loc.line, Some(7));
1956            pop_path_prefix();
1957        });
1958    }
1959
1960    #[test]
1961    fn test_nested_path_prefix_stacking() {
1962        let mut locations = SourceLocationMap::new();
1963        locations.insert(
1964            "outer.inner.field".to_string(),
1965            SourceLocation::new("config.toml").with_line(10),
1966        );
1967
1968        let ctx = ValidationContext::new(locations);
1969
1970        with_validation_context(ctx, || {
1971            // No prefix - not found
1972            assert!(current_source_location("field").is_none());
1973
1974            // Single prefix - still not found
1975            push_path_prefix("outer");
1976            assert!(current_source_location("field").is_none());
1977
1978            // Nested prefix - found
1979            push_path_prefix("inner");
1980            let loc = current_source_location("field");
1981            assert!(loc.is_some());
1982            assert_eq!(loc.unwrap().line, Some(10));
1983
1984            // Pop inner prefix
1985            pop_path_prefix();
1986            assert!(current_source_location("field").is_none());
1987
1988            // Pop outer prefix
1989            pop_path_prefix();
1990        });
1991    }
1992
1993    // ========================================================================
1994    // Predicate Bridge Tests
1995    // ========================================================================
1996
1997    use stillwater::predicate::prelude::*;
1998
1999    #[test]
2000    fn test_from_predicate_success() {
2001        let validator = from_predicate(not_empty());
2002        let result = validator.validate("hello", "field");
2003        assert!(result.is_success());
2004    }
2005
2006    #[test]
2007    fn test_from_predicate_failure() {
2008        let validator = from_predicate(not_empty());
2009        let result = validator.validate("", "field");
2010        assert!(result.is_failure());
2011
2012        if let Validation::Failure(errors) = result {
2013            assert_eq!(errors.len(), 1);
2014            assert_eq!(errors.first().path(), Some("field"));
2015        }
2016    }
2017
2018    #[test]
2019    fn test_validate_with_predicate_success() {
2020        let result = validate_with_predicate(
2021            &42,
2022            "port",
2023            between(1, 65535),
2024            "port must be between 1 and 65535",
2025        );
2026        assert!(result.is_success());
2027    }
2028
2029    #[test]
2030    fn test_validate_with_predicate_failure() {
2031        let result = validate_with_predicate(
2032            &0,
2033            "port",
2034            between(1, 65535),
2035            "port must be between 1 and 65535",
2036        );
2037        assert!(result.is_failure());
2038
2039        if let Validation::Failure(errors) = result {
2040            assert_eq!(errors.len(), 1);
2041            assert_eq!(errors.first().path(), Some("port"));
2042            // Check that custom message is used
2043            if let ConfigError::ValidationError { message, .. } = errors.first() {
2044                assert_eq!(message, "port must be between 1 and 65535");
2045            } else {
2046                panic!("Expected ValidationError");
2047            }
2048        }
2049    }
2050
2051    #[test]
2052    fn test_validate_with_predicate_custom_message() {
2053        let result = validate_with_predicate("", "username", not_empty(), "username is required");
2054
2055        assert!(result.is_failure());
2056
2057        if let Validation::Failure(errors) = result {
2058            if let ConfigError::ValidationError { message, .. } = errors.first() {
2059                assert_eq!(message, "username is required");
2060            } else {
2061                panic!("Expected ValidationError");
2062            }
2063        }
2064    }
2065
2066    #[test]
2067    fn test_predicate_preserves_source_location() {
2068        let mut locations = SourceLocationMap::new();
2069        locations.insert(
2070            "host".to_string(),
2071            SourceLocation::new("config.toml").with_line(5),
2072        );
2073
2074        let ctx = ValidationContext::new(locations);
2075
2076        with_validation_context(ctx, || {
2077            let result = validate_with_predicate("", "host", not_empty(), "host cannot be empty");
2078
2079            assert!(result.is_failure());
2080
2081            if let Validation::Failure(errors) = result {
2082                let err = errors.first();
2083                assert_eq!(
2084                    err.source_location().map(|l| l.source.as_str()),
2085                    Some("config.toml")
2086                );
2087                assert_eq!(err.source_location().and_then(|l| l.line), Some(5));
2088            }
2089        });
2090    }
2091
2092    #[test]
2093    fn test_predicate_with_nested_validation() {
2094        let mut locations = SourceLocationMap::new();
2095        locations.insert(
2096            "database.host".to_string(),
2097            SourceLocation::new("config.toml").with_line(10),
2098        );
2099
2100        let ctx = ValidationContext::new(locations);
2101
2102        with_validation_context(ctx, || {
2103            push_path_prefix("database");
2104            let result = validate_with_predicate("", "host", not_empty(), "host required");
2105            pop_path_prefix();
2106
2107            assert!(result.is_failure());
2108
2109            if let Validation::Failure(errors) = result {
2110                let err = errors.first();
2111                assert_eq!(err.source_location().and_then(|l| l.line), Some(10));
2112            }
2113        });
2114    }
2115
2116    #[test]
2117    fn test_complex_string_predicate() {
2118        // Valid username: non-empty and at least 3 chars
2119        assert!(validate_with_predicate(
2120            "user123",
2121            "username",
2122            len_min(3),
2123            "must be at least 3 chars"
2124        )
2125        .is_success());
2126
2127        // Too short
2128        assert!(
2129            validate_with_predicate("ab", "username", len_min(3), "must be at least 3 chars")
2130                .is_failure()
2131        );
2132
2133        // Test length range
2134        assert!(validate_with_predicate(
2135            "hello",
2136            "field",
2137            len_between(3, 10),
2138            "length must be 3-10 chars"
2139        )
2140        .is_success());
2141        assert!(validate_with_predicate(
2142            "hi",
2143            "field",
2144            len_between(3, 10),
2145            "length must be 3-10 chars"
2146        )
2147        .is_failure());
2148    }
2149
2150    #[test]
2151    fn test_numeric_range_predicate() {
2152        let pred = gt(0).and(le(65535));
2153        let validator = from_predicate(pred);
2154
2155        // Valid ports
2156        assert!(validator.validate(&1, "port").is_success());
2157        assert!(validator.validate(&8080, "port").is_success());
2158        assert!(validator.validate(&65535, "port").is_success());
2159
2160        // Invalid ports
2161        assert!(validator.validate(&0, "port").is_failure());
2162        assert!(validator.validate(&65536, "port").is_failure());
2163        assert!(validator.validate(&-1, "port").is_failure());
2164    }
2165
2166    #[test]
2167    fn test_string_length_predicates() {
2168        // Length minimum
2169        assert!(validate_with_predicate("hello", "field", len_min(3), "min 3 chars").is_success());
2170        assert!(validate_with_predicate("hi", "field", len_min(3), "min 3 chars").is_failure());
2171
2172        // Length maximum
2173        assert!(
2174            validate_with_predicate("hello", "field", len_max(10), "max 10 chars").is_success()
2175        );
2176        assert!(
2177            validate_with_predicate("verylongstring", "field", len_max(10), "max 10 chars")
2178                .is_failure()
2179        );
2180
2181        // Exact length
2182        assert!(
2183            validate_with_predicate("hello", "field", len_eq(5), "exactly 5 chars").is_success()
2184        );
2185        assert!(validate_with_predicate("hi", "field", len_eq(5), "exactly 5 chars").is_failure());
2186    }
2187
2188    #[test]
2189    fn test_predicate_and_validator_together() {
2190        // Mix predicate-based and traditional validators
2191        let pred_validator = from_predicate(len_min(3));
2192        let trad_validator = NonEmpty;
2193
2194        let result = validate_field("hello", "field", &[&trad_validator, &pred_validator]);
2195        assert!(result.is_success());
2196
2197        // Fails traditional validator
2198        let result = validate_field("", "field", &[&trad_validator, &pred_validator]);
2199        assert!(result.is_failure());
2200
2201        // Fails predicate validator
2202        let result = validate_field("hi", "field", &[&trad_validator, &pred_validator]);
2203        assert!(result.is_failure());
2204    }
2205
2206    #[test]
2207    fn test_validate_field_with_predicate() {
2208        let validator = from_predicate(between(1, 100));
2209
2210        // Valid value
2211        let result = validate_field(&50, "value", &[&validator]);
2212        assert!(result.is_success());
2213
2214        // Invalid value
2215        let result = validate_field(&150, "value", &[&validator]);
2216        assert!(result.is_failure());
2217    }
2218}