tanzim-validate 0.1.0

Validate and coerce tanzim-value configuration trees
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
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Build validators from a self-describing schema document.
//!
//! A schema is an ordinary [`Value`] tree (parse it with serde via [`SchemaValue`], or hand
//! one over directly from `tanzim-parse`). Every node is a map with a `"type"` tag plus the
//! options for that validator; the [`Registry`] dispatches on the tag to a constructor.
//! Custom validator types can be added with [`Registry::register`].

use std::collections::HashMap;

use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};

use crate::Segment;
use crate::Validator;
use crate::{
    Bool, Domain, DynamicMap, Either, Email, Enum, Float, Host, Integer, IpAddr, List, NonEmpty,
    Number, Path, PathKind, Percentage, Port, SocketAddr, StaticMap, Str,
};
use tanzim_value::{LocatedValue, Location, Map, Value};

/// Location used for values produced by the serde deserializer, which carry no source span.
fn schema_location() -> Location {
    Location::at("schema", "", None, None, None)
}

/// A [`Value`] that can be produced by any serde deserializer (e.g. `serde_json`).
///
/// This is the bridge between the serde world and tanzim's own [`Value`] type. Deserialize a
/// schema into a `SchemaValue`, then feed it to [`build_value`] or a [`Registry`].
#[derive(Debug, Clone, PartialEq)]
pub struct SchemaValue(pub Value);

impl SchemaValue {
    pub fn value(&self) -> &Value {
        &self.0
    }

    pub fn into_value(self) -> Value {
        self.0
    }
}

struct SchemaValueVisitor;

impl<'de> Visitor<'de> for SchemaValueVisitor {
    type Value = SchemaValue;

    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("a configuration value (no null)")
    }

    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
        Ok(SchemaValue(Value::Bool(value)))
    }

    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
        match isize::try_from(value) {
            Ok(number) => Ok(SchemaValue(Value::Int(number))),
            Err(_) => Err(de::Error::custom("integer out of range")),
        }
    }

    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
        match isize::try_from(value) {
            Ok(number) => Ok(SchemaValue(Value::Int(number))),
            Err(_) => Err(de::Error::custom("integer out of range")),
        }
    }

    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
        Ok(SchemaValue(Value::Float(value)))
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
        Ok(SchemaValue(Value::String(value.to_string())))
    }

    fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
        Ok(SchemaValue(Value::String(value)))
    }

    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
        Err(de::Error::custom("null is not supported in configuration"))
    }

    fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
        Err(de::Error::custom("null is not supported in configuration"))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        let mut items = Vec::new();
        while let Some(element) = seq.next_element::<SchemaValue>()? {
            items.push(LocatedValue {
                value: element.0,
                location: schema_location(),
            });
        }
        Ok(SchemaValue(Value::List(items)))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
        let mut map = Map::new();
        while let Some((key, element)) = access.next_entry::<String, SchemaValue>()? {
            map.insert(
                key,
                LocatedValue {
                    value: element.0,
                    location: schema_location(),
                },
            );
        }
        Ok(SchemaValue(Value::Map(map)))
    }
}

impl<'de> Deserialize<'de> for SchemaValue {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(SchemaValueVisitor)
    }
}

/// What went wrong while building a validator from a schema document.
#[derive(Debug, Clone, PartialEq)]
pub enum SchemaErrorKind {
    /// A validator node was not a map.
    NotMap,
    /// The `"type"` tag named a validator the registry does not know.
    UnknownType { tag: String },
    /// A required field was absent.
    MissingField { field: String },
    /// A field had the wrong value type.
    WrongType {
        field: String,
        expected: &'static str,
    },
    /// A field had a structurally valid but semantically invalid value.
    InvalidValue { field: String, message: String },
}

impl std::fmt::Display for SchemaErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotMap => write!(f, "validator schema must be a map"),
            Self::UnknownType { tag } => write!(f, "unknown validator type `{tag}`"),
            Self::MissingField { field } => write!(f, "missing field `{field}`"),
            Self::WrongType { field, expected } => {
                write!(f, "field `{field}` must be {expected}")
            }
            Self::InvalidValue { field, message } => write!(f, "field `{field}`: {message}"),
        }
    }
}

