babbel_yaml 0.1.1

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Built-in Validators for YAML Validation
//!
//! This module provides reusable built-in validators for common validation patterns in YAML documents.
//! It includes type checking, range validation, pattern matching, and support for custom validation logic.
//!
//! # Features
//! - Type checking validators
//! - Range and length validation
//! - Pattern matching (regex)
//! - Support for custom validation logic
//!
//! # Usage
//! Use these validators to enforce schema rules and constraints on YAML data.

use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use regex::Regex;

use crate::nodes::node::{Node, Numeric};
use crate::validation::error::ValidationError;
use crate::validation::messages;
use crate::validation::schema::SchemaType;

/// Result of a validation operation
pub type ValidationResult = Result<(), ValidationError>;

/// Trait for validators that can check nodes against rules
pub trait Validator {
    /// Validate a node and return Ok(()) or an error message
    fn validate(&self, node: &Node) -> ValidationResult;

    /// Get a description of what this validator checks
    fn description(&self) -> String;
}

/// Validates node type matches expected type
#[derive(Debug, Clone)]
pub struct TypeValidator {
    expected_type: SchemaType,
}

impl TypeValidator {
    pub fn new(expected_type: SchemaType) -> Self {
        Self { expected_type }
    }
}

impl Validator for TypeValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        let matches = match (&self.expected_type, node) {
            (SchemaType::String, Node::Str(_, _, _)) => true,
            (SchemaType::Number, Node::Number(_)) => true,
            (SchemaType::Integer, Node::Number(Numeric::Integer(_))) => true,
            (SchemaType::Integer, Node::Number(Numeric::Int32(_))) => true,
            (SchemaType::Integer, Node::Number(Numeric::Int16(_))) => true,
            (SchemaType::Integer, Node::Number(Numeric::Int8(_))) => true,
            (SchemaType::Float, Node::Number(Numeric::Float(_))) => true,
            (SchemaType::Boolean, Node::Boolean(_)) => true,
            (SchemaType::Null, Node::None) => true,
            (SchemaType::Array, Node::Array(_)) => true,
            (SchemaType::Array, Node::Set(_)) => true,
            (SchemaType::Object, Node::Mapping(_)) => true,
            (SchemaType::Any, _) => true,
            _ => false,
        };
        if matches {
            Ok(())
        } else {
            Err(
                crate::validation::engine::ValidationContextCore::fail_type_mismatch(
                    &self.expected_type,
                    node,
                ),
            )
        }
    }

    fn description(&self) -> String {
        messages::type_must_be(&self.expected_type)
    }
}

/// Validates numeric values are within a range
#[derive(Debug, Clone)]
pub struct RangeValidator {
    min: Option<f64>,
    max: Option<f64>,
}

impl RangeValidator {
    pub fn new(min: Option<f64>, max: Option<f64>) -> Self {
        Self { min, max }
    }
}

impl Validator for RangeValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        let value = match node {
            Node::Number(Numeric::Integer(i)) => *i as f64,
            Node::Number(Numeric::Float(f)) => *f,
            Node::Number(Numeric::UInteger(u)) => *u as f64,
            Node::Number(Numeric::Int32(i)) => *i as f64,
            Node::Number(Numeric::UInt32(u)) => *u as f64,
            Node::Number(Numeric::Int16(i)) => *i as f64,
            Node::Number(Numeric::UInt16(u)) => *u as f64,
            Node::Number(Numeric::Int8(i)) => *i as f64,
            Node::Number(Numeric::Byte(b)) => *b as f64,
            _ => {
                return Err(ValidationError::InvalidNodeType {
                    validator: "RangeValidator".to_string(),
                    found: node_type_name(node).to_string(),
                });
            }
        };

        if let Some(min) = self.min {
            if value < min {
                return Err(
                    crate::validation::engine::ValidationContextCore::fail_range(
                        value, self.min, self.max,
                    ),
                );
            }
        }

        if let Some(max) = self.max {
            if value > max {
                return Err(
                    crate::validation::engine::ValidationContextCore::fail_range(
                        value, self.min, self.max,
                    ),
                );
            }
        }

        Ok(())
    }

    fn description(&self) -> String {
        match (self.min, self.max) {
            (Some(min), Some(max)) => messages::value_must_be_between(min, max),
            (Some(min), None) => messages::value_must_be_at_least(min),
            (None, Some(max)) => messages::value_must_be_at_most(max),
            (None, None) => messages::no_range_restriction(),
        }
    }
}

/// Validates string/array length
#[derive(Debug, Clone)]
pub struct LengthValidator {
    min: Option<usize>,
    max: Option<usize>,
}

impl LengthValidator {
    pub fn new(min: Option<usize>, max: Option<usize>) -> Self {
        Self { min, max }
    }
}

