libxml-rs 0.1.0-alpha.27

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
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
//! C ABI exports for libxslt.so.1 — the "exec" family (§16, Phase 8).
//!
//! This module implements the element-instruction *execution* entry points
//! of the libxslt 1.1.45 C ABI: the `xslt*` runtime handlers for
//! `xsl:attribute`, `xsl:element`, `xsl:text`, `xsl:comment`,
//! `xsl:processing-instruction`, `xsl:copy`, `xsl:copy-of`, `xsl:value-of`,
//! `xsl:number`, `xsl:choose`, `xsl:if`, `xsl:for-each`, `xsl:sort`,
//! `xsl:message`, the multi-document extension elements (`xsltDocumentElem`)
//! and the numeric-formatting / sorting machinery:
//!
//! - Numbering (numbers.c): `xsltNumberFormat`, `xsltFormatNumberConversion`,
//!   `xsltDecimalFormatGetByName`, `xsltDecimalFormatGetByQName`
//! - Sorting (xsltutils.c): `xsltDefaultSortFunction`, `xsltDoSortFunction`,
//!   `xsltDocumentSortFunction`, `xsltComputeSortResult`, `xsltSetSortFunc`,
//!   `xsltSetCtxtSortFunc`
//! - Debug helper (extra.c): `xsltDebug`
//!
//! Where the native-Rust XSLT engine in `src/xslt/*` already implements the
//! upstream behaviour (the engine is oracle-tested through the xsltproc
//! CLI), the exports below are wired to it; the rest are faithful ports of
//! the upstream C sources in `archaeology/libxslt-git/libxslt/`.

#![allow(non_snake_case)]
#![allow(unused_variables)]

use core::ptr;
use std::os::raw::{c_char, c_double, c_int, c_uint, c_void};

use crate::abi::allocator::{xmlFreeImpl, xmlMallocImpl};
use crate::abi::exports_buffer::xmlBufferCCat;
use crate::abi::exports_html::{htmlNewDoc, htmlNewDocNoDtD};
use crate::abi::exports_string::{xmlStrstr, xmlUTF8Strloc, xmlUTF8Strpos, xmlUTF8Strsize};
use crate::abi::exports_uri::xmlBuildURI;
use crate::abi::exports_xml2::{
    xmlBufferAdd, xmlBufferCat, xmlBufferContent, xmlBufferCreate, xmlBufferFree,
    xmlCreateIntSubset, xmlDocGetRootElement, xmlNewComment, xmlNewDoc, xmlStrEqual, xmlStrcat,
    xmlStrcmp, xmlStrdup, xmlStrlen, xmlStrncmp, xmlStrndup, xmlXPathCastStringToNumber,
    xmlXPathCastToString, xmlXPathCmpNodes, xmlXPathEvalExpression, xmlXPathFreeObject,
    xmlXPathNodeSetCreate,
};
use crate::abi::exports_xslt_apply::_xsltCompMatch;
use crate::abi::exports_xslt_avt::{
    xsltEvalAttrValueTemplate, xsltGetQNameURI, xsltGetUTF8Char as xmlGetUTF8Char,
};
use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::*;
use crate::xml::uri::xmlURIEscapeStr;
use crate::xml::xpath::exports::{xmlXPathIsInf, xmlXPathIsNaN};

/// The XSLT namespace URI (NUL-terminated; upstream `XSLT_NAMESPACE`).
const XSLT_NAMESPACE_URI: &[u8] = b"http://www.w3.org/1999/XSL/Transform\0";

/// `xsltOutputType::XSLT_OUTPUT_XML` (upstream xsltInternals.h, enum at 0).
const XSLT_OUTPUT_XML: c_int = 0;
/// `xsltOutputType::XSLT_OUTPUT_HTML`.
const XSLT_OUTPUT_HTML: c_int = 1;
/// `xsltOutputType::XSLT_OUTPUT_TEXT`.
const XSLT_OUTPUT_TEXT: c_int = 2;

/// `xmlCharEncoding::XML_CHAR_ENCODING_UTF8` (upstream encoding.h).
const XML_CHAR_ENCODING_UTF8: c_int = 3;

/// Extension-element namespaces handled by `xsltDocumentElem`.
const XSLT_SAXON_NAMESPACE: &[u8] = b"http://icl.com/saxon\0";
const XSLT_XALAN_NAMESPACE: &[u8] = b"http://xml.apache.org/xalan\0";

/// `XSLT_MAX_SORT` (upstream xsltInternals.h): max xsl:sort instructions.
const XSLT_MAX_SORT: c_int = 15;

/// `XSLT_FUNC_*` enum values used by `xsltDebug` (upstream xsltInternals.h).
const XSLT_FUNC_PARAM: c_int = 19;
const XSLT_FUNC_VARIABLE: c_int = 20;

/// Signature of the sort function used during sorting (upstream
/// `xsltSortFunc` in xsltInternals.h):
///
/// ```c
/// typedef void (*xsltSortFunc)(xsltTransformContextPtr ctxt,
///                              xmlNodePtr *sorts, int nbsorts);
/// ```
///
/// The handler is exposed as `Option<xsltSortFunc>` so that a NULL C
/// function pointer can be represented (the `Option` is null-pointer
/// optimized and ABI-identical to the raw function pointer).
pub type xsltSortFunc = unsafe extern "C" fn(*mut _xsltTransformContext, *mut *mut _xmlNode, c_int);

/// The global sort function (upstream `static xsltSortFunction`,
/// xsltutils.c) — `None` stands for the default handler.
static mut XSLT_SORT_FUNCTION: Option<xsltSortFunc> = None;

// ═══════════════════════════════════════════════════════════════════════════════
// Common helpers
// ═══════════════════════════════════════════════════════════════════════════════

/// Emit a message through the global `xsltGenericError` handler (falling
/// back to stderr), mirroring upstream `xsltGenericError(...)` calls with a
/// literal message.
unsafe fn emit_generic_error(msg: &[u8]) {
    let handler = crate::abi::data_globals::xsltGenericError;
    if let Some(f) = handler {
        f(
            crate::abi::data_globals::xsltGenericErrorContext,
            msg.as_ptr() as *const c_char,
        );
    } else {
        let _ = libc::write(2, msg.as_ptr() as *const c_void, msg.len());
    }
}

/// 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
}

/// Read one UTF-8 char from a NUL-terminated string (upstream
/// `xsltGetUTF8CharZ`, xsltutils.c).  Returns the char value or -1 in case
/// of error and updates `len` with the number of bytes used.
unsafe fn xslt_get_utf8_char_z(utf: *const xmlChar, len: *mut c_int) -> c_int {
    if utf.is_null() || len.is_null() {
        if !len.is_null() {
            *len = 0;
        }
        return -1;
    }
    let mut c: u32 = *utf as u32;
    if c & 0x80 != 0 {
        if (*(utf.add(1)) & 0xc0) != 0x80 {
            *len = 0;
            return -1;
        }
        if (c & 0xe0) == 0xe0 {
            if (*(utf.add(2)) & 0xc0) != 0x80 {
                *len = 0;
                return -1;
            }
            if (c & 0xf0) == 0xf0 {
                if (c & 0xf8) != 0xf0 || (*(utf.add(3)) & 0xc0) != 0x80 {
                    *len = 0;
                    return -1;
                }
                *len = 4;
                /* 4-byte code */
                c = (((*utf & 0x7) as u32) << 18)
                    | (((*utf.add(1) & 0x3f) as u32) << 12)
                    | (((*utf.add(2) & 0x3f) as u32) << 6)
                    | ((*(utf.add(3)) & 0x3f) as u32);
            } else {
                /* 3-byte code */
                *len = 3;
                c = (((*utf & 0xf) as u32) << 12)
                    | (((*utf.add(1) & 0x3f) as u32) << 6)
                    | ((*(utf.add(2)) & 0x3f) as u32);
            }
        } else {
            /* 2-byte code */
            *len = 2;
            c = (((*utf & 0x1f) as u32) << 6) | ((*(utf.add(1)) & 0x3f) as u32);
        }
    } else {
        /* 1-byte code */
        *len = 1;
    }
    c as c_int
}

/// Compare the first UTF-8 char of `utf1` with the string `utf2` (upstream
/// `xsltUTF8Charcmp`, numbers.c): 0 if they start with the same character.
unsafe fn utf8_char_cmp(utf1: *const xmlChar, utf2: *const xmlChar) -> c_int {
    if utf1.is_null() {
        if utf2.is_null() {
            return 0;
        }
        return -1;
    }
    let len = xmlUTF8Strsize(utf1, 1);
    if len < 1 {
        return -1;
    }
    xmlStrncmp(utf1, utf2, len)
}

/// `xsltIsDigitZero` (numbers.c): is `ch` a Unicode digit-zero character?
unsafe fn xslt_is_digit_zero(ch: c_int) -> c_int {
    match ch {
        0x0030 | 0x0660 | 0x06f0 | 0x0966 | 0x09e6 | 0x0a66 | 0x0ae6 | 0x0b66 | 0x0c66 | 0x0ce6
        | 0x0d66 | 0x0e50 | 0x0ed0 | 0x0f20 => 1,
        _ => 0,
    }
}

/// `IS_DIGIT_ONE(x)` = `xsltIsDigitZero(x - 1)` (numbers.c).
unsafe fn xslt_is_digit_one(ch: c_int) -> c_int {
    xslt_is_digit_zero(ch - 1)
}

/// `xsltIsLetterDigit` (numbers.c): `xmlIsBaseCharQ || xmlIsIdeographicQ ||
/// xmlIsDigitQ`.
unsafe fn xslt_is_letter_digit(val: c_int) -> bool {
    if crate::xml::chvalid::xmlIsLetter(val) != 0 {
        return true;
    }
    crate::xml::chvalid::xmlIsDigit(val as c_uint) != 0
}

/// `IS_SPECIAL(self, letter)` (numbers.c): does the character at `letter`
/// equal one of the decimal format's special characters?
unsafe fn is_special(self_: *mut _xsltDecimalFormat, letter: *const xmlChar) -> bool {
    if self_.is_null() {
        return false;
    }
    utf8_char_cmp(letter, (*self_).zeroDigit) == 0
        || utf8_char_cmp(letter, (*self_).digit) == 0
        || utf8_char_cmp(letter, (*self_).decimalPoint) == 0
        || utf8_char_cmp(letter, (*self_).grouping) == 0
        || utf8_char_cmp(letter, (*self_).patternSeparator) == 0
}

/// Test a node against a compiled `xsltCompMatch` (upstream
/// `xsltTestCompMatchList`), delegating to the engine's pattern matcher.
unsafe fn test_comp_match(
    context: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    pat: *mut _xsltCompMatch,
) -> c_int {
    if pat.is_null() {
        return 0;
    }
    crate::xslt::patterns::xsltTestPattern(
        context,
        (*pat).pattern as *mut crate::xslt::patterns::_xsltPattern,
        node,
    )
}

/// `xsltTestCompMatchCount` (numbers.c): does `node` match the `count`
/// pattern?  With a NULL pattern, match any node with the same type and
/// expanded-name as the current node `cur`.
unsafe fn xslt_test_comp_match_count(
    context: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    count_pat: *mut _xsltCompMatch,
    cur: *mut _xmlNode,
) -> c_int {
    if !count_pat.is_null() {
        return test_comp_match(context, node, count_pat);
    }
    if (*node).type_ != (*cur).type_ {
        return 0;
    }
    if (*node).type_ == XML_NAMESPACE_DECL as c_int {
        return 1;
    }
    if xmlStrEqual((*node).name, (*cur).name) == 0 {
        return 0;
    }
    if (*node).ns == (*cur).ns {
        return 1;
    }
    if (*node).ns.is_null() || (*cur).ns.is_null() {
        return 0;
    }
    xmlStrEqual((*(*node).ns).href, (*(*cur).ns).href)
}

// ═══════════════════════════════════════════════════════════════════════════════
// Number formatting internals (numbers.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// `_xsltNumberData` — upstream numbersInternals.h.  Not present in
/// structs.rs, so it is defined here with the exact upstream layout.
///
/// ```c
/// struct _xsltNumberData {
///     const xmlChar *level;
///     const xmlChar *count;
///     const xmlChar *from;
///     const xmlChar *value;
///     const xmlChar *format;
///     int has_format;
///     int digitsPerGroup;
///     int groupingCharacter;
///     int groupingCharacterLen;
///     xmlDocPtr doc;
///     xmlNodePtr node;
///     struct _xsltCompMatch *countPat;
///     struct _xsltCompMatch *fromPat;
/// };
/// ```
#[repr(C)]
pub struct _xsltNumberData {
    pub level: *const xmlChar,
    pub count: *const xmlChar,
    pub from: *const xmlChar,
    pub value: *const xmlChar,
    pub format: *const xmlChar,
    pub has_format: c_int,
    pub digitsPerGroup: c_int,
    pub groupingCharacter: c_int,
    pub groupingCharacterLen: c_int,
    pub doc: *mut _xmlDoc,
    pub node: *mut _xmlNode,
    pub countPat: *mut _xsltCompMatch,
    pub fromPat: *mut _xsltCompMatch,
}

