exml 0.7.2

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
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
//! Provide internal methods and data structures for processing XPath.
//!
//! This module is based on `libxml/xpathInternals.h`, `xpath.c` and so on in `libxml2-v2.11.8`.  
//! Please refer to original libxml2 documents also.

// Copyright of the original code is the following.
// --------
// Summary: internal interfaces for XML Path Language implementation
// Description: internal interfaces for XML Path Language implementation
//              used to build new modules on top of XPath like XPointer and XSLT
//
// Copy: See Copyright for the status of this software.
//
// Author: Daniel Veillard
// --------
// xpath.c: XML Path Language implementation
//          XPath is a language for addressing parts of an XML document,
//          designed to be used by both XSLT and XPointer
//
// Reference: W3C Recommendation 16 November 1999
//     http://www.w3.org/TR/1999/REC-xpath-19991116
// Public reference:
//     http://www.w3.org/TR/xpath
//
// See Copyright for the status of this software
//
// Author: daniel@veillard.com

use std::ptr::null_mut;

#[cfg(feature = "libxml_xptr_locs")]
use crate::xpointer::XmlLocationSet;
use crate::{
    chvalid::XmlCharValid,
    error::{__xml_raise_error, XmlErrorDomain, XmlErrorLevel, XmlParserErrors},
    generic_error,
    tree::{
        NodeCommon, XML_XML_NAMESPACE, XmlAttrPtr, XmlDocPtr, XmlDtdPtr, XmlElementType,
        XmlGenericNodePtr, XmlNodePtr, XmlNs, XmlNsPtr,
    },
    valid::xml_get_id,
    xpath::{
        XML_XPATH_NAN, XmlXPathError, XmlXPathObjectType,
        functions::{cast_to_number, xml_xpath_number_function},
        xml_xpath_cast_node_to_number, xml_xpath_cast_node_to_string,
        xml_xpath_cast_number_to_boolean, xml_xpath_cast_to_number, xml_xpath_is_inf,
        xml_xpath_is_nan, xml_xpath_node_set_create, xml_xpath_object_copy,
    },
};

use super::{
    XmlNodeSet, XmlXPathContext, XmlXPathObject, XmlXPathParserContext,
    functions::xml_xpath_boolean_function, xml_xpath_new_node_set, xml_xpath_new_string,
};

// The array xmlXPathErrorMessages corresponds to the enum XmlXPathError
const XML_XPATH_ERROR_MESSAGES: &[&str] = &[
    "Ok\n",
    "Number encoding\n",
    "Unfinished literal\n",
    "Start of literal\n",
    "Expected $ for variable reference\n",
    "Undefined variable\n",
    "Invalid predicate\n",
    "Invalid expression\n",
    "Missing closing curly brace\n",
    "Unregistered function\n",
    "Invalid operand\n",
    "Invalid type\n",
    "Invalid number of arguments\n",
    "Invalid context size\n",
    "Invalid context position\n",
    "Memory allocation error\n",
    "Syntax error\n",
    "Resource error\n",
    "Sub resource error\n",
    "Undefined namespace prefix\n",
    "Encoding error\n",
    "Char out of XML range\n",
    "Invalid or incomplete context\n",
    "Stack usage error\n",
    "Forbidden variable\n",
    "Operation limit exceeded\n",
    "Recursion limit exceeded\n",
    "?? Unknown error ??\n", /* Must be last in the list! */
];
const MAXERRNO: i32 = XML_XPATH_ERROR_MESSAGES.len() as i32 - 1;

/// Handle an XPath error
#[doc(alias = "xmlXPathErr", alias = "xmlXPatherror")]
pub fn xml_xpath_err(ctxt: Option<&mut XmlXPathParserContext>, mut error: i32) {
    if !(0..=MAXERRNO).contains(&error) {
        error = MAXERRNO;
    }
    let Some(ctxt) = ctxt else {
        let code = error + XmlParserErrors::XmlXPathExpressionOk as i32
            - XmlXPathError::XPathExpressionOK as i32;
        let code = XmlParserErrors::try_from(code).unwrap();
        __xml_raise_error!(
            None,
            None,
            None,
            null_mut(),
            None,
            XmlErrorDomain::XmlFromXPath,
            code,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            None,
            None,
            None,
            0,
            0,
            Some(XML_XPATH_ERROR_MESSAGES[error as usize]),
        );
        return;
    };
    // Only report the first error
    if ctxt.error != 0 {
        return;
    }
    ctxt.error = error;
    // cleanup current last error
    ctxt.context.last_error.reset();

    ctxt.context.last_error.domain = XmlErrorDomain::XmlFromXPath;
    ctxt.context.last_error.code = XmlParserErrors::try_from(
        error + XmlParserErrors::XmlXPathExpressionOk as i32
            - XmlXPathError::XPathExpressionOK as i32,
    )
    .unwrap();
    ctxt.context.last_error.level = XmlErrorLevel::XmlErrError;
    ctxt.context.last_error.str1 = Some(ctxt.base.to_string().into());
    // (*(*ctxt).context).last_error.str1 = xml_strdup((*ctxt).base) as *mut c_char;
    ctxt.context.last_error.int1 = ctxt.cur as _;
    ctxt.context.last_error.node = ctxt.context.debug_node;
    if let Some(error) = ctxt.context.error {
        error(ctxt.context.user_data.clone(), &ctxt.context.last_error);
    } else {
        let code = error + XmlParserErrors::XmlXPathExpressionOk as i32
            - XmlXPathError::XPathExpressionOK as i32;
        let code = XmlParserErrors::try_from(code).unwrap();
        __xml_raise_error!(
            None,
            None,
            None,
            null_mut(),
            ctxt.context.debug_node,
            XmlErrorDomain::XmlFromXPath,
            code,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            Some(ctxt.base.to_string().into()),
            None,
            None,
            ctxt.cur as _,
            0,
            Some(XML_XPATH_ERROR_MESSAGES[error as usize]),
        );
    }
}

/// Handle a redefinition of attribute error
#[doc(alias = "xmlXPathErrMemory")]
pub fn xml_xpath_err_memory(ctxt: Option<&mut XmlXPathContext>, extra: Option<&str>) {
    if let Some(ctxt) = ctxt {
        ctxt.last_error.reset();
        if let Some(extra) = extra {
            let buf = format!("Memory allocation failed : {extra}\n",);
            ctxt.last_error.message = Some(buf.into());
            // (*ctxt).last_error.message = xml_strdup(buf.as_ptr()) as *mut c_char;
        } else {
            ctxt.last_error.message = Some("Memory allocation failed\n".into());
            // xml_strdup(c"Memory allocation failed\n".as_ptr() as _) as *mut c_char;
        }
        ctxt.last_error.domain = XmlErrorDomain::XmlFromXPath;
        ctxt.last_error.code = XmlParserErrors::XmlErrNoMemory;
        if let Some(error) = ctxt.error {
            error(ctxt.user_data.clone(), &ctxt.last_error);
        }
    } else if let Some(extra) = extra {
        __xml_raise_error!(
            None,
            None,
            None,
            null_mut(),
            None,
            XmlErrorDomain::XmlFromXPath,
            XmlParserErrors::XmlErrNoMemory,
            XmlErrorLevel::XmlErrFatal,
            None,
            0,
            Some(extra.to_owned().into()),
            None,
            None,
            0,
            0,
            "Memory allocation failed : {}\n",
            extra
        );
    } else {
        __xml_raise_error!(
            None,
            None,
            None,
            null_mut(),
            None,
            XmlErrorDomain::XmlFromXPath,
            XmlParserErrors::XmlErrNoMemory,
            XmlErrorLevel::XmlErrFatal,
            None,
            0,
            None,
            None,
            None,
            0,
            0,
            "Memory allocation failed\n",
        );
    }
}

/// Handle a redefinition of attribute error
#[doc(alias = "xmlXPathPErrMemory")]
pub(super) fn xml_xpath_perr_memory(ctxt: Option<&mut XmlXPathParserContext>, extra: Option<&str>) {
    if let Some(ctxt) = ctxt {
        ctxt.error = XmlXPathError::XPathMemoryError as i32;
        xml_xpath_err_memory(Some(&mut *ctxt.context), extra);
    } else {
        xml_xpath_err_memory(None, extra);
    }
}

pub const XML_NODESET_DEFAULT: usize = 10;

/// Namespace node in libxml don't match the XPath semantic. In a node set
/// the namespace nodes are duplicated and the next pointer is set to the
/// parent node in the XPath semantic.
///
/// Returns the newly created object.
#[doc(alias = "xmlXPathNodeSetDupNs")]
pub fn xml_xpath_node_set_dup_ns(
    node: Option<XmlGenericNodePtr>,
    mut ns: XmlNsPtr,
) -> Option<XmlGenericNodePtr> {
    if node.is_none_or(|node| matches!(node.element_type(), XmlElementType::XmlNamespaceDecl)) {
        if ns.node.is_none() {
            ns.node = ns.next.map(|next| next.into());
        }
        return Some(ns.into());
    }

    // Allocate a new Namespace and fill the fields.
    let Some(mut cur) = XmlNsPtr::new(XmlNs {
        typ: XmlElementType::XmlNamespaceDecl,
        ..Default::default()
    }) else {
        xml_xpath_err_memory(None, Some("duplicating namespace\n"));
        return None;
    };
    cur.href = ns.href.clone();
    cur.prefix = ns.prefix.clone();
    // cur.next = node as *mut XmlNs;
    cur.node = node;
    Some(cur.into())
}

/// Initialize the context to the root of the document
#[doc(alias = "xmlXPathRoot")]
pub fn xml_xpath_root(ctxt: &mut XmlXPathParserContext) {
    ctxt.value_push(xml_xpath_new_node_set(
        ctxt.context.doc.map(|doc| doc.into()),
    ));
}