impl Validator for LengthValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        let length = match node {
            n if n.as_str().is_some() => n.as_str().unwrap().len(),
            Node::Array(arr) => arr.len(),
            Node::Set(set) => set.len(),
            _ => {
                return Err(ValidationError::InvalidNodeType {
                    validator: "LengthValidator".to_string(),
                    found: node_type_name(node).to_string(),
                });
            }
        };

        if let Some(min) = self.min {
            if length < min {
                return Err(ValidationError::LengthError {
                    length,
                    min: self.min,
                    max: self.max,
                });
            }
        }

        if let Some(max) = self.max {
            if length > max {
                return Err(ValidationError::LengthError {
                    length,
                    min: self.min,
                    max: self.max,
                });
            }
        }

        Ok(())
    }

    fn description(&self) -> String {
        match (self.min, self.max) {
            (Some(min), Some(max)) => messages::length_must_be_between(min, max),
            (Some(min), None) => messages::length_must_be_at_least(min),
            (None, Some(max)) => messages::length_must_be_at_most(max),
            (None, None) => messages::no_length_restriction(),
        }
    }
}

/// Validates string matches a pattern

#[derive(Debug, Clone)]
pub struct PatternValidator {
    regex: Regex,
    pattern: String,
}

impl PatternValidator {
    pub fn new(pattern: impl Into<String>) -> Self {
        let pattern_str = pattern.into();
        let regex = Regex::new(&pattern_str).expect("Invalid regex pattern");
        Self {
            regex,
            pattern: pattern_str,
        }
    }

    /// Check if string matches regex pattern
    fn matches(&self, s: &str) -> bool {
        self.regex.is_match(s)
    }
}

impl Validator for PatternValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        if let Some(s) = node.as_str() {
            if self.matches(s) {
                Ok(())
            } else {
                Err(ValidationError::PatternMismatch {
                    pattern: self.pattern.clone(),
                    value: s.to_string(),
                })
            }
        } else {
            Err(ValidationError::InvalidNodeType {
                validator: "PatternValidator".to_string(),
                found: node_type_name(node).to_string(),
            })
        }
    }

    fn description(&self) -> String {
        format!("Must match regex pattern: {}", self.pattern)
    }
}

/// Validates value is one of allowed enum values

#[derive(Debug, Clone)]
pub struct EnumValidator {
    allowed: Vec<String>,
}

impl EnumValidator {
    pub fn new(allowed: Vec<String>) -> Self {
        Self { allowed }
    }

    /// Extracts a scalar value from a node as a string for comparison
    fn node_scalar_value(node: &Node) -> Option<String> {
        match node {
            Node::Str(s, _, _) => Some(s.clone()),
            Node::Number(n) => Some(match n {
                Numeric::Integer(i) => i.to_string(),
                Numeric::Float(f) => f.to_string(),
                Numeric::UInteger(u) => u.to_string(),
                Numeric::Byte(b) => b.to_string(),
                Numeric::Int32(i) => i.to_string(),
                Numeric::UInt32(u) => u.to_string(),
                Numeric::Int16(i) => i.to_string(),
                Numeric::UInt16(u) => u.to_string(),
                Numeric::Int8(i) => i.to_string(),
                Numeric::UInt8(u) => u.to_string(),
            }),
            Node::Boolean(b) => Some(b.to_string()),
            Node::None => Some("null".to_string()),
            _ => None,
        }
    }
}

impl Validator for EnumValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        match Self::node_scalar_value(node) {
            Some(value) => {
                if self.allowed.contains(&value) {
                    Ok(())
                } else {
                    Err(ValidationError::EnumMismatch {
                        allowed: self.allowed.clone(),
                        value,
                    })
                }
            }
            None => Err(ValidationError::InvalidNodeType {
                validator: "EnumValidator".to_string(),
                found: node_type_name(node).to_string(),
            }),
        }
    }

    fn description(&self) -> String {
        messages::must_be_one_of(&self.allowed)
    }
}

/// Validates a required field exists
#[derive(Debug, Clone)]
pub struct RequiredValidator {
    field_name: String,
}

impl RequiredValidator {
    pub fn new(field_name: impl Into<String>) -> Self {
        Self {
            field_name: field_name.into(),
        }
    }
}