/// Pointer to an `_xsltNumberData` (`xsltNumberDataPtr`).
pub type xsltNumberDataPtr = *mut _xsltNumberData;

/// `MAX_TOKENS` (numbers.c).
const MAX_TOKENS: usize = 1024;

/// `struct _xsltFormatToken` (numbers.c): one number-format token.
#[repr(C)]
#[derive(Clone, Copy)]
struct xsltFormatToken {
    separator: *mut xmlChar,
    token: c_int,
    width: c_int,
}

/// `struct _xsltFormat` (numbers.c): a tokenized number-format picture.
#[repr(C)]
struct xsltFormat {
    start: *mut xmlChar,
    tokens: [xsltFormatToken; MAX_TOKENS],
    nTokens: c_int,
    end: *mut xmlChar,
}

/// `struct _xsltFormatNumberInfo` (numbers.c): parsed format-number info.
#[repr(C)]
struct xsltFormatNumberInfo {
    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,
}

/// Append a (possibly multibyte) character to an output buffer (upstream
/// `xsltCopyCharMultiByte`, numbers.c).
///
/// Returns the number of xmlChar written.
unsafe fn xslt_copy_char_multi_byte(mut out: *mut xmlChar, val: c_int) -> c_int {
    if out.is_null() || val < 0 {
        return 0;
    }
    if val >= 0x80 {
        let mut savedout = out;
        let mut bits: c_int;
        if val < 0x800 {
            *out = ((val >> 6) | 0xC0) as xmlChar;
            out = out.add(1);
            bits = 0;
        } else if val < 0x10000 {
            *out = ((val >> 12) | 0xE0) as xmlChar;
            out = out.add(1);
            bits = 6;
        } else if val < 0x110000 {
            *out = ((val >> 18) | 0xF0) as xmlChar;
            out = out.add(1);
            bits = 12;
        } else {
            return 0;
        }
        while bits >= 0 {
            *out = (((val >> bits) & 0x3F) | 0x80) as u8;
            out = out.add(1);
            bits -= 6;
        }
        return (out as isize - savedout as isize) as c_int;
    }
    *out = val as xmlChar;
    1
}

/// `xsltNumberFormatDecimal` (numbers.c): emit the decimal digits of
/// `number` (building the string from the back), with `digit_zero` as the
/// zero digit, a minimum `width`, and an optional grouping separator.
unsafe fn xslt_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,
) {
    let mut temp_string: [xmlChar; 500] = [0; 500];
    let base = temp_string.as_mut_ptr();
    let mut pointer = base.add(500).sub(1); /* last char */
    *pointer = 0;
    let mut number = number;
    let mut i: c_int = 0;
    while pointer > base {
        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.offset(-(grouping_character_len as isize)) < base {
                i = -1; /* flag error */
                break;
            }
            pointer = pointer.offset(-(grouping_character_len as isize));
            xslt_copy_char_multi_byte(pointer, grouping_character);
        }
        let val = digit_zero + (number).rem_euclid(10.0) as c_int;
        if val < 0x80 {
            /* shortcut if ASCII */
            if pointer <= base {
                /* Check enough room */
                i = -1;
                break;
            }
            pointer = pointer.sub(1);
            *pointer = val as xmlChar;
        } else {
            let mut temp_char: [xmlChar; 6] = [0; 6];
            let len = xslt_copy_char_multi_byte(temp_char.as_mut_ptr(), val);
            if pointer.offset(-(len as isize)) < base {
                i = -1;
                break;
            }
            pointer = pointer.offset(-(len as isize));
            libc::memcpy(
                pointer as *mut libc::c_void,
                temp_char.as_ptr() as *const libc::c_void,
                len as usize,
            );
        }
        number /= 10.0;
        i += 1;
    }
    if i < 0 {
        emit_generic_error(b"xsltNumberFormatDecimal: Internal buffer size exceeded\n\0");
    }
    xmlBufferCat(buffer, pointer);
}

/// `xsltNumberFormatAlpha` (numbers.c): alphabetic numbering (a, b, ..., z,
/// aa, ...).  Numbers below 1 fall back to decimal.
unsafe fn xslt_number_format_alpha(
    data: *mut _xsltNumberData,
    buffer: *mut _xmlBuffer,
    number: f64,
    is_upper: c_int,
) {
    const ALPHA_UPPER: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const ALPHA_LOWER: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
    let alpha_size: f64 = 26.0;

    if number < 1.0 {
        xslt_number_format_decimal(
            buffer,
            number,
            b'0' as c_int,
            1,
            (*data).digitsPerGroup,
            (*data).groupingCharacter,
            (*data).groupingCharacterLen,
        );
        return;
    }
    /* Build buffer from back */
    let mut temp_string: [u8; 65] = [0; 65];
    let mut pointer = temp_string.as_mut_ptr().add(65);
    pointer = pointer.sub(1);
    *pointer = 0;
    let alpha_list: &[u8] = if is_upper != 0 {
        ALPHA_UPPER
    } else {
        ALPHA_LOWER
    };

    let mut number = number;
    let mut i: c_int = 1;
    while i < temp_string.len() as c_int {
        number -= 1.0;
        pointer = pointer.sub(1);
        *pointer = alpha_list[(number).rem_euclid(alpha_size) as usize];
        number /= alpha_size;
        if number < 1.0 {
            break;
        }
        i += 1;
    }
    xmlBufferCCat(buffer, pointer as *const c_char);
}

/// `xsltNumberFormatRoman` (numbers.c): Roman numeral numbering.  Numbers
/// outside [1, 5000] fall back to decimal.
unsafe fn xslt_number_format_roman(
    data: *mut _xsltNumberData,
    buffer: *mut _xmlBuffer,
    number: f64,
    is_upper: c_int,
) {
    if number < 1.0 || number > 5000.0 {
        xslt_number_format_decimal(
            buffer,
            number,
            b'0' as c_int,
            1,
            (*data).digitsPerGroup,
            (*data).groupingCharacter,
            (*data).groupingCharacterLen,
        );
        return;
    }
    let mut number = number;
    let hi = |s: &[u8]| -> Vec<u8> {
        if is_upper != 0 {
            s.to_vec()
        } else {
            s.to_ascii_lowercase()
        }
    };
    let mut ccat_hi = |s: &[u8], n: &mut f64, dec: f64| {
        xmlBufferCCat(buffer, hi(s).as_ptr() as *const c_char);
        *n -= dec;
    };
    while number >= 1000.0 {
        ccat_hi(b"M", &mut number, 1000.0);
    }
    if number >= 900.0 {
        ccat_hi(b"CM", &mut number, 900.0);
    }
    while number >= 500.0 {
        ccat_hi(b"D", &mut number, 500.0);
    }
    if number >= 400.0 {
        ccat_hi(b"CD", &mut number, 400.0);
    }
    while number >= 100.0 {
        ccat_hi(b"C", &mut number, 100.0);
    }
    if number >= 90.0 {
        ccat_hi(b"XC", &mut number, 90.0);
    }
    while number >= 50.0 {
        ccat_hi(b"L", &mut number, 50.0);
    }
    if number >= 40.0 {
        ccat_hi(b"XL", &mut number, 40.0);
    }
    while number >= 10.0 {
        ccat_hi(b"X", &mut number, 10.0);
    }
    if number >= 9.0 {
        ccat_hi(b"IX", &mut number, 9.0);
    }
    while number >= 5.0 {
        ccat_hi(b"V", &mut number, 5.0);
    }
    if number >= 4.0 {
        ccat_hi(b"IV", &mut number, 4.0);
    }
    while number >= 1.0 {
        ccat_hi(b"I", &mut number, 1.0);
    }
}

/// `xsltNumberFormatTokenize` (numbers.c): split a format picture into
/// separators and number tokens.
unsafe fn xslt_number_format_tokenize(format: *const xmlChar, tokens: *mut xsltFormat) {
    let mut ix: usize = 0;
    let mut len: c_int = 0;

    (*tokens).start = ptr::null_mut();
    (*tokens).tokens[0].separator = ptr::null_mut();
    (*tokens).end = ptr::null_mut();

    /*
     * Insert initial non-alphanumeric token.
     * There is always such a token in the list, even if NULL
     */
    let mut val = xslt_get_utf8_char_z(format.add(ix), &mut len);
    while !xslt_is_letter_digit(val) {
        if *format.add(ix) == 0 {
            break;
        }
        ix += len as usize;
        val = xslt_get_utf8_char_z(format.add(ix), &mut len);
    }
    if ix > 0 {
        (*tokens).start = xmlStrndup(format, ix as c_int);
    }

    (*tokens).nTokens = 0;
    while ((*tokens).nTokens as usize) < MAX_TOKENS {
        if *format.add(ix) == 0 {
            break;
        }
        /*
         * separator has already been parsed (except for the first
         * number) in tokens->end, recover it.
         */
        if (*tokens).nTokens > 0 {
            (*tokens).tokens[(*tokens).nTokens as usize].separator = (*tokens).end;
            (*tokens).end = ptr::null_mut();
        }

        val = xslt_get_utf8_char_z(format.add(ix), &mut len);
        if xslt_is_digit_one(val) != 0 || xslt_is_digit_zero(val) != 0 {
            (*tokens).tokens[(*tokens).nTokens as usize].width = 1;
            while xslt_is_digit_zero(val) != 0 {
                (*tokens).tokens[(*tokens).nTokens as usize].width += 1;
                ix += len as usize;
                val = xslt_get_utf8_char_z(format.add(ix), &mut len);
            }
            if xslt_is_digit_one(val) != 0 {
                (*tokens).tokens[(*tokens).nTokens as usize].token = val - 1;
                ix += len as usize;
                val = xslt_get_utf8_char_z(format.add(ix), &mut len);
            } else {
                (*tokens).tokens[(*tokens).nTokens as usize].token = b'0' as c_int;
                (*tokens).tokens[(*tokens).nTokens as usize].width = 1;
            }
        } else if val == b'A' as c_int
            || val == b'a' as c_int
            || val == b'I' as c_int
            || val == b'i' as c_int
        {
            (*tokens).tokens[(*tokens).nTokens as usize].token = val;
            ix += len as usize;
            val = xslt_get_utf8_char_z(format.add(ix), &mut len);
        } else {
            /* XSLT section 7.7: unsupported token → use "1". */
            (*tokens).tokens[(*tokens).nTokens as usize].token = b'0' as c_int;
            (*tokens).tokens[(*tokens).nTokens as usize].width = 1;
        }
        /*
         * Skip over remaining alphanumeric characters (Letter and Digit
         * classes from XML).
         */
        while xslt_is_letter_digit(val) {
            ix += len as usize;
            val = xslt_get_utf8_char_z(format.add(ix), &mut len);
        }

        /*
         * Insert temporary non-alphanumeric final token.
         */
        let j = ix;
        while !xslt_is_letter_digit(val) {
            if val == 0 {
                break;
            }
            ix += len as usize;
            val = xslt_get_utf8_char_z(format.add(ix), &mut len);
        }
        if ix > j {
            (*tokens).end = xmlStrndup(format.add(j), (ix - j) as c_int);
        }
        (*tokens).nTokens += 1;
    }
}

/// The default format token (upstream `default_token`, numbers.c).
unsafe fn default_token() -> xsltFormatToken {
    static DEFAULT_SEPARATOR: [u8; 2] = *b".\0";
    xsltFormatToken {
        separator: DEFAULT_SEPARATOR.as_ptr() as *mut xmlChar,
        token: b'0' as c_int,
        width: 1,
    }
}

