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
//! AST types, error handling, and namespace resolution for identity-constraint XPath.
//!
//! This module defines the abstract syntax tree produced by parsing the restricted XPath
//! subset used in XSD `<selector>` and `<field>` expressions. It also provides the
//! `xpathDefaultNamespace` cascade resolution required by XSD 1.1.

#![allow(dead_code)]

use std::fmt;

use crate::ids::NameId;
use crate::namespace::context::NamespaceContextSnapshot;
use crate::namespace::table::NameTable;
use crate::schema::model::XsdVersion;

use super::identity_lexer::IdXPathLexError;

/// Error produced during identity-constraint XPath compilation.
#[derive(Debug, Clone)]
pub enum IdentityXPathError {
    /// Lexer error (invalid character, unsupported syntax).
    Lex(IdXPathLexError),
    /// Parser error (unexpected token, malformed expression).
    Parse { message: String, position: usize },
    /// Unbound namespace prefix.
    UnboundPrefix { prefix: String, position: usize },
    /// Restriction violation (e.g. attribute step in selector, attribute not last).
    Restriction { message: String, position: usize },
}

impl fmt::Display for IdentityXPathError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IdentityXPathError::Lex(e) => write!(f, "{e}"),
            IdentityXPathError::Parse { message, position } => {
                write!(
                    f,
                    "identity XPath parse error at position {position}: {message}"
                )
            }
            IdentityXPathError::UnboundPrefix { prefix, position } => {
                write!(
                    f,
                    "identity XPath error at position {position}: unbound prefix `{prefix}`"
                )
            }
            IdentityXPathError::Restriction { message, position } => {
                write!(
                    f,
                    "identity XPath restriction at position {position}: {message}"
                )
            }
        }
    }
}

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

impl From<IdXPathLexError> for IdentityXPathError {
    fn from(e: IdXPathLexError) -> Self {
        IdentityXPathError::Lex(e)
    }
}

/// How an unprefixed element name matches a namespace.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NamespaceMatch {
    /// No namespace (XSD 1.0 default, or `##local`).
    NoNamespace,
    /// An exact namespace URI.
    Exact(NameId),
}

/// A name test in a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NameTest {
    /// `*` — matches any element/attribute.
    Wildcard,
    /// `ns:*` — matches any local name in the given namespace.
    NamespaceWildcard(NameId),
    /// `foo` or `ns:foo` — matches a specific QName.
    QName {
        namespace: NamespaceMatch,
        local_name: NameId,
    },
}

impl NameTest {
    /// Check whether this name test matches a given namespace URI and local name.
    pub(crate) fn matches(&self, namespace_uri: NameId, local_name: NameId) -> bool {
        match self {
            NameTest::Wildcard => true,
            NameTest::NamespaceWildcard(ns) => namespace_uri == *ns,
            NameTest::QName {
                namespace,
                local_name: ln,
            } => {
                *ln == local_name
                    && match namespace {
                        NamespaceMatch::NoNamespace => {
                            // No namespace means empty namespace URI
                            namespace_uri.0 == 0
                        }
                        NamespaceMatch::Exact(ns) => namespace_uri == *ns,
                    }
            }
        }
    }
}

/// A single step in a path expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AstStep {
    /// `.` — the current node.
    SelfNode,
    /// `foo`, `child::foo`, `*`, etc. — child axis.
    Child(NameTest),
    /// `@foo`, `attribute::foo` — attribute axis (field expressions only).
    Attribute(NameTest),
}

/// A single path in a selector/field expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AstPath {
    /// Whether this path starts with `.//` (descendant-or-self).
    pub descendant: bool,
    /// The steps in this path.
    pub steps: Vec<AstStep>,
}

/// Parsed identity-constraint XPath expression (union of paths).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Asttree {
    /// The alternative paths (union branches).
    pub paths: Vec<AstPath>,
}

