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
//! Validation Engine for YAML Library
//!
//! This module provides core helpers and context for building validation errors and implementing
//! schema-based validation logic for YAML documents. It supports DRY error construction and reusable
//! validation patterns for custom validators.
//!
//! # Features
//! - Centralized error construction for validators
//! - Context helpers for schema validation
//! - Extensible for custom validation logic
//!
//! # Usage
//! Use these helpers to implement robust and consistent validation for YAML data structures.
/// Core helpers for building validation errors (DRY for validators)
pub struct ValidationContextCore;

impl ValidationContextCore {
    pub fn fail_type_mismatch(expected: &SchemaType, node: &Node) -> ValidationError {
        ValidationError::TypeMismatch {
            expected: format!("{:?}", expected),
            found: node.to_string_lossy(),
        }
    }

    pub fn fail_range(value: f64, min: Option<f64>, max: Option<f64>) -> ValidationError {
        ValidationError::RangeError { value, min, max }
    }

    pub fn fail_required(field: &str) -> ValidationError {
        ValidationError::RequiredFieldMissing {
            field: field.to_string(),
        }
    }
}
/// Validation engine for executing schema validation against YAML nodes
///
/// Provides SchemaValidator that traverses nodes and applies validation rules.
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use log::warn;

use crate::error::YamlError;
use crate::nodes::node::Node;
use crate::nodes::node::NodeStringConvert;
use crate::validation::error::{ValidationError, ValidationIssue};
use crate::validation::schema::{PropertySchema, Schema, SchemaType};
use crate::validation::validators::{
    EnumValidator, LengthValidator, PatternValidator, RangeValidator, TypeValidator, Validator,
};

/// Context for tracking validation state during traversal
#[derive(Debug, Clone)]
pub struct ValidationContext {
    /// Current path in document
    path: Vec<String>,
    /// Accumulated errors
    errors: Vec<ValidationIssue>,
    /// Whether to stop on first error
    fail_fast: bool,
}

impl ValidationContext {
    pub fn new() -> Self {
        Self {
            path: Vec::new(),
            errors: Vec::new(),
            fail_fast: false,
        }
    }

    pub fn with_fail_fast(mut self, fail_fast: bool) -> Self {
        self.fail_fast = fail_fast;
        self
    }

    /// Add a path segment
    fn push(&mut self, segment: impl Into<String>) {
        self.path.push(segment.into());
    }

    /// Remove last path segment
    fn pop(&mut self) {
        self.path.pop();
    }

    /// Record an error and log it
    fn add_error(&mut self, error: ValidationError) {
        let issue = ValidationIssue::new(&self.path, error);
        warn!("Validation error: {:?}", issue);
        self.errors.push(issue);
    }

    /// Check if we should stop validation
    fn should_stop(&self) -> bool {
        self.fail_fast && !self.errors.is_empty()
    }

    /// Get all errors
    pub fn errors(&self) -> &[ValidationIssue] {
        &self.errors
    }

    /// Check if validation succeeded
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }
}

impl Default for ValidationContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Main validator for executing schema validation
pub struct SchemaValidator {
    schema: Schema,
}

impl SchemaValidator {
    pub fn new(schema: Schema) -> Self {
        Self { schema }
    }

    /// Validate a node against the schema
    pub fn validate(&self, node: &Node) -> Result<(), YamlError> {
        let mut ctx = ValidationContext::new();
        self.validate_with_context(node, &mut ctx);

        if ctx.is_valid() {
            Ok(())
        } else {
            // Convert collected ValidationIssue values to a single YamlError
            // with detailed messages (including paths).
            let msg = ctx
                .errors
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join(", ");
            Err(YamlError::new(
                crate::error::ErrorKind::ValidationError,
                msg,
            ))
        }
    }

    /// Validate with custom context
    pub fn validate_with_context(&self, node: &Node, ctx: &mut ValidationContext) {
        self.validate_property(node, &self.schema.root, ctx);
    }

