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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! String functions for XPath 2.0.
//!
//! This module implements XPath 2.0 string functions, delegating to
//! the implementations in `xpath::string_ops`.

use crate::types::value::XmlValue;
use crate::xpath::error::XPathError;
use crate::xpath::iterator::XmlItem;
use crate::xpath::string_ops;
use crate::xpath::DomNavigator;

use super::{
    atomize_to_double, atomize_to_string, atomize_to_string_opt, atomize_to_string_required,
    atomize_to_string_strict, atomize_to_string_strict_opt, XPathValue,
};
use crate::xpath::context::DynamicContext;

/// Default collation URI (codepoint collation).
const DEFAULT_COLLATION: &str = "http://www.w3.org/2005/xpath-functions/collation/codepoint";

/// Validate collation URI - only default collation is supported.
/// Returns Ok(()) if collation is valid (default or empty), FOCH0002 otherwise.
fn validate_collation(collation: Option<&str>) -> Result<(), XPathError> {
    match collation {
        None => Ok(()),
        Some(c) if c.is_empty() || c == DEFAULT_COLLATION => Ok(()),
        Some(c) => Err(XPathError::unknown_collation(c)),
    }
}

// ============================================================================
// String Functions
// ============================================================================

/// fn:concat($arg1 as xs:anyAtomicType?, $arg2 as xs:anyAtomicType?, ...) as xs:string
///
/// Concatenates two or more strings.
pub fn concat<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() < 2 {
        return Err(XPathError::wrong_number_of_arguments(
            "concat",
            2,
            args.len(),
        ));
    }

    let strings: Result<Vec<String>, _> = args.into_iter().map(atomize_to_string).collect();
    let strings = strings?;
    let refs: Vec<&str> = strings.iter().map(|s| s.as_str()).collect();
    let result = string_ops::concat(&refs);
    Ok(XPathValue::string(result))
}

/// fn:string-join($arg1 as xs:string*, $arg2 as xs:string) as xs:string
///
/// Joins strings with a separator.
pub fn string_join<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(
            "string-join",
            2,
            args.len(),
        ));
    }

    let separator = atomize_to_string_required(args.pop().unwrap())?;
    let sequence = args.pop().unwrap();

    // Collect all string values from the sequence
    let strings: Result<Vec<String>, XPathError> = sequence
        .into_vec()
        .into_iter()
        .map(|item| match item {
            XmlItem::Atomic(v) => Ok(v.to_string_value()),
            XmlItem::Node(n) => Ok(n.value()),
        })
        .collect();
    let strings = strings?;
    let refs: Vec<&str> = strings.iter().map(|s| s.as_str()).collect();
    let result = string_ops::string_join(&refs, &separator);
    Ok(XPathValue::string(result))
}

/// fn:substring($sourceString as xs:string?, $start as xs:double) as xs:string
/// fn:substring($sourceString as xs:string?, $start as xs:double, $length as xs:double) as xs:string
///
/// Returns a portion of the source string.
pub fn substring<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(
            "substring",
            2,
            args.len(),
        ));
    }

    let source = atomize_to_string(args.remove(0))?;
    let start = atomize_to_double(args.remove(0))?;
    let length = if !args.is_empty() {
        Some(atomize_to_double(args.remove(0))?)
    } else {
        None
    };

    let result = string_ops::substring(&source, start, length);
    Ok(XPathValue::string(result))
}

/// fn:string-length($arg as xs:string?) as xs:integer
/// fn:string-length() as xs:integer (uses context item)
///
/// Returns the length of the string in characters.
pub fn string_length<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() > 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "string-length",
            1,
            args.len(),
        ));
    }

    let source = if args.is_empty() {
        // Use context item
        match &context.context_item {
            Some(item) => match item {
                XmlItem::Atomic(v) => v.to_string_value(),
                XmlItem::Node(n) => n.value(),
            },
            None => {
                return Err(XPathError::XPDY0002 {
                    message: "Context item is absent".to_string(),
                })
            }
        }
    } else {
        atomize_to_string(args.into_iter().next().unwrap())?
    };

    let len = string_ops::string_length(&source);
    Ok(XPathValue::integer(len as i64))
}

