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
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
//! XPath 2.0 QName functions.
//!
//! This module implements:
//! - fn:resolve-QName($qname, $element) - resolve a QName against element's namespaces
//! - fn:QName($uri, $local) - construct a QName from URI and local name
//! - fn:prefix-from-QName($arg) - extract prefix from QName
//! - fn:local-name-from-QName($arg) - extract local name from QName
//! - fn:namespace-uri-from-QName($arg) - extract namespace URI from QName
//! - fn:namespace-uri-for-prefix($prefix, $element) - lookup namespace for prefix
//! - fn:in-scope-prefixes($element) - return all prefixes in scope

use crate::xpath::context::DynamicContext;
use crate::xpath::error::XPathError;
use crate::xpath::DomNavigator;
use crate::xpath::{DomNodeType, NamespaceAxisScope};

use super::{atomize_to_single_opt, atomize_to_string_opt, XPathValue};
use crate::namespace::qname::{is_ncname, QualifiedName};
use crate::types::value::{XmlAtomicValue, XmlValue, XmlValueKind};
use crate::types::XmlTypeCode;
use crate::xpath::iterator::XmlItem;

/// fn:resolve-QName($qname as xs:string?, $element as element()) as xs:QName?
///
/// Resolves a lexical QName using the in-scope namespaces of an element node.
///
/// - If $qname is empty, returns empty sequence.
/// - FORG0001 if $qname is not a valid lexical QName.
/// - XPST0081 (FONS0004) if the prefix is not bound.
pub fn resolve_qname<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "resolve-QName",
            2,
            args.len(),
        ));
    }

    let element = get_element_arg(&mut args)?;
    let qname_arg = args.remove(0);
    let qname_str = atomize_to_string_opt(qname_arg)?;

    // If $qname is empty sequence, return empty
    // If $qname is empty string, it's an invalid QName (FORG0001)
    let qname_str = match qname_str {
        None => return Ok(XPathValue::Empty),
        Some(s) if s.is_empty() => {
            return Err(XPathError::invalid_cast_value("", "xs:QName"));
        }
        Some(s) => s,
    };

    // Parse the lexical QName
    let (prefix, local_name) = parse_lexical_qname(&qname_str)?;

    // Lookup namespace for prefix using element's in-scope namespaces
    let namespace_uri = lookup_namespace_for_prefix(&element, prefix.as_deref())?;

    // Create the QName value
    let qn = create_qname_value(
        context,
        namespace_uri.as_deref(),
        &local_name,
        prefix.as_deref(),
    );
    Ok(qn)
}

/// fn:QName($paramURI as xs:string?, $paramQName as xs:string) as xs:QName
///
/// Constructs a QName from a namespace URI and a lexical QName.
///
/// - $paramURI is the namespace URI (empty string = no namespace)
/// - $paramQName is the lexical form "prefix:local" or just "local"
/// - FORG0001 if $paramQName is not valid
/// - FOCA0002 if prefix with no namespace
pub fn qname_constructor<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "QName",
            2,
            args.len(),
        ));
    }

    let local_arg = args.pop().unwrap();
    let uri_arg = args.pop().unwrap();

    let param_qname = super::atomize_to_string_required(local_arg)?;
    let param_uri = atomize_to_string_opt(uri_arg)?;

    // Parse the lexical QName
    let (prefix, local_name) = parse_lexical_qname(&param_qname)?;

    // Determine namespace URI
    let namespace_uri = match param_uri {
        None => None,
        Some(s) if s.is_empty() => None,
        Some(s) => Some(s),
    };

    // Check constraint: if prefix is present, namespace must be non-empty
    if prefix.is_some() && namespace_uri.is_none() {
        return Err(XPathError::FOCA0002 { qname: param_qname });
    }

    // Create the QName value
    let qn = create_qname_value(
        context,
        namespace_uri.as_deref(),
        &local_name,
        prefix.as_deref(),
    );
    Ok(qn)
}

/// fn:prefix-from-QName($arg as xs:QName?) as xs:NCName?
///
/// Returns the prefix component of a QName, or empty if no prefix.
pub fn prefix_from_qname<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "prefix-from-QName",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let qname = atomize_to_qname(context, arg)?;

    match qname {
        None => Ok(XPathValue::Empty),
        Some(qn) => match qn.prefix {
            None => Ok(XPathValue::Empty),
            Some(prefix_id) => {
                let prefix = context
                    .static_context
                    .names
                    .try_resolve(prefix_id)
                    .unwrap_or_default();
                if prefix.is_empty() {
                    Ok(XPathValue::Empty)
                } else {
                    Ok(XPathValue::string(prefix))
                }
            }
        },
    }
}

