libxml-rs 0.1.0-alpha.49

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; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
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
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
//! XSLT transformation engine (§33, §85 Phase 8).
//!
//! # Upstream contract
//!
//! Parity target: upstream libxslt `transform.c` (1.1.45;
//! `SRC-LIBXSLT-1.1.42-TRANSFORM-C` under oracle/historical/src). Subsystem
//! census: xslt-transform-ctxt, xslt-transform-exec, xslt-output,
//! xslt-errors, xslt-exports. ABI surface: `xsltNewTransformContext`/
//! `xsltFreeTransformContext`, `xsltApplyStylesheet` and variants,
//! `xsltApplyStylesheetUser`/`Stacked`, the `xsltMaxDepth`/`xsltMaxVars`
//! globals, and `xsltSetXIncludeDefault`/`xsltGetXIncludeDefault`.
//!
//! # Conceptual behavior
//!
//! `xsltApplyStylesheet` creates (or reuses) a transform context, seeds
//! the XPath context, initializes global variables and key tables,
//! applies the root template, and drives instruction execution: each
//! instruction builds the result tree through the context `insert`
//! pointer, with `node`/`nodeList` tracking the source node and
//! `contextSize`/`proximityPosition` tracking the XPath context.
//! `XSLT_MAX_DEPTH`/`xsltMaxDepth` bound recursion; the context state
//! (OK/ERROR/STOPPED) gates every loop.
//!
//! # Ownership & safety invariants
//!
//! - Source document: borrowed (caller keeps it).
//! - Result document: fresh, caller-owned (`xmlFreeDoc`;
//!   `xsltFreeTransformResult` alias); version/encoding strings are
//!   heap-copied (R-000104) so `free_doc` never frees borrowed literals.
//! - RVT documents: owned by the context doc lists (variables/documents
//!   modules), freed at teardown after the XPath context (R-000109).
//! - The variable stack is context-owned; `process_call_template` pops
//!   back to the saved depth, never a fixed count (R-000158).
//! - All entry points are `unsafe`; pointers must come from the matching
//!   constructor/owner (atlas/OWNERSHIP_ATLAS.md section 4).
//!
//! # Historical quirks & epochs
//!
//! E-008 (atlas/SEMANTIC_EPOCHS.md): xsltproc basic/num/empty output is
//! byte-identical from libxslt 1.1.26 (2009) through 1.1.45 — the engine
//! targets a fully frozen epoch. Residual fixes anchored here: R-000104
//! (result version/encoding double-free), R-000107 (XPath core functions
//! registration), R-000108 (AVT evaluation), R-000113 (boolean
//! conversion), R-000115 (sort wiring), R-000158 (with-param snapshot),
//! R-000159 (position() context), R-000162 (callback bridge), R-000167
//! (version symbol types).
//!
//! # Deliberate oddities
//!
//! - The default parser options for loaded documents are exactly
//!   XSLT_PARSE_OPTIONS (NOENT|DTDLOAD|DTDATTR|NOCDATA = 16398),
//!   matching transform.c `xsltNewTransformContext`.
//! - The per-context depth/vars limits are copied from the process-wide
//!   `xsltMaxDepth`/`xsltMaxVars` globals at context creation, matching
//!   upstream.
//! - Context position/size state is maintained on both the C ABI
//!   `_xmlXPathContext` and the internal Rust XPathContext (`extra`
//!   slot) — a dual-bookkeeping bridge (R-000159).
//!
//! # Proving courts
//!
//! CLI-XSLTPROC-0001..0057 (differential xsltproc corpus, byte-identical
//! receipts), XSLT-001 (xslt-family probe), DSO-LOADER, HIST-EPOCH-0001..
//! 0008 (E-008), and the in-crate `cargo test` suites.
//!
//! # Tempting simplifications that would break parity
//!
//! - Fixed-count variable pops instead of pop-to-saved-depth break
//!   xsl:call-template with defaulted parameters (R-000158).
//! - Treating position() as a function of the node alone breaks
//!   `//book[position() <= 2]` (R-000159); the predicate loops must set
//!   and restore proximity position.
//! - Evaluating AVTs once at compile time breaks context-dependent
//!   attribute values (R-000108).
//! - Iterating with-param lists while pushing variables corrupts the
//!   list (xsltPushVariable rewires `next`); snapshot first (R-000158).
//!
//! Executes compiled stylesheets against source documents:
//! - `xsltNewTransformContext` / `xsltFreeTransformContext`
//! - `xsltApplyStylesheet` and variants
//! - Template application and instruction execution
//! - Result tree construction
//! - Current node / context position / context size management
//! - Recursion depth limiting
//!
//! # UPSTREAM-PARITY
//!
//! Upstream libxslt (transform.c) drives the transformation from
//! `xsltApplyStylesheet`:
//!
//! 1. Create a transform context (or reuse a user-supplied one).
//! 2. Initialize global variables and key tables.
//! 3. Apply the template matching the root node of the source document.
//! 4. Execute the template's instructions, building the result tree.
//! 5. Return the result document.
//!
//! The `insert` pointer in the context tracks the current insertion point
//! in the result tree; the `node` / `nodeList` fields track the current
//! source node and node list; `contextSize` / `proximityPosition` track
//! the XPath context.

use crate::abi::allocator::xmlFreeImpl;
use crate::abi::exports_xml2::*;
use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;
use crate::abi::types::xmlXPathObjectType;
use crate::abi::types::*;
use crate::xml::tree::*;
use std::ffi::c_void;
use std::os::raw::{c_char, c_int};
use std::ptr;

use super::compiler::{get_element_name, get_element_ns, is_xslt_element, is_xslt_namespace};

/// Maximum template recursion depth (matches upstream XSLT_MAX_DEPTH).
pub const XSLT_MAX_DEPTH: c_int = 3000;

/// Maximum insert depth.
pub const XSLT_MAX_INSERT_DEPTH: c_int = 50;

/// State flags for the transform context.
pub const XSLT_STATE_OK: c_int = 0;
/// The transform context is in an error state after a fatal error.
pub const XSLT_STATE_ERROR: c_int = 1;

/// The transformation was stopped (e.g. xsl:message terminate="yes").
pub const XSLT_STATE_STOPPED: c_int = 2;

/// Static type cells used as `_xsltStackElem.comp` markers so the debug
/// dump (upstream extra.c `xsltDebug`, which reads `cur->comp->type`) can
/// classify pushed variables/params. Values mirror the XSLT_FUNC_* enum
/// used by exports_xslt_exec.rs (PARAM/VARIABLE get a prefix in the dump;
/// with-param prints the bare name).
pub(crate) static XSLT_COMP_TYPE_PARAM: c_int = 19;
pub(crate) static XSLT_COMP_TYPE_VARIABLE: c_int = 20;
pub(crate) static XSLT_COMP_TYPE_WITHPARAM: c_int = 24;

/// Maximum template recursion depth (upstream `xsltMaxDepth`, transform.c).
/// Default 3000 (upstream transform.c `int xsltMaxDepth = 3000`).
#[no_mangle]
pub static mut xsltMaxDepth: c_int = 3000;

/// Maximum number of variables/params (upstream `xsltMaxVars`, transform.c).
#[no_mangle]
pub static mut xsltMaxVars: c_int = 15000;

/// Whether XInclude processing is enabled by default for documents loaded
/// by the transform (upstream `xsltDoXIncludeDefault`, transform.c).
static mut XSLT_XINCLUDE_DEFAULT: c_int = 0;

/// Set whether XInclude processing is done on documents loaded by the
/// transformation (upstream `xsltSetXIncludeDefault`).
///
/// # SAFETY
///
/// - The value is a process-wide setting, matching upstream's global.
#[no_mangle]
pub unsafe extern "C" fn xsltSetXIncludeDefault(xinclude: c_int) {
    unsafe { XSLT_XINCLUDE_DEFAULT = if xinclude != 0 { 1 } else { 0 } };
}

/// Get the current XInclude default (upstream `xsltGetXIncludeDefault`).
///
/// # SAFETY
///
/// The function touches crate-global state only; it is safe
/// as long as the caller respects the library's global
/// initialization/cleanup ordering (xmlInitParser before use,
/// xmlCleanupParser only after all users are done).
///
/// Violating the global lifecycle ordering, or calling this after
/// teardown or from a signal handler, is undefined behavior.
#[no_mangle]
pub unsafe extern "C" fn xsltGetXIncludeDefault() -> c_int {
    unsafe { XSLT_XINCLUDE_DEFAULT }
}

/// Create a new transform context.
///
/// # SAFETY
///
/// - `style` must be a valid compiled `_xsltStylesheet`.
/// - `doc` must be a valid source document (may be NULL).
#[no_mangle]
pub unsafe extern "C" fn xsltNewTransformContext(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
) -> *mut _xsltTransformContext {
    if style.is_null() {
        return ptr::null_mut();
    }
    let ctxt = libc::calloc(1, core::mem::size_of::<_xsltTransformContext>())
        as *mut _xsltTransformContext;
    if ctxt.is_null() {
        return ptr::null_mut();
    }
    (*ctxt).style = style;
    (*ctxt).state = XSLT_STATE_OK;
    // UPSTREAM-PARITY: the default parser options (XSLT_PARSE_OPTIONS =
    // XML_PARSE_NOENT|DTDLOAD|DTDATTR|NOCDATA = 2+4+8+16384 = 16398),
    // exactly as transform.c xsltNewTransformContext sets it.
    (*ctxt).parserOptions = 2 | 4 | 8 | 16384;
    // UPSTREAM-PARITY: the per-context depth/vars limits come from the
    // process-wide xsltMaxDepth/xsltMaxVars globals (adjustable via
    // xsltproc --maxdepth/--maxvars).
    (*ctxt).maxTemplateDepth = unsafe { xsltMaxDepth };
    (*ctxt).maxTemplateVars = unsafe { xsltMaxVars };

    // Create the XPath context.
    let xpath_ctxt = xmlXPathNewContext(doc);
    if !xpath_ctxt.is_null() {
        (*ctxt).xpathCtxt = xpath_ctxt;
        // Stash this transform context in the XPath context's opaque slot so
        // XSLT XPath functions (e.g. key()) can reach the key tables.
        let internal = (*xpath_ctxt).extra as *mut crate::xml::xpath::context::XPathContext;
        if !internal.is_null() {
            (*internal).func_lookup_data = ctxt as *mut c_void;
        }
        // Register the standard XSLT extension functions and variable
        // lookup for XSLT evaluation. UPSTREAM-PARITY: transform.c
        // xsltNewTransformContext runs XSLT_REGISTER_VARIABLE_LOOKUP, which
        // calls xsltRegisterAllFunctions(xpathCtxt) — registering the C
        // XPath functions (format-number, key, document, ...) on the
        // context and re-registering the internal Rust implementations.
        crate::abi::exports_xslt_functions::xsltRegisterAllFunctions(xpath_ctxt);
    }

    // Security preferences: upstream xsltNewTransformContext binds the
    // process-wide default (transform.c 1.1.42); there is no per-stylesheet
    // security slot.
    (*ctxt).sec = crate::xslt::security::xsltGetDefaultSecurityPrefs();

    // UPSTREAM-PARITY: wrap the source document in an _xsltDocument
    // (docu->main = 1, transform.c) so ctxt->document is a proper document
    // wrapper; key tables and loaded documents hang off it.
    if !doc.is_null() {
        let docu = libc::calloc(1, core::mem::size_of::<_xsltDocument>()) as *mut _xsltDocument;
        if !docu.is_null() {
            (*docu).main = 1;
            (*docu).doc = doc;
            (*ctxt).document = docu;
            (*ctxt).docList = docu;
        }
        // Upstream xsltApplyStylesheetInternal records the initial context
        // here (transform.c); xsltEvalGlobalVariable evaluates global
        // variables against it (variables.c).
        (*ctxt).initialContextDoc = doc;
        (*ctxt).initialContextNode = doc as *mut _xmlNode;
    }
    ctxt
}

/// Free a transform context.
///
/// # SAFETY
///
/// - `ctxt` must be a valid `_xsltTransformContext` allocated by
///   `xsltNewTransformContext`, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltFreeTransformContext(ctxt: *mut _xsltTransformContext) {
    if ctxt.is_null() {
        return;
    }
    // Free the XPath context.
    if !(*ctxt).xpathCtxt.is_null() {
        xmlXPathFreeContext((*ctxt).xpathCtxt);
    }
    // NOTE: the result document is owned by the caller of
    // xsltApplyStylesheet (upstream xsltFreeTransformContext does not free
    // ctxt->output / resultDoc); freeing it here would double-free the
    // result when the caller releases it.
    // Free global variables.
    crate::xslt::variables::xsltFreeGlobalVariables(ctxt);
    // Free key tables.
    crate::xslt::keys::xsltFreeKeyTables(ctxt);
    // Free the document cache.
    crate::xslt::documents::xsltFreeDocCache(ctxt);
    // Free extension registrations.
    crate::xslt::extensions::xsltFreeExts(ctxt);
    // Free the variable table itself.
    if !(*ctxt).varsTab.is_null() {
        libc::free((*ctxt).varsTab as *mut libc::c_void);
    }
    if !(*ctxt).templTab.is_null() {
        libc::free((*ctxt).templTab as *mut libc::c_void);
    }
    // Free the document wrapper (the wrapped _xmlDoc belongs to the caller;
    // only the _xsltDocument shell and its key tables are owned here).
    if !(*ctxt).document.is_null() {
        let docu = (*ctxt).document;
        (*docu).doc = ptr::null_mut();
        libc::free(docu as *mut libc::c_void);
        (*ctxt).document = ptr::null_mut();
    }
    libc::free(ctxt as *mut libc::c_void);
}

/// Apply a stylesheet to a document.
///
/// `params` is a NULL-terminated array of `name=value` strings.
/// Returns the result document (caller frees with `xmlFreeDoc`).
///
/// # SAFETY
///
/// - `style` must be a valid compiled stylesheet.
/// - `doc` must be a valid source document.
#[no_mangle]
pub unsafe extern "C" fn xsltApplyStylesheet(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
    params: *mut *const c_char,
) -> *mut _xmlDoc {
    xsltApplyStylesheetUser(
        style,
        doc,
        params,
        ptr::null(),
        ptr::null_mut(),
        ptr::null_mut(),
    )
}