/// `xsltNumberFormatInsertNumbers` (numbers.c): format `numbers_max` numbers
/// with the tokenized picture into `buffer`.
unsafe fn xslt_number_format_insert_numbers(
    data: *mut _xsltNumberData,
    numbers: *mut f64,
    numbers_max: c_int,
    tokens: *mut xsltFormat,
    buffer: *mut _xmlBuffer,
) {
    let mut i: c_int = 0;
    let mut number: f64;
    let mut token: xsltFormatToken;

    /*
     * Handle initial non-alphanumeric token
     */
    if !(*tokens).start.is_null() {
        xmlBufferCat(buffer, (*tokens).start);
    }

    while i < numbers_max {
        /* Insert number */
        number = *numbers.offset((numbers_max - 1 - i) as isize);
        /* Round to nearest like XSLT 2.0 */
        number = (number + 0.5).floor();
        if number < 0.0 {
            crate::xslt::errors::xsltTransformError(
                ptr::null_mut(),
                ptr::null_mut(),
                ptr::null_mut(),
                b"xsl-number : negative value\n\0".as_ptr() as *const c_char,
            );
            /* Recover by treating negative values as zero. */
            number = 0.0;
        }
        if (i as usize) < (*tokens).nTokens as usize {
            /*
             * The "n"th format token will be used to format the "n"th
             * number in the list
             */
            token = (*tokens).tokens[i as usize];
        } else if (*tokens).nTokens > 0 {
            /*
             * If there are more numbers than format tokens, then the
             * last format token will be used to format the remaining
             * numbers.
             */
            token = (*tokens).tokens[((*tokens).nTokens - 1) as usize];
        } else {
            /*
             * If there are no format tokens, then a format token of
             * 1 is used to format all numbers.
             */
            token = default_token();
        }

        /* Print separator, except for the first number */
        if i > 0 {
            if !token.separator.is_null() {
                xmlBufferCat(buffer, token.separator);
            } else {
                xmlBufferCCat(buffer, b".\0".as_ptr() as *const c_char);
            }
        }

        let inf = xmlXPathIsInf(number as c_double);
        if inf == -1 {
            xmlBufferCCat(buffer, b"-Infinity\0".as_ptr() as *const c_char);
        } else if inf == 1 {
            xmlBufferCCat(buffer, b"Infinity\0".as_ptr() as *const c_char);
        } else if xmlXPathIsNaN(number as c_double) != 0 {
            xmlBufferCCat(buffer, b"NaN\0".as_ptr() as *const c_char);
        } else {
            match token.token {
                /* 'A' */
                65 => {
                    xslt_number_format_alpha(data, buffer, number, 1);
                }
                /* 'a' */
                97 => {
                    xslt_number_format_alpha(data, buffer, number, 0);
                }
                /* 'I' */
                73 => {
                    xslt_number_format_roman(data, buffer, number, 1);
                }
                /* 'i' */
                105 => {
                    xslt_number_format_roman(data, buffer, number, 0);
                }
                _ => {
                    if xslt_is_digit_zero(token.token) != 0 {
                        xslt_number_format_decimal(
                            buffer,
                            number,
                            token.token,
                            token.width,
                            (*data).digitsPerGroup,
                            (*data).groupingCharacter,
                            (*data).groupingCharacterLen,
                        );
                    }
                }
            }
        }
        i += 1;
    }

    /*
     * Handle final non-alphanumeric token
     */
    if !(*tokens).end.is_null() {
        xmlBufferCat(buffer, (*tokens).end);
    }
}

/// `xsltNumberFormatGetAnyLevel` (numbers.c): count matches for
/// `level="any"`.
unsafe fn xslt_number_format_get_any_level(
    context: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    count_pat: *mut _xsltCompMatch,
    from_pat: *mut _xsltCompMatch,
    array: *mut f64,
) -> c_int {
    let mut cnt: c_int = 0;
    let mut cur = node;

    while !cur.is_null() {
        /* process current node */
        if xslt_test_comp_match_count(context, cur, count_pat, node) != 0 {
            cnt += 1;
        }
        if !from_pat.is_null() && test_comp_match(context, cur, from_pat) != 0 {
            break;
        }

        /* Skip to next preceding or ancestor */
        let typ = (*cur).type_;
        if typ == XML_DOCUMENT_NODE as c_int || typ == XML_HTML_DOCUMENT_NODE as c_int {
            break;
        }

        if typ == XML_NAMESPACE_DECL as c_int {
            /* The XPath module stores the parent of a namespace node in
             * the ns->next field. */
            cur = (*(cur as *mut _xmlNs)).next as *mut _xmlNode;
        } else if typ == XML_ATTRIBUTE_NODE as c_int {
            cur = (*cur).parent;
        } else {
            while !(*cur).prev.is_null() {
                let pt = (*(*cur).prev).type_;
                if pt != XML_DTD_NODE as c_int
                    && pt != XML_XINCLUDE_START as c_int
                    && pt != XML_XINCLUDE_END as c_int
                {
                    break;
                }
                cur = (*cur).prev;
            }
            if !(*cur).prev.is_null() {
                cur = (*cur).prev;
                while !(*cur).last.is_null() {
                    cur = (*cur).last;
                }
            } else {
                cur = (*cur).parent;
            }
        }
    }

    *array.offset(0) = cnt as f64;
    1
}

/// `xsltNumberFormatGetMultipleLevel` (numbers.c): compute the hierarchical
/// number for `level="single"` / `level="multiple"`.
unsafe fn xslt_number_format_get_multiple_level(
    context: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    count_pat: *mut _xsltCompMatch,
    from_pat: *mut _xsltCompMatch,
    array: *mut f64,
    max: c_int,
) -> c_int {
    let mut amount: c_int = 0;
    let mut ancestor = node;

    while !ancestor.is_null() && (*ancestor).type_ != XML_DOCUMENT_NODE as c_int {
        if !from_pat.is_null() && test_comp_match(context, ancestor, from_pat) != 0 {
            break;
        }

        if xslt_test_comp_match_count(context, ancestor, count_pat, node) != 0 {
            /* count(preceding-sibling::*) */
            let mut cnt: c_int = 1;
            let mut preceding = if (*ancestor).type_ != XML_NAMESPACE_DECL as c_int {
                (*ancestor).prev
            } else {
                ptr::null_mut()
            };
            while !preceding.is_null() {
                if xslt_test_comp_match_count(context, preceding, count_pat, node) != 0 {
                    cnt += 1;
                }
                preceding = (*preceding).prev;
            }
            *array.offset(amount as isize) = cnt as f64;
            amount += 1;
            if amount >= max {
                break;
            }
        }

        if !ancestor.is_null() && (*ancestor).type_ == XML_NAMESPACE_DECL as c_int {
            let ns = ancestor as *mut _xmlNs;
            if !(*ns).next.is_null() && (*(*ns).next).type_ != XML_NAMESPACE_DECL as c_int {
                ancestor = (*ns).next as *mut _xmlNode;
            } else {
                ancestor = ptr::null_mut();
            }
        } else {
            ancestor = (*ancestor).parent;
        }
    }

    amount
}

/// `xsltNumberFormatGetValue` (numbers.c): evaluate the `value` attribute
/// wrapped in `number(...)` against `node`.
unsafe fn xslt_number_format_get_value(
    context: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    value: *const xmlChar,
    number: *mut f64,
) -> c_int {
    let mut amount: c_int = 0;
    let pattern = xmlBufferCreate();
    if !pattern.is_null() {
        xmlBufferCCat(pattern, b"number(\0".as_ptr() as *const c_char);
        xmlBufferCat(pattern, value);
        xmlBufferCCat(pattern, b")\0".as_ptr() as *const c_char);
        let old_node = (*context).node;
        (*context).node = node;
        let obj = crate::xslt::transform::eval_xpath(context, xmlBufferContent(pattern));
        if !obj.is_null() {
            *number = (*obj).floatval;
            amount += 1;
            xmlXPathFreeObject(obj);
        }
        xmlBufferFree(pattern);
        (*context).node = old_node;
    }
    amount
}

