fastxml 0.9.0

A fast, memory-efficient XML library with XPath and XSD validation support
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
//! Built-in XSD primitive type lexical and value-space validation.
//!
//! This module classifies a [`SimpleType`] into a [`PrimitiveKind`] by walking
//! the `base_type` chain, then provides [`PrimitiveKind::validate`] to enforce
//! the corresponding lexical and value-space rules.
//!
//! Per XSD 1.0 ยง4.3.6, every primitive type in the numeric / boolean /
//! date-time families carries a fixed `whiteSpace=collapse` facet. We
//! collapse-normalize the input before applying the lexical regex.

use std::sync::OnceLock;

use regex::Regex;

use crate::schema::types::{CompiledSchema, SimpleType, TypeDef};

/// Classification of an XSD built-in primitive (or derived) simple type for
/// lexical/value-space validation purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum PrimitiveKind {
    Boolean,
    Decimal,
    Float,
    Double,
    Integer,
    Long,
    Int,
    Short,
    Byte,
    NonNegativeInteger,
    PositiveInteger,
    NonPositiveInteger,
    NegativeInteger,
    UnsignedLong,
    UnsignedInt,
    UnsignedShort,
    UnsignedByte,
    Date,
    DateTime,
    Time,
    GYear,
    GYearMonth,
    GMonth,
    GMonthDay,
    GDay,
    Duration,
    HexBinary,
    Base64Binary,
    AnyUri,
    QName,
}

impl PrimitiveKind {
    /// Maps a built-in XSD type name (with or without the `xs:` prefix) to
    /// its primitive kind. The unprefixed form is what
    /// [`crate::schema::xsd::builtin::register_builtin_types`] stores in
    /// `SimpleType::name`, so this also matches values pulled off a
    /// `SimpleType` after one chain hop.
    pub fn from_type_name(name: &str) -> Option<Self> {
        let local = name.strip_prefix("xs:").unwrap_or(name);
        Some(match local {
            "boolean" => Self::Boolean,
            "decimal" => Self::Decimal,
            "float" => Self::Float,
            "double" => Self::Double,
            "integer" => Self::Integer,
            "long" => Self::Long,
            "int" => Self::Int,
            "short" => Self::Short,
            "byte" => Self::Byte,
            "nonNegativeInteger" => Self::NonNegativeInteger,
            "positiveInteger" => Self::PositiveInteger,
            "nonPositiveInteger" => Self::NonPositiveInteger,
            "negativeInteger" => Self::NegativeInteger,
            "unsignedLong" => Self::UnsignedLong,
            "unsignedInt" => Self::UnsignedInt,
            "unsignedShort" => Self::UnsignedShort,
            "unsignedByte" => Self::UnsignedByte,
            "date" => Self::Date,
            "dateTime" => Self::DateTime,
            "time" => Self::Time,
            "gYear" => Self::GYear,
            "gYearMonth" => Self::GYearMonth,
            "gMonth" => Self::GMonth,
            "gMonthDay" => Self::GMonthDay,
            "gDay" => Self::GDay,
            "duration" => Self::Duration,
            "hexBinary" => Self::HexBinary,
            "base64Binary" => Self::Base64Binary,
            "anyURI" => Self::AnyUri,
            "QName" => Self::QName,
            _ => return None,
        })
    }