/// Apply a stylesheet with user control.
///
/// # SAFETY
///
/// - All pointers must be valid or NULL where permitted.
#[no_mangle]
pub unsafe extern "C" fn xsltApplyStylesheetUser(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
    params: *mut *const c_char,
    _output: *const c_char,
    _profile: *mut c_void,
    userCtxt: *mut _xsltTransformContext,
) -> *mut _xmlDoc {
    if style.is_null() || doc.is_null() {
        return ptr::null_mut();
    }

    // Use the user-provided context or create a new one.
    let mut ctxt = userCtxt;
    let mut own_ctxt = false;
    if ctxt.is_null() {
        ctxt = xsltNewTransformContext(style, doc);
        if ctxt.is_null() {
            return ptr::null_mut();
        }
        own_ctxt = true;
    }

    // Parse the stylesheet parameters.
    if !params.is_null() {
        crate::xslt::parameters::xsltParseStylesheetParams(style, params);
    }

    // Initialize global variables.
    crate::xslt::variables::xsltInitGlobalVariables(ctxt);

    // Initialize key tables.
    crate::xslt::keys::xsltInitKeys(ctxt, style);

    // Apply the strip-space rules to the source document.
    crate::xslt::whitespace::xsltApplyStripSpaces(style, doc);

    // Build the result document. UPSTREAM-PARITY (transform.c
    // xsltApplyStylesheetInternal -> xmlNewDoc): the result document is a
    // fresh xmlNewDoc, whose defaults are standalone=-1 (undeclared),
    // compression=-1, charset=UTF-8 and properties=XML_DOC_USERBUILT. The
    // pre-fix calloc only zeroed the struct, so the serializer emitted an
    // unwanted `standalone="no"` in the XML declaration (xslt006 +
    // xsltprocessor_transformToXML diff) and the wrong charset defaults.
    let result = libc::calloc(1, core::mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
    if result.is_null() {
        if own_ctxt {
            xsltFreeTransformContext(ctxt);
        }
        return ptr::null_mut();
    }
    (*result).type_ = XML_DOCUMENT_NODE as c_int;
    (*result).standalone = -1;
    (*result).compression = -1;
    (*result).charset = crate::abi::types::xmlCharEncoding::XML_CHAR_ENCODING_UTF8 as c_int;
    (*result).properties = crate::abi::types::xmlDocProperties::XML_DOC_USERBUILT as c_int;
    (*result).version = crate::xml::string::xml_strdup(c"1.0".as_ptr() as *const xmlChar);
    (*result).doc = result;
    // Copy output settings from the stylesheet. These are heap-copied so
    // that free_doc (which frees version/encoding with xmlFree) is safe
    // and the stylesheet keeps its own copies.
    if !(*style).encoding.is_null() {
        (*result).encoding = crate::xml::string::xml_strdup((*style).encoding);
    }
    if !(*style).version.is_null() {
        let v = crate::xml::string::xml_strdup((*style).version);
        if !v.is_null() {
            if !(*result).version.is_null() {
                libc::free((*result).version as *mut libc::c_void);
            }
            (*result).version = v;
        }
    }

    // UPSTREAM-PARITY: xsltApplyStylesheetInternal records the initial
    // context here (transform.c 1.1.42); global variable evaluation uses it.
    (*ctxt).initialContextDoc = doc;
    (*ctxt).initialContextNode = doc as *mut _xmlNode;

    (*ctxt).output = result;
    (*ctxt).insert = result as *mut _xmlNode;

    // Apply the root template: XSLT 1.0 §5.1 applies the template
    // matching "/" to the document node (the root of the source tree).
    // The document node is the doc cast to a node; its parent is null.
    (*ctxt).node = doc as *mut _xmlNode;
    if !(*ctxt).xpathCtxt.is_null() {
        (*(*ctxt).xpathCtxt).node = doc as *mut _xmlNode;
        (*(*ctxt).xpathCtxt).doc = doc;
        (*(*ctxt).xpathCtxt).contextSize = 1;
        (*(*ctxt).xpathCtxt).proximityPosition = 1;
    }
    let result_code = apply_templates_to_node(ctxt, doc as *mut _xmlNode, ptr::null());
    let _ = result_code;

    // UPSTREAM-PARITY: a transformation whose context is no longer in the
    // OK state produces no result (xsltApplyStylesheetInternal frees the
    // result and returns NULL when ctxt->state != XSLT_STATE_OK).
    let final_result = if (*ctxt).state == XSLT_STATE_OK {
        result
    } else {
        free_doc(result);
        ptr::null_mut()
    };

    if own_ctxt {
        // Detach the result document from the context before freeing.
        (*ctxt).output = ptr::null_mut();
        xsltFreeTransformContext(ctxt);
    }
    final_result
}

/// Apply a stylesheet with a parameter stack.
///
/// # SAFETY
///
/// - All pointers must be valid or NULL where permitted.
#[no_mangle]
pub unsafe extern "C" fn xsltApplyStylesheetStacked(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
    params: *mut *const c_char,
    _stack: *mut c_void,
) -> *mut _xmlDoc {
    xsltApplyStylesheet(style, doc, params)
}

/// Free the result of a transformation.
///
/// # SAFETY
///
/// - `result` must be a document returned by `xsltApplyStylesheet` or NULL.
#[no_mangle]
pub unsafe extern "C" fn xsltFreeTransformResult(result: *mut _xmlDoc) {
    if !result.is_null() {
        free_doc(result);
    }
}

/// Apply a stylesheet and write the result to an output channel.
///
/// # UPSTREAM-PARITY
///
/// Mirrors `xsltRunStylesheetUser` (transform.c 1.1.45): applies the
/// stylesheet and saves to `output` (a filename) or `IObuf`. The SAX
/// callback mode is not implemented by upstream either (it returns -1).
///
/// # SAFETY
///
/// - All pointers must be valid or NULL where permitted.
#[no_mangle]
pub unsafe extern "C" fn xsltRunStylesheetUser(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
    params: *mut *const c_char,
    output: *const c_char,
    SAX: *mut crate::abi::structs::_xmlSAXHandler,
    IObuf: *mut crate::abi::structs::_xmlOutputBuffer,
    profile: *mut c_void,
    userCtxt: *mut _xsltTransformContext,
) -> c_int {
    if output.is_null() && SAX.is_null() && IObuf.is_null() {
        return -1;
    }
    if !SAX.is_null() && !IObuf.is_null() {
        return -1;
    }
    // SAX output mode is unsupported upstream as well.
    if !SAX.is_null() {
        return -1;
    }
    let tmp = xsltApplyStylesheetUser(style, doc, params, output, profile, userCtxt);
    if tmp.is_null() {
        eprintln!("xsltRunStylesheet : run failed");
        return -1;
    }
    let ret = if !IObuf.is_null() {
        let mut txt: *mut xmlChar = ptr::null_mut();
        let mut len: c_int = 0;
        let r = crate::xslt::serialization::xsltSaveResultToString(&mut txt, &mut len, tmp, style);
        if r != 0 || txt.is_null() {
            -1
        } else {
            let written = crate::xml::io::output_buffer_write(IObuf, len, txt as *const c_char);
            crate::abi::allocator::xmlFreeImpl(txt as *mut c_void);
            written
        }
    } else {
        crate::xslt::serialization::xsltSaveResultToFilename(output, tmp, style, 0)
    };
    free_doc(tmp);
    ret
}

/// Apply a stylesheet and write the result to an output channel.
///
/// # SAFETY
///
/// - All pointers must be valid or NULL where permitted.
#[no_mangle]
pub unsafe extern "C" fn xsltRunStylesheet(
    style: *mut _xsltStylesheet,
    doc: *mut _xmlDoc,
    params: *mut *const c_char,
    output: *const c_char,
    SAX: *mut crate::abi::structs::_xmlSAXHandler,
    IObuf: *mut crate::abi::structs::_xmlOutputBuffer,
) -> c_int {
    xsltRunStylesheetUser(
        style,
        doc,
        params,
        output,
        SAX,
        IObuf,
        ptr::null_mut(),
        ptr::null_mut(),
    )
}

/// Apply the root template (match="/") for empty documents.
///
/// # SAFETY
///
/// - All pointers must be valid.
#[allow(dead_code)]
pub(crate) unsafe fn apply_root_template(
    ctxt: *mut _xsltTransformContext,
    doc: *mut _xmlDoc,
) -> c_int {
    // Find the template matching "/".
    let style = (*ctxt).style;
    if style.is_null() {
        return -1;
    }
    // Use the document node itself as the context node.
    let doc_node = doc as *mut _xmlNode;
    (*ctxt).node = doc_node;
    if !(*ctxt).xpathCtxt.is_null() {
        (*(*ctxt).xpathCtxt).contextSize = 1;
        (*(*ctxt).xpathCtxt).proximityPosition = 1;
    }
    let templ = crate::xslt::templates::xsltFindTemplate(style, doc_node, ptr::null());
    if templ.is_null() {
        // No match: copy nothing (empty result).
        return 0;
    }
    // Execute the template body.
    let mut vars_base = (*ctxt).varsNr;
    let _ = &mut vars_base;
    (*ctxt).templ = templ;
    execute_content(ctxt, (*templ).content);
    (*ctxt).templ = ptr::null_mut();
    0
}

/// Push a template onto the transform context's template stack (upstream
/// xsltApplyXSLTTemplate pushes the template into `ctxt->templTab` before
/// instantiating it; extra.c `xsltDebug` dumps the last 15 entries).
///
/// # SAFETY
///
/// - `ctxt` and `templ` must be valid pointers.
unsafe fn template_stack_push(ctxt: *mut _xsltTransformContext, templ: *mut _xsltTemplate) {
    unsafe {
        let nr = (*ctxt).templNr;
        if nr >= (*ctxt).templMax {
            let new_max = if (*ctxt).templMax == 0 {
                32
            } else {
                (*ctxt).templMax * 2
            };
            let new_tab = libc::realloc(
                (*ctxt).templTab as *mut libc::c_void,
                (new_max as usize) * core::mem::size_of::<*mut _xsltTemplate>(),
            ) as *mut *mut _xsltTemplate;
            if new_tab.is_null() {
                return;
            }
            (*ctxt).templTab = new_tab;
            (*ctxt).templMax = new_max;
        }
        *(*ctxt).templTab.add(nr as usize) = templ;
        (*ctxt).templNr = nr + 1;
    }
}

/// Pop a template from the transform context's template stack.
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer.
unsafe fn template_stack_pop(ctxt: *mut _xsltTransformContext) {
    unsafe {
        if (*ctxt).templNr > 0 {
            (*ctxt).templNr -= 1;
            *(*ctxt).templTab.add((*ctxt).templNr as usize) = ptr::null_mut();
        }
    }
}

/// Report a template-recursion guard (upstream transform.c
/// xsltApplySequenceConstructor / xsltApplyXSLTTemplate): the context line
/// and the two-line diagnostic through xsltTransformError, the
/// Templates:/Variables: debug dump (extra.c xsltDebug), then
/// XSLT_STATE_STOPPED — the transformation ends with no further output
/// (php bug71571_a / bug71571_b).
///
/// `depth_guard` selects the message (maxTemplateDepth vs maxTemplateVars);
/// `node` is the stylesheet node attributed to the error (the current
/// instruction for the depth guard, the instantiated template's first
/// content node for the variable guard).
///
/// # SAFETY
///
/// - `ctxt` and `node` must be valid pointers.
unsafe fn report_template_recursion(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    depth_guard: bool,
) {
    unsafe {
        let limit = if depth_guard {
            (*ctxt).maxTemplateDepth
        } else {
            (*ctxt).maxTemplateVars
        };
        let text = if depth_guard {
            format!(
                "xsltApplySequenceConstructor: A potential infinite template recursion was detected.\nYou can adjust $maxTemplateDepth in order to raise the maximum number of nested template calls and variables/params (currently set to {}).\n",
                limit
            )
        } else {
            format!(
                "xsltApplyXSLTTemplate: A potential infinite template recursion was detected.\nYou can adjust $maxTemplateVars in order to raise the maximum number of variables/params (currently set to {}).\n",
                limit
            )
        };
        let Ok(msg) = std::ffi::CString::new(text) else {
            return;
        };
        crate::xslt::errors::xsltTransformError(ctxt, ptr::null_mut(), node, msg.as_ptr());
        crate::abi::exports_xslt_exec::xsltDebug(
            ctxt,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        );
        (*ctxt).state = XSLT_STATE_STOPPED;
    }
}

/// Apply templates to a single node in the given mode.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn apply_templates_to_node(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    mode: *const xmlChar,
) -> c_int {
    let style = (*ctxt).style;
    if style.is_null() {
        return -1;
    }
    let templ = crate::xslt::templates::xsltFindTemplate(style, node, mode);
    if templ.is_null() {
        // Built-in template rules (XSLT 1.0 §5.8):
        // - For root/document: apply templates to children.
        // - For elements: apply templates to children.
        // - For text/attribute: copy the text.
        // - For comments/PIs: do nothing.
        let typ = (*node).type_;
        if typ == XML_TEXT_NODE as c_int
            || typ == XML_CDATA_SECTION_NODE as c_int
            || typ == XML_ATTRIBUTE_NODE as c_int
        {
            let content = node_get_content(node);
            if !content.is_null() {
                append_text_node(ctxt, content);
                libc::free(content as *mut libc::c_void);
            }
        } else if typ == XML_ELEMENT_NODE as c_int
            || typ == XML_DOCUMENT_NODE as c_int
            || typ == XML_HTML_DOCUMENT_NODE as c_int
        {
            // Apply templates to children.
            apply_templates_to_children(ctxt, node, mode);
        }
        return 0;
    }
    // UPSTREAM-PARITY (transform.c xsltApplyXSLTTemplate): the template is
    // pushed onto the template stack (the recursion dump lists it) before
    // the recursion guards run.
    template_stack_push(ctxt, templ);
    (*ctxt).depth += 1;
    // Check recursion depth (php bug71571_a): stop once the maximum of
    // nested templates is exceeded, report, dump, and stop the transform.
    if (*ctxt).depth > (*ctxt).maxTemplateDepth {
        report_template_recursion(ctxt, node, true);
        (*ctxt).depth -= 1;
        template_stack_pop(ctxt);
        return 0;
    }
    if (*ctxt).varsNr >= (*ctxt).maxTemplateVars {
        let err_node = if (*templ).content.is_null() {
            node
        } else {
            (*templ).content
        };
        report_template_recursion(ctxt, err_node, false);
        (*ctxt).depth -= 1;
        template_stack_pop(ctxt);
        return 0;
    }
    (*ctxt).templ = templ;
    (*ctxt).node = node;
    if !(*ctxt).xpathCtxt.is_null() {
        (*(*ctxt).xpathCtxt).contextSize = 1;
        (*(*ctxt).xpathCtxt).proximityPosition = 1;
    }
    execute_content(ctxt, (*templ).content);
    (*ctxt).depth -= 1;
    template_stack_pop(ctxt);
    (*ctxt).templ = ptr::null_mut();
    0
}

/// Apply templates to all children of a node.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn apply_templates_to_children(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    mode: *const xmlChar,
) -> c_int {
    // Collect the children in document order.
    let mut children: Vec<*mut _xmlNode> = Vec::new();
    let mut child = (*node).children;
    while !child.is_null() {
        children.push(child);
        child = (*child).next;
    }
    // Sort if xsl:sort children are present on the apply-templates
    // instruction (handled by the caller via sort handling).
    let size = children.len();
    if !(*ctxt).xpathCtxt.is_null() {
        (*(*ctxt).xpathCtxt).contextSize = size as c_int;
    }
    for (i, node) in children.iter().enumerate() {
        (*ctxt).node = *node;
        if !(*ctxt).xpathCtxt.is_null() {
            (*(*ctxt).xpathCtxt).proximityPosition = (i + 1) as c_int;
        }
        apply_templates_to_node(ctxt, *node, mode);
    }
    0
}

/// Execute the content of a template (a list of nodes).
///
/// # SAFETY
///
/// - All pointers must be valid.
pub unsafe fn execute_content(ctxt: *mut _xsltTransformContext, content: *mut _xmlNode) -> c_int {
    let mut cur = content;
    while !cur.is_null() {
        // UPSTREAM-PARITY (transform.c xsltApplySequenceConstructor): the
        // instruction loop stops as soon as the context leaves the OK
        // state (an XPath failure sets STOPPED, a hard error sets ERROR).
        if (*ctxt).state == XSLT_STATE_ERROR || (*ctxt).state == XSLT_STATE_STOPPED {
            return -1;
        }
        let next = (*cur).next;
        xsltProcessInstruction(ctxt, cur);
        cur = next;
    }
    0
}

/// Process a single instruction node.
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context.
/// - `inst` must be a valid instruction node.
pub unsafe fn xsltProcessInstruction(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) -> c_int {
    if ctxt.is_null() || inst.is_null() {
        return -1;
    }
    let typ = (*inst).type_;
    // UPSTREAM-PARITY: the transform context tracks the current instruction
    // (transform.c xsltProcessOneNode); XPath evaluation and error reporting
    // use it for namespace scope and diagnostics.
    (*ctxt).inst = inst;
    match typ {
        t if t == XML_TEXT_NODE as c_int || t == XML_CDATA_SECTION_NODE as c_int => {
            // Literal text: copy to the result.
            if !(*inst).content.is_null() {
                append_text_node(ctxt, (*inst).content);
            }
            0
        }
        t if t == XML_COMMENT_NODE as c_int => {
            // Literal comment: copy to the result.
            if !(*inst).content.is_null() {
                append_comment_node(ctxt, (*inst).content);
            }
            0
        }
        t if t == XML_PI_NODE as c_int => {
            // Literal PI: copy to the result.
            if !(*inst).name.is_null() {
                let content = if (*inst).content.is_null() {
                    ptr::null()
                } else {
                    (*inst).content
                };
                append_pi_node(ctxt, (*inst).name, content);
            }
            0
        }
        t if t == XML_ELEMENT_NODE as c_int => {
            if is_xslt_namespace(inst) {
                process_xslt_instruction(ctxt, inst);
            } else {
                // UPSTREAM-PARITY (transform.c xsltProcessOneNode): an
                // element whose namespace is a REGISTERED extension
                // namespace is an extension-element instruction, NOT a
                // literal result element — it dispatches to the module's
                // transform handler (xsltDocumentElem for the built-in
                // saxon:output / xalan:write / xt:document extras; php
                // bug54446). exsl:document is dispatched natively.
                let ns = get_element_ns(inst);
                if let Some(ref ns_uri) = ns {
                    if ns_uri == crate::exslt::EXSLT_NS_COMMON
                        && get_element_name(inst).as_deref() == Some("document")
                    {
                        process_exsl_document(ctxt, inst);
                        return 0;
                    }
                    let ns_c = str_to_cstr(ns_uri);
                    let ns_ptr = ns_c.as_ptr() as *const xmlChar;
                    if !(*inst).name.is_null() {
                        // Per-context extension-element registration
                        // (xsltRegisterExtElement).
                        let ctx_h =
                            crate::xslt::extensions::xsltFindExtElement(ctxt, (*inst).name, ns_ptr);
                        if !ctx_h.is_null() {
                            // UPSTREAM-PARITY (transform.c xsltProcessOneNode /
                            // xsltExtElementPreCompTest): the registered
                            // xsltTransformFunction is invoked with the
                            // transform context, the CURRENT context node
                            // (ctxt->node), the extension-element instance,
                            // and NULL for the precomputed data (per-context
                            // registrations never carry a comp block).
                            let func: crate::abi::exports_xslt_compile::xsltTransformFunction =
                                core::mem::transmute(ctx_h);
                            func(ctxt, (*ctxt).node, inst, ptr::null_mut());
                            return 0;
                        }
                        // Global module-element table
                        // (xsltRegisterExtModuleElement); the built-in
                        // extras (saxon:output etc.) land here via
                        // xsltRegisterAllExtras -> xsltInit.
                        if let Some(handler) =
                            crate::abi::exports_xslt_ext::xsltExtModuleElementLookup(
                                (*inst).name,
                                ns_ptr,
                            )
                        {
                            handler(ctxt, (*ctxt).node, inst, ptr::null_mut());
                            return 0;
                        }
                    }
                }
                // Literal result element: create the element and process
                // its content.
                process_literal_element(ctxt, inst);
            }
            0
        }
        _ => 0,
    }
}

/// Process an XSLT instruction element.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_xslt_instruction(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) -> c_int {
    let name = get_element_name(inst);
    match name.as_deref() {
        Some("apply-templates") => {
            process_apply_templates(ctxt, inst);
        }
        Some("call-template") => {
            process_call_template(ctxt, inst);
        }
        Some("apply-imports") => {
            process_apply_imports(ctxt, inst);
        }
        Some("for-each") => {
            process_for_each(ctxt, inst);
        }
        Some("value-of") => {
            process_value_of(ctxt, inst);
        }
        Some("copy-of") => {
            process_copy_of(ctxt, inst);
        }
        Some("copy") => {
            process_copy(ctxt, inst);
        }
        Some("element") => {
            process_element(ctxt, inst);
        }
        Some("attribute") => {
            process_attribute(ctxt, inst);
        }
        Some("text") => {
            process_text(ctxt, inst);
        }
        Some("comment") => {
            process_comment(ctxt, inst);
        }
        Some("processing-instruction") => {
            process_pi(ctxt, inst);
        }
        Some("number") => {
            process_number(ctxt, inst);
        }
        Some("choose") => {
            process_choose(ctxt, inst);
        }
        Some("when") | Some("otherwise") => {
            // Only valid inside xsl:choose; ignored here.
        }
        Some("if") => {
            process_if(ctxt, inst);
        }
        Some("variable") => {
            process_variable(ctxt, inst);
        }
        Some("param") => {
            process_param(ctxt, inst);
        }
        Some("with-param") => {
            // Only valid inside call-template/apply-templates; ignored.
        }
        Some("sort") => {
            // Only valid inside for-each/apply-templates; ignored.
        }
        Some("message") => {
            process_message(ctxt, inst);
        }
        Some("fallback") => {
            // Only used when an extension element is unavailable.
        }
        Some("output")
        | Some("decimal-format")
        | Some("namespace-alias")
        | Some("attribute-set")
        | Some("key")
        | Some("strip-space")
        | Some("preserve-space")
        | Some("import")
        | Some("include")
        | Some("stylesheet")
        | Some("transform") => {
            // Top-level elements: not instructions, ignored in content.
        }
        _ => {
            // Unknown element: may be an EXSLT extension element or a
            // registered extension element.
            let ns = get_element_ns(inst);
            if let Some(ns_uri) = ns {
                // exsl:document — write the element content to a file.
                if ns_uri == crate::exslt::EXSLT_NS_COMMON
                    && get_element_name(inst).as_deref() == Some("document")
                {
                    process_exsl_document(ctxt, inst);
                    return 0;
                }
                // Check for a registered extension element.
                let name_ptr = (*inst).name;
                let ns_cstr = str_to_cstr(&ns_uri);
                let found = crate::xslt::extensions::xsltFindExtElement(
                    ctxt,
                    name_ptr,
                    ns_cstr.as_ptr() as *const xmlChar,
                );
                if !found.is_null() {
                    // UPSTREAM-PARITY: dispatch a registered extension element
                    // (this branch is reached for non-XSLT-namespace unknown
                    // elements routed through process_xslt_instruction).
                    let func: crate::abi::exports_xslt_compile::xsltTransformFunction =
                        core::mem::transmute(found);
                    func(ctxt, (*ctxt).node, inst, ptr::null_mut());
                    return 0;
                }
            }
            // Unknown instruction: process fallback children or ignore.
        }
    }
    0
}

/// Convert a Rust string to a NUL-terminated byte vec.
fn str_to_cstr(s: &str) -> Vec<u8> {
    let mut v = s.as_bytes().to_vec();
    v.push(0);
    v
}

