exml 0.7.3-deprecated

Pure Rust XML library based on libxml2
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
use std::iter::repeat;

use crate::{
    chvalid::XmlCharValid,
    parser::build_qname,
    tree::{NodeCommon, XmlAttrPtr, XmlElementType, XmlNodePtr, XmlNsPtr},
    xpath::XmlXPathObjectType,
};

use super::{
    XmlXPathError, XmlXPathParserContext, xml_xpath_cast_node_to_number,
    xml_xpath_cast_node_to_string, xml_xpath_convert_boolean, xml_xpath_convert_number,
    xml_xpath_convert_string, xml_xpath_err, xml_xpath_free_node_set,
    xml_xpath_get_elements_by_ids, xml_xpath_new_boolean, xml_xpath_new_float,
    xml_xpath_new_node_set, xml_xpath_new_string, xml_xpath_node_set_create,
    xml_xpath_node_set_merge, xml_xpath_string_eval_number, xml_xpath_wrap_node_set,
    xml_xpath_wrap_string,
};

/// Macro to check that the number of args passed to an XPath function matches.
#[doc(alias = "CHECK_ARITY")]
pub(crate) fn check_arity(
    ctxt: &mut XmlXPathParserContext,
    nargs: usize,
    x: usize,
) -> Result<(), XmlXPathError> {
    if nargs != x {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidArity as i32);
        return Err(XmlXPathError::XPathInvalidArity);
    }
    if (ctxt.value_tab.len() as i32) < ctxt.value_frame + x as i32 {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathStackError as i32);
        return Err(XmlXPathError::XPathInvalidArity);
    }
    Ok(())
}

/// Macro to try to cast the value on the top of the XPath stack to a number.
#[doc(alias = "CAST_TO_NUMBER")]
pub(super) fn cast_to_number(ctxt: &mut XmlXPathParserContext) {
    if ctxt
        .value()
        .is_some_and(|value| value.typ != XmlXPathObjectType::XPathNumber)
    {
        xml_xpath_number_function(ctxt, 1);
    }
}

/// Macro to try to cast the value on the top of the XPath stack to a string.
#[doc(alias = "CAST_TO_STRING")]
pub(super) fn cast_to_string(ctxt: &mut XmlXPathParserContext) {
    if ctxt
        .value()
        .is_some_and(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_string_function(ctxt, 1);
    }
}

/// Macro to try to cast the value on the top of the XPath stack to a boolean.
#[doc(alias = "CAST_TO_BOOLEAN")]
pub(super) fn cast_to_boolean(ctxt: &mut XmlXPathParserContext) {
    if ctxt
        .value()
        .is_some_and(|value| value.typ != XmlXPathObjectType::XPathBoolean)
    {
        xml_xpath_boolean_function(ctxt, 1);
    }
}

/// Implement the boolean() XPath function
///    boolean boolean(object)
/// The boolean function converts its argument to a boolean as follows:
///    - a number is true if and only if it is neither positive or
///      negative zero nor NaN
///    - a node-set is true if and only if it is non-empty
///    - a string is true if and only if its length is non-zero
#[doc(alias = "xmlXPathBooleanFunction")]
pub fn xml_xpath_boolean_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    let Some(cur) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let cur = xml_xpath_convert_boolean(Some(cur));
    ctxt.value_push(cur);
}

/// Implement the ceiling() XPath function
///    number ceiling(number)
/// The ceiling function returns the smallest (closest to negative infinity)
/// number that is not less than the argument and that is an integer.
#[doc(alias = "xmlXPathCeilingFunction")]
pub fn xml_xpath_ceiling_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_number(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathNumber)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };

    let val = &mut ctxt.value_mut().unwrap().floatval;
    *val = val.ceil();
}

/// Implement the count() XPath function
///    number count(node-set)
#[doc(alias = "xmlXPathCountFunction")]
pub fn xml_xpath_count_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    if ctxt.value().is_none_or(|value| {
        !matches!(
            value.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        )
    }) {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    }
    if let Some(cur) = ctxt.value_pop() {
        if let Some(nodeset) = cur.nodesetval.as_deref() {
            ctxt.value_push(xml_xpath_new_float(nodeset.len() as f64));
        } else {
            ctxt.value_push(xml_xpath_new_float(0.0));
        }
    } else {
        ctxt.value_push(xml_xpath_new_float(0.0));
    }
}

