noml 0.9.3

High-performance dynamic configuration language with format preservation, environment variables, native types, string interpolation, and TOML compatibility. Blazing-fast parsing at 25ยตs with zero-copy architecture.
Documentation
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
//! # NOML Schema Validation
//!
//! Comprehensive schema validation system for NOML configurations. Provides
//! type-safe validation with detailed error reporting to catch configuration
//! errors early in development and deployment.
//!
//! ## Overview
//!
//! The schema system enables you to define expected structure and types for
//! configuration files, ensuring data integrity and providing clear error
//! messages when validation fails.
//!
//! ## Quick Start
//!
//! ```rust
//! use noml::{Config, SchemaBuilder, FieldType};
//!
//! // Define schema using builder pattern
//! let schema = SchemaBuilder::new()
//!     .require_string("app_name")
//!     .require_integer("port")
//!     .optional_bool("debug")
//!     .build();
//!
//! // Load and validate configuration
//! let config = Config::from_string(r#"
//!     app_name = "my-service"
//!     port = 8080
//!     debug = true
//! "#)?;
//!
//! config.validate_schema(&schema)?;
//!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Advanced Schema Definition
//!
//! ```rust
//! use noml::{Schema, FieldSchema, FieldType, Value};
//! use std::collections::HashMap;
//!
//! // Create nested schema for database configuration
//! let mut db_schema = Schema::new()
//!     .required_field("host", FieldType::String)
//!     .required_field("port", FieldType::Integer)
//!     .optional_field("ssl", FieldType::Bool)
//!     .field_with_default("timeout", FieldType::Integer, Value::integer(30));
//!
//! // Main application schema
//! let app_schema = Schema::new()
//!     .required_field("name", FieldType::String)
//!     .required_field("database", FieldType::Table(db_schema))
//!     .allow_additional(false);  // Strict validation
//!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Validation Features
//!
//! - **๐Ÿ” Type Checking** - Ensure values match expected types
//! - **๐Ÿ“‹ Required Fields** - Validate presence of mandatory configuration
//! - **๐Ÿ”ง Default Values** - Automatic insertion of missing optional fields
//! - **๐Ÿ—๏ธ Nested Validation** - Deep validation of table structures
//! - **๐Ÿ“ Descriptive Errors** - Clear messages with field paths
//! - **๐Ÿ”“ Flexible Schemas** - Allow or reject additional fields

use crate::error::{NomlError, Result};
use crate::value::Value;
use std::collections::HashMap;

/// Schema definition for validating NOML configurations
#[derive(Debug, Clone, PartialEq)]
pub struct Schema {
    /// Field definitions
    pub fields: HashMap<String, FieldSchema>,
    /// Whether to allow additional fields not defined in schema
    pub allow_additional: bool,
}

/// Schema definition for a field
#[derive(Debug, Clone, PartialEq)]
pub struct FieldSchema {
    /// Expected type of the field
    pub field_type: FieldType,
    /// Whether this field is required
    pub required: bool,
    /// Optional description for documentation
    pub description: Option<String>,
    /// Default value if field is missing
    pub default: Option<Value>,
}

/// Supported field types for validation
#[derive(Debug, Clone, PartialEq)]
pub enum FieldType {
    /// String value
    String,
    /// Integer value
    Integer,
    /// Float value
    Float,
    /// Boolean value
    Bool,
    /// Binary data
    Binary,
    /// DateTime value
    DateTime,
    /// Array of specific type
    Array(Box<FieldType>),
    /// Table/object with nested schema
    Table(Schema),
    /// Any type (no validation)
    Any,
    /// One of several types
    Union(Vec<FieldType>),
}