    /// Resolves a [`SimpleType`] to its base built-in primitive kind by
    /// walking the `base_type` chain. Returns `None` if the chain does not
    /// terminate at a known primitive (notably the `xs:string` family is left
    /// out so empty content remains valid for `xs:string`).
    ///
    /// Handles both:
    /// - direct references like `<xs:element type="xs:int"/>` (the SimpleType
    ///   itself is `xs:int`'s built-in definition), and
    /// - anonymous restrictions like
    ///   `<xs:simpleType><xs:restriction base="xs:boolean"/></xs:simpleType>`
    ///   (the SimpleType is anonymous, base hops through the chain).
    pub fn resolve(schema: &CompiledSchema, simple: &SimpleType) -> Option<Self> {
        if let Some(kind) = Self::from_type_name(&simple.name) {
            return Some(kind);
        }

        let mut current = simple.base_type.clone()?;
        // Defensive bound on chain length to avoid pathological cycles or
        // very deep accidental recursion. XSD's built-in tree is shallow (at
        // most ~6 levels), so 16 is more than enough.
        for _ in 0..16 {
            if let Some(kind) = Self::from_type_name(&current) {
                return Some(kind);
            }
            let next = match schema.get_type(&current)? {
                TypeDef::Simple(s) => s,
                TypeDef::Complex(_) => return None,
            };
            if let Some(kind) = Self::from_type_name(&next.name) {
                return Some(kind);
            }
            current = next.base_type.clone()?;
        }
        None
    }

    /// Validates a value against this primitive type's lexical and value
    /// space. The input is whitespace-collapsed first (per XSD's fixed
    /// `whiteSpace=collapse` for these primitives).
    ///
    /// Kinds whose lexical space is not yet enforced fall through to
    /// `Ok(())`; callers can still rely on the regular `FacetValidator` to
    /// catch user-declared facets on those types.
    pub fn validate(&self, raw: &str) -> Result<(), PrimitiveError> {
        let normalized = collapse(raw);
        let v = normalized.as_str();
        match self {
            Self::Boolean => validate_with_regex(v, boolean_regex(), "boolean"),
            Self::Decimal => validate_with_regex(v, decimal_regex(), "decimal"),
            Self::Float => validate_with_regex(v, double_regex(), "float"),
            Self::Double => validate_with_regex(v, double_regex(), "double"),
            Self::Integer => validate_integer_lexical(v, "integer"),
            Self::Long => validate_bounded_integer(v, i64::MIN as i128, i64::MAX as i128, "long"),
            Self::Int => validate_bounded_integer(v, i32::MIN as i128, i32::MAX as i128, "int"),
            Self::Short => validate_bounded_integer(v, i16::MIN as i128, i16::MAX as i128, "short"),
            Self::Byte => validate_bounded_integer(v, i8::MIN as i128, i8::MAX as i128, "byte"),
            Self::NonNegativeInteger => {
                validate_signed_integer(v, "nonNegativeInteger", SignReq::NonNegative)
            }
            Self::PositiveInteger => {
                validate_signed_integer(v, "positiveInteger", SignReq::Positive)
            }
            Self::NonPositiveInteger => {
                validate_signed_integer(v, "nonPositiveInteger", SignReq::NonPositive)
            }
            Self::NegativeInteger => {
                validate_signed_integer(v, "negativeInteger", SignReq::Negative)
            }
            Self::UnsignedLong => {
                validate_signed_integer(v, "unsignedLong", SignReq::NonNegative)?;
                validate_unsigned_range(v, u64::MAX as u128, "unsignedLong")
            }
            Self::UnsignedInt => {
                validate_signed_integer(v, "unsignedInt", SignReq::NonNegative)?;
                validate_unsigned_range(v, u32::MAX as u128, "unsignedInt")
            }
            Self::UnsignedShort => {
                validate_signed_integer(v, "unsignedShort", SignReq::NonNegative)?;
                validate_unsigned_range(v, u16::MAX as u128, "unsignedShort")
            }
            Self::UnsignedByte => {
                validate_signed_integer(v, "unsignedByte", SignReq::NonNegative)?;
                validate_unsigned_range(v, u8::MAX as u128, "unsignedByte")
            }
            Self::Date => validate_date(v),
            Self::DateTime => validate_datetime(v),
            Self::GYear => validate_gyear(v),
            // Lexical space not yet enforced โ€” accept (FacetValidator still
            // handles any user-declared facets on these types).
            Self::Time
            | Self::GYearMonth
            | Self::GMonth
            | Self::GMonthDay
            | Self::GDay
            | Self::Duration
            | Self::HexBinary
            | Self::Base64Binary
            | Self::AnyUri
            | Self::QName => Ok(()),
        }
    }
}

