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
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
//! XPath 2.0 regex functions.
//!
//! This module implements:
//! - fn:matches($input, $pattern, $flags?) - test if string matches pattern
//! - fn:replace($input, $pattern, $replacement, $flags?) - replace matches
//! - fn:tokenize($input, $pattern, $flags?) - split string by pattern
//!
//! Uses the `regexml` crate for native XML Schema 1.1 regex with full Unicode support.

use regexml::Regex;

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

use super::{atomize_to_string, atomize_to_string_opt, atomize_to_string_required, XPathValue};
use crate::types::value::XmlValue;
use crate::xpath::iterator::XmlItem;

/// fn:matches($input as xs:string?, $pattern as xs:string, $flags as xs:string?) as xs:boolean
///
/// Returns true if $input matches the regular expression $pattern.
///
/// - If $input is empty, it is treated as empty string.
/// - FORX0001 if $flags contains invalid characters.
/// - FORX0002 if $pattern is not a valid regular expression.
pub fn matches<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() < 2 || args.len() > 3 {
        return Err(XPathError::wrong_number_of_arguments(
            "matches",
            2,
            args.len(),
        ));
    }

    // Get flags (optional third argument)
    let flags = if args.len() == 3 {
        atomize_to_string_opt(args.pop().unwrap())?
    } else {
        None
    };

    // Get pattern (second argument)
    let pattern = atomize_to_string_required(args.pop().unwrap())?;

    // Get input (first argument)
    let input = atomize_to_string(args.pop().unwrap())?;

    let flags_str = flags.as_deref().unwrap_or("");

    // Build the regex
    let regex = build_regex(&pattern, flags_str)?;

    let result = regex.is_match(&input);

    Ok(XPathValue::boolean(result))
}

/// fn:replace($input as xs:string?, $pattern as xs:string, $replacement as xs:string,
///            $flags as xs:string?) as xs:string
///
/// Replaces all occurrences of $pattern in $input with $replacement.
///
/// - FORX0001 if $flags contains invalid characters.
/// - FORX0002 if $pattern is not a valid regular expression.
/// - FORX0003 if $pattern matches a zero-length string.
/// - FORX0004 if $replacement has invalid syntax.
pub fn replace<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() < 3 || args.len() > 4 {
        return Err(XPathError::wrong_number_of_arguments(
            "replace",
            3,
            args.len(),
        ));
    }

    // Get flags (optional fourth argument)
    let flags = if args.len() == 4 {
        atomize_to_string_opt(args.pop().unwrap())?
    } else {
        None
    };

    // Get replacement (third argument)
    let replacement = atomize_to_string_required(args.pop().unwrap())?;

    // Get pattern (second argument)
    let pattern = atomize_to_string_required(args.pop().unwrap())?;

    // Get input (first argument)
    let input = atomize_to_string(args.pop().unwrap())?;

    // Build the regex
    let regex = build_regex(&pattern, flags.as_deref().unwrap_or(""))?;

    // regexml handles FORX0003 (zero-length match) and FORX0004 (invalid replacement) internally
    let result = regex
        .replace_all(&input, &replacement)
        .map_err(|e| match e {
            regexml::Error::MatchesEmptyString => XPathError::regex_matches_zero_length(&pattern),
            regexml::Error::InvalidReplacementString(_) => {
                XPathError::invalid_replacement_string(&replacement)
            }
            _ => XPathError::invalid_regex_pattern(&pattern),
        })?;

    Ok(XPathValue::string(result))
}

/// fn:tokenize($input as xs:string?, $pattern as xs:string, $flags as xs:string?) as xs:string*
///
/// Splits $input into a sequence of strings using $pattern as delimiter.
///
/// - FORX0001 if $flags contains invalid characters.
/// - FORX0002 if $pattern is not a valid regular expression.
/// - FORX0003 if $pattern matches a zero-length string.
pub fn tokenize<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() < 2 || args.len() > 3 {
        return Err(XPathError::wrong_number_of_arguments(
            "tokenize",
            2,
            args.len(),
        ));
    }

    // Get flags (optional third argument)
    let flags = if args.len() == 3 {
        atomize_to_string_opt(args.pop().unwrap())?
    } else {
        None
    };

    // Get pattern (second argument)
    let pattern = atomize_to_string_required(args.pop().unwrap())?;

    // Get input (first argument)
    let input = atomize_to_string(args.pop().unwrap())?;

    // If input is empty, return empty sequence
    if input.is_empty() {
        return Ok(XPathValue::Empty);
    }

    // Build the regex
    let regex = build_regex(&pattern, flags.as_deref().unwrap_or(""))?;

    // regexml handles FORX0003 (zero-length match) internally
    let token_iter = regex.tokenize(&input).map_err(|e| match e {
        regexml::Error::MatchesEmptyString => XPathError::regex_matches_zero_length(&pattern),
        _ => XPathError::invalid_regex_pattern(&pattern),
    })?;

    // Convert to XPathValue sequence, filtering out empty tokens
    let items: Vec<XmlItem<N>> = token_iter
        .filter(|s| !s.is_empty())
        .map(|s| XmlItem::Atomic(XmlValue::string(&s)))
        .collect();

    Ok(XPathValue::from_sequence(items))
}

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