impl Asttree {
    /// Compile a selector XPath expression.
    ///
    /// Selector expressions may not contain attribute steps.
    /// In XSD 1.0 mode, `xpathDefaultNamespace` is ignored (forced to `NoNamespace`).
    pub fn compile_selector(
        xpath: &str,
        ns_snapshot: &NamespaceContextSnapshot,
        name_table: &NameTable,
        own_xpath_default_ns: Option<&str>,
        schema_xpath_default_ns: Option<NameId>,
        target_namespace: Option<NameId>,
        xsd_version: XsdVersion,
    ) -> Result<Asttree, IdentityXPathError> {
        use super::identity_parser::IdXPathParser;

        // In XSD 1.0 mode, xpathDefaultNamespace is not supported
        let (effective_own, effective_schema) = match xsd_version {
            XsdVersion::V1_0 => (None, None),
            XsdVersion::V1_1 => (own_xpath_default_ns, schema_xpath_default_ns),
        };

        let unprefixed_ns = resolve_effective_default_ns(
            effective_own,
            effective_schema,
            ns_snapshot,
            target_namespace,
            name_table,
        );
        let mut parser = IdXPathParser::new(xpath, ns_snapshot, name_table, unprefixed_ns)?;
        parser.parse_selector()
    }

    /// Compile a field XPath expression.
    ///
    /// Field expressions allow an optional final attribute step.
    /// In XSD 1.0 mode, `xpathDefaultNamespace` is ignored (forced to `NoNamespace`).
    pub fn compile_field(
        xpath: &str,
        ns_snapshot: &NamespaceContextSnapshot,
        name_table: &NameTable,
        own_xpath_default_ns: Option<&str>,
        schema_xpath_default_ns: Option<NameId>,
        target_namespace: Option<NameId>,
        xsd_version: XsdVersion,
    ) -> Result<Asttree, IdentityXPathError> {
        use super::identity_parser::IdXPathParser;

        // In XSD 1.0 mode, xpathDefaultNamespace is not supported
        let (effective_own, effective_schema) = match xsd_version {
            XsdVersion::V1_0 => (None, None),
            XsdVersion::V1_1 => (own_xpath_default_ns, schema_xpath_default_ns),
        };

        let unprefixed_ns = resolve_effective_default_ns(
            effective_own,
            effective_schema,
            ns_snapshot,
            target_namespace,
            name_table,
        );
        let mut parser = IdXPathParser::new(xpath, ns_snapshot, name_table, unprefixed_ns)?;
        parser.parse_field()
    }
}