impl Validator for RequiredValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        match node {
            Node::Mapping(pairs) => {
                let found = pairs.iter().any(|(k, _)| match k {
                    Node::Str(s, _, _) => s == &self.field_name,
                    Node::Number(n) => {
                        let key_str = match n {
                            Numeric::Integer(i) => i.to_string(),
                            Numeric::Float(f) => f.to_string(),
                            Numeric::UInteger(u) => u.to_string(),
                            Numeric::Byte(b) => b.to_string(),
                            Numeric::Int32(i) => i.to_string(),
                            Numeric::UInt32(u) => u.to_string(),
                            Numeric::Int16(i) => i.to_string(),
                            Numeric::UInt16(u) => u.to_string(),
                            Numeric::Int8(i) => i.to_string(),
                            Numeric::UInt8(u) => u.to_string(),
                        };
                        key_str == self.field_name
                    }
                    Node::Boolean(b) => b.to_string() == self.field_name,
                    Node::None => self.field_name == "null",
                    _ => false,
                });

                if found {
                    Ok(())
                } else {
                    Err(
                        crate::validation::engine::ValidationContextCore::fail_required(
                            &self.field_name,
                        ),
                    )
                }
            }
            _ => Err(ValidationError::InvalidNodeType {
                validator: "RequiredValidator".to_string(),
                found: node_type_name(node).to_string(),
            }),
        }
    }

    fn description(&self) -> String {
        format!("Field '{}' is required", self.field_name)
    }
}

/// Custom validator using a closure
pub struct CustomValidator {
    validate_fn: Box<dyn Fn(&Node) -> ValidationResult>,
    description: String,
}

impl CustomValidator {
    pub fn new<F>(description: impl Into<String>, validate_fn: F) -> Self
    where
        F: Fn(&Node) -> ValidationResult + 'static,
    {
        Self {
            validate_fn: Box::new(validate_fn),
            description: description.into(),
        }
    }
}

impl Validator for CustomValidator {
    fn validate(&self, node: &Node) -> ValidationResult {
        (self.validate_fn)(node)
    }

    fn description(&self) -> String {
        self.description.clone()
    }
}

/// Get human-readable name for node type
pub fn node_type_name(node: &Node) -> &'static str {
    match node {
        Node::Boolean(_) => "Boolean",
        Node::Number(_) => "Number",
        Node::Str(_, _, _) => "String",
        Node::Array(_) => "Array",
        Node::Set(_) => "Set",
        Node::Mapping(_) => "Mapping",
        Node::Comment(_) => "Comment",
        Node::Document(_) => "Document",
        Node::Anchored(_, _) => "Anchored",
        Node::Tagged(_, _) => "Tagged",
        Node::Alias(_) => "Alias",
        Node::Documents(_) => "Documents",
        Node::None => "Null",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_type_validator() {
        let validator = TypeValidator::new(SchemaType::String);

        assert!(validator.validate(&Node::from("hello")).is_ok());
        assert!(validator.validate(&Node::from(42)).is_err());
    }

    #[test]
    fn test_range_validator() {
        let validator = RangeValidator::new(Some(0.0), Some(100.0));

        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(50)))
                .is_ok()
        );
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(150)))
                .is_err()
        );
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(-10)))
                .is_err()
        );
    }

    #[test]
    fn test_length_validator() {
        let validator = LengthValidator::new(Some(3), Some(10));

        assert!(validator.validate(&Node::from("hello")).is_ok());
        assert!(validator.validate(&Node::from("hi")).is_err());
        assert!(validator.validate(&Node::from("verylongstring")).is_err());
    }

    #[test]
    fn test_pattern_validator() {
        // Simple substring pattern
        let validator = PatternValidator::new("@");
        assert!(validator.validate(&Node::from("user@example.com")).is_ok());
        assert!(validator.validate(&Node::from("invalid")).is_err());

        // Regex pattern: email
        let validator = PatternValidator::new(r"^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$");
        assert!(validator.validate(&Node::from("user@example.com")).is_ok());
        assert!(validator.validate(&Node::from("user@domain")).is_err());
        assert!(validator.validate(&Node::from("@domain.com")).is_err());

        // Non-string node
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(42)))
                .is_err()
        );
    }

    #[test]
    fn test_enum_validator() {
        // String values
        let validator = EnumValidator::new(vec![
            "red".to_string(),
            "green".to_string(),
            "blue".to_string(),
        ]);
        assert!(validator.validate(&Node::from("red")).is_ok());
        assert!(validator.validate(&Node::from("yellow")).is_err());

        // Integer values
        let validator = EnumValidator::new(vec!["1".to_string(), "2".to_string()]);
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(1)))
                .is_ok()
        );
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(3)))
                .is_err()
        );

        // Boolean values
        let validator = EnumValidator::new(vec!["true".to_string(), "false".to_string()]);
        assert!(validator.validate(&Node::Boolean(true)).is_ok());
        assert!(validator.validate(&Node::Boolean(false)).is_ok());
        assert!(validator.validate(&Node::from("true")).is_ok());
        assert!(validator.validate(&Node::from("maybe")).is_err());

        // Null value
        let validator = EnumValidator::new(vec!["null".to_string()]);
        assert!(validator.validate(&Node::None).is_ok());
        assert!(validator.validate(&Node::from("null")).is_ok());
        assert!(validator.validate(&Node::from("notnull")).is_err());

        // Non-scalar node
        assert!(validator.validate(&Node::Array(vec![])).is_err());
    }

    #[test]
    fn test_required_validator() {
        // String key
        let validator = RequiredValidator::new("name");
        let mapping = Node::Mapping(vec![
            (Node::from("name"), Node::from("Alice")),
            (Node::from("age"), Node::from(30)),
        ]);
        assert!(validator.validate(&mapping).is_ok());
        let mapping2 = Node::Mapping(vec![(Node::from("age"), Node::from(30))]);
        assert!(validator.validate(&mapping2).is_err());

        // Integer key
        let validator = RequiredValidator::new("42");
        let mapping = Node::Mapping(vec![(
            Node::Number(Numeric::Integer(42)),
            Node::from("answer"),
        )]);
        assert!(validator.validate(&mapping).is_ok());
        let mapping2 = Node::Mapping(vec![(
            Node::Number(Numeric::Integer(43)),
            Node::from("not answer"),
        )]);
        assert!(validator.validate(&mapping2).is_err());

        // Boolean key
        let validator = RequiredValidator::new("true");
        let mapping = Node::Mapping(vec![(Node::Boolean(true), Node::from("yes"))]);
        assert!(validator.validate(&mapping).is_ok());
        let mapping2 = Node::Mapping(vec![(Node::Boolean(false), Node::from("no"))]);
        assert!(validator.validate(&mapping2).is_err());

        // Null key
        let validator = RequiredValidator::new("null");
        let mapping = Node::Mapping(vec![(Node::None, Node::from("missing"))]);
        assert!(validator.validate(&mapping).is_ok());
        let mapping2 = Node::Mapping(vec![(Node::from("notnull"), Node::from("not missing"))]);
        assert!(validator.validate(&mapping2).is_err());

        // Non-mapping node
        assert!(validator.validate(&Node::Array(vec![])).is_err());
    }

    #[test]
    fn test_custom_validator() {
        let validator = CustomValidator::new("Must be positive", |node| match node {
            Node::Number(Numeric::Integer(i)) if *i > 0 => Ok(()),
            Node::Number(Numeric::Integer(_)) => {
                Err(ValidationError::Custom("Number must be positive".to_string()).into())
            }
            _ => Err(ValidationError::Custom("Not a number".to_string()).into()),
        });

        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(10)))
                .is_ok()
        );
        assert!(
            validator
                .validate(&Node::Number(Numeric::Integer(-5)))
                .is_err()
        );
    }
}