/// Process the EXSLT `<exsl:document href="...">` extension element:
/// instantiate the element's content into a separate result document and
/// write it to the file named by the `href` attribute.
///
/// # UPSTREAM-PARITY
///
/// Upstream libexslt (common.c `exsltDocumentElem`) creates a new document
/// whose root element copies the attributes of the exsl:document element
/// (minus href), evaluates the content into it, and saves it to the
/// resolved href (relative to the stylesheet's base URI).
///
/// # SAFETY
///
/// - All pointers must be valid.
unsafe fn process_exsl_document(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let href = get_prop(inst, c"href".as_ptr() as *const xmlChar);
    if href.is_null() {
        crate::xslt::errors::xsltTransformError(
            ctxt,
            (*ctxt).style,
            inst,
            c"exsl:document: missing href attribute".as_ptr() as *const c_char,
        );
        return;
    }
    // Build the fragment document.
    let frag = libc::calloc(1, core::mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
    if frag.is_null() {
        libc::free(href as *mut libc::c_void);
        return;
    }
    (*frag).type_ = XML_DOCUMENT_NODE as c_int;
    (*frag).doc = frag;
    let saved_insert = (*ctxt).insert;
    let saved_output = (*ctxt).output;
    (*ctxt).insert = frag as *mut _xmlNode;
    (*ctxt).output = frag;
    execute_content(ctxt, (*inst).children);
    (*ctxt).insert = saved_insert;
    (*ctxt).output = saved_output;

    // Write the fragment to the file.
    let fname = crate::abi::versioning::c_str_to_bytes(href as *const c_char);
    if let Some(name) = fname {
        let path = String::from_utf8_lossy(name);
        let cpath = str_to_cstr(&path);
        let out = libc::fopen(
            cpath.as_ptr() as *const c_char,
            c"wb".as_ptr() as *const c_char,
        );
        if !out.is_null() {
            let buf = crate::xml::io::buf_create(-1);
            if !buf.is_null() {
                crate::xml::tree::doc_dump(buf, frag);
                let content = crate::xml::io::buf_content(buf);
                let len = crate::xml::io::buf_length(buf);
                if !content.is_null() && len > 0 {
                    libc::fwrite(content as *const libc::c_void, 1, len as usize, out);
                }
                crate::xml::io::buf_free(buf);
            }
            libc::fclose(out);
        }
    }
    libc::free(href as *mut libc::c_void);
    free_doc(frag);
}

/// Evaluate an XPath expression in the current context.
/// Returns an XPath object (caller frees) or NULL on error.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn eval_xpath(
    ctxt: *mut _xsltTransformContext,
    expr: *const xmlChar,
) -> *mut _xmlXPathObject {
    if ctxt.is_null() || expr.is_null() {
        return ptr::null_mut();
    }
    let xpath_ctxt = (*ctxt).xpathCtxt;
    if xpath_ctxt.is_null() {
        return ptr::null_mut();
    }
    // Set the context node and position on both the C ABI struct and the
    // internal Rust XPathContext (which is what the evaluator actually
    // reads via the `extra` field). contextSize/proximityPosition live on
    // the XPath context (UPSTREAM-PARITY: libxml2 xpath.h), so the mirror
    // copies from there.
    (*xpath_ctxt).node = (*ctxt).node;
    if !(*ctxt).document.is_null() {
        (*xpath_ctxt).doc = (*(*ctxt).document).doc;
    }
    let internal = (*xpath_ctxt).extra as *mut crate::xml::xpath::context::XPathContext;
    if !internal.is_null() {
        (*internal).context_node = (*ctxt).node;
        if !(*ctxt).document.is_null() {
            (*internal).document = (*(*ctxt).document).doc;
        }
        (*internal).context_size = (*xpath_ctxt).contextSize;
        (*internal).context_position = (*xpath_ctxt).proximityPosition;
        (*internal).proximity_position = (*xpath_ctxt).proximityPosition;
        // UPSTREAM-PARITY (transform.c xsltEvalXPathString): the in-scope
        // namespace declarations of the current instruction are registered
        // on the XPath context, so prefixed extension-function names resolve
        // and unknown ones report "Unregistered function" instead of
        // "Undefined namespace prefix".
        if !(*ctxt).inst.is_null() {
            register_in_scope_ns(internal, (*ctxt).inst);
        }
    }
    xmlXPathEvalExpression(expr, xpath_ctxt)
}

/// Register the in-scope namespace declarations of `node` (its own nsDef
/// chain plus every ancestor's) on the internal XPath context.
///
/// # SAFETY
///
/// - `internal` must be a valid XPathContext pointer.
/// - `node` must be a valid node pointer.
pub(crate) unsafe fn register_in_scope_ns(
    internal: *mut crate::xml::xpath::context::XPathContext,
    node: *mut _xmlNode,
) {
    unsafe {
        let mut cur = node;
        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        while !cur.is_null() {
            let mut ns = (*cur).nsDef;
            while !ns.is_null() {
                let prefix = if (*ns).prefix.is_null() {
                    String::new()
                } else {
                    let l = libc::strlen((*ns).prefix as *const libc::c_char);
                    String::from_utf8_lossy(core::slice::from_raw_parts((*ns).prefix, l))
                        .into_owned()
                };
                if !seen.contains(&prefix) && !(*ns).href.is_null() {
                    let l = libc::strlen((*ns).href as *const libc::c_char);
                    let href = String::from_utf8_lossy(core::slice::from_raw_parts((*ns).href, l))
                        .into_owned();
                    (*internal).register_namespace(&prefix, &href);
                    seen.insert(prefix);
                }
                ns = (*ns).next;
            }
            cur = (*cur).parent;
        }
    }
}

/// Report an XPath evaluation failure the way upstream xsltproc does and
/// fail the transformation (the caller's stylesheet yields no result and
/// xsltproc exits 10).
///
/// ```text
/// XPath error : Unregistered function: str:upper-case
/// runtime error: file exsl.xsl line 17 element value-of
/// XPath evaluation returned no result.
/// ```
///
/// # SAFETY
///
/// - `ctxt` / `inst` must be valid pointers.
pub(crate) unsafe fn report_xpath_eval_failure(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
    elem_name: &str,
) {
    unsafe {
        // UPSTREAM-PARITY (transform.c xsltValueOf / xsltCopyOf): an XPath
        // evaluation failure is reported through xsltTransformError — the
        // context line ("runtime error: file ... element value-of") and the
        // message are emitted as SEPARATE handler calls, so library
        // consumers (lxml's _receiveXSLTError error_log) record the
        // "runtime error, element '...'" entry before "XPath evaluation
        // returned no result.". The XPath diagnostic itself was already
        // delivered by the evaluation path (raise_xpath_error → the XPath
        // context's error handler / generic channel), so it is not repeated
        // here. The transformation stops (XSLT_STATE_STOPPED, not ERROR —
        // xsltproc exits 10). The element name for the context line comes
        // from the instruction node itself (upstream xsltPrintErrorContext).
        let _ = elem_name;
        let style = if ctxt.is_null() {
            ptr::null_mut()
        } else {
            (*ctxt).style
        };
        crate::xslt::errors::xsltTransformError(
            ctxt,
            style,
            inst,
            c"XPath evaluation returned no result.\n".as_ptr() as *const c_char,
        );
        (*ctxt).state = XSLT_STATE_STOPPED;
    }
}

/// Process `xsl:apply-templates`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_apply_templates(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) {
    // mode attribute.
    let mode = get_prop(inst, c"mode".as_ptr() as *const xmlChar);
    // select attribute (default: all children).
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    // with-param children.
    let params = collect_with_params(ctxt, inst);

    let obj = if !select.is_null() {
        eval_xpath(ctxt, select)
    } else {
        // Default select: "node()" — all children.
        // Build a node-set from children.
        build_child_node_set(ctxt)
    };
    if !select.is_null() {
        libc::free(select as *mut libc::c_void);
    }
    if obj.is_null() {
        if !mode.is_null() {
            libc::free(mode as *mut libc::c_void);
        }
        report_xpath_eval_failure(ctxt, inst, "apply-templates");
        return;
    }

    // Extract the node-set.
    let nodes = if (*obj).type_ == xmlXPathObjectType::XPATH_NODESET as c_int {
        (*obj).nodesetval as *mut _xmlNodeSet
    } else {
        ptr::null_mut()
    };

    if !nodes.is_null() && (*nodes).nodeNr > 0 {
        // Check for xsl:sort children.
        let sort = find_sort_children(ctxt, inst);
        let mut node_ptrs: Vec<*mut _xmlNode> = Vec::new();
        let mut i = 0;
        while i < (*nodes).nodeNr {
            let n = *(*nodes).nodeTab.offset(i as isize);
            if !n.is_null() {
                node_ptrs.push(n);
            }
            i += 1;
        }
        // Sort if requested.
        if !sort.is_null() {
            let sorted = libc::calloc(1, core::mem::size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
            if !sorted.is_null() {
                (*sorted).nodeNr = node_ptrs.len() as c_int;
                (*sorted).nodeMax = node_ptrs.len() as c_int;
                let tab = libc::malloc(node_ptrs.len() * core::mem::size_of::<*mut _xmlNode>())
                    as *mut *mut _xmlNode;
                (*sorted).nodeTab = tab;
                for (idx, n) in node_ptrs.iter().enumerate() {
                    if !tab.is_null() {
                        *tab.add(idx) = *n;
                    }
                }
                crate::xslt::sorting::xsltSortNodeSet(ctxt, sorted, sort);
                // Apply templates in sorted order.
                let mut k = 0;
                while k < (*sorted).nodeNr {
                    // UPSTREAM-PARITY (transform.c xsltApplyTemplates): stop
                    // once the context leaves the OK state.
                    if (*ctxt).state == XSLT_STATE_ERROR || (*ctxt).state == XSLT_STATE_STOPPED {
                        break;
                    }
                    let n = *(*sorted).nodeTab.offset(k as isize);
                    if !n.is_null() {
                        (*ctxt).node = n;
                        if !(*ctxt).xpathCtxt.is_null() {
                            (*(*ctxt).xpathCtxt).contextSize = (*sorted).nodeNr;
                            (*(*ctxt).xpathCtxt).proximityPosition = k + 1;
                        }
                        apply_templates_with_params(ctxt, n, mode, params);
                    }
                    k += 1;
                }
                libc::free((*sorted).nodeTab as *mut libc::c_void);
                libc::free(sorted as *mut libc::c_void);
            }
        } else {
            if !(*ctxt).xpathCtxt.is_null() {
                (*(*ctxt).xpathCtxt).contextSize = node_ptrs.len() as c_int;
            }
            for (i, n) in node_ptrs.iter().enumerate() {
                // UPSTREAM-PARITY (transform.c xsltApplyTemplates): stop
                // once the context leaves the OK state.
                if (*ctxt).state == XSLT_STATE_ERROR || (*ctxt).state == XSLT_STATE_STOPPED {
                    break;
                }
                if !n.is_null() {
                    (*ctxt).node = *n;
                    if !(*ctxt).xpathCtxt.is_null() {
                        (*(*ctxt).xpathCtxt).proximityPosition = (i + 1) as c_int;
                    }
                    apply_templates_with_params(ctxt, *n, mode, params);
                }
            }
        }
    }

    if !mode.is_null() {
        libc::free(mode as *mut libc::c_void);
    }
    xmlXPathFreeObject(obj);
}

/// Apply templates to a node, passing parameters.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn apply_templates_with_params(
    ctxt: *mut _xsltTransformContext,
    node: *mut _xmlNode,
    mode: *const xmlChar,
    params: *mut _xsltStackElem,
) {
    // Push the params onto the parameter stack.
    let mut p = params;
    while !p.is_null() {
        crate::xslt::parameters::xsltPushParam(ctxt, p);
        p = (*p).next;
    }
    apply_templates_to_node(ctxt, node, mode);
    // Pop the params.
    let mut p = params;
    while !p.is_null() {
        crate::xslt::parameters::xsltPopParam(ctxt);
        p = (*p).next;
    }
}

/// Build a node-set from the children of the current node.
///
/// # SAFETY
///
/// - `ctxt` must be valid.
pub(crate) unsafe fn build_child_node_set(
    ctxt: *mut _xsltTransformContext,
) -> *mut _xmlXPathObject {
    let ns = xmlXPathNodeSetCreate(ptr::null_mut());
    if ns.is_null() {
        return ptr::null_mut();
    }
    let obj = xmlMalloc_zero_obj();
    if obj.is_null() {
        libc::free(ns as *mut libc::c_void);
        return ptr::null_mut();
    }
    (*obj).type_ = xmlXPathObjectType::XPATH_NODESET as c_int;
    (*obj).nodesetval = ns as *mut c_void;
    let node = (*ctxt).node;
    if !node.is_null() {
        let mut child = (*node).children;
        while !child.is_null() {
            append_to_node_set(ns, child);
            child = (*child).next;
        }
    }
    obj
}

/// Allocate a zeroed XPath object.
unsafe fn xmlMalloc_zero_obj() -> *mut _xmlXPathObject {
    libc::calloc(1, core::mem::size_of::<_xmlXPathObject>()) as *mut _xmlXPathObject
}

/// Append a node to a node-set.
///
/// # SAFETY
///
/// - All pointers must be valid.
unsafe fn append_to_node_set(ns: *mut _xmlNodeSet, node: *mut _xmlNode) {
    if ns.is_null() || node.is_null() {
        return;
    }
    // Deduplicate.
    let mut i = 0;
    while i < (*ns).nodeNr {
        if *(*ns).nodeTab.offset(i as isize) == node {
            return;
        }
        i += 1;
    }
    if (*ns).nodeNr >= (*ns).nodeMax {
        let new_max = if (*ns).nodeMax == 0 {
            8
        } else {
            (*ns).nodeMax * 2
        };
        let new_tab = libc::realloc(
            (*ns).nodeTab as *mut libc::c_void,
            (new_max as usize) * core::mem::size_of::<*mut _xmlNode>(),
        ) as *mut *mut _xmlNode;
        if new_tab.is_null() {
            return;
        }
        (*ns).nodeTab = new_tab;
        (*ns).nodeMax = new_max;
    }
    *(*ns).nodeTab.offset((*ns).nodeNr as isize) = node;
    (*ns).nodeNr += 1;
}

/// Collect the `xsl:with-param` children of an instruction.
///
/// Returns a linked list of evaluated parameter stack elements.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn collect_with_params(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) -> *mut _xsltStackElem {
    let mut head: *mut _xsltStackElem = ptr::null_mut();
    let mut tail: *mut _xsltStackElem = ptr::null_mut();
    let mut child = (*inst).children;
    while !child.is_null() {
        let next = (*child).next;
        if is_xslt_element(child, "with-param") {
            let param = evaluate_with_param(ctxt, child);
            if !param.is_null() {
                (*param).next = ptr::null_mut();
                if tail.is_null() {
                    head = param;
                    tail = param;
                } else {
                    (*tail).next = param;
                    tail = param;
                }
            }
        }
        child = next;
    }
    head
}

/// Evaluate a single `xsl:with-param` element.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn evaluate_with_param(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) -> *mut _xsltStackElem {
    let name = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name.is_null() {
        return ptr::null_mut();
    }
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    let param = libc::calloc(1, core::mem::size_of::<_xsltStackElem>()) as *mut _xsltStackElem;
    if param.is_null() {
        libc::free(name as *mut libc::c_void);
        if !select.is_null() {
            libc::free(select as *mut libc::c_void);
        }
        return ptr::null_mut();
    }
    (*param).name = name;
    (*param).flags = 2 | 4; // PARAM | INTERNAL
                            // comp type marker for the xsltDebug variable dump (extra.c reads
                            // cur->comp->type): a with-param prints its bare name (not PARAM/VARIABLE).
    (*param).comp = &XSLT_COMP_TYPE_WITHPARAM as *const c_int as *mut c_void;
    if !select.is_null() {
        let obj = eval_xpath(ctxt, select);
        if !obj.is_null() {
            (*param).value = obj;
        } else {
            report_xpath_eval_failure(ctxt, inst, "with-param");
            libc::free(select as *mut libc::c_void);
            libc::free(param as *mut libc::c_void);
            return ptr::null_mut();
        }
        libc::free(select as *mut libc::c_void);
    } else {
        // Inline content: result tree fragment.
        let value = eval_content_fragment(ctxt, (*inst).children);
        if !value.is_null() {
            (*param).value = value;
        }
    }
    param
}