/// fn:normalize-space($arg as xs:string?) as xs:string
/// fn:normalize-space() as xs:string (uses context item)
///
/// Normalizes whitespace in a string.
pub fn normalize_space<N: DomNavigator>(
    context: &mut DynamicContext<'_, N>,
    args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() > 1 {
        return Err(XPathError::wrong_number_of_arguments(
            "normalize-space",
            1,
            args.len(),
        ));
    }

    let source = if args.is_empty() {
        // Use context item
        match &context.context_item {
            Some(item) => match item {
                XmlItem::Atomic(v) => v.to_string_value(),
                XmlItem::Node(n) => n.value(),
            },
            None => {
                return Err(XPathError::XPDY0002 {
                    message: "Context item is absent".to_string(),
                })
            }
        }
    } else {
        atomize_to_string(args.into_iter().next().unwrap())?
    };

    let result = string_ops::normalize_space(&source);
    Ok(XPathValue::string(result))
}

/// fn:normalize-unicode($arg as xs:string?) as xs:string
/// fn:normalize-unicode($arg as xs:string?, $normalizationForm as xs:string) as xs:string
///
/// Normalizes a string using Unicode normalization.
pub fn normalize_unicode<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(
            "normalize-unicode",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict(args.remove(0))?;

    let form = if !args.is_empty() {
        let form_str = atomize_to_string_required(args.remove(0))?;
        let trimmed = form_str.trim();
        if trimmed.is_empty() {
            None
        } else {
            match string_ops::UnicodeNormalizationForm::parse(trimmed) {
                Some(f) => Some(f),
                None => {
                    return Err(XPathError::FOCH0003 {
                        normalization_form: form_str,
                    })
                }
            }
        }
    } else {
        // Default is NFC
        Some(string_ops::UnicodeNormalizationForm::NFC)
    };

    #[cfg(feature = "unicode-normalization")]
    let result = string_ops::normalize_unicode(&source, form);

    #[cfg(not(feature = "unicode-normalization"))]
    let result = string_ops::normalize_unicode(&source, form)?;

    Ok(XPathValue::string(result))
}

/// fn:upper-case($arg as xs:string?) as xs:string
///
/// Converts a string to uppercase.
pub fn upper_case<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(
            "upper-case",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string(args.remove(0))?;
    let result = string_ops::upper_case(&source);
    Ok(XPathValue::string(result))
}

/// fn:lower-case($arg as xs:string?) as xs:string
///
/// Converts a string to lowercase.
pub fn lower_case<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(
            "lower-case",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string(args.remove(0))?;
    let result = string_ops::lower_case(&source);
    Ok(XPathValue::string(result))
}

/// fn:translate($arg as xs:string?, $mapString as xs:string, $transString as xs:string) as xs:string
///
/// Translates characters in a string.
pub fn translate<N: DomNavigator>(
    _context: &mut DynamicContext<'_, N>,
    mut args: Vec<XPathValue<N>>,
) -> Result<XPathValue<N>, XPathError> {
    if args.len() != 3 {
        return Err(XPathError::wrong_number_of_arguments(
            "translate",
            3,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict(args.remove(0))?;
    let map_string = atomize_to_string_strict(args.remove(0))?;
    let trans_string = atomize_to_string_strict(args.remove(0))?;

    let result = string_ops::translate(&source, &map_string, &trans_string);
    Ok(XPathValue::string(result))
}

/// fn:encode-for-uri($uri-part as xs:string?) as xs:string
///
/// Encodes a string for use in a URI.
pub fn encode_for_uri<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(
            "encode-for-uri",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict(args.remove(0))?;
    let result = string_ops::encode_for_uri(&source);
    Ok(XPathValue::string(result))
}

/// fn:iri-to-uri($iri as xs:string?) as xs:string
///
/// Converts an IRI to a URI.
pub fn iri_to_uri<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(
            "iri-to-uri",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict(args.remove(0))?;
    let result = string_ops::iri_to_uri(&source);
    Ok(XPathValue::string(result))
}

/// fn:escape-html-uri($uri as xs:string?) as xs:string
///
/// Escapes a URI for use in HTML.
pub fn escape_html_uri<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(
            "escape-html-uri",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict(args.remove(0))?;
    let result = string_ops::escape_html_uri(&source);
    Ok(XPathValue::string(result))
}

/// fn:contains($arg1 as xs:string?, $arg2 as xs:string?) as xs:boolean
/// fn:contains($arg1 as xs:string?, $arg2 as xs:string?, $collation as xs:string) as xs:boolean
///
/// Checks if a string contains a substring.
pub fn contains<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(
            "contains",
            2,
            args.len(),
        ));
    }

    if args.len() == 3 {
        let _collation = atomize_to_string_required(args.pop().unwrap())?;
    }
    let source = atomize_to_string(args.remove(0))?;
    let substring = atomize_to_string(args.remove(0))?;
    // Collation argument is ignored for now (uses default Unicode codepoint collation)

    let result = string_ops::contains(&source, &substring);
    Ok(XPathValue::boolean(result))
}

