libxml-rs 0.1.0-alpha.24

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure (xmlXPath*, xmlTextReader*, xmlTextWriter*, catalogs, serialization, data globals, chvalid, encoding, the full libxslt surface) — parity ledger at 0 missing for both libxml2 and libxslt. 1144 tests passing.
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
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
//! C ABI exports for libxslt.so.1 — the "functions" (XPath extension
//! functions) family (§16, Phase 8).
//!
//! Implements the libxslt 1.1.45 XPath extension-function surface:
//!
//! - XSLT XPath functions: `xsltDocumentFunction`, `xsltKeyFunction`,
//!   `xsltUnparsedEntityURIFunction`, `xsltFormatNumberFunction`,
//!   `xsltGenerateIdFunction`, `xsltSystemPropertyFunction`,
//!   `xsltElementAvailableFunction`, `xsltFunctionAvailableFunction`
//! - EXSLT helpers: `xsltFunctionNodeSet` (node-set())
//! - XPath evaluation utilities: `xsltEvalXPathPredicate`,
//!   `xsltEvalXPathString`, `xsltEvalXPathStringNs`, `xsltXPathCompile`,
//!   `xsltXPathCompileFlags`
//! - XPath-context hooks: `xsltXPathFunctionLookup`, `xsltXPathVariableLookup`,
//!   `xsltXPathGetTransformContext`
//! - Registration: `xsltRegisterAllFunctions`
//!
//! All semantics follow upstream libxslt 1.1.45 (`archaeology/libxslt-git`):
//! `functions.c`, `extra.c`, `templates.c`, `xsltutils.c`, `variables.c`,
//! `xslt.c`, `numbers.c` and `extensions.c`. Where the native-Rust engine in
//! `src/xslt/*` already implements the upstream behaviour, the exports below
//! are wired to it; everything else is a faithful port.
//!
//! # Candidate wiring notes
//!
//! Upstream stores the transform context in the XPath context's `extra`
//! slot (`ctxt->context->extra`, set by `XSLT_REGISTER_VARIABLE_LOOKUP` in
//! transform.c). The candidate uses `extra` for the internal Rust
//! `XPathContext` and stashes the transform context in the internal
//! context's `func_lookup_data` (`xsltNewTransformContext` in
//! `src/xslt/transform/mod.rs`). `xsltXPathGetTransformContext` therefore
//! resolves the transform context through that slot.

#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::comparison_chain)]

use core::ffi::c_void;
use std::ffi::CStr;
use std::os::raw::{c_char, c_int, c_ushort};
use std::ptr;

use crate::abi::allocator::{xmlFreeImpl, xmlMallocImpl};
use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;
use crate::xml::xpath::context::XPathContext;
use crate::xml::xpath::exports::xmlXPathNewString;
use crate::xml::xpath::parser_context::{value_pop, value_push, XmlXPathParserContext};

// ═══════════════════════════════════════════════════════════════════════════════
// Constants (upstream xslt.h / xsltutils.h / transform.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// `XSLT_NAMESPACE` — the XSLT namespace URI.
const XSLT_NAMESPACE: &[u8] = b"http://www.w3.org/1999/XSL/Transform\0";

/// `XSLT_DEFAULT_VERSION` (xslt.h).
const XSLT_DEFAULT_VERSION: &[u8] = b"1.0\0";

/// `XSLT_DEFAULT_VENDOR` (xslt.h).
const XSLT_DEFAULT_VENDOR: &[u8] = b"libxslt\0";

/// `XSLT_DEFAULT_URL` (xslt.h).
const XSLT_DEFAULT_URL: &[u8] = b"http://xmlsoft.org/XSLT/\0";

/// `XSLT_STATE_STOPPED` (transform.c): the transform was stopped.
const XSLT_STATE_STOPPED: c_int = 2;

/// `XSLT_SOURCE_NODE_MASK` (xsltutils.h).
const XSLT_SOURCE_NODE_MASK: c_int = 15;

/// `XSLT_SOURCE_NODE_HAS_ID` (xsltutils.h).
const XSLT_SOURCE_NODE_HAS_ID: c_int = 2;

/// `SYMBOL_QUOTE` (numbers.c).
const SYMBOL_QUOTE: xmlChar = b'\'';

/// `DBL_MAX_10_EXP` (numbers.c): 308 on IEEE platforms.
const DBL_MAX_10_EXP: c_int = 308;

// ═══════════════════════════════════════════════════════════════════════════════
// Small helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// The internal Rust XPath context stored in `_xmlXPathContext.extra`.
unsafe fn internal_xpath_ctxt(xpath_ctxt: *mut _xmlXPathContext) -> *mut XPathContext {
    if xpath_ctxt.is_null() {
        return ptr::null_mut();
    }
    unsafe { (*xpath_ctxt).extra as *mut XPathContext }
}

/// Resolve the transform context from an XPath parser context.
///
/// UPSTREAM-PARITY: upstream returns `ctxt->context->extra` (extensions.c
/// `xsltXPathGetTransformContext`); the candidate keeps the internal Rust
/// `XPathContext` in `extra` and the transform context in
/// `internal->func_lookup_data` (see module docs).
unsafe fn transform_context_from_parser(ctxt: *mut c_void) -> *mut _xsltTransformContext {
    if ctxt.is_null() {
        return ptr::null_mut();
    }
    let pc = ctxt as *mut XmlXPathParserContext;
    let xpath_ctxt = unsafe { (*pc).context };
    if xpath_ctxt.is_null() {
        return ptr::null_mut();
    }
    let internal = unsafe { internal_xpath_ctxt(xpath_ctxt) };
    if internal.is_null() {
        return ptr::null_mut();
    }
    unsafe { (*internal).func_lookup_data as *mut _xsltTransformContext }
}

/// Compare two NUL-terminated xmlChar strings for equality.
unsafe fn xml_chars_equal(a: *const xmlChar, b: *const xmlChar) -> bool {
    if a.is_null() || b.is_null() {
        return false;
    }
    libc::strcmp(a as *const libc::c_char, b as *const libc::c_char) == 0
}

/// `IS_XSLT_REAL_NODE` (xsltutils.h): document, element, text, cdata,
/// attribute, comment or PI node.
unsafe fn is_real_node(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }
    let t = unsafe { (*node).type_ };
    t == XML_ELEMENT_NODE as c_int
        || t == XML_TEXT_NODE as c_int
        || t == XML_CDATA_SECTION_NODE as c_int
        || t == XML_ATTRIBUTE_NODE as c_int
        || t == XML_DOCUMENT_NODE as c_int
        || t == XML_HTML_DOCUMENT_NODE as c_int
        || t == XML_COMMENT_NODE as c_int
        || t == XML_PI_NODE as c_int
}

/// Split a QName into (prefix, local) — pointers into `name` (upstream
/// `xsltSplitQName`, xsltutils.c; the dict-interning is not observable for
/// the read-only uses here).
///
/// Returns `(prefix, local)`: `prefix` is NULL when `name` has no prefix
/// (or starts with ':'), otherwise it points at the prefix inside `name`;
/// `local` points at the local part.
unsafe fn split_qname_ref(name: *const xmlChar) -> (*const xmlChar, *const xmlChar) {
    if name.is_null() {
        return (ptr::null(), ptr::null());
    }
    unsafe {
        if *name == b':' {
            return (ptr::null(), name);
        }
        let mut len: usize = 0;
        while *name.add(len) != 0 && *name.add(len) != b':' {
            len += 1;
        }
        if *name.add(len) == 0 {
            return (ptr::null(), name);
        }
        (name, name.add(len + 1))
    }
}

/// `xsltGetPSVIPtr` (xsltutils.c): pointer to the psvi member of a node.
unsafe fn get_psvi_ptr(cur: *mut _xmlNode) -> *mut *mut c_void {
    if cur.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        match (*cur).type_ {
            t if t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int => {
                &mut (*(cur as *mut _xmlDoc)).psvi
            }
            t if t == XML_ATTRIBUTE_NODE as c_int => &mut (*(cur as *mut _xmlAttr)).psvi,
            t if t == XML_ELEMENT_NODE as c_int
                || t == XML_TEXT_NODE as c_int
                || t == XML_CDATA_SECTION_NODE as c_int
                || t == XML_PI_NODE as c_int
                || t == XML_COMMENT_NODE as c_int =>
            {
                &mut (*cur).psvi
            }
            _ => ptr::null_mut(),
        }
    }
}

/// `xsltGetSourceNodeFlags` (xsltutils.c).
unsafe fn get_source_node_flags(node: *mut _xmlNode) -> c_int {
    if node.is_null() {
        return 0;
    }
    unsafe {
        match (*node).type_ {
            t if t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int => {
                (*(node as *mut _xmlDoc)).properties >> 27
            }
            t if t == XML_ATTRIBUTE_NODE as c_int => (*(node as *mut _xmlAttr)).atype >> 27,
            t if t == XML_ELEMENT_NODE as c_int
                || t == XML_TEXT_NODE as c_int
                || t == XML_CDATA_SECTION_NODE as c_int
                || t == XML_PI_NODE as c_int
                || t == XML_COMMENT_NODE as c_int =>
            {
                ((*node).extra as c_int) >> 12
            }
            _ => 0,
        }
    }
}

/// `xsltSetSourceNodeFlags` (xsltutils.c).
unsafe fn set_source_node_flags(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    flags: c_int,
) -> c_int {
    unsafe {
        if !ctxt.is_null()
            && !(*ctxt).initialContextDoc.is_null()
            && !node.is_null()
            && (*node).doc == (*ctxt).initialContextDoc
        {
            (*ctxt).sourceDocDirty = 1;
        }
        match (*node).type_ {
            t if t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int => {
                (*(node as *mut _xmlDoc)).properties |= flags << 27;
                0
            }
            t if t == XML_ATTRIBUTE_NODE as c_int => {
                (*(node as *mut _xmlAttr)).atype |= flags << 27;
                0
            }
            t if t == XML_ELEMENT_NODE as c_int
                || t == XML_TEXT_NODE as c_int
                || t == XML_CDATA_SECTION_NODE as c_int
                || t == XML_PI_NODE as c_int
                || t == XML_COMMENT_NODE as c_int =>
            {
                (*node).extra = ((*node).extra as c_int | (flags << 12)) as c_ushort;
                0
            }
            _ => -1,
        }
    }
}

/// `xsltClearSourceNodeFlags` (xsltutils.c).
unsafe fn clear_source_node_flags(node: *mut _xmlNode, flags: c_int) -> c_int {
    unsafe {
        match (*node).type_ {
            t if t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int => {
                (*(node as *mut _xmlDoc)).properties &= !(flags << 27);
                0
            }
            t if t == XML_ATTRIBUTE_NODE as c_int => {
                (*(node as *mut _xmlAttr)).atype &= !(flags << 27);
                0
            }
            t if t == XML_ELEMENT_NODE as c_int
                || t == XML_TEXT_NODE as c_int
                || t == XML_CDATA_SECTION_NODE as c_int
                || t == XML_PI_NODE as c_int
                || t == XML_COMMENT_NODE as c_int =>
            {
                (*node).extra = ((*node).extra as c_int & !(flags << 12)) as c_ushort;
                0
            }
            _ => -1,
        }
    }
}

/// `xsltCleanupSourceDoc` (transform.c): remove psvi fields and source-node
/// flags from a document tree (used on stylesheet-doc copies).
unsafe fn cleanup_source_doc(doc: *mut _xmlDoc) {
    if doc.is_null() {
        return;
    }
    unsafe {
        let mut cur = doc as *mut _xmlNode;
        loop {
            clear_source_node_flags(cur, XSLT_SOURCE_NODE_MASK);
            let psvi_ptr = get_psvi_ptr(cur);
            if !psvi_ptr.is_null() {
                *psvi_ptr = ptr::null_mut();
            }
            if (*cur).type_ == XML_ELEMENT_NODE as c_int {
                let mut prop = (*cur).properties;
                while !prop.is_null() {
                    (*prop).atype &= !(XSLT_SOURCE_NODE_MASK << 27);
                    (*prop).psvi = ptr::null_mut();
                    prop = (*prop).next;
                }
            }
            if !(*cur).children.is_null() && (*cur).type_ != XML_ENTITY_REF_NODE as c_int {
                cur = (*cur).children;
            } else {
                if cur == doc as *mut _xmlNode {
                    return;
                }
                while (*cur).next.is_null() {
                    cur = (*cur).parent;
                    if cur == doc as *mut _xmlNode {
                        return;
                    }
                }
                cur = (*cur).next;
            }
        }
    }
}

