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
//! XPath 2.0 URI functions.
//!
//! This module implements:
//! - fn:resolve-uri($relative, $base?) - resolve a relative URI against a base URI
//! - fn:static-base-uri() - return the static base URI from context

use crate::xpath::context::DynamicContext;
use crate::xpath::error::XPathError;
use crate::xpath::DomNavigator;

use super::{atomize_to_string_opt, XPathValue};
use crate::types::value::{XmlAtomicValue, XmlValue, XmlValueKind};
use crate::types::XmlTypeCode;
use crate::xpath::iterator::XmlItem;

/// fn:resolve-uri($relative as xs:string?, $base as xs:string?) as xs:anyURI?
///
/// Resolves a relative URI against a base URI, returning the resolved URI.
///
/// Behavior:
/// - If $relative is empty sequence, returns empty sequence
/// - If $relative is empty string, resolves it against base (returns base URI)
/// - 1-arg form: uses static base URI from context (FONS0005 if not defined)
/// - 2-arg form with empty base: requires base to be absolute, FORG0009 if not
/// - FORG0009 if the URI resolution fails
pub fn resolve_uri<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.is_empty() || args.len() > 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "resolve-uri",
            2,
            args.len(),
        ));
    }

    let is_one_arg_form = args.len() == 1;

    // Get the relative URI (first argument)
    let relative_arg = args.remove(0);
    let relative = atomize_to_string_opt(relative_arg)?;

    // If relative is empty sequence, return empty sequence
    let relative = match relative {
        None => return Ok(XPathValue::Empty),
        Some(s) => s, // Empty string is valid and resolves to base
    };

    // Get base URI (second argument or context base_uri)
    let base = if !args.is_empty() {
        // 2-arg form
        let base_arg = args.remove(0);
        atomize_to_string_opt(base_arg)?
    } else {
        // 1-arg form: use static base URI
        context.base_uri.clone()
    };

    // Validate base URI
    let base = match base {
        None if is_one_arg_form => {
            // 1-arg form requires base URI to be defined
            return Err(XPathError::base_uri_not_defined());
        }
        None => {
            // 2-arg form with empty sequence base: if relative is absolute, return it
            if is_absolute_uri(&relative) {
                return Ok(make_any_uri(&relative));
            }
            // Otherwise, error - can't resolve relative against empty
            return Err(XPathError::uri_resolution_error(&relative));
        }
        Some(b) if b.is_empty() => {
            // Empty string base
            if is_one_arg_form {
                return Err(XPathError::base_uri_not_defined());
            }
            // 2-arg with empty string: if relative is absolute, return it
            if is_absolute_uri(&relative) {
                return Ok(make_any_uri(&relative));
            }
            // Can't resolve relative against empty string
            return Err(XPathError::uri_resolution_error(&relative));
        }
        Some(b) => b,
    };

    // Validate the relative URI is a syntactically valid URI reference
    if !relative.is_empty() && !is_valid_uri_reference(&relative) {
        return Err(XPathError::uri_resolution_error(&relative));
    }

    // Validate the base URI is a syntactically valid absolute URI
    if !is_valid_base_uri(&base) {
        return Err(XPathError::uri_resolution_error(&relative));
    }

    // Resolve the URI
    let resolved = resolve_uri_reference(&relative, &base)
        .map_err(|_| XPathError::uri_resolution_error(&relative))?;

    Ok(make_any_uri(&resolved))
}

/// fn:static-base-uri() as xs:anyURI?
///
/// Returns the base URI from the static context.
/// Returns empty sequence if no base URI is defined.
pub fn static_base_uri<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if !args.is_empty() {
        return Err(XPathError::wrong_number_of_arguments(
            "static-base-uri",
            0,
            args.len(),
        ));
    }

    match &context.base_uri {
        Some(uri) if !uri.is_empty() => Ok(make_any_uri(uri)),
        _ => Ok(XPathValue::Empty),
    }
}

/// Create an xs:anyURI value from a string.
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))
}