/// fn:starts-with($arg1 as xs:string?, $arg2 as xs:string?) as xs:boolean
/// fn:starts-with($arg1 as xs:string?, $arg2 as xs:string?, $collation as xs:string) as xs:boolean
///
/// Checks if a string starts with a prefix.
pub fn starts_with<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(
            "starts-with",
            2,
            args.len(),
        ));
    }

    if args.len() == 3 {
        let _collation = atomize_to_string_required(args.pop().unwrap())?;
    }
    let source = atomize_to_string(args.remove(0))?;
    let prefix = atomize_to_string(args.remove(0))?;
    // Collation argument is ignored for now

    let result = string_ops::starts_with(&source, &prefix);
    Ok(XPathValue::boolean(result))
}

/// fn:ends-with($arg1 as xs:string?, $arg2 as xs:string?) as xs:boolean
/// fn:ends-with($arg1 as xs:string?, $arg2 as xs:string?, $collation as xs:string) as xs:boolean
///
/// Checks if a string ends with a suffix.
pub fn ends_with<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(
            "ends-with",
            2,
            args.len(),
        ));
    }

    if args.len() == 3 {
        let _collation = atomize_to_string_required(args.pop().unwrap())?;
    }
    let source = atomize_to_string(args.remove(0))?;
    let suffix = atomize_to_string(args.remove(0))?;
    // Collation argument is ignored for now

    let result = string_ops::ends_with(&source, &suffix);
    Ok(XPathValue::boolean(result))
}

/// fn:substring-before($arg1 as xs:string?, $arg2 as xs:string?) as xs:string
/// fn:substring-before($arg1 as xs:string?, $arg2 as xs:string?, $collation as xs:string) as xs:string
///
/// Returns the substring before the first occurrence of the pattern.
pub fn substring_before<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(
            "substring-before",
            2,
            args.len(),
        ));
    }

    if args.len() == 3 {
        let _collation = atomize_to_string_required(args.pop().unwrap())?;
    }
    let source = atomize_to_string(args.remove(0))?;
    let pattern = atomize_to_string(args.remove(0))?;
    // Collation argument is ignored for now

    let result = string_ops::substring_before(&source, &pattern);
    Ok(XPathValue::string(result))
}

/// fn:substring-after($arg1 as xs:string?, $arg2 as xs:string?) as xs:string
/// fn:substring-after($arg1 as xs:string?, $arg2 as xs:string?, $collation as xs:string) as xs:string
///
/// Returns the substring after the first occurrence of the pattern.
pub fn substring_after<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(
            "substring-after",
            2,
            args.len(),
        ));
    }

    if args.len() == 3 {
        let _collation = atomize_to_string_required(args.pop().unwrap())?;
    }
    let source = atomize_to_string(args.remove(0))?;
    let pattern = atomize_to_string(args.remove(0))?;
    // Collation argument is ignored for now

    let result = string_ops::substring_after(&source, &pattern);
    Ok(XPathValue::string(result))
}