impl Schema {
    /// Create a new empty schema
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
            allow_additional: true,
        }
    }

    /// Add a required field to the schema
    pub fn required_field(mut self, name: &str, field_type: FieldType) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type,
                required: true,
                description: None,
                default: None,
            },
        );
        self
    }

    /// Add an optional field to the schema
    pub fn optional_field(mut self, name: &str, field_type: FieldType) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type,
                required: false,
                description: None,
                default: None,
            },
        );
        self
    }

    /// Add a field with a default value
    pub fn field_with_default(mut self, name: &str, field_type: FieldType, default: Value) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type,
                required: false,
                description: None,
                default: Some(default),
            },
        );
        self
    }

    /// Set whether to allow additional fields
    pub fn allow_additional(mut self, allow: bool) -> Self {
        self.allow_additional = allow;
        self
    }

    /// Validate a value against this schema.
    ///
    /// Errors name the full path of the offending field, such as
    /// `server.port` or `hosts[2]`. Fields are checked in name order, so the
    /// same input always reports the same first error.
    pub fn validate(&self, value: &Value) -> Result<()> {
        self.validate_at(value, "")
    }

    /// Fill in the defaults of fields declared with
    /// [`field_with_default`](Self::field_with_default) that are missing from
    /// `value`, including inside nested table schemas. Values that are
    /// present are never changed, and a non-table `value` is left alone.
    pub fn apply_defaults(&self, value: &mut Value) {
        let Value::Table(table) = value else {
            return;
        };
        for (name, field) in &self.fields {
            if !table.contains_key(name) {
                if let Some(default) = &field.default {
                    table.insert(name.clone(), default.clone());
                }
            }
            if let (Some(child), FieldType::Table(nested)) =
                (table.get_mut(name), &field.field_type)
            {
                nested.apply_defaults(child);
            }
        }
    }

    fn validate_at(&self, value: &Value, prefix: &str) -> Result<()> {
        let path = |name: &str| {
            if prefix.is_empty() {
                name.to_string()
            } else {
                format!("{prefix}.{name}")
            }
        };
        match value {
            Value::Table(table) => {
                let mut names: Vec<&String> = self.fields.keys().collect();
                names.sort();

                // Check required fields
                for name in &names {
                    if self.fields[*name].required && !table.contains_key(*name) {
                        return Err(NomlError::validation_at(
                            format!("Required field '{}' is missing", path(name)),
                            path(name),
                        ));
                    }
                }

                // Validate existing fields (BTreeMap iterates in name order)
                for (key, val) in table {
                    if let Some(field_schema) = self.fields.get(key) {
                        self.validate_field_type(val, &field_schema.field_type, &path(key))?;
                    } else if !self.allow_additional {
                        return Err(NomlError::validation_at(
                            format!("Additional field '{}' is not allowed", path(key)),
                            path(key),
                        ));
                    }
                }

                Ok(())
            }
            _ => Err(NomlError::validation(if prefix.is_empty() {
                "Schema validation requires a table/object at the root".to_string()
            } else {
                format!("Field '{prefix}' must be a table")
            })),
        }
    }

    /// Validate a field against its expected type
    fn validate_field_type(
        &self,
        value: &Value,
        expected_type: &FieldType,
        field_path: &str,
    ) -> Result<()> {
        match (value, expected_type) {
            (Value::String(_), FieldType::String) => Ok(()),
            (Value::Integer(_), FieldType::Integer) => Ok(()),
            (Value::Float(_), FieldType::Float) => Ok(()),
            (Value::Bool(_), FieldType::Bool) => Ok(()),
            (Value::Binary(_), FieldType::Binary) => Ok(()),
            #[cfg(feature = "chrono")]
            (Value::DateTime(_), FieldType::DateTime) => Ok(()),
            (_, FieldType::Any) => Ok(()),

            (Value::Array(arr), FieldType::Array(element_type)) => {
                for (i, item) in arr.iter().enumerate() {
                    let item_path = format!("{field_path}[{i}]");
                    self.validate_field_type(item, element_type, &item_path)?;
                }
                Ok(())
            }

            (Value::Table(_), FieldType::Table(nested_schema)) => {
                nested_schema.validate_at(value, field_path)
            }

            (val, FieldType::Union(types)) => {
                for field_type in types {
                    if self
                        .validate_field_type(val, field_type, field_path)
                        .is_ok()
                    {
                        return Ok(());
                    }
                }
                Err(NomlError::validation_at(
                    format!("Field '{field_path}' does not match any of the expected types"),
                    field_path,
                ))
            }

            _ => Err(NomlError::validation_at(
                format!(
                    "Field '{field_path}' has incorrect type. Expected {expected_type:?}, got {:?}",
                    self.value_type_name(value)
                ),
                field_path,
            )),
        }
    }

    /// Get a human-readable type name for a value
    fn value_type_name(&self, value: &Value) -> &'static str {
        match value {
            Value::String(_) => "String",
            Value::Integer(_) => "Integer",
            Value::Float(_) => "Float",
            Value::Bool(_) => "Bool",
            Value::Array(_) => "Array",
            Value::Table(_) => "Table",
            Value::Null => "Null",
            Value::Size(_) => "Size",
            Value::Duration(_) => "Duration",
            Value::Binary(_) => "Binary",
            #[cfg(feature = "chrono")]
            Value::DateTime(_) => "DateTime",
        }
    }
}

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