/// Resolve a relative URI reference against a base URI.
///
/// This implements a simplified RFC 3986 URI resolution algorithm.
fn resolve_uri_reference(relative: &str, base: &str) -> Result<String, ()> {
    // If relative is already absolute (has scheme), return as-is
    if is_absolute_uri(relative) {
        return Ok(relative.to_string());
    }

    // Parse base URI
    let (base_scheme, base_authority, base_path, _base_query) = parse_uri_components(base)?;

    // If relative starts with //, it's a network-path reference
    if relative.starts_with("//") {
        return Ok(format!("{}{}", base_scheme.unwrap_or_default(), relative));
    }

    // If relative starts with /, it's an absolute-path reference
    if relative.starts_with('/') {
        let resolved_path = remove_dot_segments(relative);
        return Ok(format!(
            "{}{}{}",
            base_scheme.unwrap_or_default(),
            base_authority
                .map(|a| format!("//{}", a))
                .unwrap_or_default(),
            resolved_path
        ));
    }

    // If relative is empty, return base with optional query/fragment from relative
    if relative.is_empty() {
        return Ok(base.to_string());
    }

    // If relative starts with ?, it's a query reference
    if relative.starts_with('?') {
        let (base_without_query, _) = base.split_once('?').unwrap_or((base, ""));
        let (base_without_fragment, _) = base_without_query
            .split_once('#')
            .unwrap_or((base_without_query, ""));
        return Ok(format!("{}{}", base_without_fragment, relative));
    }

    // If relative starts with #, it's a fragment reference
    if relative.starts_with('#') {
        let (base_without_fragment, _) = base.split_once('#').unwrap_or((base, ""));
        return Ok(format!("{}{}", base_without_fragment, relative));
    }

    // Otherwise, merge paths
    let merged_path = merge_paths(base_authority.is_some(), base_path.unwrap_or(""), relative);
    let resolved_path = remove_dot_segments(&merged_path);

    Ok(format!(
        "{}{}{}",
        base_scheme.unwrap_or_default(),
        base_authority
            .map(|a| format!("//{}", a))
            .unwrap_or_default(),
        resolved_path
    ))
}

/// Check if a URI is absolute (has a scheme).
fn is_absolute_uri(uri: &str) -> bool {
    // A scheme is a letter followed by letters, digits, +, -, or .
    // followed by :
    if let Some(colon_pos) = uri.find(':') {
        if colon_pos > 0 {
            let scheme = &uri[..colon_pos];
            let mut chars = scheme.chars();
            if let Some(first) = chars.next() {
                if first.is_ascii_alphabetic() {
                    return chars
                        .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.');
                }
            }
        }
    }
    false
}

/// URI components tuple: (scheme, authority, path, query)
type UriComponents<'a> = (
    Option<String>,
    Option<&'a str>,
    Option<&'a str>,
    Option<&'a str>,
);

/// Parse URI into components (scheme, authority, path, query).
fn parse_uri_components(uri: &str) -> Result<UriComponents<'_>, ()> {
    let mut rest = uri;
    let mut scheme = None;
    let mut authority = None;

    // Extract scheme
    if let Some(colon_pos) = rest.find(':') {
        let potential_scheme = &rest[..colon_pos];
        if is_valid_scheme(potential_scheme) {
            scheme = Some(format!("{}:", potential_scheme));
            rest = &rest[colon_pos + 1..];
        }
    }

    // Extract authority
    if rest.starts_with("//") {
        rest = &rest[2..];
        let auth_end = rest
            .find('/')
            .or_else(|| rest.find('?'))
            .or_else(|| rest.find('#'))
            .unwrap_or(rest.len());
        authority = Some(&rest[..auth_end]);
        rest = &rest[auth_end..];
    }

    // Extract query and fragment
    let (path_and_query, _fragment) = rest.split_once('#').unwrap_or((rest, ""));
    let (path, query) = path_and_query
        .split_once('?')
        .map(|(p, q)| (Some(p), Some(q)))
        .unwrap_or((Some(path_and_query), None));

    Ok((scheme, authority, path, query))
}