pub(super) const XPATH_MAX_RECURSION_DEPTH: usize = 5000;

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlXPathAxisVal {
    AxisAncestor = 1,
    AxisAncestorOrSelf = 2,
    AxisAttribute = 3,
    AxisChild = 4,
    AxisDescendant = 5,
    AxisDescendantOrSelf = 6,
    AxisFollowing = 7,
    AxisFollowingSibling = 8,
    AxisNamespace = 9,
    AxisParent = 10,
    AxisPreceding = 11,
    AxisPrecedingSibling = 12,
    AxisSelf = 13,
}

impl TryFrom<i32> for XmlXPathAxisVal {
    type Error = anyhow::Error;
    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value == 1 {
            Ok(Self::AxisAncestor)
        } else if value == 2 {
            Ok(Self::AxisAncestorOrSelf)
        } else if value == 3 {
            Ok(Self::AxisAttribute)
        } else if value == 4 {
            Ok(Self::AxisChild)
        } else if value == 5 {
            Ok(Self::AxisDescendant)
        } else if value == 6 {
            Ok(Self::AxisDescendantOrSelf)
        } else if value == 7 {
            Ok(Self::AxisFollowing)
        } else if value == 8 {
            Ok(Self::AxisFollowingSibling)
        } else if value == 9 {
            Ok(Self::AxisNamespace)
        } else if value == 10 {
            Ok(Self::AxisParent)
        } else if value == 11 {
            Ok(Self::AxisPreceding)
        } else if value == 12 {
            Ok(Self::AxisPrecedingSibling)
        } else if value == 13 {
            Ok(Self::AxisSelf)
        } else {
            Err(anyhow::anyhow!(
                "Invalid convert from value '{value}' to XmlXPathAxisVal"
            ))
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlXPathTestVal {
    NodeTestNone = 0,
    NodeTestType = 1,
    NodeTestPI = 2,
    NodeTestAll = 3,
    NodeTestNs = 4,
    NodeTestName = 5,
}

impl TryFrom<i32> for XmlXPathTestVal {
    type Error = anyhow::Error;
    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value == 0 {
            Ok(Self::NodeTestNone)
        } else if value == 1 {
            Ok(Self::NodeTestType)
        } else if value == 2 {
            Ok(Self::NodeTestPI)
        } else if value == 3 {
            Ok(Self::NodeTestAll)
        } else if value == 4 {
            Ok(Self::NodeTestNs)
        } else if value == 5 {
            Ok(Self::NodeTestName)
        } else {
            Err(anyhow::anyhow!(
                "Invalid convert from value '{value}' to XmlXPathTestVal"
            ))
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlXPathTypeVal {
    NodeTypeNode = 0,
    NodeTypeComment = XmlElementType::XmlCommentNode as isize,
    NodeTypeText = XmlElementType::XmlTextNode as isize,
    NodeTypePI = XmlElementType::XmlPINode as isize,
}

impl TryFrom<i32> for XmlXPathTypeVal {
    type Error = anyhow::Error;
    fn try_from(value: i32) -> Result<Self, Self::Error> {
        if value == 0 {
            Ok(Self::NodeTypeNode)
        } else if value == Self::NodeTypeComment as i32 {
            Ok(Self::NodeTypeComment)
        } else if value == Self::NodeTypeText as i32 {
            Ok(Self::NodeTypeText)
        } else if value == Self::NodeTypePI as i32 {
            Ok(Self::NodeTypePI)
        } else {
            Err(anyhow::anyhow!(
                "Invalid convert from value '{value}' to XmlXPathTypeVal"
            ))
        }
    }
}

// Used for merging node sets in xmlXPathCollectAndTest().
#[doc(alias = "xmlXPathNodeSetMergeFunction")]
pub type XmlXPathNodeSetMergeFunction =
    fn(Option<Box<XmlNodeSet>>, Option<&mut XmlNodeSet>) -> Option<Box<XmlNodeSet>>;

// A traversal function enumerates nodes along an axis.
// Initially it must be called with NULL, and it indicates
// termination on the axis by returning NULL.
pub type XmlXPathTraversalFunction = fn(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr>;

/// Traversal function for the "child" direction and nodes of type element.
/// The child axis contains the children of the context node in document order.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextChildElement")]
pub(super) fn xml_xpath_next_child_element(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let Some(mut cur) = cur else {
        let cur = ctxt.context.node?;
        // Get the first element child.
        match cur.element_type() {
        XmlElementType::XmlElementNode
        | XmlElementType::XmlDocumentFragNode
        // URGENT TODO: entify-refs as well?
        | XmlElementType::XmlEntityRefNode
        | XmlElementType::XmlEntityNode => {
            let mut cur = cur.children()?;
            if matches!(cur.element_type(), XmlElementType::XmlElementNode) {
                return Some(cur);
            }
            while let Some(next) = cur.next().filter(|next| !matches!(next.element_type(), XmlElementType::XmlElementNode)) {
                cur = next;
            }
            return Some(cur);
        }
        XmlElementType::XmlDocumentNode | XmlElementType::XmlHTMLDocumentNode => {
            return XmlDocPtr::try_from(cur).unwrap().get_root_element().map(|root| root.into());
        }
        _ => {
            return None;
        }
    }
    };
    // Get the next sibling element node.
    match cur.element_type() {
        XmlElementType::XmlElementNode
        | XmlElementType::XmlTextNode
        | XmlElementType::XmlEntityRefNode
        | XmlElementType::XmlEntityNode
        | XmlElementType::XmlCDATASectionNode
        | XmlElementType::XmlPINode
        | XmlElementType::XmlCommentNode
        | XmlElementType::XmlXIncludeEnd => {}
        /* case XML_DTD_NODE: */ /* URGENT TODO: DTD-node as well? */
        _ => {
            return None;
        }
    }
    let next = cur.next()?;
    if matches!(next.element_type(), XmlElementType::XmlElementNode) {
        return Some(next);
    }
    cur = next;
    while let Some(next) = cur
        .next()
        .filter(|next| !matches!(next.element_type(), XmlElementType::XmlElementNode))
    {
        cur = next;
    }
    Some(cur)
}

/// Traversal function for the "preceding" direction
/// the preceding axis contains all nodes in the same document as the context
/// node that are before the context node in document order, excluding any
/// ancestors and excluding attribute nodes and namespace nodes; the nodes are
/// ordered in reverse document order
/// This is a faster implementation but internal only since it requires a
/// state kept in the parser context: ctxt.ancestor.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextPrecedingInternal")]
pub(super) fn xml_xpath_next_preceding_internal(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let mut cur = cur.or_else(|| {
        let mut cur = ctxt.context.node?;
        if matches!(cur.element_type(), XmlElementType::XmlAttributeNode) {
            cur = cur.parent()?;
        } else if let Ok(ns) = XmlNsPtr::try_from(cur) {
            cur = ns
                .node
                .filter(|node| node.element_type() != XmlElementType::XmlNamespaceDecl)?;
        }
        ctxt.ancestor = cur.parent();
        Some(cur)
    })?;
    if matches!(cur.element_type(), XmlElementType::XmlNamespaceDecl) {
        return None;
    }
    if let Some(prev) = cur
        .prev()
        .filter(|p| matches!(p.element_type(), XmlElementType::XmlDTDNode))
    {
        cur = prev;
    }
    while cur.prev().is_none() {
        cur = cur.parent()?;
        if Some(cur) == ctxt.context.doc.unwrap().children {
            return None;
        }
        if Some(cur) != ctxt.ancestor {
            return Some(cur);
        }
        ctxt.ancestor = cur.parent();
    }
    cur = cur.prev()?;
    while let Some(last) = cur.last() {
        cur = last;
    }
    Some(cur)
}

/// Filter a node set, keeping only nodes for which the predicate expression
/// matches. Afterwards, keep only nodes between minPos and maxPos in the
/// filtered result.
#[doc(alias = "xmlXPathNodeSetFilter")]
pub(super) fn xml_xpath_node_set_filter(
    ctxt: &mut XmlXPathParserContext,
    set: Option<&mut XmlNodeSet>,
    filter_op_index: i32,
    min_pos: i32,
    max_pos: i32,
    has_ns_nodes: bool,
) {
    let Some(set) = set.filter(|s| !s.is_empty()) else {
        return;
    };

    // Check if the node set contains a sufficient number of nodes for
    // the requested range.
    if (set.node_tab.len() as i32) < min_pos {
        set.clear(has_ns_nodes);
        return;
    }

    let oldnode = ctxt.context.node;
    let olddoc = ctxt.context.doc;
    let oldcs: i32 = ctxt.context.context_size;
    let oldpp: i32 = ctxt.context.proximity_position;

    ctxt.context.context_size = set.node_tab.len() as i32;

    let mut i = 0;
    let mut j = 0;
    let mut pos = 1;
    while i < set.node_tab.len() {
        let node = set.node_tab[i];

        ctxt.context.node = Some(node);
        ctxt.context.proximity_position = i as i32 + 1;

        // Also set the xpath document in case things like
        // key() are evaluated in the predicate.
        //
        // TODO: Get real doc for namespace nodes.
        if !matches!(node.element_type(), XmlElementType::XmlNamespaceDecl)
            && node.document().is_some()
        {
            ctxt.context.doc = node.document();
        }

        let res = ctxt.evaluate_precompiled_operation_to_boolean(filter_op_index as usize, true);

        if ctxt.error != XmlXPathError::XPathExpressionOK as i32 {
            break;
        }
        if res < 0 {
            // Shouldn't happen
            xml_xpath_err(Some(ctxt), XmlXPathError::XPathExprError as i32);
            break;
        }

        if res != 0 && (pos >= min_pos && pos <= max_pos) {
            if i != j {
                set.node_tab[j] = node;
            }

            j += 1;
        } else {
            // Remove the entry from the initial node set.
            if let Ok(ns) = XmlNsPtr::try_from(node) {
                xml_xpath_node_set_free_ns(ns);
            }
        }

        if res != 0 {
            if pos == max_pos {
                i += 1;
                break;
            }

            pos += 1;
        }

        i += 1;
    }

    // Free remaining nodes.
    if has_ns_nodes {
        while i < set.node_tab.len() {
            let node = set.node_tab[i];
            if let Ok(ns) = XmlNsPtr::try_from(node) {
                xml_xpath_node_set_free_ns(ns);
            }
            i += 1;
        }
    }

    set.node_tab.truncate(j);
    set.node_tab.shrink_to_fit();

    ctxt.context.node = oldnode;
    ctxt.context.doc = olddoc;
    ctxt.context.context_size = oldcs;
    ctxt.context.proximity_position = oldpp;
}

/// Move the last node to the first position and clear temporary XPath objects
/// (e.g. namespace nodes) from all other nodes. Sets the length of the list to 1.
#[doc(alias = "xmlXPathNodeSetKeepLast")]
pub(super) fn xml_xpath_node_set_keep_last(set: Option<&mut XmlNodeSet>) {
    let Some(set) = set.filter(|s| s.len() > 1) else {
        return;
    };
    if set.node_tab.len() <= 1 {
        return;
    }
    let len = set.node_tab.len();
    for node in set.node_tab.drain(..len - 1) {
        if let Ok(ns) = XmlNsPtr::try_from(node) {
            xml_xpath_node_set_free_ns(ns);
        }
    }
}

/// Filter a location set, keeping only nodes for which the predicate expression matches.  
/// Afterwards, keep only nodes between minPos and maxPos in the filtered result.
#[doc(alias = "xmlXPathLocationSetFilter")]
#[cfg(feature = "libxml_xptr_locs")]
pub(super) fn xml_xpath_location_set_filter(
    ctxt: &mut XmlXPathParserContext,
    locset: &mut XmlLocationSet,
    filter_op_index: i32,
    min_pos: i32,
    max_pos: i32,
) {
    if locset.loc_tab.is_empty() || filter_op_index == -1 {
        return;
    }

    let oldnode = ctxt.context.node;
    let olddoc = ctxt.context.doc;
    let oldcs: i32 = ctxt.context.context_size;
    let oldpp: i32 = ctxt.context.proximity_position;

    ctxt.context.context_size = locset.loc_tab.len() as i32;

    let mut i = 0;
    let mut j = 0;
    let mut pos = 1;
    while i < locset.loc_tab.len() {
        let context_node = locset.loc_tab[i]
            .user
            .as_ref()
            .and_then(|user| user.as_node())
            .copied()
            .unwrap();

        ctxt.context.node = Some(context_node);
        ctxt.context.proximity_position = i as i32 + 1;

        // Also set the xpath document in case things like
        // key() are evaluated in the predicate.
        //
        // TODO: Get real doc for namespace nodes.
        if !matches!(
            context_node.element_type(),
            XmlElementType::XmlNamespaceDecl
        ) && context_node.document().is_some()
        {
            ctxt.context.doc = context_node.document();
        }

        let res: i32 =
            ctxt.evaluate_precompiled_operation_to_boolean(filter_op_index as usize, true);

        if ctxt.error != XmlXPathError::XPathExpressionOK as i32 {
            break;
        }
        if res < 0 {
            // Shouldn't happen
            xml_xpath_err(Some(ctxt), XmlXPathError::XPathExprError as i32);
            break;
        }

        if res != 0 && (pos >= min_pos && pos <= max_pos) {
            if i != j {
                locset.loc_tab[j] = locset.loc_tab[i].clone();
            }

            j += 1;
        }

        if res != 0 {
            if pos == max_pos {
                // i += 1;
                break;
            }

            pos += 1;
        }

        i += 1;
    }

    // Free remaining nodes.
    locset.loc_tab.truncate(j);
    // If too many elements were removed, shrink table to preserve memory.
    locset.loc_tab.shrink_to(XML_NODESET_DEFAULT);

    ctxt.context.node = oldnode;
    ctxt.context.doc = olddoc;
    ctxt.context.context_size = oldcs;
    ctxt.context.proximity_position = oldpp;
}

pub(super) const MAX_FRAC: usize = 20;

/// ```text
/// [30a]  Float  ::= Number ('e' Digits?)?
///
/// [30]   Number ::= Digits ('.' Digits?)? | '.' Digits
/// [31]   Digits ::= [0-9]+
/// ```
///
/// Compile a Number in the string
/// In complement of the Number expression, this function also handles
/// negative values : '-' Number.
///
/// Returns the let value: f64.
#[doc(alias = "xmlXPathStringEvalNumber")]
pub fn xml_xpath_string_eval_number(s: Option<&str>) -> f64 {
    let Some(s) = s else {
        return 0.0;
    };
    let mut ok = false;
    let mut isneg = false;
    let mut exponent = 0;
    let mut cur = s.trim_matches(|c: char| c.is_xml_blank_char());
    if let Some(rem) = cur.strip_prefix('-') {
        isneg = true;
        cur = rem;
    }
    if !cur.starts_with(|c: char| c == '.' || c.is_ascii_digit()) {
        return XML_XPATH_NAN;
    }

    let mut ret = 0.0;
    while let Some(b) = cur.as_bytes().first().copied().filter(u8::is_ascii_digit) {
        ret = ret * 10. + (b - b'0') as f64;
        cur = &cur[1..];
        ok = true;
    }

    if let Some(rem) = cur.strip_prefix('.') {
        if !ok && !cur.starts_with(|c: char| c.is_ascii_digit()) {
            return XML_XPATH_NAN;
        }

        cur = rem.trim_start_matches('0');
        let mut frac = rem.len() - cur.len();
        let max = frac + MAX_FRAC;
        let mut fraction = 0.0;
        while let Some(b) = cur
            .as_bytes()
            .first()
            .filter(|b| b.is_ascii_digit() && frac < max)
        {
            fraction = fraction * 10. + (b - b'0') as f64;
            frac += 1;
            cur = &cur[1..];
        }
        fraction /= 10.0f64.powi(frac as i32);
        ret += fraction;
        cur = cur.trim_start_matches(|c: char| c.is_ascii_digit());
    }

    let mut is_exponent_negative = false;
    if let Some(rem) = cur.strip_prefix(['e', 'E']) {
        if let Some(rem) = rem.strip_prefix('-') {
            is_exponent_negative = true;
            cur = rem;
        } else {
            cur = rem.strip_prefix('+').unwrap_or(rem);
        }
        while let Some(b) = cur
            .as_bytes()
            .first()
            .filter(|b| b.is_ascii_digit() && exponent < 1000000)
        {
            exponent = exponent * 10 + (b - b'0') as i32;
            cur = &cur[1..];
        }
        cur = cur.trim_start_matches(|c: char| c.is_ascii_digit());
    }
    if !cur.is_empty() {
        return XML_XPATH_NAN;
    }
    if isneg {
        ret = -ret;
    }
    if is_exponent_negative {
        exponent = -exponent;
    }
    ret * 10.0f64.powi(exponent)
}

/// Function computing the beginning of the string value of the node,
/// used to speed up comparisons
///
/// Returns an int usable as a hash
#[doc(alias = "xmlXPathNodeValHash")]
fn xml_xpath_node_val_hash(node: Option<XmlGenericNodePtr>) -> u32 {
    let mut len: i32 = 2;
    let mut ret: u32 = 0;

    let Some(mut node) = node else {
        return 0;
    };

    if matches!(node.element_type(), XmlElementType::XmlDocumentNode) {
        if let Some(tmp) = XmlDocPtr::try_from(node)
            .unwrap()
            .get_root_element()
            .map(|root| root.into())
        {
            node = tmp;
        } else if let Some(tmp) = node.children() {
            node = tmp;
        } else {
            return 0;
        }
    }

    let mut tmp = match node.element_type() {
        XmlElementType::XmlCommentNode
        | XmlElementType::XmlPINode
        | XmlElementType::XmlCDATASectionNode
        | XmlElementType::XmlTextNode => {
            let node = XmlNodePtr::try_from(node).unwrap();
            let Some(string) = node.content.as_deref() else {
                return 0;
            };
            if string.is_empty() {
                return 0;
            }
            let s0 = string.as_bytes()[0];
            let s1 = *string.as_bytes().get(1).unwrap_or(&0);
            return s0 as u32 + ((s1 as u32) << 8);
        }
        XmlElementType::XmlNamespaceDecl => {
            let ns = XmlNsPtr::try_from(node).unwrap();
            let Some(string) = ns.href.as_deref() else {
                return 0;
            };
            if string.is_empty() {
                return 0;
            }
            let s0 = string.as_bytes()[0];
            let s1 = *string.as_bytes().get(1).unwrap_or(&0);
            return s0 as u32 + ((s1 as u32) << 8);
        }
        XmlElementType::XmlAttributeNode => {
            let attr = XmlAttrPtr::try_from(node).unwrap();
            attr.children.map(XmlGenericNodePtr::from)
        }
        XmlElementType::XmlElementNode => node.children(),
        _ => {
            return 0;
        }
    };
    while let Some(now) = tmp {
        let string = match now.element_type() {
            XmlElementType::XmlCDATASectionNode | XmlElementType::XmlTextNode => {
                let node = XmlNodePtr::try_from(now).unwrap();
                node.content.clone()
            }
            _ => None,
        };
        if let Some(string) = string.filter(|s| !s.is_empty()) {
            let bytes = string.as_bytes();
            if len == 1 {
                return ret + ((bytes[0] as u32) << 8);
            }
            if bytes.len() == 1 {
                len = 1;
                ret = bytes[0] as u32;
            } else {
                return bytes[0] as u32 + ((bytes[1] as u32) << 8);
            }
        }
        // Skip to next node
        if let Some(children) = now.children().filter(|children| {
            !matches!(now.element_type(), XmlElementType::XmlDTDNode)
                && !matches!(children.element_type(), XmlElementType::XmlEntityDecl)
        }) {
            tmp = Some(children);
            continue;
        }
        if tmp == Some(node) {
            break;
        }

        if let Some(next) = now.next() {
            tmp = Some(next);
            continue;
        }

        tmp = loop {
            let Some(tmp) = now.parent() else {
                break None;
            };
            if tmp == node {
                break None;
            }
            if let Some(next) = tmp.next() {
                break Some(next);
            }
        };
    }
    ret
}

/// Implement the equal / not equal operation on XPath nodesets:
/// @arg1 == @arg2  or  @arg1 != @arg2
/// If both objects to be compared are node-sets, then the comparison
/// will be true if and only if there is a node in the first node-set and
/// a node in the second node-set such that the result of performing the
/// comparison on the string-values of the two nodes is true.
///
/// (needless to say, this is a costly operation)
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathEqualNodeSets")]
fn xml_xpath_equal_node_sets(arg1: XmlXPathObject, arg2: XmlXPathObject, neq: i32) -> i32 {
    let mut ret: i32 = 0;

    if !matches!(
        arg1.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }
    if !matches!(
        arg2.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }

    let (Some(ns1), Some(ns2)) = (arg1.nodesetval.as_deref(), arg2.nodesetval.as_deref()) else {
        return 0;
    };
    if ns1.node_tab.is_empty() || ns2.node_tab.is_empty() {
        return 0;
    }

    // for equal, check if there is a node pertaining to both sets
    if neq == 0 {
        for &node1 in &ns1.node_tab {
            for &node2 in &ns2.node_tab {
                if node1 == node2 {
                    return 1;
                }
            }
        }
    }

    let mut values1 = vec![None; ns1.node_tab.len()];
    let mut hashs1 = vec![0; ns1.node_tab.len()];
    let mut values2 = vec![None; ns2.node_tab.len()];
    let mut hashs2 = vec![0; ns2.node_tab.len()];
    for (i, &node1) in ns1.node_tab.iter().enumerate() {
        hashs1[i] = xml_xpath_node_val_hash(Some(node1));
        for (j, &node2) in ns2.node_tab.iter().enumerate() {
            if i == 0 {
                hashs2[j] = xml_xpath_node_val_hash(Some(node2));
            }
            if hashs1[i] != hashs2[j] {
                if neq != 0 {
                    ret = 1;
                    break;
                }
            } else {
                if values1[i].is_none() {
                    values1[i] = node1.get_content();
                }
                if values2[j].is_none() {
                    values2[j] = node2.get_content();
                }
                ret = (values1[i] == values2[j]) as i32 ^ neq;
                if ret != 0 {
                    break;
                }
            }
        }
        if ret != 0 {
            break;
        }
    }
    ret
}

/// Implement the equal operation on XPath objects content: @arg1 == @arg2
/// If one object to be compared is a node-set and the other is a number,
/// then the comparison will be true if and only if there is a node in
/// the node-set such that the result of performing the comparison on the
/// number to be compared and on the result of converting the string-value
/// of that node to a number using the number function is true.
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathEqualNodeSetFloat")]
fn xml_xpath_equal_node_set_float(
    ctxt: &mut XmlXPathParserContext,
    arg: XmlXPathObject,
    f: f64,
    neq: i32,
) -> i32 {
    let mut ret: i32 = 0;

    if !matches!(
        arg.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }

    if let Some(ns) = arg.nodesetval.as_deref() {
        for &node in &ns.node_tab {
            ctxt.value_push(xml_xpath_new_string(Some(&xml_xpath_cast_node_to_string(
                Some(node),
            ))));
            xml_xpath_number_function(ctxt, 1);
            if ctxt.error != XmlXPathError::XPathExpressionOK as i32 {
                return 0;
            };
            let val = ctxt.value_pop().unwrap();
            let v = val.floatval;
            if !xml_xpath_is_nan(v) {
                if (neq == 0 && v == f) || (neq != 0 && v != f) {
                    ret = 1;
                    break;
                }
            } else {
                // NaN is unequal to any value
                if neq != 0 {
                    ret = 1;
                }
            }
        }
    }

    ret
}

/// Function computing the beginning of the string value of the node,
/// used to speed up comparisons
///
/// Returns an int usable as a hash
#[doc(alias = "xmlXPathStringHash")]
fn xml_xpath_string_hash(string: &str) -> u32 {
    if string.is_empty() {
        return 0;
    }
    let string = string.as_bytes();
    string[0] as u32 + ((*string.get(1).unwrap_or(&0) as u32) << 8)
}

/// Implement the equal operation on XPath objects content: @arg1 == @arg2
/// If one object to be compared is a node-set and the other is a string,
/// then the comparison will be true if and only if there is a node in
/// the node-set such that the result of performing the comparison on the
/// string-value of the node and the other string is true.
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathEqualNodeSetString")]
fn xml_xpath_equal_node_set_string(arg: XmlXPathObject, s: &str, neq: i32) -> i32 {
    if !matches!(
        arg.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }

    // A NULL nodeset compared with a string is always false
    // (since there is no node equal, and no node not equal)
    let Some(ns) = arg.nodesetval.as_deref().filter(|n| !n.is_empty()) else {
        return 0;
    };

    let hash: u32 = xml_xpath_string_hash(s);
    for &node in &ns.node_tab {
        if xml_xpath_node_val_hash(Some(node)) == hash {
            let str2 = node.get_content();
            if (str2.is_some() && Some(s) == str2.as_deref()) || (str2.is_none() && s.is_empty()) {
                if neq != 0 {
                    continue;
                }
                return 1;
            } else if neq != 0 {
                return 1;
            }
        } else if neq != 0 {
            return 1;
        }
    }
    0
}

fn xml_xpath_equal_values_common(
    ctxt: &mut XmlXPathParserContext,
    mut arg1: XmlXPathObject,
    mut arg2: XmlXPathObject,
) -> i32 {
    let mut ret: i32 = 0;
    // At this point we are assured neither arg1 nor arg2
    // is a nodeset, so we can just pick the appropriate routine.
    match arg1.typ {
        XmlXPathObjectType::XPathUndefined => {}
        XmlXPathObjectType::XPathBoolean => match arg2.typ {
            XmlXPathObjectType::XPathUndefined => {}
            XmlXPathObjectType::XPathBoolean => {
                ret = (arg1.boolval == arg2.boolval) as i32;
            }
            XmlXPathObjectType::XPathNumber => {
                ret = (arg1.boolval == xml_xpath_cast_number_to_boolean(arg2.floatval)) as i32;
            }
            XmlXPathObjectType::XPathString => {
                let f = arg2.stringval.as_deref().is_some_and(|s| !s.is_empty());
                ret = (arg1.boolval == f) as i32;
            }
            XmlXPathObjectType::XPathUsers => {
                todo!()
            }
            #[cfg(feature = "libxml_xptr_locs")]
            XmlXPathObjectType::XPathPoint
            | XmlXPathObjectType::XPathRange
            | XmlXPathObjectType::XPathLocationset => {
                todo!()
            }
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {}
        },
        XmlXPathObjectType::XPathNumber => {
            match arg2.typ {
                XmlXPathObjectType::XPathUndefined => {}
                XmlXPathObjectType::XPathBoolean => {
                    ret = (arg2.boolval == xml_xpath_cast_number_to_boolean(arg1.floatval)) as i32;
                }

                ty @ XmlXPathObjectType::XPathString
                | ty @ XmlXPathObjectType::XPathNumber => 'to_break: {
                    if matches!(ty, XmlXPathObjectType::XPathString) {
                        ctxt.value_push(arg2);
                        xml_xpath_number_function(&mut *ctxt, 1);
                        arg2 = ctxt.value_pop().unwrap();
                        if ctxt.error != 0 {
                            break 'to_break;
                        }
                        // Falls through.
                    }

                    // Hand check NaN and Infinity equalities
                    if xml_xpath_is_nan(arg1.floatval) || xml_xpath_is_nan(arg2.floatval) {
                        ret = 0;
                    } else if xml_xpath_is_inf(arg1.floatval) == 1 {
                        if xml_xpath_is_inf(arg2.floatval) == 1 {
                            ret = 1;
                        } else {
                            ret = 0;
                        }
                    } else if xml_xpath_is_inf(arg1.floatval) == -1 {
                        if xml_xpath_is_inf(arg2.floatval) == -1 {
                            ret = 1;
                        } else {
                            ret = 0;
                        }
                    } else if xml_xpath_is_inf(arg2.floatval) == 1 {
                        if xml_xpath_is_inf(arg1.floatval) == 1 {
                            ret = 1;
                        } else {
                            ret = 0;
                        }
                    } else if xml_xpath_is_inf(arg2.floatval) == -1 {
                        if xml_xpath_is_inf(arg1.floatval) == -1 {
                            ret = 1;
                        } else {
                            ret = 0;
                        }
                    } else {
                        ret = (arg1.floatval == arg2.floatval) as i32;
                    }
                }
                XmlXPathObjectType::XPathUsers => {
                    todo!()
                }
                #[cfg(feature = "libxml_xptr_locs")]
                XmlXPathObjectType::XPathPoint
                | XmlXPathObjectType::XPathRange
                | XmlXPathObjectType::XPathLocationset => {
                    todo!()
                }
                XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {}
            }
        }
        XmlXPathObjectType::XPathString => {
            match arg2.typ {
                XmlXPathObjectType::XPathUndefined => {}
                XmlXPathObjectType::XPathBoolean => {
                    let f = arg1.stringval.as_deref().is_some_and(|s| !s.is_empty());
                    ret = (arg2.boolval == f) as i32;
                }
                XmlXPathObjectType::XPathString => {
                    ret = (arg1.stringval == arg2.stringval) as i32;
                }
                XmlXPathObjectType::XPathNumber => {
                    ctxt.value_push(arg1);
                    xml_xpath_number_function(&mut *ctxt, 1);
                    arg1 = ctxt.value_pop().unwrap();
                    if ctxt.error != 0 {
                        // break;
                    } else {
                        // Hand check NaN and Infinity equalities
                        if xml_xpath_is_nan(arg1.floatval) || xml_xpath_is_nan(arg2.floatval) {
                            ret = 0;
                        } else if xml_xpath_is_inf(arg1.floatval) == 1 {
                            if xml_xpath_is_inf(arg2.floatval) == 1 {
                                ret = 1;
                            } else {
                                ret = 0;
                            }
                        } else if xml_xpath_is_inf(arg1.floatval) == -1 {
                            if xml_xpath_is_inf(arg2.floatval) == -1 {
                                ret = 1;
                            } else {
                                ret = 0;
                            }
                        } else if xml_xpath_is_inf(arg2.floatval) == 1 {
                            if xml_xpath_is_inf(arg1.floatval) == 1 {
                                ret = 1;
                            } else {
                                ret = 0;
                            }
                        } else if xml_xpath_is_inf(arg2.floatval) == -1 {
                            if xml_xpath_is_inf(arg1.floatval) == -1 {
                                ret = 1;
                            } else {
                                ret = 0;
                            }
                        } else {
                            ret = (arg1.floatval == arg2.floatval) as i32;
                        }
                    }
                }
                XmlXPathObjectType::XPathUsers => {
                    todo!()
                }
                #[cfg(feature = "libxml_xptr_locs")]
                XmlXPathObjectType::XPathPoint
                | XmlXPathObjectType::XPathRange
                | XmlXPathObjectType::XPathLocationset => {
                    todo!()
                }
                XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {}
            }
        }
        XmlXPathObjectType::XPathUsers => {
            todo!()
        }
        #[cfg(feature = "libxml_xptr_locs")]
        XmlXPathObjectType::XPathPoint
        | XmlXPathObjectType::XPathRange
        | XmlXPathObjectType::XPathLocationset => {
            todo!()
        }
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {}
    }
    ret
}

/// Implement the equal operation on XPath objects content: @arg1 == @arg2
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathEqualValues")]
pub fn xml_xpath_equal_values(ctxt: &mut XmlXPathParserContext) -> i32 {
    let mut ret: i32 = 0;

    let Some((mut arg2, mut arg1)) = ctxt.value_pop().zip(ctxt.value_pop()) else {
        xml_xpath_err(Some(&mut *ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return 0;
    };

    if arg1 == arg2 {
        return 1;
    }

    // If either argument is a nodeset, it's a 'special case'
    if matches!(
        arg2.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) || matches!(
        arg1.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        // Hack it to assure arg1 is the nodeset
        if !matches!(
            arg1.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) {
            (arg1, arg2) = (arg2, arg1);
        }
        match arg2.typ {
            XmlXPathObjectType::XPathUndefined => {}
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
                ret = xml_xpath_equal_node_sets(arg1, arg2, 0);
            }
            XmlXPathObjectType::XPathBoolean => {
                let f = arg1.nodesetval.as_deref().is_some_and(|n| !n.is_empty());
                ret = (f == arg2.boolval) as i32;
            }
            XmlXPathObjectType::XPathNumber => {
                ret = xml_xpath_equal_node_set_float(ctxt, arg1, arg2.floatval, 0);
            }
            XmlXPathObjectType::XPathString => {
                ret = xml_xpath_equal_node_set_string(
                    arg1,
                    arg2.stringval.as_deref().expect("Internal Error"),
                    0,
                );
            }
            XmlXPathObjectType::XPathUsers => {
                todo!()
            }
            #[cfg(feature = "libxml_xptr_locs")]
            XmlXPathObjectType::XPathPoint
            | XmlXPathObjectType::XPathRange
            | XmlXPathObjectType::XPathLocationset => todo!(),
            // _ => {}
        }
        return ret;
    }

    xml_xpath_equal_values_common(ctxt, arg1, arg2)
}

/// Implement the equal operation on XPath objects content: @arg1 == @arg2
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathNotEqualValues")]
pub fn xml_xpath_not_equal_values(ctxt: &mut XmlXPathParserContext) -> i32 {
    let mut ret: i32 = 0;

    let Some((mut arg2, mut arg1)) = ctxt.value_pop().zip(ctxt.value_pop()) else {
        xml_xpath_err(Some(&mut *ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return 0;
    };

    if arg1 == arg2 {
        return 0;
    }

    // If either argument is a nodeset, it's a 'special case'
    if matches!(
        arg2.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) || matches!(
        arg1.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        // Hack it to assure arg1 is the nodeset
        if !matches!(
            arg1.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) {
            (arg1, arg2) = (arg2, arg1);
        }
        match arg2.typ {
            XmlXPathObjectType::XPathUndefined => {}
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
                ret = xml_xpath_equal_node_sets(arg1, arg2, 1);
            }
            XmlXPathObjectType::XPathBoolean => {
                let f = arg1.nodesetval.as_deref().is_some_and(|n| !n.is_empty());
                ret = (f != arg2.boolval) as i32;
            }
            XmlXPathObjectType::XPathNumber => {
                ret = xml_xpath_equal_node_set_float(ctxt, arg1, arg2.floatval, 1);
            }
            XmlXPathObjectType::XPathString => {
                ret = xml_xpath_equal_node_set_string(
                    arg1,
                    arg2.stringval.as_deref().expect("Internal Error"),
                    1,
                );
            }
            XmlXPathObjectType::XPathUsers => {
                todo!()
            }
            #[cfg(feature = "libxml_xptr_locs")]
            XmlXPathObjectType::XPathPoint
            | XmlXPathObjectType::XPathRange
            | XmlXPathObjectType::XPathLocationset => {
                todo!()
            } // _ => {}
        }
        return ret;
    }

    (xml_xpath_equal_values_common(ctxt, arg1, arg2) == 0) as i32
}

/// Implement the compare operation on nodesets:
///
/// If both objects to be compared are node-sets, then the comparison
/// will be true if and only if there is a node in the first node-set
/// and a node in the second node-set such that the result of performing
/// the comparison on the string-values of the two nodes is true.
/// ....
/// When neither object to be compared is a node-set and the operator
/// is <=, <, >= or >, then the objects are compared by converting both
/// objects to numbers and comparing the numbers according to IEEE 754.
/// ....
/// The number function converts its argument to a number as follows:
///  - a string that consists of optional whitespace followed by an
///    optional minus sign followed by a Number followed by whitespace
///    is converted to the IEEE 754 number that is nearest (according
///    to the IEEE 754 round-to-nearest rule) to the mathematical value
///    represented by the string; any other string is converted to NaN
///
/// Conclusion all nodes need to be converted first to their string value
/// and then the comparison must be done when possible
#[doc(alias = "xmlXPathCompareNodeSets")]
fn xml_xpath_compare_node_sets(
    inf: i32,
    strict: i32,
    arg1: XmlXPathObject,
    arg2: XmlXPathObject,
) -> i32 {
    let mut init: i32 = 0;
    let mut val1: f64;
    let mut ret: i32 = 0;

    if !matches!(
        arg1.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }
    if !matches!(
        arg2.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }

    let Some(ns1_table) = arg1
        .nodesetval
        .as_deref()
        .filter(|set| !set.node_tab.is_empty())
        .map(|n| n.node_tab.as_slice())
    else {
        return 0;
    };
    let Some(ns2_table) = arg2
        .nodesetval
        .as_deref()
        .filter(|set| !set.node_tab.is_empty())
        .map(|n| n.node_tab.as_slice())
    else {
        return 0;
    };

    let mut values2 = vec![0.0; ns2_table.len()];
    for &node1 in ns1_table {
        val1 = xml_xpath_cast_node_to_number(Some(node1));
        if xml_xpath_is_nan(val1) {
            continue;
        }
        for (j, &node2) in ns2_table.iter().enumerate() {
            if init == 0 {
                values2[j] = xml_xpath_cast_node_to_number(Some(node2));
            }
            if xml_xpath_is_nan(values2[j]) {
                continue;
            }
            if inf != 0 && strict != 0 {
                ret = (val1 < values2[j]) as i32;
            } else if inf != 0 && strict == 0 {
                ret = (val1 <= values2[j]) as i32;
            } else if inf == 0 && strict != 0 {
                ret = (val1 > values2[j]) as i32;
            } else if inf == 0 && strict == 0 {
                ret = (val1 >= values2[j]) as i32;
            }
            if ret != 0 {
                break;
            }
        }
        if ret != 0 {
            break;
        }
        init = 1;
    }
    ret
}

/// Implement the compare operation between a nodeset and a number
///     @ns < @val    (1, 1, ...
///     @ns <= @val   (1, 0, ...
///     @ns > @val    (0, 1, ...
///     @ns >= @val   (0, 0, ...
///
/// If one object to be compared is a node-set and the other is a number,
/// then the comparison will be true if and only if there is a node in the
/// node-set such that the result of performing the comparison on the number
/// to be compared and on the result of converting the string-value of that
/// node to a number using the number function is true.
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathCompareNodeSetFloat")]
fn xml_xpath_compare_node_set_float(
    ctxt: &mut XmlXPathParserContext,
    inf: i32,
    strict: i32,
    arg: XmlXPathObject,
    f: XmlXPathObject,
) -> i32 {
    let mut ret: i32 = 0;

    if !matches!(
        arg.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }
    if let Some(ns) = arg.nodesetval.as_deref() {
        for &node in &ns.node_tab {
            ctxt.value_push(xml_xpath_new_string(Some(&xml_xpath_cast_node_to_string(
                Some(node),
            ))));
            xml_xpath_number_function(ctxt, 1);
            ctxt.value_push(xml_xpath_object_copy(&f));
            ret = xml_xpath_compare_values(ctxt, inf, strict);
            if ret != 0 {
                break;
            }
        }
    }
    ret
}

/// Implement the compare operation between a nodeset and a string
///     @ns < @val    (1, 1, ...
///     @ns <= @val   (1, 0, ...
///     @ns > @val    (0, 1, ...
///     @ns >= @val   (0, 0, ...
///
/// If one object to be compared is a node-set and the other is a string,
/// then the comparison will be true if and only if there is a node in
/// the node-set such that the result of performing the comparison on the
/// string-value of the node and the other string is true.
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathCompareNodeSetString")]
fn xml_xpath_compare_node_set_string(
    ctxt: &mut XmlXPathParserContext,
    inf: i32,
    strict: i32,
    arg: XmlXPathObject,
    s: XmlXPathObject,
) -> i32 {
    let mut ret: i32 = 0;

    if !matches!(
        arg.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }
    if let Some(ns) = arg.nodesetval.as_deref() {
        for &node in &ns.node_tab {
            ctxt.value_push(xml_xpath_new_string(Some(&xml_xpath_cast_node_to_string(
                Some(node),
            ))));
            ctxt.value_push(xml_xpath_object_copy(&s));
            ret = xml_xpath_compare_values(ctxt, inf, strict);
            if ret != 0 {
                break;
            }
        }
    }
    ret
}

/// Implement the compare operation between a nodeset and a value
///     @ns < @val    (1, 1, ...
///     @ns <= @val   (1, 0, ...
///     @ns > @val    (0, 1, ...
///     @ns >= @val   (0, 0, ...
///
/// If one object to be compared is a node-set and the other is a boolean,
/// then the comparison will be true if and only if the result of performing
/// the comparison on the boolean and on the result of converting
/// the node-set to a boolean using the boolean function is true.
///
/// Returns 0 or 1 depending on the results of the test.
#[doc(alias = "xmlXPathCompareNodeSetValue")]
fn xml_xpath_compare_node_set_value(
    ctxt: &mut XmlXPathParserContext,
    inf: i32,
    strict: i32,
    arg: XmlXPathObject,
    val: XmlXPathObject,
) -> i32 {
    if !matches!(
        arg.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        return 0;
    }

    match val.typ {
        XmlXPathObjectType::XPathNumber => {
            xml_xpath_compare_node_set_float(ctxt, inf, strict, arg, val)
        }
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree => {
            xml_xpath_compare_node_sets(inf, strict, arg, val)
        }
        XmlXPathObjectType::XPathString => {
            xml_xpath_compare_node_set_string(ctxt, inf, strict, arg, val)
        }
        XmlXPathObjectType::XPathBoolean => {
            ctxt.value_push(arg);
            xml_xpath_boolean_function(ctxt, 1);
            ctxt.value_push(val);
            xml_xpath_compare_values(ctxt, inf, strict)
        }
        _ => {
            generic_error!(
                "xmlXPathCompareNodeSetValue: Can't compare node set and object of type {:?}\n",
                val.typ
            );
            xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidType as i32);
            0
        }
    }
}

/// Implement the compare operation on XPath objects:
///     @arg1 < @arg2    (1, 1, ...
///     @arg1 <= @arg2   (1, 0, ...
///     @arg1 > @arg2    (0, 1, ...
///     @arg1 >= @arg2   (0, 0, ...
///
/// When neither object to be compared is a node-set and the operator is
/// <=, <, >=, >, then the objects are compared by converted both objects
/// to numbers and comparing the numbers according to IEEE 754. The <
/// comparison will be true if and only if the first number is less than the
/// second number. The <= comparison will be true if and only if the first
/// number is less than or equal to the second number. The > comparison
/// will be true if and only if the first number is greater than the second
/// number. The >= comparison will be true if and only if the first number
/// is greater than or equal to the second number.
///
/// Returns 1 if the comparison succeeded, 0 if it failed
#[doc(alias = "xmlXPathCompareValues")]
pub fn xml_xpath_compare_values(ctxt: &mut XmlXPathParserContext, inf: i32, strict: i32) -> i32 {
    let mut ret: i32 = 0;
    let arg1i: i32;
    let arg2i: i32;

    let Some((mut arg2, mut arg1)) = ctxt.value_pop().zip(ctxt.value_pop()) else {
        xml_xpath_err(Some(&mut *ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return 0;
    };

    if matches!(
        arg2.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) || matches!(
        arg1.typ,
        XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
    ) {
        // If either argument is a XpathNodeset or XpathXsltTree the two arguments
        // are not freed from within this routine; they will be freed from the
        // called routine, e.g. xmlXPathCompareNodeSets or xmlXPathCompareNodeSetValue
        if matches!(
            arg2.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) && matches!(
            arg1.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) {
            ret = xml_xpath_compare_node_sets(inf, strict, arg1, arg2);
        } else if matches!(
            arg1.typ,
            XmlXPathObjectType::XPathNodeset | XmlXPathObjectType::XPathXSLTTree
        ) {
            ret = xml_xpath_compare_node_set_value(ctxt, inf, strict, arg1, arg2);
        } else {
            ret = xml_xpath_compare_node_set_value(ctxt, !inf, strict, arg2, arg1);
        }
        return ret;
    }

    if !matches!(arg1.typ, XmlXPathObjectType::XPathNumber) {
        ctxt.value_push(arg1);
        xml_xpath_number_function(&mut *ctxt, 1);
        arg1 = ctxt.value_pop().unwrap();
    }
    if !matches!(arg2.typ, XmlXPathObjectType::XPathNumber) {
        ctxt.value_push(arg2);
        xml_xpath_number_function(&mut *ctxt, 1);
        arg2 = ctxt.value_pop().unwrap();
    }
    if ctxt.error != 0 {
        // goto error;
        return ret;
    }
    // Add tests for infinity and nan
    // => feedback on 3.4 for Inf and NaN
    /* Hand check NaN and Infinity comparisons */
    if xml_xpath_is_nan(arg1.floatval) || xml_xpath_is_nan(arg2.floatval) {
        ret = 0;
    } else {
        arg1i = xml_xpath_is_inf(arg1.floatval);
        arg2i = xml_xpath_is_inf(arg2.floatval);
        if inf != 0 && strict != 0 {
            if (arg1i == -1 && arg2i != -1) || (arg2i == 1 && arg1i != 1) {
                ret = 1;
            } else if arg1i == 0 && arg2i == 0 {
                ret = (arg1.floatval < arg2.floatval) as i32;
            } else {
                ret = 0;
            }
        } else if inf != 0 && strict == 0 {
            if arg1i == -1 || arg2i == 1 {
                ret = 1;
            } else if arg1i == 0 && arg2i == 0 {
                ret = (arg1.floatval <= arg2.floatval) as i32;
            } else {
                ret = 0;
            }
        } else if inf == 0 && strict != 0 {
            if (arg1i == 1 && arg2i != 1) || (arg2i == -1 && arg1i != -1) {
                ret = 1;
            } else if arg1i == 0 && arg2i == 0 {
                ret = (arg1.floatval > arg2.floatval) as i32;
            } else {
                ret = 0;
            }
        } else if inf == 0 && strict == 0 {
            if arg1i == 1 || arg2i == -1 {
                ret = 1;
            } else if arg1i == 0 && arg2i == 0 {
                ret = (arg1.floatval >= arg2.floatval) as i32;
            } else {
                ret = 0;
            }
        }
    }
    // error:
    ret
}

/// Implement the unary - operation on an XPath object
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathValueFlipSign")]
pub fn xml_xpath_value_flip_sign(ctxt: &mut XmlXPathParserContext) {
    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;
}

/// Implement the add operation on XPath objects:
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathAddValues")]
pub fn xml_xpath_add_values(ctxt: &mut XmlXPathParserContext) {
    let Some(mut arg) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let val: f64 = xml_xpath_cast_to_number(&mut arg);
    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;
    };
    ctxt.value_mut().unwrap().floatval += val;
}

/// Implement the subtraction operation on XPath objects:
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathSubValues")]
pub fn xml_xpath_sub_values(ctxt: &mut XmlXPathParserContext) {
    let Some(mut arg) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let val: f64 = xml_xpath_cast_to_number(&mut arg);
    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;
    };
    ctxt.value_mut().unwrap().floatval -= val;
}

/// Implement the multiply operation on XPath objects:
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathMultValues")]
pub fn xml_xpath_mult_values(ctxt: &mut XmlXPathParserContext) {
    let Some(mut arg) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let val: f64 = xml_xpath_cast_to_number(&mut arg);
    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;
    };
    ctxt.value_mut().unwrap().floatval *= val;
}

/// Implement the div operation on XPath objects @arg1 / @arg2:
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathDivValues")]
pub fn xml_xpath_div_values(ctxt: &mut XmlXPathParserContext) {
    let Some(mut arg) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let val: f64 = xml_xpath_cast_to_number(&mut arg);
    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;
    };
    ctxt.value_mut().unwrap().floatval /= val;
}

/// Implement the mod operation on XPath objects: @arg1 / @arg2
/// The numeric operators convert their operands to numbers as if
/// by calling the number function.
#[doc(alias = "xmlXPathModValues")]
pub fn xml_xpath_mod_values(ctxt: &mut XmlXPathParserContext) {
    let Some(mut arg) = ctxt.value_pop() else {
        xml_xpath_err(Some(ctxt), XmlXPathError::XPathInvalidOperand as i32);
        return;
    };
    let arg2: f64 = xml_xpath_cast_to_number(&mut arg);
    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 arg1 = &mut ctxt.value_mut().unwrap().floatval;
    if arg2 == 0.0 {
        *arg1 = XML_XPATH_NAN;
    } else {
        *arg1 %= arg2;
    }
}

/// Traversal function for the "self" direction
/// The self axis contains just the context node itself
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextSelf")]
pub fn xml_xpath_next_self(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    if cur.is_none() {
        return ctxt.context.node;
    }
    None
}

/// Traversal function for the "child" direction
/// The child axis contains the children of the context node in document order.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextChild")]
pub fn xml_xpath_next_child(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let Some(cur) = cur else {
        let node = ctxt.context.node?;
        match node.element_type() {
            XmlElementType::XmlElementNode
            | XmlElementType::XmlTextNode
            | XmlElementType::XmlCDATASectionNode
            | XmlElementType::XmlEntityRefNode
            | XmlElementType::XmlEntityNode
            | XmlElementType::XmlPINode
            | XmlElementType::XmlCommentNode
            | XmlElementType::XmlNotationNode
            | XmlElementType::XmlDTDNode => {
                return node.children();
            }
            XmlElementType::XmlDocumentNode
            | XmlElementType::XmlDocumentTypeNode
            | XmlElementType::XmlDocumentFragNode
            | XmlElementType::XmlHTMLDocumentNode => {
                return node.children();
            }
            XmlElementType::XmlElementDecl
            | XmlElementType::XmlAttributeDecl
            | XmlElementType::XmlEntityDecl
            | XmlElementType::XmlAttributeNode
            | XmlElementType::XmlNamespaceDecl
            | XmlElementType::XmlXIncludeStart
            | XmlElementType::XmlXIncludeEnd => {
                return None;
            }
            _ => unreachable!(),
        }
    };
    if matches!(
        cur.element_type(),
        XmlElementType::XmlDocumentNode | XmlElementType::XmlHTMLDocumentNode
    ) {
        return None;
    }
    cur.next()
}

/// Traversal function for the "descendant" direction
/// the descendant axis contains the descendants of the context node in document
/// order; a descendant is a child or a child of a child and so on.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextDescendant")]
pub fn xml_xpath_next_descendant(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let Some(mut cur) = cur else {
        let node = ctxt.context.node?;
        if matches!(
            node.element_type(),
            XmlElementType::XmlAttributeNode | XmlElementType::XmlNamespaceDecl
        ) {
            return None;
        }

        if ctxt.context.node == ctxt.context.doc.map(|doc| doc.into()) {
            return ctxt.context.doc.unwrap().children;
        }
        return node.children();
    };

    if matches!(cur.element_type(), XmlElementType::XmlNamespaceDecl) {
        return None;
    }
    if let Some(children) = cur.children() {
        // Do not descend on entities declarations
        if !matches!(children.element_type(), XmlElementType::XmlEntityDecl) {
            cur = children;
            // Skip DTDs
            if !matches!(cur.element_type(), XmlElementType::XmlDTDNode) {
                return Some(cur);
            }
        }
    }

    if Some(cur) == ctxt.context.node {
        return None;
    }

    while let Some(next) = cur.next() {
        cur = next;
        if !matches!(
            cur.element_type(),
            XmlElementType::XmlEntityDecl | XmlElementType::XmlDTDNode
        ) {
            return Some(cur);
        }
    }

    loop {
        cur = cur.parent()?;
        if Some(cur) == ctxt.context.node {
            break None;
        }
        if let Some(next) = cur.next() {
            cur = next;
            break Some(cur);
        }
    }
}

/// Traversal function for the "descendant-or-self" direction
/// the descendant-or-self axis contains the context node and the descendants
/// of the context node in document order; thus the context node is the first
/// node on the axis, and the first child of the context node is the second node
/// on the axis
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextDescendantOrSelf")]
pub fn xml_xpath_next_descendant_or_self(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    if cur.is_none() {
        return ctxt.context.node;
    }

    if matches!(
        ctxt.context.node?.element_type(),
        XmlElementType::XmlAttributeNode | XmlElementType::XmlNamespaceDecl
    ) {
        return None;
    }

    xml_xpath_next_descendant(ctxt, cur)
}

/// Traversal function for the "parent" direction
/// The parent axis contains the parent of the context node, if there is one.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextParent")]
pub fn xml_xpath_next_parent(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    // the parent of an attribute or namespace node is the element
    // to which the attribute or namespace node is attached
    // Namespace handling !!!
    if cur.is_none() {
        let node = ctxt.context.node?;
        match node.element_type() {
            XmlElementType::XmlElementNode
            | XmlElementType::XmlTextNode
            | XmlElementType::XmlCDATASectionNode
            | XmlElementType::XmlEntityRefNode
            | XmlElementType::XmlEntityNode
            | XmlElementType::XmlPINode
            | XmlElementType::XmlCommentNode
            | XmlElementType::XmlNotationNode
            | XmlElementType::XmlDTDNode
            | XmlElementType::XmlElementDecl
            | XmlElementType::XmlAttributeDecl
            | XmlElementType::XmlXIncludeStart
            | XmlElementType::XmlXIncludeEnd
            | XmlElementType::XmlEntityDecl => {
                let Some(parent) = node.parent() else {
                    return ctxt.context.doc.map(|doc| doc.into());
                };
                if XmlNodePtr::try_from(parent)
                    .ok()
                    .filter(|node| node.element_type() == XmlElementType::XmlElementNode)
                    .as_deref()
                    .and_then(|node| node.name())
                    .filter(|name| name.starts_with(' ') || name == "fake node libxslt")
                    .is_some()
                {
                    return None;
                }
                return Some(parent);
            }
            XmlElementType::XmlAttributeNode => {
                let att = XmlAttrPtr::try_from(node).unwrap();
                return att.parent.map(XmlGenericNodePtr::from);
            }
            XmlElementType::XmlDocumentNode
            | XmlElementType::XmlDocumentTypeNode
            | XmlElementType::XmlDocumentFragNode
            | XmlElementType::XmlHTMLDocumentNode => {
                return None;
            }
            XmlElementType::XmlNamespaceDecl => {
                let ns = XmlNsPtr::try_from(node).unwrap();
                if let Some(next) = ns
                    .node
                    .filter(|node| node.element_type() != XmlElementType::XmlNamespaceDecl)
                {
                    return Some(next);
                }
                return None;
            }
            _ => unreachable!(),
        }
    }
    None
}

/// Traversal function for the "ancestor-or-self" direction
/// he ancestor-or-self axis contains the context node and ancestors of
/// the context node in reverse document order; thus the context node is
/// the first node on the axis, and the context node's parent the second;
/// parent here is defined the same as with the parent axis.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextAncestorOrSelf")]
pub fn xml_xpath_next_ancestor_or_self(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    if cur.is_none() {
        return ctxt.context.node;
    }
    xml_xpath_next_ancestor(ctxt, cur)
}

/// Traversal function for the "following-sibling" direction
/// The following-sibling axis contains the following siblings of the context
/// node in document order.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextFollowingSibling")]
pub fn xml_xpath_next_following_sibling(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let node = ctxt.context.node?;
    if matches!(
        node.element_type(),
        XmlElementType::XmlAttributeNode | XmlElementType::XmlNamespaceDecl
    ) {
        return None;
    }
    if cur == ctxt.context.doc.map(|doc| doc.into()) {
        return None;
    }
    if let Some(cur) = cur {
        cur.next()
    } else {
        node.next()
    }
}

/// Traversal function for the "following" direction
/// The following axis contains all nodes in the same document as the context
/// node that are after the context node in document order, excluding any
/// descendants and excluding attribute nodes and namespace nodes; the nodes
/// are ordered in document order
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextFollowing")]
pub fn xml_xpath_next_following(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    if let Some(children) = cur
        .filter(|cur| {
            !matches!(
                cur.element_type(),
                XmlElementType::XmlAttributeNode | XmlElementType::XmlNamespaceDecl
            )
        })
        .and_then(|cur| cur.children())
    {
        return Some(children);
    }

    let mut cur = cur.or_else(|| {
        let cur = ctxt.context.node?;
        if let Ok(attr) = XmlAttrPtr::try_from(cur) {
            attr.parent()
        } else if let Ok(ns) = XmlNsPtr::try_from(cur) {
            ns.node
                .filter(|node| node.element_type() != XmlElementType::XmlNamespaceDecl)
        } else {
            None
        }
    })?;
    if let Some(next) = cur.next() {
        return Some(next);
    }
    loop {
        cur = cur.parent()?;
        if Some(cur) == ctxt.context.doc.map(|doc| doc.into()) {
            break None;
        }
        if let Some(next) = cur.next() {
            break Some(next);
        }
    }
}

thread_local! {
    static XML_XPATH_XMLNAMESPACE_STRUCT: XmlNs = XmlNs {
        next: None,
        typ: XmlElementType::XmlNamespaceDecl,
        href: Some(XML_XML_NAMESPACE.into()),
        prefix: Some("xml".into()),
        _private: null_mut(),
        context: None,
        node: None,
    };
}

/// Traversal function for the "namespace" direction
/// the namespace axis contains the namespace nodes of the context node;
/// the order of nodes on this axis is implementation-defined; the axis will
/// be empty unless the context node is an element
///
/// We keep the XML namespace node at the end of the list.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextNamespace")]
pub fn xml_xpath_next_namespace(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let node = ctxt.context.node?;
    if !matches!(node.element_type(), XmlElementType::XmlElementNode) {
        return None;
    }
    if cur.is_none() {
        ctxt.context.tmp_ns_list = node.get_ns_list(ctxt.context.doc);
        ctxt.context.tmp_ns_nr = 0;
        if let Some(list) = ctxt.context.tmp_ns_list.as_deref() {
            ctxt.context.tmp_ns_nr = list.len() as i32;
        }
        // Does it work ???
        let reference = XML_XPATH_XMLNAMESPACE_STRUCT.with(|s| s as *const XmlNs);
        return XmlGenericNodePtr::from_raw(reference as *mut XmlNs);
    }
    if ctxt.context.tmp_ns_nr > 0 {
        ctxt.context.tmp_ns_nr -= 1;
        Some(ctxt.context.tmp_ns_list.as_deref().unwrap()[ctxt.context.tmp_ns_nr as usize].into())
    } else {
        ctxt.context.tmp_ns_list = None;
        None
    }
}

/// Traversal function for the "attribute" direction
/// TODO: support DTD inherited default attributes
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextAttribute")]
pub fn xml_xpath_next_attribute(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let node = XmlNodePtr::try_from(ctxt.context.node?)
        .ok()
        .filter(|node| node.element_type() == XmlElementType::XmlElementNode)?;
    if let Some(cur) = cur {
        cur.next()
    } else {
        if ctxt.context.node == ctxt.context.doc.map(|doc| doc.into()) {
            return None;
        }
        node.properties.map(|prop| prop.into())
    }
}

/// Check that @ancestor is a @node's ancestor
///
/// returns 1 if @ancestor is a @node's ancestor, 0 otherwise.
#[doc(alias = "xmlXPathIsAncestor")]
fn xml_xpath_is_ancestor(
    ancestor: Option<XmlGenericNodePtr>,
    node: Option<XmlGenericNodePtr>,
) -> i32 {
    let Some((ancestor, mut node)) = ancestor.zip(node) else {
        return 0;
    };
    if matches!(node.element_type(), XmlElementType::XmlNamespaceDecl) {
        return 0;
    }
    if matches!(ancestor.element_type(), XmlElementType::XmlNamespaceDecl) {
        return 0;
    }
    // nodes need to be in the same document
    if ancestor.document() != node.document() {
        return 0;
    }
    // avoid searching if ancestor or node is the root node
    if Some(ancestor) == node.document().map(|doc| doc.into()) {
        return 1;
    }
    if Some(node) == ancestor.document().map(|doc| doc.into()) {
        return 0;
    }
    while let Some(parent) = node.parent() {
        if parent == ancestor {
            return 1;
        }
        node = parent;
    }
    0
}

/// Traversal function for the "preceding" direction
/// the preceding axis contains all nodes in the same document as the context
/// node that are before the context node in document order, excluding any
/// ancestors and excluding attribute nodes and namespace nodes; the nodes are
/// ordered in reverse document order
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextPreceding")]
pub fn xml_xpath_next_preceding(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let mut cur = cur.or_else(|| {
        let cur = ctxt.context.node?;
        if matches!(cur.element_type(), XmlElementType::XmlAttributeNode) {
            cur.parent()
        } else if let Ok(ns) = XmlNsPtr::try_from(cur) {
            ns.node
                .filter(|node| node.element_type() != XmlElementType::XmlNamespaceDecl)
        } else {
            None
        }
    })?;
    if matches!(cur.element_type(), XmlElementType::XmlNamespaceDecl) {
        return None;
    }
    if let Some(prev) = cur
        .prev()
        .filter(|p| matches!(p.element_type(), XmlElementType::XmlDTDNode))
    {
        cur = prev;
    }
    loop {
        if let Some(prev) = cur.prev() {
            cur = prev;
            while let Some(last) = cur.last() {
                cur = last;
            }
            break Some(cur);
        }

        cur = cur.parent()?;
        if Some(cur) == ctxt.context.doc.unwrap().children {
            break None;
        }
        if xml_xpath_is_ancestor(Some(cur), ctxt.context.node) == 0 {
            break Some(cur);
        }
    }
}

/// Traversal function for the "ancestor" direction
/// the ancestor axis contains the ancestors of the context node; the ancestors
/// of the context node consist of the parent of context node and the parent's
/// parent and so on; the nodes are ordered in reverse document order; thus the
/// parent is the first node on the axis, and the parent's parent is the second
/// node on the axis
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextAncestor")]
pub fn xml_xpath_next_ancestor(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    // the parent of an attribute or namespace node is the element
    // to which the attribute or namespace node is attached !!!!!!!!!!!!!
    let Some(cur) = cur else {
        let node = ctxt.context.node?;
        match node.element_type() {
            XmlElementType::XmlElementNode
            | XmlElementType::XmlTextNode
            | XmlElementType::XmlCDATASectionNode
            | XmlElementType::XmlEntityRefNode
            | XmlElementType::XmlEntityNode
            | XmlElementType::XmlPINode
            | XmlElementType::XmlCommentNode
            | XmlElementType::XmlDTDNode
            | XmlElementType::XmlElementDecl
            | XmlElementType::XmlAttributeDecl
            | XmlElementType::XmlEntityDecl
            | XmlElementType::XmlNotationNode
            | XmlElementType::XmlXIncludeStart
            | XmlElementType::XmlXIncludeEnd => {
                let Some(parent) = node.parent() else {
                    return ctxt.context.doc.map(|doc| doc.into());
                };
                if XmlNodePtr::try_from(parent)
                    .ok()
                    .filter(|node| node.element_type() == XmlElementType::XmlElementNode)
                    .as_deref()
                    .and_then(|node| node.name())
                    .filter(|name| name.starts_with(' ') || name == "fake node libxslt")
                    .is_some()
                {
                    return None;
                }
                return Some(parent);
            }
            XmlElementType::XmlAttributeNode => {
                let tmp = XmlAttrPtr::try_from(node).unwrap();
                return tmp.parent();
            }
            XmlElementType::XmlDocumentNode
            | XmlElementType::XmlDocumentTypeNode
            | XmlElementType::XmlDocumentFragNode
            | XmlElementType::XmlHTMLDocumentNode => {
                return None;
            }
            XmlElementType::XmlNamespaceDecl => {
                let ns = XmlNsPtr::try_from(node).unwrap();
                if let Some(next) = ns
                    .node
                    .filter(|node| !matches!(node.element_type(), XmlElementType::XmlNamespaceDecl))
                {
                    return Some(next);
                }
                // Bad, how did that namespace end up here ?
                return None;
            }
            _ => unreachable!(),
        }
    };
    if Some(cur) == ctxt.context.doc.unwrap().children {
        return ctxt.context.doc.map(|doc| doc.into());
    }
    if Some(cur) == ctxt.context.doc.map(|doc| doc.into()) {
        return None;
    }
    match cur.element_type() {
        XmlElementType::XmlElementNode
        | XmlElementType::XmlTextNode
        | XmlElementType::XmlCDATASectionNode
        | XmlElementType::XmlEntityRefNode
        | XmlElementType::XmlEntityNode
        | XmlElementType::XmlPINode
        | XmlElementType::XmlCommentNode
        | XmlElementType::XmlNotationNode
        | XmlElementType::XmlDTDNode
        | XmlElementType::XmlElementDecl
        | XmlElementType::XmlAttributeDecl
        | XmlElementType::XmlEntityDecl
        | XmlElementType::XmlXIncludeStart
        | XmlElementType::XmlXIncludeEnd => {
            let parent = cur.parent()?;

            if XmlNodePtr::try_from(parent)
                .ok()
                .filter(|node| node.element_type() == XmlElementType::XmlElementNode)
                .as_deref()
                .and_then(|node| node.name())
                .filter(|name| name.starts_with(' ') || name == "fake node libxslt")
                .is_some()
            {
                return None;
            }
            Some(parent)
        }
        XmlElementType::XmlAttributeNode => {
            let att = XmlAttrPtr::try_from(cur).unwrap();
            att.parent.map(XmlGenericNodePtr::from)
        }
        XmlElementType::XmlNamespaceDecl => {
            let ns = XmlNsPtr::try_from(cur).unwrap();

            if let Some(next) = ns
                .node
                .filter(|node| !matches!(node.element_type(), XmlElementType::XmlNamespaceDecl))
            {
                return Some(next);
            }
            // Bad, how did that namespace end up here ?
            None
        }
        XmlElementType::XmlDocumentNode
        | XmlElementType::XmlDocumentTypeNode
        | XmlElementType::XmlDocumentFragNode
        | XmlElementType::XmlHTMLDocumentNode => None,
        _ => unreachable!(),
    }
}

/// Traversal function for the "preceding-sibling" direction
/// The preceding-sibling axis contains the preceding siblings of the context
/// node in reverse document order; the first preceding sibling is first on the
/// axis; the sibling preceding that node is the second on the axis and so on.
///
/// Returns the next element following that axis
#[doc(alias = "xmlXPathNextPrecedingSibling")]
pub fn xml_xpath_next_preceding_sibling(
    ctxt: &mut XmlXPathParserContext,
    cur: Option<XmlGenericNodePtr>,
) -> Option<XmlGenericNodePtr> {
    let context_node = ctxt.context.node?;
    if matches!(
        context_node.element_type(),
        XmlElementType::XmlAttributeNode | XmlElementType::XmlNamespaceDecl
    ) {
        return None;
    }
    if cur == ctxt.context.doc.map(|doc| doc.into()) {
        return None;
    }
    let Some(mut cur) = cur else {
        return context_node.prev();
    };
    if let Some(prev) = cur.prev().and_then(|p| XmlDtdPtr::try_from(p).ok()) {
        cur = prev.into();
    }
    cur.prev()
}

/// Selects elements by their unique ID.
///
/// Returns a node-set of selected elements.
#[doc(alias = "xmlXPathGetElementsByIds")]
pub(super) fn xml_xpath_get_elements_by_ids(
    doc: XmlDocPtr,
    ids: Option<&str>,
) -> Option<Box<XmlNodeSet>> {
    let ids = ids?;
    let mut ret = xml_xpath_node_set_create(None)?;

    for id in ids
        .split(|c: char| c.is_xml_blank_char())
        .filter(|s| !s.is_empty())
    {
        // We used to check the fact that the value passed
        // was an NCName, but this generated much troubles for
        // me and Aleksey Sanin, people blatantly violated that
        // constraint, like Visa3D spec.
        // if (xmlValidateNCName(ID, 1) == 0)
        if let Some(attr) = xml_get_id(doc, id) {
            let elem = if let Ok(attr) = attr {
                attr.parent.map(XmlGenericNodePtr::from)
            // The following branch can not be reachable
            // because `xml_get_id` can only return `XmlAttrPtr` or `XmlDocPtr`...
            // What is the purpose of this branch ???
            // } else if matches!(attr.element_type(), XmlElementType::XmlElementNode) {
            //     Some(XmlGenericNodePtr::from(attr))
            } else {
                None
            };
            // TODO: Check memory error.
            if let Some(elem) = elem {
                ret.as_mut().add(elem);
            }
        }
    }
    Some(ret)
}

/// Namespace nodes in libxml don't match the XPath semantic. In a node set
/// the namespace nodes are duplicated and the next pointer is set to the
/// parent node in the XPath semantic. Check if such a node needs to be freed
#[doc(alias = "xmlXPathNodeSetFreeNs")]
#[cfg(feature = "xpath")]
pub(crate) fn xml_xpath_node_set_free_ns(ns: XmlNsPtr) {
    if !matches!(ns.typ, XmlElementType::XmlNamespaceDecl) {
        return;
    }

    if ns
        .node
        .is_some_and(|node| !matches!(node.element_type(), XmlElementType::XmlNamespaceDecl))
    {
        unsafe {
            ns.free();
        }
    }
}