/// fn:local-name-from-QName($arg as xs:QName?) as xs:NCName?
///
/// Returns the local name component of a QName.
pub fn local_name_from_qname<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "local-name-from-QName",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let qname = atomize_to_qname(context, arg)?;

    match qname {
        None => Ok(XPathValue::Empty),
        Some(qn) => {
            let local = context
                .static_context
                .names
                .try_resolve(qn.local_name)
                .unwrap_or_default();
            Ok(XPathValue::string(local))
        }
    }
}

/// fn:namespace-uri-from-QName($arg as xs:QName?) as xs:anyURI?
///
/// Returns the namespace URI component of a QName.
pub fn namespace_uri_from_qname<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "namespace-uri-from-QName",
            1,
            args.len(),
        ));
    }

    let arg = args.remove(0);
    let qname = atomize_to_qname(context, arg)?;

    match qname {
        None => Ok(XPathValue::Empty),
        Some(qn) => {
            match qn.namespace_uri {
                None => {
                    // Return empty anyURI (not empty sequence)
                    Ok(make_any_uri(""))
                }
                Some(ns_id) => {
                    let ns = context
                        .static_context
                        .names
                        .try_resolve(ns_id)
                        .unwrap_or_default();
                    Ok(make_any_uri(&ns))
                }
            }
        }
    }
}

/// fn:namespace-uri-for-prefix($prefix as xs:string?, $element as element()) as xs:anyURI?
///
/// Returns the namespace URI bound to a prefix in the scope of an element.
/// - Empty prefix or empty string prefix returns the default namespace
/// - If no default namespace, returns empty string anyURI (not empty sequence)
/// - Empty result (empty sequence) only if a non-empty prefix is not bound
pub fn namespace_uri_for_prefix<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "namespace-uri-for-prefix",
            2,
            args.len(),
        ));
    }

    let element = get_element_arg(&mut args)?;
    let prefix_arg = args.remove(0);
    let prefix = atomize_to_string_opt(prefix_arg)?;

    // Determine if we're looking for the default namespace
    let is_default_ns_lookup = prefix.is_none() || prefix.as_deref() == Some("");

    // Lookup namespace
    let namespace = lookup_namespace_for_prefix_opt(&element, prefix.as_deref());

    match namespace {
        Some(ns) => Ok(make_any_uri(&ns)),
        None if is_default_ns_lookup => {
            // For default namespace lookup, return empty anyURI if no default ns
            Ok(make_any_uri(""))
        }
        None => {
            // For prefixed lookup, return empty sequence if prefix not bound
            Ok(XPathValue::Empty)
        }
    }
}

/// fn:in-scope-prefixes($element as element()) as xs:string*
///
/// Returns a sequence of all prefixes bound to namespaces in scope for an element.
/// Always includes "xml" prefix.
pub fn in_scope_prefixes<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "in-scope-prefixes",
            1,
            args.len(),
        ));
    }

    let element = get_element_arg(&mut args)?;

    let mut prefixes = Vec::new();

    // Always include "xml" prefix
    prefixes.push("xml".to_string());

    // Iterate over namespace axis
    let mut nav = element.clone();
    if nav.move_to_first_namespace(NamespaceAxisScope::All) {
        loop {
            let prefix = nav.local_name();
            // Skip if already in list (shouldn't happen but be safe)
            if !prefixes.iter().any(|p| p == prefix) {
                prefixes.push(prefix.to_string());
            }
            if !nav.move_to_next_namespace(NamespaceAxisScope::All) {
                break;
            }
        }
    }

    // Convert to sequence of strings
    let items: Vec<XmlItem<N>> = prefixes
        .into_iter()
        .map(|p| XmlItem::Atomic(XmlValue::string(p)))
        .collect();

    Ok(XPathValue::from_sequence(items))
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Parse a lexical QName string into (prefix, local_name).
///
/// This function validates that both the prefix (if present) and local name
/// are valid NCNames per XML namespaces specification.
pub fn parse_lexical_qname(qname: &str) -> Result<(Option<String>, String), XPathError> {
    let qname = qname.trim();

    if qname.is_empty() {
        return Err(XPathError::invalid_cast_value(qname, "xs:QName"));
    }

    match qname.find(':') {
        Some(pos) if pos > 0 && pos < qname.len() - 1 => {
            let prefix = &qname[..pos];
            let local = &qname[pos + 1..];

            // Validate prefix is NCName
            if !is_ncname(prefix) {
                return Err(XPathError::invalid_cast_value(qname, "xs:QName"));
            }

            // Validate local is NCName (no additional colons)
            if !is_ncname(local) || local.contains(':') {
                return Err(XPathError::invalid_cast_value(qname, "xs:QName"));
            }

            Ok((Some(prefix.to_string()), local.to_string()))
        }
        Some(_) => {
            // Colon at start or end
            Err(XPathError::invalid_cast_value(qname, "xs:QName"))
        }
        None => {
            // No prefix
            if !is_ncname(qname) {
                return Err(XPathError::invalid_cast_value(qname, "xs:QName"));
            }
            Ok((None, qname.to_string()))
        }
    }
}