use crate::types::validators::is_valid_uri_scheme as is_valid_scheme;

/// Merge paths according to RFC 3986.
fn merge_paths(has_authority: bool, base_path: &str, relative: &str) -> String {
    if has_authority && base_path.is_empty() {
        format!("/{}", relative)
    } else {
        // Remove everything after the last / in base_path
        let last_slash = base_path.rfind('/').map(|i| i + 1).unwrap_or(0);
        format!("{}{}", &base_path[..last_slash], relative)
    }
}

/// Remove dot segments from a path (RFC 3986 section 5.2.4).
fn remove_dot_segments(path: &str) -> String {
    let mut input = path.to_string();
    let mut output = Vec::new();

    while !input.is_empty() {
        // A: If the input buffer begins with a prefix of "../" or "./"
        if input.starts_with("../") {
            input = input[3..].to_string();
        } else if input.starts_with("./") {
            input = input[2..].to_string();
        }
        // B: If the input buffer begins with a prefix of "/./" or "/."
        else if input.starts_with("/./") {
            input = format!("/{}", &input[3..]);
        } else if input == "/." {
            input = "/".to_string();
        }
        // C: If the input buffer begins with a prefix of "/../" or "/.."
        else if input.starts_with("/../") {
            input = format!("/{}", &input[4..]);
            output.pop();
        } else if input == "/.." {
            input = "/".to_string();
            output.pop();
        }
        // D: if the input buffer consists only of "." or ".."
        else if input == "." || input == ".." {
            input.clear();
        }
        // E: move the first path segment (including initial "/" if any) to output
        else {
            let start = if input.starts_with('/') { 1 } else { 0 };
            let end = input[start..]
                .find('/')
                .map(|i| i + start)
                .unwrap_or(input.len());
            output.push(input[..end].to_string());
            input = input[end..].to_string();
        }
    }

    output.join("")
}

/// Check if a string is a valid URI reference (absolute or relative).
///
/// A relative reference must not start with a colon (which would be an empty scheme).
/// Per RFC 3986, a relative-reference starts with either a relative-part or is empty.
/// A path-noscheme segment-nz-nc must not contain ':' before first '/'.
fn is_valid_uri_reference(uri: &str) -> bool {
    if uri.is_empty() {
        return true;
    }

    // If it's absolute (has a valid scheme), it's a valid URI reference
    if is_absolute_uri(uri) {
        return true;
    }

    // For relative references: the first path segment must not contain ':'
    // (to avoid ambiguity with scheme). RFC 3986 §4.2
    if uri.starts_with("//") || uri.starts_with('/') || uri.starts_with('?') || uri.starts_with('#')
    {
        return true;
    }

    // Get the first path segment (up to first '/' or end)
    let first_segment = uri.split('/').next().unwrap_or(uri);
    // Remove query and fragment
    let first_segment = first_segment.split('?').next().unwrap_or(first_segment);
    let first_segment = first_segment.split('#').next().unwrap_or(first_segment);

    // First segment of a relative path must not contain ':'
    !first_segment.contains(':')
}

/// Check if a string is a valid base URI (must be an absolute URI with a valid scheme).
///
/// A base URI must have a scheme followed by scheme-specific content.
/// "http://" alone (scheme + empty authority + empty path) is not a usable base URI.
fn is_valid_base_uri(uri: &str) -> bool {
    if !is_absolute_uri(uri) {
        return false;
    }

    // Parse to check it has meaningful content after the scheme
    if let Ok((scheme, authority, path, _)) = parse_uri_components(uri) {
        // Must have a scheme
        if scheme.is_none() {
            return false;
        }
        // If it has an authority, it needs at least something (non-empty authority or a path)
        if let Some(auth) = authority {
            if auth.is_empty() {
                // scheme://  with empty authority — check if there's a path
                if let Some(p) = path {
                    return !p.is_empty();
                }
                return false;
            }
        }
        true
    } else {
        false
    }
}