/// Implement the concat() XPath function
///    string concat(string, string, string*)
/// The concat function returns the concatenation of its arguments.
#[doc(alias = "xmlXPathConcatFunction")]
pub fn xml_xpath_concat_function(ctxt: &mut XmlXPathParserContext, mut nargs: usize) {
    if nargs < 2 && check_arity(ctxt, nargs, 2).is_err() {
        return;
    }

    cast_to_string(ctxt);
    let Some(mut cur) = ctxt
        .value_pop()
        .filter(|cur| cur.typ == XmlXPathObjectType::XPathString)
    else {
        return;
    };
    nargs -= 1;

    while nargs > 0 {
        cast_to_string(ctxt);
        let Some(mut newobj) = ctxt
            .value_pop()
            .filter(|cur| cur.typ == XmlXPathObjectType::XPathString)
        else {
            xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
            return;
        };
        let mut tmp = newobj.stringval.take();
        if let Some(curstr) = cur.stringval.take() {
            tmp.get_or_insert_with(String::new).push_str(&curstr);
            newobj.stringval = Some(curstr);
        }
        cur.stringval = tmp;
        nargs -= 1;
    }
    ctxt.value_push(cur);
}

/// Implement the contains() XPath function
///    boolean contains(string, string)
/// The contains function returns true if the first argument string
/// contains the second argument string, and otherwise returns false.
#[doc(alias = "xmlXPathContainsFunction")]
pub fn xml_xpath_contains_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 2).is_err() {
        return;
    }
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let needle = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let hay = ctxt.value_pop();

    let Some(hay) = hay.filter(|hay| hay.typ == XmlXPathObjectType::XPathString) else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    if needle
        .stringval
        .as_deref()
        .filter(|&s| {
            hay.stringval
                .as_deref()
                .expect("Internal Error")
                .contains(s)
        })
        .is_some()
    {
        ctxt.value_push(xml_xpath_new_boolean(true));
    } else {
        ctxt.value_push(xml_xpath_new_boolean(false));
    }
}

/// Implement the id() XPath function
///    node-set id(object)
/// The id function selects elements by their unique ID
/// (see [5.2.1 Unique IDs]). When the argument to id is of type node-set,
/// then the result is the union of the result of applying id to the
/// string value of each of the nodes in the argument node-set. When the
/// argument to id is of any other type, the argument is converted to a
/// string as if by a call to the string function; the string is split
/// into a whitespace-separated list of tokens (whitespace is any sequence
/// of characters matching the production S); the result is a node-set
/// containing the elements in the same document as the context node that
/// have a unique ID equal to any of the tokens in the list.
#[doc(alias = "xmlXPathIdFunction")]
pub fn xml_xpath_id_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    let Some(obj) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    if matches!(
        obj.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        // TODO: Check memory error.
        let mut ret = xml_xpath_node_set_create(None);

        if let Some(nodeset) = obj.nodesetval.as_deref() {
            for &node in &nodeset.node_tab {
                let tokens = xml_xpath_cast_node_to_string(Some(node));
                let ns = xml_xpath_get_elements_by_ids(ctxt.context.doc.unwrap(), Some(&tokens));
                // TODO: Check memory error.
                ret = xml_xpath_node_set_merge(ret, ns.as_deref());
                xml_xpath_free_node_set(ns);
            }
        }
        ctxt.value_push(xml_xpath_wrap_node_set(ret));
        return;
    }
    let obj = xml_xpath_convert_string(Some(obj));
    let strval = obj.stringval.as_deref();
    let ret = xml_xpath_get_elements_by_ids(ctxt.context.doc.unwrap(), strval);
    ctxt.value_push(xml_xpath_wrap_node_set(ret));
}

/// Implement the false() XPath function
///    boolean false()
#[doc(alias = "xmlXPathFalseFunction")]
pub fn xml_xpath_false_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 0).is_err() {
        return;
    }
    ctxt.value_push(xml_xpath_new_boolean(false));
}

/// Implement the floor() XPath function
///    number floor(number)
/// The floor function returns the largest (closest to positive infinity)
/// number that is not greater than the argument and that is an integer.
#[doc(alias = "xmlXPathFloorFunction")]
pub fn xml_xpath_floor_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_number(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathNumber)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };

    let val = &mut ctxt.value_mut().unwrap().floatval;
    *val = val.floor();
}

/// Implement the last() XPath function
///    number last()
/// The last function returns the number of nodes in the context node list.
#[doc(alias = "xmlXPathLastFunction")]
pub fn xml_xpath_last_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 0).is_err() {
        return;
    }
    if ctxt.context.context_size >= 0 {
        ctxt.value_push(xml_xpath_new_float(ctxt.context.context_size as f64));
    } else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidCtxtSize as i32);
    }
}