// ═══════════════════════════════════════════════════════════════════════════════
// Instruction handlers wired to the engine (transform.c / attributes.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Execute an `xsl:attribute` instruction.
///
/// Wired to the engine's `process_attribute`, which evaluates the (possibly
/// AVT) `name` attribute, instantiates the content into a temporary
/// fragment and sets the resulting attribute on the current result element
/// (`ctxt->insert`).  The engine reads the current source node from
/// `ctxt->node`, so it is set from `contextNode` first (and restored, since
/// upstream leaves `ctxt->node` untouched).  `castedComp` is ignored — the
/// candidate does not populate `xsltElemPreComp` structs.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltAttribute(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
///               xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `contextNode` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltAttribute(
    ctxt: *mut _xsltTransformContext,
    contextNode: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || contextNode.is_null() || inst.is_null() {
        return;
    }
    if (*inst).type_ != XML_ELEMENT_NODE as c_int {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = contextNode;
    crate::xslt::transform::process_attribute(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:element` instruction.
///
/// Wired to the engine's `process_element`, which evaluates the `name` and
/// `namespace` attributes (both AVTs), creates the result element at
/// `ctxt->insert` and instantiates the content inside it.  Upstream returns
/// immediately when there is no insertion point; that guard is kept.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltElement(xsltTransformContextPtr ctxt, xmlNodePtr node,
///             xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltElement(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    if (*ctxt).insert.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_element(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:text` instruction.
///
/// Wired to the engine's `process_text`, which copies the text children of
/// the instruction into the result tree.  NOTE: upstream 1.1.45 reads the
/// compiled `disable-output-escaping` flag from `inst->psvi` (set at
/// compile time) and marks non-CDATA text with `xmlStringTextNoenc`; the
/// engine instead reads the `disable-output-escaping` attribute directly
/// from the instruction node and appends ordinary text nodes, so the
/// serialization layer decides the escaping — documented simplification
/// (the engine is the oracle-tested behaviour).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltText(xsltTransformContextPtr ctxt, xmlNodePtr node ATTRIBUTE_UNUSED,
///          xmlNodePtr inst, xsltElemPreCompPtr comp ATTRIBUTE_UNUSED);
/// ```
///
/// # SAFETY
///
/// - `ctxt` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltText(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    comp: *mut c_void,
) {
    let _ = (node, comp);
    if ctxt.is_null() || inst.is_null() {
        return;
    }
    if (*inst).children.is_null() {
        return;
    }
    crate::xslt::transform::process_text(ctxt, inst);
}

/// Execute an `xsl:comment` instruction.
///
/// Wired to the engine's `process_comment`, which computes the string value
/// of the content and appends a comment node.  Upstream additionally
/// rejects comments containing `--` or ending in `-` (reporting an error
/// but still emitting the comment) — the engine skips that validation;
/// documented simplification.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltComment(xsltTransformContextPtr ctxt, xmlNodePtr node,
///             xmlNodePtr inst, xsltElemPreCompPtr comp ATTRIBUTE_UNUSED);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltComment(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    comp: *mut c_void,
) {
    let _ = comp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_comment(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:processing-instruction` instruction.
///
/// Wired to the engine's `process_pi`, which evaluates the `name` attribute
/// (AVT) and appends a PI node with the string value of the content.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltProcessingInstruction(xsltTransformContextPtr ctxt, xmlNodePtr node,
///                           xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltProcessingInstruction(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    if (*ctxt).insert.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_pi(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:copy` instruction.
///
/// Wired to the engine's `process_copy`, which shallow-copies the current
/// node (`ctxt->node`) into the result tree and instantiates the content
/// inside the copy (element case) or at the insertion point otherwise.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltCopy(xsltTransformContextPtr ctxt, xmlNodePtr node,
///          xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltCopy(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_copy(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:copy-of` instruction.
///
/// Wired to the engine's `process_copy_of`, which evaluates the `select`
/// expression and deep-copies node-sets / result tree fragments (or inserts
/// the string value for atomic results).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node,
///            xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltCopyOf(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_copy_of(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:value-of` instruction.
///
/// Wired to the engine's `process_value_of`, which evaluates the `select`
/// expression, casts the result to a string and appends a text node.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltValueOf(xsltTransformContextPtr ctxt, xmlNodePtr node,
///             xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltValueOf(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_value_of(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:number` instruction.
///
/// Wired to the engine's `process_number`, which evaluates the `value`
/// attribute (or computes a position from the current node) and formats the
/// result with the `format` attribute.  NOTE: upstream computes the number
/// from the compiled `level`/`count`/`from` data in `castedComp->numdata`;
/// the engine performs the simplified level computation (preceding-sibling
/// count + 1) and formats with `xsltFormatNumber` — documented
/// simplification.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node,
///            xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltNumber(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = node;
    crate::xslt::transform::process_number(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:choose` instruction.
///
/// Wired to the engine's `process_choose`, which evaluates the `test`
/// attribute of each `xsl:when` child in turn and instantiates the first
/// matching branch (or the `xsl:otherwise` child).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
///            xmlNodePtr inst, xsltElemPreCompPtr comp ATTRIBUTE_UNUSED);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `contextNode` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltChoose(
    ctxt: *mut _xsltTransformContext,
    contextNode: *mut _xmlNode,
    inst: *mut _xmlNode,
    comp: *mut c_void,
) {
    let _ = comp;
    if ctxt.is_null() || contextNode.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = contextNode;
    crate::xslt::transform::process_choose(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:if` instruction.
///
/// Wired to the engine's `process_if`, which evaluates the `test` attribute
/// (XPath 1.0 boolean conversion) and instantiates the content when true.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltIf(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
///        xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `contextNode` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltIf(
    ctxt: *mut _xsltTransformContext,
    contextNode: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || contextNode.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = contextNode;
    crate::xslt::transform::process_if(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Execute an `xsl:for-each` instruction.
///
/// Wired to the engine's `process_for_each`, which evaluates the `select`
/// expression, optionally sorts the resulting node-set with the engine's
/// `xsltSortNodeSet`, and instantiates the content once per node (with the
/// context position/size maintained).  The engine saves and restores the
/// current node itself; the wrapper additionally restores `ctxt->node` to
/// its pre-call value (upstream leaves it unchanged for the caller).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
///             xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `contextNode` and `inst` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltForEach(
    ctxt: *mut _xsltTransformContext,
    contextNode: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || contextNode.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    (*ctxt).node = contextNode;
    crate::xslt::transform::process_for_each(ctxt, inst);
    (*ctxt).node = old_node;
}

/// Process an `xsl:message` instruction.
///
/// Wired to the engine's `process_message`, which writes the string value
/// of the content to stderr and stops the transformation when
/// `terminate="yes"` (the engine flags `XSLT_STATE_ERROR`, which also
/// discards the result — upstream uses `XSLT_STATE_STOPPED`; observable
/// outcome is the same).  NOTE: upstream routes the message through the
/// per-context error handler (`ctxt->error`) with a trailing newline; the
/// engine writes directly to stderr — documented simplification.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltMessage(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst);
/// ```
///
/// # SAFETY
///
/// - `ctxt` and `inst` must be valid pointers; `node` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltMessage(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
) {
    if ctxt.is_null() || inst.is_null() {
        return;
    }
    let old_node = (*ctxt).node;
    if !node.is_null() {
        (*ctxt).node = node;
    }
    crate::xslt::transform::process_message(ctxt, inst);
    (*ctxt).node = old_node;
}

// ═══════════════════════════════════════════════════════════════════════════════
// Numbering (numbers.c / xslt.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Format a number according to an `_xsltNumberData` specification
/// (upstream `xsltNumberFormat`, numbers.c).
///
/// Ported faithfully: the format picture is tokenized, the value is
/// computed either from `data->value` (evaluated as `number(...)`) or from
/// the `level`/`count`/`from` patterns (`single`/`multiple`/`any`), and the
/// resulting text node is appended at `ctxt->insert`.  Pattern matching
/// (`countPat`/`fromPat`) delegates to the engine's `xsltTestPattern`.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltNumberFormat(xsltTransformContextPtr ctxt, xsltNumberDataPtr data,
///                  xmlNodePtr node);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `data` and `node` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltNumberFormat(
    ctxt: *mut _xsltTransformContext,
    data: xsltNumberDataPtr,
    node: *mut _xmlNode,
) {
    if ctxt.is_null() || data.is_null() {
        return;
    }
    let mut tokens: xsltFormat = core::mem::zeroed();

    if !(*data).format.is_null() {
        xslt_number_format_tokenize((*data).format, &mut tokens);
    } else {
        /* The format needs to be recomputed each time */
        if (*data).has_format == 0 {
            return;
        }
        let format = xsltEvalAttrValueTemplate(
            ctxt,
            (*data).node,
            b"format\0".as_ptr() as *const xmlChar,
            XSLT_NAMESPACE_URI.as_ptr() as *const xmlChar,
        );
        if format.is_null() {
            return;
        }
        xslt_number_format_tokenize(format, &mut tokens);
        xmlFreeImpl(format as *mut c_void);
    }

    let output = xmlBufferCreate();
    if output.is_null() {
        // Nothing was emitted; still clean up the tokenized picture.
        cleanup_tokens(&mut tokens);
        return;
    }

    /*
     * Evaluate the XPath expression to find the value(s)
     */
    if !(*data).value.is_null() {
        let mut number: f64 = 0.0;
        let amount = xslt_number_format_get_value(ctxt, node, (*data).value, &mut number);
        if amount == 1 {
            xslt_number_format_insert_numbers(data, &mut number, 1, &mut tokens, output);
        }
    } else if !(*data).level.is_null() {
        if xmlStrEqual((*data).level, b"single\0".as_ptr() as *const xmlChar) != 0 {
            let mut number: f64 = 0.0;
            let amount = xslt_number_format_get_multiple_level(
                ctxt,
                node,
                (*data).countPat,
                (*data).fromPat,
                &mut number,
                1,
            );
            if amount == 1 {
                xslt_number_format_insert_numbers(data, &mut number, 1, &mut tokens, output);
            }
        } else if xmlStrEqual((*data).level, b"multiple\0".as_ptr() as *const xmlChar) != 0 {
            let mut numarray: [f64; 1024] = [0.0; 1024];
            let max = (numarray.len()) as c_int;
            let amount = xslt_number_format_get_multiple_level(
                ctxt,
                node,
                (*data).countPat,
                (*data).fromPat,
                numarray.as_mut_ptr(),
                max,
            );
            if amount > 0 {
                xslt_number_format_insert_numbers(
                    data,
                    numarray.as_mut_ptr(),
                    amount,
                    &mut tokens,
                    output,
                );
            }
        } else if xmlStrEqual((*data).level, b"any\0".as_ptr() as *const xmlChar) != 0 {
            let mut number: f64 = 0.0;
            let amount = xslt_number_format_get_any_level(
                ctxt,
                node,
                (*data).countPat,
                (*data).fromPat,
                &mut number,
            );
            if amount > 0 {
                xslt_number_format_insert_numbers(data, &mut number, 1, &mut tokens, output);
            }
        }

        /*
         * Unlike `match` patterns, `count` and `from` patterns can contain
         * variable references, so the pattern match cache is cleared if the
         * "direct" matching algorithm was used (no-op in the candidate).
         */
        if !(*data).countPat.is_null() {
            crate::abi::exports_xslt_apply::xsltCompMatchClearCache(ctxt, (*data).countPat);
        }
        if !(*data).fromPat.is_null() {
            crate::abi::exports_xslt_apply::xsltCompMatchClearCache(ctxt, (*data).fromPat);
        }
    }

    /* Insert number as text node */
    crate::xslt::transform::append_text_node(ctxt, xmlBufferContent(output));

    xmlBufferFree(output);
    cleanup_tokens(&mut tokens);
}

/// Free the allocated parts of a tokenized number-format picture.
unsafe fn cleanup_tokens(tokens: *mut xsltFormat) {
    if !(*tokens).start.is_null() {
        xmlFreeImpl((*tokens).start as *mut c_void);
    }
    if !(*tokens).end.is_null() {
        xmlFreeImpl((*tokens).end as *mut c_void);
    }
    let mut i: c_int = 0;
    while i < (*tokens).nTokens {
        if !(*tokens).tokens[i as usize].separator.is_null() {
            xmlFreeImpl((*tokens).tokens[i as usize].separator as *mut c_void);
        }
        i += 1;
    }
}

/// `xsltFormatNumberPreSuffix` (numbers.c): walk a prefix/suffix, counting
/// bytes and detecting a percent/permille multiplier.
///
/// Returns the byte length of the prefix/suffix, or -1 on error.
unsafe fn xslt_format_number_pre_suffix(
    self_: *mut _xsltDecimalFormat,
    format: *mut *mut xmlChar,
    info: *mut xsltFormatNumberInfo,
) -> c_int {
    let mut count: c_int = 0;
    let mut len: c_int;

    loop {
        if **format == 0 {
            return count;
        }
        /* if next character 'escaped' just count it */
        if **format == b'\'' as xmlChar {
            *format = (*format).add(1);
            if **format == 0 {
                return -1;
            }
        } else if is_special(self_, *format) {
            return count;
        } else {
            /*
             * for +ve prefix/suffix, allow only a single occurrence of
             * either percent or permille
             */
            if utf8_char_cmp(*format, (*self_).percent) == 0 {
                if (*info).is_multiplier_set != 0 {
                    return -1;
                }
                (*info).multiplier = 100;
                (*info).is_multiplier_set = 1;
            } else if utf8_char_cmp(*format, (*self_).permille) == 0 {
                if (*info).is_multiplier_set != 0 {
                    return -1;
                }
                (*info).multiplier = 1000;
                (*info).is_multiplier_set = 1;
            }
        }

        len = xmlUTF8Strsize(*format, 1);
        if len < 1 {
            return -1;
        }
        count += len;
        *format = (*format).offset(len as isize);
    }
}

/// Implement the JDK 1.1 `DecimalFormat` algorithm used by `format-number()`
/// (upstream `xsltFormatNumberConversion`, numbers.c).
///
/// Ported faithfully from numbers.c 1.1.45: the positive subpattern is
/// parsed (prefix, integer `#`/`0` run, fraction `0`/`#` run, suffix), the
/// negative subpattern (after `patternSeparator`) is applied for negative
/// numbers, the multiplier from `%`/`permille` is applied, the number is
/// rounded to the fraction width and the result is assembled with the
/// decimal format's characters (grouping, decimal point, minus sign,
/// infinity, NaN).
///
/// When `self` is NULL a default ASCII decimal format is substituted (the
/// same character set upstream's default `xsltDecimalFormat` carries), so
/// the NULL case behaves like upstream-with-default instead of crashing.
/// `*result` is allocated with `xmlStrdup` (caller frees with `xmlFree`).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathError
/// xsltFormatNumberConversion(xsltDecimalFormatPtr self, xmlChar *format,
///                            double number, xmlChar **result);
/// ```
///
/// # SAFETY
///
/// - `format` and `result` must be valid pointers; `self` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltFormatNumberConversion(
    self_: *mut _xsltDecimalFormat,
    format: *mut xmlChar,
    number: f64,
    result: *mut *mut xmlChar,
) -> c_int {
    let status: c_int = XPATH_EXPRESSION_OK as c_int;
    let mut default_fmt: _xsltDecimalFormat;

    if result.is_null() {
        return XPATH_MEMORY_ERROR as c_int;
    }

    if xmlStrlen(format) <= 0 {
        crate::xslt::errors::xsltTransformError(
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            b"xsltFormatNumberConversion : Invalid format (0-length)\n\0".as_ptr() as *const c_char,
        );
    }
    *result = ptr::null_mut();

    if xmlXPathIsNaN(number as c_double) != 0 {
        if self_.is_null() || (*self_).noNumber.is_null() {
            *result = xmlStrdup(b"NaN\0".as_ptr() as *const xmlChar);
        } else {
            *result = xmlStrdup((*self_).noNumber);
        }
        return status;
    }

    // Substitute a default ASCII decimal format for a NULL @self (see the
    // doc comment; upstream would dereference NULL in the general path).
    let selfp: *mut _xsltDecimalFormat = if self_.is_null() {
        default_fmt = _xsltDecimalFormat {
            next: ptr::null_mut(),
            name: ptr::null_mut(),
            digit: b"#\0".as_ptr() as *mut xmlChar,
            patternSeparator: b";\0".as_ptr() as *mut xmlChar,
            minusSign: b"-\0".as_ptr() as *mut xmlChar,
            infinity: b"Infinity\0".as_ptr() as *mut xmlChar,
            noNumber: b"NaN\0".as_ptr() as *mut xmlChar,
            decimalPoint: b".\0".as_ptr() as *mut xmlChar,
            grouping: b",\0".as_ptr() as *mut xmlChar,
            percent: b"%\0".as_ptr() as *mut xmlChar,
            permille: b"\xE2\x80\xB0\0".as_ptr() as *mut xmlChar,
            zeroDigit: b"0\0".as_ptr() as *mut xmlChar,
            nsUri: ptr::null(),
        };
        &mut default_fmt
    } else {
        self_
    };

    let mut format_info: xsltFormatNumberInfo = core::mem::zeroed();
    format_info.integer_hash = 0;
    format_info.integer_digits = 0;
    format_info.frac_digits = 0;
    format_info.frac_hash = 0;
    format_info.group = -1;
    format_info.multiplier = 1;
    format_info.add_decimal = 0;
    format_info.is_multiplier_set = 0;
    format_info.is_negative_pattern = 0;

    let mut the_format: *mut xmlChar = format;

    /*
     * First we process the +ve pattern to get percent / permille,
     * as well as main format
     */
    let mut prefix: *mut xmlChar = the_format;
    let mut prefix_length = xslt_format_number_pre_suffix(selfp, &mut the_format, &mut format_info);
    let mut suffix: *mut xmlChar = ptr::null_mut();
    let mut suffix_length: c_int = 0;
    let mut nprefix: *mut xmlChar = ptr::null_mut();
    let mut nsuffix: *mut xmlChar = ptr::null_mut();
    let mut nprefix_length: c_int = 0;
    let mut nsuffix_length: c_int = 0;
    let mut len: c_int = 0;
    let mut found_error: c_int = 0;
    if prefix_length < 0 {
        found_error = 1;
        // fall through to OUTPUT_NUMBER
    }

    /*
     * Here we process the "number" part of the format.  It gets a little
     * messy because of the percent/per-mille - if that appears at the end,
     * it may be part of the suffix instead of part of the number, so the
     * variable delayed_multiplier is used to handle it.
     */
    let mut delayed_multiplier: c_int = 0;
    let self_grouping_len = xmlStrlen((*selfp).grouping);
    if found_error == 0 {
        while *the_format != 0
            && utf8_char_cmp(the_format, (*selfp).decimalPoint) != 0
            && utf8_char_cmp(the_format, (*selfp).patternSeparator) != 0
        {
            if delayed_multiplier != 0 {
                format_info.multiplier = delayed_multiplier;
                format_info.is_multiplier_set = 1;
                delayed_multiplier = 0;
            }
            if utf8_char_cmp(the_format, (*selfp).digit) == 0 {
                if format_info.integer_digits > 0 {
                    found_error = 1;
                    break;
                }
                format_info.integer_hash += 1;
                if format_info.group >= 0 {
                    format_info.group += 1;
                }
            } else if utf8_char_cmp(the_format, (*selfp).zeroDigit) == 0 {
                format_info.integer_digits += 1;
                if format_info.group >= 0 {
                    format_info.group += 1;
                }
            } else if self_grouping_len > 0
                && xmlStrncmp(the_format, (*selfp).grouping, self_grouping_len) == 0
            {
                /* Reset group count */
                format_info.group = 0;
                the_format = the_format.offset(self_grouping_len as isize);
                continue;
            } else if utf8_char_cmp(the_format, (*selfp).percent) == 0 {
                if format_info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 100;
            } else if utf8_char_cmp(the_format, (*selfp).permille) == 0 {
                if format_info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 1000;
            } else {
                break;
            }

            len = xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
                break;
            }
            the_format = the_format.offset(len as isize);
        }
    }

    /* We have finished the integer part, now work on fraction */
    if found_error == 0 {
        if *the_format != 0 && utf8_char_cmp(the_format, (*selfp).decimalPoint) == 0 {
            format_info.add_decimal = 1;
            len = xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
            } else {
                the_format = the_format.offset(len as isize); /* Skip over the decimal */
            }
        }
    }

    if found_error == 0 {
        while *the_format != 0 {
            if utf8_char_cmp(the_format, (*selfp).zeroDigit) == 0 {
                if format_info.frac_hash != 0 {
                    found_error = 1;
                    break;
                }
                format_info.frac_digits += 1;
            } else if utf8_char_cmp(the_format, (*selfp).digit) == 0 {
                format_info.frac_hash += 1;
            } else if utf8_char_cmp(the_format, (*selfp).percent) == 0 {
                if format_info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 100;
                len = xmlUTF8Strsize(the_format, 1);
                if len < 1 {
                    found_error = 1;
                    break;
                }
                the_format = the_format.offset(len as isize);
                continue;
            } else if utf8_char_cmp(the_format, (*selfp).permille) == 0 {
                if format_info.is_multiplier_set != 0 {
                    found_error = 1;
                    break;
                }
                delayed_multiplier = 1000;
                len = xmlUTF8Strsize(the_format, 1);
                if len < 1 {
                    found_error = 1;
                    break;
                }
                the_format = the_format.offset(len as isize);
                continue;
            } else if utf8_char_cmp(the_format, (*selfp).grouping) != 0 {
                break;
            }
            len = xmlUTF8Strsize(the_format, 1);
            if len < 1 {
                found_error = 1;
                break;
            }
            the_format = the_format.offset(len as isize);
            if delayed_multiplier != 0 {
                format_info.multiplier = delayed_multiplier;
                delayed_multiplier = 0;
                format_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 {
        the_format = the_format.offset(-(len as isize));
        delayed_multiplier = 0;
    }

    let mut default_sign: c_int = 0;
    if found_error == 0 {
        suffix = the_format;
        suffix_length = xslt_format_number_pre_suffix(selfp, &mut the_format, &mut format_info);
        if suffix_length < 0
            || (*the_format != 0 && utf8_char_cmp(the_format, (*selfp).patternSeparator) != 0)
        {
            found_error = 1;
        }
    }

    /*
     * We have processed the +ve prefix, number part and +ve suffix.
     * If the number is -ve, we must substitute the -ve prefix / suffix.
     */
    if found_error == 0 && number < 0.0 {
        /*
         * Note that j is the number of UTF8 chars before the separator,
         * not the number of bytes! (bug 151975)
         */
        let j = xmlUTF8Strloc(format, (*selfp).patternSeparator);
        if j < 0 {
            /* No -ve pattern present, so use default signing */
            default_sign = 1;
        } else {
            /* Skip over pattern separator (accounting for UTF8) */
            the_format = xmlUTF8Strpos(format, j + 1) as *mut xmlChar;
            /*
             * Flag changes interpretation of percent/permille
             * in the -ve pattern.
             */
            format_info.is_negative_pattern = 1;
            format_info.is_multiplier_set = 0;

            /* First do the -ve prefix */
            nprefix = the_format;
            nprefix_length =
                xslt_format_number_pre_suffix(selfp, &mut the_format, &mut format_info);
            if nprefix_length < 0 {
                found_error = 1;
            }

            if found_error == 0 {
                while *the_format != 0 {
                    if utf8_char_cmp(the_format, (*selfp).percent) == 0
                        || utf8_char_cmp(the_format, (*selfp).permille) == 0
                    {
                        if format_info.is_multiplier_set != 0 {
                            found_error = 1;
                            break;
                        }
                        format_info.is_multiplier_set = 1;
                        delayed_multiplier = 1;
                    } else if is_special(selfp, the_format) {
                        delayed_multiplier = 0;
                    } else {
                        break;
                    }
                    len = xmlUTF8Strsize(the_format, 1);
                    if len < 1 {
                        found_error = 1;
                        break;
                    }
                    the_format = the_format.offset(len as isize);
                }
                if delayed_multiplier != 0 {
                    format_info.is_multiplier_set = 0;
                    the_format = the_format.offset(-(len as isize));
                }
            }

            /* Finally do the -ve suffix */
            if found_error == 0 {
                if *the_format != 0 {
                    nsuffix = the_format;
                    nsuffix_length =
                        xslt_format_number_pre_suffix(selfp, &mut the_format, &mut format_info);
                    if nsuffix_length < 0 {
                        found_error = 1;
                    }
                } else {
                    nsuffix_length = 0;
                }
                if found_error == 0 && *the_format != 0 {
                    found_error = 1;
                }
            }

            /*
             * Here's another Java peculiarity:
             * if -ve prefix/suffix == +ve ones, discard & use default
             */
            if found_error == 0
                && (nprefix_length != prefix_length
                    || nsuffix_length != suffix_length
                    || (nprefix_length > 0 && xmlStrncmp(nprefix, prefix, prefix_length) != 0)
                    || (nsuffix_length > 0 && xmlStrncmp(nsuffix, suffix, suffix_length) != 0))
            {
                prefix = nprefix;
                prefix_length = nprefix_length;
                suffix = nsuffix;
                suffix_length = nsuffix_length;
            }
        }
    }

    // OUTPUT_NUMBER:
    if found_error != 0 {
        crate::xslt::errors::xsltTransformError(
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            b"xsltFormatNumberConversion : error in format string, using default\n\0".as_ptr()
                as *const c_char,
        );
        default_sign = if number < 0.0 { 1 } else { 0 };
        prefix_length = 0;
        suffix_length = 0;
        format_info.integer_hash = 0;
        format_info.integer_digits = 1;
        format_info.frac_digits = 1;
        format_info.frac_hash = 4;
        format_info.group = -1;
        format_info.multiplier = 1;
        format_info.add_decimal = 1;
    }

    /* Apply multiplier */
    let mut number = number * format_info.multiplier as f64;
    let inf = xmlXPathIsInf(number as c_double);
    if inf == -1 || inf == 1 {
        if inf == -1 {
            if (*selfp).minusSign.is_null() {
                *result = xmlStrdup(b"-\0".as_ptr() as *const xmlChar);
            } else {
                *result = xmlStrdup((*selfp).minusSign);
            }
        }
        if (*selfp).infinity.is_null() {
            *result = xmlStrcat(*result, b"Infinity\0".as_ptr() as *const xmlChar);
        } else {
            *result = xmlStrcat(*result, (*selfp).infinity);
        }
        return status;
    }

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

    /* Ready to output our number.  First see if "default sign" is required */
    if default_sign != 0 {
        if (*selfp).minusSign.is_null() {
            xmlBufferAdd(buffer, b"-\0".as_ptr() as *const xmlChar, 1);
        } else {
            xmlBufferAdd(
                buffer,
                (*selfp).minusSign,
                xmlUTF8Strsize((*selfp).minusSign, 1),
            );
        }
    }

    /* Put the prefix into the buffer */
    let mut j: c_int = 0;
    while j < prefix_length {
        if *prefix == b'\'' as xmlChar {
            prefix = prefix.add(1);
        }
        len = xmlUTF8Strsize(prefix, 1);
        xmlBufferAdd(buffer, prefix, len);
        prefix = prefix.offset(len as isize);
        j += len;
    }

    /* Round to n digits */
    let mut number = number.abs();
    let mut exp10: c_int = format_info.frac_digits + format_info.frac_hash;
    /* DBL_MAX_10_EXP should be 308 on IEEE platforms. */
    if exp10 > 308 {
        if format_info.frac_digits > 308 {
            format_info.frac_digits = 308;
            format_info.frac_hash = 0;
        } else {
            format_info.frac_hash = 308 - format_info.frac_digits;
        }
        exp10 = 308;
    }
    let scale = 10.0_f64.powf(exp10 as f64);
    number += 0.5 / scale;
    number -= (number).rem_euclid(1.0 / scale);

    /* Next do the integer part of the number */
    if !(*selfp).grouping.is_null() && *(*selfp).grouping != 0 {
        let mut glen: c_int = xmlStrlen((*selfp).grouping);
        let gchar = xmlGetUTF8Char((*selfp).grouping as *const u8, &mut glen);
        xslt_number_format_decimal(
            buffer,
            (number).floor(),
            *(*selfp).zeroDigit as c_int,
            format_info.integer_digits,
            format_info.group,
            gchar,
            glen,
        );
    } else {
        xslt_number_format_decimal(
            buffer,
            (number).floor(),
            *(*selfp).zeroDigit as c_int,
            format_info.integer_digits,
            format_info.group,
            b',' as c_int,
            1,
        );
    }

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

    /* Add leading zero, if required */
    if (number).floor() == 0.0 && format_info.integer_digits + format_info.frac_digits == 0 {
        xmlBufferAdd(
            buffer,
            (*selfp).zeroDigit,
            xmlUTF8Strsize((*selfp).zeroDigit, 1),
        );
    }

    /* Next the fractional part, if required */
    if format_info.frac_digits + format_info.frac_hash == 0 {
        if format_info.add_decimal != 0 {
            xmlBufferAdd(
                buffer,
                (*selfp).decimalPoint,
                xmlUTF8Strsize((*selfp).decimalPoint, 1),
            );
        }
    } else {
        let mut number = number - (number).floor();
        if number != 0.0 || format_info.frac_digits != 0 {
            xmlBufferAdd(
                buffer,
                (*selfp).decimalPoint,
                xmlUTF8Strsize((*selfp).decimalPoint, 1),
            );
            number = (scale * number + 0.5).floor();
            let mut j = format_info.frac_hash;
            while j > 0 {
                if (number).rem_euclid(10.0) >= 1.0 {
                    break;
                }
                number /= 10.0;
                j -= 1;
            }
            xslt_number_format_decimal(
                buffer,
                (number).floor(),
                *(*selfp).zeroDigit as c_int,
                format_info.frac_digits + j,
                0,
                0,
                0,
            );
        }
    }
    /* Put the suffix into the buffer */
    let mut j = 0;
    while j < suffix_length {
        if *suffix == b'\'' as xmlChar {
            suffix = suffix.add(1);
        }
        len = xmlUTF8Strsize(suffix, 1);
        xmlBufferAdd(buffer, suffix, len);
        suffix = suffix.offset(len as isize);
        j += len;
    }

    *result = xmlStrdup(xmlBufferContent(buffer));
    xmlBufferFree(buffer);
    status
}

/// Find a named decimal format in a stylesheet (upstream
/// `xsltDecimalFormatGetByName`, xslt.c).
///
/// With a NULL `name` the default format (the head of the chain) is
/// returned.  Otherwise the `decimalFormat` chain of the stylesheet and its
/// imports is walked; the first entry with a matching name and a NULL
/// namespace URI wins.  Returns NULL when no match exists.  (The candidate's
/// compiler only creates decimal-format entries for explicit
/// `xsl:decimal-format` elements, so a stylesheet without any may have a
/// NULL chain — the walk handles that by returning NULL, where upstream
/// assumes a default entry exists.)
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xsltDecimalFormatPtr
/// xsltDecimalFormatGetByName(xsltStylesheetPtr style, xmlChar *name);
/// ```
///
/// # SAFETY
///
/// - `style` must be a valid stylesheet; `name` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltDecimalFormatGetByName(
    style: *mut _xsltStylesheet,
    name: *mut xmlChar,
) -> *mut _xsltDecimalFormat {
    if style.is_null() {
        return ptr::null_mut();
    }
    if name.is_null() {
        return (*style).decimalFormat;
    }
    let mut cur_style = style;
    while !cur_style.is_null() {
        if !(*cur_style).decimalFormat.is_null() {
            let mut result = (*(*cur_style).decimalFormat).next;
            while !result.is_null() {
                if (*result).nsUri.is_null()
                    && xmlStrEqual(name as *const xmlChar, (*result).name) != 0
                {
                    return result;
                }
                result = (*result).next;
            }
        }
        cur_style = crate::abi::exports_xslt_apply::xsltNextImport(cur_style);
    }
    ptr::null_mut()
}

/// Find a decimal format by expanded-name (upstream
/// `xsltDecimalFormatGetByQName`, xslt.c).
///
/// Same walk as [`xsltDecimalFormatGetByName`], matching on namespace URI
/// and local name.  With a NULL `name` the default format is returned.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xsltDecimalFormatPtr
/// xsltDecimalFormatGetByQName(xsltStylesheetPtr style, const xmlChar *nsUri,
///                             const xmlChar *name);
/// ```
///
/// # SAFETY
///
/// - `style` must be a valid stylesheet; `nsUri` and `name` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltDecimalFormatGetByQName(
    style: *mut _xsltStylesheet,
    nsUri: *const xmlChar,
    name: *const xmlChar,
) -> *mut _xsltDecimalFormat {
    if style.is_null() {
        return ptr::null_mut();
    }
    if name.is_null() {
        return (*style).decimalFormat;
    }
    let mut cur_style = style;
    while !cur_style.is_null() {
        if !(*cur_style).decimalFormat.is_null() {
            let mut result = (*(*cur_style).decimalFormat).next;
            while !result.is_null() {
                if xmlStrEqual(nsUri, (*result).nsUri) != 0
                    && xmlStrEqual(name, (*result).name) != 0
                {
                    return result;
                }
                result = (*result).next;
            }
        }
        cur_style = crate::abi::exports_xslt_apply::xsltNextImport(cur_style);
    }
    ptr::null_mut()
}