/// `xsltNextImport` (imports.c).
unsafe fn next_import(cur: *mut _xsltStylesheet) -> *mut _xsltStylesheet {
    if cur.is_null() {
        return ptr::null_mut();
    }
    unsafe {
        if !(*cur).imports.is_null() {
            return (*cur).imports;
        }
        if !(*cur).next.is_null() {
            return (*cur).next;
        }
        let mut c = (*cur).parent;
        while !c.is_null() {
            if !(*c).next.is_null() {
                return (*c).next;
            }
            c = (*c).parent;
        }
    }
    ptr::null_mut()
}

/// Report an XSLT error with a static format string (variadic arguments are
/// not expanded; the raw format string is recorded, matching the candidate's
/// `xsltTransformError` safe subset).
unsafe fn xslt_error(ctxt: *mut _xsltTransformContext, msg: &'static [u8]) {
    crate::xslt::errors::xsltTransformError(
        ctxt,
        ptr::null_mut(),
        ptr::null_mut(),
        msg.as_ptr() as *const c_char,
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// 1. XSLT XPath functions (functions.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Upstream `xsltDocumentFunctionLoadDocument` (functions.c): load a
/// document by URI and push its root node-set; honour a `#fragment`
/// XPointer selection.
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context; `URI`/`fragment` valid strings
///   or NULL.
unsafe fn xslt_document_function_load_document(
    ctxt: *mut c_void,
    uri: *const xmlChar,
    fragment: *const xmlChar,
) {
    let pc = ctxt as *mut XmlXPathParserContext;
    let tctxt = transform_context_from_parser(ctxt);
    if tctxt.is_null() {
        xslt_error(
            ptr::null_mut(),
            b"document() : internal error tctxt == NULL\n\0",
        );
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
        );
        return;
    }

    let mut doc = crate::xslt::documents::xsltLoadDocument(tctxt, uri);
    if doc.is_null() {
        // This selects the stylesheet's doc itself.
        let style = (*tctxt).style;
        let style_doc = if style.is_null() {
            ptr::null_mut()
        } else {
            (*style).doc
        };
        let select_style = uri.is_null()
            || *uri == b'#'
            || (!style_doc.is_null() && {
                let url = (*style_doc).URL;
                !url.is_null()
                    && crate::abi::exports_xml2::xmlStrEqual(url as *const xmlChar, uri) != 0
            });
        if select_style && !style_doc.is_null() {
            let copy = crate::abi::exports_xml2::xmlCopyDoc(style_doc as *const _xmlDoc, 1);
            if copy.is_null() {
                xslt_error(tctxt, b"document() : failed to copy style doc\n\0");
                value_push(
                    pc,
                    crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
                );
                return;
            }
            cleanup_source_doc(copy);
            doc = copy;
        } else {
            value_push(
                pc,
                crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
            );
            return;
        }
    }

    if fragment.is_null() {
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet(doc as *mut _xmlNode),
        );
        return;
    }

    // Use XPointer / HTML location for the fragment ID.
    // UPSTREAM-PARITY: upstream evaluates with xmlXPtrEval() on a fresh
    // context of `doc`; the candidate's XPointer bridge
    // (xmlXPtrEvalNodeSet) evaluates the fragment against the document and
    // returns a node-set.
    let res_ns = crate::xml::xpointer::xmlXPtrEvalNodeSet(fragment as *const c_char, doc);
    if res_ns.is_null() {
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
        );
    } else {
        value_push(pc, crate::xml::xpath::exports::xmlXPathWrapNodeSet(res_ns));
    }
}

/// Implement the XSLT `document()` function:
/// `node-set document(object, node-set?)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltDocumentFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltDocumentFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();
    let mut obj2: *mut _xmlXPathObject = ptr::null_mut();
    let mut new_uri: *mut xmlChar = ptr::null_mut();
    let mut fragment: *mut xmlChar = ptr::null_mut();

    if (nargs < 1) || (nargs > 2) {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"document() : invalid number of args %d\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    if (*pc).value.is_null() {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"document() : invalid arg value\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        return;
    }

    if nargs == 2 {
        if (*(*pc).value).type_ != xmlXPathObjectType::XPATH_NODESET as c_int {
            xslt_error(
                transform_context_from_parser(ctxt),
                b"document() : invalid arg expecting a nodeset\n\0",
            );
            (*pc).error = XPATH_INVALID_TYPE as c_int;
            return;
        }
        obj2 = value_pop(pc);
    }

    if !(*pc).value.is_null() && (*(*pc).value).type_ == xmlXPathObjectType::XPATH_NODESET as c_int
    {
        // First argument is a node-set: apply document() to each node and
        // merge the results.
        let mut i: c_int = 0;
        let mut newobj: *mut _xmlXPathObject = ptr::null_mut();
        obj = value_pop(pc);
        let ret = crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut());
        if !obj.is_null() && !(*obj).nodesetval.is_null() && !ret.is_null() {
            let ns = (*obj).nodesetval as *mut _xmlNodeSet;
            while i < (*ns).nodeNr {
                let node = *(*ns).nodeTab.offset(i as isize);
                value_push(pc, crate::abi::exports_xml2::xmlXPathNewNodeSet(node));
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
                if nargs == 2 {
                    value_push(pc, crate::abi::exports_xml2::xmlXPathObjectCopy(obj2));
                } else {
                    value_push(pc, crate::abi::exports_xml2::xmlXPathNewNodeSet(node));
                }
                if (*pc).error != 0 {
                    break;
                }
                xsltDocumentFunction(ctxt, 2);
                newobj = value_pop(pc);
                if !newobj.is_null() {
                    let merged = crate::xml::xpath::exports::xmlXPathNodeSetMerge(
                        (*ret).nodesetval as *mut _xmlNodeSet,
                        (*newobj).nodesetval as *mut _xmlNodeSet,
                    );
                    (*ret).nodesetval = merged as *mut c_void;
                    crate::abi::exports_xml2::xmlXPathFreeObject(newobj);
                }
                i += 1;
            }
        }
        if !obj.is_null() {
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        }
        if !obj2.is_null() {
            crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
        }
        value_push(pc, ret);
        return;
    }

    // Make sure it's converted to a string.
    crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
    if (*pc).value.is_null() || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"document() : invalid arg expecting a string\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        if !obj2.is_null() {
            crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
        }
        return;
    }
    obj = value_pop(pc);

    if (*obj).stringval.is_null() {
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
        );
    } else {
        let tctxt = transform_context_from_parser(ctxt);
        let mut url = (*obj).stringval;

        let uri = crate::abi::exports_xml2::xmlParseURI(url as *const c_char);
        if uri.is_null() {
            xslt_error(tctxt, b"document() : failed to parse URI '%s'\n\0");
            value_push(
                pc,
                crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
            );
            // goto error
        } else {
            // Check for and remove the fragment identifier. The URI object
            // mirrors upstream `_xmlURI`; the fragment string is detached so
            // xmlFreeURI does not free it (the caller frees it below).
            #[repr(C)]
            struct XmlUriC {
                scheme: *mut c_char,
                opaque: *mut c_char,
                authority: *mut c_char,
                server: *mut c_char,
                user: *mut c_char,
                port: c_int,
                path: *mut c_char,
                query: *mut c_char,
                fragment: *mut c_char,
                cleanup: c_int,
                query_raw: *mut c_char,
            }
            let uri_c = uri as *mut XmlUriC;
            fragment = (*uri_c).fragment as *mut xmlChar;
            if !fragment.is_null() {
                (*uri_c).fragment = ptr::null_mut();
                new_uri = crate::abi::exports_xml2::xmlSaveUri(uri);
                url = new_uri;
            }
            crate::abi::exports_xml2::xmlFreeURI(uri);

            // Compute the base URI from the optional second argument or the
            // current instruction.
            let mut base: *mut xmlChar = ptr::null_mut();
            if !obj2.is_null()
                && !(*obj2).nodesetval.is_null()
                && {
                    let ns2 = (*obj2).nodesetval as *mut _xmlNodeSet;
                    (*ns2).nodeNr > 0
                }
                && is_real_node(*(*((*obj2).nodesetval as *mut _xmlNodeSet)).nodeTab)
            {
                let mut target = *(*((*obj2).nodesetval as *mut _xmlNodeSet)).nodeTab;
                if (*target).type_ == XML_ATTRIBUTE_NODE as c_int
                    || (*target).type_ == XML_PI_NODE as c_int
                {
                    target = (*target).parent;
                }
                base = crate::abi::exports_tree::xmlNodeGetBase((*target).doc, target);
            } else if !tctxt.is_null() && !(*tctxt).inst.is_null() {
                base =
                    crate::abi::exports_tree::xmlNodeGetBase((*(*tctxt).inst).doc, (*tctxt).inst);
            } else if !tctxt.is_null()
                && !(*tctxt).style.is_null()
                && !(*tctxt).style.is_null()
                && !(*(*tctxt).style).doc.is_null()
            {
                base = crate::abi::exports_tree::xmlNodeGetBase(
                    (*(*tctxt).style).doc,
                    (*(*tctxt).style).doc as *mut _xmlNode,
                );
            }

            let resolved =
                crate::abi::exports_uri::xmlBuildURI(url as *const c_char, base as *const c_char);
            if !base.is_null() {
                xmlFreeImpl(base as *mut c_void);
            }
            if resolved.is_null() {
                if !tctxt.is_null()
                    && !(*tctxt).style.is_null()
                    && !(*(*tctxt).style).doc.is_null()
                    && !(*(*(*tctxt).style).doc).URL.is_null()
                    && crate::abi::exports_xml2::xmlStrEqual(
                        resolved as *const xmlChar,
                        (*(*(*tctxt).style).doc).URL as *const xmlChar,
                    ) != 0
                {
                    // This selects the stylesheet's doc itself.
                    value_push(
                        pc,
                        crate::abi::exports_xml2::xmlXPathNewNodeSet(
                            (*(*tctxt).style).doc as *mut _xmlNode,
                        ),
                    );
                } else {
                    value_push(
                        pc,
                        crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
                    );
                }
            } else {
                xslt_document_function_load_document(ctxt, resolved, fragment);
                xmlFreeImpl(resolved as *mut c_void);
            }
        }
    }

    // error: label cleanup
    if !new_uri.is_null() {
        xmlFreeImpl(new_uri as *mut c_void);
    }
    if !fragment.is_null() {
        xmlFreeImpl(fragment as *mut c_void);
    }
    if !obj.is_null() {
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
    }
    if !obj2.is_null() {
        crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
    }
}