/// Implement the lang() XPath function
///    boolean lang(string)
/// The lang function returns true or false depending on whether the
/// language of the context node as specified by xml:lang attributes
/// is the same as or is a sublanguage of the language specified by
/// the argument string. The language of the context node is determined
/// by the value of the xml:lang attribute on the context node, or, if
/// the context node has no xml:lang attribute, by the value of the
/// xml:lang attribute on the nearest ancestor of the context node that
/// has an xml:lang attribute. If there is no such attribute, then lang
/// returns false. If there is such an attribute, then lang returns
/// true if the attribute value is equal to the argument ignoring case,
/// or if there is some suffix starting with - such that the attribute
/// value is equal to the argument ignoring that suffix of the attribute
/// value and ignoring case.
#[doc(alias = "xmlXPathLangFunction")]
pub fn xml_xpath_lang_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    let mut ret: i32 = 0;

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let val = ctxt.value_pop().unwrap();
    let lang = val.stringval.as_deref();
    let the_lang = ctxt.context.node.unwrap().get_lang();
    'not_equal: {
        if let (Some(the_lang), Some(lang)) = (the_lang, lang) {
            let the_lang = the_lang.as_bytes();
            let lang = lang.as_bytes();
            let mut i = 0;
            while i < lang.len() {
                if !lang[i].eq_ignore_ascii_case(the_lang.get(i).unwrap_or(&0)) {
                    break 'not_equal;
                }
                i += 1;
            }
            if the_lang.get(i).unwrap_or(&0) == &0 || the_lang[i] == b'-' {
                ret = 1;
            }
        }
    }
    // not_equal:

    ctxt.value_push(xml_xpath_new_boolean(ret != 0));
}

/// Implement the local-name() XPath function
///    string local-name(node-set?)
/// The local-name function returns a string containing the local part
/// of the name of the node in the argument node-set that is first in
/// document order. If the node-set is empty or the first node has no
/// name, an empty string is returned. If the argument is omitted it
/// defaults to the context node.
#[doc(alias = "xmlXPathLocalNameFunction")]
pub fn xml_xpath_local_name_function(ctxt: &mut XmlXPathParserContext, mut nargs: usize) {
    if nargs == 0 {
        ctxt.value_push(xml_xpath_new_node_set(ctxt.context.node));
        nargs = 1;
    }

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    if ctxt.value().is_none_or(|value| {
        !matches!(
            value.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        )
    }) {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    }
    let cur = ctxt.value_pop().unwrap();

    if let Some(nodeset) = cur.nodesetval.as_deref() {
        if !nodeset.node_tab.is_empty() {
            let table = &nodeset.node_tab;
            let i = 0; /* Should be first in document order !!!!! */
            match table[i].element_type() {
                XmlElementType::XmlElementNode
                | XmlElementType::XmlAttributeNode
                | XmlElementType::XmlPINode => {
                    if table[i].name().is_some_and(|name| name.starts_with(' ')) {
                        ctxt.value_push(xml_xpath_new_string(Some("")));
                    } else {
                        ctxt.value_push(xml_xpath_new_string((*table[i]).name().as_deref()));
                    }
                }
                XmlElementType::XmlNamespaceDecl => {
                    let ns = XmlNsPtr::try_from(table[i]).unwrap();
                    let prefix = ns.prefix();
                    let value = xml_xpath_new_string(prefix.as_deref());
                    ctxt.value_push(value);
                }
                _ => {
                    ctxt.value_push(xml_xpath_new_string(Some("")));
                }
            }
        } else {
            ctxt.value_push(xml_xpath_new_string(Some("")));
        }
    } else {
        ctxt.value_push(xml_xpath_new_string(Some("")));
    }
}

/// Implement the not() XPath function
///    boolean not(boolean)
/// The not function returns true if its argument is false,
/// and false otherwise.
#[doc(alias = "xmlXPathNotFunction")]
pub fn xml_xpath_not_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_boolean(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathBoolean)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let val = &mut ctxt.value_mut().unwrap().boolval;
    *val = !*val;
}