#[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,
        base_uri: Option<&str>,
    ) -> DynamicContext<'a, RoXmlNavigator<'a>> {
        let mut static_ctx = XPathContext::new(names);
        if let Some(uri) = base_uri {
            static_ctx = static_ctx.with_base_uri(uri);
        }
        let static_ctx = Box::leak(Box::new(static_ctx));
        DynamicContext::new(static_ctx, 0)
    }

    #[test]
    fn test_static_base_uri_defined() {
        let names = NameTable::new();
        let mut ctx = create_context(&names, Some("http://example.com/base/"));

        let result = static_base_uri(&mut ctx, vec![]).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(value)) => {
                assert_eq!(value.to_string_value(), "http://example.com/base/");
            }
            _ => panic!("Expected anyURI"),
        }
    }

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

        let result = static_base_uri(&mut ctx, vec![]).unwrap();
        assert!(matches!(result, XPathValue::Empty));
    }

    #[test]
    fn test_resolve_uri_absolute() {
        let names = NameTable::new();
        let mut ctx = create_context(&names, Some("http://example.com/base/"));

        let result = resolve_uri(
            &mut ctx,
            vec![
                XPathValue::string("http://other.com/path"),
                XPathValue::string("http://example.com/ignored"),
            ],
        )
        .unwrap();

        match result {
            XPathValue::Item(XmlItem::Atomic(value)) => {
                assert_eq!(value.to_string_value(), "http://other.com/path");
            }
            _ => panic!("Expected anyURI"),
        }
    }

    #[test]
    fn test_resolve_uri_relative() {
        let names = NameTable::new();
        let mut ctx = create_context(&names, Some("http://example.com/base/"));

        let result = resolve_uri(
            &mut ctx,
            vec![
                XPathValue::string("path/file.xml"),
                XPathValue::string("http://example.com/base/"),
            ],
        )
        .unwrap();

        match result {
            XPathValue::Item(XmlItem::Atomic(value)) => {
                assert_eq!(
                    value.to_string_value(),
                    "http://example.com/base/path/file.xml"
                );
            }
            _ => panic!("Expected anyURI"),
        }
    }

    #[test]
    fn test_resolve_uri_empty_relative() {
        let names = NameTable::new();
        let mut ctx = create_context(&names, Some("http://example.com/base/"));

        let result = resolve_uri(&mut ctx, vec![XPathValue::Empty]).unwrap();

        assert!(matches!(result, XPathValue::Empty));
    }

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

        let result = resolve_uri(
            &mut ctx,
            vec![
                XPathValue::string("../other/file.xml"),
                XPathValue::string("http://example.com/base/subdir/"),
            ],
        )
        .unwrap();

        match result {
            XPathValue::Item(XmlItem::Atomic(value)) => {
                assert_eq!(
                    value.to_string_value(),
                    "http://example.com/base/other/file.xml"
                );
            }
            _ => panic!("Expected anyURI"),
        }
    }

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

        // 1-arg form with no base URI should fail
        let result = resolve_uri(&mut ctx, vec![XPathValue::string("path/file.xml")]);

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

    #[test]
    fn test_is_absolute_uri() {
        assert!(is_absolute_uri("http://example.com"));
        assert!(is_absolute_uri("https://example.com/path"));
        assert!(is_absolute_uri("file:///path/to/file"));
        assert!(is_absolute_uri("urn:isbn:0451450523"));
        assert!(!is_absolute_uri("/path/to/file"));
        assert!(!is_absolute_uri("path/to/file"));
        assert!(!is_absolute_uri("../relative"));
    }

    #[test]
    fn test_remove_dot_segments() {
        assert_eq!(remove_dot_segments("/a/b/c/./../../g"), "/a/g");
        assert_eq!(remove_dot_segments("mid/content=5/../6"), "mid/6");
        assert_eq!(remove_dot_segments("/../../../g"), "/g");
        assert_eq!(remove_dot_segments("./g"), "g");
        assert_eq!(remove_dot_segments("../../../g"), "g");
    }
}