/// Get an element node from the arguments list.
fn get_element_arg<N: DomNavigator>(args: &mut Vec<XPathValue<N>>) -> Result<N, XPathError> {
    let arg = args
        .pop()
        .ok_or_else(|| XPathError::type_mismatch("element()", "empty-sequence()"))?;

    match arg {
        XPathValue::Item(XmlItem::Node(nav)) => {
            if nav.node_type() == DomNodeType::Element {
                Ok(nav)
            } else {
                Err(XPathError::type_mismatch("element()", "node()"))
            }
        }
        XPathValue::Sequence(items) if items.len() == 1 => {
            if let Some(XmlItem::Node(nav)) = items.into_iter().next() {
                if nav.node_type() == DomNodeType::Element {
                    Ok(nav)
                } else {
                    Err(XPathError::type_mismatch("element()", "node()"))
                }
            } else {
                Err(XPathError::type_mismatch("element()", "atomic value"))
            }
        }
        _ => Err(XPathError::type_mismatch("element()", "sequence")),
    }
}

/// Atomize a value to a QualifiedName.
fn atomize_to_qname<N: DomNavigator>(
    _context: &DynamicContext<'_, N>,
    value: XPathValue<N>,
) -> Result<Option<QualifiedName>, XPathError> {
    let atomic = atomize_to_single_opt(value)?;

    match atomic {
        None => Ok(None),
        Some(value) => {
            if let Some(qn) = value.as_qname() {
                Ok(Some(qn.clone()))
            } else {
                Err(XPathError::type_mismatch(
                    "xs:QName",
                    format!("{:?}", value.type_code),
                ))
            }
        }
    }
}

/// Lookup namespace for a prefix using element's namespace axis.
fn lookup_namespace_for_prefix<N: DomNavigator>(
    element: &N,
    prefix: Option<&str>,
) -> Result<Option<String>, XPathError> {
    let result = lookup_namespace_for_prefix_opt(element, prefix);

    // For resolve-QName, undefined prefix is an error
    if prefix.is_some() && prefix != Some("") && result.is_none() {
        return Err(XPathError::undefined_prefix(prefix.unwrap_or("")));
    }

    Ok(result)
}

/// Lookup namespace for a prefix, returning None if not found.
fn lookup_namespace_for_prefix_opt<N: DomNavigator>(
    element: &N,
    prefix: Option<&str>,
) -> Option<String> {
    let target_prefix = prefix.unwrap_or("");

    let mut nav = element.clone();
    if nav.move_to_first_namespace(NamespaceAxisScope::All) {
        loop {
            let ns_prefix = nav.local_name();
            if ns_prefix == target_prefix {
                let uri = nav.value();
                if uri.is_empty() {
                    return None; // Empty namespace (undeclaration)
                }
                return Some(uri);
            }
            if !nav.move_to_next_namespace(NamespaceAxisScope::All) {
                break;
            }
        }
    }

    // Special case: "xml" prefix is always bound
    if target_prefix == "xml" {
        return Some("http://www.w3.org/XML/1998/namespace".to_string());
    }

    None
}

/// Create an xs:anyURI value.
fn make_any_uri<N: DomNavigator>(uri: &str) -> XPathValue<N> {
    let value = XmlValue::new(
        XmlTypeCode::AnyUri,
        XmlValueKind::Atomic(XmlAtomicValue::AnyUri(uri.to_string())),
    );
    XPathValue::Item(XmlItem::Atomic(value))
}