/// Implement the XSLT `key()` function: `node-set key(string, object)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltKeyFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltKeyFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj1: *mut _xmlXPathObject = ptr::null_mut();
    let mut obj2: *mut _xmlXPathObject = ptr::null_mut();

    if nargs != 2 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"key() : expects two arguments\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }

    // Get the key's value.
    obj2 = value_pop(pc);
    crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
    if obj2.is_null()
        || (*pc).value.is_null()
        || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int
    {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"key() : invalid arg expecting a string\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
        return;
    }
    // Get the key's name.
    obj1 = value_pop(pc);

    if (*obj2).type_ == xmlXPathObjectType::XPATH_NODESET as c_int
        || (*obj2).type_ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int
    {
        let mut i: c_int = 0;
        let mut newobj: *mut _xmlXPathObject = ptr::null_mut();
        let ret = crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut());
        if ret.is_null() {
            (*pc).error = XPATH_MEMORY_ERROR as c_int;
            crate::abi::exports_xml2::xmlXPathFreeObject(obj1);
            crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
            return;
        }
        if !(*obj2).nodesetval.is_null() {
            let ns = (*obj2).nodesetval as *mut _xmlNodeSet;
            while i < (*ns).nodeNr {
                value_push(pc, crate::abi::exports_xml2::xmlXPathObjectCopy(obj1));
                value_push(
                    pc,
                    crate::abi::exports_xml2::xmlXPathNewNodeSet(*(*ns).nodeTab.offset(i as isize)),
                );
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
                xsltKeyFunction(ctxt, 2);
                newobj = value_pop(pc);
                if !newobj.is_null() {
                    let merged = crate::xml::xpath::exports::xmlXPathNodeSetMerge(
                        (*ret).nodesetval as *mut _xmlNodeSet,
                        (*newobj).nodesetval as *mut _xmlNodeSet,
                    );
                    (*ret).nodesetval = merged as *mut c_void;
                }
                crate::abi::exports_xml2::xmlXPathFreeObject(newobj);
                i += 1;
            }
        }
        value_push(pc, ret);
    } else {
        let mut nodelist: *mut _xmlNodeSet = ptr::null_mut();
        let mut key: *mut xmlChar = ptr::null_mut();
        let mut key_uri: *const xmlChar = ptr::null();
        let tctxt = transform_context_from_parser(ctxt);
        let xpctxt = (*pc).context;
        let mut tmp_node: *mut _xmlNode = ptr::null_mut();

        if tctxt.is_null() || xpctxt.is_null() {
            (*pc).error = XPATH_INVALID_TYPE as c_int;
            // mirror upstream error: push an empty node-set.
            value_push(
                pc,
                crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
            );
        } else {
            let old_doc_info = (*tctxt).document;

            if (*xpctxt).node.is_null() {
                xslt_error(
                    tctxt,
                    b"Internal error in xsltKeyFunction(): The context node is not set on the XPath context.\n\0",
                );
                (*tctxt).state = XSLT_STATE_STOPPED;
                value_push(
                    pc,
                    crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
                );
            } else {
                // Get the associated namespace URI if qualified name.
                let qname = (*obj1).stringval;
                let mut prefix: *mut xmlChar = ptr::null_mut();
                key = crate::xml::string::split_qname2(qname, &mut prefix);
                if key.is_null() {
                    key = crate::abi::exports_xml2::xmlStrdup(qname);
                    key_uri = ptr::null();
                    if !prefix.is_null() {
                        xmlFreeImpl(prefix as *mut c_void);
                    }
                } else if !prefix.is_null() {
                    key_uri = crate::xml::xpath::exports::xmlXPathNsLookup(xpctxt, prefix);
                    if key_uri.is_null() {
                        xslt_error(tctxt, b"key() : prefix %s is not bound\n\0");
                    }
                    xmlFreeImpl(prefix as *mut c_void);
                } else {
                    key_uri = ptr::null();
                }

                // Force conversion of the value to string.
                value_push(pc, obj2);
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
                obj2 = value_pop(pc);
                if obj2.is_null() || (*obj2).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
                    xslt_error(tctxt, b"key() : invalid arg expecting a string\n\0");
                    (*pc).error = XPATH_INVALID_TYPE as c_int;
                } else {
                    let value = (*obj2).stringval;

                    // Determine the context node's owner doc.
                    if (*xpctxt).node.is_null() {
                        tmp_node = ptr::null_mut();
                    } else if (*xpctxt).node.is_null()
                        || (*(*xpctxt).node).type_ != XML_NAMESPACE_DECL as c_int
                    {
                        tmp_node = (*xpctxt).node;
                    } else {
                        // Namespace node: the owner element is stored in
                        // ns->next (libxml2 XPath hack).
                        let ns = (*xpctxt).node as *mut _xmlNs;
                        if !(*ns).next.is_null() && (*(*ns).next).type_ == XML_ELEMENT_NODE as c_int
                        {
                            tmp_node = (*ns).next as *mut _xmlNode;
                        }
                    }

                    if tmp_node.is_null() || (*tmp_node).doc.is_null() {
                        xslt_error(
                            tctxt,
                            b"Internal error in xsltKeyFunction(): Couldn't get the doc of the XPath context node.\n\0",
                        );
                    } else if (*tctxt).document.is_null()
                        || (*(*tctxt).document).doc != (*tmp_node).doc
                    {
                        // UPSTREAM-PARITY (simplified): upstream switches
                        // tctxt->document to the context node's document
                        // wrapper (xsltNewDocument / xsltFindDocument).
                        // The candidate indexes key tables on the main
                        // document wrapper only (see xsltInitKeys /
                        // xsltEvalKeyFunction in src/xslt/keys), so no
                        // switch is performed here; the lookup below uses
                        // ctxt->document as-is.
                        if (*tctxt).document.is_null() {
                            (*tctxt).state = XSLT_STATE_STOPPED;
                        }
                    }

                    if (*tctxt).document.is_null() {
                        xslt_error(
                            tctxt,
                            b"Internal error in xsltKeyFunction(): Could not get the document info of a context doc.\n\0",
                        );
                        (*tctxt).state = XSLT_STATE_STOPPED;
                    } else {
                        // Get/compute the key value. UPSTREAM-PARITY: the
                        // candidate's key-table lookup (xsltEvalKeyFunction)
                        // matches tables by local name only; the namespace
                        // URI resolved above is not part of the lookup
                        // (same behaviour as the internal engine's key()).
                        nodelist = crate::xslt::keys::xsltEvalKeyFunction(tctxt, key, value);
                    }
                }

                (*tctxt).document = old_doc_info;
            }

            // error: push the (possibly empty) merged node-set.
            if nodelist.is_null() {
                value_push(
                    pc,
                    crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
                );
            } else {
                let merged =
                    crate::xml::xpath::exports::xmlXPathNodeSetMerge(ptr::null_mut(), nodelist);
                crate::abi::exports_xml2::xmlXPathFreeNodeSet(nodelist);
                value_push(pc, crate::xml::xpath::exports::xmlXPathWrapNodeSet(merged));
            }
            if !key.is_null() {
                xmlFreeImpl(key as *mut c_void);
            }
        }
    }

    if !obj1.is_null() {
        crate::abi::exports_xml2::xmlXPathFreeObject(obj1);
    }
    if !obj2.is_null() {
        crate::abi::exports_xml2::xmlXPathFreeObject(obj2);
    }
}

/// Implement the XSLT `unparsed-entity-uri()` function:
/// `string unparsed-entity-uri(string)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltUnparsedEntityURIFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltUnparsedEntityURIFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();

    if (nargs != 1) || (*pc).value.is_null() {
        crate::xslt::errors::xsltTransformError(
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            b"unparsed-entity-uri() : expects one string arg\n\0".as_ptr() as *const c_char,
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    obj = value_pop(pc);
    if (*obj).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
        obj = crate::xml::xpath::exports::xmlXPathConvertString(obj);
        if obj.is_null() {
            (*pc).error = XPATH_MEMORY_ERROR as c_int;
            return;
        }
    }

    let str = (*obj).stringval;
    let xpctxt = (*pc).context;
    if str.is_null() || xpctxt.is_null() || (*xpctxt).doc.is_null() {
        value_push(pc, xmlXPathNewString(ptr::null()));
    } else {
        let entity = crate::abi::exports_xml2::xmlGetDocEntity((*xpctxt).doc, str);
        if entity.is_null() || (*entity).URI.is_null() {
            value_push(pc, xmlXPathNewString(ptr::null()));
        } else {
            value_push(pc, xmlXPathNewString((*entity).URI as *const xmlChar));
        }
    }
    crate::abi::exports_xml2::xmlXPathFreeObject(obj);
}

// ── format-number(): picture-format algorithm (numbers.c) ──────────────────────

/// `xsltUTF8Charcmp` (numbers.c): compare the first UTF-8 char of `utf1`
/// with the string at `utf2` (byte comparison of the char's encoded form).
unsafe fn utf8_charcmp(utf1: *const xmlChar, utf2: *const xmlChar) -> c_int {
    if utf1.is_null() {
        return -1;
    }
    let len = crate::abi::exports_string::xmlUTF8Strsize(utf1, 1);
    if len < 1 {
        return -1;
    }
    crate::abi::exports_xml2::xmlStrncmp(utf1, utf2, len)
}

/// `IS_SPECIAL` (numbers.c).
unsafe fn is_special(self_: *mut _xsltDecimalFormat, letter: *const xmlChar) -> bool {
    unsafe {
        utf8_charcmp(letter, (*self_).zeroDigit) == 0
            || utf8_charcmp(letter, (*self_).digit) == 0
            || utf8_charcmp(letter, (*self_).decimalPoint) == 0
            || utf8_charcmp(letter, (*self_).grouping) == 0
            || utf8_charcmp(letter, (*self_).patternSeparator) == 0
    }
}

/// `xsltCopyCharMultiByte` (numbers.c): encode a UCS-4 value as UTF-8 into
/// `out`; returns the number of bytes written.
unsafe fn copy_char_multibyte(mut out: *mut xmlChar, val: c_int) -> c_int {
    if out.is_null() || val < 0 {
        return 0;
    }
    unsafe {
        if val < 0x80 {
            *out = val as xmlChar;
            return 1;
        }
        let savedout = out;
        let mut bits: c_int;
        if val < 0x800 {
            *out = ((val >> 6) as xmlChar) | 0xC0;
            bits = 0;
            out = out.add(1);
        } else if val < 0x10000 {
            *out = ((val >> 12) as xmlChar) | 0xE0;
            bits = 6;
            out = out.add(1);
        } else if val < 0x110000 {
            *out = ((val >> 18) as xmlChar) | 0xF0;
            bits = 12;
            out = out.add(1);
        } else {
            return 0;
        }
        while bits >= 0 {
            *out = (((val >> bits) as xmlChar) & 0x3F) | 0x80;
            out = out.add(1);
            bits -= 6;
        }
        out.offset_from(savedout) as c_int
    }
}

/// `xsltGetUTF8Char` (xsltutils.c): decode the first UTF-8 char of `utf`;
/// `*len` is the available byte count and is updated to the char length.
unsafe fn xslt_get_utf8_char(utf: *const u8, len: *mut c_int) -> c_int {
    unsafe {
        if utf.is_null() || len.is_null() || *len < 1 {
            if !len.is_null() {
                *len = 0;
            }
            return -1;
        }
        let mut c: c_int = *utf as c_int;
        if (c & 0x80) != 0 {
            if *len < 2 || (*utf.add(1) & 0xc0) != 0x80 {
                *len = 0;
                return -1;
            }
            if (c & 0xe0) == 0xe0 {
                if *len < 3 || (*utf.add(2) & 0xc0) != 0x80 {
                    *len = 0;
                    return -1;
                }
                if (c & 0xf0) == 0xf0 {
                    if *len < 4 || (c & 0xf8) != 0xf0 || (*utf.add(3) & 0xc0) != 0x80 {
                        *len = 0;
                        return -1;
                    }
                    *len = 4;
                    c = (*utf as c_int & 0x7) << 18;
                    c |= (*utf.add(1) as c_int & 0x3f) << 12;
                    c |= (*utf.add(2) as c_int & 0x3f) << 6;
                    c |= *utf.add(3) as c_int & 0x3f;
                } else {
                    *len = 3;
                    c = (*utf as c_int & 0xf) << 12;
                    c |= (*utf.add(1) as c_int & 0x3f) << 6;
                    c |= *utf.add(2) as c_int & 0x3f;
                }
            } else {
                *len = 2;
                c = (*utf as c_int & 0x1f) << 6;
                c |= *utf.add(1) as c_int & 0x3f;
            }
        } else {
            *len = 1;
        }
        c
    }
}