/// Implement the name() XPath function
///    string name(node-set?)
/// The name function returns a string containing a QName representing
/// the name of the node in the argument node-set that is first in document
/// order. The QName must represent the name with respect to the namespace
/// declarations in effect on the node whose name is being represented.
/// Typically, this will be the form in which the name occurred in the XML
/// source. This need not be the case if there are namespace declarations
/// in effect on the node that associate multiple prefixes with the same
/// namespace. However, an implementation may include information about
/// the original prefix in its representation of nodes; in this case, an
/// implementation can ensure that the returned string is always the same
/// as the QName used in the XML source. If the argument it omitted it
/// defaults to the context node.
/// Libxml keep the original prefix so the "real qualified name" used is returned.
#[doc(alias = "xmlXPathNameFunction")]
pub(super) fn xml_xpath_name_function(ctxt: &mut XmlXPathParserContext, mut nargs: usize) {
    if nargs == 0 {
        ctxt.value_push(xml_xpath_new_node_set(ctxt.context.node));
        nargs = 1;
    }

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    if ctxt.value().is_none_or(|value| {
        !matches!(
            value.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        )
    }) {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    }
    let cur = ctxt.value_pop().unwrap();

    if let Some(nodeset) = cur.nodesetval.as_deref() {
        if !nodeset.node_tab.is_empty() {
            let table = &nodeset.node_tab;
            let i = 0; /* Should be first in document order !!!!! */

            match table[i].element_type() {
                XmlElementType::XmlElementNode => {
                    let node = XmlNodePtr::try_from(table[i]).unwrap();
                    if node.name.starts_with(' ') {
                        ctxt.value_push(xml_xpath_new_string(Some("")));
                    } else if let Some(prefix) =
                        node.ns.as_deref().and_then(|ns| ns.prefix.as_deref())
                    {
                        let nodename = node.name().unwrap();
                        let fullname = build_qname(&nodename, Some(prefix));
                        ctxt.value_push(xml_xpath_wrap_string(Some(&fullname)));
                    } else {
                        ctxt.value_push(xml_xpath_new_string(node.name().as_deref()));
                    }
                }
                XmlElementType::XmlAttributeNode => {
                    let attr = XmlAttrPtr::try_from(table[i]).unwrap();
                    if attr.name.starts_with(' ') {
                        ctxt.value_push(xml_xpath_new_string(Some("")));
                    } else if let Some(prefix) =
                        attr.ns.as_deref().and_then(|ns| ns.prefix.as_deref())
                    {
                        let attrname = attr.name().unwrap();
                        let fullname = build_qname(&attrname, Some(prefix));
                        ctxt.value_push(xml_xpath_wrap_string(Some(&fullname)));
                    } else {
                        ctxt.value_push(xml_xpath_new_string(attr.name().as_deref()));
                    }
                }
                _ => {
                    ctxt.value_push(xml_xpath_new_node_set(Some(table[i])));
                    xml_xpath_local_name_function(ctxt, 1);
                }
            }
        } else {
            ctxt.value_push(xml_xpath_new_string(Some("")));
        }
    } else {
        ctxt.value_push(xml_xpath_new_string(Some("")));
    }
}

/// Implement the namespace-uri() XPath function
///    string namespace-uri(node-set?)
/// The namespace-uri function returns a string containing the
/// namespace URI of the expanded name of the node in the argument
/// node-set that is first in document order. If the node-set is empty,
/// the first node has no name, or the expanded name has no namespace
/// URI, an empty string is returned. If the argument is omitted it
/// defaults to the context node.
#[doc(alias = "xmlXPathNamespaceURIFunction")]
pub fn xml_xpath_namespace_uri_function(ctxt: &mut XmlXPathParserContext, mut nargs: usize) {
    if nargs == 0 {
        ctxt.value_push(xml_xpath_new_node_set(ctxt.context.node));
        nargs = 1;
    }
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    if ctxt.value().is_none_or(|value| {
        !matches!(
            value.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        )
    }) {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    }
    let cur = ctxt.value_pop().unwrap();

    if let Some(nodeset) = cur.nodesetval.as_deref() {
        if !nodeset.node_tab.is_empty() {
            let table = &nodeset.node_tab;
            let i = 0; /* Should be first in document order !!!!! */
            match table[i].element_type() {
                XmlElementType::XmlElementNode | XmlElementType::XmlAttributeNode => {
                    if let Ok(Some(ns)) = XmlNodePtr::try_from(table[i])
                        .map(|node| node.ns)
                        .or_else(|_| XmlAttrPtr::try_from(table[i]).map(|attr| attr.ns))
                    {
                        ctxt.value_push(xml_xpath_new_string(ns.href.as_deref()));
                    } else {
                        ctxt.value_push(xml_xpath_new_string(Some("")));
                    }
                }
                _ => {
                    ctxt.value_push(xml_xpath_new_string(Some("")));
                }
            }
        } else {
            ctxt.value_push(xml_xpath_new_string(Some("")));
        }
    } else {
        ctxt.value_push(xml_xpath_new_string(Some("")));
    }
}