    /// Validate node against property schema
    fn validate_property(&self, node: &Node, schema: &PropertySchema, ctx: &mut ValidationContext) {
        if ctx.should_stop() {
            return;
        }

        // Type validation
        let type_validator = TypeValidator::new(schema.schema_type.clone());
        if let Err(err) = type_validator.validate(node) {
            ctx.add_error(err);
            return;
        }

        // Range validation for numbers
        if let (Some(min), Some(max)) = (schema.minimum, schema.maximum) {
            let validator = RangeValidator::new(Some(min), Some(max));
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        } else if let Some(min) = schema.minimum {
            let validator = RangeValidator::new(Some(min), None);
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        } else if let Some(max) = schema.maximum {
            let validator = RangeValidator::new(None, Some(max));
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        }

        // Length validation for strings/arrays
        if let (Some(min), Some(max)) = (schema.min_length, schema.max_length) {
            let validator = LengthValidator::new(Some(min), Some(max));
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        } else if let Some(min) = schema.min_length {
            let validator = LengthValidator::new(Some(min), None);
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        } else if let Some(max) = schema.max_length {
            let validator = LengthValidator::new(None, Some(max));
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        }

        // Pattern validation
        if let Some(ref pattern) = schema.pattern {
            let validator = PatternValidator::new(pattern.clone());
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        }

        // Enum validation
        if let Some(ref allowed) = schema.enum_values {
            let validator = EnumValidator::new(allowed.clone());
            if let Err(err) = validator.validate(node) {
                ctx.add_error(err);
                return;
            }
        }

        // Validate nested structures
        match (&schema.schema_type, node) {
            (SchemaType::Array, Node::Array(arr)) => {
                if let Some(ref items) = schema.items {
                    // Validate each item against the schema
                    for (i, item) in arr.iter().enumerate() {
                        ctx.push(format!("[{}]", i));
                        self.validate_property(item, items, ctx);
                        ctx.pop();

                        if ctx.should_stop() {
                            return;
                        }
                    }
                }
            }
            (SchemaType::Object, Node::Mapping(pairs)) => {
                if let Some(ref properties) = schema.properties {
                    // Build a map of property names to values
                    let mut props = BTreeMap::new();
                    for (key, value) in pairs {
                        if let Node::Str(k, _, _) = key {
                            props.insert(k.as_str(), value);
                        }
                    }

                    // Validate each property against its schema
                    for (prop_name, prop_schema) in properties {
                        if let Some(value) = props.get(prop_name.as_str()) {
                            ctx.push(prop_name.clone());
                            self.validate_property(value, prop_schema, ctx);
                            ctx.pop();

                            if ctx.should_stop() {
                                return;
                            }
                        } else if prop_schema.required {
                            ctx.add_error(ValidationError::RequiredFieldMissing {
                                field: prop_name.clone(),
                            });
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nodes::node::Numeric;
    use crate::validation::schema::Schema;

    #[test]
    fn test_simple_validation() {
        let schema = Schema::string();
        let validator = SchemaValidator::new(schema);

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

    #[test]
    fn test_range_validation() {
        let schema = Schema {
            root: PropertySchema::new(SchemaType::Integer)
                .with_minimum(0.0)
                .with_maximum(100.0),
            title: None,
            description: None,
        };
        let validator = SchemaValidator::new(schema);

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

    #[test]
    fn test_object_validation() {
        let mut properties = BTreeMap::new();
        properties.insert(
            "name".to_string(),
            PropertySchema::new(SchemaType::String).required(),
        );
        properties.insert("age".to_string(), PropertySchema::new(SchemaType::Integer));

        let schema = Schema::object(properties);
        let validator = SchemaValidator::new(schema);

        let valid_obj = Node::Mapping(vec![
            (Node::from("name"), Node::from("Alice")),
            (Node::from("age"), Node::Number(Numeric::Integer(30))),
        ]);
        assert!(validator.validate(&valid_obj).is_ok());

        let invalid_obj = Node::Mapping(vec![(
            Node::from("age"),
            Node::Number(Numeric::Integer(30)),
        )]);
        assert!(validator.validate(&invalid_obj).is_err());
    }

    #[test]
    fn test_array_validation() {
        let schema = Schema::array(PropertySchema::new(SchemaType::Integer));
        let validator = SchemaValidator::new(schema);

        let valid_arr = Node::Array(vec![
            Node::Number(Numeric::Integer(1)),
            Node::Number(Numeric::Integer(2)),
            Node::Number(Numeric::Integer(3)),
        ]);
        assert!(validator.validate(&valid_arr).is_ok());

        let wrong_type = Node::Array(vec![Node::from("not a number")]);
        assert!(validator.validate(&wrong_type).is_err());
    }

    #[test]
    fn test_validation_error_paths() {
        let mut user_props = BTreeMap::new();
        user_props.insert("name".to_string(), PropertySchema::new(SchemaType::String));
        user_props.insert("age".to_string(), PropertySchema::new(SchemaType::Integer));

        let mut root_props = BTreeMap::new();
        root_props.insert(
            "user".to_string(),
            PropertySchema::new(SchemaType::Object).with_properties(user_props),
        );

        let schema = Schema::object(root_props);
        let validator = SchemaValidator::new(schema);

        let obj = Node::Mapping(vec![(
            Node::from("user"),
            Node::Mapping(vec![
                (Node::from("name"), Node::from("Alice")),
                (Node::from("age"), Node::from("not a number")),
            ]),
        )]);

        let result = validator.validate(&obj);
        assert!(result.is_err());

        let error = result.unwrap_err();
        let msg = error.to_string();
        // Check that the error message contains the expected type mismatch
        assert!(msg.contains("Type mismatch"));
    }
}

#[cfg(test)]
mod additional_validation_engine_tests {
    use super::*;
    use crate::nodes::node::{Node, Numeric};
    use crate::validation::schema::{PropertySchema, Schema, SchemaType};

    #[test]
    fn test_fail_type_mismatch_error() {
        let err = ValidationContextCore::fail_type_mismatch(&SchemaType::String, &Node::from(42));
        match err {
            ValidationError::TypeMismatch { expected, found } => {
                assert!(expected.contains("String"));
                assert!(found.contains("42"));
            }
            _ => panic!("Expected TypeMismatch error"),
        }
    }

    #[test]
    fn test_fail_range_error() {
        let err = ValidationContextCore::fail_range(5.0, Some(1.0), Some(10.0));
        match err {
            ValidationError::RangeError { value, min, max } => {
                assert_eq!(value, 5.0);
                assert_eq!(min, Some(1.0));
                assert_eq!(max, Some(10.0));
            }
            _ => panic!("Expected RangeError"),
        }
    }

    #[test]
    fn test_fail_required_error() {
        let err = ValidationContextCore::fail_required("foo");
        match err {
            ValidationError::RequiredFieldMissing { field } => {
                assert_eq!(field, "foo");
            }
            _ => panic!("Expected RequiredFieldMissing error"),
        }
    }

    #[test]
    fn test_validation_context_fail_fast() {
        let mut ctx = ValidationContext::new().with_fail_fast(true);
        ctx.add_error(ValidationError::RequiredFieldMissing {
            field: "x".to_string(),
        });
        assert!(ctx.should_stop());
    }

    #[test]
    fn test_schema_validator_empty_object() {
        let schema = Schema::object(BTreeMap::new());
        let validator = SchemaValidator::new(schema);
        let node = Node::Mapping(vec![]);
        assert!(validator.validate(&node).is_ok());
    }

    #[test]
    fn test_schema_validator_array_with_items() {
        let mut item_schema = PropertySchema::new(SchemaType::Integer);
        item_schema.required = true;
        let mut root_schema = PropertySchema::new(SchemaType::Array);
        root_schema.items = Some(Box::new(item_schema));
        let schema = Schema {
            root: root_schema,
            title: None,
            description: None,
        };
        let validator = SchemaValidator::new(schema);
        let node = Node::Array(vec![
            Node::Number(Numeric::Integer(1)),
            Node::Number(Numeric::Integer(2)),
        ]);
        assert!(validator.validate(&node).is_ok());
    }

    #[test]
    fn test_schema_validator_object_missing_required() {
        let mut props = BTreeMap::new();
        let mut required_schema = PropertySchema::new(SchemaType::String);
        required_schema.required = true;
        props.insert("foo".to_string(), required_schema);
        let schema = Schema::object(props);
        let validator = SchemaValidator::new(schema);
        let node = Node::Mapping(vec![]);
        let result = validator.validate(&node);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("Required field"));
    }
}