/// Errors raised by [`PrimitiveKind::validate`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PrimitiveError {
    /// Value does not match the type's lexical form.
    InvalidLexical {
        /// XSD primitive name (e.g., `"integer"`).
        kind: &'static str,
        /// The offending value.
        value: String,
    },
    /// Value's lexical form is valid but lies outside the type's value space
    /// (range, sign requirement, calendar validity, โ€ฆ).
    OutOfRange {
        /// The offending value.
        value: String,
        /// Human-readable constraint that was violated.
        constraint: &'static str,
    },
}

impl std::fmt::Display for PrimitiveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidLexical { kind, value } => {
                write!(f, "'{}' is not a valid xs:{}", value, kind)
            }
            Self::OutOfRange { value, constraint } => {
                write!(f, "'{}' {}", value, constraint)
            }
        }
    }
}

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

// ---------------------------------------------------------------------------
// Lexical regexes (lazily compiled, shared across validators).
// ---------------------------------------------------------------------------

/// `xs:boolean` lexical space (XSD 1.0 ยง3.2.2): exactly one of
/// `true | false | 1 | 0` after `whiteSpace=collapse` normalization.
fn boolean_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| Regex::new(r"^(?:true|false|1|0)$").unwrap())
}

/// `xs:integer` family lexical space (XSD 1.0 ยง3.3.13):
/// `[+-]?[0-9]+`. No decimal point, no exponent, arbitrary precision.
/// Per-subtype value-space limits (e.g., 32-bit range for `xs:int`, sign
/// requirement for `xs:nonNegativeInteger`) are applied on top by
/// [`validate_bounded_integer`] / [`validate_signed_integer`].
fn integer_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| Regex::new(r"^[+-]?[0-9]+$").unwrap())
}

/// `xs:decimal` lexical space (XSD 1.0 ยง3.2.3): an optional sign followed by
/// either one or more digits with an optional fractional part (`42`, `42.`,
/// `42.5`), or a leading `.` followed by one or more digits (`.5`). No
/// exponent โ€” that's `xs:double` / `xs:float`.
fn decimal_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| Regex::new(r"^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$").unwrap())
}

/// `xs:double` and `xs:float` share this lexical space (XSD 1.0 ยง3.2.5,
/// ยง3.2.4): a decimal numeral optionally followed by an `e`/`E` exponent, or
/// one of the special literals `INF` / `-INF` / `NaN` (case-sensitive). We
/// also accept `+INF`, which XSD doesn't list but is widely produced.
fn double_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| {
        Regex::new(r"^(?:[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|[+-]?INF|NaN)$")
            .unwrap()
    })
}

/// `xs:date` lexical space (XSD 1.0 ยง3.2.9): `-?YYYY-MM-DD(Z|[+-]HH:MM)?`
/// with the year at least 4 digits. Month / day range and calendar
/// (leap-year) validity are enforced on top in [`validate_date`].
fn date_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| {
        Regex::new(r"^(-?)([0-9]{4,})-([0-9]{2})-([0-9]{2})(Z|[+-][0-9]{2}:[0-9]{2})?$").unwrap()
    })
}

/// `xs:gYear` lexical space (XSD 1.0 ยง3.2.11): `-?YYYY(Z|[+-]HH:MM)?`,
/// year at least 4 digits, no further fields.
fn gyear_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| Regex::new(r"^(-?)([0-9]{4,})(Z|[+-][0-9]{2}:[0-9]{2})?$").unwrap())
}