// ═══════════════════════════════════════════════════════════════════════════════
// Sorting (transform.c / xsltutils.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Process an `xsl:sort` node.
///
/// Upstream 1.1.45 (transform.c) never dispatches `xsl:sort` through the
/// instruction handlers — the sort nodes are collected and handed to
/// [`xsltDoSortFunction`] by `xsl:apply-templates`/`xsl:for-each` — so
/// `xsltSort` is an error stub reporting "improper use".  Ported verbatim.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltSort(xsltTransformContextPtr ctxt, xmlNodePtr node ATTRIBUTE_UNUSED,
///          xmlNodePtr inst, xsltElemPreCompPtr comp);
/// ```
///
/// # SAFETY
///
/// - `ctxt` and `inst` must be valid pointers; `comp` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltSort(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    comp: *mut c_void,
) {
    let _ = node;
    if ctxt.is_null() || inst.is_null() {
        return;
    }
    if comp.is_null() {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            ptr::null_mut(),
            inst,
            b"xsl:sort : compilation failed\n\0".as_ptr() as *const c_char,
        );
        return;
    }
    crate::xslt::errors::xsltTransformError(
        ctxt,
        ptr::null_mut(),
        inst,
        b"xsl:sort : improper use this should not be reached\n\0".as_ptr() as *const c_char,
    );
}