/// Implement the normalize-space() XPath function
///    string normalize-space(string?)
/// The normalize-space function returns the argument string with white
/// space normalized by stripping leading and trailing whitespace
/// and replacing sequences of whitespace characters by a single
/// space. Whitespace characters are the same allowed by the S production
/// in XML. If the argument is omitted, it defaults to the context
/// node converted to a string, in other words the value of the context node.
#[doc(alias = "xmlXPathNormalizeFunction")]
pub fn xml_xpath_normalize_function(ctxt: &mut XmlXPathParserContext, mut nargs: usize) {
    if nargs == 0 {
        // Use current context node
        let val = xml_xpath_cast_node_to_string(ctxt.context.node);
        ctxt.value_push(xml_xpath_wrap_string(Some(&val)));
        nargs = 1;
    }

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let Some(source) = ctxt.value_mut().unwrap().stringval.as_deref_mut() else {
        return;
    };
    let oldlen = source.len();
    // Skip leading whitespaces
    let Some(start) = source.find(|c: char| !c.is_xml_blank_char()) else {
        ctxt.value_mut()
            .unwrap()
            .stringval
            .as_mut()
            .unwrap()
            .clear();
        return;
    };
    let target = unsafe { source.as_bytes_mut() };

    // Collapse intermediate whitespaces, and skip trailing whitespaces
    let mut written = 0;
    let mut blank = false;
    for i in start..oldlen {
        let c = target[i];
        if c.is_xml_blank_char() {
            blank = true;
        } else {
            if blank {
                target[written] = 0x20;
                written += 1;
                blank = false;
            }
            target[written] = c;
            written += 1;
        }
    }
    ctxt.value_mut()
        .unwrap()
        .stringval
        .as_mut()
        .unwrap()
        .truncate(written);
}

/// Implement the number() XPath function
///    number number(object?)
#[doc(alias = "xmlXPathNumberFunction")]
pub fn xml_xpath_number_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if nargs == 0 {
        if let Some(context_node) = ctxt.context.node {
            let content = context_node.get_content();
            let res = xml_xpath_string_eval_number(content.as_deref());
            ctxt.value_push(xml_xpath_new_float(res));
        } else {
            ctxt.value_push(xml_xpath_new_float(0.0));
        }
        return;
    }

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    let cur = ctxt.value_pop();
    ctxt.value_push(xml_xpath_convert_number(cur));
}

/// Implement the position() XPath function
///    number position()
/// The position function returns the position of the context node in the
/// context node list. The first position is 1, and so the last position
/// will be equal to last().
#[doc(alias = "xmlXPathPositionFunction")]
pub fn xml_xpath_position_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 0).is_err() {
        return;
    }
    if ctxt.context.proximity_position >= 0 {
        ctxt.value_push(xml_xpath_new_float(ctxt.context.proximity_position as f64));
    } else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidCtxtPosition as i32);
    }
}

/// Implement the round() XPath function
///    number round(number)
/// The round function returns the number that is closest to the
/// argument and that is an integer. If there are two such numbers,
/// then the one that is closest to positive infinity is returned.
#[doc(alias = "xmlXPathRoundFunction")]
pub fn xml_xpath_round_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_number(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathNumber)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };

    let f: f64 = ctxt.value().unwrap().floatval;

    if (-0.5..0.5).contains(&f) {
        /* Handles negative zero. */
        ctxt.value_mut().unwrap().floatval *= 0.0;
    } else {
        let mut rounded: f64 = f.floor();
        if f - rounded >= 0.5 {
            rounded += 1.0;
        }
        ctxt.value_mut().unwrap().floatval = rounded;
    }
}

/// Implement the string() XPath function
///    string string(object?)
/// The string function converts an object to a string as follows:
///    - A node-set is converted to a string by returning the value of
///      the node in the node-set that is first in document order.
///      If the node-set is empty, an empty string is returned.
///    - A number is converted to a string as follows
///      + NaN is converted to the string NaN
///      + positive zero is converted to the string 0
///      + negative zero is converted to the string 0
///      + positive infinity is converted to the string Infinity
///      + negative infinity is converted to the string -Infinity
///      + if the number is an integer, the number is represented in
///        decimal form as a Number with no decimal point and no leading
///        zeros, preceded by a minus sign (-) if the number is negative
///      + otherwise, the number is represented in decimal form as a
///        Number including a decimal point with at least one digit
///        before the decimal point and at least one digit after the
///        decimal point, preceded by a minus sign (-) if the number
///        is negative; there must be no leading zeros before the decimal
///        point apart possibly from the one required digit immediately
///        before the decimal point; beyond the one required digit
///        after the decimal point there must be as many, but only as
///        many, more digits as are needed to uniquely distinguish the
///        number from all other IEEE 754 numeric values.
///    - The boolean false value is converted to the string false.
///      The boolean true value is converted to the string true.
///
/// If the argument is omitted, it defaults to a node-set with the
/// context node as its only member.
#[doc(alias = "xmlXPathStringFunction")]
pub fn xml_xpath_string_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if nargs == 0 {
        let val = xml_xpath_cast_node_to_string(ctxt.context.node);
        ctxt.value_push(xml_xpath_wrap_string(Some(&val)));
        return;
    }

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    let Some(cur) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    ctxt.value_push(xml_xpath_convert_string(Some(cur)));
}