/// fn:string-to-codepoints($arg as xs:string?) as xs:integer*
///
/// Converts a string to a sequence of codepoints.
pub fn string_to_codepoints<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(
            "string-to-codepoints",
            1,
            args.len(),
        ));
    }

    let source = atomize_to_string_strict_opt(args.remove(0))?;

    match source {
        None => Ok(XPathValue::empty()),
        Some(ref s) if s.is_empty() => Ok(XPathValue::empty()),
        Some(s) => {
            let codepoints = string_ops::string_to_codepoints(&s);
            let items: Vec<XmlItem<N>> = codepoints
                .into_iter()
                .map(|cp| XmlItem::Atomic(XmlValue::integer(cp.into())))
                .collect();
            Ok(XPathValue::from_sequence(items))
        }
    }
}

/// fn:codepoints-to-string($arg as xs:integer*) as xs:string
///
/// Converts a sequence of codepoints to a string.
/// Accepts any numeric type that can be converted to an integer codepoint.
pub fn codepoints_to_string<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(
            "codepoints-to-string",
            1,
            args.len(),
        ));
    }

    let sequence = args.remove(0);
    let items = sequence.into_vec();

    if items.is_empty() {
        return Ok(XPathValue::string(""));
    }

    let mut codepoints = Vec::with_capacity(items.len());
    for item in items {
        match item {
            XmlItem::Atomic(v) => {
                let cp = atomize_to_codepoint(&v)?;
                codepoints.push(cp);
            }
            XmlItem::Node(_) => {
                return Err(XPathError::XPTY0004 {
                    expected: "xs:integer".to_string(),
                    found: "node()".to_string(),
                });
            }
        }
    }

    match string_ops::codepoints_to_string(&codepoints) {
        Some(s) => Ok(XPathValue::string(s)),
        None => Err(XPathError::FOCH0001 {
            codepoint: "invalid".to_string(),
        }),
    }
}

/// Check if a codepoint is a valid XML character per XML 1.0 spec.
///
/// Valid XML chars: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
fn is_valid_xml_char(cp: u32) -> bool {
    matches!(cp,
        0x9 | 0xA | 0xD |
        0x20..=0xD7FF |
        0xE000..=0xFFFD |
        0x10000..=0x10FFFF
    )
}

/// Convert an atomic value to a codepoint (u32).
/// Handles integer types directly and numeric types that are whole numbers.
/// Validates the codepoint is a valid XML character (FOCH0001 if not).
fn atomize_to_codepoint(value: &XmlValue) -> Result<u32, XPathError> {
    let cp;

    // Try integer first (most common case)
    if let Some(i) = value.as_integer() {
        cp = i.try_into().map_err(|_| XPathError::FOCH0001 {
            codepoint: i.to_string(),
        })?;
    } else if value.type_code.is_numeric() {
        if let Some(d) = value.as_double() {
            // Check it's a whole number
            if d.is_nan() || d.is_infinite() || d.fract() != 0.0 {
                return Err(XPathError::FORG0001 {
                    value: d.to_string(),
                    target_type: "xs:integer".to_string(),
                });
            }
            // Check it's in valid u32 range
            if d < 0.0 || d > u32::MAX as f64 {
                return Err(XPathError::FOCH0001 {
                    codepoint: d.to_string(),
                });
            }
            cp = d as u32;
        } else {
            return Err(XPathError::XPTY0004 {
                expected: "xs:integer".to_string(),
                found: format!("{:?}", value.type_code),
            });
        }
    } else {
        return Err(XPathError::XPTY0004 {
            expected: "xs:integer".to_string(),
            found: format!("{:?}", value.type_code),
        });
    }

    // Validate the codepoint is a valid XML character
    if !is_valid_xml_char(cp) {
        return Err(XPathError::FOCH0001 {
            codepoint: cp.to_string(),
        });
    }

    Ok(cp)
}