/// `xs:dateTime` lexical space (XSD 1.0 ยง3.2.7): `xs:date` body (without
/// timezone) + uppercase `T` + `HH:MM:SS(.fff)?` + optional
/// `(Z|[+-]HH:MM)`. Seconds are mandatory; the separator must be `T`, not a
/// space. Calendar / clock-range validity is enforced in
/// [`validate_datetime`].
fn datetime_regex() -> &'static Regex {
    static R: OnceLock<Regex> = OnceLock::new();
    R.get_or_init(|| {
        Regex::new(
            r"^(-?)([0-9]{4,})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})?$",
        )
        .unwrap()
    })
}

// ---------------------------------------------------------------------------
// Shared validators
// ---------------------------------------------------------------------------

fn validate_with_regex(v: &str, regex: &Regex, kind: &'static str) -> Result<(), PrimitiveError> {
    if regex.is_match(v) {
        Ok(())
    } else {
        Err(PrimitiveError::InvalidLexical {
            kind,
            value: v.to_string(),
        })
    }
}

fn validate_integer_lexical(v: &str, kind: &'static str) -> Result<(), PrimitiveError> {
    validate_with_regex(v, integer_regex(), kind)
}

fn validate_bounded_integer(
    v: &str,
    min: i128,
    max: i128,
    kind: &'static str,
) -> Result<(), PrimitiveError> {
    validate_integer_lexical(v, kind)?;
    // i128::from_str accepts a leading `+`, but be defensive.
    let stripped = v.strip_prefix('+').unwrap_or(v);
    let parsed: i128 = stripped.parse().map_err(|_| PrimitiveError::OutOfRange {
        value: v.to_string(),
        constraint: "is outside the type's representable range",
    })?;
    if parsed < min || parsed > max {
        Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: "is outside the type's representable range",
        })
    } else {
        Ok(())
    }
}

fn validate_unsigned_range(v: &str, max: u128, _kind: &'static str) -> Result<(), PrimitiveError> {
    // Caller has already enforced SignReq::NonNegative, so the only sign char
    // we might still see is a leading `+` (u128::from_str rejects).
    let stripped = v.strip_prefix('+').unwrap_or(v);
    let parsed: u128 = stripped.parse().map_err(|_| PrimitiveError::OutOfRange {
        value: v.to_string(),
        constraint: "is outside the type's representable range",
    })?;
    if parsed > max {
        Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: "is outside the type's representable range",
        })
    } else {
        Ok(())
    }
}

#[derive(Debug, Clone, Copy)]
enum SignReq {
    /// `value >= 0`
    NonNegative,
    /// `value >= 1`
    Positive,
    /// `value <= 0`
    NonPositive,
    /// `value <= -1`
    Negative,
}

fn validate_signed_integer(
    v: &str,
    kind: &'static str,
    requirement: SignReq,
) -> Result<(), PrimitiveError> {
    validate_integer_lexical(v, kind)?;

    // Classify the value as one of {zero, positive, negative} from its
    // lexical form alone โ€” this works for arbitrary-precision integers
    // (xs:nonNegativeInteger etc. have no representable-range cap).
    let (negative, digits) = if let Some(rest) = v.strip_prefix('-') {
        (true, rest)
    } else {
        let rest = v.strip_prefix('+').unwrap_or(v);
        (false, rest)
    };
    let all_zero = digits.bytes().all(|b| b == b'0');
    let is_positive = !negative && !all_zero;
    let is_negative = negative && !all_zero;

    let ok = match requirement {
        SignReq::NonNegative => !is_negative,
        SignReq::Positive => is_positive,
        SignReq::NonPositive => !is_positive,
        SignReq::Negative => is_negative,
    };

    if ok {
        Ok(())
    } else {
        Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: match requirement {
                SignReq::NonNegative => "must be greater than or equal to 0",
                SignReq::Positive => "must be greater than or equal to 1",
                SignReq::NonPositive => "must be less than or equal to 0",
                SignReq::Negative => "must be less than or equal to -1",
            },
        })
    }
}

// ---------------------------------------------------------------------------
// Date / time validators
// ---------------------------------------------------------------------------