/// Evaluate inline content into a result tree fragment object.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn eval_content_fragment(
    ctxt: *mut _xsltTransformContext,
    content: *mut _xmlNode,
) -> *mut _xmlXPathObject {
    let frag = libc::calloc(1, core::mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
    if frag.is_null() {
        return ptr::null_mut();
    }
    (*frag).type_ = XML_DOCUMENT_NODE as c_int;
    (*frag).doc = frag;
    // Save the insert point and redirect into the fragment.
    let saved_insert = (*ctxt).insert;
    let saved_output = (*ctxt).output;
    (*ctxt).insert = frag as *mut _xmlNode;
    (*ctxt).output = frag;
    execute_content(ctxt, content);
    (*ctxt).insert = saved_insert;
    (*ctxt).output = saved_output;

    let obj = xmlMalloc_zero_obj();
    if obj.is_null() {
        free_doc(frag);
        return ptr::null_mut();
    }
    (*obj).type_ = xmlXPathObjectType::XPATH_XSLT_TREE as c_int;
    (*obj).nodesetval = frag as *mut c_void;
    obj
}

/// Process `xsl:call-template`.
///
/// # SAFETY
///
/// - All pointers must be valid.
#[allow(clippy::while_immutable_condition)]
pub(crate) unsafe fn process_call_template(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name.is_null() {
        return;
    }
    let style = (*ctxt).style;
    let templ = crate::xslt::templates::xsltLookupTemplate(style, name);
    libc::free(name as *mut libc::c_void);
    if templ.is_null() {
        return;
    }
    // UPSTREAM-PARITY (transform.c xsltApplyXSLTTemplate): push the
    // template before the recursion guards run so the debug dump lists it.
    template_stack_push(ctxt, templ);
    (*ctxt).depth += 1;
    // Depth guard (php bug71571_a): report + dump + STOPPED instead of the
    // previous silent early return.
    if (*ctxt).depth > (*ctxt).maxTemplateDepth {
        report_template_recursion(ctxt, inst, true);
        (*ctxt).depth -= 1;
        template_stack_pop(ctxt);
        return;
    }
    // UPSTREAM-PARITY (templates.c xsltApplyTemplate): remember the variable
    // stack depth, push the with-params, instantiate the template (whose
    // xsl:param defaults may push MORE variables on top), then pop back to
    // the saved depth — never a fixed count. A fixed count misaligns the
    // stack whenever a default parameter was materialized during the call
    // and leaves stale bindings behind (R-000158).
    let old_vars_nr = (*ctxt).varsNr;
    let params = collect_with_params(ctxt, inst);
    // Snapshot the with-param list BEFORE pushing: xsltPushVariable rewires
    // (*var).next into the variable-stack chain, clobbering the list links.
    let mut to_push: Vec<*mut _xsltStackElem> = Vec::new();
    let mut p = params;
    while !p.is_null() {
        to_push.push(p);
        p = (*p).next;
    }
    for param in to_push {
        crate::xslt::parameters::xsltPushParam(ctxt, param);
    }
    // Variable-count guard (php bug71571_b): the caller's with-params are on
    // the stack by now; report against the template's first content node
    // (its xsl:param) like upstream's xsltApplyXSLTTemplate error.
    if (*ctxt).varsNr >= (*ctxt).maxTemplateVars {
        let err_node = if (*templ).content.is_null() {
            inst
        } else {
            (*templ).content
        };
        report_template_recursion(ctxt, err_node, false);
        (*ctxt).depth -= 1;
        template_stack_pop(ctxt);
        while (*ctxt).varsNr > old_vars_nr {
            crate::xslt::parameters::xsltPopParam(ctxt);
        }
        return;
    }
    let saved_templ = (*ctxt).templ;
    (*ctxt).templ = templ;
    execute_content(ctxt, (*templ).content);
    (*ctxt).templ = saved_templ;
    while (*ctxt).varsNr > old_vars_nr {
        crate::xslt::parameters::xsltPopParam(ctxt);
    }
    (*ctxt).depth -= 1;
    template_stack_pop(ctxt);
}

/// Process `xsl:apply-imports`.
///
/// XSLT 1.0 §5.6: applies the next template in import precedence order
/// that matches the current node, skipping templates at the same or
/// higher import precedence as the current template.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_apply_imports(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let _ = inst;
    let style = (*ctxt).style;
    let node = (*ctxt).node;
    let current_templ = (*ctxt).templ;
    if style.is_null() || node.is_null() || current_templ.is_null() {
        return;
    }
    // The current template's import depth; imported templates have HIGHER
    // depth values. apply-imports considers templates with depth strictly
    // greater than the current template's depth. (Depth is carried in
    // `position`, candidate-internal; upstream tracks it via the stylesheet
    // import chain.)
    let current_depth = (*current_templ).position;
    let mode = (*current_templ).mode;

    let mut best: *mut _xsltTemplate = ptr::null_mut();
    let mut best_priority: f32 = f32::NEG_INFINITY;
    let mut best_depth: c_int = -1;

    let mut templ = (*style).templates;
    while !templ.is_null() {
        // Only templates imported more deeply than the current one.
        if (*templ).position <= current_depth {
            templ = (*templ).next;
            continue;
        }
        // Mode must match.
        if !(*templ).mode.is_null() {
            if mode.is_null()
                || libc::strcmp(
                    (*templ).mode as *const libc::c_char,
                    mode as *const libc::c_char,
                ) != 0
            {
                templ = (*templ).next;
                continue;
            }
        } else if !mode.is_null() {
            templ = (*templ).next;
            continue;
        }
        // Pattern must match. The compiled pattern is carried in `params`
        // (candidate-internal; see xsltAddTemplate).
        let pattern_ptr = (*templ).params as *mut crate::xslt::patterns::_xsltPattern;
        if pattern_ptr.is_null() {
            templ = (*templ).next;
            continue;
        }
        if crate::xslt::patterns::xsltTestPattern(ctxt, pattern_ptr, node) == 0 {
            templ = (*templ).next;
            continue;
        }
        // Priority: explicit or default.
        let priority = (*templ).priority;
        if priority > best_priority || (priority == best_priority && (*templ).position > best_depth)
        {
            best = templ;
            best_priority = priority;
            best_depth = (*templ).position;
        }
        templ = (*templ).next;
    }

    if !best.is_null() {
        template_stack_push(ctxt, best);
        (*ctxt).depth += 1;
        if (*ctxt).depth > (*ctxt).maxTemplateDepth {
            report_template_recursion(ctxt, inst, true);
            (*ctxt).depth -= 1;
            template_stack_pop(ctxt);
            return;
        }
        if (*ctxt).varsNr >= (*ctxt).maxTemplateVars {
            let err_node = if (*best).content.is_null() {
                inst
            } else {
                (*best).content
            };
            report_template_recursion(ctxt, err_node, false);
            (*ctxt).depth -= 1;
            template_stack_pop(ctxt);
            return;
        }
        let saved_templ = (*ctxt).templ;
        (*ctxt).templ = best;
        execute_content(ctxt, (*best).content);
        (*ctxt).templ = saved_templ;
        (*ctxt).depth -= 1;
        template_stack_pop(ctxt);
    }
}

/// Process `xsl:for-each`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_for_each(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    if select.is_null() {
        return;
    }
    let obj = eval_xpath(ctxt, select);
    libc::free(select as *mut libc::c_void);
    if obj.is_null() {
        report_xpath_eval_failure(ctxt, inst, "for-each");
        return;
    }
    if (*obj).type_ != xmlXPathObjectType::XPATH_NODESET as c_int {
        xmlXPathFreeObject(obj);
        return;
    }
    let nodes = (*obj).nodesetval as *mut _xmlNodeSet;
    if nodes.is_null() || (*nodes).nodeNr == 0 {
        xmlXPathFreeObject(obj);
        return;
    }
    // Check for xsl:sort children.
    let sort = find_sort_children(ctxt, inst);
    // Save the current node list state (contextSize/proximityPosition live
    // on the XPath context; UPSTREAM-PARITY: xpath.h).
    let saved_node = (*ctxt).node;
    let xpath_ctxt = (*ctxt).xpathCtxt;
    let (saved_size, saved_pos) = if xpath_ctxt.is_null() {
        (0, 0)
    } else {
        ((*xpath_ctxt).contextSize, (*xpath_ctxt).proximityPosition)
    };

    let mut node_ptrs: Vec<*mut _xmlNode> = Vec::new();
    let mut i = 0;
    while i < (*nodes).nodeNr {
        let n = *(*nodes).nodeTab.offset(i as isize);
        if !n.is_null() {
            node_ptrs.push(n);
        }
        i += 1;
    }

    if !sort.is_null() {
        // Build a temporary node-set and sort it.
        let sorted = libc::calloc(1, core::mem::size_of::<_xmlNodeSet>()) as *mut _xmlNodeSet;
        if !sorted.is_null() {
            (*sorted).nodeNr = node_ptrs.len() as c_int;
            (*sorted).nodeMax = node_ptrs.len() as c_int;
            let tab = libc::malloc(node_ptrs.len() * core::mem::size_of::<*mut _xmlNode>())
                as *mut *mut _xmlNode;
            (*sorted).nodeTab = tab;
            for (idx, n) in node_ptrs.iter().enumerate() {
                if !tab.is_null() {
                    *tab.add(idx) = *n;
                }
            }
            crate::xslt::sorting::xsltSortNodeSet(ctxt, sorted, sort);
            if !xpath_ctxt.is_null() {
                (*xpath_ctxt).contextSize = (*sorted).nodeNr;
            }
            let mut k = 0;
            while k < (*sorted).nodeNr {
                // UPSTREAM-PARITY (transform.c xsltForEach): stop iterating
                // once the context leaves the OK state.
                if (*ctxt).state == XSLT_STATE_ERROR || (*ctxt).state == XSLT_STATE_STOPPED {
                    break;
                }
                let n = *(*sorted).nodeTab.offset(k as isize);
                if !n.is_null() {
                    (*ctxt).node = n;
                    if !xpath_ctxt.is_null() {
                        (*xpath_ctxt).proximityPosition = k + 1;
                    }
                    execute_content(ctxt, (*inst).children);
                }
                k += 1;
            }
            libc::free((*sorted).nodeTab as *mut libc::c_void);
            libc::free(sorted as *mut libc::c_void);
        }
    } else {
        if !xpath_ctxt.is_null() {
            (*xpath_ctxt).contextSize = node_ptrs.len() as c_int;
        }
        for (i, n) in node_ptrs.iter().enumerate() {
            // UPSTREAM-PARITY (transform.c xsltForEach): stop iterating
            // once the context leaves the OK state.
            if (*ctxt).state == XSLT_STATE_ERROR || (*ctxt).state == XSLT_STATE_STOPPED {
                break;
            }
            if !n.is_null() {
                (*ctxt).node = *n;
                if !xpath_ctxt.is_null() {
                    (*xpath_ctxt).proximityPosition = (i + 1) as c_int;
                }
                execute_content(ctxt, (*inst).children);
            }
        }
    }

    // Restore the current node state.
    (*ctxt).node = saved_node;
    if !xpath_ctxt.is_null() {
        (*xpath_ctxt).contextSize = saved_size;
        (*xpath_ctxt).proximityPosition = saved_pos;
    }
    xmlXPathFreeObject(obj);
}

/// Find the first `xsl:sort` child of an instruction and compile it.
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context.
/// - `inst` must be a valid node.
unsafe fn find_sort_children(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) -> *mut _xsltSort {
    if ctxt.is_null() || inst.is_null() {
        return ptr::null_mut();
    }
    let mut child = (*inst).children;
    while !child.is_null() {
        if is_xslt_element(child, "sort") {
            // Compile the sort from the instruction node, with the actual
            // stylesheet so xsltCompileSort can record it on the sort.
            let style = (*ctxt).style;
            let sort = crate::xslt::sorting::xsltCompileSort(style, child);
            return sort;
        }
        child = (*child).next;
    }
    ptr::null_mut()
}

/// Process `xsl:value-of`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_value_of(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    if select.is_null() {
        return;
    }
    let obj = eval_xpath(ctxt, select);
    libc::free(select as *mut libc::c_void);
    if obj.is_null() {
        // UPSTREAM-PARITY: an XPath evaluation failure in xsl:value-of is a
        // fatal transform error (xsltValueOf -> "XPath evaluation returned
        // no result.", exit 10).
        report_xpath_eval_failure(ctxt, inst, "value-of");
        return;
    }
    let strv = xmlXPathCastToString(obj);
    xmlXPathFreeObject(obj);
    if !strv.is_null() {
        // UPSTREAM-PARITY (transform.c xsltValueOf 1.1.45): the string value
        // is copied into the result only when it is non-empty
        // (`if (value[0] != 0)`); an empty value-of must NOT create an empty
        // text node, otherwise an otherwise-empty element would serialize
        // as `<out></out>` instead of the oracle's `<out/>`.
        if *strv != 0 {
            append_text_node(ctxt, strv);
        }
        libc::free(strv as *mut libc::c_void);
    }
}

/// Process `xsl:copy-of`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_copy_of(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    if select.is_null() {
        return;
    }
    let obj = eval_xpath(ctxt, select);
    libc::free(select as *mut libc::c_void);
    if obj.is_null() {
        report_xpath_eval_failure(ctxt, inst, "copy-of");
        return;
    }
    if (*obj).type_ == xmlXPathObjectType::XPATH_NODESET as c_int {
        let nodes = (*obj).nodesetval as *mut _xmlNodeSet;
        if !nodes.is_null() {
            let mut i = 0;
            while i < (*nodes).nodeNr {
                let n = *(*nodes).nodeTab.offset(i as isize);
                if !n.is_null() {
                    copy_node_deep(ctxt, n);
                }
                i += 1;
            }
        }
    } else if (*obj).type_ == xmlXPathObjectType::XPATH_XSLT_TREE as c_int {
        // Result tree fragment: copy the fragment's children.
        let frag = (*obj).nodesetval as *mut _xmlDoc;
        if !frag.is_null() {
            let mut child = (*frag).children;
            while !child.is_null() {
                let next = (*child).next;
                copy_node_deep(ctxt, child);
                child = next;
            }
        }
    } else {
        // Atomic value: copy as text. UPSTREAM-PARITY (transform.c
        // xsltCopyOf 1.1.45): the cast string is appended only when
        // non-empty (`if (value[0] != 0)`); an empty atomic copy-of must
        // not create an empty text node (same rule as xsltValueOf).
        let strv = xmlXPathCastToString(obj);
        if !strv.is_null() {
            if *strv != 0 {
                append_text_node(ctxt, strv);
            }
            libc::free(strv as *mut libc::c_void);
        }
    }
    xmlXPathFreeObject(obj);
}

/// Deep-copy a source node into the result tree.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn copy_node_deep(ctxt: *mut _xsltTransformContext, node: *mut _xmlNode) {
    if node.is_null() {
        return;
    }
    let typ = (*node).type_;
    if typ == XML_TEXT_NODE as c_int || typ == XML_CDATA_SECTION_NODE as c_int {
        if !(*node).content.is_null() {
            append_text_node(ctxt, (*node).content);
        }
    } else if typ == XML_COMMENT_NODE as c_int {
        if !(*node).content.is_null() {
            append_comment_node(ctxt, (*node).content);
        }
    } else if typ == XML_PI_NODE as c_int {
        if !(*node).name.is_null() {
            append_pi_node(ctxt, (*node).name, (*node).content);
        }
    } else if typ == XML_ELEMENT_NODE as c_int {
        // Create the element.
        let name = (*node).name;
        let new_elem = new_element_node(ctxt, name, (*node).ns);
        if new_elem.is_null() {
            return;
        }
        // Copy attributes.
        let mut prop = (*node).properties;
        while !prop.is_null() {
            let attr_name = (*prop).name;
            let attr_val = node_get_content((*prop).children);
            if !attr_name.is_null() && !attr_val.is_null() {
                set_prop(new_elem, attr_name, attr_val);
                libc::free(attr_val as *mut libc::c_void);
            }
            prop = (*prop).next;
        }
        // Recurse into children.
        let saved_insert = (*ctxt).insert;
        (*ctxt).insert = new_elem;
        let mut child = (*node).children;
        while !child.is_null() {
            let next = (*child).next;
            copy_node_deep(ctxt, child);
            child = next;
        }
        (*ctxt).insert = saved_insert;
    } else if typ == XML_DOCUMENT_NODE as c_int || typ == XML_HTML_DOCUMENT_NODE as c_int {
        // Document node: copy its children (the root element and any
        // top-level nodes). `xsl:copy-of select="document('')"` must emit
        // the stylesheet's root element (lxml test_xslt_document_*).
        let mut child = (*node).children;
        while !child.is_null() {
            let next = (*child).next;
            copy_node_deep(ctxt, child);
            child = next;
        }
    }
}

/// Create an element node in the result tree.
///
/// # SAFETY
///
/// - All pointers must be valid.
unsafe fn new_element_node(
    ctxt: *mut _xsltTransformContext,
    name: *const xmlChar,
    ns: *mut _xmlNs,
) -> *mut _xmlNode {
    let elem = new_node(ns, name);
    if elem.is_null() {
        return ptr::null_mut();
    }
    append_to_result(ctxt, elem);
    elem
}

/// Append a node to the result tree at the current insertion point.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn append_to_result(ctxt: *mut _xsltTransformContext, node: *mut _xmlNode) {
    let insert = (*ctxt).insert;
    if insert.is_null() {
        return;
    }
    // If the insert point is a document, add as a child.
    add_child(insert, node);
    // Fix up the document pointer.
    let doc = if (*insert).type_ == XML_DOCUMENT_NODE as c_int {
        insert as *mut _xmlDoc
    } else {
        (*insert).doc
    };
    if !doc.is_null() {
        set_node_doc(node, doc);
    }
}

/// Recursively set the doc pointer of a subtree.
///
/// # SAFETY
///
/// - All pointers must be valid.
unsafe fn set_node_doc(node: *mut _xmlNode, doc: *mut _xmlDoc) {
    if node.is_null() {
        return;
    }
    (*node).doc = doc;
    let mut prop = (*node).properties;
    while !prop.is_null() {
        (*prop).doc = doc;
        prop = (*prop).next;
    }
    let mut child = (*node).children;
    while !child.is_null() {
        set_node_doc(child, doc);
        child = (*child).next;
    }
}

/// Append a text node to the result tree.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn append_text_node(ctxt: *mut _xsltTransformContext, content: *const xmlChar) {
    let insert = (*ctxt).insert;
    if insert.is_null() || content.is_null() {
        return;
    }
    let text = new_text(content);
    if text.is_null() {
        return;
    }
    append_to_result(ctxt, text);
}

/// Append a comment node to the result tree.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn append_comment_node(
    ctxt: *mut _xsltTransformContext,
    content: *const xmlChar,
) {
    let insert = (*ctxt).insert;
    if insert.is_null() || content.is_null() {
        return;
    }
    let comment = new_comment(content);
    if comment.is_null() {
        return;
    }
    append_to_result(ctxt, comment);
}

/// Append a PI node to the result tree.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn append_pi_node(
    ctxt: *mut _xsltTransformContext,
    name: *const xmlChar,
    content: *const xmlChar,
) {
    let insert = (*ctxt).insert;
    if insert.is_null() || name.is_null() {
        return;
    }
    let pi = new_pi(name, content);
    if pi.is_null() {
        return;
    }
    append_to_result(ctxt, pi);
}

/// Process `xsl:copy`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_copy(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let node = (*ctxt).node;
    if node.is_null() {
        return;
    }
    let typ = (*node).type_;
    let saved_insert = (*ctxt).insert;
    if typ == XML_ELEMENT_NODE as c_int {
        // UPSTREAM-PARITY (transform.c xsltCopy -> xsltShallowCopyElem,
        // non-LRE): shallow-copy the element into the result tree, declare
        // the source element's namespace declarations on the copy, and
        // re-bind the element namespace with xsltGetSpecialNamespace
        // (namespace fixup). The pre-fix code only carried the source ns
        // pointer over without declaring it, so copied elements lost their
        // in-scope declarations (gh21357_2 / namespaced identity copies).
        let name = (*node).name;
        if name.is_null() {
            return;
        }
        // New element with NO namespace yet; append BEFORE the fixups so the
        // namespace search can see the ancestor chain (upstream order).
        let new_elem = crate::xml::tree::new_node(ptr::null_mut(), name);
        if new_elem.is_null() {
            return;
        }
        append_to_result(ctxt, new_elem);
        // Declare the copied element's namespace declarations (upstream
        // xsltCopyNamespaceListInternal — plain copies, no aliasing).
        let mut nsdef = (*node).nsDef;
        while !nsdef.is_null() {
            unsafe {
                if !(*nsdef).href.is_null() {
                    crate::xml::tree::new_ns(new_elem, (*nsdef).href, (*nsdef).prefix);
                }
            }
            nsdef = unsafe { (*nsdef).next };
        }
        if !(*node).ns.is_null() {
            let src_ns = &*(*node).ns;
            if src_ns.href.is_null() || *src_ns.href == 0 {
                // Source element's namespace is a disabled/empty decl.
                (*new_elem).ns = ptr::null_mut();
            } else {
                let fixed = crate::abi::exports_xslt_avt::xsltGetSpecialNamespace(
                    ctxt,
                    inst,
                    src_ns.href,
                    src_ns.prefix,
                    new_elem,
                );
                (*new_elem).ns = fixed;
            }
        } else if !saved_insert.is_null()
            && (*saved_insert).type_ == XML_ELEMENT_NODE as c_int
            && !(*saved_insert).ns.is_null()
        {
            // "Undeclare" the default namespace (upstream).
            crate::abi::exports_xslt_avt::xsltGetSpecialNamespace(
                ctxt,
                inst,
                ptr::null(),
                ptr::null(),
                new_elem,
            );
        }
        (*ctxt).insert = new_elem;
    } else if typ == XML_TEXT_NODE as c_int || typ == XML_CDATA_SECTION_NODE as c_int {
        if !(*node).content.is_null() {
            append_text_node(ctxt, (*node).content);
        }
    } else if typ == XML_COMMENT_NODE as c_int {
        if !(*node).content.is_null() {
            append_comment_node(ctxt, (*node).content);
        }
    } else if typ == XML_PI_NODE as c_int {
        if !(*node).name.is_null() {
            append_pi_node(ctxt, (*node).name, (*node).content);
        }
    } else if typ == XML_ATTRIBUTE_NODE as c_int {
        // UPSTREAM-PARITY (transform.c xsltCopy -> xsltShallowCopyAttr): an
        // xsl:copy of an attribute node creates an ATTRIBUTE copy on the
        // current result element — namespace fixup through
        // xsltGetSpecialNamespace + xmlSetNsProp — never a text node.
        // Modern DOM documents expose xmlns declarations as attributes in
        // the xmlns namespace (php_dom_ns_compat_mark_attribute_list);
        // copying such an attribute must reproduce the declaration literally
        // (gh21357_2: ns_1:xmlns="..."), not splat its value as text.
        let target = (*ctxt).insert;
        let copy_ok = if target.is_null() || (*target).type_ != XML_ELEMENT_NODE as c_int {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                c"Cannot add an attribute node to a non-element node.\n"
                    .as_ptr()
                    .cast::<libc::c_char>(),
            );
            false
        } else if !(*target).children.is_null() {
            crate::xslt::errors::xsltTransformError(
                ctxt,
                ptr::null_mut(),
                inst,
                c"Attribute nodes must be added before any child nodes to an element.\n"
                    .as_ptr()
                    .cast::<libc::c_char>()
                    .add(0),
            );
            false
        } else {
            let val = node_get_content((*node).children);
            let attr = node as *mut _xmlAttr;
            let attr_ref = &*attr;
            let ns = if attr_ref.ns.is_null() {
                ptr::null_mut()
            } else {
                crate::abi::exports_xslt_avt::xsltGetSpecialNamespace(
                    ctxt,
                    inst,
                    (*attr_ref.ns).href,
                    (*attr_ref.ns).prefix,
                    target,
                )
            };
            // xmlSetNsProp(target, ns, attr->name, value): duplicates are
            // replaced and the namespace is assigned even to a duplicate
            // (upstream note). NULL value is tolerated (xmlSetNsProp with
            // NULL content creates an empty attribute).
            crate::abi::exports_xml2::xmlSetNsProp(target, ns, attr_ref.name, val);
            if !val.is_null() {
                libc::free(val as *mut libc::c_void);
            }
            true
        };
        let _ = copy_ok;
    }
    // Process children (attributes and content).
    execute_content(ctxt, (*inst).children);
    (*ctxt).insert = saved_insert;
}

