xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
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
// ============================================================================
// Helper Functions
// ============================================================================

fn parse_optional_attr<T, F>(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
    parse: F,
) -> SchemaResult<Option<T>>
where
    F: FnOnce(&str) -> Result<T, String>,
{
    match attrs.get_value_by_name(name_table, name) {
        Some(value) => {
            let parsed = parse(value).map_err(|err| {
                SchemaError::structural(
                    "ct-props-correct",
                    format!("Invalid value for attribute '{}': {}", name, err),
                    None,
                )
            })?;
            Ok(Some(parsed))
        }
        None => Ok(None),
    }
}

fn validate_attr_value<T, F>(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
    parse: F,
) -> SchemaResult<()>
where
    F: FnOnce(&str) -> Result<T, String>,
{
    parse_optional_attr(attrs, name_table, name, parse).map(|_| ())
}

fn parse_optional_bool_attr(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<Option<bool>> {
    parse_optional_attr(attrs, name_table, name, parse_boolean)
}

fn parse_bool_attr_default(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
    default: bool,
) -> SchemaResult<bool> {
    Ok(parse_optional_bool_attr(attrs, name_table, name)?.unwrap_or(default))
}

fn parse_occurs_attr_raw(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<Option<Option<u32>>> {
    match attrs.get_value_by_name(name_table, name) {
        Some(value) => {
            let parsed = parse_occurs(value).map_err(|err| {
                SchemaError::structural(
                    "ct-props-correct",
                    format!("Invalid value for attribute '{}': {}", name, err),
                    None,
                )
            })?;
            Ok(Some(parsed))
        }
        None => Ok(None),
    }
}

fn parse_min_occurs_attr(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<u32> {
    match parse_occurs_attr_raw(attrs, name_table, name)? {
        None => Ok(1),
        Some(Some(value)) => Ok(value),
        Some(None) => Err(SchemaError::structural(
            "ct-props-correct",
            format!("Invalid value for attribute '{}': 'unbounded'", name),
            None,
        )),
    }
}

fn parse_max_occurs_attr(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<Option<u32>> {
    match parse_occurs_attr_raw(attrs, name_table, name)? {
        None => Ok(Some(1)),
        Some(Some(value)) => Ok(Some(value)),
        Some(None) => Ok(None),
    }
}

fn parse_process_contents_value(value: &str) -> Result<ProcessContents, String> {
    match value {
        "strict" => Ok(ProcessContents::Strict),
        "lax" => Ok(ProcessContents::Lax),
        "skip" => Ok(ProcessContents::Skip),
        _ => Err(format!("Invalid processContents value: '{}'", value)),
    }
}

#[cfg(feature = "xsd11")]
fn parse_open_content_mode(value: &str) -> Result<OpenContentMode, String> {
    match value {
        "none" => Ok(OpenContentMode::None),
        "interleave" => Ok(OpenContentMode::Interleave),
        "suffix" => Ok(OpenContentMode::Suffix),
        _ => Err(format!("Invalid open content mode: '{}'", value)),
    }
}

fn parse_process_contents_attr(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<ProcessContents> {
    match parse_optional_attr(attrs, name_table, name, parse_process_contents_value)? {
        Some(value) => Ok(value),
        None => Ok(ProcessContents::Strict),
    }
}

#[cfg(feature = "xsd11")]
fn parse_open_content_mode_attr(
    attrs: &AttributeMap,
    name_table: &NameTable,
    name: &str,
) -> SchemaResult<OpenContentMode> {
    match parse_optional_attr(attrs, name_table, name, parse_open_content_mode)? {
        Some(value) => Ok(value),
        None => Ok(OpenContentMode::Interleave),
    }
}

/// Parse a `block`/`final`-style attribute. `None` = attribute absent; caller
/// decides whether to inherit a document-level default. `Some(set)` = present
/// (including the empty value `""`, which explicitly overrides any default).
fn parse_derivation_set_opt(value: Option<&str>) -> SchemaResult<Option<DerivationSet>> {
    let Some(value) = value else {
        return Ok(None);
    };

    if value == "#all" {
        return Ok(Some(DerivationSet::ALL));
    }

    let mut set = DerivationSet::empty();
    for token in value.split_whitespace() {
        match token {
            "extension" => set |= DerivationSet::EXTENSION,
            "restriction" => set |= DerivationSet::RESTRICTION,
            "list" => set |= DerivationSet::LIST,
            "union" => set |= DerivationSet::UNION,
            "substitution" => set |= DerivationSet::SUBSTITUTION,
            _ => {
                return Err(SchemaError::structural(
                    "sch-props-correct",
                    format!("Invalid derivation method: '{}'", token),
                    None,
                ));
            }
        }
    }

    Ok(Some(set))
}

/// Parse a derivation set, collapsing absent into empty (caller has no
/// None-vs-empty distinction to make).
fn parse_derivation_set(value: Option<&str>) -> SchemaResult<DerivationSet> {
    Ok(parse_derivation_set_opt(value)?.unwrap_or_default())
}

/// Parse a QName reference with namespace resolution
///
/// Resolves the prefix to a namespace URI using the provided namespace context snapshot.
fn parse_qname_ref(
    value: &str,
    name_table: &NameTable,
    ns_snapshot: &NamespaceContextSnapshot,
) -> SchemaResult<QNameRef> {
    // xs:QName has whiteSpace=collapse.
    let value = value.trim();
    let (local, prefix) = if let Some(pos) = value.find(':') {
        let prefix = &value[..pos];
        let local = &value[pos + 1..];
        (local, Some(prefix))
    } else {
        (value, None)
    };

    // Validate QName lexical form: both prefix and local part must be non-empty
    // NCNames (no colons allowed in either part).
    if local.is_empty() || local.contains(':') {
        return Err(SchemaError::structural(
            "src-resolve",
            format!("Invalid QName: '{}'", value),
            None,
        ));
    }
    if let Some(p) = prefix {
        if p.is_empty() {
            return Err(SchemaError::structural(
                "src-resolve",
                format!("Invalid QName: '{}'", value),
                None,
            ));
        }
    }

    // Use add() (intern-or-get) rather than get() so that forward-referenced
    // names are interned immediately. Resolution of whether the name actually
    // exists happens later in the reference-resolution phase.
    let local_name = name_table.add(local);

    let prefix_id = prefix.and_then(|p| name_table.get(p));

    // Resolve namespace immediately using the snapshot
    let namespace = if let Some(pid) = prefix_id {
        ns_snapshot.resolve_prefix(pid)
    } else {
        // For unprefixed QNames in XSD attribute values (type, ref, base, etc.),
        // use the default namespace if one is declared. Per XML namespace rules,
        // an unprefixed QName resolves using the default namespace in scope.
        ns_snapshot.default_namespace()
    };

    Ok(QNameRef {
        prefix: prefix_id,
        local_name,
        namespace,
    })
}

/// Parse a list of QName references with namespace resolution
fn parse_qname_list(
    value: &str,
    name_table: &NameTable,
    ns_snapshot: &NamespaceContextSnapshot,
) -> SchemaResult<Vec<QNameRef>> {
    value
        .split_whitespace()
        .map(|s| parse_qname_ref(s, name_table, ns_snapshot))
        .collect()
}

/// Parse namespace constraint for wildcards
fn parse_namespace_constraint(
    value: Option<&str>,
    name_table: &NameTable,
) -> SchemaResult<WildcardNamespace> {
    let Some(value) = value else {
        return Ok(WildcardNamespace::Any);
    };

    match value {
        "##any" => Ok(WildcardNamespace::Any),
        "##other" => Ok(WildcardNamespace::Other),
        "##targetNamespace" => Ok(WildcardNamespace::TargetNamespace),
        "##local" => Ok(WildcardNamespace::Local),
        _ => {
            let mut namespaces = Vec::new();
            for s in value.split_whitespace() {
                match s {
                    "##targetNamespace" => namespaces.push(NamespaceToken::TargetNamespace),
                    "##local" => namespaces.push(NamespaceToken::Local),
                    "##any" | "##other" => {
                        return Err(SchemaError::structural(
                            "src-wildcard",
                            format!("'{}' must appear alone, not in a list namespace constraint", s),
                            None,
                        ))
                    }
                    s if s.starts_with("##") => {
                        return Err(SchemaError::structural(
                            "src-wildcard",
                            format!("Unrecognized namespace token '{}'; expected ##any, ##other, ##targetNamespace, ##local, or a URI", s),
                            None,
                        ))
                    }
                    _ => namespaces.push(NamespaceToken::Uri(name_table.add(s))),
                }
            }
            Ok(WildcardNamespace::List(namespaces))
        }
    }
}

/// Parse notNamespace attribute (XSD 1.1)
#[cfg(feature = "xsd11")]
pub(crate) fn parse_not_namespace(
    value: Option<&str>,
    name_table: &NameTable,
) -> Vec<NamespaceToken> {
    let Some(value) = value else {
        return Vec::new();
    };
    value
        .split_whitespace()
        .map(|s| match s {
            "##targetNamespace" => NamespaceToken::TargetNamespace,
            "##local" => NamespaceToken::Local,
            _ => NamespaceToken::Uri(name_table.add(s)),
        })
        .collect()
}

/// Parse notQName attribute (XSD 1.1).
///
/// Validates the QName lexical form per Datatypes ยง3.3.18 and rejects
/// undeclared prefixes per ยง3.10.6.1 rule 1 (a wildcard's properties must
/// match the property tableau, including QName lexical validity). The
/// per-name namespace-allowed check from ยง3.10.6.1 rule 4 is applied after
/// assembly when the wildcard's resolved namespace constraint is available
/// (see `validate_wildcard_disallowed_names`).
#[cfg(feature = "xsd11")]
pub(crate) fn parse_not_qname(
    value: Option<&str>,
    name_table: &NameTable,
    ns_snapshot: &NamespaceContextSnapshot,
    is_element_wildcard: bool,
) -> SchemaResult<Vec<NotQNameItem>> {
    let Some(value) = value else {
        return Ok(Vec::new());
    };
    let mut items = Vec::new();
    for s in value.split_whitespace() {
        match s {
            "##defined" => items.push(NotQNameItem::Defined),
            "##definedSibling" => {
                if !is_element_wildcard {
                    // ยง3.10.6.1 rule 5: attribute wildcards must not use sibling.
                    return Err(SchemaError::structural(
                        "w-props-correct",
                        "##definedSibling is not allowed on xs:anyAttribute".to_string(),
                        None,
                    ));
                }
                items.push(NotQNameItem::DefinedSibling);
            }
            _ => {
                // Validate QName lexical form: split on the FIRST colon and
                // require that both parts are non-empty NCNames with no
                // additional colons. This rejects ":name", "name:", and
                // "a:b:c" forms (covers wild038 / wild039).
                let (prefix, local) = match s.split_once(':') {
                    Some((p, l)) => (Some(p), l),
                    None => (None, s),
                };
                if local.is_empty() || local.contains(':') {
                    return Err(SchemaError::structural(
                        "w-props-correct",
                        format!("Invalid QName '{}' in notQName", s),
                        None,
                    ));
                }
                if let Some(p) = prefix {
                    if p.is_empty() {
                        return Err(SchemaError::structural(
                            "w-props-correct",
                            format!("Invalid QName '{}' in notQName", s),
                            None,
                        ));
                    }
                }

                let namespace = if let Some(p) = prefix {
                    // Reject undeclared prefixes (covers wild036 / wild037).
                    let prefix_id = match name_table.get(p) {
                        Some(id) => id,
                        None => {
                            return Err(SchemaError::structural(
                                "w-props-correct",
                                format!(
                                    "Undeclared prefix '{}' in notQName entry '{}'",
                                    p, s
                                ),
                                None,
                            ));
                        }
                    };
                    match ns_snapshot.resolve_prefix(prefix_id) {
                        Some(ns) => Some(ns),
                        None => {
                            return Err(SchemaError::structural(
                                "w-props-correct",
                                format!(
                                    "Undeclared prefix '{}' in notQName entry '{}'",
                                    p, s
                                ),
                                None,
                            ));
                        }
                    }
                } else {
                    // Unprefixed: per the QName datatype, unprefixed names
                    // resolve to the default namespace (if one is declared)
                    // or otherwise to the absent namespace.
                    ns_snapshot.default_namespace()
                };

                let local_name = name_table.add(local);
                items.push(NotQNameItem::QName { namespace, local_name });
            }
        }
    }
    Ok(items)
}

/// Parse an XSD nonNegativeInteger/positiveInteger facet value.
///
/// Applies whitespace collapse (the schema-for-schemas types these attributes
/// as `nonNegativeInteger`/`positiveInteger`) and strips an optional leading `+`.
fn parse_nonneg_integer<T: std::str::FromStr>(value: &str, facet_name: &str) -> SchemaResult<T> {
    let trimmed = value.trim();
    let text = trimmed.strip_prefix('+').unwrap_or(trimmed);
    text.parse().map_err(|_| {
        SchemaError::structural(
            "st-props-correct",
            format!("Invalid {} value '{}': must be a nonNegativeInteger", facet_name, value),
            None,
        )
    })
}

/// Apply a facet to a facet set
fn apply_facet(facets: &mut FacetSet, facet: FacetResult) -> SchemaResult<()> {
    use crate::types::facets::{FacetFixed, WhitespaceMode};

    let fixed = if facet.fixed {
        FacetFixed::Fixed
    } else {
        FacetFixed::Default
    };

    let dup = |name: &str| {
        SchemaError::structural(
            "st-props-correct",
            format!("Facet '{}' must not appear more than once in a restriction", name),
            None,
        )
    };

    match facet.kind {
        FacetKind::Enumeration => {
            facets.add_enumeration(facet.value, facet.source);
        }
        FacetKind::Pattern => {
            // Use unchecked to defer pattern compilation to validation phase
            facets.add_pattern_unchecked(facet.value, facet.source);
        }
        FacetKind::MinLength => {
            if facets.min_length.is_some() { return Err(dup("minLength")); }
            facets.set_min_length(parse_nonneg_integer(&facet.value, "minLength")?, fixed, facet.source);
        }
        FacetKind::MaxLength => {
            if facets.max_length.is_some() { return Err(dup("maxLength")); }
            facets.set_max_length(parse_nonneg_integer(&facet.value, "maxLength")?, fixed, facet.source);
        }
        FacetKind::Length => {
            if facets.length.is_some() { return Err(dup("length")); }
            facets.set_length(parse_nonneg_integer(&facet.value, "length")?, fixed, facet.source);
        }
        FacetKind::MinInclusive => {
            if facets.min_inclusive.is_some() { return Err(dup("minInclusive")); }
            facets.set_min_inclusive(facet.value, fixed, facet.source);
        }
        FacetKind::MaxInclusive => {
            if facets.max_inclusive.is_some() { return Err(dup("maxInclusive")); }
            facets.set_max_inclusive(facet.value, fixed, facet.source);
        }
        FacetKind::MinExclusive => {
            if facets.min_exclusive.is_some() { return Err(dup("minExclusive")); }
            facets.set_min_exclusive(facet.value, fixed, facet.source);
        }
        FacetKind::MaxExclusive => {
            if facets.max_exclusive.is_some() { return Err(dup("maxExclusive")); }
            facets.set_max_exclusive(facet.value, fixed, facet.source);
        }
        FacetKind::TotalDigits => {
            if facets.total_digits.is_some() { return Err(dup("totalDigits")); }
            let v: u32 = parse_nonneg_integer(&facet.value, "totalDigits")?;
            if v == 0 {
                return Err(SchemaError::structural(
                    "st-props-correct",
                    "Invalid totalDigits value '0': must be a positiveInteger (> 0)",
                    None,
                ));
            }
            facets.set_total_digits(v, fixed, facet.source);
        }
        FacetKind::FractionDigits => {
            if facets.fraction_digits.is_some() { return Err(dup("fractionDigits")); }
            facets.set_fraction_digits(parse_nonneg_integer(&facet.value, "fractionDigits")?, fixed, facet.source);
        }
        FacetKind::WhiteSpace => {
            if facets.whitespace.is_some() { return Err(dup("whiteSpace")); }
            let mode = match facet.value.as_str() {
                "preserve" => WhitespaceMode::Preserve,
                "replace" => WhitespaceMode::Replace,
                "collapse" => WhitespaceMode::Collapse,
                _ => WhitespaceMode::Collapse,
            };
            facets.set_whitespace(mode, fixed, facet.source);
        }
        FacetKind::Assertion => {
            // XSD 1.1: assertion facet - the value is the XPath test expression
            facets.add_assertion(
                facet.value,
                facet.xpath_default_namespace,
                facet.ns_snapshot.unwrap_or_default(),
                facet.source,
            );
        }
        FacetKind::ExplicitTimezone => {
            if facets.explicit_timezone.is_some() { return Err(dup("explicitTimezone")); }
            // XSD 1.1 ยง4.3.16: explicitTimezone value must be one of required/prohibited/optional.
            let mode = match facet.value.as_str() {
                "required" => ExplicitTimezone::Required,
                "prohibited" => ExplicitTimezone::Prohibited,
                "optional" => ExplicitTimezone::Optional,
                other => {
                    return Err(SchemaError::structural(
                        "st-props-correct",
                        format!(
                            "Invalid explicitTimezone value '{}': expected 'required', 'prohibited', or 'optional'",
                            other
                        ),
                        None,
                    ));
                }
            };
            facets.set_explicit_timezone(mode, fixed, facet.source);
        }
    }

    Ok(())
}