fn validate_date(v: &str) -> Result<(), PrimitiveError> {
    let caps = date_regex()
        .captures(v)
        .ok_or_else(|| PrimitiveError::InvalidLexical {
            kind: "date",
            value: v.to_string(),
        })?;
    let sign_neg = !caps.get(1).map(|m| m.as_str()).unwrap_or("").is_empty();
    let year: i64 =
        caps.get(2)
            .unwrap()
            .as_str()
            .parse()
            .map_err(|_| PrimitiveError::InvalidLexical {
                kind: "date",
                value: v.to_string(),
            })?;
    let year = if sign_neg { -year } else { year };
    let month: u32 = caps.get(3).unwrap().as_str().parse().unwrap();
    let day: u32 = caps.get(4).unwrap().as_str().parse().unwrap();

    validate_year_month_day(year, month, day, v)?;
    if let Some(tz) = caps.get(5) {
        validate_timezone(tz.as_str(), v)?;
    }
    Ok(())
}

fn validate_gyear(v: &str) -> Result<(), PrimitiveError> {
    let caps = gyear_regex()
        .captures(v)
        .ok_or_else(|| PrimitiveError::InvalidLexical {
            kind: "gYear",
            value: v.to_string(),
        })?;
    // We only need to confirm the year is parseable; XSD 1.0 disallows year 0
    // but tests don't exercise that and we'd risk false negatives on data
    // that downstream consumers accept.
    let _year: i64 =
        caps.get(2)
            .unwrap()
            .as_str()
            .parse()
            .map_err(|_| PrimitiveError::InvalidLexical {
                kind: "gYear",
                value: v.to_string(),
            })?;
    if let Some(tz) = caps.get(3) {
        validate_timezone(tz.as_str(), v)?;
    }
    Ok(())
}

fn validate_datetime(v: &str) -> Result<(), PrimitiveError> {
    let caps = datetime_regex()
        .captures(v)
        .ok_or_else(|| PrimitiveError::InvalidLexical {
            kind: "dateTime",
            value: v.to_string(),
        })?;
    let sign_neg = !caps.get(1).map(|m| m.as_str()).unwrap_or("").is_empty();
    let year: i64 =
        caps.get(2)
            .unwrap()
            .as_str()
            .parse()
            .map_err(|_| PrimitiveError::InvalidLexical {
                kind: "dateTime",
                value: v.to_string(),
            })?;
    let year = if sign_neg { -year } else { year };
    let month: u32 = caps.get(3).unwrap().as_str().parse().unwrap();
    let day: u32 = caps.get(4).unwrap().as_str().parse().unwrap();
    let hour: u32 = caps.get(5).unwrap().as_str().parse().unwrap();
    let minute: u32 = caps.get(6).unwrap().as_str().parse().unwrap();
    let second: u32 = caps.get(7).unwrap().as_str().parse().unwrap();

    validate_year_month_day(year, month, day, v)?;

    // hh:mm:ss range. XSD permits 24:00:00 for end-of-day; otherwise hour
    // must be 0โ€“23, minute 0โ€“59, second 0โ€“60 (leap second allowed).
    let end_of_day = hour == 24 && minute == 0 && second == 0;
    if !end_of_day && hour > 23 {
        return Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: "hour-of-day must be 00-23 (or 24:00:00)",
        });
    }
    if minute > 59 {
        return Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: "minute must be 00-59",
        });
    }
    if second > 60 {
        return Err(PrimitiveError::OutOfRange {
            value: v.to_string(),
            constraint: "second must be 00-60",
        });
    }

    if let Some(tz) = caps.get(8) {
        validate_timezone(tz.as_str(), v)?;
    }
    Ok(())
}