/// Resolve the effective default namespace for unprefixed element names.
///
/// Cascade: `own_raw` > `schema_raw_id` (resolved via `name_table`).
/// Special values:
/// - `##defaultNamespace` → snapshot's default namespace
/// - `##targetNamespace` → schema's target namespace
/// - `##local` → `NoNamespace`
/// - other string → `Exact(name_table.add(uri))`
/// - no value → `NoNamespace` (XSD 1.0 behavior)
fn resolve_effective_default_ns(
    own_raw: Option<&str>,
    schema_raw_id: Option<NameId>,
    ns_snapshot: &NamespaceContextSnapshot,
    target_namespace: Option<NameId>,
    name_table: &NameTable,
) -> NamespaceMatch {
    // Try own-level first, then schema-level
    let effective = if let Some(raw) = own_raw {
        Some(raw.to_string())
    } else {
        schema_raw_id.map(|id| name_table.resolve(id))
    };

    match effective.as_deref() {
        Some("##defaultNamespace") => match ns_snapshot.default_ns {
            Some(ns_id) => NamespaceMatch::Exact(ns_id),
            None => NamespaceMatch::NoNamespace,
        },
        Some("##targetNamespace") => match target_namespace {
            Some(ns_id) => NamespaceMatch::Exact(ns_id),
            None => NamespaceMatch::NoNamespace,
        },
        Some("##local") => NamespaceMatch::NoNamespace,
        Some(uri) => NamespaceMatch::Exact(name_table.add(uri)),
        None => NamespaceMatch::NoNamespace,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::namespace::context::NamespaceContextSnapshot;
    use crate::namespace::table::NameTable;

    // --- Namespace resolution tests ---

    #[test]
    fn no_default_unprefixed() {
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let result = resolve_effective_default_ns(None, None, &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::NoNamespace);
    }

    #[test]
    fn own_default_namespace() {
        let table = NameTable::new();
        let uri_id = table.add("http://example.com/ns");
        let snapshot = NamespaceContextSnapshot {
            default_ns: Some(uri_id),
            bindings: vec![],
        };
        let result =
            resolve_effective_default_ns(Some("##defaultNamespace"), None, &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::Exact(uri_id));
    }

    #[test]
    fn own_target_namespace() {
        let table = NameTable::new();
        let tns = table.add("http://example.com/target");
        let snapshot = NamespaceContextSnapshot::default();
        let result = resolve_effective_default_ns(
            Some("##targetNamespace"),
            None,
            &snapshot,
            Some(tns),
            &table,
        );
        assert_eq!(result, NamespaceMatch::Exact(tns));
    }

    #[test]
    fn own_local() {
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let result = resolve_effective_default_ns(Some("##local"), None, &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::NoNamespace);
    }

    #[test]
    fn own_literal_uri() {
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let result =
            resolve_effective_default_ns(Some("http://example.com"), None, &snapshot, None, &table);
        let expected_id = table.add("http://example.com");
        assert_eq!(result, NamespaceMatch::Exact(expected_id));
    }

    #[test]
    fn cascade_own_over_schema() {
        let table = NameTable::new();
        let schema_ns = table.add("http://example.com");
        let snapshot = NamespaceContextSnapshot::default();
        // own = ##local wins over schema-level URI
        let result =
            resolve_effective_default_ns(Some("##local"), Some(schema_ns), &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::NoNamespace);
    }

    #[test]
    fn cascade_schema_fallback() {
        let table = NameTable::new();
        let schema_ns = table.add("http://example.com");
        let snapshot = NamespaceContextSnapshot::default();
        // own = None, falls through to schema-level
        let result = resolve_effective_default_ns(None, Some(schema_ns), &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::Exact(schema_ns));
    }

    #[test]
    fn default_ns_absent() {
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot {
            default_ns: None,
            bindings: vec![],
        };
        let result =
            resolve_effective_default_ns(Some("##defaultNamespace"), None, &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::NoNamespace);
    }

    #[test]
    fn target_ns_absent() {
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let result =
            resolve_effective_default_ns(Some("##targetNamespace"), None, &snapshot, None, &table);
        assert_eq!(result, NamespaceMatch::NoNamespace);
    }

    // --- NameTest::matches tests ---

    #[test]
    fn wildcard_matches_anything() {
        let table = NameTable::new();
        let ns = table.add("http://example.com");
        let ln = table.add("foo");
        assert!(NameTest::Wildcard.matches(ns, ln));
    }

    #[test]
    fn namespace_wildcard_matches_same_ns() {
        let table = NameTable::new();
        let ns = table.add("http://example.com");
        let ln = table.add("foo");
        assert!(NameTest::NamespaceWildcard(ns).matches(ns, ln));
    }

    #[test]
    fn namespace_wildcard_rejects_different_ns() {
        let table = NameTable::new();
        let ns1 = table.add("http://example.com/1");
        let ns2 = table.add("http://example.com/2");
        let ln = table.add("foo");
        assert!(!NameTest::NamespaceWildcard(ns1).matches(ns2, ln));
    }

    #[test]
    fn qname_exact_match() {
        let table = NameTable::new();
        let ns = table.add("http://example.com");
        let ln = table.add("foo");
        let test = NameTest::QName {
            namespace: NamespaceMatch::Exact(ns),
            local_name: ln,
        };
        assert!(test.matches(ns, ln));
    }

    #[test]
    fn qname_no_namespace_match() {
        let table = NameTable::new();
        let ln = table.add("foo");
        let test = NameTest::QName {
            namespace: NamespaceMatch::NoNamespace,
            local_name: ln,
        };
        use crate::namespace::table::well_known;
        // NameId(0) = empty string = no namespace
        assert!(test.matches(well_known::EMPTY, ln));
    }

    #[test]
    fn qname_rejects_wrong_local() {
        let table = NameTable::new();
        let ns = table.add("http://example.com");
        let ln1 = table.add("foo");
        let ln2 = table.add("bar");
        let test = NameTest::QName {
            namespace: NamespaceMatch::Exact(ns),
            local_name: ln1,
        };
        assert!(!test.matches(ns, ln2));
    }

    // --- XSD version gating tests ---

    #[test]
    fn compile_selector_v10_ignores_own_xpath_default_ns() {
        // In XSD 1.0 mode, xpathDefaultNamespace should be ignored,
        // so unprefixed element names resolve to NoNamespace.
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let tree = Asttree::compile_selector(
            "foo",
            &snapshot,
            &table,
            Some("http://example.com/default"),
            None,
            None,
            XsdVersion::V1_0,
        )
        .unwrap();
        match &tree.paths[0].steps[0] {
            AstStep::Child(NameTest::QName { namespace, .. }) => {
                assert_eq!(*namespace, NamespaceMatch::NoNamespace);
            }
            other => panic!("expected Child(QName{{NoNamespace, ..}}), got {other:?}"),
        }
    }

    #[test]
    fn compile_selector_v11_applies_own_xpath_default_ns() {
        // In XSD 1.1 mode, xpathDefaultNamespace should be applied.
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let ns_id = table.add("http://example.com/default");
        let tree = Asttree::compile_selector(
            "foo",
            &snapshot,
            &table,
            Some("http://example.com/default"),
            None,
            None,
            XsdVersion::V1_1,
        )
        .unwrap();
        match &tree.paths[0].steps[0] {
            AstStep::Child(NameTest::QName { namespace, .. }) => {
                assert_eq!(*namespace, NamespaceMatch::Exact(ns_id));
            }
            other => panic!("expected Child(QName{{Exact, ..}}), got {other:?}"),
        }
    }

    #[test]
    fn compile_selector_v10_ignores_schema_xpath_default_ns() {
        // In XSD 1.0 mode, even schema-level xpathDefaultNamespace is ignored.
        let table = NameTable::new();
        let schema_ns = table.add("http://example.com/schema");
        let snapshot = NamespaceContextSnapshot::default();
        let tree = Asttree::compile_selector(
            "foo",
            &snapshot,
            &table,
            None,
            Some(schema_ns),
            None,
            XsdVersion::V1_0,
        )
        .unwrap();
        match &tree.paths[0].steps[0] {
            AstStep::Child(NameTest::QName { namespace, .. }) => {
                assert_eq!(*namespace, NamespaceMatch::NoNamespace);
            }
            other => panic!("expected Child(QName{{NoNamespace, ..}}), got {other:?}"),
        }
    }

    #[test]
    fn compile_field_v10_ignores_xpath_default_ns() {
        // In XSD 1.0 mode, field compilation ignores xpathDefaultNamespace.
        let table = NameTable::new();
        let snapshot = NamespaceContextSnapshot::default();
        let tree = Asttree::compile_field(
            "foo",
            &snapshot,
            &table,
            Some("http://example.com/default"),
            None,
            None,
            XsdVersion::V1_0,
        )
        .unwrap();
        match &tree.paths[0].steps[0] {
            AstStep::Child(NameTest::QName { namespace, .. }) => {
                assert_eq!(*namespace, NamespaceMatch::NoNamespace);
            }
            other => panic!("expected Child(QName{{NoNamespace, ..}}), got {other:?}"),
        }
    }
}