/// `xsltNumberFormatDecimal` (numbers.c): write the decimal digits of
/// `number` into `buffer` with the given width, grouping and zero digit.
unsafe fn number_format_decimal(
    buffer: *mut _xmlBuffer,
    number: f64,
    digit_zero: c_int,
    width: c_int,
    digits_per_group: c_int,
    grouping_character: c_int,
    grouping_character_len: c_int,
) {
    unsafe {
        let mut temp_string = [0u8; 500];
        let mut temp_char = [0u8; 6];
        let mut i: c_int = 0;
        let mut number = number;

        // Build the buffer from the back.
        let mut pointer = (temp_string.as_mut_ptr() as usize + temp_string.len() - 1) as *mut u8;
        *pointer = 0;
        while (pointer as usize) > (temp_string.as_ptr() as usize) {
            if (i >= width) && number.abs() < 1.0 {
                break;
            }
            if (i > 0)
                && (grouping_character != 0)
                && (digits_per_group > 0)
                && ((i % digits_per_group) == 0)
            {
                if (pointer as usize)
                    .checked_sub(grouping_character_len as usize)
                    .map_or(true, |p| p < temp_string.as_ptr() as usize)
                {
                    i = -1; // flag error
                    break;
                }
                pointer = pointer.sub(grouping_character_len as usize);
                copy_char_multibyte(pointer as *mut xmlChar, grouping_character);
            }

            let val = digit_zero + (number % 10.0) as c_int;
            if val < 0x80 {
                // Shortcut if ASCII.
                if (pointer as usize) <= (temp_string.as_ptr() as usize) {
                    i = -1;
                    break;
                }
                pointer = pointer.sub(1);
                *pointer = val as u8;
            } else {
                // Multibyte character: encode into temp_char, then copy.
                let len = copy_char_multibyte(temp_char.as_mut_ptr() as *mut xmlChar, val);
                if (pointer as usize)
                    .checked_sub(len as usize)
                    .map_or(true, |p| p < temp_string.as_ptr() as usize)
                {
                    i = -1;
                    break;
                }
                pointer = pointer.sub(len as usize);
                ptr::copy_nonoverlapping(temp_char.as_ptr(), pointer, len as usize);
            }
            number /= 10.0;
            i += 1;
        }
        if i < 0 {
            // xsltGenericError(xsltGenericErrorContext, "xsltNumberFormatDecimal: ...")
            let msg = b"xsltNumberFormatDecimal: Internal buffer size exceeded\n";
            libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len());
        }
        crate::abi::exports_xml2::xmlBufferCat(buffer, pointer as *mut xmlChar);
    }
}

/// `xsltFormatNumberPreSuffix` (numbers.c): consume a prefix/suffix of the
/// format string, returning its byte length (or -1 on error).
unsafe fn format_number_presuffix(
    self_: *mut _xsltDecimalFormat,
    format: *mut *mut xmlChar,
    info: *mut FormatNumberInfo,
) -> c_int {
    let mut count: c_int = 0;
    loop {
        let cur = *format;
        if cur.is_null() || *cur == 0 {
            return count;
        }
        if *cur == SYMBOL_QUOTE {
            let next = cur.add(1);
            *format = next;
            if *next == 0 {
                return -1;
            }
        } else if is_special(self_, cur) {
            return count;
        } else if utf8_charcmp(cur, (*self_).percent) == 0 {
            if (*info).is_multiplier_set != 0 {
                return -1;
            }
            (*info).multiplier = 100;
            (*info).is_multiplier_set = 1;
        } else if utf8_charcmp(cur, (*self_).permille) == 0 {
            if (*info).is_multiplier_set != 0 {
                return -1;
            }
            (*info).multiplier = 1000;
            (*info).is_multiplier_set = 1;
        }
        let len = crate::abi::exports_string::xmlUTF8Strsize(*format, 1);
        if len < 1 {
            return -1;
        }
        count += len;
        *format = (*format).add(len as usize);
    }
}

/// `xsltFormatNumberInfo` (numbers.c) — parsed picture-format state.
#[repr(C)]
#[derive(Clone, Copy)]
struct FormatNumberInfo {
    integer_hash: c_int,
    integer_digits: c_int,
    frac_digits: c_int,
    frac_hash: c_int,
    group: c_int,
    multiplier: c_int,
    add_decimal: c_int,
    is_multiplier_set: c_int,
    is_negative_pattern: c_int,
}

impl Default for FormatNumberInfo {
    fn default() -> Self {
        FormatNumberInfo {
            integer_hash: 0,
            integer_digits: 0,
            frac_digits: 0,
            frac_hash: 0,
            group: -1,
            multiplier: 1,
            add_decimal: 0,
            is_multiplier_set: 0,
            is_negative_pattern: 0,
        }
    }
}

/// `xsltFormatNumberConversion` (numbers.c): the JDK 1.1 DecimalFormat-style
/// picture-format algorithm behind format-number().
///
/// Returns an XPath error code; `*result` receives an xmlMalloc'd string
/// (NULL on failure).
unsafe fn format_number_conversion(
    self_: *mut _xsltDecimalFormat,
    format: *mut xmlChar,
    number: f64,
    result: *mut *mut xmlChar,
) -> c_int {
    unsafe {
        let status = XPATH_EXPRESSION_OK as c_int;
        let mut the_format: *mut xmlChar = ptr::null_mut();
        let mut prefix: *mut xmlChar = ptr::null_mut();
        let mut suffix: *mut xmlChar = ptr::null_mut();
        let mut nprefix: *mut xmlChar = ptr::null_mut();
        let mut nsuffix: *mut xmlChar = ptr::null_mut();
        let mut prefix_length: c_int = 0;
        let mut suffix_length: c_int = 0;
        let mut nprefix_length: c_int = 0;
        let mut nsuffix_length: c_int = 0;
        let mut len: c_int = 0;
        let mut j: c_int;
        let mut info = FormatNumberInfo::default();
        let mut delayed_multiplier: c_int = 0;
        let mut default_sign: c_int = 0;
        let mut found_error: c_int = 0;
        let mut number = number;

        if crate::abi::exports_xml2::xmlStrlen(format) <= 0 {
            xslt_error(
                ptr::null_mut(),
                b"xsltFormatNumberConversion : Invalid format (0-length)\n\0",
            );
        }
        *result = ptr::null_mut();
        if crate::xml::xpath::exports::xmlXPathIsNaN(number) != 0 {
            *result = if self_.is_null() || (*self_).noNumber.is_null() {
                crate::abi::exports_xml2::xmlStrdup(b"NaN\0".as_ptr() as *const xmlChar)
            } else {
                crate::abi::exports_xml2::xmlStrdup((*self_).noNumber)
            };
            return status;
        }

        the_format = format;

        // First process the +ve pattern to get percent/permille as well as
        // the main format.
        prefix = the_format;
        prefix_length = format_number_presuffix(self_, &mut the_format, &mut info);
        if prefix_length < 0 {
            found_error = 1;
        }

        // Process the "number" part of the format. A trailing percent or
        // per-mille may be part of the suffix, so it is delayed.
        let self_grouping_len = crate::abi::exports_xml2::xmlStrlen((*self_).grouping);
        while found_error == 0
            && !the_format.is_null()
            && *the_format != 0
            && utf8_charcmp(the_format, (*self_).decimalPoint) != 0
            && utf8_charcmp(the_format, (*self_).patternSeparator) != 0
        {
            if delayed_multiplier != 0 {
                info.multiplier = delayed_multiplier;
                info.is_multiplier_set = 1;
                delayed_multiplier = 0;
            }
            if utf8_charcmp(the_format, (*self_).digit) == 0 {
                if info.integer_digits > 0 {
                    found_error = 1;
                    break;
                }
                info.integer_hash += 1;
                if info.group >= 0 {
                    info.group += 1;
                }
            } else if utf8_charcmp(the_format, (*self_).zeroDigit) == 0 {
                info.integer_digits += 1;
                if info.group >= 0 {
                    info.group += 1;
                }
            } else if (self_grouping_len > 0)
                && !(*self_).grouping.is_null()
                && crate::abi::exports_xml2::xmlStrncmp(
                    the_format,
                    (*self_).grouping,
                    self_grouping_len,
                ) == 0
            {
                // Reset group count.
                info.group = 0;
                the_format = the_format.add(self_grouping_len as usize);
                continue;
            } else if utf8_charcmp(the_format, (*self_).percent) == 0 {
                if info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 100;
            } else if utf8_charcmp(the_format, (*self_).permille) == 0 {
                if info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 1000;
            } else {
                break; // while
            }

            len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
                break;
            }
            the_format = the_format.add(len as usize);
        }

        // Finished the integer part; now work on the fraction.
        if found_error == 0
            && !the_format.is_null()
            && *the_format != 0
            && utf8_charcmp(the_format, (*self_).decimalPoint) == 0
        {
            info.add_decimal = 1;
            len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
            } else {
                the_format = the_format.add(len as usize); // skip over the decimal
            }
        }

        while found_error == 0 && !the_format.is_null() && *the_format != 0 {
            if utf8_charcmp(the_format, (*self_).zeroDigit) == 0 {
                if info.frac_hash != 0 {
                    found_error = 1;
                    break;
                }
                info.frac_digits += 1;
            } else if utf8_charcmp(the_format, (*self_).digit) == 0 {
                info.frac_hash += 1;
            } else if utf8_charcmp(the_format, (*self_).percent) == 0 {
                if info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 100;
                len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
                if len < 1 {
                    found_error = 1;
                    break;
                }
                the_format = the_format.add(len as usize);
                continue;
            } else if utf8_charcmp(the_format, (*self_).permille) == 0 {
                if info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 1000;
                len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
                if len < 1 {
                    found_error = 1;
                    break;
                }
                the_format = the_format.add(len as usize);
                continue;
            } else if utf8_charcmp(the_format, (*self_).grouping) != 0 {
                break; // while
            }
            len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
                break;
            }
            the_format = the_format.add(len as usize);
            if delayed_multiplier != 0 {
                info.multiplier = delayed_multiplier;
                delayed_multiplier = 0;
                info.is_multiplier_set = 1;
            }
        }

        // If delayed_multiplier is set after processing the "number" part,
        // it should be in the suffix.
        if delayed_multiplier != 0 && found_error == 0 {
            the_format = the_format.sub(len as usize);
            delayed_multiplier = 0;
        }

        suffix = the_format;
        suffix_length = format_number_presuffix(self_, &mut the_format, &mut info);
        if (suffix_length < 0)
            || (!the_format.is_null()
                && *the_format != 0
                && utf8_charcmp(the_format, (*self_).patternSeparator) != 0)
        {
            found_error = 1;
        }

        // If the number is -ve, substitute the -ve prefix/suffix.
        if found_error == 0 && number < 0.0 {
            // j is the number of UTF-8 chars before the separator.
            j = crate::abi::exports_string::xmlUTF8Strloc(format, (*self_).patternSeparator);
            if j < 0 {
                // No -ve pattern present, so use default signing.
                default_sign = 1;
            } else {
                // Skip over the pattern separator (accounting for UTF-8).
                the_format =
                    crate::abi::exports_string::xmlUTF8Strpos(format, j + 1) as *mut xmlChar;
                // Flag changes interpretation of percent/permille in the
                // -ve pattern.
                info.is_negative_pattern = 1;
                info.is_multiplier_set = 0;

                // First do the -ve prefix.
                nprefix = the_format;
                nprefix_length = format_number_presuffix(self_, &mut the_format, &mut info);
                if nprefix_length < 0 {
                    found_error = 1;
                }
                while found_error == 0 && !the_format.is_null() && *the_format != 0 {
                    if (utf8_charcmp(the_format, (*self_).percent) == 0)
                        || (utf8_charcmp(the_format, (*self_).permille) == 0)
                    {
                        if info.is_multiplier_set != 0 {
                            found_error = 1;
                            break;
                        }
                        info.is_multiplier_set = 1;
                        delayed_multiplier = 1;
                    } else if is_special(self_, the_format) {
                        delayed_multiplier = 0;
                    } else {
                        break; // while
                    }
                    len = crate::abi::exports_string::xmlUTF8Strsize(the_format, 1);
                    if len < 1 {
                        found_error = 1;
                        break;
                    }
                    the_format = the_format.add(len as usize);
                }
                if delayed_multiplier != 0 && found_error == 0 {
                    info.is_multiplier_set = 0;
                    the_format = the_format.sub(len as usize);
                }

                // Finally do the -ve suffix.
                if found_error == 0 && !the_format.is_null() && *the_format != 0 {
                    nsuffix = the_format;
                    nsuffix_length = format_number_presuffix(self_, &mut the_format, &mut info);
                    if nsuffix_length < 0 {
                        found_error = 1;
                    }
                } else if found_error == 0 {
                    nsuffix_length = 0;
                }
                if found_error == 0 && !the_format.is_null() && *the_format != 0 {
                    found_error = 1;
                }
                if found_error == 0
                    && ((nprefix_length != prefix_length)
                        || (nsuffix_length != suffix_length)
                        || ((nprefix_length > 0)
                            && crate::abi::exports_xml2::xmlStrncmp(
                                nprefix,
                                prefix,
                                prefix_length,
                            ) != 0)
                        || ((nsuffix_length > 0)
                            && crate::abi::exports_xml2::xmlStrncmp(
                                nsuffix,
                                suffix,
                                suffix_length,
                            ) != 0))
                {
                    prefix = nprefix;
                    prefix_length = nprefix_length;
                    suffix = nsuffix;
                    suffix_length = nsuffix_length;
                }
            }
        }

        // OUTPUT_NUMBER: on error use the default format.
        if found_error != 0 {
            xslt_error(
                ptr::null_mut(),
                b"xsltFormatNumberConversion : error in format string '%s', using default\n\0",
            );
            default_sign = if number < 0.0 { 1 } else { 0 };
            prefix_length = 0;
            suffix_length = 0;
            info.integer_hash = 0;
            info.integer_digits = 1;
            info.frac_digits = 1;
            info.frac_hash = 4;
            info.group = -1;
            info.multiplier = 1;
            info.add_decimal = 1;
        }

        // Apply the multiplier.
        number *= info.multiplier as f64;
        match crate::xml::xpath::exports::xmlXPathIsInf(number) {
            -1 => {
                // Intentional fall-through: minus sign then infinity.
                let minus = if (*self_).minusSign.is_null() {
                    b"-\0".as_ptr() as *const xmlChar
                } else {
                    (*self_).minusSign
                };
                let mut res = crate::abi::exports_xml2::xmlStrdup(minus);
                let inf = if self_.is_null() || (*self_).infinity.is_null() {
                    b"Infinity\0".as_ptr() as *const xmlChar
                } else {
                    (*self_).infinity
                };
                res = crate::abi::exports_xml2::xmlStrcat(res, inf);
                *result = res;
                return status;
            }
            1 => {
                let inf = if self_.is_null() || (*self_).infinity.is_null() {
                    b"Infinity\0".as_ptr() as *const xmlChar
                } else {
                    (*self_).infinity
                };
                *result = crate::abi::exports_xml2::xmlStrcat(ptr::null_mut(), inf);
                return status;
            }
            _ => {}
        }

        let buffer = crate::abi::exports_xml2::xmlBufferCreate();
        if buffer.is_null() {
            return XPATH_MEMORY_ERROR as c_int;
        }

        // Default sign first.
        if default_sign != 0 {
            crate::abi::exports_xml2::xmlBufferAdd(
                buffer,
                (*self_).minusSign,
                crate::abi::exports_string::xmlUTF8Strsize((*self_).minusSign, 1),
            );
        }

        // Prefix.
        let mut p = prefix;
        let mut j: c_int = 0;
        while j < prefix_length {
            if *p == SYMBOL_QUOTE {
                p = p.add(1);
            }
            len = crate::abi::exports_string::xmlUTF8Strsize(p, 1);
            crate::abi::exports_xml2::xmlBufferAdd(buffer, p, len);
            p = p.add(len as usize);
            j += len;
        }

        // Round to n digits.
        number = number.abs();
        let mut exp10: c_int = info.frac_digits + info.frac_hash;
        if exp10 > DBL_MAX_10_EXP {
            if info.frac_digits > DBL_MAX_10_EXP {
                info.frac_digits = DBL_MAX_10_EXP;
                info.frac_hash = 0;
            } else {
                info.frac_hash = DBL_MAX_10_EXP - info.frac_digits;
            }
            exp10 = DBL_MAX_10_EXP;
        }
        let scale = 10.0f64.powi(exp10);
        number += 0.5 / scale;
        number -= number % (1.0 / scale);

        // Integer part.
        if !(*self_).grouping.is_null() && *(*self_).grouping != 0 {
            len = crate::abi::exports_xml2::xmlStrlen((*self_).grouping);
            let gchar = xslt_get_utf8_char((*self_).grouping as *const u8, &mut len);
            number_format_decimal(
                buffer,
                number.floor(),
                *((*self_).zeroDigit) as c_int,
                info.integer_digits,
                info.group,
                gchar,
                len,
            );
        } else {
            number_format_decimal(
                buffer,
                number.floor(),
                *((*self_).zeroDigit) as c_int,
                info.integer_digits,
                info.group,
                b',' as c_int,
                1,
            );
        }

        // Special case: java treats '.#' like '.0', '.##' like '.0#', etc.
        if (info.integer_digits + info.integer_hash + info.frac_digits == 0) && (info.frac_hash > 0)
        {
            info.frac_digits += 1;
            info.frac_hash -= 1;
        }

        // Add a leading zero if required.
        if (number.floor() == 0.0) && (info.integer_digits + info.frac_digits == 0) {
            crate::abi::exports_xml2::xmlBufferAdd(
                buffer,
                (*self_).zeroDigit,
                crate::abi::exports_string::xmlUTF8Strsize((*self_).zeroDigit, 1),
            );
        }

        // Fractional part, if required.
        if info.frac_digits + info.frac_hash == 0 {
            if info.add_decimal != 0 {
                crate::abi::exports_xml2::xmlBufferAdd(
                    buffer,
                    (*self_).decimalPoint,
                    crate::abi::exports_string::xmlUTF8Strsize((*self_).decimalPoint, 1),
                );
            }
        } else {
            number -= number.floor();
            if (number != 0.0) || (info.frac_digits != 0) {
                crate::abi::exports_xml2::xmlBufferAdd(
                    buffer,
                    (*self_).decimalPoint,
                    crate::abi::exports_string::xmlUTF8Strsize((*self_).decimalPoint, 1),
                );
                number = (scale * number + 0.5).floor();
                let mut k = info.frac_hash;
                while k > 0 {
                    if number % 10.0 >= 1.0 {
                        break;
                    }
                    number /= 10.0;
                    k -= 1;
                }
                number_format_decimal(
                    buffer,
                    number.floor(),
                    *((*self_).zeroDigit) as c_int,
                    info.frac_digits + k,
                    0,
                    0,
                    0,
                );
            }
        }

        // Suffix.
        let mut s = suffix;
        let mut j: c_int = 0;
        while j < suffix_length {
            if *s == SYMBOL_QUOTE {
                s = s.add(1);
            }
            len = crate::abi::exports_string::xmlUTF8Strsize(s, 1);
            crate::abi::exports_xml2::xmlBufferAdd(buffer, s, len);
            s = s.add(len as usize);
            j += len;
        }

        *result =
            crate::abi::exports_xml2::xmlStrdup(crate::abi::exports_xml2::xmlBufferContent(buffer));
        crate::abi::exports_xml2::xmlBufferFree(buffer);
        status
    }
}