/// The default sort function: reorder `ctxt->nodeList` in place according
/// to the sort keys of the `sorts` array of `xsl:sort` instruction nodes
/// (upstream `xsltDefaultSortFunction`, xsltutils.c).
///
/// The candidate compiles each `xsl:sort` node on the fly with the engine's
/// `xsltCompileSort` and delegates the actual reordering to the engine's
/// `xsltSortNodeSet` (which implements the same comparison semantics as the
/// upstream shell sort: text/number data-type, ascending/descending order,
/// multi-key tie-breaking).  Simplifications: `data-type`/`order` are read
/// as static attribute values (upstream additionally evaluates them as AVTs
/// when the compiled record marks them dynamic), and locale-aware key
/// generation (`lang`/`case-order`) is not applied.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltDefaultSortFunction(xsltTransformContextPtr ctxt, xmlNodePtr *sorts,
///                         int nbsorts);
/// ```
///
/// # SAFETY
///
/// - `ctxt` and `sorts` must be valid pointers; `sorts` must hold
///   `nbsorts` entries (0 < nbsorts < XSLT_MAX_SORT).
#[no_mangle]
pub unsafe extern "C" fn xsltDefaultSortFunction(
    ctxt: *mut _xsltTransformContext,
    sorts: *mut *mut _xmlNode,
    nbsorts: c_int,
) {
    if ctxt.is_null() || sorts.is_null() || nbsorts <= 0 || nbsorts >= XSLT_MAX_SORT {
        return;
    }
    if (*sorts).is_null() {
        return;
    }
    let list = (*ctxt).nodeList;
    if list.is_null() || (*list).nodeNr <= 1 {
        return; /* nothing to do */
    }

    // Compile the sort key chain (primary = sorts[0]).
    let style = (*ctxt).style;
    let mut chain_head: *mut _xsltSort = ptr::null_mut();
    let mut chain_tail: *mut _xsltSort = ptr::null_mut();
    let mut j: c_int = 0;
    while j < nbsorts {
        let inst = *sorts.offset(j as isize);
        if !inst.is_null() {
            let s = crate::xslt::sorting::xsltCompileSort(style, inst);
            if !s.is_null() {
                if chain_tail.is_null() {
                    chain_head = s;
                    chain_tail = s;
                } else {
                    (*chain_tail).next = s;
                    chain_tail = s;
                }
            }
        }
        j += 1;
    }
    if chain_head.is_null() {
        return; /* sorts[0] failed to compile (upstream: psvi == NULL) */
    }

    crate::xslt::sorting::xsltSortNodeSet(ctxt, list, chain_head);
    crate::xslt::sorting::xsltFreeSortList(chain_head);
}

/// Dispatcher for sorting (upstream `xsltDoSortFunction`, xsltutils.c):
/// call the context-specific sort function if set, otherwise the global
/// sort function (defaulting to [`xsltDefaultSortFunction`]).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltDoSortFunction(xsltTransformContextPtr ctxt, xmlNodePtr *sorts,
///                    int nbsorts);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer; `sorts` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltDoSortFunction(
    ctxt: *mut _xsltTransformContext,
    sorts: *mut *mut _xmlNode,
    nbsorts: c_int,
) {
    // (Upstream dereferences ctxt unconditionally; the null guard is a
    // defensive divergence.)
    if ctxt.is_null() {
        return;
    }
    let sf = (*ctxt).sortfunc;
    if !sf.is_null() {
        let f: xsltSortFunc = core::mem::transmute(sf);
        f(ctxt, sorts, nbsorts);
        return;
    }
    let global = unsafe { XSLT_SORT_FUNCTION };
    if let Some(f) = global {
        f(ctxt, sorts, nbsorts);
    } else {
        xsltDefaultSortFunction(ctxt, sorts, nbsorts);
    }
}

/// Reorder a node-set into document order (upstream
/// `xsltDocumentSortFunction`, xsltutils.c).
///
/// Upstream bubble-sorts by `xmlXPathCmpNodes`, swapping whenever the first
/// node follows the second.  NOTE: the candidate's `xmlXPathCmpNodes` uses
/// the opposite sign convention of libxml2's (it returns a negative value
/// when the first node *precedes* the second), so the swap test is
/// `tst == 1` here to produce the same ascending document order as
/// upstream.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltDocumentSortFunction(xmlNodeSetPtr list);
/// ```
///
/// # SAFETY
///
/// - `list` must be a valid node-set or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltDocumentSortFunction(list: *mut _xmlNodeSet) {
    if list.is_null() {
        return;
    }
    let len = (*list).nodeNr;
    if len <= 1 {
        return;
    }
    let tab = (*list).nodeTab;
    if tab.is_null() {
        return;
    }
    /* TODO: sort is really not optimized, does it need to be? */
    let mut i: c_int = 0;
    while i < len - 1 {
        let mut j = i + 1;
        while j < len {
            let tst = xmlXPathCmpNodes(*tab.offset(i as isize), *tab.offset(j as isize));
            // Candidate convention: positive ⇒ nodeTab[i] follows
            // nodeTab[j] in document order ⇒ swap (ascending order).
            if tst == 1 {
                let node = *tab.offset(i as isize);
                *tab.offset(i as isize) = *tab.offset(j as isize);
                *tab.offset(j as isize) = node;
            }
            j += 1;
        }
        i += 1;
    }
}

/// Compute the sort-key results for the current node-set (upstream
/// `xsltComputeSortResult`, xsltutils.c).
///
/// Evaluates the sort key of the `sort` instruction for every node of
/// `ctxt->nodeList` and returns an array of `len` XPath objects
/// (`XPATH_STRING` for text sorts, `XPATH_NUMBER` for numeric sorts), each
/// carrying its original position in `index`.  The array is allocated with
/// `xmlMalloc`; the caller frees each object with `xmlXPathFreeObject` and
/// the array with `xmlFree`.  Returns NULL on failure (including when the
/// node-set has at most one node, or the sort key has no `select`).
///
/// The candidate compiles the sort key on the fly (`xsltCompileSort`) and
/// evaluates it with the engine's `xsltEvalSortKey` (which evaluates the
/// `select` expression per node with the correct context position/size).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlXPathObjectPtr *
/// xsltComputeSortResult(xsltTransformContextPtr ctxt, xmlNodePtr sort);
/// ```
///
/// # SAFETY
///
/// - `ctxt` and `sort` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn xsltComputeSortResult(
    ctxt: *mut _xsltTransformContext,
    sort: *mut _xmlNode,
) -> *mut *mut _xmlXPathObject {
    if ctxt.is_null() || sort.is_null() {
        return ptr::null_mut();
    }
    let style = (*ctxt).style;
    let compiled = crate::xslt::sorting::xsltCompileSort(style, sort);
    if compiled.is_null() {
        emit_generic_error(b"xsl:sort : compilation failed\n\0");
        return ptr::null_mut();
    }
    if (*compiled).select.is_null() {
        crate::xslt::sorting::xsltFreeSortList(compiled);
        return ptr::null_mut();
    }

    let list = (*ctxt).nodeList;
    if list.is_null() || (*list).nodeNr <= 1 {
        crate::xslt::sorting::xsltFreeSortList(compiled);
        return ptr::null_mut();
    }
    let len = (*list).nodeNr;
    let is_number = (*compiled).isText == 0;

    let results = xmlMallocImpl(len as usize * core::mem::size_of::<*mut _xmlXPathObject>())
        as *mut *mut _xmlXPathObject;
    if results.is_null() {
        emit_generic_error(b"xsltComputeSortResult: memory allocation failure\n\0");
        crate::xslt::sorting::xsltFreeSortList(compiled);
        return ptr::null_mut();
    }

    let xpath_ctxt = (*ctxt).xpathCtxt;
    let old_node = (*ctxt).node;
    let (old_pos, old_size) = if xpath_ctxt.is_null() {
        (0, 0)
    } else {
        ((*xpath_ctxt).proximityPosition, (*xpath_ctxt).contextSize)
    };

    let mut i: c_int = 0;
    while i < len {
        let node = *(*list).nodeTab.offset(i as isize);
        (*ctxt).node = node;
        if !xpath_ctxt.is_null() {
            (*xpath_ctxt).node = node;
            (*xpath_ctxt).contextSize = len;
            (*xpath_ctxt).proximityPosition = i + 1;
        }
        let key = crate::xslt::sorting::xsltEvalSortKey(ctxt, node, compiled);
        if key.is_null() {
            (*ctxt).state = crate::xslt::transform::XSLT_STATE_STOPPED;
            *results.offset(i as isize) = ptr::null_mut();
        } else {
            let obj =
                libc::calloc(1, core::mem::size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject;
            if obj.is_null() {
                // Recover: record a NULL slot like upstream does on
                // evaluation failure.
                *results.offset(i as isize) = ptr::null_mut();
                xmlFreeImpl(key as *mut c_void);
            } else if is_number {
                (*obj).type_ = xmlXPathObjectType::XPATH_NUMBER as c_int;
                (*obj).floatval = xmlXPathCastStringToNumber(key);
                (*obj).index = i;
                *results.offset(i as isize) = obj;
                xmlFreeImpl(key as *mut c_void);
            } else {
                (*obj).type_ = xmlXPathObjectType::XPATH_STRING as c_int;
                (*obj).stringval = key;
                (*obj).index = i;
                *results.offset(i as isize) = obj;
            }
        }
        i += 1;
    }

    (*ctxt).node = old_node;
    if !xpath_ctxt.is_null() {
        (*xpath_ctxt).node = old_node;
        (*xpath_ctxt).proximityPosition = old_pos;
        (*xpath_ctxt).contextSize = old_size;
    }
    crate::xslt::sorting::xsltFreeSortList(compiled);
    results
}

/// Set the global sort handler (upstream `xsltSetSortFunc`, xsltutils.c).
///
/// A NULL handler restores the default sort function.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltSetSortFunc(xsltSortFunc handler);
/// ```
///
/// # SAFETY
///
/// - `handler` must be a valid function pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltSetSortFunc(handler: Option<xsltSortFunc>) {
    unsafe {
        XSLT_SORT_FUNCTION = if handler.is_some() {
            handler
        } else {
            Some(xsltDefaultSortFunction)
        };
    }
}

