Skip to main content

ggen_core/validation/
input_compiler.rs

1//! Validation rule compiler for declarative rule definitions
2//!
3//! This module provides a declarative API for defining validation rules
4//! and compiling them into efficient validators.
5//!
6//! ## Example
7//!
8//! ```rust
9//! use crate::validation::input_compiler::{RuleCompiler, RuleDefinition};
10//!
11//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
12//! let compiler = RuleCompiler::new();
13//!
14//! // Define validation rules declaratively
15//! let rules = vec![
16//!     RuleDefinition::length("username", 3, 32),
17//!     RuleDefinition::pattern("username", r"^[a-zA-Z0-9_-]+$"),
18//!     RuleDefinition::length("email", 5, 254),
19//!     RuleDefinition::format("email", "email"),
20//! ];
21//!
22//! // Compile into efficient validator
23//! let validator = compiler.compile(&rules)?;
24//!
25//! // Validate inputs
26//! validator.validate_field("username", "alice")?;
27//! validator.validate_field("email", "alice@example.com")?;
28//! # Ok(())
29//! # }
30//! ```
31
32use super::input::{CharsetRule, FormatRule, InputValidationError, StringValidator};
33use crate::utils::error::Result;
34use std::collections::HashMap;
35
36/// Rule definition for declarative validation
37#[derive(Debug, Clone)]
38pub enum RuleDefinition {
39    /// Length constraint (field, min, max)
40    Length {
41        field: String,
42        min: usize,
43        max: usize,
44    },
45
46    /// Pattern constraint (field, regex pattern)
47    Pattern { field: String, pattern: String },
48
49    /// Charset constraint (field, charset type)
50    Charset { field: String, charset: String },
51
52    /// Format constraint (field, format type)
53    Format { field: String, format: String },
54
55    /// Whitelist constraint (field, allowed values)
56    Whitelist { field: String, allowed: Vec<String> },
57
58    /// Blacklist constraint (field, forbidden values)
59    Blacklist {
60        field: String,
61        forbidden: Vec<String>,
62    },
63
64    /// Composite AND (left, right)
65    And {
66        left: Box<RuleDefinition>,
67        right: Box<RuleDefinition>,
68    },
69
70    /// Composite OR (left, right)
71    Or {
72        left: Box<RuleDefinition>,
73        right: Box<RuleDefinition>,
74    },
75
76    /// Composite NOT (inner)
77    Not { inner: Box<RuleDefinition> },
78}
79
80impl RuleDefinition {
81    /// Create length constraint
82    pub fn length(field: &str, min: usize, max: usize) -> Self {
83        Self::Length {
84            field: field.to_string(),
85            min,
86            max,
87        }
88    }
89
90    /// Create pattern constraint
91    pub fn pattern(field: &str, pattern: &str) -> Self {
92        Self::Pattern {
93            field: field.to_string(),
94            pattern: pattern.to_string(),
95        }
96    }
97
98    /// Create charset constraint
99    pub fn charset(field: &str, charset: &str) -> Self {
100        Self::Charset {
101            field: field.to_string(),
102            charset: charset.to_string(),
103        }
104    }
105
106    /// Create format constraint
107    pub fn format(field: &str, format: &str) -> Self {
108        Self::Format {
109            field: field.to_string(),
110            format: format.to_string(),
111        }
112    }
113
114    /// Create whitelist constraint
115    pub fn whitelist(field: &str, allowed: Vec<String>) -> Self {
116        Self::Whitelist {
117            field: field.to_string(),
118            allowed,
119        }
120    }
121
122    /// Create blacklist constraint
123    pub fn blacklist(field: &str, forbidden: Vec<String>) -> Self {
124        Self::Blacklist {
125            field: field.to_string(),
126            forbidden,
127        }
128    }
129
130    /// Combine with AND
131    pub fn and(self, other: RuleDefinition) -> Self {
132        Self::And {
133            left: Box::new(self),
134            right: Box::new(other),
135        }
136    }
137
138    /// Combine with OR
139    pub fn or(self, other: RuleDefinition) -> Self {
140        Self::Or {
141            left: Box::new(self),
142            right: Box::new(other),
143        }
144    }
145
146    /// Negate with NOT
147    pub fn negate(self) -> Self {
148        Self::Not {
149            inner: Box::new(self),
150        }
151    }
152
153    /// Get field name for this rule
154    pub fn field_name(&self) -> Option<&str> {
155        match self {
156            Self::Length { field, .. }
157            | Self::Pattern { field, .. }
158            | Self::Charset { field, .. }
159            | Self::Format { field, .. }
160            | Self::Whitelist { field, .. }
161            | Self::Blacklist { field, .. } => Some(field),
162            Self::And { left, .. } => left.field_name(),
163            Self::Or { left, .. } => left.field_name(),
164            Self::Not { inner } => inner.field_name(),
165        }
166    }
167}
168
169/// Compiled validator from rule definitions
170pub struct CompiledValidator {
171    validators: HashMap<String, StringValidator>,
172}
173
174impl CompiledValidator {
175    /// Create new compiled validator
176    pub fn new(validators: HashMap<String, StringValidator>) -> Self {
177        Self { validators }
178    }
179
180    /// Validate a field value
181    pub fn validate_field(&self, field: &str, value: &str) -> Result<String> {
182        if let Some(validator) = self.validators.get(field) {
183            validator.validate(value).map_err(|e| {
184                InputValidationError::FormatViolation {
185                    field: field.to_string(),
186                    reason: format!("Validation failed: {}", e),
187                }
188                .into()
189            })
190        } else {
191            Err(InputValidationError::EmptyInput {
192                field: format!("No validator defined for field: {}", field),
193            }
194            .into())
195        }
196    }
197
198    /// Validate multiple fields
199    pub fn validate_fields(
200        &self, fields: &HashMap<String, String>,
201    ) -> Result<HashMap<String, String>> {
202        let mut validated = HashMap::new();
203
204        for (field, value) in fields {
205            let validated_value = self.validate_field(field, value)?;
206            validated.insert(field.clone(), validated_value);
207        }
208
209        Ok(validated)
210    }
211}
212
213/// Rule compiler for building validators from definitions
214pub struct RuleCompiler {
215    // Future: caching, optimization
216}
217
218impl RuleCompiler {
219    pub fn new() -> Self {
220        Self {}
221    }
222
223    /// Compile rule definitions into efficient validator
224    pub fn compile(&self, rules: &[RuleDefinition]) -> Result<CompiledValidator> {
225        let mut validators: HashMap<String, StringValidator> = HashMap::new();
226
227        // Group rules by field
228        let mut rules_by_field: HashMap<String, Vec<&RuleDefinition>> = HashMap::new();
229        for rule in rules {
230            if let Some(field) = rule.field_name() {
231                rules_by_field
232                    .entry(field.to_string())
233                    .or_default()
234                    .push(rule);
235            }
236        }
237
238        // Build validator for each field
239        for (field, field_rules) in rules_by_field {
240            let mut validator = StringValidator::new();
241
242            for rule in field_rules {
243                validator = self.apply_rule(validator, rule)?;
244            }
245
246            validators.insert(field, validator);
247        }
248
249        Ok(CompiledValidator::new(validators))
250    }
251
252    fn apply_rule(
253        &self, mut validator: StringValidator, rule: &RuleDefinition,
254    ) -> Result<StringValidator> {
255        match rule {
256            RuleDefinition::Length { min, max, .. } => {
257                validator = validator.with_length(*min, *max);
258            }
259            RuleDefinition::Pattern { pattern, .. } => {
260                validator = validator.with_pattern(pattern);
261            }
262            RuleDefinition::Charset { charset, .. } => {
263                let charset_rule = match charset.as_str() {
264                    "alphanumeric" => CharsetRule::alphanumeric(),
265                    "identifier" => CharsetRule::identifier(),
266                    "ascii_printable" => CharsetRule::ascii_printable(),
267                    _ => {
268                        return Err(InputValidationError::FormatViolation {
269                            field: "charset".to_string(),
270                            reason: format!("Unknown charset type: {}", charset),
271                        }
272                        .into())
273                    }
274                };
275                validator = validator.with_charset(charset_rule);
276            }
277            RuleDefinition::Format { format, .. } => {
278                let format_rule = match format.as_str() {
279                    "email" => FormatRule::Email,
280                    "uuid" => FormatRule::Uuid,
281                    "semver" => FormatRule::Semver,
282                    "ip" => FormatRule::IpAddress,
283                    "hostname" => FormatRule::Hostname,
284                    _ => {
285                        return Err(InputValidationError::FormatViolation {
286                            field: "format".to_string(),
287                            reason: format!("Unknown format type: {}", format),
288                        }
289                        .into())
290                    }
291                };
292                validator = validator.with_format(format_rule);
293            }
294            RuleDefinition::Whitelist { allowed, .. } => {
295                validator = validator.with_whitelist(allowed.clone());
296            }
297            RuleDefinition::Blacklist { forbidden, .. } => {
298                validator = validator.with_blacklist(forbidden.clone());
299            }
300            RuleDefinition::And { .. } | RuleDefinition::Or { .. } | RuleDefinition::Not { .. } => {
301                // Composite rules are not yet supported in builder API
302                // This is a limitation of the current implementation
303                return Err(InputValidationError::CompositeViolation {
304                    reason: "Composite rules (AND/OR/NOT) not yet supported in compiler"
305                        .to_string(),
306                }
307                .into());
308            }
309        }
310
311        Ok(validator)
312    }
313}
314
315impl Default for RuleCompiler {
316    fn default() -> Self {
317        Self::new()
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn test_rule_definition_length() {
327        // Arrange & Act
328        let rule = RuleDefinition::length("username", 3, 32);
329
330        // Assert
331        assert_eq!(rule.field_name(), Some("username"));
332    }
333
334    #[test]
335    fn test_rule_definition_pattern() {
336        // Arrange & Act
337        let rule = RuleDefinition::pattern("email", r"^.+@.+$");
338
339        // Assert
340        assert_eq!(rule.field_name(), Some("email"));
341    }
342
343    #[test]
344    fn test_rule_compiler_single_rule() {
345        // Arrange
346        let compiler = RuleCompiler::new();
347        let rules = vec![RuleDefinition::length("username", 3, 32)];
348
349        // Act
350        let validator = compiler.compile(&rules).expect("compilation succeeds");
351        let result = validator.validate_field("username", "alice");
352
353        // Assert
354        assert!(result.is_ok());
355    }
356
357    #[test]
358    fn test_rule_compiler_multiple_rules_same_field() {
359        // Arrange
360        let compiler = RuleCompiler::new();
361        let rules = vec![
362            RuleDefinition::length("username", 3, 32),
363            RuleDefinition::charset("username", "identifier"),
364        ];
365
366        // Act
367        let validator = compiler.compile(&rules).expect("compilation succeeds");
368
369        // Assert - valid username
370        assert!(validator.validate_field("username", "alice_123").is_ok());
371
372        // Assert - invalid (too short)
373        assert!(validator.validate_field("username", "ab").is_err());
374
375        // Assert - invalid (wrong charset)
376        assert!(validator.validate_field("username", "alice@123").is_err());
377    }
378
379    #[test]
380    fn test_rule_compiler_multiple_fields() {
381        // Arrange
382        let compiler = RuleCompiler::new();
383        let rules = vec![
384            RuleDefinition::length("username", 3, 32),
385            RuleDefinition::length("email", 5, 254),
386            RuleDefinition::format("email", "email"),
387        ];
388
389        // Act
390        let validator = compiler.compile(&rules).expect("compilation succeeds");
391
392        // Assert - validate both fields
393        assert!(validator.validate_field("username", "alice").is_ok());
394        assert!(validator
395            .validate_field("email", "alice@example.com")
396            .is_ok());
397    }
398
399    #[test]
400    fn test_rule_compiler_format_email() {
401        // Arrange
402        let compiler = RuleCompiler::new();
403        let rules = vec![RuleDefinition::format("email", "email")];
404
405        // Act
406        let validator = compiler.compile(&rules).expect("compilation succeeds");
407
408        // Assert
409        assert!(validator
410            .validate_field("email", "alice@example.com")
411            .is_ok());
412        assert!(validator.validate_field("email", "not-an-email").is_err());
413    }
414
415    #[test]
416    fn test_rule_compiler_whitelist() {
417        // Arrange
418        let compiler = RuleCompiler::new();
419        let rules = vec![RuleDefinition::whitelist(
420            "role",
421            vec!["admin".to_string(), "user".to_string()],
422        )];
423
424        // Act
425        let validator = compiler.compile(&rules).expect("compilation succeeds");
426
427        // Assert
428        assert!(validator.validate_field("role", "admin").is_ok());
429        assert!(validator.validate_field("role", "user").is_ok());
430        assert!(validator.validate_field("role", "guest").is_err());
431    }
432
433    #[test]
434    fn test_rule_compiler_blacklist() {
435        // Arrange
436        let compiler = RuleCompiler::new();
437        let rules = vec![RuleDefinition::blacklist(
438            "username",
439            vec!["admin".to_string(), "root".to_string()],
440        )];
441
442        // Act
443        let validator = compiler.compile(&rules).expect("compilation succeeds");
444
445        // Assert
446        assert!(validator.validate_field("username", "alice").is_ok());
447        assert!(validator.validate_field("username", "admin").is_err());
448        assert!(validator.validate_field("username", "root").is_err());
449    }
450
451    #[test]
452    fn test_compiled_validator_validate_fields() {
453        // Arrange
454        let compiler = RuleCompiler::new();
455        let rules = vec![
456            RuleDefinition::length("username", 3, 32),
457            RuleDefinition::format("email", "email"),
458        ];
459
460        let validator = compiler.compile(&rules).expect("compilation succeeds");
461
462        let mut fields = HashMap::new();
463        fields.insert("username".to_string(), "alice".to_string());
464        fields.insert("email".to_string(), "alice@example.com".to_string());
465
466        // Act
467        let result = validator.validate_fields(&fields);
468
469        // Assert
470        assert!(result.is_ok());
471        let validated = result.unwrap();
472        assert_eq!(validated.get("username"), Some(&"alice".to_string()));
473        assert_eq!(
474            validated.get("email"),
475            Some(&"alice@example.com".to_string())
476        );
477    }
478
479    #[test]
480    fn test_compiled_validator_unknown_field() {
481        // Arrange
482        let compiler = RuleCompiler::new();
483        let rules = vec![RuleDefinition::length("username", 3, 32)];
484
485        let validator = compiler.compile(&rules).expect("compilation succeeds");
486
487        // Act
488        let result = validator.validate_field("unknown", "value");
489
490        // Assert
491        assert!(result.is_err());
492    }
493
494    #[test]
495    fn test_rule_definition_and() {
496        // Arrange & Act
497        let rule = RuleDefinition::length("field", 5, 10)
498            .and(RuleDefinition::charset("field", "alphanumeric"));
499
500        // Assert
501        assert_eq!(rule.field_name(), Some("field"));
502    }
503
504    #[test]
505    fn test_rule_definition_or() {
506        // Arrange & Act
507        let rule =
508            RuleDefinition::length("field", 5, 10).or(RuleDefinition::length("field", 20, 30));
509
510        // Assert
511        assert_eq!(rule.field_name(), Some("field"));
512    }
513
514    #[test]
515    fn test_rule_definition_negate() {
516        // Arrange & Act
517        let rule = RuleDefinition::length("field", 5, 10).negate();
518
519        // Assert
520        assert_eq!(rule.field_name(), Some("field"));
521    }
522}