/// `xsltDecimalFormatGetByQName` (xslt.c): find a decimal format by QName,
/// searching the stylesheet and its imports.
unsafe fn decimal_format_get_by_qname(
    style: *mut _xsltStylesheet,
    ns_uri: *const xmlChar,
    name: *const xmlChar,
) -> *mut _xsltDecimalFormat {
    let mut style = style;
    unsafe {
        if name.is_null() {
            if style.is_null() {
                return ptr::null_mut();
            }
            return (*style).decimalFormat;
        }
        while !style.is_null() {
            // UPSTREAM-PARITY: upstream starts from `decimalFormat->next`,
            // skipping the always-present default format at the head. The
            // candidate only creates formats on demand, so the equivalent
            // is to match every entry (the default's NULL name can never
            // equal a non-NULL name).
            let mut result = (*style).decimalFormat;
            while !result.is_null() {
                if crate::abi::exports_xml2::xmlStrEqual(ns_uri, (*result).nsUri) != 0
                    && crate::abi::exports_xml2::xmlStrEqual(name, (*result).name) != 0
                {
                    return result;
                }
                result = (*result).next;
            }
            style = next_import(style);
        }
    }
    ptr::null_mut()
}

/// The default `_xsltDecimalFormat` values (upstream xsltNewDecimalFormat).
///
/// Used when the stylesheet declares no `xsl:decimal-format` (upstream
/// always creates the default; the candidate creates formats on demand).
static DEFAULT_FMT_DIGIT: &[u8] = b"#\0";
static DEFAULT_FMT_PATTERN_SEP: &[u8] = b";\0";
static DEFAULT_FMT_MINUS: &[u8] = b"-\0";
static DEFAULT_FMT_INFINITY: &[u8] = b"Infinity\0";
static DEFAULT_FMT_NAN: &[u8] = b"NaN\0";
static DEFAULT_FMT_DECIMAL: &[u8] = b".\0";
static DEFAULT_FMT_GROUPING: &[u8] = b",\0";
static DEFAULT_FMT_PERCENT: &[u8] = b"%\0";
static DEFAULT_FMT_PERMILLE: &[u8] = "\0".as_bytes();
static DEFAULT_FMT_ZERO: &[u8] = b"0\0";

unsafe fn default_decimal_format() -> _xsltDecimalFormat {
    _xsltDecimalFormat {
        next: ptr::null_mut(),
        name: ptr::null_mut(),
        digit: DEFAULT_FMT_DIGIT.as_ptr() as *mut xmlChar,
        patternSeparator: DEFAULT_FMT_PATTERN_SEP.as_ptr() as *mut xmlChar,
        minusSign: DEFAULT_FMT_MINUS.as_ptr() as *mut xmlChar,
        infinity: DEFAULT_FMT_INFINITY.as_ptr() as *mut xmlChar,
        noNumber: DEFAULT_FMT_NAN.as_ptr() as *mut xmlChar,
        decimalPoint: DEFAULT_FMT_DECIMAL.as_ptr() as *mut xmlChar,
        grouping: DEFAULT_FMT_GROUPING.as_ptr() as *mut xmlChar,
        percent: DEFAULT_FMT_PERCENT.as_ptr() as *mut xmlChar,
        permille: DEFAULT_FMT_PERMILLE.as_ptr() as *mut xmlChar,
        zeroDigit: DEFAULT_FMT_ZERO.as_ptr() as *mut xmlChar,
        nsUri: ptr::null(),
    }
}

/// Implement the XSLT `format-number()` function:
/// `string format-number(number, string, string?)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltFormatNumberFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltFormatNumberFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut number_obj: *mut _xmlXPathObject = ptr::null_mut();
    let mut format_obj: *mut _xmlXPathObject = ptr::null_mut();
    let mut decimal_obj: *mut _xmlXPathObject = ptr::null_mut();
    let mut format_values: *mut _xsltDecimalFormat = ptr::null_mut();

    let tctxt = transform_context_from_parser(ctxt);
    if tctxt.is_null() || (*tctxt).inst.is_null() {
        return;
    }
    let sheet = (*tctxt).style;
    if sheet.is_null() {
        return;
    }

    match nargs {
        3 => {
            if !(*pc).value.is_null()
                && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int
            {
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
            }
            decimal_obj = value_pop(pc);
            let (prefix, ncname) = split_qname_ref((*decimal_obj).stringval);
            let mut ns_uri: *const xmlChar = ptr::null();
            let mut ncname = ncname;
            if !prefix.is_null() {
                let ns = crate::abi::exports_xml2::xmlSearchNs(
                    (*(*tctxt).inst).doc,
                    (*tctxt).inst,
                    prefix,
                );
                if ns.is_null() {
                    xslt_error(
                        tctxt,
                        b"format-number : No namespace found for QName '%s:%s'\n\0",
                    );
                    (*sheet).errors += 1;
                    ncname = ptr::null();
                } else {
                    ns_uri = (*ns).href;
                }
            }
            if !ncname.is_null() {
                format_values = decimal_format_get_by_qname(sheet, ns_uri, ncname);
            }
            if format_values.is_null() {
                xslt_error(
                    tctxt,
                    b"format-number() : undeclared decimal format '%s'\n\0",
                );
            }
            // Intentional fall-through.
            if (*pc).value.is_null() {
                // Arity already validated below; nothing to pop.
            }
            if !(*pc).value.is_null()
                && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int
            {
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
            }
            format_obj = value_pop(pc);
            if !(*pc).value.is_null()
                && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_NUMBER as c_int
            {
                crate::xml::xpath::exports::xmlXPathNumberFunction(ctxt, 1);
            }
            number_obj = value_pop(pc);
        }
        2 => {
            if !(*pc).value.is_null()
                && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int
            {
                crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
            }
            format_obj = value_pop(pc);
            if !(*pc).value.is_null()
                && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_NUMBER as c_int
            {
                crate::xml::xpath::exports::xmlXPathNumberFunction(ctxt, 1);
            }
            number_obj = value_pop(pc);
        }
        _ => {
            (*pc).error = XPATH_INVALID_ARITY as c_int;
            return;
        }
    }

    // UPSTREAM-PARITY: upstream always has the default format at the head
    // of `style->decimalFormat`; the candidate creates formats on demand,
    // so a NULL head falls back to the standard defaults.
    let local_default: _xsltDecimalFormat;
    if format_values.is_null() {
        local_default = default_decimal_format();
        format_values = &local_default as *const _xsltDecimalFormat as *mut _xsltDecimalFormat;
    }

    if (*pc).error == 0
        && !format_values.is_null()
        && !format_obj.is_null()
        && !number_obj.is_null()
    {
        let mut result: *mut xmlChar = ptr::null_mut();
        if format_number_conversion(
            format_values,
            (*format_obj).stringval,
            (*number_obj).floatval,
            &mut result,
        ) == XPATH_EXPRESSION_OK as c_int
        {
            value_push(pc, xmlXPathNewString(result));
            if !result.is_null() {
                xmlFreeImpl(result as *mut c_void);
            }
        }
    }

    crate::abi::exports_xml2::xmlXPathFreeObject(number_obj);
    crate::abi::exports_xml2::xmlXPathFreeObject(format_obj);
    crate::abi::exports_xml2::xmlXPathFreeObject(decimal_obj);
}