/// Set the context-specific sort handler (upstream `xsltSetCtxtSortFunc`,
/// xsltutils.c).  A NULL handler makes [`xsltDoSortFunction`] fall back to
/// the global sort function.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltSetCtxtSortFunc(xsltTransformContextPtr ctxt, xsltSortFunc handler);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context; `handler` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltSetCtxtSortFunc(
    ctxt: *mut _xsltTransformContext,
    handler: Option<xsltSortFunc>,
) {
    if ctxt.is_null() {
        return;
    }
    (*ctxt).sortfunc = match handler {
        Some(f) => f as *const c_void as *mut c_void,
        None => ptr::null_mut(),
    };
}

// ═══════════════════════════════════════════════════════════════════════════════
// Multi-document output (transform.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Execute the multi-document output extension elements — `saxon:output`,
/// `xalan:write` and `xt:document`/`xsl:document` — (upstream
/// `xsltDocumentElem`, transform.c 1.1.45).
///
/// Ported faithfully: the target filename is computed from the element name
/// (`file`/`href`/`select` attributes, evaluated as AVTs — `select` as an
/// XPath expression), resolved against `ctxt->outputFile` with
/// `xmlBuildURI`, checked against the write security callback, a fresh
/// output stylesheet is created from the `version`/`encoding`/`method`/
/// `doctype-*`/`standalone`/`indent`/`omit-xml-declaration`/
/// `cdata-section-elements`/`append` attributes, the instruction content is
/// instantiated into a new result document, and the document is serialized
/// to the resolved filename.  The context's `output`/`insert`/`type`/
/// `outputFile` are saved and restored around the instantiation.
///
/// Simplifications: the generated-HTML-doctype table (`xsltGetHTMLIDs`,
/// behind `XSLT_GENERATE_HTML_DOCTYPE`) is not reproduced, the
/// `cdata-section-elements` entries are recorded in the output stylesheet's
/// `stripSpaces` hash but are inert in the candidate serializer, and error
/// messages do not interpolate the offending filename (the candidate's
/// non-variadic error API).
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node,
///                  xmlNodePtr inst, xsltElemPreCompPtr castedComp);
/// ```
///
/// # SAFETY
///
/// - `ctxt`, `node`, `inst` must be valid pointers; `castedComp` may be
///   NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltDocumentElem(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    castedComp: *mut c_void,
) {
    let _ = castedComp;
    if ctxt.is_null() || node.is_null() || inst.is_null() {
        return;
    }

    let mut ret: c_int;
    let mut URL: *mut xmlChar = ptr::null_mut();
    let mut filename: *mut xmlChar = ptr::null_mut();
    let mut prop: *mut xmlChar;
    let mut style: *mut _xsltStylesheet = ptr::null_mut();
    let mut res: *mut _xmlDoc = ptr::null_mut();
    let mut redirect_write_append: c_int = 0;

    let inst_name = (*inst).name;
    if xmlStrEqual(inst_name, b"output\0".as_ptr() as *const xmlChar) != 0 {
        /*
         * The element "output" is in the namespace XSLT_SAXON_NAMESPACE
         * (http://icl.com/saxon); the @file attribute is in no namespace.
         */
        URL = xsltEvalAttrValueTemplate(
            ctxt,
            inst,
            b"file\0".as_ptr() as *const xmlChar,
            XSLT_SAXON_NAMESPACE.as_ptr() as *const xmlChar,
        );
        if URL.is_null() {
            URL = xsltEvalAttrValueTemplate(
                ctxt,
                inst,
                b"href\0".as_ptr() as *const xmlChar,
                XSLT_SAXON_NAMESPACE.as_ptr() as *const xmlChar,
            );
        }
    } else if xmlStrEqual(inst_name, b"write\0".as_ptr() as *const xmlChar) != 0 {
        URL = xsltEvalAttrValueTemplate(
            ctxt,
            inst,
            b"select\0".as_ptr() as *const xmlChar,
            XSLT_XALAN_NAMESPACE.as_ptr() as *const xmlChar,
        );
        if !URL.is_null() {
            /*
             * Trying to handle bug #59212: the value of the "select"
             * attribute is an XPath expression.
             * (see http://xml.apache.org/xalan-j/extensionslib.html#redirect)
             */
            let obj = crate::xslt::transform::eval_xpath(ctxt, URL);
            let val = if obj.is_null() {
                ptr::null_mut()
            } else {
                let v = xmlXPathCastToString(obj);
                xmlXPathFreeObject(obj);
                v
            };
            xmlFreeImpl(URL as *mut c_void);
            URL = val;
        }
        if URL.is_null() {
            URL = xsltEvalAttrValueTemplate(
                ctxt,
                inst,
                b"file\0".as_ptr() as *const xmlChar,
                XSLT_XALAN_NAMESPACE.as_ptr() as *const xmlChar,
            );
        }
        if URL.is_null() {
            URL = xsltEvalAttrValueTemplate(
                ctxt,
                inst,
                b"href\0".as_ptr() as *const xmlChar,
                XSLT_XALAN_NAMESPACE.as_ptr() as *const xmlChar,
            );
        }
    } else if xmlStrEqual(inst_name, b"document\0".as_ptr() as *const xmlChar) != 0 {
        URL = xsltEvalAttrValueTemplate(
            ctxt,
            inst,
            b"href\0".as_ptr() as *const xmlChar,
            ptr::null(),
        );
    }

    if URL.is_null() {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            ptr::null_mut(),
            inst,
            b"xsltDocumentElem: href/URI-Reference not found\n\0".as_ptr() as *const c_char,
        );
        return;
    }

    /*
     * If the computation failed, it's likely that the URL wasn't escaped.
     */
    filename = xmlBuildURI(URL as *const c_char, (*ctxt).outputFile);
    if filename.is_null() {
        let esc_url = xmlURIEscapeStr(URL, b":/.?,\0".as_ptr() as *const xmlChar);
        if !esc_url.is_null() {
            filename = xmlBuildURI(esc_url as *const c_char, (*ctxt).outputFile);
            xmlFreeImpl(esc_url as *mut c_void);
        }
    }
    if filename.is_null() {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            ptr::null_mut(),
            inst,
            b"xsltDocumentElem: URL computation failed\n\0".as_ptr() as *const c_char,
        );
        xmlFreeImpl(URL as *mut c_void);
        return;
    }

    /*
     * Security checking: can we write to this resource.
     */
    if !(*ctxt).sec.is_null() {
        let check = crate::xslt::security::xsltGetSecurityPrefs(
            (*ctxt).sec,
            crate::xslt::security::XSLT_SECPREF_WRITE_FILE,
        );
        ret = match check {
            Some(f) => f(ctxt as *mut c_void, (*ctxt).sec, filename as *const c_char),
            None => 1,
        };
        if ret <= 0 {
            if ret == 0 {
                crate::xslt::errors::xsltTransformError(
                    ctxt,
                    ptr::null_mut(),
                    inst,
                    b"xsltDocumentElem: write rights denied\n\0".as_ptr() as *const c_char,
                );
            }
            xmlFreeImpl(URL as *mut c_void);
            xmlFreeImpl(filename as *mut c_void);
            return;
        }
    }

    let old_output_file = (*ctxt).outputFile;
    let old_output = (*ctxt).output;
    let old_insert = (*ctxt).insert;
    let old_type = (*ctxt).type_;
    (*ctxt).outputFile = filename as *const c_char;

    style = crate::xslt::stylesheet::xsltStylesheetCreate();
    if style.is_null() {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            ptr::null_mut(),
            inst,
            b"xsltDocumentElem: out of memory\n\0".as_ptr() as *const c_char,
        );
        goto_error(
            ctxt,
            old_output,
            old_insert,
            old_type,
            old_output_file,
            URL,
            filename,
            style,
            res,
        );
        return;
    }

    /*
     * Version described in 1.1 draft allows full parameterization of the
     * output.
     */
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"version\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if !(*style).version.is_null() {
            xmlFreeImpl((*style).version as *mut c_void);
        }
        (*style).version = prop;
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"encoding\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if !(*style).encoding.is_null() {
            xmlFreeImpl((*style).encoding as *mut c_void);
        }
        (*style).encoding = prop;
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"method\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        let mut method_name: *mut xmlChar = prop;
        let uri = xsltGetQNameURI(inst, &mut method_name);
        if method_name.is_null() {
            (*style).errors += 1;
        } else if uri.is_null() {
            if xmlStrEqual(method_name, b"xml\0".as_ptr() as *const xmlChar) != 0
                || xmlStrEqual(method_name, b"html\0".as_ptr() as *const xmlChar) != 0
                || xmlStrEqual(method_name, b"text\0".as_ptr() as *const xmlChar) != 0
            {
                (*style).method = method_name;
            } else {
                crate::xslt::errors::xsltTransformError(
                    ctxt,
                    ptr::null_mut(),
                    inst,
                    b"invalid value for method\n\0".as_ptr() as *const c_char,
                );
                (*style).warnings += 1;
                xmlFreeImpl(method_name as *mut c_void);
            }
        } else {
            (*style).method = method_name;
            (*style).methodURI = xmlStrdup(uri);
        }
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"doctype-system\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if !(*style).doctypeSystem.is_null() {
            xmlFreeImpl((*style).doctypeSystem as *mut c_void);
        }
        (*style).doctypeSystem = prop;
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"doctype-public\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if !(*style).doctypePublic.is_null() {
            xmlFreeImpl((*style).doctypePublic as *mut c_void);
        }
        (*style).doctypePublic = prop;
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"standalone\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if xmlStrEqual(prop, b"yes\0".as_ptr() as *const xmlChar) != 0 {
            (*style).standalone = 1;
        } else if xmlStrEqual(prop, b"no\0".as_ptr() as *const xmlChar) != 0 {
            (*style).standalone = 0;
        } else {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                b"invalid value for standalone\n\0".as_ptr() as *const c_char,
            );
            (*style).warnings += 1;
        }
        xmlFreeImpl(prop as *mut c_void);
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"indent\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if xmlStrEqual(prop, b"yes\0".as_ptr() as *const xmlChar) != 0 {
            (*style).indent = 1;
        } else if xmlStrEqual(prop, b"no\0".as_ptr() as *const xmlChar) != 0 {
            (*style).indent = 0;
        } else {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                b"invalid value for indent\n\0".as_ptr() as *const c_char,
            );
            (*style).warnings += 1;
        }
        xmlFreeImpl(prop as *mut c_void);
    }
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"omit-xml-declaration\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if xmlStrEqual(prop, b"yes\0".as_ptr() as *const xmlChar) != 0 {
            (*style).omitXmlDeclaration = 1;
        } else if xmlStrEqual(prop, b"no\0".as_ptr() as *const xmlChar) != 0 {
            (*style).omitXmlDeclaration = 0;
        } else {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                b"invalid value for omit-xml-declaration\n\0".as_ptr() as *const c_char,
            );
            (*style).warnings += 1;
        }
        xmlFreeImpl(prop as *mut c_void);
    }

    /*
     * cdata-section-elements: upstream stores "cdata" entries in the
     * output stylesheet's stripSpaces hash.  The candidate serializer does
     * not consult it, but the parsing is kept for fidelity.
     */
    let elements = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"cdata-section-elements\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !elements.is_null() {
        if (*style).stripSpaces.is_null() {
            (*style).stripSpaces = crate::xml::hash::hash_create(10) as *mut c_void;
        }
        if !(*style).stripSpaces.is_null() {
            let mut element: *mut xmlChar = elements;
            while *element != 0 {
                while crate::xml::chvalid::xmlIsBlank(*element as c_uint) != 0 {
                    element = element.add(1);
                }
                if *element == 0 {
                    break;
                }
                let mut end = element;
                while *end != 0 && crate::xml::chvalid::xmlIsBlank(*end as c_uint) == 0 {
                    end = end.add(1);
                }
                let mut el = xmlStrndup(element, (end as isize - element as isize) as c_int);
                if !el.is_null() {
                    let uri = xsltGetQNameURI(inst, &mut el);
                    crate::xml::hash::hash_add_entry2(
                        (*style).stripSpaces as *mut crate::xml::hash::HashTable,
                        el,
                        uri,
                        b"cdata\0".as_ptr() as *mut c_void,
                    );
                    xmlFreeImpl(el as *mut c_void);
                }
                element = end;
            }
        }
        xmlFreeImpl(elements as *mut c_void);
    }

    /*
     * Create a new document tree and process the element template.
     */
    let method: *const xmlChar = (*style).method;
    let doctype_public: *const xmlChar = (*style).doctypePublic;
    let doctype_system: *const xmlChar = (*style).doctypeSystem;
    let version: *const xmlChar = (*style).version;
    let encoding: *const xmlChar = (*style).encoding;

    if !method.is_null() && xmlStrEqual(method, b"xml\0".as_ptr() as *const xmlChar) == 0 {
        if xmlStrEqual(method, b"html\0".as_ptr() as *const xmlChar) != 0 {
            (*ctxt).type_ = XSLT_OUTPUT_HTML;
            if !doctype_public.is_null() || !doctype_system.is_null() {
                res = htmlNewDoc(doctype_system, doctype_public);
            } else {
                res = htmlNewDocNoDtD(doctype_system, doctype_public);
            }
        } else if xmlStrEqual(method, b"xhtml\0".as_ptr() as *const xmlChar) != 0 {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                b"xsltDocumentElem: unsupported method xhtml\n\0".as_ptr() as *const c_char,
            );
            (*ctxt).type_ = XSLT_OUTPUT_HTML;
            res = htmlNewDocNoDtD(doctype_system, doctype_public);
        } else if xmlStrEqual(method, b"text\0".as_ptr() as *const xmlChar) != 0 {
            (*ctxt).type_ = XSLT_OUTPUT_TEXT;
            res = xmlNewDoc(version);
        } else {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                b"xsltDocumentElem: unsupported method\n\0".as_ptr() as *const c_char,
            );
            goto_error(
                ctxt,
                old_output,
                old_insert,
                old_type,
                old_output_file,
                URL,
                filename,
                style,
                res,
            );
            return;
        }
    } else {
        (*ctxt).type_ = XSLT_OUTPUT_XML;
        res = xmlNewDoc(version);
    }
    if res.is_null() {
        goto_error(
            ctxt,
            old_output,
            old_insert,
            old_type,
            old_output_file,
            URL,
            filename,
            style,
            res,
        );
        return;
    }
    (*res).charset = XML_CHAR_ENCODING_UTF8;
    if !encoding.is_null() {
        (*res).encoding = xmlStrdup(encoding);
    }
    (*ctxt).output = res;
    (*ctxt).insert = res as *mut _xmlNode;
    (*ctxt).node = node;
    crate::xslt::transform::execute_content(ctxt, (*inst).children);

    /*
     * Do some post processing work depending on the generated output.
     */
    let root = xmlDocGetRootElement(res);
    if !root.is_null() {
        let mut doctype: *const xmlChar = ptr::null();

        if !(*root).ns.is_null() && !(*(*root).ns).prefix.is_null() {
            if !(*ctxt).dict.is_null() {
                /* xmlDictQLookup: intern "prefix:name" in the dict. */
                let plen = crate::xml::string::xml_strlen((*(*root).ns).prefix);
                let nlen = crate::xml::string::xml_strlen((*root).name);
                let mut qn = Vec::with_capacity(plen + 1 + nlen);
                qn.extend_from_slice(core::slice::from_raw_parts(
                    (*(*root).ns).prefix as *const u8,
                    plen,
                ));
                qn.push(b':');
                qn.extend_from_slice(core::slice::from_raw_parts((*root).name as *const u8, nlen));
                qn.push(0);
                doctype = crate::xml::dictionary::dict_lookup(
                    (*ctxt).dict as *mut crate::xml::dictionary::Dict,
                    qn.as_ptr() as *const xmlChar,
                    (plen + 1 + nlen) as c_int,
                );
            }
        }
        if doctype.is_null() {
            doctype = (*root).name;
        }

        /*
         * Apply the default selection of the method.
         */
        if method.is_null()
            && (*root).ns.is_null()
            && libc::strcasecmp(
                (*root).name as *const c_char,
                b"html\0".as_ptr() as *const c_char,
            ) == 0
        {
            let mut tmp = (*res).children;
            while !tmp.is_null() && tmp != root {
                if (*tmp).type_ == XML_ELEMENT_NODE as c_int {
                    break;
                }
                if (*tmp).type_ == XML_TEXT_NODE as c_int
                    && crate::xml::chvalid::xmlIsBlankNode(tmp) == 0
                {
                    break;
                }
                tmp = (*tmp).next;
            }
            if tmp == root {
                (*ctxt).type_ = XSLT_OUTPUT_HTML;
                (*res).type_ = XML_HTML_DOCUMENT_NODE as c_int;
                if !doctype_public.is_null() || !doctype_system.is_null() {
                    (*res).intSubset =
                        xmlCreateIntSubset(res, doctype, doctype_public, doctype_system);
                }
            }
        }
        if (*ctxt).type_ == XSLT_OUTPUT_XML {
            if !doctype_public.is_null() || !doctype_system.is_null() {
                (*res).intSubset = xmlCreateIntSubset(res, doctype, doctype_public, doctype_system);
            }
        }
    }

    /*
     * Calls to redirect:write also take an optional attribute append.
     * append="true|yes" appends to an existing file instead of always
     * opening a new one.
     */
    prop = xsltEvalAttrValueTemplate(
        ctxt,
        inst,
        b"append\0".as_ptr() as *const xmlChar,
        ptr::null(),
    );
    if !prop.is_null() {
        if xmlStrEqual(prop, b"true\0".as_ptr() as *const xmlChar) != 0
            || xmlStrEqual(prop, b"yes\0".as_ptr() as *const xmlChar) != 0
        {
            (*style).omitXmlDeclaration = 1;
            redirect_write_append = 1;
        } else {
            (*style).omitXmlDeclaration = 0;
        }
        xmlFreeImpl(prop as *mut c_void);
    }

    if redirect_write_append != 0 {
        let f = libc::fopen(filename as *const c_char, b"ab\0".as_ptr() as *const c_char);
        if f.is_null() {
            ret = -1;
        } else {
            ret = crate::xslt::serialization::xsltSaveResultToFile(f as *mut c_void, res, style);
            libc::fclose(f);
        }
    } else {
        ret = crate::xslt::serialization::xsltSaveResultToFilename(
            filename as *const c_char,
            res,
            style,
            0,
        );
    }
    if ret < 0 {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            ptr::null_mut(),
            inst,
            b"xsltDocumentElem: unable to save result\n\0".as_ptr() as *const c_char,
        );
    }

    goto_error(
        ctxt,
        old_output,
        old_insert,
        old_type,
        old_output_file,
        URL,
        filename,
        style,
        res,
    );
}