/// Create a QName XPathValue.
///
/// Uses interior mutability of NameTable to intern the strings at runtime.
fn create_qname_value<N: DomNavigator>(
    context: &DynamicContext<'_, N>,
    namespace_uri: Option<&str>,
    local_name: &str,
    prefix: Option<&str>,
) -> XPathValue<N> {
    // Intern strings in the NameTable using interior mutability
    let names = context.static_context.names;

    let local_id = names.add(local_name);
    let ns_id = namespace_uri.map(|ns| names.add(ns));
    let prefix_id = prefix.map(|p| names.add(p));

    let qn = QualifiedName::new(ns_id, local_id, prefix_id);

    // Create a QName value
    let value = XmlValue::new(
        XmlTypeCode::QName,
        XmlValueKind::Atomic(XmlAtomicValue::QName(qn)),
    );

    XPathValue::Item(XmlItem::Atomic(value))
}

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

    fn create_context<'a>(names: &'a NameTable) -> DynamicContext<'a, RoXmlNavigator<'a>> {
        let static_ctx = XPathContext::new(names);
        let static_ctx = Box::leak(Box::new(static_ctx));
        DynamicContext::new(static_ctx, 0)
    }

    #[test]
    fn test_qname_constructor_and_extraction() {
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        // Create a QName: fn:QName("http://example.com", "p:local")
        let qname_result = qname_constructor(
            &mut ctx,
            vec![
                XPathValue::string("http://example.com"),
                XPathValue::string("p:local"),
            ],
        )
        .unwrap();

        // Now extract the components
        // prefix-from-QName should return "p"
        let prefix_result = prefix_from_qname(&mut ctx, vec![qname_result.clone()]).unwrap();
        if let XPathValue::Item(XmlItem::Atomic(value)) = prefix_result {
            assert_eq!(value.as_string(), Some("p"));
        } else {
            panic!("Expected string for prefix");
        }

        // local-name-from-QName should return "local"
        let local_result = local_name_from_qname(&mut ctx, vec![qname_result.clone()]).unwrap();
        if let XPathValue::Item(XmlItem::Atomic(value)) = local_result {
            assert_eq!(value.as_string(), Some("local"));
        } else {
            panic!("Expected string for local name");
        }

        // namespace-uri-from-QName should return "http://example.com"
        let ns_result = namespace_uri_from_qname(&mut ctx, vec![qname_result]).unwrap();
        if let XPathValue::Item(XmlItem::Atomic(value)) = ns_result {
            assert_eq!(value.to_string_value(), "http://example.com");
        } else {
            panic!("Expected anyURI for namespace");
        }
    }

    #[test]
    fn test_qname_unprefixed() {
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        // Create unprefixed QName
        let qname_result = qname_constructor(
            &mut ctx,
            vec![
                XPathValue::Empty, // No namespace
                XPathValue::string("localonly"),
            ],
        )
        .unwrap();

        // prefix-from-QName should return empty sequence
        let prefix_result = prefix_from_qname(&mut ctx, vec![qname_result.clone()]).unwrap();
        assert!(matches!(prefix_result, XPathValue::Empty));

        // local-name-from-QName should return "localonly"
        let local_result = local_name_from_qname(&mut ctx, vec![qname_result]).unwrap();
        if let XPathValue::Item(XmlItem::Atomic(value)) = local_result {
            assert_eq!(value.as_string(), Some("localonly"));
        } else {
            panic!("Expected string for local name");
        }
    }

    #[test]
    fn test_qname_prefix_with_no_namespace_error() {
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        // Prefix without namespace should error (FOCA0002)
        let result = qname_constructor(
            &mut ctx,
            vec![
                XPathValue::Empty, // No namespace but prefix present
                XPathValue::string("p:local"),
            ],
        );

        assert!(result.is_err());
        if let Err(XPathError::FOCA0002 { .. }) = result {
            // Expected
        } else {
            panic!("Expected FOCA0002 error");
        }
    }

    #[test]
    fn test_parse_lexical_qname_prefixed() {
        let (prefix, local) = parse_lexical_qname("xs:string").unwrap();
        assert_eq!(prefix, Some("xs".to_string()));
        assert_eq!(local, "string");
    }

    #[test]
    fn test_parse_lexical_qname_unprefixed() {
        let (prefix, local) = parse_lexical_qname("localName").unwrap();
        assert_eq!(prefix, None);
        assert_eq!(local, "localName");
    }

    #[test]
    fn test_parse_lexical_qname_invalid() {
        assert!(parse_lexical_qname("").is_err());
        assert!(parse_lexical_qname(":local").is_err());
        assert!(parse_lexical_qname("prefix:").is_err());
        assert!(parse_lexical_qname("a:b:c").is_err());
        assert!(parse_lexical_qname("123invalid").is_err());
    }

    #[test]
    fn test_parse_lexical_qname_with_whitespace() {
        let (prefix, local) = parse_lexical_qname("  xs:string  ").unwrap();
        assert_eq!(prefix, Some("xs".to_string()));
        assert_eq!(local, "string");
    }
}