/// Process `xsl:element`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_element(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name_attr = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name_attr.is_null() {
        return;
    }
    // Evaluate the name attribute (it may be an AVT).
    let name_str = eval_avt(ctxt, name_attr);
    libc::free(name_attr as *mut libc::c_void);
    if name_str.is_null() {
        return;
    }
    // Check for the namespace attribute.
    let ns_attr = get_prop(inst, c"namespace".as_ptr() as *const xmlChar);
    let had_ns_attr = !ns_attr.is_null();
    let ns_str = if !ns_attr.is_null() {
        let v = eval_avt(ctxt, ns_attr);
        libc::free(ns_attr as *mut libc::c_void);
        v
    } else {
        ptr::null_mut()
    };
    // Resolve the namespace name (upstream xsltElement): the `namespace`
    // attribute (AVT, may be empty = no namespace); when ABSENT, the QName
    // is expanded using the namespace declarations in effect for the
    // xsl:element element, INCLUDING any default namespace declaration
    // (`xmlSearchNs(inst->doc, inst, NULL)`). gh21357_2's
    // `<xsl:element ... xmlns="http://something/new/">` relies on the
    // default-ns case: the created element is in the instruction's default
    // namespace.
    //
    // Borrowed pointers into the stylesheet when no namespace attribute is
    // present; `ns_str` (owned) when the attribute supplied a value. The
    // binding below copies the href/prefix before `ns_str` is freed.
    let mut borrowed_href: *const xmlChar = ptr::null();
    let mut borrowed_prefix: *const xmlChar = ptr::null();
    if !ns_str.is_null() && *ns_str != 0 {
        borrowed_href = ns_str;
    } else if ns_str.is_null() && !had_ns_attr {
        // No namespace attribute: in-scope default namespace of the
        // instruction (prefix NULL).
        let def = crate::abi::exports_xml2::xmlSearchNs((*inst).doc, inst, ptr::null());
        if !def.is_null() && !(*def).href.is_null() && *(*def).href != 0 {
            borrowed_href = (*def).href;
            borrowed_prefix = (*def).prefix;
        }
    }
    let elem = crate::xml::tree::new_node(ptr::null_mut(), name_str);
    libc::free(name_str as *mut libc::c_void);
    if elem.is_null() {
        if !ns_str.is_null() {
            libc::free(ns_str as *mut libc::c_void);
        }
        return;
    }
    append_to_result(ctxt, elem);
    if !borrowed_href.is_null() && *borrowed_href != 0 {
        // Bind: find or declare the namespace on the element
        // (xsltGetSpecialNamespace — declares a default decl when the
        // prefix is free; mints ns_1.. when the default is taken).
        let bound = crate::abi::exports_xslt_avt::xsltGetSpecialNamespace(
            ctxt,
            inst,
            borrowed_href,
            borrowed_prefix,
            elem,
        );
        (*elem).ns = bound;
    }
    if !ns_str.is_null() {
        libc::free(ns_str as *mut libc::c_void);
    }
    let saved_insert = (*ctxt).insert;
    (*ctxt).insert = elem;
    execute_content(ctxt, (*inst).children);
    (*ctxt).insert = saved_insert;
}

/// Process `xsl:attribute`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_attribute(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name_attr = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name_attr.is_null() {
        return;
    }
    // The name attribute may be an AVT (XSLT 1.0 §7.6.2).
    let name_str = eval_avt(ctxt, name_attr);
    libc::free(name_attr as *mut libc::c_void);
    if name_str.is_null() {
        return;
    }
    let insert = (*ctxt).insert;
    if insert.is_null() {
        xmlFreeImpl(name_str as *mut c_void);
        return;
    }
    // Evaluate the content into a temporary buffer.
    let saved_insert = (*ctxt).insert;
    let buf = libc::calloc(1, core::mem::size_of::<_xmlBuffer>()) as *mut _xmlBuffer;
    if buf.is_null() {
        xmlFreeImpl(name_str as *mut c_void);
        return;
    }
    (*buf).content = libc::calloc(1, 64) as *mut xmlChar;
    (*buf).size = 64;
    (*buf).use_ = 0;
    let frag_doc = libc::calloc(1, core::mem::size_of::<_xmlDoc>()) as *mut _xmlDoc;
    if frag_doc.is_null() {
        libc::free(buf as *mut libc::c_void);
        xmlFreeImpl(name_str as *mut c_void);
        return;
    }
    (*frag_doc).type_ = XML_DOCUMENT_NODE as c_int;
    (*frag_doc).doc = frag_doc;
    (*ctxt).insert = frag_doc as *mut _xmlNode;
    execute_content(ctxt, (*inst).children);
    // Collect the text from the fragment.
    let mut value: Vec<u8> = Vec::new();
    let mut child = (*frag_doc).children;
    while !child.is_null() {
        if (*child).type_ == XML_TEXT_NODE as c_int && !(*child).content.is_null() {
            let len = libc::strlen((*child).content as *const libc::c_char) as usize;
            value.extend_from_slice(core::slice::from_raw_parts((*child).content, len));
        }
        child = (*child).next;
    }
    // Free the fragment.
    free_doc(frag_doc);
    (*ctxt).insert = saved_insert;

    // Set the attribute on the current result element.
    let mut cvalue = value.clone();
    cvalue.push(0);
    set_prop(insert, name_str, cvalue.as_ptr() as *const xmlChar);
    xmlFreeImpl(name_str as *mut c_void);
}

/// Process `xsl:text`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_text(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    // disable-output-escaping attribute.
    let doe = get_prop(inst, c"disable-output-escaping".as_ptr() as *const xmlChar);
    if !doe.is_null() {
        libc::free(doe as *mut libc::c_void);
    }
    // Copy the text children verbatim.
    let mut child = (*inst).children;
    while !child.is_null() {
        if (*child).type_ == XML_TEXT_NODE as c_int && !(*child).content.is_null() {
            append_text_node(ctxt, (*child).content);
        }
        child = (*child).next;
    }
}

/// Process `xsl:comment`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_comment(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let content = node_get_content((*inst).children);
    if !content.is_null() {
        append_comment_node(ctxt, content);
        libc::free(content as *mut libc::c_void);
    }
}

/// Process `xsl:processing-instruction`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_pi(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name_attr = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name_attr.is_null() {
        return;
    }
    // The name attribute may be an AVT (XSLT 1.0 §7.6.2).
    let name_str = eval_avt(ctxt, name_attr);
    libc::free(name_attr as *mut libc::c_void);
    if name_str.is_null() {
        return;
    }
    let content = node_get_content((*inst).children);
    append_pi_node(ctxt, name_str, content);
    if !content.is_null() {
        libc::free(content as *mut libc::c_void);
    }
    xmlFreeImpl(name_str as *mut c_void);
}

/// Process `xsl:number`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_number(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let value_attr = get_prop(inst, c"value".as_ptr() as *const xmlChar);
    let mut number: f64 = f64::NAN;
    if !value_attr.is_null() {
        let obj = eval_xpath(ctxt, value_attr);
        libc::free(value_attr as *mut libc::c_void);
        if !obj.is_null() {
            number = (*obj).floatval;
            xmlXPathFreeObject(obj);
        } else {
            report_xpath_eval_failure(ctxt, inst, "number");
            return;
        }
    } else {
        // Compute the number from the level (single/multiple/any) and
        // count patterns. Phase 8: full implementation computes preceding
        // siblings etc. Simplified: count preceding siblings + 1.
        number = 1.0;
        let node = (*ctxt).node;
        if !node.is_null() {
            let mut sib = (*node).prev;
            while !sib.is_null() {
                if (*sib).type_ == XML_ELEMENT_NODE as c_int {
                    number += 1.0;
                }
                sib = (*sib).prev;
            }
        }
    }
    // Format the number: format attribute with tokens.
    let format = get_prop(inst, c"format".as_ptr() as *const xmlChar);
    let formatted = crate::xslt::numbering::xsltFormatNumber(number, format);
    if !format.is_null() {
        libc::free(format as *mut libc::c_void);
    }
    if !formatted.is_null() {
        append_text_node(ctxt, formatted);
        libc::free(formatted as *mut libc::c_void);
    }
}

/// XPath 1.0 boolean conversion (§4.3) of a C ABI XPath object.
///
/// - node-set → true iff non-empty
/// - number → true iff non-zero and not NaN
/// - string → true iff non-empty
/// - boolean → itself
unsafe fn xpath_obj_boolean(obj: *mut _xmlXPathObject) -> bool {
    if obj.is_null() {
        return false;
    }
    let typ = (*obj).type_;
    if typ == xmlXPathObjectType::XPATH_BOOLEAN as c_int {
        return (*obj).boolval != 0;
    }
    if typ == xmlXPathObjectType::XPATH_NUMBER as c_int {
        let n = (*obj).floatval;
        return n != 0.0 && !n.is_nan();
    }
    if typ == xmlXPathObjectType::XPATH_STRING as c_int {
        return !(*obj).stringval.is_null() && *(*obj).stringval != 0;
    }
    if typ == xmlXPathObjectType::XPATH_NODESET as c_int {
        let ns = (*obj).nodesetval as *mut _xmlNodeSet;
        return !ns.is_null() && (*ns).nodeNr > 0;
    }
    false
}

/// Process `xsl:choose`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_choose(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let mut child = (*inst).children;
    let mut executed = false;
    while !child.is_null() {
        let next = (*child).next;
        if is_xslt_element(child, "when") {
            let test = get_prop(child, c"test".as_ptr() as *const xmlChar);
            if !test.is_null() {
                let obj = eval_xpath(ctxt, test);
                libc::free(test as *mut libc::c_void);
                if obj.is_null() {
                    report_xpath_eval_failure(ctxt, child, "when");
                    return;
                }
                let truthy = xpath_obj_boolean(obj);
                xmlXPathFreeObject(obj);
                if truthy {
                    execute_content(ctxt, (*child).children);
                    executed = true;
                    break;
                }
            }
        } else if is_xslt_element(child, "otherwise") && !executed {
            execute_content(ctxt, (*child).children);
            executed = true;
        }
        child = next;
    }
}

/// Process `xsl:if`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_if(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let test = get_prop(inst, c"test".as_ptr() as *const xmlChar);
    if test.is_null() {
        return;
    }
    let obj = eval_xpath(ctxt, test);
    libc::free(test as *mut libc::c_void);
    if obj.is_null() {
        report_xpath_eval_failure(ctxt, inst, "if");
        return;
    }
    // XPath 1.0 boolean conversion (§4.3): the test may be a node-set
    // (e.g. `test="author"`), number, or string — `boolval` alone is only
    // valid for boolean objects.
    let truthy = xpath_obj_boolean(obj);
    xmlXPathFreeObject(obj);
    if truthy {
        execute_content(ctxt, (*inst).children);
    }
}

/// Process `xsl:variable` (local variable).
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_variable(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name.is_null() {
        return;
    }
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    let var = libc::calloc(1, core::mem::size_of::<_xsltStackElem>()) as *mut _xsltStackElem;
    if var.is_null() {
        libc::free(name as *mut libc::c_void);
        if !select.is_null() {
            libc::free(select as *mut libc::c_void);
        }
        return;
    }
    (*var).name = name;
    (*var).flags = 4; // INTERNAL
                      // comp type marker for the xsltDebug variable dump: an xsl:variable
                      // prints "var".
    (*var).comp = &XSLT_COMP_TYPE_VARIABLE as *const c_int as *mut c_void;
    if !select.is_null() {
        let obj = eval_xpath(ctxt, select);
        if !obj.is_null() {
            (*var).value = obj;
        } else {
            report_xpath_eval_failure(ctxt, inst, "variable");
            libc::free(select as *mut libc::c_void);
            libc::free(var as *mut libc::c_void);
            return;
        }
        libc::free(select as *mut libc::c_void);
    } else {
        let value = eval_content_fragment(ctxt, (*inst).children);
        if !value.is_null() {
            (*var).value = value;
        }
    }
    crate::xslt::variables::xsltPushVariable(ctxt, var);
}

/// Process `xsl:param` (local param with default).
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_param(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let name = get_prop(inst, c"name".as_ptr() as *const xmlChar);
    if name.is_null() {
        return;
    }
    // Check whether a value was passed (via xsl:with-param or a global
    // caller parameter). With-params are registered in the XPath context's
    // variable hash by xsltPushParam, so consult the hash.
    let already_bound = {
        let xpath_ctxt = (*ctxt).xpathCtxt;
        if xpath_ctxt.is_null() {
            false
        } else {
            let internal = (*xpath_ctxt).extra as *mut crate::xml::xpath::context::XPathContext;
            if internal.is_null() {
                false
            } else {
                let name_len = libc::strlen(name as *const libc::c_char);
                let name_bytes = core::slice::from_raw_parts(name, name_len);
                let name_owned = String::from_utf8_lossy(name_bytes).into_owned();
                (*internal).variables.contains_key(&name_owned)
            }
        }
    };
    if already_bound {
        // Value already provided by with-param / caller.
        libc::free(name as *mut libc::c_void);
        return;
    }
    let select = get_prop(inst, c"select".as_ptr() as *const xmlChar);
    let var = libc::calloc(1, core::mem::size_of::<_xsltStackElem>()) as *mut _xsltStackElem;
    if var.is_null() {
        libc::free(name as *mut libc::c_void);
        if !select.is_null() {
            libc::free(select as *mut libc::c_void);
        }
        return;
    }
    (*var).name = name;
    (*var).flags = 2 | 4; // PARAM | INTERNAL
                          // comp type marker for the xsltDebug variable dump: an xsl:param prints
                          // "param".
    (*var).comp = &XSLT_COMP_TYPE_PARAM as *const c_int as *mut c_void;
    if !select.is_null() {
        let obj = eval_xpath(ctxt, select);
        if !obj.is_null() {
            (*var).value = obj;
        } else {
            report_xpath_eval_failure(ctxt, inst, "param");
            libc::free(select as *mut libc::c_void);
            libc::free(var as *mut libc::c_void);
            return;
        }
        libc::free(select as *mut libc::c_void);
    } else {
        let value = eval_content_fragment(ctxt, (*inst).children);
        if !value.is_null() {
            (*var).value = value;
        }
    }
    crate::xslt::variables::xsltPushVariable(ctxt, var);
}

/// Process `xsl:message`.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_message(ctxt: *mut _xsltTransformContext, inst: *mut _xmlNode) {
    let content = node_get_content((*inst).children);
    if !content.is_null() {
        // UPSTREAM-PARITY (transform.c xsltMessage): the message is emitted
        // through the transform error handler (ctxt->error) or the global
        // generic channel, NOT raw stderr — lxml's _receiveXSLTError and
        // php's xsl_libxslt_error_handler only capture it via that route.
        let len = libc::strlen(content as *const libc::c_char) as usize;
        let bytes = core::slice::from_raw_parts(content as *const u8, len);
        crate::xslt::errors::xsltEmitMessage(ctxt, bytes);
        // terminate attribute: if "yes", stop the transformation.
        let terminate = get_prop(inst, c"terminate".as_ptr() as *const xmlChar);
        if !terminate.is_null() {
            if libc::strcmp(
                terminate as *const libc::c_char,
                c"yes".as_ptr() as *const libc::c_char,
            ) == 0
            {
                (*ctxt).state = XSLT_STATE_ERROR;
            }
            libc::free(terminate as *mut libc::c_void);
        }
        libc::free(content as *mut libc::c_void);
    }
}

/// Evaluate an attribute value template (AVT) per XSLT 1.0 §7.6.2.
///
/// - `{{` and `}}` escape to literal `{` / `}`.
/// - `{expr}` evaluates `expr` as an XPath expression and substitutes its
///   string value.
/// - An unmatched `{` is copied literally (upstream `xsltEvalAttrValueTemplate`
///   keeps malformed templates verbatim).
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context.
/// - `value` must be NULL or a valid NUL-terminated C string.
///
/// Returns a heap-allocated NUL-terminated string; the caller frees it with
/// `xmlFree`. Returns NULL only on allocation failure.
pub(crate) unsafe fn eval_avt(
    ctxt: *mut _xsltTransformContext,
    value: *const xmlChar,
) -> *mut xmlChar {
    if value.is_null() {
        return ptr::null_mut();
    }
    let len = libc::strlen(value as *const libc::c_char);
    let bytes = core::slice::from_raw_parts(value, len);
    let mut out: Vec<u8> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'{' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'{' {
                out.push(b'{');
                i += 2;
                continue;
            }
            // Find the closing brace of the embedded XPath expression.
            if let Some(rel) = bytes[i + 1..].iter().position(|c| *c == b'}') {
                let close = i + 1 + rel;
                let expr_bytes = &bytes[i + 1..close];
                let expr_c = crate::xml::string::bytes_to_xmlstr(expr_bytes);
                if !expr_c.is_null() {
                    let obj = eval_xpath(ctxt, expr_c);
                    xmlFreeImpl(expr_c as *mut c_void);
                    if !obj.is_null() {
                        let strv = xmlXPathCastToString(obj);
                        xmlXPathFreeObject(obj);
                        if !strv.is_null() {
                            let slen = libc::strlen(strv as *const libc::c_char);
                            out.extend_from_slice(core::slice::from_raw_parts(strv, slen));
                            xmlFreeImpl(strv as *mut c_void);
                        }
                    } else {
                        report_xpath_eval_failure(ctxt, (*ctxt).inst, "attribute-value-template");
                        return ptr::null_mut();
                    }
                }
                i = close + 1;
                continue;
            }
            // No closing brace: literal '{'.
            out.push(b'{');
            i += 1;
            continue;
        }
        if b == b'}' {
            if i + 1 < bytes.len() && bytes[i + 1] == b'}' {
                out.push(b'}');
                i += 2;
                continue;
            }
            out.push(b'}');
            i += 1;
            continue;
        }
        out.push(b);
        i += 1;
    }
    crate::xml::string::bytes_to_xmlstr(&out)
}