#[cfg(test)]
mod additional_validators_tests {
    use super::*;

    #[test]
    fn test_type_validator_any() {
        let validator = TypeValidator::new(SchemaType::Any);
        assert!(validator.validate(&Node::from("string")).is_ok());
        assert!(validator.validate(&Node::Number(Numeric::Integer(1))).is_ok());
        assert!(validator.validate(&Node::Boolean(true)).is_ok());
    }

    #[test]
    fn test_range_validator_invalid_node() {
        let validator = RangeValidator::new(Some(0.0), Some(10.0));
        let result = validator.validate(&Node::from("not a number"));
        assert!(result.is_err());
        if let Err(ValidationError::InvalidNodeType { validator: v, .. }) = result {
            assert_eq!(v, "RangeValidator");
        } else {
            panic!("Expected InvalidNodeType error");
        }
    }

    #[test]
    fn test_length_validator_string_and_array() {
        let validator = LengthValidator::new(Some(2), Some(4));
        assert!(validator.validate(&Node::from("ab")).is_ok());
        assert!(validator.validate(&Node::from("abcd")).is_ok());
        assert!(validator.validate(&Node::from("a")).is_err());
        assert!(validator.validate(&Node::from("abcde")).is_err());

        let arr = Node::Array(vec![Node::from(1), Node::from(2)]);
        assert!(validator.validate(&arr).is_ok());
        let arr = Node::Array(vec![Node::from(1)]);
        assert!(validator.validate(&arr).is_err());
    }

    #[test]
    fn test_pattern_validator() {
        let validator = PatternValidator::new("^abc[0-9]+$".to_string());
        assert!(validator.validate(&Node::from("abc123")).is_ok());
        assert!(validator.validate(&Node::from("ab123")).is_err());
    }

    #[test]
    fn test_enum_validator() {
        let validator = EnumValidator::new(vec!["A".to_string(), "B".to_string()]);
        assert!(validator.validate(&Node::from("A")).is_ok());
        assert!(validator.validate(&Node::from("C")).is_err());
    }

    #[test]
    fn test_required_validator_non_mapping() {
        let validator = RequiredValidator::new("foo");
        let node = Node::Array(vec![]);
        assert!(validator.validate(&node).is_err());
    }
}