/// fn:compare($comparand1 as xs:string?, $comparand2 as xs:string?) as xs:integer?
/// fn:compare($comparand1 as xs:string?, $comparand2 as xs:string?, $collation as xs:string) as xs:integer?
///
/// Compares two strings.
pub fn compare<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(
            "compare",
            2,
            args.len(),
        ));
    }

    // Validate collation if provided (third argument)
    if args.len() == 3 {
        let collation = atomize_to_string_required(args.pop().unwrap())?;
        validate_collation(Some(&collation))?;
    }
    let s1 = atomize_to_string_opt(args.remove(0))?;
    let s2 = atomize_to_string_opt(args.remove(0))?;

    match (s1, s2) {
        (Some(a), Some(b)) => {
            let result = string_ops::compare(&a, &b);
            Ok(XPathValue::integer(result as i64))
        }
        _ => Ok(XPathValue::empty()),
    }
}

/// fn:codepoint-equal($comparand1 as xs:string?, $comparand2 as xs:string?) as xs:boolean?
///
/// Compares two strings by codepoint.
pub fn codepoint_equal<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(
            "codepoint-equal",
            2,
            args.len(),
        ));
    }

    let s1 = atomize_to_string_strict_opt(args.remove(0))?;
    let s2 = atomize_to_string_strict_opt(args.remove(0))?;

    match (s1, s2) {
        (Some(a), Some(b)) => {
            let result = string_ops::codepoint_equal(&a, &b);
            Ok(XPathValue::boolean(result))
        }
        _ => Ok(XPathValue::empty()),
    }
}

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

    fn make_context() -> (NameTable, DynamicContext<'static, RoXmlNavigator<'static>>) {
        let table = Box::leak(Box::new(NameTable::new()));
        let static_ctx = Box::leak(Box::new(XPathContext::new(table)));
        let dyn_ctx = DynamicContext::new(static_ctx, 0);
        (NameTable::new(), dyn_ctx)
    }

    #[test]
    fn test_concat() {
        let (_, mut ctx) = make_context();
        let args = vec![
            XPathValue::string("Hello"),
            XPathValue::string(", "),
            XPathValue::string("World!"),
        ];
        let result = concat(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "Hello, World!");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_string_join() {
        let (_, mut ctx) = make_context();
        let seq = XPathValue::from_sequence(vec![
            XmlItem::Atomic(XmlValue::string("a")),
            XmlItem::Atomic(XmlValue::string("b")),
            XmlItem::Atomic(XmlValue::string("c")),
        ]);
        let args = vec![seq, XPathValue::string("-")];
        let result = string_join(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "a-b-c");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_substring() {
        let (_, mut ctx) = make_context();
        let args = vec![
            XPathValue::string("hello"),
            XPathValue::double(2.0),
            XPathValue::double(3.0),
        ];
        let result = substring(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "ell");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_string_length() {
        let (_, mut ctx) = make_context();
        let args = vec![XPathValue::string("hello")];
        let result = string_length(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(*v.as_integer().unwrap(), 5.into());
            }
            _ => panic!("Expected integer"),
        }
    }

    #[test]
    fn test_upper_lower_case() {
        let (_, mut ctx) = make_context();

        let args = vec![XPathValue::string("Hello")];
        let result = upper_case(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "HELLO");
            }
            _ => panic!("Expected string"),
        }

        let args = vec![XPathValue::string("Hello")];
        let result = lower_case(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "hello");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_contains() {
        let (_, mut ctx) = make_context();
        let args = vec![
            XPathValue::string("hello world"),
            XPathValue::string("world"),
        ];
        let result = contains(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert!(v.as_boolean().unwrap());
            }
            _ => panic!("Expected boolean"),
        }
    }

    #[test]
    fn test_starts_ends_with() {
        let (_, mut ctx) = make_context();

        let args = vec![XPathValue::string("hello"), XPathValue::string("he")];
        let result = starts_with(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert!(v.as_boolean().unwrap());
            }
            _ => panic!("Expected boolean"),
        }

        let args = vec![XPathValue::string("hello"), XPathValue::string("lo")];
        let result = ends_with(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert!(v.as_boolean().unwrap());
            }
            _ => panic!("Expected boolean"),
        }
    }

    #[test]
    fn test_encode_for_uri() {
        let (_, mut ctx) = make_context();
        let args = vec![XPathValue::string("hello world")];
        let result = encode_for_uri(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "hello%20world");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_string_to_codepoints() {
        let (_, mut ctx) = make_context();
        let args = vec![XPathValue::string("ABC")];
        let result = string_to_codepoints(&mut ctx, args).unwrap();
        let items = result.into_vec();
        assert_eq!(items.len(), 3);
        match &items[0] {
            XmlItem::Atomic(v) => assert_eq!(*v.as_integer().unwrap(), 65.into()),
            _ => panic!("Expected integer"),
        }
    }

    #[test]
    fn test_codepoints_to_string() {
        let (_, mut ctx) = make_context();
        let seq = XPathValue::from_sequence(vec![
            XmlItem::Atomic(XmlValue::integer(65.into())),
            XmlItem::Atomic(XmlValue::integer(66.into())),
            XmlItem::Atomic(XmlValue::integer(67.into())),
        ]);
        let args = vec![seq];
        let result = codepoints_to_string(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "ABC");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_codepoints_to_string_from_doubles() {
        let (_, mut ctx) = make_context();
        // Use doubles that are whole numbers
        let seq = XPathValue::from_sequence(vec![
            XmlItem::Atomic(XmlValue::double(65.0)),
            XmlItem::Atomic(XmlValue::double(66.0)),
            XmlItem::Atomic(XmlValue::double(67.0)),
        ]);
        let args = vec![seq];
        let result = codepoints_to_string(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "ABC");
            }
            _ => panic!("Expected string"),
        }
    }

    #[test]
    fn test_codepoints_to_string_fractional_double_fails() {
        let (_, mut ctx) = make_context();
        // Use a double with a fractional part - should fail
        let seq = XPathValue::from_sequence(vec![XmlItem::Atomic(XmlValue::double(65.5))]);
        let args = vec![seq];
        let result = codepoints_to_string(&mut ctx, args);
        assert!(result.is_err());
    }

    #[test]
    fn test_codepoints_to_string_empty() {
        let (_, mut ctx) = make_context();
        let seq = XPathValue::<RoXmlNavigator>::Empty;
        let args = vec![seq];
        let result = codepoints_to_string(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(v.as_string().unwrap(), "");
            }
            _ => panic!("Expected empty string"),
        }
    }

    #[test]
    fn test_compare() {
        let (_, mut ctx) = make_context();
        let args = vec![XPathValue::string("abc"), XPathValue::string("abd")];
        let result = compare(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(*v.as_integer().unwrap(), (-1).into());
            }
            _ => panic!("Expected integer"),
        }
    }

    #[test]
    fn test_codepoint_equal() {
        let (_, mut ctx) = make_context();
        let args = vec![XPathValue::string("abc"), XPathValue::string("abc")];
        let result = codepoint_equal(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert!(v.as_boolean().unwrap());
            }
            _ => panic!("Expected boolean"),
        }

        let args = vec![XPathValue::string("abc"), XPathValue::string("ABC")];
        let result = codepoint_equal(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert!(!v.as_boolean().unwrap());
            }
            _ => panic!("Expected boolean"),
        }
    }

    #[test]
    fn test_compare_with_default_collation() {
        let (_, mut ctx) = make_context();
        // Should work with default collation
        let args = vec![
            XPathValue::string("abc"),
            XPathValue::string("abd"),
            XPathValue::string(DEFAULT_COLLATION),
        ];
        let result = compare(&mut ctx, args).unwrap();
        match result {
            XPathValue::Item(XmlItem::Atomic(v)) => {
                assert_eq!(*v.as_integer().unwrap(), (-1).into());
            }
            _ => panic!("Expected integer"),
        }
    }

    #[test]
    fn test_compare_with_invalid_collation() {
        let (_, mut ctx) = make_context();
        // Should fail with unsupported collation
        let args = vec![
            XPathValue::string("abc"),
            XPathValue::string("abd"),
            XPathValue::string("http://example.com/custom-collation"),
        ];
        let result = compare(&mut ctx, args);
        assert!(matches!(result, Err(XPathError::FOCH0002 { .. })));
    }
}