fn validate_year_month_day(
    year: i64,
    month: u32,
    day: u32,
    raw: &str,
) -> Result<(), PrimitiveError> {
    if !(1..=12).contains(&month) {
        return Err(PrimitiveError::OutOfRange {
            value: raw.to_string(),
            constraint: "month must be between 01 and 12",
        });
    }
    let max_day = match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if is_leap_year(year) {
                29
            } else {
                28
            }
        }
        _ => unreachable!(),
    };
    if !(1..=max_day).contains(&day) {
        return Err(PrimitiveError::OutOfRange {
            value: raw.to_string(),
            constraint: "day is not valid for the given month",
        });
    }
    Ok(())
}

fn is_leap_year(year: i64) -> bool {
    if year % 400 == 0 {
        true
    } else if year % 100 == 0 {
        false
    } else {
        year % 4 == 0
    }
}

fn validate_timezone(tz: &str, raw: &str) -> Result<(), PrimitiveError> {
    if tz == "Z" {
        return Ok(());
    }
    // Regex guarantees the shape `[+-]HH:MM`; just enforce the range.
    let hh: u32 = tz[1..3]
        .parse()
        .map_err(|_| PrimitiveError::InvalidLexical {
            kind: "timezone",
            value: tz.to_string(),
        })?;
    let mm: u32 = tz[4..6]
        .parse()
        .map_err(|_| PrimitiveError::InvalidLexical {
            kind: "timezone",
            value: tz.to_string(),
        })?;
    if mm > 59 {
        return Err(PrimitiveError::OutOfRange {
            value: raw.to_string(),
            constraint: "timezone minute offset must be 00-59",
        });
    }
    // XSD timezone offset range is -14:00 .. +14:00.
    if hh > 14 || (hh == 14 && mm > 0) {
        return Err(PrimitiveError::OutOfRange {
            value: raw.to_string(),
            constraint: "timezone offset out of range (allowed: -14:00..+14:00)",
        });
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Whitespace collapse helper
// ---------------------------------------------------------------------------

/// Collapse-normalizes a string per XSD `whiteSpace=collapse`:
/// every run of whitespace becomes a single space, and leading/trailing
/// whitespace is stripped. Returns an owned `String` so callers can use it
/// without worrying about the borrow lifetime of the input.
fn collapse(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut prev_was_space = true; // start true to trim leading whitespace
    for ch in input.chars() {
        if ch.is_whitespace() {
            if !prev_was_space {
                out.push(' ');
                prev_was_space = true;
            }
        } else {
            out.push(ch);
            prev_was_space = false;
        }
    }
    if out.ends_with(' ') {
        out.pop();
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::xsd::builtin::register_builtin_types;

    fn schema() -> CompiledSchema {
        let mut s = CompiledSchema::new();
        register_builtin_types(&mut s);
        s
    }

    fn simple_with_base(base: &str) -> SimpleType {
        let mut st = SimpleType::new("");
        st.base_type = Some(base.to_string());
        st
    }

    // ---- PrimitiveKind::from_type_name ----

    #[test]
    fn from_type_name_accepts_prefixed_and_unprefixed() {
        assert_eq!(
            PrimitiveKind::from_type_name("xs:boolean"),
            Some(PrimitiveKind::Boolean)
        );
        assert_eq!(
            PrimitiveKind::from_type_name("boolean"),
            Some(PrimitiveKind::Boolean)
        );
        assert_eq!(
            PrimitiveKind::from_type_name("xs:nonNegativeInteger"),
            Some(PrimitiveKind::NonNegativeInteger)
        );
        assert_eq!(PrimitiveKind::from_type_name("string"), None);
        assert_eq!(PrimitiveKind::from_type_name("anyType"), None);
    }

    // ---- PrimitiveKind::resolve via base chain ----

    #[test]
    fn resolve_via_built_in_chain() {
        let s = schema();
        // The built-in xs:int has name="int" base="xs:long" โ†’ walk hits "int" first.
        let int_def = match s.get_type("xs:int").unwrap() {
            TypeDef::Simple(simple) => simple.clone(),
            _ => panic!("xs:int should be SimpleType"),
        };
        assert_eq!(
            PrimitiveKind::resolve(&s, &int_def),
            Some(PrimitiveKind::Int)
        );
    }

    #[test]
    fn resolve_anonymous_restriction_of_boolean() {
        // mirrors XSD_BOOL_RESTRICTION in validation_primitive_test.rs
        let s = schema();
        let anon = simple_with_base("xs:boolean");
        assert_eq!(
            PrimitiveKind::resolve(&s, &anon),
            Some(PrimitiveKind::Boolean)
        );
    }

    #[test]
    fn resolve_returns_none_for_string_derivatives() {
        let s = schema();
        // xs:NCName chain bottoms out at xs:string, which we deliberately do
        // NOT map to a PrimitiveKind so empty xs:string content stays valid.
        let ncname = match s.get_type("xs:NCName").unwrap() {
            TypeDef::Simple(simple) => simple.clone(),
            _ => panic!("xs:NCName should be SimpleType"),
        };
        assert_eq!(PrimitiveKind::resolve(&s, &ncname), None);
    }

    // ---- Boolean ----

    #[test]
    fn boolean_accepts_canonical_literals() {
        for v in ["true", "false", "1", "0"] {
            assert!(PrimitiveKind::Boolean.validate(v).is_ok(), "{v}");
        }
    }

    #[test]
    fn boolean_rejects_other_forms() {
        for v in ["True", "FALSE", "yes", "2", "", "  "] {
            assert!(PrimitiveKind::Boolean.validate(v).is_err(), "{v}");
        }
    }

    #[test]
    fn boolean_collapses_whitespace_before_match() {
        // collapse-normalization strips surrounding whitespace so " true " is valid
        assert!(PrimitiveKind::Boolean.validate(" true ").is_ok());
        assert!(PrimitiveKind::Boolean.validate("\ntrue\n").is_ok());
    }

    // ---- Integer family ----

    #[test]
    fn integer_lexical_pass() {
        for v in ["0", "42", "-42", "+42"] {
            assert!(PrimitiveKind::Integer.validate(v).is_ok(), "{v}");
        }
    }

    #[test]
    fn integer_lexical_fail() {
        for v in ["1.5", "abc", "", "1e2", "+"] {
            assert!(PrimitiveKind::Integer.validate(v).is_err(), "{v}");
        }
    }

    #[test]
    fn int_enforces_32bit_range() {
        assert!(PrimitiveKind::Int.validate("-2147483648").is_ok());
        assert!(PrimitiveKind::Int.validate("2147483647").is_ok());
        assert!(PrimitiveKind::Int.validate("2147483648").is_err());
        assert!(PrimitiveKind::Int.validate("-2147483649").is_err());
    }

    #[test]
    fn non_negative_integer_sign_check() {
        assert!(PrimitiveKind::NonNegativeInteger.validate("0").is_ok());
        assert!(PrimitiveKind::NonNegativeInteger.validate("100").is_ok());
        assert!(PrimitiveKind::NonNegativeInteger.validate("+0").is_ok());
        assert!(PrimitiveKind::NonNegativeInteger.validate("-0").is_ok());
        assert!(PrimitiveKind::NonNegativeInteger.validate("-1").is_err());
    }

    #[test]
    fn positive_integer_sign_check() {
        assert!(PrimitiveKind::PositiveInteger.validate("1").is_ok());
        assert!(PrimitiveKind::PositiveInteger.validate("+1").is_ok());
        assert!(PrimitiveKind::PositiveInteger.validate("0").is_err());
        assert!(PrimitiveKind::PositiveInteger.validate("-0").is_err());
        assert!(PrimitiveKind::PositiveInteger.validate("-1").is_err());
    }

    // ---- Decimal ----

    #[test]
    fn decimal_lexical_pass() {
        for v in ["0", "1.5", "-1.5", ".5", "1.", "+1.5"] {
            assert!(PrimitiveKind::Decimal.validate(v).is_ok(), "{v}");
        }
    }

    #[test]
    fn decimal_lexical_fail() {
        for v in ["1e2", "abc", "1.5.6", "", "+", ".", "1.2.3"] {
            assert!(PrimitiveKind::Decimal.validate(v).is_err(), "{v}");
        }
    }

    // ---- Double / Float ----

    #[test]
    fn double_lexical_pass() {
        for v in ["0", "1.5", "-1.5e-3", "1.2E10", "INF", "-INF", "NaN", ".5"] {
            assert!(PrimitiveKind::Double.validate(v).is_ok(), "{v}");
        }
    }

    #[test]
    fn double_lexical_fail() {
        for v in ["abc", "1.5.6", "inf", "nan", ""] {
            assert!(PrimitiveKind::Double.validate(v).is_err(), "{v}");
        }
    }

    #[test]
    fn float_shares_double_lexical_space() {
        assert!(PrimitiveKind::Float.validate("3.14").is_ok());
        assert!(PrimitiveKind::Float.validate("abc").is_err());
    }

    // ---- Date ----

    #[test]
    fn date_canonical_forms() {
        assert!(PrimitiveKind::Date.validate("2026-05-28").is_ok());
        assert!(PrimitiveKind::Date.validate("2026-05-28Z").is_ok());
        assert!(PrimitiveKind::Date.validate("2026-05-28+09:00").is_ok());
        assert!(PrimitiveKind::Date.validate("2026-05-28-05:00").is_ok());
    }

    #[test]
    fn date_invalid_forms() {
        for v in [
            "2026-13-01",
            "2026-02-30",
            "26-05-28",
            "2026/05/28",
            "abc",
            "",
        ] {
            assert!(PrimitiveKind::Date.validate(v).is_err(), "{v}");
        }
    }

    #[test]
    fn date_leap_year_handling() {
        assert!(PrimitiveKind::Date.validate("2024-02-29").is_ok()); // leap
        assert!(PrimitiveKind::Date.validate("2023-02-29").is_err()); // non-leap
        assert!(PrimitiveKind::Date.validate("2000-02-29").is_ok()); // div 400
        assert!(PrimitiveKind::Date.validate("1900-02-29").is_err()); // div 100 not 400
    }

    // ---- gYear ----

    #[test]
    fn gyear_canonical_forms() {
        assert!(PrimitiveKind::GYear.validate("2026").is_ok());
        assert!(PrimitiveKind::GYear.validate("2026Z").is_ok());
        assert!(PrimitiveKind::GYear.validate("2026+09:00").is_ok());
    }

    #[test]
    fn gyear_invalid_forms() {
        for v in ["26", "2026-05", "abc", ""] {
            assert!(PrimitiveKind::GYear.validate(v).is_err(), "{v}");
        }
    }

    // ---- DateTime ----

    #[test]
    fn datetime_canonical_forms() {
        assert!(
            PrimitiveKind::DateTime
                .validate("2026-05-28T10:30:00")
                .is_ok()
        );
        assert!(
            PrimitiveKind::DateTime
                .validate("2026-05-28T10:30:00.123")
                .is_ok()
        );
        assert!(
            PrimitiveKind::DateTime
                .validate("2026-05-28T10:30:00Z")
                .is_ok()
        );
        assert!(
            PrimitiveKind::DateTime
                .validate("2026-05-28T10:30:00+09:00")
                .is_ok()
        );
    }

    #[test]
    fn datetime_invalid_forms() {
        for v in [
            "2026-05-28 10:30:00", // space separator
            "2026-05-28T10:30",    // missing seconds
            "2026-13-01T10:30:00", // bad month
            "abc",
            "",
        ] {
            assert!(PrimitiveKind::DateTime.validate(v).is_err(), "{v}");
        }
    }
}