/// Implement the string-length() XPath function
///    number string-length(string?)
/// The string-length returns the number of characters in the string
/// (see [3.6 Strings]). If the argument is omitted, it defaults to
/// the context node converted to a string, in other words the value
/// of the context node.
#[doc(alias = "xmlXPathStringLengthFunction")]
pub fn xml_xpath_string_length_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if nargs == 0 {
        if let Some(context_node) = ctxt.context.node {
            let content = xml_xpath_cast_node_to_string(Some(context_node));
            ctxt.value_push(xml_xpath_new_float(content.chars().count() as f64));
        } else {
            ctxt.value_push(xml_xpath_new_float(0.0));
        }
        return;
    }
    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let cur = ctxt.value_pop().unwrap();
    ctxt.value_push(xml_xpath_new_float(
        cur.stringval.as_deref().map_or(0, |s| s.chars().count()) as _,
    ));
}

/// Implement the starts-with() XPath function
///    boolean starts-with(string, string)
/// The starts-with function returns true if the first argument string
/// starts with the second argument string, and otherwise returns false.
#[doc(alias = "xmlXPathStartsWithFunction")]
pub fn xml_xpath_starts_with_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 2).is_err() {
        return;
    }
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let needle = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let hay = ctxt.value_pop();

    let Some(hay) = hay.filter(|hay| hay.typ == XmlXPathObjectType::XPathString) else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let m = hay.stringval.as_deref().map_or(0, |s| s.len());
    let n = needle.stringval.as_deref().map_or(0, |s| s.len());
    if &hay.stringval.as_deref().unwrap()[..n.min(m)]
        != needle.stringval.as_deref().expect("Internal Error")
    {
        ctxt.value_push(xml_xpath_new_boolean(false));
    } else {
        ctxt.value_push(xml_xpath_new_boolean(true));
    }
}

/// Implement the substring() XPath function
///    string substring(string, number, number?)
/// The substring function returns the substring of the first argument
/// starting at the position specified in the second argument with
/// length specified in the third argument. For example,
/// substring("12345",2,3) returns "234". If the third argument is not
/// specified, it returns the substring starting at the position specified
/// in the second argument and continuing to the end of the string. For
/// example, substring("12345",2) returns "2345".  More precisely, each
/// character in the string (see [3.6 Strings]) is considered to have a
/// numeric position: the position of the first character is 1, the position
/// of the second character is 2 and so on. The returned substring contains
/// those characters for which the position of the character is greater than
/// or equal to the second argument and, if the third argument is specified,
/// less than the sum of the second and third arguments; the comparisons
/// and addition used for the above follow the standard IEEE 754 rules. Thus:
///  - substring("12345", 1.5, 2.6) returns "234"
///  - substring("12345", 0, 3) returns "12"
///  - substring("12345", 0 div 0, 3) returns ""
///  - substring("12345", 1, 0 div 0) returns ""
///  - substring("12345", -42, 1 div 0) returns "12345"
///  - substring("12345", -1 div 0, 1 div 0) returns ""
#[doc(alias = "xmlXPathSubstringFunction")]
pub fn xml_xpath_substring_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    let mut le: f64 = 0.0;
    let mut i: i32 = 1;
    let mut j: i32 = i32::MAX;

    if nargs < 2 && check_arity(ctxt, nargs, 2).is_err() {
        return;
    }
    if nargs > 3 && check_arity(ctxt, nargs, 3).is_err() {
        return;
    }
    // take care of possible last (position) argument
    if nargs == 3 {
        cast_to_number(ctxt);
        if ctxt
            .value()
            .is_none_or(|value| value.typ != XmlXPathObjectType::XPathNumber)
        {
            xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
            return;
        };
        let len = ctxt.value_pop().unwrap();
        le = len.floatval;
    }

    cast_to_number(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathNumber)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let start = ctxt.value_pop().unwrap();
    let input: f64 = start.floatval;
    cast_to_string(ctxt);
    if ctxt
        .value()
        .is_none_or(|value| value.typ != XmlXPathObjectType::XPathString)
    {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    };
    let str = ctxt.value_pop().unwrap();

    if !matches!(
        input.partial_cmp(&(i32::MAX as f64)),
        Some(std::cmp::Ordering::Less)
    ) {
        // Logical NOT to handle NaNs
        i = i32::MAX;
    } else if input >= 1.0 {
        i = input as _;
        if input - input.floor() >= 0.5 {
            i += 1;
        }
    }

    if nargs == 3 {
        let mut rin: f64;
        let mut rle: f64;

        rin = input.floor();
        if input - rin >= 0.5 {
            rin += 1.0;
        }

        rle = le.floor();
        if le - rle >= 0.5 {
            rle += 1.0;
        }

        let end: f64 = rin + rle;
        if !matches!(
            end.partial_cmp(&1.0),
            Some(std::cmp::Ordering::Equal) | Some(std::cmp::Ordering::Greater)
        ) {
            // Logical NOT to handle NaNs
            j = 1;
        } else if end < i32::MAX as f64 {
            j = end as _;
        }
    }

    if i < j {
        let ret = str
            .stringval
            .as_deref()
            .expect("Internal Error")
            .chars()
            .skip(i as usize - 1)
            .take((j - i) as usize)
            .collect::<String>();
        ctxt.value_push(xml_xpath_new_string(Some(&ret)));
    } else {
        ctxt.value_push(xml_xpath_new_string(Some("")));
    }
}