/// A schema-construction failure, with a breadcrumb path and (when known) source location.
#[derive(Debug, Clone, PartialEq)]
pub struct SchemaError {
    pub kind: SchemaErrorKind,
    pub path: Vec<Segment>,
    /// Boxed to keep the error small (`clippy::result_large_err`).
    pub location: Option<Box<Location>>,
}

impl std::fmt::Display for SchemaError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (position, segment) in self.path.iter().enumerate() {
            match segment {
                Segment::Key(key) => {
                    if position > 0 {
                        write!(f, ".")?;
                    }
                    write!(f, "{key}")?;
                }
                Segment::Index(index) => write!(f, "[{index}]")?,
            }
        }
        if !self.path.is_empty() {
            write!(f, ": ")?;
        }
        write!(f, "{}", self.kind)?;
        if let Some(location) = &self.location {
            write!(f, " at {location}")?;
        }
        Ok(())
    }
}

impl std::error::Error for SchemaError {}

/// A validator node: the map of options plus what's needed to read them and recurse.
///
/// Passed to each [`Registry`] constructor. Custom constructors use its readers
/// (`opt_int`, `flag`, `child`, …) to pull options and build nested validators.
pub struct Node<'a> {
    registry: &'a Registry,
    map: &'a Map,
    location: &'a Location,
    path: Vec<Segment>,
}

impl Node<'_> {
    /// Build an error anchored at this node.
    pub fn error(&self, kind: SchemaErrorKind) -> SchemaError {
        SchemaError {
            kind,
            path: self.path.clone(),
            location: Some(Box::new(self.location.clone())),
        }
    }

    fn missing(&self, field: &str) -> SchemaError {
        self.error(SchemaErrorKind::MissingField {
            field: field.to_string(),
        })
    }

    fn wrong(&self, field: &str, expected: &'static str) -> SchemaError {
        self.error(SchemaErrorKind::WrongType {
            field: field.to_string(),
            expected,
        })
    }

    /// Read a required string field.
    pub fn req_str(&self, field: &str) -> Result<&str, SchemaError> {
        match self.opt_str(field)? {
            Some(text) => Ok(text),
            None => Err(self.missing(field)),
        }
    }

    /// Read an optional string field.
    pub fn opt_str(&self, field: &str) -> Result<Option<&str>, SchemaError> {
        match self.map.get(field) {
            None => Ok(None),
            Some(entry) => match &entry.value {
                Value::String(text) => Ok(Some(text)),
                _ => Err(self.wrong(field, "a string")),
            },
        }
    }

    /// Read an optional integer field.
    pub fn opt_int(&self, field: &str) -> Result<Option<isize>, SchemaError> {
        match self.map.get(field) {
            None => Ok(None),
            Some(entry) => match &entry.value {
                Value::Int(number) => Ok(Some(*number)),
                _ => Err(self.wrong(field, "an integer")),
            },
        }
    }

    /// Read an optional non-negative integer field as a `usize`.
    pub fn opt_usize(&self, field: &str) -> Result<Option<usize>, SchemaError> {
        match self.opt_int(field)? {
            None => Ok(None),
            Some(number) => match usize::try_from(number) {
                Ok(value) => Ok(Some(value)),
                Err(_) => Err(self.error(SchemaErrorKind::InvalidValue {
                    field: field.to_string(),
                    message: "must be non-negative".to_string(),
                })),
            },
        }
    }

    /// Read an optional number field (integer or float) as an `f64`.
    pub fn opt_f64(&self, field: &str) -> Result<Option<f64>, SchemaError> {
        match self.map.get(field) {
            None => Ok(None),
            Some(entry) => match &entry.value {
                Value::Float(number) => Ok(Some(*number)),
                Value::Int(number) => Ok(Some(*number as f64)),
                _ => Err(self.wrong(field, "a number")),
            },
        }
    }

    /// Read an optional boolean field.
    pub fn opt_bool(&self, field: &str) -> Result<Option<bool>, SchemaError> {
        match self.map.get(field) {
            None => Ok(None),
            Some(entry) => match &entry.value {
                Value::Bool(value) => Ok(Some(*value)),
                _ => Err(self.wrong(field, "a boolean")),
            },
        }
    }

    /// Read a boolean field, defaulting to `false` when absent.
    pub fn flag(&self, field: &str) -> Result<bool, SchemaError> {
        match self.opt_bool(field)? {
            Some(value) => Ok(value),
            None => Ok(false),
        }
    }

    /// Read a list field as raw values (used by `enum`). Absent → empty.
    pub fn values(&self, field: &str) -> Result<Vec<Value>, SchemaError> {
        match self.map.get(field) {
            None => Ok(Vec::new()),
            Some(entry) => match &entry.value {
                Value::List(items) => {
                    let mut out = Vec::new();
                    for item in items {
                        out.push(item.value.clone());
                    }
                    Ok(out)
                }
                _ => Err(self.wrong(field, "a list")),
            },
        }
    }

    /// Read a list-of-strings field (used by `path.extensions`, `url.schemes`). Absent → empty.
    pub fn str_list(&self, field: &str) -> Result<Vec<String>, SchemaError> {
        match self.map.get(field) {
            None => Ok(Vec::new()),
            Some(entry) => match &entry.value {
                Value::List(items) => {
                    let mut out = Vec::new();
                    for item in items {
                        match &item.value {
                            Value::String(text) => out.push(text.clone()),
                            _ => return Err(self.wrong(field, "a list of strings")),
                        }
                    }
                    Ok(out)
                }
                _ => Err(self.wrong(field, "a list of strings")),
            },
        }
    }

    /// Build a required nested validator from a sub-schema field.
    pub fn child(&self, field: &str) -> Result<Box<dyn Validator>, SchemaError> {
        match self.map.get(field) {
            Some(entry) => self.build_sub(entry, field),
            None => Err(self.missing(field)),
        }
    }

    /// Build an optional nested validator from a sub-schema field.
    pub fn opt_child(&self, field: &str) -> Result<Option<Box<dyn Validator>>, SchemaError> {
        match self.map.get(field) {
            Some(entry) => Ok(Some(self.build_sub(entry, field)?)),
            None => Ok(None),
        }
    }

    fn build_sub(
        &self,
        entry: &LocatedValue,
        field: &str,
    ) -> Result<Box<dyn Validator>, SchemaError> {
        let mut path = self.path.clone();
        path.push(Segment::Key(field.to_string()));
        let node = self.registry.node(entry, path)?;
        self.registry.build_node(&node)
    }
}