/// Build a Regex from an XPath pattern and flags using regexml.
///
/// regexml natively handles XML Schema regex syntax including:
/// - Character class subtraction `[A-Z-[OI]]`
/// - XSD-specific escapes `\i`, `\c`, `\I`, `\C`
/// - Unicode categories `\p{Lu}`, `\P{Lu}`
/// - Flag handling (s, m, i, x)
fn build_regex(pattern: &str, flags: &str) -> Result<Regex, XPathError> {
    Regex::xpath(pattern, flags).map_err(|e| match e {
        regexml::Error::InvalidFlags(_) => XPathError::invalid_regex_flags(flags),
        regexml::Error::Syntax(_) => XPathError::invalid_regex_pattern(pattern),
        _ => XPathError::invalid_regex_pattern(pattern),
    })
}

#[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_matches_basic() {
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        let result = matches(
            &mut ctx,
            vec![XPathValue::string("abracadabra"), XPathValue::string("bra")],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![XPathValue::string("abracadabra"), XPathValue::string("xyz")],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![
                XPathValue::string("HELLO"),
                XPathValue::string("hello"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![
                XPathValue::string("line1\nline2"),
                XPathValue::string("^line2"),
                XPathValue::string("m"),
            ],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![
                XPathValue::string("abcd\ndefg\n"),
                XPathValue::string("^$"),
                XPathValue::string("m"),
            ],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![
                XPathValue::string("abcd\n\ndefg\n"),
                XPathValue::string("^$"),
                XPathValue::string("m"),
            ],
        )
        .unwrap();

        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

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

        let match_x = matches(
            &mut ctx,
            vec![
                XPathValue::string("X"),
                XPathValue::string("[A-Z-[OI]]"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();
        assert!(
            matches!(match_x, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );

        let match_o = matches(
            &mut ctx,
            vec![
                XPathValue::string("O"),
                XPathValue::string("[A-Z-[OI]]"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();
        assert!(
            matches!(match_o, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );

        let match_i = matches(
            &mut ctx,
            vec![
                XPathValue::string("i"),
                XPathValue::string("[A-Z-[OI]]"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();
        assert!(
            matches!(match_i, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );
    }

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

        let upper = matches(
            &mut ctx,
            vec![
                XPathValue::string("m"),
                XPathValue::string(r"\p{Lu}"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();
        assert!(
            matches!(upper, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );

        let not_upper = matches(
            &mut ctx,
            vec![
                XPathValue::string("m"),
                XPathValue::string(r"\P{Lu}"),
                XPathValue::string("i"),
            ],
        )
        .unwrap();
        assert!(
            matches!(not_upper, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

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

        let result = matches(
            &mut ctx,
            vec![
                XPathValue::string("test"),
                XPathValue::string("test"),
                XPathValue::string("z"),
            ],
        );

        assert!(matches!(result, Err(XPathError::FORX0001 { .. })));
    }

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

        let result = matches(
            &mut ctx,
            vec![XPathValue::string("test"), XPathValue::string("[invalid")],
        );

        assert!(matches!(result, Err(XPathError::FORX0002 { .. })));
    }

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

        let result = replace(
            &mut ctx,
            vec![
                XPathValue::string("abracadabra"),
                XPathValue::string("a"),
                XPathValue::string("X"),
            ],
        )
        .unwrap();

        if let XPathValue::Item(XmlItem::Atomic(v)) = result {
            assert_eq!(v.as_string(), Some("XbrXcXdXbrX"));
        } else {
            panic!("Expected string");
        }
    }

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

        let result = replace(
            &mut ctx,
            vec![
                XPathValue::string("hello world"),
                XPathValue::string("([a-z]+) ([a-z]+)"),
                XPathValue::string("$2 $1"),
            ],
        )
        .unwrap();

        if let XPathValue::Item(XmlItem::Atomic(v)) = result {
            assert_eq!(v.as_string(), Some("world hello"));
        } else {
            panic!("Expected string");
        }
    }

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

        let result = replace(
            &mut ctx,
            vec![
                XPathValue::string("test"),
                XPathValue::string("a?"),
                XPathValue::string("X"),
            ],
        );

        assert!(matches!(result, Err(XPathError::FORX0003 { .. })));
    }

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

        // $ not followed by digit or $
        let result = replace(
            &mut ctx,
            vec![
                XPathValue::string("test"),
                XPathValue::string("t"),
                XPathValue::string("$x"),
            ],
        );

        assert!(matches!(result, Err(XPathError::FORX0004 { .. })));
    }

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

        let result = tokenize(
            &mut ctx,
            vec![XPathValue::string("a,b,c"), XPathValue::string(",")],
        )
        .unwrap();

        match result {
            XPathValue::Sequence(items) => {
                assert_eq!(items.len(), 3);
                let strs: Vec<String> = items
                    .iter()
                    .map(|item| {
                        if let XmlItem::Atomic(v) = item {
                            v.to_string_value()
                        } else {
                            panic!("Expected atomic")
                        }
                    })
                    .collect();
                assert_eq!(strs, vec!["a", "b", "c"]);
            }
            _ => panic!("Expected sequence"),
        }
    }

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

        let result = tokenize(
            &mut ctx,
            vec![
                XPathValue::string("red   green   blue"),
                XPathValue::string("\\s+"),
            ],
        )
        .unwrap();

        match result {
            XPathValue::Sequence(items) => {
                assert_eq!(items.len(), 3);
            }
            _ => panic!("Expected sequence"),
        }
    }

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

        let result = tokenize(
            &mut ctx,
            vec![XPathValue::string(""), XPathValue::string(",")],
        )
        .unwrap();

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

    #[test]
    fn test_tokenize_filters_empty_tokens() {
        // Test that tokenize filters out empty tokens from leading/trailing delimiters
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        // Leading delimiter - should not produce empty token at start
        let result = tokenize(
            &mut ctx,
            vec![XPathValue::string(",a,b"), XPathValue::string(",")],
        )
        .unwrap();

        match result {
            XPathValue::Sequence(items) => {
                assert_eq!(items.len(), 2); // "a" and "b" only, no leading empty
                let strs: Vec<String> = items
                    .iter()
                    .map(|item| {
                        if let XmlItem::Atomic(v) = item {
                            v.to_string_value()
                        } else {
                            panic!("Expected atomic")
                        }
                    })
                    .collect();
                assert_eq!(strs, vec!["a", "b"]);
            }
            _ => panic!("Expected sequence"),
        }
    }

    #[test]
    fn test_tokenize_trailing_delimiter() {
        // Trailing delimiter - should not produce empty token at end
        let names = NameTable::new();
        let mut ctx = create_context(&names);

        let result = tokenize(
            &mut ctx,
            vec![XPathValue::string("a,b,"), XPathValue::string(",")],
        )
        .unwrap();

        match result {
            XPathValue::Sequence(items) => {
                assert_eq!(items.len(), 2); // "a" and "b" only, no trailing empty
            }
            _ => panic!("Expected sequence"),
        }
    }

    // =========================================================================
    // XSD/XPath character class escape tests (\i, \c)
    // =========================================================================

    #[test]
    fn test_matches_initial_name_char() {
        // Test \i matches initial XML name characters
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = matches(
            &mut ctx,
            vec![XPathValue::string("_foo"), XPathValue::string(r"\i")],
        )
        .unwrap();
        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

    #[test]
    fn test_matches_xml_name_pattern() {
        // Test \i\c* matches XML names
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = matches(
            &mut ctx,
            vec![XPathValue::string("foo:bar"), XPathValue::string(r"\i\c*")],
        )
        .unwrap();
        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

    #[test]
    fn test_matches_digit_not_initial() {
        // Test \i does NOT match digits
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = matches(
            &mut ctx,
            vec![XPathValue::string("123"), XPathValue::string(r"^\i")],
        )
        .unwrap();
        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(false))
        );
    }

    #[test]
    fn test_matches_name_char_with_digits() {
        // Test \c matches digits and other name characters
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = matches(
            &mut ctx,
            vec![XPathValue::string("abc123"), XPathValue::string(r"\c+")],
        )
        .unwrap();
        assert!(
            matches!(result, XPathValue::Item(XmlItem::Atomic(v)) if v.as_boolean() == Some(true))
        );
    }

    #[test]
    fn test_replace_with_name_char_pattern() {
        // Test replace with \c pattern
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = replace(
            &mut ctx,
            vec![
                XPathValue::string("hello world"),
                XPathValue::string(r"\c+"),
                XPathValue::string("X"),
            ],
        )
        .unwrap();

        if let XPathValue::Item(XmlItem::Atomic(v)) = result {
            assert_eq!(v.as_string(), Some("X X"));
        } else {
            panic!("Expected string");
        }
    }

    #[test]
    fn test_tokenize_with_non_name_char() {
        // Test tokenize using \C (non-name character) as delimiter
        let names = NameTable::new();
        let mut ctx = create_context(&names);
        let result = tokenize(
            &mut ctx,
            vec![
                XPathValue::string("foo bar baz"),
                XPathValue::string(r"\C+"),
            ],
        )
        .unwrap();

        match result {
            XPathValue::Sequence(items) => {
                assert_eq!(items.len(), 3);
                let strs: Vec<String> = items
                    .iter()
                    .map(|item| {
                        if let XmlItem::Atomic(v) = item {
                            v.to_string_value()
                        } else {
                            panic!("Expected atomic")
                        }
                    })
                    .collect();
                assert_eq!(strs, vec!["foo", "bar", "baz"]);
            }
            _ => panic!("Expected sequence"),
        }
    }
}