/// Implement the substring-before() XPath function
///    string substring-before(string, string)
/// The substring-before function returns the substring of the first
/// argument string that precedes the first occurrence of the second
/// argument string in the first argument string, or the empty string
/// if the first argument string does not contain the second argument
/// string. For example, substring-before("1999/04/01","/") returns 1999.
#[doc(alias = "xmlXPathSubstringBeforeFunction")]
pub fn xml_xpath_substring_before_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 2).is_err() {
        return;
    }
    cast_to_string(ctxt);
    let find = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let str = ctxt.value_pop().unwrap();

    let ss = str.stringval.as_deref().unwrap();
    let fs = find.stringval.as_deref().unwrap();
    let target = ss.find(fs).map(|pos| ss[..pos].to_owned());
    ctxt.value_push(xml_xpath_new_string(target.as_deref()));
}

/// Implement the substring-after() XPath function
///    string substring-after(string, string)
/// The substring-after function returns the substring of the first
/// argument string that follows the first occurrence of the second
/// argument string in the first argument string, or the empty stringi
/// if the first argument string does not contain the second argument
/// string. For example, substring-after("1999/04/01","/") returns 04/01,
/// and substring-after("1999/04/01","19") returns 99/04/01.
#[doc(alias = "xmlXPathSubstringAfterFunction")]
pub fn xml_xpath_substring_after_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 2).is_err() {
        return;
    }
    cast_to_string(ctxt);
    let find = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let str = ctxt.value_pop().unwrap();

    let ss = str.stringval.as_deref().unwrap();
    let fs = find.stringval.as_deref().unwrap();
    let target = ss.find(fs).map(|pos| ss[pos..].to_owned());
    ctxt.value_push(xml_xpath_new_string(target.as_deref()));
}

/// Implement the sum() XPath function
///    number sum(node-set)
/// The sum function returns the sum of the values of the nodes in
/// the argument node-set.
#[doc(alias = "xmlXPathSumFunction")]
pub fn xml_xpath_sum_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    let mut res: f64 = 0.0;

    if check_arity(ctxt, nargs, 1).is_err() {
        return;
    }
    if ctxt.value().is_none_or(|value| {
        !matches!(
            value.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        )
    }) {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
        return;
    }
    let cur = ctxt.value_pop().unwrap();

    if let Some(nodeset) = cur.nodesetval.as_deref().filter(|n| !n.is_empty()) {
        if !nodeset.node_tab.is_empty() {
            for &node in &nodeset.node_tab {
                res += xml_xpath_cast_node_to_number(Some(node));
            }
        }
    }
    ctxt.value_push(xml_xpath_new_float(res));
}

/// Implement the true() XPath function
///    boolean true()
#[doc(alias = "xmlXPathTrueFunction")]
pub fn xml_xpath_true_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 0).is_err() {
        return;
    }
    ctxt.value_push(xml_xpath_new_boolean(true));
}

/// Implement the translate() XPath function
///    string translate(string, string, string)
/// The translate function returns the first argument string with
/// occurrences of characters in the second argument string replaced
/// by the character at the corresponding position in the third argument
/// string. For example, translate("bar","abc","ABC") returns the string
/// BAr. If there is a character in the second argument string with no
/// character at a corresponding position in the third argument string
/// (because the second argument string is longer than the third argument
/// string), then occurrences of that character in the first argument
/// string are removed. For example, translate("--aaa--","abc-","ABC")
/// returns "AAA". If a character occurs more than once in second
/// argument string, then the first occurrence determines the replacement
/// character. If the third argument string is longer than the second
/// argument string, then excess characters are ignored.
#[doc(alias = "xmlXPathTranslateFunction")]
pub fn xml_xpath_translate_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    if check_arity(ctxt, nargs, 3).is_err() {
        return;
    }

    cast_to_string(ctxt);
    let to = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let from = ctxt.value_pop().unwrap();
    cast_to_string(ctxt);
    let str = ctxt.value_pop().unwrap();

    let to_str = to.stringval.as_deref().unwrap();
    let from_str = from.stringval.as_deref().unwrap();
    let arg = str.stringval.as_deref().unwrap();
    let mut target = String::with_capacity(arg.len());
    for c in arg.chars() {
        if let Some((_, replace)) = from_str
            .chars()
            .zip(to_str.chars().map(Ok).chain(repeat(Err(()))))
            .find(|e| e.0 == c)
        {
            if let Ok(c) = replace {
                target.push(c);
            }
        } else {
            target.push(c);
        }
    }
    ctxt.value_push(xml_xpath_new_string(Some(&target)));
}