/// Constructs one validator kind from its [`Node`].
pub type Constructor = Box<dyn Fn(&Node) -> Result<Box<dyn Validator>, SchemaError>>;

/// Maps `"type"` tags to validator constructors.
pub struct Registry {
    constructors: HashMap<String, Constructor>,
}

impl Default for Registry {
    fn default() -> Self {
        Self::with_builtins()
    }
}

impl Registry {
    /// An empty registry with no constructors.
    pub fn empty() -> Self {
        Self {
            constructors: HashMap::new(),
        }
    }

    /// Register (or replace) the constructor for `tag`.
    pub fn register(
        &mut self,
        tag: impl Into<String>,
        constructor: impl Fn(&Node) -> Result<Box<dyn Validator>, SchemaError> + 'static,
    ) {
        self.constructors.insert(tag.into(), Box::new(constructor));
    }

    /// Build a validator from a located schema node, seeding source locations into errors.
    pub fn build(&self, value: &LocatedValue) -> Result<Box<dyn Validator>, SchemaError> {
        let node = self.node(value, Vec::new())?;
        self.build_node(&node)
    }

    /// Build a validator from a bare [`Value`] (errors carry no source location).
    pub fn build_value(&self, value: &Value) -> Result<Box<dyn Validator>, SchemaError> {
        let located = LocatedValue {
            value: value.clone(),
            location: schema_location(),
        };
        self.build(&located)
    }