/// Implement the XSLT `generate-id()` function:
/// `string generate-id(node-set?)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltGenerateIdFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut cur: *mut _xmlNode = ptr::null_mut();
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();
    let mut ns_prefix: *const xmlChar = ptr::null();
    let mut id: u64;
    let mut ns_prefix_size: usize = 0;

    let tctxt = transform_context_from_parser(ctxt);

    if nargs == 0 {
        let xpctxt = (*pc).context;
        cur = if xpctxt.is_null() {
            ptr::null_mut()
        } else {
            (*xpctxt).node
        };
    } else if nargs == 1 {
        if (*pc).value.is_null()
            || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_NODESET as c_int
        {
            (*pc).error = XPATH_INVALID_TYPE as c_int;
            xslt_error(
                tctxt,
                b"generate-id() : invalid arg expecting a node-set\n\0",
            );
            // goto out
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
            return;
        }
        obj = value_pop(pc);
        let nodelist = (*obj).nodesetval as *mut _xmlNodeSet;
        if nodelist.is_null() || (*nodelist).nodeNr <= 0 {
            value_push(
                pc,
                crate::abi::exports_xml2::xmlXPathNewCString(ptr::null()),
            );
            // goto out
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
            return;
        }
        cur = *(*nodelist).nodeTab;
        let mut i: c_int = 1;
        while i < (*nodelist).nodeNr {
            let ret = crate::abi::exports_xml2::xmlXPathCmpNodes(
                cur,
                *(*nodelist).nodeTab.offset(i as isize),
            );
            if ret == -1 {
                cur = *(*nodelist).nodeTab.offset(i as isize);
            }
            i += 1;
        }
    } else {
        xslt_error(tctxt, b"generate-id() : invalid number of args %d\n\0");
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        // goto out
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        return;
    }

    let mut size: usize = 30; // for "id%lu"

    if cur.is_null() {
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        return;
    }

    if (*cur).type_ == XML_NAMESPACE_DECL as c_int {
        let ns = cur as *mut _xmlNs;
        ns_prefix = (*ns).prefix;
        if ns_prefix.is_null() {
            ns_prefix = b"\0".as_ptr() as *const xmlChar;
        }
        ns_prefix_size = crate::abi::exports_xml2::xmlStrlen(ns_prefix) as usize;
        // For "ns" and the hex-encoded string.
        size += ns_prefix_size * 2 + 2;
        // Parent is stored in 'next'.
        cur = (*ns).next as *mut _xmlNode;
    }

    let psvi_ptr = get_psvi_ptr(cur);
    if psvi_ptr.is_null() {
        xslt_error(tctxt, b"generate-id(): invalid node type %d\n\0");
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        // goto out
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        return;
    }

    if (get_source_node_flags(cur) & XSLT_SOURCE_NODE_HAS_ID) != 0 {
        id = *psvi_ptr as u64;
    } else {
        if (*cur).type_ == XML_TEXT_NODE as c_int && (*cur).line == u16::MAX {
            // Text nodes store big line numbers in psvi.
            (*cur).line = 0;
        } else if !(*psvi_ptr).is_null() {
            xslt_error(tctxt, b"generate-id(): psvi already set\n\0");
            (*pc).error = XPATH_MEMORY_ERROR as c_int;
            // goto out
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
            return;
        }

        if !tctxt.is_null() && (*tctxt).currentId == u64::MAX {
            xslt_error(tctxt, b"generate-id(): id overflow\n\0");
            (*pc).error = XPATH_MEMORY_ERROR as c_int;
            // goto out
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
            return;
        }

        if tctxt.is_null() {
            (*pc).error = XPATH_MEMORY_ERROR as c_int;
            crate::abi::exports_xml2::xmlXPathFreeObject(obj);
            return;
        }
        id = (*tctxt).currentId + 1;
        (*tctxt).currentId = id;
        *psvi_ptr = id as *mut c_void;
        set_source_node_flags(tctxt, cur, XSLT_SOURCE_NODE_HAS_ID);
    }

    let buf = xmlMallocImpl(size) as *mut u8;
    if buf.is_null() {
        xslt_error(tctxt, b"generate-id(): out of memory\n\0");
        (*pc).error = XPATH_MEMORY_ERROR as c_int;
        // goto out
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        return;
    }
    let mut content: Vec<u8> = Vec::with_capacity(size);
    if ns_prefix.is_null() {
        content.extend_from_slice(format!("id{}", id).as_bytes());
    } else {
        content.extend_from_slice(format!("id{}ns", id).as_bytes());
        // Only ASCII alphanumerics are allowed, so hex-encode the prefix.
        for i in 0..ns_prefix_size {
            let v = *ns_prefix.add(i) >> 4;
            content.push(if v < 10 { b'0' + v } else { b'A' + (v - 10) });
            let v = *ns_prefix.add(i) & 15;
            content.push(if v < 10 { b'0' + v } else { b'A' + (v - 10) });
        }
    }
    debug_assert!(content.len() < size);
    ptr::copy_nonoverlapping(content.as_ptr(), buf, content.len());
    *buf.add(content.len()) = 0;
    value_push(
        pc,
        crate::xml::xpath::exports::xmlXPathWrapString(buf as *mut xmlChar),
    );

    // out:
    crate::abi::exports_xml2::xmlXPathFreeObject(obj);
}

/// Implement the XSLT `system-property()` function:
/// `object system-property(string)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltSystemPropertyFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltSystemPropertyFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();

    if nargs != 1 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"system-property() : expects one string arg\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    if (*pc).value.is_null() || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"system-property() : invalid arg expecting a string\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        return;
    }
    obj = value_pop(pc);

    if (*obj).stringval.is_null() {
        value_push(pc, xmlXPathNewString(ptr::null()));
    } else {
        let mut name: *mut xmlChar = ptr::null_mut();
        let mut ns_uri: *const xmlChar = ptr::null();
        let mut prefix: *mut xmlChar = ptr::null_mut();
        name = crate::xml::string::split_qname2((*obj).stringval, &mut prefix);
        if name.is_null() {
            name = crate::abi::exports_xml2::xmlStrdup((*obj).stringval);
        } else {
            let xpctxt = (*pc).context;
            ns_uri = if xpctxt.is_null() {
                ptr::null()
            } else {
                crate::xml::xpath::exports::xmlXPathNsLookup(xpctxt, prefix)
            };
            if ns_uri.is_null() {
                xslt_error(
                    transform_context_from_parser(ctxt),
                    b"system-property() : prefix %s is not bound\n\0",
                );
            }
        }

        if crate::abi::exports_xml2::xmlStrEqual(ns_uri, XSLT_NAMESPACE.as_ptr() as *const xmlChar)
            != 0
        {
            if xml_chars_equal(name, b"vendor\0".as_ptr() as *const xmlChar) {
                // DOCBOOK_XSL_HACK (functions.c): DocBook XSL uses the vendor
                // string to detect chunking support.
                let tctxt = transform_context_from_parser(ctxt);
                let sheet = if !tctxt.is_null()
                    && !(*tctxt).inst.is_null()
                    && xml_chars_equal(
                        (*(*tctxt).inst).name,
                        b"variable\0".as_ptr() as *const xmlChar,
                    )
                    && !(*(*tctxt).inst).parent.is_null()
                    && xml_chars_equal(
                        (*(*(*tctxt).inst).parent).name,
                        b"template\0".as_ptr() as *const xmlChar,
                    ) {
                    (*tctxt).style
                } else {
                    ptr::null_mut()
                };
                if !sheet.is_null()
                    && !(*sheet).doc.is_null()
                    && !(*(*sheet).doc).URL.is_null()
                    && !crate::abi::exports_string::xmlStrstr(
                        (*(*sheet).doc).URL as *const xmlChar,
                        b"chunk\0".as_ptr() as *const xmlChar,
                    )
                    .is_null()
                {
                    value_push(
                        pc,
                        xmlXPathNewString(
                            b"libxslt (SAXON 6.2 compatible)\0".as_ptr() as *const xmlChar
                        ),
                    );
                } else {
                    value_push(
                        pc,
                        xmlXPathNewString(XSLT_DEFAULT_VENDOR.as_ptr() as *const xmlChar),
                    );
                }
            } else if xml_chars_equal(name, b"version\0".as_ptr() as *const xmlChar) {
                value_push(
                    pc,
                    xmlXPathNewString(XSLT_DEFAULT_VERSION.as_ptr() as *const xmlChar),
                );
            } else if xml_chars_equal(name, b"vendor-url\0".as_ptr() as *const xmlChar) {
                value_push(
                    pc,
                    xmlXPathNewString(XSLT_DEFAULT_URL.as_ptr() as *const xmlChar),
                );
            } else {
                value_push(pc, xmlXPathNewString(ptr::null()));
            }
        } else {
            value_push(pc, xmlXPathNewString(ptr::null()));
        }
        if !name.is_null() {
            xmlFreeImpl(name as *mut c_void);
        }
        if !prefix.is_null() {
            xmlFreeImpl(prefix as *mut c_void);
        }
    }
    crate::abi::exports_xml2::xmlXPathFreeObject(obj);
}

/// The standard XSLT elements registered by upstream `xsltRegisterAllElement`
/// (transform.c) — used by element-available().
static XSLT_ELEMENTS: &[&[u8]] = &[
    b"apply-templates\0",
    b"apply-imports\0",
    b"call-template\0",
    b"element\0",
    b"attribute\0",
    b"text\0",
    b"processing-instruction\0",
    b"comment\0",
    b"copy\0",
    b"value-of\0",
    b"number\0",
    b"for-each\0",
    b"if\0",
    b"choose\0",
    b"sort\0",
    b"copy-of\0",
    b"message\0",
    b"variable\0",
    b"param\0",
    b"with-param\0",
    b"decimal-format\0",
    b"when\0",
    b"otherwise\0",
    b"fallback\0",
];

/// `xsltExtElementLookup` (extensions.c): context-level extension elements
/// first, then the module registry.
///
/// UPSTREAM-PARITY (simplified): the candidate has no module-level element
/// registry (`xsltRegisterExtModuleElement`); the standard XSLT instruction
/// elements that upstream registers globally are reported available here.
unsafe fn xslt_ext_element_lookup(
    ctxt: *mut _xsltTransformContext,
    name: *const xmlChar,
    ns_uri: *const xmlChar,
) -> *mut c_void {
    if name.is_null() || ns_uri.is_null() {
        return ptr::null_mut();
    }
    if !ctxt.is_null() && !(*ctxt).extElements.is_null() {
        let f = crate::xslt::extensions::xsltFindExtElement(ctxt, name, ns_uri);
        if !f.is_null() {
            return f;
        }
    }
    if xml_chars_equal(ns_uri, XSLT_NAMESPACE.as_ptr() as *const xmlChar) {
        for e in XSLT_ELEMENTS {
            if xml_chars_equal(name, e.as_ptr() as *const xmlChar) {
                // Only a non-NULL presence marker is tested by the caller.
                return 1usize as *mut c_void;
            }
        }
    }
    ptr::null_mut()
}