/// Implement the escape-uri() XPath function
///    string escape-uri(string $str, bool $escape-reserved)
///
/// This function applies the URI escaping rules defined in section 2 of [RFC
/// 2396] to the string supplied as $uri-part, which typically represents all
/// or part of a URI. The effect of the function is to replace any special
/// character in the string by an escape sequence of the form %xx%yy...,
/// where xxyy... is the hexadecimal representation of the octets used to
/// represent the character in UTF-8.
///
/// The set of characters that are escaped depends on the setting of the
/// boolean argument $escape-reserved.
///
/// If $escape-reserved is true, all characters are escaped other than lower
/// case letters a-z, upper case letters A-Z, digits 0-9, and the characters
/// referred to in [RFC 2396] as "marks": specifically, "-" | "_" | "." | "!"
/// | "~" | "*" | "'" | "(" | ")". The "%" character itself is escaped only
/// if it is not followed by two hexadecimal digits (that is, 0-9, a-f, and A-F).
///
/// If $escape-reserved is false, the behavior differs in that characters
/// referred to in [RFC 2396] as reserved characters are not escaped. These
/// characters are ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ",".
///
/// [RFC 2396] does not define whether escaped URIs should use lower case or
/// upper case for hexadecimal digits. To ensure that escaped URIs can be
/// compared using string comparison functions, this function must always use
/// the upper-case letters A-F.
///
/// Generally, $escape-reserved should be set to true when escaping a string
/// that is to form a single part of a URI, and to false when escaping an
/// entire URI or URI reference.
///
/// In the case of non-ascii characters, the string is encoded according to
/// utf-8 and then converted according to RFC 2396.
///
/// Examples
///  xf:escape-uri ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"), true())
///  returns "gopher%3A%2F%2Fspinaltap.micro.umn.edu%2F00%2FWeather%2FCalifornia%2FLos%20Angeles%23ocean"
///  xf:escape-uri ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"), false())
///  returns "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles%23ocean"
#[doc(alias = "xmlXPathEscapeUriFunction")]
pub(super) fn xml_xpath_escape_uri_function(ctxt: &mut XmlXPathParserContext, nargs: usize) {
    let mut escape: [u8; 4] = [0; 4];

    if check_arity(ctxt, nargs, 2).is_err() {
        return;
    }

    let escape_reserved = ctxt.pop_boolean();

    cast_to_string(ctxt);
    let str = ctxt.value_pop().unwrap();

    escape[0] = b'%';
    escape[3] = 0;

    let mut target = String::new();
    let cptr = str.stringval.as_deref().expect("Internal Error").as_bytes();
    for (i, &c) in cptr.iter().enumerate() {
        if c.is_ascii_alphanumeric()
            || c == b'-'
            || c == b'_'
            || c == b'.'
            || c == b'!'
            || c == b'~'
            || c == b'*'
            || c == b'\''
            || c == b'('
            || c == b')'
            || (c == b'%'
                && (i + 1 < cptr.len() && cptr[i + 1].is_ascii_hexdigit())
                && (i + 2 < cptr.len() && cptr[i + 2].is_ascii_hexdigit()))
            || (!escape_reserved
                && (c == b';'
                    || c == b'/'
                    || c == b'?'
                    || c == b':'
                    || c == b'@'
                    || c == b'&'
                    || c == b'='
                    || c == b'+'
                    || c == b'$'
                    || c == b','))
        {
            target.push(c as char);
        } else {
            target.push('%');
            let hi = if c >> 4 < 10 {
                b'0' + (c >> 4)
            } else {
                b'A' - 10 + (c >> 4)
            };
            target.push(hi as char);
            let lo = if c & 0xF < 10 {
                b'0' + (c & 0xF)
            } else {
                b'A' - 10 + (c & 0xF)
            };
            target.push(lo as char);
        }
    }
    ctxt.value_push(xml_xpath_new_string(Some(&target)));
}