    fn node<'a>(
        &'a self,
        value: &'a LocatedValue,
        path: Vec<Segment>,
    ) -> Result<Node<'a>, SchemaError> {
        match &value.value {
            Value::Map(map) => Ok(Node {
                registry: self,
                map,
                location: &value.location,
                path,
            }),
            _ => Err(SchemaError {
                kind: SchemaErrorKind::NotMap,
                path,
                location: Some(Box::new(value.location.clone())),
            }),
        }
    }

    fn build_node(&self, node: &Node) -> Result<Box<dyn Validator>, SchemaError> {
        let tag = node.req_str("type")?;
        match self.constructors.get(tag) {
            Some(constructor) => constructor(node),
            None => Err(node.error(SchemaErrorKind::UnknownType {
                tag: tag.to_string(),
            })),
        }
    }

    /// A registry pre-loaded with every built-in validator type.
    pub fn with_builtins() -> Self {
        let mut registry = Self::empty();

        registry.register("bool", |_node| Ok(Box::new(Bool::new())));
        registry.register("non_empty", |_node| Ok(Box::new(NonEmpty::new())));
        registry.register("percentage", |_node| Ok(Box::new(Percentage::new())));

        registry.register("integer", |node| {
            let mut validator = Integer::new();
            if let Some(min) = node.opt_int("min")? {
                validator = validator.min(min);
            }
            if let Some(max) = node.opt_int("max")? {
                validator = validator.max(max);
            }
            if node.flag("positive")? {
                validator = validator.positive();
            }
            if node.flag("non_negative")? {
                validator = validator.non_negative();
            }
            if node.flag("negative")? {
                validator = validator.negative();
            }
            if node.flag("non_positive")? {
                validator = validator.non_positive();
            }
            Ok(Box::new(validator))
        });

        registry.register("float", |node| {
            let mut validator = Float::new();
            if let Some(min) = node.opt_f64("min")? {
                validator = validator.min(min);
            }
            if let Some(max) = node.opt_f64("max")? {
                validator = validator.max(max);
            }
            if node.flag("positive")? {
                validator = validator.positive();
            }
            if node.flag("non_negative")? {
                validator = validator.non_negative();
            }
            if node.flag("negative")? {
                validator = validator.negative();
            }
            if node.flag("non_positive")? {
                validator = validator.non_positive();
            }
            Ok(Box::new(validator))
        });

        registry.register("number", |node| {
            let mut validator = Number::new();
            if let Some(min) = node.opt_f64("min")? {
                validator = validator.min(min);
            }
            if let Some(max) = node.opt_f64("max")? {
                validator = validator.max(max);
            }
            if node.flag("positive")? {
                validator = validator.positive();
            }
            if node.flag("non_negative")? {
                validator = validator.non_negative();
            }
            if node.flag("negative")? {
                validator = validator.negative();
            }
            if node.flag("non_positive")? {
                validator = validator.non_positive();
            }
            Ok(Box::new(validator))
        });

        registry.register("string", |node| {
            let mut validator = Str::new();
            if let Some(min) = node.opt_usize("min_chars")? {
                validator = validator.min_chars(min);
            }
            if let Some(max) = node.opt_usize("max_chars")? {
                validator = validator.max_chars(max);
            }
            #[cfg(feature = "regex")]
            if let Some(pattern) = node.opt_str("regex")? {
                validator = match validator.regex(pattern) {
                    Ok(validator) => validator,
                    Err(message) => {
                        return Err(node.error(SchemaErrorKind::InvalidValue {
                            field: "regex".to_string(),
                            message,
                        }));
                    }
                };
            }
            Ok(Box::new(validator))
        });

        registry.register("list", |node| {
            let mut validator = List::new();
            if let Some(min) = node.opt_usize("min_len")? {
                validator = validator.min_len(min);
            }
            if let Some(max) = node.opt_usize("max_len")? {
                validator = validator.max_len(max);
            }
            if node.flag("unique")? {
                validator = validator.unique();
            }
            if let Some(items) = node.opt_child("items")? {
                validator = validator.items(items);
            }
            Ok(Box::new(validator))
        });

        registry.register("dynamic_map", |node| {
            let mut validator = DynamicMap::new();
            if let Some(min) = node.opt_usize("min_len")? {
                validator = validator.min_len(min);
            }
            if let Some(max) = node.opt_usize("max_len")? {
                validator = validator.max_len(max);
            }
            if let Some(values) = node.opt_child("values")? {
                validator = validator.values(values);
            }
            Ok(Box::new(validator))
        });

        registry.register("static_map", |node| {
            let mut validator = StaticMap::new();
            if node.flag("allow_unknown")? {
                validator = validator.allow_unknown();
            }
            if let Some(entry) = node.map.get("fields") {
                let fields = match &entry.value {
                    Value::Map(map) => map,
                    _ => return Err(node.wrong("fields", "a map")),
                };
                for (key, field_entry) in fields.entries() {
                    let mut path = node.path.clone();
                    path.push(Segment::Key("fields".to_string()));
                    path.push(Segment::Key(key.clone()));
                    let field_node = node.registry.node(field_entry, path)?;
                    let required = field_node.flag("required")?;
                    let field_validator = field_node.opt_child("validator")?;
                    validator = match (required, field_validator) {
                        (true, Some(inner)) => validator.required(key.clone(), inner),
                        (true, None) => validator.required_any(key.clone()),
                        (false, Some(inner)) => validator.optional(key.clone(), inner),
                        (false, None) => validator.optional_any(key.clone()),
                    };
                }
            }
            Ok(Box::new(validator))
        });

        registry.register("enum", |node| {
            let mut validator = Enum::new(node.values("values")?);
            if node.flag("case_insensitive")? {
                validator = validator.case_insensitive();
            }
            Ok(Box::new(validator))
        });

        registry.register("either", |node| {
            let first = node.child("first")?;
            let second = node.child("second")?;
            Ok(Box::new(Either::new(first, second)))
        });

        registry.register("host", |_node| Ok(Box::new(Host::new())));
        registry.register("email", |_node| Ok(Box::new(Email::new())));
        registry.register("socket_addr", |_node| Ok(Box::new(SocketAddr::new())));

        registry.register("domain", |node| {
            let mut validator = Domain::new();
            if node.flag("require_dot")? {
                validator = validator.require_dot();
            }
            Ok(Box::new(validator))
        });

        registry.register("port", |node| {
            let mut validator = Port::new();
            if node.flag("allow_zero")? {
                validator = validator.allow_zero();
            }
            if let Some(privileged) = node.opt_bool("privileged_ok")? {
                validator = validator.privileged_ok(privileged);
            }
            Ok(Box::new(validator))
        });

        registry.register("ip_addr", |node| {
            let mut validator = IpAddr::new();
            if node.flag("v4_only")? {
                validator = validator.v4_only();
            }
            if node.flag("v6_only")? {
                validator = validator.v6_only();
            }
            Ok(Box::new(validator))
        });

        registry.register("path", |node| {
            let mut validator = Path::new();
            if node.flag("absolute")? {
                validator = validator.absolute();
            }
            if node.flag("relative")? {
                validator = validator.relative();
            }
            for extension in node.str_list("extensions")? {
                validator = validator.extension(extension);
            }
            if node.flag("must_exist")? {
                validator = validator.must_exist();
            }
            if let Some(kind) = node.opt_str("kind")? {
                let kind = match kind {
                    "dir" => PathKind::Dir,
                    "file" => PathKind::File,
                    "symlink" => PathKind::Symlink,
                    other => {
                        return Err(node.error(SchemaErrorKind::InvalidValue {
                            field: "kind".to_string(),
                            message: format!("unknown kind `{other}`"),
                        }));
                    }
                };
                validator = validator.kind(kind);
            }
            if node.flag("readable")? {
                validator = validator.readable();
            }
            if node.flag("writable")? {
                validator = validator.writable();
            }
            Ok(Box::new(validator))
        });

        #[cfg(feature = "regex")]
        registry.register("regex_pattern", |_node| {
            Ok(Box::new(crate::RegexPattern::new()))
        });

        #[cfg(feature = "url")]
        registry.register("url", |node| {
            let mut validator = crate::Url::new();
            let schemes = node.str_list("schemes")?;
            if !schemes.is_empty() {
                validator = validator.schemes(schemes);
            }
            if node.flag("require_host")? {
                validator = validator.require_host();
            }
            Ok(Box::new(validator))
        });

        #[cfg(feature = "cidr")]
        registry.register("cidr", |_node| Ok(Box::new(crate::Cidr::new())));

        #[cfg(feature = "uuid")]
        registry.register("uuid", |_node| Ok(Box::new(crate::Uuid::new())));

        #[cfg(feature = "semver")]
        registry.register("semver", |_node| Ok(Box::new(crate::Semver::new())));

        #[cfg(feature = "encoding")]
        {
            registry.register("base64", |_node| Ok(Box::new(crate::Base64::new())));
            registry.register("hex", |_node| Ok(Box::new(crate::Hex::new())));
        }

        #[cfg(feature = "duration")]
        registry.register("duration", |node| {
            let mut validator = crate::Duration::new();
            if node.flag("millis")? {
                validator = validator.millis();
            }
            Ok(Box::new(validator))
        });

        #[cfg(feature = "bytesize")]
        registry.register("bytesize", |_node| Ok(Box::new(crate::ByteSize::new())));

        #[cfg(feature = "datetime")]
        {
            registry.register("datetime", |_node| Ok(Box::new(crate::DateTime::new())));
            registry.register("date", |_node| Ok(Box::new(crate::Date::new())));
        }

        registry
    }
}