/// Implement the XSLT `element-available()` function:
/// `boolean element-available(string)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltElementAvailableFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltElementAvailableFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();

    if nargs != 1 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"element-available() : expects one string arg\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
    if (*pc).value.is_null() || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"element-available() : invalid arg expecting a string\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        return;
    }
    obj = value_pop(pc);
    let tctxt = transform_context_from_parser(ctxt);
    if tctxt.is_null() || (*tctxt).inst.is_null() {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"element-available() : internal error tctxt == NULL\n\0",
        );
        crate::abi::exports_xml2::xmlXPathFreeObject(obj);
        value_push(pc, crate::abi::exports_xml2::xmlXPathNewBoolean(0));
        return;
    }

    let mut name: *mut xmlChar = ptr::null_mut();
    let mut ns_uri: *const xmlChar = ptr::null();
    let mut prefix: *mut xmlChar = ptr::null_mut();
    name = crate::xml::string::split_qname2((*obj).stringval, &mut prefix);
    if name.is_null() {
        name = crate::abi::exports_xml2::xmlStrdup((*obj).stringval);
        let ns =
            crate::abi::exports_xml2::xmlSearchNs((*(*tctxt).inst).doc, (*tctxt).inst, ptr::null());
        if !ns.is_null() {
            ns_uri = (*ns).href;
        }
    } else {
        let xpctxt = (*pc).context;
        ns_uri = if xpctxt.is_null() {
            ptr::null()
        } else {
            crate::xml::xpath::exports::xmlXPathNsLookup(xpctxt, prefix)
        };
        if ns_uri.is_null() {
            xslt_error(tctxt, b"element-available() : prefix %s is not bound\n\0");
        }
    }

    if !xslt_ext_element_lookup(tctxt, name, ns_uri).is_null() {
        value_push(pc, crate::abi::exports_xml2::xmlXPathNewBoolean(1));
    } else {
        value_push(pc, crate::abi::exports_xml2::xmlXPathNewBoolean(0));
    }

    crate::abi::exports_xml2::xmlXPathFreeObject(obj);
    if !name.is_null() {
        xmlFreeImpl(name as *mut c_void);
    }
    if !prefix.is_null() {
        xmlFreeImpl(prefix as *mut c_void);
    }
}

/// Implement the XSLT `function-available()` function:
/// `boolean function-available(string)`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltFunctionAvailableFunction(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltFunctionAvailableFunction(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    let mut obj: *mut _xmlXPathObject = ptr::null_mut();

    if nargs != 1 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"function-available() : expects one string arg\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    crate::xml::xpath::exports::xmlXPathStringFunction(ctxt, 1);
    if (*pc).value.is_null() || (*(*pc).value).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"function-available() : invalid arg expecting a string\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        return;
    }
    obj = value_pop(pc);

    let mut name: *mut xmlChar = ptr::null_mut();
    let mut ns_uri: *const xmlChar = ptr::null();
    let mut prefix: *mut xmlChar = ptr::null_mut();
    name = crate::xml::string::split_qname2((*obj).stringval, &mut prefix);
    if name.is_null() {
        name = crate::abi::exports_xml2::xmlStrdup((*obj).stringval);
    } else {
        let xpctxt = (*pc).context;
        ns_uri = if xpctxt.is_null() {
            ptr::null()
        } else {
            crate::xml::xpath::exports::xmlXPathNsLookup(xpctxt, prefix)
        };
        if ns_uri.is_null() {
            xslt_error(
                transform_context_from_parser(ctxt),
                b"function-available() : prefix %s is not bound\n\0",
            );
        }
    }

    let xpctxt = (*pc).context;
    if !xpctxt.is_null()
        && !crate::xml::xpath::exports::xmlXPathFunctionLookupNS(xpctxt, name, ns_uri).is_none()
    {
        value_push(pc, crate::abi::exports_xml2::xmlXPathNewBoolean(1));
    } else {
        value_push(pc, crate::abi::exports_xml2::xmlXPathNewBoolean(0));
    }

    crate::abi::exports_xml2::xmlXPathFreeObject(obj);
    if !name.is_null() {
        xmlFreeImpl(name as *mut c_void);
    }
    if !prefix.is_null() {
        xmlFreeImpl(prefix as *mut c_void);
    }
}