/// Collect the raw prefixes listed in an `xsl:exclude-result-prefixes` or
/// `xsl:extension-element-prefixes` attribute (on a literal result element or
/// the stylesheet root). Both designate namespaces that must not be copied to
/// the result tree (XSLT 1.0 §14.1: an extension namespace is excluded from
/// the result unless actually used). An empty entry represents `#default`
/// (the default namespace).
///
/// # Safety
///
/// - `node` must be NULL or a valid element node whose properties/children
///   are valid.
unsafe fn read_excluded_prefixes(node: *mut _xmlNode) -> Vec<Vec<u8>> {
    let mut out = Vec::new();
    if node.is_null() {
        return out;
    }
    let mut prop = (*node).properties;
    while !prop.is_null() {
        let is_exclude = {
            let name = (*prop).name;
            let is_name = if name.is_null() {
                false
            } else {
                let b = core::slice::from_raw_parts(
                    name,
                    libc::strlen(name as *const libc::c_char) as usize,
                );
                b == b"exclude-result-prefixes" || b == b"extension-element-prefixes"
            };
            let is_xsl_ns = if (*prop).ns.is_null() {
                false
            } else {
                let h = (*(*prop).ns).href;
                !h.is_null() && {
                    let hb = core::slice::from_raw_parts(
                        h,
                        libc::strlen(h as *const libc::c_char) as usize,
                    );
                    hb == XSLT_NAMESPACE_BYTES
                }
            };
            // Unprefixed XSLT attributes on the stylesheet root have no
            // namespace (`exclude-result-prefixes="..."` written without
            // `xsl:`); a literal result element uses the prefixed
            // `xsl:exclude-result-prefixes` form. Accept both.
            is_name && (is_xsl_ns || (*prop).ns.is_null())
        };
        if is_exclude {
            let content = node_get_content((*prop).children);
            if !content.is_null() {
                let len = libc::strlen(content as *const libc::c_char) as usize;
                let bytes = core::slice::from_raw_parts(content, len);
                for tok in bytes.split(|&b| b == b' ' || b == b'\t' || b == b'\n' || b == b'\r') {
                    if !tok.is_empty() {
                        out.push(tok.to_vec());
                    }
                }
                xmlFreeImpl(content as *mut c_void);
            }
        }
        prop = (*prop).next;
    }
    out
}

/// Find the top-level `xsl:stylesheet`/`xsl:transform` element ancestor of a
/// stylesheet node (or NULL).
///
/// # Safety
///
/// - `node` must be NULL or a valid node whose parent chain stays alive.
unsafe fn find_stylesheet_root(node: *mut _xmlNode) -> *mut _xmlNode {
    let mut cur = node;
    while !cur.is_null() {
        if (*cur).type_ == XML_ELEMENT_NODE as c_int {
            if unsafe { is_xslt_namespace(cur) } {
                let name = get_element_name(cur);
                if matches!(name.as_deref(), Some("stylesheet") | Some("transform")) {
                    return cur;
                }
            }
        }
        let t = (*cur).type_;
        cur = (*cur).parent;
        if cur.is_null() || t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int
        {
            break;
        }
    }
    ptr::null_mut()
}

const XSLT_NAMESPACE_BYTES: &[u8] = b"http://www.w3.org/1999/XSL/Transform";

/// Whether an LRE's full effective namespace set is suppressed: libxslt only
/// computes effective ns-decls for literal result elements whose stylesheet
/// ancestry to the template/stylesheet boundary contains no content-executing
/// XSLT instruction (xsl:for-each / xsl:if / xsl:choose / xsl:when /
/// xsl:otherwise). Inside such instruction bodies the compile-time LRE ns
/// scope is empty (observed oracle behavior: `<xsl:for-each>..<br/>` at the
/// top of a result emits NO xmlns declarations, while a `<br/>` directly in
/// the template does). Literal-result ancestors do NOT reset the suppression;
/// only the element's own namespace binding is still materialised (a
/// prefixed literal `<php:x>` inside xsl:for-each DOES declare xmlns:php).
///
/// # Safety
///
/// - `node` must be NULL or a valid node whose parent chain stays alive.
unsafe fn lre_decls_suppressed(node: *mut _xmlNode) -> bool {
    let mut cur = if node.is_null() {
        return false;
    } else {
        (*node).parent
    };
    while !cur.is_null() {
        let t = (*cur).type_;
        if t == XML_ELEMENT_NODE as c_int && unsafe { is_xslt_namespace(cur) } {
            let name = get_element_name(cur);
            match name.as_deref() {
                Some("for-each") | Some("if") | Some("choose") | Some("when")
                | Some("otherwise") => return true,
                Some("template") | Some("stylesheet") | Some("transform") => return false,
                _ => {}
            }
        }
        if cur.is_null() || t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int
        {
            break;
        }
        cur = (*cur).parent;
    }
    false
}

/// Create the namespace declarations a literal result element must carry
/// (XSLT 1.0 §7.1.3): its in-scope namespace nodes from the stylesheet,
/// minus the xml namespace, minus any prefix bound to the XSLT namespace and
/// minus `xsl:exclude-result-prefixes` entries. Declarations already in scope
/// at the result insertion point (same prefix AND href) are not duplicated;
/// the element's own namespace is bound to the matching declaration (creating
/// it when needed). When the literal element is in NO namespace but the
/// result parent has a non-empty default namespace, `xmlns=""` undeclares it
/// (upstream transform.c xsltCopyTree ns handling).
///
/// # Safety
///
/// - `ctxt` must be a valid transform context whose `insert` is the result
///   insertion point; `elem` a freshly created, already-appended result
///   element; `inst` the stylesheet literal element.
unsafe fn copy_literal_result_ns(
    ctxt: *mut _xsltTransformContext,
    elem: *mut _xmlNode,
    inst: *mut _xmlNode,
) {
    // Excluded prefix lists: the literal element itself and the stylesheet
    // root (XSLT 1.0 §7.1.3: both attribute forms are honored).
    let mut excluded: Vec<Vec<u8>> = Vec::new();
    excluded.extend(read_excluded_prefixes(inst));
    let root = find_stylesheet_root(inst);
    if !root.is_null() && root != inst {
        excluded.extend(read_excluded_prefixes(root));
    }
    let excluded_default = excluded.iter().any(|p| p.is_empty());

    // The in-scope declarations of the stylesheet element: own nsDef first,
    // then ancestors, deduplicated by prefix (nearest declaration wins).
    struct NsDecl {
        prefix: *const xmlChar,
        href: *const xmlChar,
    }
    let mut in_scope: Vec<NsDecl> = Vec::new();
    let mut cur: *mut _xmlNode = inst;
    while !cur.is_null() {
        let mut d = (*cur).nsDef;
        while !d.is_null() {
            let prefix = (*d).prefix;
            let dup = in_scope.iter().any(|e| {
                (prefix.is_null() && e.prefix.is_null())
                    || (!prefix.is_null()
                        && !e.prefix.is_null()
                        && unsafe { xmlStrEqual(prefix, e.prefix) != 0 })
            });
            if !dup {
                in_scope.push(NsDecl {
                    prefix,
                    href: (*d).href,
                });
            }
            d = (*d).next;
        }
        let t = (*cur).type_;
        cur = (*cur).parent;
        if cur.is_null() || t == XML_DOCUMENT_NODE as c_int || t == XML_HTML_DOCUMENT_NODE as c_int
        {
            break;
        }
    }

    let result_parent = (*elem).parent;
    let result_doc = (*elem).doc;

    // UPSTREAM-PARITY: inside xsl:for-each/if/choose/when/otherwise bodies
    // the compiled LRE carries NO effective namespace declarations (the
    // element-name binding and xmlns="" undeclaration below still apply).
    let suppressed = unsafe { lre_decls_suppressed(inst) };
    if !suppressed {
        for decl in &in_scope {
            let href = decl.href;
            if href.is_null() {
                continue;
            }
            // Skip the xml prefix (always implicitly bound).
            if !decl.prefix.is_null() {
                let pbytes = core::slice::from_raw_parts(
                    decl.prefix,
                    libc::strlen(decl.prefix as *const libc::c_char) as usize,
                );
                if pbytes == b"xml" {
                    continue;
                }
                let is_xslt_bound = {
                    let hbytes = core::slice::from_raw_parts(
                        href,
                        libc::strlen(href as *const libc::c_char) as usize,
                    );
                    hbytes == XSLT_NAMESPACE_BYTES
                };
                let is_excluded = excluded.iter().any(|p| p.as_slice() == pbytes);
                if is_xslt_bound || is_excluded {
                    continue;
                }
            } else if excluded_default {
                continue;
            }
            // Redundant when the result insertion point already binds this
            // prefix to the same URI.
            let parent =
                if result_parent.is_null() || (*result_parent).type_ != XML_ELEMENT_NODE as c_int {
                    ptr::null_mut()
                } else {
                    result_parent
                };
            if !parent.is_null() {
                let ins = search_ns(result_doc, parent, decl.prefix);
                if !ins.is_null() && !(*ins).href.is_null() {
                    let same = unsafe { xmlStrEqual((*ins).href, href) != 0 };
                    if same {
                        continue;
                    }
                }
            }
            unsafe {
                new_ns(elem, href, decl.prefix);
            }
        }
    }

    // Bind the element's own namespace.
    let inst_ns = (*inst).ns;
    if !inst_ns.is_null() {
        let want_prefix = (*inst_ns).prefix;
        let want_href = (*inst_ns).href;
        // 1. a declaration we just created on elem with the same prefix.
        let mut own = (*elem).nsDef;
        while !own.is_null() {
            let prefix_eq = (want_prefix.is_null() && (*own).prefix.is_null())
                || (!want_prefix.is_null()
                    && !(*own).prefix.is_null()
                    && unsafe { xmlStrEqual(want_prefix, (*own).prefix) != 0 });
            if prefix_eq && !(*own).href.is_null() && !want_href.is_null() {
                if unsafe { xmlStrEqual((*own).href, want_href) != 0 } {
                    (*elem).ns = own;
                    break;
                }
            }
            own = (*own).next;
        }
        if (*elem).ns.is_null() {
            // 2. already in scope at the result parent.
            let parent =
                if result_parent.is_null() || (*result_parent).type_ != XML_ELEMENT_NODE as c_int {
                    ptr::null_mut()
                } else {
                    result_parent
                };
            let mut in_scope_ns: *mut _xmlNs = ptr::null_mut();
            if !parent.is_null() {
                in_scope_ns = search_ns(result_doc, parent, want_prefix);
            }
            if !in_scope_ns.is_null()
                && !want_href.is_null()
                && !(*in_scope_ns).href.is_null()
                && unsafe { xmlStrEqual((*in_scope_ns).href, want_href) != 0 }
            {
                (*elem).ns = in_scope_ns;
            } else {
                // 3. declare it on the element itself.
                let created = unsafe { new_ns(elem, want_href, want_prefix) };
                if !created.is_null() {
                    (*elem).ns = created;
                }
            }
        }
    } else if !result_parent.is_null() && (*result_parent).type_ == XML_ELEMENT_NODE as c_int {
        // The literal element is in no namespace but the result parent is:
        // undeclare the default namespace so serialization does not put the
        // element in it (xmlns="").
        let d = unsafe { search_ns(result_doc, result_parent, ptr::null()) };
        if !d.is_null()
            && !(*d).href.is_null()
            && unsafe { *(*d).href } != 0
            && unsafe { (*elem).ns }.is_null()
        {
            unsafe {
                new_ns(elem, c"".as_ptr() as *const xmlChar, ptr::null());
            }
        }
    }
}

/// Process a literal result element.
///
/// # SAFETY
///
/// - All pointers must be valid.
pub(crate) unsafe fn process_literal_element(
    ctxt: *mut _xsltTransformContext,
    inst: *mut _xmlNode,
) {
    // Create the result element.
    let elem = new_node(ptr::null_mut(), (*inst).name);
    if elem.is_null() {
        return;
    }
    append_to_result(ctxt, elem);
    // Copy the in-scope namespace declarations onto the result element
    // (XSLT 1.0 literal-result-element rules) and bind its namespace.
    copy_literal_result_ns(ctxt, elem, inst);
    // Copy attributes, evaluating attribute value templates.
    let mut prop = (*inst).properties;
    while !prop.is_null() {
        let attr_name = (*prop).name;
        // Skip xmlns declarations (they are namespace nodes).
        if !attr_name.is_null() {
            let name_bytes = core::slice::from_raw_parts(
                attr_name,
                libc::strlen(attr_name as *const libc::c_char) as usize,
            );
            if name_bytes != b"xmlns" {
                let attr_val = node_get_content((*prop).children);
                if !attr_val.is_null() {
                    // AVT: the attribute value may contain {expr} templates.
                    let avt_val = eval_avt(ctxt, attr_val);
                    libc::free(attr_val as *mut libc::c_void);
                    if !avt_val.is_null() {
                        set_prop(elem, attr_name, avt_val);
                        xmlFreeImpl(avt_val as *mut c_void);
                    }
                }
            }
        }
        prop = (*prop).next;
    }
    // Process the content.
    let saved_insert = (*ctxt).insert;
    (*ctxt).insert = elem;
    execute_content(ctxt, (*inst).children);
    (*ctxt).insert = saved_insert;
}

/// Register the XSLT-specific XPath functions: document(), key(),
/// generate-id(), system-property(), element-available(),
/// function-available(), and current().
///
/// # SAFETY
///
/// - `ctxt` must be a valid transform context.
///
/// Emit a transform error through the XSLT error machinery with the given
///
/// transform context (so the context line carries the current instruction's
///
/// file/line/element, matching upstream xsltTransformError(ctxt, ...)).
///
/// # SAFETY
///
/// - `tctxt` may be NULL; `msg` must not contain interior NUL bytes.
unsafe fn emit_transform_error_with_ctxt(tctxt: *mut _xsltTransformContext, msg: &[u8]) {
    {
        let mut buf = msg.to_vec();
        buf.push(0);
        crate::xslt::errors::xsltTransformError(
            tctxt,
            ptr::null_mut(),
            ptr::null_mut(),
            buf.as_ptr() as *const std::os::raw::c_char,
        );
    }
}