/// Builder for creating schemas more easily
pub struct SchemaBuilder {
    schema: Schema,
}

impl SchemaBuilder {
    /// Create a new schema builder
    pub fn new() -> Self {
        Self {
            schema: Schema::new(),
        }
    }

    /// Add a required string field
    pub fn require_string(mut self, name: &str) -> Self {
        self.schema = self.schema.required_field(name, FieldType::String);
        self
    }

    /// Add a required integer field
    pub fn require_integer(mut self, name: &str) -> Self {
        self.schema = self.schema.required_field(name, FieldType::Integer);
        self
    }

    /// Add an optional boolean field
    pub fn optional_bool(mut self, name: &str) -> Self {
        self.schema = self.schema.optional_field(name, FieldType::Bool);
        self
    }

    /// Build the final schema
    pub fn build(self) -> Schema {
        self.schema
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::Value;
    use std::collections::BTreeMap;

    #[test]
    fn test_basic_schema_validation() {
        let schema = Schema::new()
            .required_field("name", FieldType::String)
            .required_field("port", FieldType::Integer)
            .optional_field("debug", FieldType::Bool);

        // Valid config
        let mut config = BTreeMap::new();
        config.insert("name".to_string(), Value::String("test".to_string()));
        config.insert("port".to_string(), Value::Integer(8080));
        config.insert("debug".to_string(), Value::Bool(true));

        let valid_value = Value::Table(config);
        assert!(schema.validate(&valid_value).is_ok());

        // Missing required field
        let mut invalid_config = BTreeMap::new();
        invalid_config.insert("name".to_string(), Value::String("test".to_string()));
        // missing port

        let invalid_value = Value::Table(invalid_config);
        assert!(schema.validate(&invalid_value).is_err());
    }

    #[test]
    fn test_schema_builder() {
        let schema = SchemaBuilder::new()
            .require_string("app_name")
            .require_integer("version")
            .optional_bool("debug")
            .build();

        let mut config = BTreeMap::new();
        config.insert("app_name".to_string(), Value::String("MyApp".to_string()));
        config.insert("version".to_string(), Value::Integer(1));

        let value = Value::Table(config);
        assert!(schema.validate(&value).is_ok());
    }

    #[test]
    fn test_array_validation() {
        let schema =
            Schema::new().required_field("tags", FieldType::Array(Box::new(FieldType::String)));

        let mut config = BTreeMap::new();
        config.insert(
            "tags".to_string(),
            Value::Array(vec![
                Value::String("web".to_string()),
                Value::String("api".to_string()),
            ]),
        );

        let value = Value::Table(config);
        assert!(schema.validate(&value).is_ok());

        // Invalid array element type
        let mut invalid_config = BTreeMap::new();
        invalid_config.insert(
            "tags".to_string(),
            Value::Array(vec![
                Value::String("web".to_string()),
                Value::Integer(123), // Wrong type
            ]),
        );

        let invalid_value = Value::Table(invalid_config);
        assert!(schema.validate(&invalid_value).is_err());
    }

    #[test]
    fn nested_errors_name_the_full_path() {
        let schema = Schema::new().required_field(
            "server",
            FieldType::Table(Schema::new().required_field("port", FieldType::Integer)),
        );
        let mut server = std::collections::BTreeMap::new();
        server.insert("port".to_string(), Value::String("x".to_string()));
        let mut root = std::collections::BTreeMap::new();
        root.insert("server".to_string(), Value::Table(server));
        let error = schema.validate(&Value::Table(root)).unwrap_err();
        assert!(error.to_string().contains("server.port"), "{error}");
    }

    #[test]
    fn defaults_are_applied_without_overwriting() {
        let schema = Schema::new()
            .field_with_default("port", FieldType::Integer, Value::Integer(80))
            .field_with_default("host", FieldType::String, Value::String("h".into()))
            .optional_field(
                "db",
                FieldType::Table(Schema::new().field_with_default(
                    "pool",
                    FieldType::Integer,
                    Value::Integer(5),
                )),
            );
        let mut value = crate::parse("port = 8080\n[db]\nname = \"x\"").unwrap();
        schema.apply_defaults(&mut value);
        assert_eq!(value.get("port"), Some(&Value::Integer(8080)));
        assert_eq!(value.get("host"), Some(&Value::String("h".into())));
        assert_eq!(value.get("db.pool"), Some(&Value::Integer(5)));
        assert!(schema.validate(&value).is_ok());
    }
}