/// Build a validator from a located schema node using a default [`Registry`].
pub fn build(value: &LocatedValue) -> Result<Box<dyn Validator>, SchemaError> {
    Registry::with_builtins().build(value)
}

/// Build a validator from a bare [`Value`] using a default [`Registry`].
pub fn build_value(value: &Value) -> Result<Box<dyn Validator>, SchemaError> {
    Registry::with_builtins().build_value(value)
}

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

    fn parse(json: &str) -> Value {
        let schema: SchemaValue = serde_json::from_str(json).unwrap();
        schema.into_value()
    }

    fn build_err(json: &str) -> SchemaError {
        match build_value(&parse(json)) {
            Ok(_) => panic!("expected a schema error"),
            Err(error) => error,
        }
    }

    #[test]
    fn builds_nested_schema_and_validates() {
        let schema = parse(
            r#"{
                "type": "static_map",
                "fields": {
                    "host": {"required": true,  "validator": {"type": "host"}},
                    "port": {"required": false, "validator": {"type": "port"}},
                    "tags": {"required": false, "validator": {
                        "type": "list", "unique": true,
                        "items": {"type": "string", "min_chars": 1}
                    }},
                    "mode": {"required": true, "validator": {
                        "type": "either",
                        "first":  {"type": "enum", "values": ["auto", "manual"]},
                        "second": {"type": "integer", "min": 0}
                    }}
                }
            }"#,
        );
        let validator = build_value(&schema).unwrap();

        let mut config = LocatedValue {
            value: parse(
                r#"{"host": "localhost", "port": "8080", "tags": ["a", "b"], "mode": "auto"}"#,
            ),
            location: schema_location(),
        };
        crate::validate(validator.as_ref(), &mut config).unwrap();

        // port string was coerced to an integer
        let port = config.value.as_map().unwrap().get("port").unwrap();
        assert_eq!(port.value, Value::Int(8080));
    }

    #[test]
    fn unknown_type_is_reported() {
        let error = build_err(r#"{"type": "nope"}"#);
        assert!(matches!(error.kind, SchemaErrorKind::UnknownType { .. }));
    }

    #[test]
    fn wrong_option_type_is_reported() {
        let error = build_err(r#"{"type": "integer", "min": "x"}"#);
        assert!(matches!(error.kind, SchemaErrorKind::WrongType { .. }));
    }

    #[test]
    fn missing_type_is_reported() {
        let error = build_err(r#"{"min": 1}"#);
        assert!(matches!(error.kind, SchemaErrorKind::MissingField { .. }));
    }

    #[test]
    fn nested_error_carries_path() {
        let error = build_err(r#"{"type": "list", "items": {"type": "integer", "min": "x"}}"#);
        assert_eq!(error.path, vec![Segment::Key("items".to_string())]);
    }

    #[test]
    fn custom_validator_can_be_registered() {
        let mut registry = Registry::with_builtins();
        registry.register("yes", |_node| Ok(Box::new(Bool::new())));
        let validator = registry.build_value(&parse(r#"{"type": "yes"}"#)).unwrap();
        assert!(validator.validate(&mut Value::Bool(true)).is_ok());
    }

    #[test]
    fn empty_registry_knows_nothing() {
        let error = match Registry::empty().build_value(&parse(r#"{"type": "bool"}"#)) {
            Ok(_) => panic!("expected a schema error"),
            Err(error) => error,
        };
        assert!(matches!(error.kind, SchemaErrorKind::UnknownType { .. }));
    }

    #[cfg(feature = "uuid")]
    #[test]
    fn feature_gated_tag_round_trips() {
        let validator = build_value(&parse(r#"{"type": "uuid"}"#)).unwrap();
        assert!(
            validator
                .validate(&mut Value::String(
                    "67e55044-10b1-426f-9247-bb680e5fe0c8".into()
                ))
                .is_ok()
        );
    }
}