/// Upstream `xsltCurrentFunction` (functions.c, static): the XSLT `current()`
/// function, registered by `xsltRegisterAllFunctions`.
unsafe extern "C" fn xslt_current_function(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    if nargs != 0 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"current() : function uses no argument\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    let tctxt = transform_context_from_parser(ctxt);
    if tctxt.is_null() {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"current() : internal error tctxt == NULL\n\0",
        );
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet(ptr::null_mut()),
        );
    } else {
        value_push(
            pc,
            crate::abi::exports_xml2::xmlXPathNewNodeSet((*tctxt).node),
        ); // current
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 2. node-set() extension (extra.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Implement the `node-set()` XSLT extension function (libxslt, saxon and xt
/// namespaces): convert a result tree fragment to a node-set.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltFunctionNodeSet(xmlXPathParserContextPtr ctxt, int nargs);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context.
#[no_mangle]
pub unsafe extern "C" fn xsltFunctionNodeSet(ctxt: *mut c_void, nargs: c_int) {
    let pc = ctxt as *mut XmlXPathParserContext;
    if pc.is_null() {
        return;
    }
    if nargs != 1 {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"node-set() : expects one result-tree arg\n\0",
        );
        (*pc).error = XPATH_INVALID_ARITY as c_int;
        return;
    }
    if (*pc).value.is_null()
        || ((*(*pc).value).type_ != xmlXPathObjectType::XPATH_XSLT_TREE as c_int
            && (*(*pc).value).type_ != xmlXPathObjectType::XPATH_NODESET as c_int)
    {
        xslt_error(
            transform_context_from_parser(ctxt),
            b"node-set() invalid arg expecting a result tree\n\0",
        );
        (*pc).error = XPATH_INVALID_TYPE as c_int;
        return;
    }
    if (*(*pc).value).type_ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int {
        (*(*pc).value).type_ = xmlXPathObjectType::XPATH_NODESET as c_int;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 3. XPath evaluation utilities (templates.c / xsltutils.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Mirror the C-level XPath context state into the internal Rust evaluator
/// context (which is what the evaluator reads via `extra`), and apply the
/// temporary namespace list.
///
/// Returns the previous internal namespace map (to restore later).
unsafe fn mirror_context_for_eval(
    ctxt: *mut _xsltTransformContext,
    ns_list: *mut *mut _xmlNs,
    ns_nr: c_int,
) -> std::collections::HashMap<String, String> {
    let xpath_ctxt = (*ctxt).xpathCtxt;
    let internal = internal_xpath_ctxt(xpath_ctxt);
    let mut saved: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    if internal.is_null() {
        return saved;
    }
    unsafe {
        let node = (*ctxt).node;
        (*internal).context_node = node;
        if !node.is_null() && !(*node).doc.is_null() {
            (*internal).document = (*node).doc;
        }
        (*internal).context_size = (*xpath_ctxt).contextSize;
        (*internal).context_position = (*xpath_ctxt).proximityPosition;
        (*internal).proximity_position = (*xpath_ctxt).proximityPosition;
        if !(*internal).context_list.is_empty() {
            // keep the existing context list; position/size are mirrored above
        }
        // Temporarily replace the namespace map with the nsList contents.
        saved = std::mem::replace(
            &mut (*internal).namespaces,
            std::collections::HashMap::new(),
        );
        if !ns_list.is_null() {
            let mut i: c_int = 0;
            while i < ns_nr {
                let ns = *ns_list.offset(i as isize);
                if !ns.is_null() {
                    let p = (*ns).prefix;
                    let h = (*ns).href;
                    if !p.is_null() && !h.is_null() {
                        let prefix_str = CStr::from_ptr(p as *const c_char)
                            .to_string_lossy()
                            .into_owned();
                        let href_str = CStr::from_ptr(h as *const c_char)
                            .to_string_lossy()
                            .into_owned();
                        (*internal).namespaces.insert(prefix_str, href_str);
                    }
                }
                i += 1;
            }
        }
    }
    saved
}

/// Evaluate a compiled XPath expression as a predicate on `ctxt->node`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xsltEvalXPathPredicate(xsltTransformContextPtr ctxt,
///                            xmlXPathCompExprPtr comp,
///                            xmlNsPtr *nsList, int nsNr);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context; `comp` a compiled expression
///   or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltEvalXPathPredicate(
    ctxt: *mut _xsltTransformContext,
    comp: *mut c_void,
    nsList: *mut *mut _xmlNs,
    nsNr: c_int,
) -> c_int {
    if ctxt.is_null() || (*ctxt).inst.is_null() {
        xslt_error(
            ctxt,
            b"xsltEvalXPathPredicate: No context or instruction\n\0",
        );
        return 0;
    }
    let xpath_ctxt = (*ctxt).xpathCtxt;
    if xpath_ctxt.is_null() {
        return 0;
    }

    let old_node = (*xpath_ctxt).node;
    let old_context_size = (*xpath_ctxt).contextSize;
    let old_proximity_position = (*xpath_ctxt).proximityPosition;
    let old_ns_nr = (*xpath_ctxt).nsNr;
    let old_namespaces = (*xpath_ctxt).namespaces;
    let old_inst = (*ctxt).inst;

    (*xpath_ctxt).node = (*ctxt).node;
    (*xpath_ctxt).namespaces = nsList;
    (*xpath_ctxt).nsNr = nsNr;
    let saved_ns = mirror_context_for_eval(ctxt, nsList, nsNr);

    let res = crate::xml::xpath::exports::xmlXPathCompiledEval(comp, xpath_ctxt);

    let ret: c_int;
    if !res.is_null() {
        ret = crate::xml::xpath::exports::xmlXPathEvalPredicate(xpath_ctxt, res);
        crate::abi::exports_xml2::xmlXPathFreeObject(res);
    } else {
        (*ctxt).state = XSLT_STATE_STOPPED;
        ret = 0;
    }

    (*xpath_ctxt).node = old_node;
    (*xpath_ctxt).nsNr = old_ns_nr;
    (*xpath_ctxt).namespaces = old_namespaces;
    (*ctxt).inst = old_inst;
    (*xpath_ctxt).contextSize = old_context_size;
    (*xpath_ctxt).proximityPosition = old_proximity_position;
    let internal = internal_xpath_ctxt(xpath_ctxt);
    if !internal.is_null() {
        (*internal).namespaces = saved_ns;
        (*internal).context_node = old_node;
        (*internal).context_size = old_context_size;
        (*internal).context_position = old_proximity_position;
        (*internal).proximity_position = old_proximity_position;
    }

    ret
}

/// Evaluate a compiled XPath expression with an explicit namespace mapping
/// and return its string value.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlChar * xsltEvalXPathStringNs(xsltTransformContextPtr ctxt,
///                                 xmlXPathCompExprPtr comp,
///                                 int nsNr, xmlNsPtr *nsList);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context; `comp` a compiled expression
///   or NULL. The returned string is xmlMalloc'd and must be freed by the
///   caller with `xmlFree`.
#[no_mangle]
pub unsafe extern "C" fn xsltEvalXPathStringNs(
    ctxt: *mut _xsltTransformContext,
    comp: *mut c_void,
    nsNr: c_int,
    nsList: *mut *mut _xmlNs,
) -> *mut xmlChar {
    if ctxt.is_null() || (*ctxt).inst.is_null() {
        xslt_error(
            ctxt,
            b"xsltEvalXPathStringNs: No context or instruction\n\0",
        );
        return ptr::null_mut();
    }
    let xpath_ctxt = (*ctxt).xpathCtxt;
    if xpath_ctxt.is_null() {
        return ptr::null_mut();
    }

    let old_inst = (*ctxt).inst;
    let old_node = (*xpath_ctxt).node;
    let old_pos = (*xpath_ctxt).proximityPosition;
    let old_size = (*xpath_ctxt).contextSize;
    let old_ns_nr = (*xpath_ctxt).nsNr;
    let old_namespaces = (*xpath_ctxt).namespaces;

    (*xpath_ctxt).node = (*ctxt).node;
    (*xpath_ctxt).namespaces = nsList;
    (*xpath_ctxt).nsNr = nsNr;
    let saved_ns = mirror_context_for_eval(ctxt, nsList, nsNr);

    let mut ret: *mut xmlChar = ptr::null_mut();
    let mut res = crate::xml::xpath::exports::xmlXPathCompiledEval(comp, xpath_ctxt);
    if !res.is_null() {
        if (*res).type_ != xmlXPathObjectType::XPATH_STRING as c_int {
            res = crate::xml::xpath::exports::xmlXPathConvertString(res);
        }
        if !res.is_null() && (*res).type_ == xmlXPathObjectType::XPATH_STRING as c_int {
            ret = (*res).stringval;
            (*res).stringval = ptr::null_mut();
        } else {
            xslt_error(
                ctxt,
                b"xpath : string() function didn't return a String\n\0",
            );
        }
        crate::abi::exports_xml2::xmlXPathFreeObject(res);
    } else {
        (*ctxt).state = XSLT_STATE_STOPPED;
    }

    (*ctxt).inst = old_inst;
    (*xpath_ctxt).node = old_node;
    (*xpath_ctxt).contextSize = old_size;
    (*xpath_ctxt).proximityPosition = old_pos;
    (*xpath_ctxt).nsNr = old_ns_nr;
    (*xpath_ctxt).namespaces = old_namespaces;
    let internal = internal_xpath_ctxt(xpath_ctxt);
    if !internal.is_null() {
        (*internal).namespaces = saved_ns;
        (*internal).context_node = old_node;
        (*internal).context_size = old_size;
        (*internal).context_position = old_pos;
        (*internal).proximity_position = old_pos;
    }

    ret
}

/// Evaluate a compiled XPath expression and return its string value.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlChar * xsltEvalXPathString(xsltTransformContextPtr ctxt,
///                               xmlXPathCompExprPtr comp);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context; `comp` a compiled expression
///   or NULL. The returned string is xmlMalloc'd and must be freed by the
///   caller with `xmlFree`.
#[no_mangle]
pub unsafe extern "C" fn xsltEvalXPathString(
    ctxt: *mut _xsltTransformContext,
    comp: *mut c_void,
) -> *mut xmlChar {
    unsafe { xsltEvalXPathStringNs(ctxt, comp, 0, ptr::null_mut()) }
}

/// Compile an XPath expression with extra compilation flags, using the
/// stylesheet's XPath context (or a fresh one when `style` is NULL).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathCompExprPtr xsltXPathCompileFlags(xsltStylesheetPtr style,
///                                           const xmlChar *str, int flags);
/// ```
///
/// # SAFETY
///
/// - `style` must be a valid stylesheet or NULL; `str` a valid string or
///   NULL. The caller frees the result with `xmlXPathFreeCompExpr`.
#[no_mangle]
pub unsafe extern "C" fn xsltXPathCompileFlags(
    style: *mut _xsltStylesheet,
    str_: *const xmlChar,
    flags: c_int,
) -> *mut c_void {
    if str_.is_null() {
        return ptr::null_mut();
    }
    let xpath_ctxt: *mut _xmlXPathContext;
    let mut free_ctxt: bool = false;
    if !style.is_null() {
        // UPSTREAM-PARITY: upstream uses `style->principal->xpathCtxt`
        // (principal is the top-level stylesheet for imports).
        let principal = if (*style).principal.is_null() {
            style
        } else {
            (*style).principal
        };
        xpath_ctxt = (*principal).xpathCtxt;
        if xpath_ctxt.is_null() {
            return ptr::null_mut();
        }
        (*xpath_ctxt).dict = (*style).dict;
    } else {
        xpath_ctxt = crate::abi::exports_xml2::xmlXPathNewContext(ptr::null_mut());
        if xpath_ctxt.is_null() {
            return ptr::null_mut();
        }
        free_ctxt = true;
    }
    (*xpath_ctxt).flags = flags;

    let ret = crate::xml::xpath::exports::xmlXPathCtxtCompile(xpath_ctxt, str_);

    if free_ctxt {
        crate::abi::exports_xml2::xmlXPathFreeContext(xpath_ctxt);
    }
    ret
}

/// Compile an XPath expression.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathCompExprPtr xsltXPathCompile(xsltStylesheetPtr style,
///                                      const xmlChar *str);
/// ```
///
/// # SAFETY
///
/// - `style` must be a valid stylesheet or NULL; `str` a valid string or
///   NULL. The caller frees the result with `xmlXPathFreeCompExpr`.
#[no_mangle]
pub unsafe extern "C" fn xsltXPathCompile(
    style: *mut _xsltStylesheet,
    str_: *const xmlChar,
) -> *mut c_void {
    unsafe { xsltXPathCompileFlags(style, str_, 0) }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 4. XPath-context hooks (functions.c / variables.c / extensions.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Look up an XPath extension function for the XPath interpreter
/// (registered as the context's `funcLookupFunc`; `vctxt` is the XPath
/// context).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathFunction xsltXPathFunctionLookup(void *vctxt,
///                                          const xmlChar *name,
///                                          const xmlChar *ns_uri);
/// ```
///
/// # SAFETY
///
/// - `vctxt` must be a valid XPath context; `name`/`ns_uri` valid strings.
#[no_mangle]
pub unsafe extern "C" fn xsltXPathFunctionLookup(
    vctxt: *mut c_void,
    name: *const xmlChar,
    ns_uri: *const xmlChar,
) -> Option<unsafe extern "C" fn(*mut c_void, c_int)> {
    if vctxt.is_null() || name.is_null() || ns_uri.is_null() {
        return None;
    }
    let xpath_ctxt = vctxt as *mut _xmlXPathContext;
    // Give priority to context-level functions (upstream
    // xmlHashLookup2(ctxt->funcHash, name, ns_uri)).
    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
        Ok(s) => s,
        Err(_) => return None,
    };
    let qualified = if ns_uri.is_null() {
        name_str.to_string()
    } else {
        let ns = match CStr::from_ptr(ns_uri as *const c_char).to_str() {
            Ok(s) => s,
            Err(_) => return None,
        };
        format!("{{{}}}{}", ns, name_str)
    };
    if let Some(f) = crate::abi::exports_xml2::xpath_cfunc_lookup((*xpath_ctxt).extra, &qualified) {
        return Some(f);
    }
    // Module registry fallback (upstream xsltExtModuleFunctionLookup).
    // UPSTREAM-PARITY (simplified): the candidate's module-level registry
    // (crate::exslt) holds Rust closures with the internal XPathFunction
    // signature, which cannot be exposed through the C `xmlXPathFunction`
    // pointer type; nothing else registers module functions.
    None
}

/// Look up a global XSLT variable in the internal XPath context's variable
/// hash (the candidate keeps globals there — see xsltInitGlobalVariables).
unsafe fn internal_global_variable_lookup(
    tctxt: *mut _xsltTransformContext,
    name: *const xmlChar,
) -> *mut _xmlXPathObject {
    if tctxt.is_null() || name.is_null() || (*tctxt).xpathCtxt.is_null() {
        return ptr::null_mut();
    }
    let internal = internal_xpath_ctxt((*tctxt).xpathCtxt);
    if internal.is_null() {
        return ptr::null_mut();
    }
    let name_str = match CStr::from_ptr(name as *const c_char).to_str() {
        Ok(s) => s,
        Err(_) => return ptr::null_mut(),
    };
    match (*internal).variables.get(name_str) {
        Some(v) => crate::abi::exports_xml2::xpath_to_object_pub(v.clone()),
        None => ptr::null_mut(),
    }
}

/// Look up a variable for the XPath interpreter (registered as the
/// context's `varLookupFunc`; `ctxt` is the transform context).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathObjectPtr xsltXPathVariableLookup(void *ctxt,
///                                           const xmlChar *name,
///                                           const xmlChar *ns_uri);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context; `name`/`ns_uri` valid
///   strings. The returned object is owned by the caller.
#[no_mangle]
pub unsafe extern "C" fn xsltXPathVariableLookup(
    ctxt: *mut c_void,
    name: *const xmlChar,
    ns_uri: *const xmlChar,
) -> *mut _xmlXPathObject {
    if ctxt.is_null() || name.is_null() {
        return ptr::null_mut();
    }
    let tctxt = ctxt as *mut _xsltTransformContext;
    let mut value_obj: *mut _xmlXPathObject = ptr::null_mut();

    // Local variables/params: lookup from the top of the stack.
    if (*tctxt).varsNr != 0 {
        let variable = crate::xslt::variables::xsltLookupVariable(tctxt, name, ns_uri);
        if !variable.is_null() {
            if (*variable).computed == 0 {
                // UPSTREAM-PARITY: upstream computes lazily and stores the
                // value on the stack element; the candidate computes
                // variables eagerly at push time, so xsltEvalVariable
                // returns a copy of the stored value.
                let v = crate::xslt::variables::xsltEvalVariable(tctxt, variable);
                (*variable).computed = 1;
                if !v.is_null() {
                    value_obj = v;
                }
            } else if !(*variable).value.is_null() {
                value_obj = crate::abi::exports_xml2::xmlXPathObjectCopy((*variable).value);
            }
            if !value_obj.is_null() {
                return value_obj;
            }
        }
    }

    // Global variables/params.
    if value_obj.is_null() {
        value_obj = internal_global_variable_lookup(tctxt, name);
    }

    if value_obj.is_null() {
        // UPSTREAM-PARITY: upstream reports the undeclared variable via
        // xsltTransformError (the format arguments are not expanded in the
        // candidate's safe error subset).
        if !ns_uri.is_null() {
            xslt_error(tctxt, b"Variable '{%s}%s' has not been declared.\n\0");
        } else {
            xslt_error(tctxt, b"Variable '%s' has not been declared.\n\0");
        }
    }
    value_obj
}

/// Provide the XSLT transformation context from the XPath parser context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xsltTransformContextPtr xsltXPathGetTransformContext(xmlXPathParserContextPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid parser context or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltXPathGetTransformContext(
    ctxt: *mut c_void,
) -> *mut _xsltTransformContext {
    unsafe { transform_context_from_parser(ctxt) }
}

// ═══════════════════════════════════════════════════════════════════════════════
// 5. Registration (functions.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Register all default XSLT functions in an XPath context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xsltRegisterAllFunctions(xmlXPathContextPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid XPath context.
#[no_mangle]
pub unsafe extern "C" fn xsltRegisterAllFunctions(ctxt: *mut _xmlXPathContext) {
    if ctxt.is_null() {
        return;
    }
    // Order matters: register the C-level functions first (they install a
    // stub in the internal evaluator context), then re-register the
    // internal Rust implementations so the native evaluator keeps its full
    // implementations (the stubs cannot be invoked from the Rust engine).
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"current\0".as_ptr() as *const xmlChar,
        Some(xslt_current_function),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"document\0".as_ptr() as *const xmlChar,
        Some(xsltDocumentFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"key\0".as_ptr() as *const xmlChar,
        Some(xsltKeyFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"unparsed-entity-uri\0".as_ptr() as *const xmlChar,
        Some(xsltUnparsedEntityURIFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"format-number\0".as_ptr() as *const xmlChar,
        Some(xsltFormatNumberFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"generate-id\0".as_ptr() as *const xmlChar,
        Some(xsltGenerateIdFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"system-property\0".as_ptr() as *const xmlChar,
        Some(xsltSystemPropertyFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"element-available\0".as_ptr() as *const xmlChar,
        Some(xsltElementAvailableFunction),
    );
    crate::abi::exports_xml2::xmlXPathRegisterFunc(
        ctxt,
        b"function-available\0".as_ptr() as *const xmlChar,
        Some(xsltFunctionAvailableFunction),
    );

    // Re-register the internal Rust implementations on the transform's
    // XPath context (candidate wiring — see register_xslt_functions in
    // src/xslt/transform/mod.rs).
    let internal = internal_xpath_ctxt(ctxt);
    if !internal.is_null() {
        let tctxt = (*internal).func_lookup_data as *mut _xsltTransformContext;
        if !tctxt.is_null() {
            crate::xslt::transform::register_xslt_functions(tctxt);
        }
    }
}