/// Restore the transform context fields saved by `xsltDocumentElem` and
/// release its temporaries (upstream `error:` label).
#[allow(clippy::too_many_arguments)]
unsafe fn goto_error(
    ctxt: *mut _xsltTransformContext,
    old_output: *mut _xmlDoc,
    old_insert: *mut _xmlNode,
    old_type: c_int,
    old_output_file: *const c_char,
    url: *mut xmlChar,
    filename: *mut xmlChar,
    style: *mut _xsltStylesheet,
    res: *mut _xmlDoc,
) {
    (*ctxt).output = old_output;
    (*ctxt).insert = old_insert;
    (*ctxt).type_ = old_type;
    (*ctxt).outputFile = old_output_file;
    if !url.is_null() {
        xmlFreeImpl(url as *mut c_void);
    }
    if !filename.is_null() {
        xmlFreeImpl(filename as *mut c_void);
    }
    if !style.is_null() {
        crate::xslt::stylesheet::xsltFreeStylesheet(style);
    }
    if !res.is_null() {
        crate::xml::tree::free_doc(res);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Debug (extra.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Process a `libxslt:debug` element (upstream `xsltDebug`, extra.c):
/// dump the last 15 entries of the template stack and the variable stack
/// through the generic error handler.
///
/// Ported faithfully.  The upstream `xmlXPathDebugDumpObject` dump of
/// variable values (guarded by `LIBXML_DEBUG_ENABLED`) is not reproduced —
/// the candidate lacks that debug API; the text output is identical for the
/// common case.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void
/// xsltDebug(xsltTransformContextPtr ctxt, xmlNodePtr node ATTRIBUTE_UNUSED,
///           xmlNodePtr inst ATTRIBUTE_UNUSED,
///           xsltElemPreCompPtr comp ATTRIBUTE_UNUSED);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context.
#[no_mangle]
pub unsafe extern "C" fn xsltDebug(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    inst: *mut _xmlNode,
    comp: *mut c_void,
) {
    let _ = (node, inst, comp);
    if ctxt.is_null() {
        return;
    }

    let mut i: c_int = 0;
    let mut j = (*ctxt).templNr - 1;
    emit_generic_error(b"Templates:\n\0");
    if !(*ctxt).templTab.is_null() {
        while i < 15 && j >= 0 {
            let msg = format!("#{} ", i);
            emit_generic_error(msg.as_bytes());
            let t = *(*ctxt).templTab.offset(j as isize);
            if !t.is_null() {
                if !(*t).name.is_null() {
                    let m = format!("name {} ", bytes_to_lossy((*t).name));
                    emit_generic_error(m.as_bytes());
                }
                if !(*t).r#match.is_null() {
                    // NOTE: upstream prints "name %s" for the match pattern
                    // too (extra.c quirk).
                    let m = format!("name {} ", bytes_to_lossy((*t).r#match));
                    emit_generic_error(m.as_bytes());
                }
                if !(*t).mode.is_null() {
                    let m = format!("name {} ", bytes_to_lossy((*t).mode));
                    emit_generic_error(m.as_bytes());
                }
            }
            emit_generic_error(b"\n\0");
            i += 1;
            j -= 1;
        }
    }

    emit_generic_error(b"Variables:\n\0");
    i = 0;
    j = (*ctxt).varsNr - 1;
    if !(*ctxt).varsTab.is_null() {
        while i < 15 && j >= 0 {
            let cur = *(*ctxt).varsTab.offset(j as isize);
            if cur.is_null() {
                j -= 1;
                i += 1;
                continue;
            }
            let msg = format!("#{}\n", i);
            emit_generic_error(msg.as_bytes());
            let mut p = cur;
            while !p.is_null() {
                if (*p).comp.is_null() {
                    emit_generic_error(b"corrupted !!!\n\0");
                } else {
                    let typ = *((*p).comp as *const c_int);
                    if typ == XSLT_FUNC_PARAM {
                        emit_generic_error(b"param \0");
                    } else if typ == XSLT_FUNC_VARIABLE {
                        emit_generic_error(b"var \0");
                    }
                }
                if !(*p).name.is_null() {
                    let m = format!("{} ", bytes_to_lossy((*p).name));
                    emit_generic_error(m.as_bytes());
                } else {
                    emit_generic_error(b"noname !!!!\n\0");
                }
                p = (*p).next;
            }
            j -= 1;
            i += 1;
        }
    }
}

/// Render a NUL-terminated xmlChar string as a lossy Rust string (for the
/// debug dumps).
unsafe fn bytes_to_lossy(s: *const xmlChar) -> String {
    if s.is_null() {
        return String::new();
    }
    let len = libc::strlen(s as *const c_char) as usize;
    String::from_utf8_lossy(core::slice::from_raw_parts(s, len)).into_owned()
}