/// Register the XPath 1.0 core, XSLT, EXSLT, and extension functions on the
/// transform context's XPath context.
///
/// # Safety
///
/// - `ctxt` must be a non-NULL pointer to a valid, live
///   `_xsltTransformContext` whose `xpathCtxt` field is NULL or a pointer to a
///   valid XPath context, and whose `extra` field is NULL or a pointer to the
///   internal `XPathContext` struct used here; that internal context is
///   mutably borrowed for the whole call, so no other code may access it
///   concurrently. When `ctxt->style` is non-NULL, the style and its `doc`
///   node tree must stay alive as long as the registered closures can run,
///   because the `key` and `format-number` closures and the
///   extension-function lookup dereference `tctxt`, `style`, `inst`,
///   namespace nodes, and `style.doc` through raw pointers.
pub(crate) unsafe fn register_xslt_functions(ctxt: *mut _xsltTransformContext) {
    let xpath_ctxt = (*ctxt).xpathCtxt;
    if xpath_ctxt.is_null() {
        return;
    }
    let internal = (*xpath_ctxt).extra as *mut crate::xml::xpath::context::XPathContext;
    if internal.is_null() {
        return;
    }
    let internal = &mut *internal;

    use crate::xml::xpath::context::XPathContext;
    use crate::xml::xpath::types::{NodeSet, XPathValue};

    // The XPath 1.0 core function library (count, string, substring, concat,
    // …) is served by the static lookup_core_function table (Phase 16.5.9);
    // only the XSLT/EXSLT additions below are registered into the context map.

    // document() — loads an external document (first argument) and returns
    // its root node-set.
    internal.register_function("document", |ctx, args| {
        let value = match args.first() {
            Some(v) => v.as_string(),
            None => return Err("document() requires an argument".to_string()),
        };
        let tctxt = ctx.func_lookup_data as *mut _xsltTransformContext;
        if tctxt.is_null() {
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        // UPSTREAM-PARITY (functions.c xsltDocumentFunction): an empty URI
        // (document('')) selects the STYLESHEET document itself, not a
        // resolver/loader round-trip. Without this, lxml's test_xslt_document
        // family (which loads document('') from a file) returns an empty
        // result tree.
        if value.is_empty() {
            unsafe {
                let style = (*tctxt).style;
                if !style.is_null() && !(*style).doc.is_null() {
                    let mut ns = NodeSet::new();
                    ns.push((*style).doc as *mut _xmlNode);
                    return Ok(XPathValue::NodeSet(ns));
                }
            }
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        unsafe {
            // UPSTREAM-PARITY (functions.c xsltDocumentFunction): the URI is
            // resolved against the current instruction's document (the
            // stylesheet) with xmlBuildURI, then loaded through the
            // transform's document loader (xsltLoadDocument), which invokes
            // the registered xsltDocLoaderFunc — lxml's loader records
            // resolver failures so XSLTApplyError("Cannot resolve URI ...")
            // surfaces after the run, exactly like the oracle.
            let mut base: *mut xmlChar = ptr::null_mut();
            let inst = (*tctxt).inst;
            if !inst.is_null() {
                base = crate::abi::exports_tree::xmlNodeGetBase((*inst).doc, inst);
            } else if !(*tctxt).style.is_null() && !(*(*tctxt).style).doc.is_null() {
                base = crate::abi::exports_tree::xmlNodeGetBase(
                    (*(*tctxt).style).doc,
                    (*(*tctxt).style).doc as *mut _xmlNode,
                );
            }
            let value_c = crate::xml::string::bytes_to_xmlstr(value.as_bytes());
            let resolved = crate::abi::exports_uri::xmlBuildURI(
                value_c as *const c_char,
                base as *const c_char,
            );
            if !base.is_null() {
                crate::abi::allocator::xmlFreeImpl(base as *mut c_void);
            }
            if !value_c.is_null() {
                crate::abi::allocator::xmlFreeImpl(value_c as *mut c_void);
            }
            let load_uri: Vec<u8> = if resolved.is_null() {
                value.as_bytes().to_vec()
            } else {
                let l = libc::strlen(resolved as *const libc::c_char);
                core::slice::from_raw_parts(resolved as *const u8, l).to_vec()
            };
            if !resolved.is_null() {
                crate::abi::allocator::xmlFreeImpl(resolved as *mut c_void);
            }
            let mut load_c = load_uri;
            load_c.push(0);
            let doc =
                crate::xslt::documents::xsltLoadDocument(tctxt, load_c.as_ptr() as *const xmlChar);
            if doc.is_null() {
                // UPSTREAM-PARITY: a failed load selects the stylesheet doc
                // only for the special URIs (handled by the load failure
                // fallback in xsltDocumentFunctionLoadDocument); otherwise an
                // empty node-set is pushed and the transform continues — the
                // loader's recorded exception surfaces at the end.
                return Ok(XPathValue::NodeSet(NodeSet::new()));
            }
            // The node-set contains the DOCUMENT node (upstream pushes
            // xmlXPathNewNodeSet((xmlNodePtr) doc)); child steps like
            // document('x')/r/v navigate from it.
            let mut ns = NodeSet::new();
            ns.push(doc as *mut _xmlNode);
            Ok(XPathValue::NodeSet(ns))
        }
    });

    // key() — looks up the key tables built by xsltInitKeys. The value is
    // matched against the key table's stored string keys (upstream
    // xsltEvalKeyFunction, keys.c). The transform context is reached through
    // the XPath context's opaque func_lookup_data slot, which is set below.
    internal.register_function("key", |ctx, args| {
        let tctxt = ctx.func_lookup_data as *mut _xsltTransformContext;
        if tctxt.is_null() {
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        let name_str = match args.first() {
            Some(v) => v.as_string(),
            None => return Err("key() requires a name argument".to_string()),
        };
        // The value may be a node-set: use the string value of the first node
        // (upstream iterates every node; the common case is a single value).
        let value_str = match args.get(1) {
            Some(XPathValue::NodeSet(ns)) => match ns.first() {
                Some(n) => crate::xml::xpath::types::node_string_value(n),
                None => return Ok(XPathValue::NodeSet(NodeSet::new())),
            },
            Some(v) => v.as_string(),
            None => return Err("key() requires a value argument".to_string()),
        };
        let name_c = crate::xml::string::bytes_to_xmlstr(name_str.as_bytes());
        let value_c = crate::xml::string::bytes_to_xmlstr(value_str.as_bytes());
        if name_c.is_null() || value_c.is_null() {
            if !name_c.is_null() {
                crate::abi::allocator::xmlFreeImpl(name_c as *mut c_void);
            }
            if !value_c.is_null() {
                crate::abi::allocator::xmlFreeImpl(value_c as *mut c_void);
            }
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        let ns = unsafe { crate::xslt::keys::xsltEvalKeyFunction(tctxt, name_c, value_c) };
        crate::abi::allocator::xmlFreeImpl(name_c as *mut c_void);
        crate::abi::allocator::xmlFreeImpl(value_c as *mut c_void);
        if ns.is_null() {
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        let mut out = NodeSet::new();
        unsafe {
            let node_nr = (*ns).nodeNr;
            let node_tab = (*ns).nodeTab;
            if !node_tab.is_null() {
                for i in 0..node_nr as isize {
                    let n = *node_tab.add(i as usize);
                    if !n.is_null() {
                        out.push(n);
                    }
                }
            }
            crate::abi::exports_xml2::xmlXPathFreeNodeSet(ns);
        }
        Ok(XPathValue::NodeSet(out))
    });

    // generate-id() — returns a unique ID for the first node of the
    // node-set argument (or the context node).
    internal.register_function("generate-id", |ctx, args| {
        let node = match args.first() {
            Some(XPathValue::NodeSet(ns)) => ns.first().unwrap_or(ctx.context_node),
            _ => ctx.context_node,
        };
        if node.is_null() {
            return Ok(XPathValue::String(String::new()));
        }
        // SAFETY: node must be valid.
        let id = { format!("id{:p}", node) };
        Ok(XPathValue::String(id))
    });

    // format-number() — formats a number with an XSLT decimal-format
    // picture (numbers.c xsltFormatNumberConversion). Two or three
    // arguments: (number, picture [, decimal-format-name]). Faithful to
    // upstream functions.c xsltFormatNumberFunction:
    //
    // - without a third argument the default format (chain head) is used;
    // - an unresolvable QName prefix reports
    //   "format-number : No namespace found for QName 'p:l'" and falls
    //   back to the default format;
    // - an undeclared format reports
    //   "format-number() : undeclared decimal format 'name'" and pushes no
    //   result, which surfaces as an XPath "Stack usage error".
    internal.register_function("format-number", |ctx, args| {
        if args.len() < 2 || args.len() > 3 {
            return Err("format-number() requires 2 or 3 arguments".to_string());
        }
        let number = args[0].as_number();
        let picture = args[1].as_string();
        let tctxt = ctx.func_lookup_data as *mut _xsltTransformContext;
        // Upstream starts from the default format (sheet->decimalFormat).
        let mut fmt: *mut _xsltDecimalFormat = if tctxt.is_null() {
            ptr::null_mut()
        } else {
            unsafe { (*(*tctxt).style).decimalFormat }
        };
        if args.len() == 3 {
            let qname = args[2].as_string();
            let (prefix, local) = match qname.split_once(':') {
                Some((p, l)) => (Some(p), l),
                None => (None, qname.as_str()),
            };
            let mut ns_uri: *const xmlChar = ptr::null();
            let mut ncname_ok = true;
            if let Some(p) = prefix {
                let inst = unsafe { (*tctxt).inst };
                if inst.is_null() {
                    ncname_ok = false;
                } else {
                    let prefix_c = crate::xml::string::bytes_to_xmlstr(p.as_bytes());
                    let ns = unsafe {
                        crate::abi::exports_xml2::xmlSearchNs((*inst).doc, inst, prefix_c)
                    };
                    if !prefix_c.is_null() {
                        crate::abi::allocator::xmlFreeImpl(prefix_c as *mut c_void);
                    }
                    if ns.is_null() {
                        // UPSTREAM-PARITY: unresolvable prefix — report and
                        // fall back to the default format.
                        let msg = format!(
                            "format-number : No namespace found for QName '{}:{}'\n",
                            p, local
                        );
                        emit_transform_error_with_ctxt(tctxt, msg.as_bytes());
                        unsafe {
                            (*(*tctxt).style).errors += 1;
                        }
                        ncname_ok = false;
                    } else {
                        ns_uri = unsafe { (*ns).href };
                    }
                }
            }
            if ncname_ok {
                let local_c = crate::xml::string::bytes_to_xmlstr(local.as_bytes());
                let style = unsafe { (*tctxt).style };
                fmt = crate::xslt::numbering::decimal_format_by_qname(style, ns_uri, local_c);
                if !local_c.is_null() {
                    crate::abi::allocator::xmlFreeImpl(local_c as *mut c_void);
                }
                if fmt.is_null() {
                    // UPSTREAM-PARITY: undeclared format — report and push
                    // nothing (the value-of then reports a stack error).
                    let msg = format!("format-number() : undeclared decimal format '{}'\n", qname);
                    emit_transform_error_with_ctxt(tctxt, msg.as_bytes());
                    return Err("Stack usage error".to_string());
                }
            }
        }
        let picture_c = crate::xml::string::bytes_to_xmlstr(picture.as_bytes());
        let mut result: *mut xmlChar = ptr::null_mut();
        let status = unsafe {
            crate::xslt::numbering::xslt_format_number_conversion(
                fmt,
                picture_c,
                number,
                &mut result,
            )
        };
        if !picture_c.is_null() {
            crate::abi::allocator::xmlFreeImpl(picture_c as *mut c_void);
        }
        let _ = status;
        let s = if result.is_null() {
            String::new()
        } else {
            unsafe {
                std::ffi::CStr::from_ptr(result as *const std::os::raw::c_char)
                    .to_string_lossy()
                    .into_owned()
            }
        };
        if !result.is_null() {
            crate::abi::allocator::xmlFreeImpl(result as *mut c_void);
        }
        Ok(XPathValue::String(s))
    });

    // system-property() — returns system properties (xsl:version,
    // xsl:vendor, xsl:vendor-url).
    internal.register_function("system-property", |_ctx, args| {
        let name = match args.first() {
            Some(v) => v.as_string(),
            None => return Err("system-property() requires an argument".to_string()),
        };
        let value = match name.as_str() {
            "xsl:version" => "1.0",
            "xsl:vendor" => "libxslt",
            "xsl:vendor-url" => "http://xmlsoft.org/XSLT/",
            _ => "",
        };
        Ok(XPathValue::String(value.to_string()))
    });

    // element-available() / function-available() — check availability of
    // XSLT elements/functions (all standard ones are available).
    internal.register_function("element-available", |_ctx, args| {
        let name = match args.first() {
            Some(v) => v.as_string(),
            None => return Err("element-available() requires an argument".to_string()),
        };
        // All standard XSLT 1.0 elements are available, plus EXSLT elements.
        let exslt_elements = [
            "exsl:document",
            "exsl:node-set",
            "exsl:object-type",
            "func:function",
            "func:result",
            "func:script",
            "dyn:element",
            "dyn:attribute",
            "dyn:call",
            "dyn:evaluate",
        ];
        let available = name.starts_with("xsl:")
            || exslt_elements.contains(&name.as_str())
            || matches!(
                name.as_str(),
                "apply-templates"
                    | "call-template"
                    | "apply-imports"
                    | "for-each"
                    | "value-of"
                    | "copy-of"
                    | "copy"
                    | "element"
                    | "attribute"
                    | "text"
                    | "comment"
                    | "processing-instruction"
                    | "number"
                    | "choose"
                    | "if"
                    | "variable"
                    | "param"
                    | "sort"
                    | "message"
                    | "fallback"
                    | "output"
                    | "decimal-format"
                    | "namespace-alias"
                    | "attribute-set"
                    | "key"
                    | "strip-space"
                    | "preserve-space"
                    | "import"
                    | "include"
                    | "stylesheet"
                    | "transform"
            );
        Ok(XPathValue::Boolean(available))
    });

    internal.register_function("function-available", |_ctx, args| {
        let name = match args.first() {
            Some(v) => v.as_string(),
            None => return Err("function-available() requires an argument".to_string()),
        };
        // All XPath 1.0 core functions plus the XSLT functions are available.
        let core = [
            "last",
            "position",
            "count",
            "id",
            "local-name",
            "namespace-uri",
            "name",
            "string",
            "concat",
            "starts-with",
            "contains",
            "substring-before",
            "substring-after",
            "substring",
            "string-length",
            "normalize-space",
            "translate",
            "boolean",
            "not",
            "true",
            "false",
            "lang",
            "number",
            "sum",
            "floor",
            "ceiling",
            "round",
        ];
        let xslt_fn = [
            "document",
            "key",
            "generate-id",
            "system-property",
            "element-available",
            "function-available",
            "current",
            "unparsed-entity-uri",
        ];
        // EXSLT functions (e.g. math:max, exsl:node-set) are available when
        // the EXSLT registry has been populated (exsltRegisterAll).
        let exslt_available = crate::exslt::lookup(&name).is_some();
        let local = name.rsplit(':').next().unwrap_or(&name);
        Ok(XPathValue::Boolean(
            core.contains(&local) || xslt_fn.contains(&local) || exslt_available,
        ))
    });

    // current() — returns the current node.
    internal.register_function("current", |ctx, _args| {
        let node = ctx.context_node;
        if node.is_null() {
            return Ok(XPathValue::NodeSet(NodeSet::new()));
        }
        let mut ns = NodeSet::new();
        ns.push(node);
        Ok(XPathValue::NodeSet(ns))
    });

    // ── EXSLT functions (§35) ────────────────────────────────────────────
    //
    // Upstream requires an explicit exsltRegisterAll() before EXSLT
    // functions become available; xsltproc calls it at startup. We mirror
    // that: copy the process-wide EXSLT registry into this context.
    for (name, f) in crate::exslt::iter_functions() {
        internal.register_function(&name, f);
    }
    // Register <func:function> definitions found in the stylesheet.
    crate::exslt::functions::register_stylesheet_functions(
        internal,
        (*ctxt)
            .style
            .as_ref()
            .map_or(std::ptr::null_mut(), |s| s.doc),
    );

    // Extension functions: `prefix:local(...)` resolves the prefix against
    // the stylesheet's namespace declarations and dispatches to the
    // transform context's registered extension functions (upstream
    // XSLT_REGISTER_FUNCTION_LOOKUP -> xsltXPathFunctionLookup,
    // extensions.c). The C callback runs through the same synthesized
    // parser-context bridge used by xmlXPathRegisterFunc.
    internal.function_lookup = Some(Box::new(|ctx: &XPathContext, name: &str| {
        let (prefix, local) = name.split_once(':')?;
        let tctxt = ctx.func_lookup_data as *mut _xsltTransformContext;
        if tctxt.is_null() {
            return None;
        }
        // Resolve the prefix from the stylesheet's in-scope namespaces.
        let style = unsafe { (*tctxt).style.as_ref() }?;
        let style_doc = style.doc;
        let prefix_c = crate::xml::string::bytes_to_xmlstr(prefix.as_bytes());
        let root = unsafe { (*style_doc).children };
        let ns = unsafe { crate::xml::tree::search_ns(style_doc, root, prefix_c) };
        if !prefix_c.is_null() {
            crate::abi::allocator::xmlFreeImpl(prefix_c as *mut c_void);
        }
        if ns.is_null() {
            return None;
        }
        let href = unsafe { (*ns).href };
        if href.is_null() {
            return None;
        }
        let href_str = unsafe {
            std::ffi::CStr::from_ptr(href as *const std::os::raw::c_char)
                .to_string_lossy()
                .into_owned()
        };
        let local_c = crate::xml::string::bytes_to_xmlstr(local.as_bytes());
        let href_c = crate::xml::string::bytes_to_xmlstr(href_str.as_bytes());
        let mut fnptr =
            unsafe { crate::xslt::extensions::xsltFindExtFunction(tctxt, local_c, href_c) };
        if fnptr.is_null() {
            // UPSTREAM-PARITY (functions.c xsltXPathFunctionLookup): when the
            // per-context registry misses, fall back to the process-wide
            // extension-module registry (extensions.c xsltExtModuleFunction
            // Lookup). php registers its php:function / php:functionString
            // dispatchers there at MINIT via xsltRegisterExtModuleFunction.
            if let Some(modfn) = unsafe {
                crate::abi::exports_xslt_ext::xsltExtModuleFunctionLookup(local_c, href_c)
            } {
                fnptr = modfn as usize as *mut c_void;
            }
        }
        if !local_c.is_null() {
            crate::abi::allocator::xmlFreeImpl(local_c as *mut c_void);
        }
        if !href_c.is_null() {
            crate::abi::allocator::xmlFreeImpl(href_c as *mut c_void);
        }
        if fnptr.is_null() {
            return None;
        }
        // SAFETY: fnptr was stored by xsltRegisterExtFunction as the C
        // xmlXPathFunction callback.
        let f: Option<unsafe extern "C" fn(*mut c_void, c_int)> =
            unsafe { std::mem::transmute(fnptr) };
        let tctxt_addr = tctxt as usize;
        let local_owned = local.to_string();
        let href_owned = href_str.clone();
        Some(Box::new(
            move |_ctx: &mut XPathContext, args: &[XPathValue]| {
                let t = tctxt_addr as *mut _xsltTransformContext;
                let xpath_ctxt = unsafe { (*t).xpathCtxt };
                if xpath_ctxt.is_null() {
                    return Err("XSLT: null XPath context".to_string());
                }
                unsafe {
                    // The mirror bridge exposes an upstream-layout context
                    // (extra = transform context) to the C callback, which
                    // php's xsl handlers require (xsl_proxy_factory reads
                    // ctxt->context->extra directly).
                    crate::abi::exports_xml2::call_xslt_ext_function(
                        f,
                        t,
                        xpath_ctxt,
                        &local_owned,
                        Some(&href_owned),
                        args,
                    )
                }
            },
        ))
    }));
}

/// The set of EXSLT element names recognized by `element-available()`.
pub const fn exslt_element_names() -> &'static [&'static str] {
    &[
        "exsl:document",
        "exsl:node-set",
        "exsl:object-type",
        "func:function",
        "func:result",
        "func:script",
        "dyn:element",
        "dyn:attribute",
        "dyn:call",
        "dyn:evaluate",
    ]
}

/// The set of EXSLT function QNames (prefix:local) for `function-available()`.
pub fn exslt_function_names() -> Vec<String> {
    crate::exslt::iter_functions()
        .into_iter()
        .map(|(n, _)| n)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ptr;

    #[test]
    /// Tests that `xsltNewTransformContext` returns NULL for a NULL style.
    ///
    /// # Safety
    ///
    /// - `xsltNewTransformContext` tolerates NULL arguments and returns NULL
    ///   without dereferencing them, so passing two null pointers is sound.
    fn test_new_context_null_style() {
        unsafe {
            assert!(xsltNewTransformContext(ptr::null_mut(), ptr::null_mut()).is_null());
        }
    }

    #[test]
    /// Tests that the context and result free functions tolerate NULL.
    ///
    /// # Safety
    ///
    /// - `xsltFreeTransformContext` and `xsltFreeTransformResult` check their
    ///   arguments for NULL and return early without dereferencing them.
    fn test_free_null() {
        unsafe {
            xsltFreeTransformContext(ptr::null_mut());
            xsltFreeTransformResult(ptr::null_mut());
        }
    }

    #[test]
    /// Tests that `xsltApplyStylesheet` returns NULL for NULL inputs.
    ///
    /// # Safety
    ///
    /// - `xsltApplyStylesheet` validates its arguments and returns NULL
    ///   without dereferencing the null style, document, and parameters.
    fn test_apply_stylesheet_null() {
        unsafe {
            assert!(
                xsltApplyStylesheet(ptr::null_mut(), ptr::null_mut(), ptr::null_mut()).is_null()
            );
        }
    }

    #[test]
    /// Tests a full transform with a simplified stylesheet, end to end.
    ///
    /// # Safety
    ///
    /// - `xsl` and `src` are NUL-terminated byte buffers that stay alive
    ///   while `xsltParseStylesheetMemory` and `xmlReadMemory` parse them;
    ///   `style` and `doc` are asserted non-NULL before use; `txt` and `len`
    ///   are live stack pointers passed to `xsltSaveResultToString`, and the
    ///   returned `txt` buffer is valid for `len` bytes when sliced via
    ///   `from_raw_parts` and is freed with `libc::free`; `result`, `doc`,
    ///   and `style` are freed once each after the last use.
    fn test_end_to_end_simplified_stylesheet() {
        unsafe {
            // A simplified stylesheet: a literal <html> element with an
            // implicit template matching "/" (and the required
            // xsl:version attribute).
            let xsl = b"<?xml version=\"1.0\"?><html xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xsl:version=\"1.0\"><body><p>Hello</p></body></html>\0";
            let style = crate::xslt::stylesheet::xsltParseStylesheetMemory(
                xsl.as_ptr() as *const c_char,
                (xsl.len() - 1) as c_int,
                ptr::null(),
            );
            assert!(!style.is_null(), "stylesheett parse failed");

            // Source document.
            let src = b"<?xml version=\"1.0\"?><root><item>world</item></root>\0";
            let doc = crate::abi::exports_xml2::xmlReadMemory(
                src.as_ptr() as *const c_char,
                (src.len() - 1) as c_int,
                ptr::null(),
                ptr::null(),
                0,
            );
            assert!(!doc.is_null());

            let result = xsltApplyStylesheet(style, doc, ptr::null_mut());
            assert!(!result.is_null(), "apply failed");

            // Serialize the result.
            let mut txt: *mut xmlChar = ptr::null_mut();
            let mut len: c_int = 0;
            let ret = crate::xslt::serialization::xsltSaveResultToString(
                &mut txt, &mut len, result, style,
            );
            assert_eq!(ret, 0);
            assert!(!txt.is_null());
            let out = String::from_utf8_lossy(core::slice::from_raw_parts(txt, len as usize));
            assert!(
                out.contains("Hello"),
                "result should contain the literal text, got: {}",
                out
            );

            libc::free(txt as *mut libc::c_void);
            crate::xml::tree::free_doc(result);
            crate::xml::tree::free_doc(doc);
            crate::xslt::stylesheet::xsltFreeStylesheet(style);
        }
    }

    #[test]
    /// Tests a full transform with an explicit template, end to end.
    ///
    /// # Safety
    ///
    /// - `xsl` and `src` are NUL-terminated byte buffers alive for the parse
    ///   calls; `style` and `doc` are asserted non-NULL before use; `txt` and
    ///   `len` are live stack pointers for `xsltSaveResultToString`, and the
    ///   returned `txt` buffer is valid for `len` bytes when sliced via
    ///   `from_raw_parts` and is freed with `libc::free`; `result`, `doc`,
    ///   and `style` are each freed exactly once after their last use.
    fn test_end_to_end_template_transform() {
        unsafe {
            // A normal stylesheet with an explicit template that emits
            // element and value-of.
            let xsl = b"<?xml version=\"1.0\"?>\n\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\
              <xsl:template match=\"/\">\n\
                <out><xsl:value-of select=\"/root/item\"/></out>\n\
              </xsl:template>\n\
            </xsl:stylesheet>\0";
            let style = crate::xslt::stylesheet::xsltParseStylesheetMemory(
                xsl.as_ptr() as *const c_char,
                (xsl.len() - 1) as c_int,
                ptr::null(),
            );
            assert!(!style.is_null(), "stylesheet parse failed");

            let src = b"<?xml version=\"1.0\"?><root><item>world</item></root>\0";
            let doc = crate::abi::exports_xml2::xmlReadMemory(
                src.as_ptr() as *const c_char,
                (src.len() - 1) as c_int,
                ptr::null(),
                ptr::null(),
                0,
            );
            assert!(!doc.is_null());

            let result = xsltApplyStylesheet(style, doc, ptr::null_mut());
            assert!(!result.is_null(), "apply failed");

            let mut txt: *mut xmlChar = ptr::null_mut();
            let mut len: c_int = 0;
            let ret = crate::xslt::serialization::xsltSaveResultToString(
                &mut txt, &mut len, result, style,
            );
            assert_eq!(ret, 0);
            let out = String::from_utf8_lossy(core::slice::from_raw_parts(txt, len as usize));
            assert!(
                out.contains("world"),
                "result should contain the selected value, got: {}",
                out
            );

            libc::free(txt as *mut libc::c_void);
            crate::xml::tree::free_doc(result);
            crate::xml::tree::free_doc(doc);
            crate::xslt::stylesheet::xsltFreeStylesheet(style);
        }
    }

    /// Helper: transform a source document with a stylesheet and return the
    /// serialized result.
    unsafe fn run_transform(xsl: &[u8], src: &[u8]) -> String {
        let style = crate::xslt::stylesheet::xsltParseStylesheetMemory(
            xsl.as_ptr() as *const c_char,
            (xsl.len() - 1) as c_int,
            ptr::null(),
        );
        assert!(!style.is_null(), "stylesheet parse failed");
        let doc = crate::abi::exports_xml2::xmlReadMemory(
            src.as_ptr() as *const c_char,
            (src.len() - 1) as c_int,
            ptr::null(),
            ptr::null(),
            0,
        );
        assert!(!doc.is_null());
        let result = xsltApplyStylesheet(style, doc, ptr::null_mut());
        assert!(!result.is_null(), "apply failed");
        let mut txt: *mut xmlChar = ptr::null_mut();
        let mut len: c_int = 0;
        let ret =
            crate::xslt::serialization::xsltSaveResultToString(&mut txt, &mut len, result, style);
        assert_eq!(ret, 0);
        let out =
            String::from_utf8_lossy(core::slice::from_raw_parts(txt, len as usize)).into_owned();
        libc::free(txt as *mut libc::c_void);
        crate::xml::tree::free_doc(result);
        crate::xml::tree::free_doc(doc);
        crate::xslt::stylesheet::xsltFreeStylesheet(style);
        out
    }

    #[test]
    /// Tests `xsl:for-each` over the selected nodes.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers that stay
    ///   alive for the whole `run_transform` call, which parses, transforms,
    ///   and serializes them and frees every created document before
    ///   returning.
    fn test_xslt_for_each() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <list><xsl:for-each select=\"/root/item\"><i><xsl:value-of select=\".\"/></i></xsl:for-each></list>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src =
                b"<?xml version=\"1.0\"?><root><item>a</item><item>b</item><item>c</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<i>a</i>"), "got: {}", out);
            assert!(out.contains("<i>b</i>"), "got: {}", out);
            assert!(out.contains("<i>c</i>"), "got: {}", out);
        }
    }

    #[test]
    /// Tests that the XPath 1.0 core function library is registered on the
    /// transform context.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_core_functions_in_value_of() {
        // UPSTREAM-PARITY: the transform context must register the XPath 1.0
        // core function library (count, string, substring, ...) so that
        // function calls in XPath expressions evaluate correctly. Before the
        // fix, every function call failed with an unknown-function error.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <cnt><xsl:value-of select=\"count(library/book)\"/></cnt>\
                  <sub><xsl:value-of select=\"substring('hello',1,2)\"/></sub>\
                  <str><xsl:value-of select=\"string(library/book[1]/title)\"/></str>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library>\
              <book><title>Rust</title></book>\
              <book><title>XML</title></book>\
            </library>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<cnt>2</cnt>"), "count() wrong: {}", out);
            assert!(out.contains("<sub>he</sub>"), "substring() wrong: {}", out);
            assert!(out.contains("<str>Rust</str>"), "string() wrong: {}", out);
        }
    }

    #[test]
    /// Tests attribute value templates inside literal result element
    /// attributes.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_avt_in_literal_attribute() {
        // UPSTREAM-PARITY: literal result element attributes may contain
        // attribute value templates (XSLT 1.0 §7.6.2): {expr} is evaluated
        // and its string value substituted, {{ and }} are literal braces.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <xsl:for-each select=\"library/book\">\
                    <book id=\"{@id}\" label=\"{{literal}}\"/>\
                  </xsl:for-each>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library>\
              <book id=\"b1\"/>\
              <book id=\"b2\"/>\
            </library>\0";
            let out = run_transform(xsl, src);
            assert!(
                out.contains("<book id=\"b1\" label=\"{literal}\""),
                "AVT not evaluated: {}",
                out
            );
            assert!(
                out.contains("<book id=\"b2\" label=\"{literal}\""),
                "AVT not evaluated: {}",
                out
            );
        }
    }

    #[test]
    /// Tests that `xsl:element` name is treated as an AVT.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_avt_in_xsl_element_name() {
        // UPSTREAM-PARITY: xsl:element/@name is an AVT.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <xsl:element name=\"el-{library/book/@id}\">text</xsl:element>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library><book id=\"b1\"/></library>\0";
            let out = run_transform(xsl, src);
            assert!(
                out.contains("<el-b1>"),
                "xsl:element AVT not evaluated: {}",
                out
            );
        }
    }

    #[test]
    /// Tests that a variable with inline content is copied into a result tree
    /// fragment and stringifies to its full descendant text.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_variable_inline_content_rtf() {
        // UPSTREAM-PARITY: a variable with inline content is a result tree
        // fragment. Regression test: the inline content must be copied into
        // a context-owned RVT (not left pointing into the stylesheet doc,
        // which caused a double-free at teardown), and $var must stringify
        // to the full descendant text.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:variable name=\"rtf\"><nums><n>3</n><n>7</n></nums></xsl:variable>\
              <xsl:template match=\"/\">\
                <out><v><xsl:value-of select=\"$rtf\"/></v></out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            // Must complete without a double-free and produce the text.
            let out = run_transform(xsl, src);
            assert!(out.contains("<v>37</v>"), "RTF string-value wrong: {}", out);
        }
    }

    #[test]
    /// Tests `exsl:node-set` on a result tree fragment variable.
    ///
    /// # Safety
    ///
    /// - `exslt::register_all` runs before the transform; the `xsl` and `src`
    ///   byte slices are NUL-terminated buffers alive for the whole
    ///   `run_transform` call, which parses, transforms, and serializes them
    ///   and frees every created document before returning.
    fn test_xslt_exsl_node_set_on_rtf() {
        // UPSTREAM-PARITY: exsl:node-set($var) on an RTF variable yields a
        // node-set whose root is the RVT document node, so path navigation
        // and node-set functions work on it (§35).
        unsafe {
            crate::exslt::register_all();
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:exsl=\"http://exslt.org/common\" xmlns:math=\"http://exslt.org/math\" extension-element-prefixes=\"exsl math\">\
              <xsl:variable name=\"rtf\"><nums><n>3</n><n>7</n><n>1</n><n>9</n></nums></xsl:variable>\
              <xsl:template match=\"/\">\
                <out>\
                  <max><xsl:value-of select=\"math:max(exsl:node-set($rtf)/nums/n)\"/></max>\
                  <cnt><xsl:value-of select=\"count(exsl:node-set($rtf)/nums/n)\"/></cnt>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<max>9</max>"), "math:max wrong: {}", out);
            assert!(out.contains("<cnt>4</cnt>"), "count wrong: {}", out);
        }
    }

    #[test]
    /// Tests that `extension-element-prefixes` and `exclude-result-prefixes`
    /// namespaces are not copied into the result tree (XSLT 1.0 §14.1 / §7.1.3).
    ///
    /// Regression: the unprefixed forms on `xsl:stylesheet` were missed by the
    /// namespace check, so `xmlns:exsl` leaked into every serialized result.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call.
    fn test_xslt_extension_prefixes_excluded_from_result() {
        unsafe {
            crate::exslt::register_all();
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:exsl=\"http://exslt.org/common\" extension-element-prefixes=\"exsl\">\
              <xsl:template match=\"/\">\
                <out><v><xsl:value-of select=\"count(exsl:node-set(/doc/b)/b)\"/></v></out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><doc><b>x</b></doc>\0";
            let out = run_transform(xsl, src);
            assert!(
                !out.contains("xmlns:exsl"),
                "extension-element-prefixes leaked: {}",
                out
            );

            let xsl2 = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:exsl=\"http://exslt.org/common\" exclude-result-prefixes=\"exsl\">\
              <xsl:template match=\"/\">\
                <out><v><xsl:value-of select=\"count(exsl:node-set(/doc/b)/b)\"/></v></out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let out2 = run_transform(xsl2, src);
            assert!(
                !out2.contains("xmlns:exsl"),
                "exclude-result-prefixes leaked: {}",
                out2
            );
        }
    }

    #[test]
    /// Tests that `xsl:if` accepts a node-set `test` expression.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_if_node_set_test() {
        // UPSTREAM-PARITY: xsl:if/@test may be a node-set (XPath boolean
        // conversion §4.3). Regression: the transform read only boolval,
        // which is 0 for node-set objects, so test="author" was always
        // false.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <xsl:for-each select=\"library/book\">\
                    <b><xsl:if test=\"author\">A</xsl:if><xsl:if test=\"missing\">M</xsl:if></b>\
                  </xsl:for-each>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library><book><author>x</author></book><book/></library>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<b>A</b>"), "node-set test false: {}", out);
            assert!(out.contains("<b/>"), "missing-node test true: {}", out);
        }
    }

    #[test]
    /// Tests that attribute string values are used by `string` and
    /// predicates.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_attribute_string_value() {
        // UPSTREAM-PARITY: string(@attr) / @attr='x' predicates use the
        // attribute's string value. Regression: node_string_value treated
        // type 13 (XML_HTML_DOCUMENT_NODE) as attribute and returned empty
        // for real attributes (type 2).
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <x><xsl:value-of select=\"string(library/book[1]/@id)\"/></x>\
                  <y><xsl:value-of select=\"count(library/book[@id='b2'])\"/></y>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library><book id=\"b1\"/><book id=\"b2\"/></library>\0";
            let out = run_transform(xsl, src);
            assert!(
                out.contains("<x>b1</x>"),
                "attr string-value wrong: {}",
                out
            );
            assert!(out.contains("<y>1</y>"), "attr predicate wrong: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:sort` with descending order.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_sort_descending() {
        // UPSTREAM-PARITY: xsl:sort with order="descending" inverts the
        // comparison. Regression: the sort was never compiled (null style)
        // and the sort key evaluated against the wrong context node.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <xsl:for-each select=\"library/book\">\
                    <xsl:sort select=\"title\" order=\"descending\"/>\
                    <i><xsl:value-of select=\"title\"/></i>\
                  </xsl:for-each>\
                </out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library><book><title>Alpha</title></book><book><title>Gamma</title></book><book><title>Beta</title></book></library>\0";
            let out = run_transform(xsl, src);
            let gamma = out.find("<i>Gamma</i>").unwrap();
            let beta = out.find("<i>Beta</i>").unwrap();
            let alpha = out.find("<i>Alpha</i>").unwrap();
            assert!(gamma < beta && beta < alpha, "not descending: {}", out);
        }
    }

    #[test]
    /// Tests the `key` function through the stylesheet key tables.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_key_function() {
        // UPSTREAM-PARITY: key(name, value) resolves through the key tables
        // built from xsl:key definitions.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:key name=\"byAuthor\" match=\"book\" use=\"author\"/>\
              <xsl:template match=\"/\">\
                <out><k><xsl:value-of select=\"key('byAuthor', 'Smith')/title\"/></k></out>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?>\
            <library><book><title>A</title><author>Smith</author></book><book><title>B</title><author>Jones</author></book></library>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<k>A</k>"), "key() wrong: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:call-template` with `xsl:with-param` and `xsl:param`
    /// defaults.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_call_template_with_params() {
        // UPSTREAM-PARITY: xsl:with-param values are visible to $name inside
        // the called template; xsl:param defaults apply when no value is
        // passed. Regression: with-params were never registered in the XPath
        // variable hash.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out>\
                  <xsl:call-template name=\"greet\">\
                    <xsl:with-param name=\"who\" select=\"'World'\"/>\
                  </xsl:call-template>\
                </out>\
              </xsl:template>\
              <xsl:template name=\"greet\">\
                <xsl:param name=\"who\" select=\"'nobody'\"/>\
                <g>Hello <xsl:value-of select=\"$who\"/>!</g>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("Hello World"), "with-param lost: {}", out);
        }
    }

    #[test]
    /// Tests the HTML output method's meta charset insertion and formatting.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_html_method_meta_charset() {
        // UPSTREAM-PARITY: method="html" inserts <meta charset="..."> in
        // the <head> of the root <html> and formats with newlines only.
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:output method=\"html\" indent=\"yes\"/>\
              <xsl:template match=\"/\">\
                <html><head><title>T</title></head><body><p>x</p></body></html>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            let out = run_transform(xsl, src);
            assert!(
                out.contains("<meta charset=\"UTF-8\">"),
                "meta charset missing: {}",
                out
            );
            assert!(!out.contains("  <head>"), "unexpected indent: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:if` with string equality tests.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_if() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <xsl:if test=\"/root/item = 'yes'\"><yes/></xsl:if>\
                <xsl:if test=\"/root/item = 'no'\"><no/></xsl:if>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><item>yes</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<yes/>"), "got: {}", out);
            assert!(!out.contains("<no/>"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:choose` with `xsl:when` and `xsl:otherwise` branches.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_choose() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <xsl:choose>\
                  <xsl:when test=\"/root/item = 'a'\"><chosen>a</chosen></xsl:when>\
                  <xsl:when test=\"/root/item = 'b'\"><chosen>b</chosen></xsl:when>\
                  <xsl:otherwise><chosen>other</chosen></xsl:otherwise>\
                </xsl:choose>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><item>b</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<chosen>b</chosen>"), "got: {}", out);
        }
    }

    #[test]
    /// Tests variables and `xsl:call-template` together.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_variable_and_call_template() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:variable name=\"greeting\" select=\"'Hello'\"/>\
              <xsl:template match=\"/\">\
                <xsl:call-template name=\"say\"/>\
              </xsl:template>\
              <xsl:template name=\"say\">\
                <msg><xsl:value-of select=\"$greeting\"/> <xsl:value-of select=\"/root/name\"/></msg>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><name>World</name></root>\0";
            let out = run_transform(xsl, src);
            // UPSTREAM-PARITY: the whitespace-only text node between the two
            // xsl:value-of instructions is stripped at stylesheet
            // preprocessing, exactly as upstream libxslt does; preserving it
            // requires an explicit <xsl:text> </xsl:text>.
            assert!(out.contains("HelloWorld"), "got: {}", out);
        }
    }

    #[test]
    /// Tests that `xsl:text` preserves whitespace verbatim.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_text_preserves_whitespace() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <msg><xsl:value-of select=\"'Hello'\"/><xsl:text> </xsl:text><xsl:value-of select=\"/root/name\"/></msg>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><name>World</name></root>\0";
            let out = run_transform(xsl, src);
            // UPSTREAM-PARITY: xsl:text content is preserved verbatim.
            assert!(out.contains("Hello World"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:element` and `xsl:attribute` construction.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_element_and_attribute() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <xsl:element name=\"custom\">\
                  <xsl:attribute name=\"attr\">value</xsl:attribute>\
                  <xsl:value-of select=\"/root/item\"/>\
                </xsl:element>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><item>data</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("custom"), "got: {}", out);
            assert!(out.contains("attr=\"value\""), "got: {}", out);
            assert!(out.contains("data"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:apply-templates` with a `select` expression.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_apply_templates_with_select() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <out><xsl:apply-templates select=\"/root/item\"/></out>\
              </xsl:template>\
              <xsl:template match=\"item\"><item><xsl:value-of select=\".\"/></item></xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><item>alpha</item><item>beta</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<item>alpha</item>"), "got: {}", out);
            assert!(out.contains("<item>beta</item>"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:text`, `xsl:comment`, and `xsl:processing-instruction`
    /// output.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_text_and_comment_and_pi() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <xsl:text>plain</xsl:text>\
                <xsl:comment>a comment</xsl:comment>\
                <xsl:processing-instruction name=\"target\">pi-data</xsl:processing-instruction>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("plain"), "got: {}", out);
            assert!(out.contains("<!--a comment-->"), "got: {}", out);
            assert!(out.contains("<?target pi-data?>"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:copy-of` for node sets and literal strings.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_copy_and_copy_of() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <xsl:copy-of select=\"/root/item\"/>\
                <xsl:copy-of select=\"'literal'\"/>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root><item>copied</item></root>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<item>copied</item>"), "got: {}", out);
            assert!(out.contains("literal"), "got: {}", out);
        }
    }

    #[test]
    /// Tests `xsl:number` with explicit values and formats.
    ///
    /// # Safety
    ///
    /// - The `xsl` and `src` byte slices are NUL-terminated buffers alive for
    ///   the whole `run_transform` call, which parses, transforms, and
    ///   serializes them and frees every created document before returning.
    fn test_xslt_number() {
        unsafe {
            let xsl = b"<?xml version=\"1.0\"?>\
            <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\
              <xsl:template match=\"/\">\
                <n><xsl:number value=\"42\"/></n>\
                <r><xsl:number value=\"9\" format=\"I\"/></r>\
              </xsl:template>\
            </xsl:stylesheet>\0";
            let src = b"<?xml version=\"1.0\"?><root/>\0";
            let out = run_transform(xsl, src);
            assert!(out.contains("<n>42</n>"), "got: {}", out);
            assert!(out.contains("<r>IX</r>"), "got: {}", out);
        }
    }
}