libxml-rs 0.1.0-alpha.42

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
//! exports_automata — family closure (11.1-I).
//!
//! C ABI exports for the automata / stream / regex-exec / pattern families
//! from `xmlautomata.h`, `xmlregexp.h`, `pattern.h`, `encoding.h` and
//! `xmlIO.h` that are *not* already exported by the internal engines in
//! `src/xml/automata/mod.rs` and `src/xml/regex/mod.rs`.
//!
//! # What is wired to the internal engines
//!
//! - `xmlAutomata*` "2"-token variants and `xmlAutomataIsDeterminist` call
//!   into `crate::xml::automata` (the base single-token constructors and
//!   `xmlAutomataIsDeterministic` live there and are `#[no_mangle]` already).
//!   The internal automata model is single-byte-token based, so the
//!   `token2` value is folded into the transition token exactly like
//!   upstream folds it into one atom (`token|token2`), but only the first
//!   byte is honored by the engine when compiling/matching.
//! - `xmlRegExecPushString2` ports upstream `xmlregexp.c`'s concatenation
//!   of `value`, `XML_REG_STRING_SEPARATOR` (`|`) and `value2` and pushes
//!   the combined token through `xmlRegExecPushString`.
//! - `xmlRegexpIsDeterminist` delegates to the engine's
//!   `xmlRegexpIsDeterministic`.
//!
//! # Side registries
//!
//! `xmlPattern*` / `xmlStream*` use side registries keyed by fake opaque
//! pointers (upstream keeps these structures in `pattern.c`). A compiled
//! pattern is a list of branches (one per `|` alternative); a stream
//! context is a chain of per-branch contexts, mirroring upstream's
//! `_xmlPattern.next` / `_xmlStreamCtxt.next` lists.
//!
//! # Known divergences from upstream
//!
//! - `xmlPatterncompile` is a faithful port of `pattern.c`'s mini pattern
//!   compiler (`/`, `//`, `.`, `@attr`, `*`, `QName`, `prefix:*`,
//!   `child::`, `attribute::`), including the streaming compilation and
//!   the push/pop stream evaluator. Name scanning approximates XML
//!   `Name`/`NCName` with the ASCII subset plus any byte >= 0x80; the
//!   dictionary argument is stored but not used for interning (all names
//!   are owned copies).
//! - `xmlRegExecNextValues` / `xmlRegExecErrInfo` return `0` with
//!   `nbval`/`nbneg` set to 0: the internal `RegExecCtxt` does not expose
//!   its NFA transition table, so the expected-next-value enumeration of
//!   upstream cannot be reproduced. `terminal` is approximated from the
//!   last `xmlRegExecPushString2` result.
//! - `xmlAutomataNewNegTrans` degrades to a plain transition: the
//!   internal automata engine has no negated-transition support.
//! - The `xmlRegister*Callbacks` registrations are stored faithfully in a
//!   side table (the internal I/O layer does not yet consult them) and
//!   `xmlRegisterHTTPPostCallbacks` is a no-op (no HTTP support).
//!
//! # Upstream contract
//!
//! Parity target is upstream `xmlautomata.c`/`xmlregexp.c`/`pattern.c`
//! (libxml2 2.15.3, SRC-LIBXML2-2.15.0-XMLAUTOMATA-C); the signatures follow
//! `xmlautomata.h`, `xmlregexp.h` and `pattern.h` so every symbol here
//! resolves against the oracle DSO export set.
//!
//! # Conceptual behavior
//!
//! This module implements the automata/stream/regex-exec/pattern export
//! family: NFA construction (`xmlAutomataNew*`), determinism checks, regex
//! execution against pushed strings, and the compiled-pattern streaming
//! evaluators, wired to the internal engines in `src/xml/automata` and
//! `src/xml/regex` with the divergences listed above.
//!
//! # Ownership & safety invariants
//!
//! Handles (`xmlAutomataPtr`, `xmlRegExecCtxtPtr`, `xmlPatternPtr`,
//! `xmlStreamCtxtPtr`) are owned by the caller and freed with the matching
//! `xmlAutomataFree*`/`xmlRegFree*`/`xmlPatternFree*`/`xmlStreamFree*` entry
//! points; the side registries keyed by fake opaque pointers keep internal
//! state alive until the free functions run.
//!
//! # Historical quirks & epochs
//!
//! The automata/regex subsystem matured in the 2.6 `validation_era`
//! (HISTORY.md) and has been ABI-stable since; the parity target is the 2.15.3
//! oracle. R-000165 (11.1-O) closed the subsystem census so every oracle-DSO
//! automata symbol is exported.
//!
//! # Deliberate oddities
//!
//! `xmlRegExecNextValues`/`xmlRegExecErrInfo` return 0 with empty value
//! lists, `xmlAutomataNewNegTrans` degrades to a plain transition, and
//! `xmlRegisterHTTPPostCallbacks` is a no-op (no HTTP support) — all
//! deliberate, documented divergences where the internal engine lacks the
//! upstream feature.
//!
//! # Proving courts
//!
//! The RELAXNG/automata probes and the DSO-LOADER court (25/25 symbols load)
//! plus HEADER-COMPILE exercise this module; the data-ABI family
//! probes require byte-identical behavior on the supported paths.
//!
//! # Tempting simplifications that would break parity
//!
//! A tempting simplification is to fold the token2 value into a single token
//! and claim full two-token support — the header already documents that only
//! the first byte is honored by the engine; widening the claim would break the
//! automata probes that feed two-byte tokens. Dropping the side registries
//! would make pattern/stream handles dangle across calls.

#![allow(
    missing_docs,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals
)]

// SAFETY-SCOPE: EXPORT-AUTOMATA-MECHANICAL-001
// (11.1-Z.3 proof scope, classified-generated) — this module is the
// mechanical extern-"C" export surface: every `unsafe` block in it is
// the documented indirection/registry-access pattern whose validity
// rests on the upstream C contract, and the exported signatures are
// machine-measured by the ABI-FUNCTION-SIGNATURE and DSO-LOADER
// courts and the C-API differential probes. The safety contract of
// each export is stated in its own doc comment; this scope covers the
// mechanical wrappers' unsafe blocks.

use core::ffi::c_void;
use core::ptr;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::os::raw::{c_char, c_int};

use crate::abi::callbacks::{
    xmlInputCloseCallback, xmlInputReadCallback, xmlOutputCloseCallback, xmlOutputWriteCallback,
};
use crate::abi::structs::{_xmlCharEncodingHandler, _xmlNode};
use crate::abi::types::xmlChar;
use crate::xml::automata::{
    xmlAutomataIsDeterministic, xmlAutomataNewCountTrans, xmlAutomataNewOnceTrans,
    xmlAutomataNewState, xmlAutomataNewTransition, XmlAutomataPtr, XmlAutomataStatePtr,
};
use crate::xml::encoding;
use crate::xml::regex::{xmlRegExecPushString, xmlRegexpIsDeterministic, RegExecCtxt, XmlRegexp};

// ═══════════════════════════════════════════════════════════════════════════════
// 1. xmlAutomata* — the "2"-token variants and IsDeterminist
//    (base constructors live in src/xml/automata/mod.rs)
// ═══════════════════════════════════════════════════════════════════════════════

/// Build the atom value exactly like upstream `xmlautomata.c` /
/// `xmlregexp.c`: `token` if `token2` is NULL/empty, else `token|token2`.
unsafe fn build_token2_value(token: *const xmlChar, token2: *const xmlChar) -> Option<Vec<u8>> {
    if token.is_null() {
        return None;
    }
    let lenp = cstr_len(token);
    let lenn = if token2.is_null() {
        0
    } else {
        cstr_len(token2)
    };
    if lenn == 0 {
        let mut v = Vec::with_capacity(lenp + 1);
        v.extend_from_slice(unsafe { core::slice::from_raw_parts(token, lenp) });
        v.push(0);
        return Some(v);
    }
    let mut v = Vec::with_capacity(lenp + lenn + 2);
    v.extend_from_slice(unsafe { core::slice::from_raw_parts(token, lenp) });
    v.push(b'|');
    v.extend_from_slice(unsafe { core::slice::from_raw_parts(token2, lenn) });
    v.push(0);
    Some(v)
}

/// Upstream `int xmlAutomataIsDeterminist(xmlAutomata *am)` — delegates to
/// the engine's `xmlAutomataIsDeterministic` (compiled regex determinism).
///
/// # SAFETY
///
/// - `am` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlAutomataIsDeterminist(am: XmlAutomataPtr) -> c_int {
    xmlAutomataIsDeterministic(am)
}

/// Upstream `xmlAutomataState * xmlAutomataNewTransition2(...)`.
///
/// If `to` is NULL a new target state is created (upstream creates the
/// state and returns it). The `token`/`token2` pair is folded into one
/// atom value (`token|token2`) like upstream, then wired through the
/// internal single-token transition builder.
///
/// # SAFETY
///
/// - `am`, `from`, `to`, `data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `token`, `token2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlAutomataNewTransition2(
    am: XmlAutomataPtr,
    from: XmlAutomataStatePtr,
    to: XmlAutomataStatePtr,
    token: *const xmlChar,
    token2: *const xmlChar,
    data: *mut c_void,
) -> XmlAutomataStatePtr {
    if am.is_null() || from.is_null() || token.is_null() {
        return ptr::null_mut();
    }
    let value = match unsafe { build_token2_value(token, token2) } {
        Some(v) => v,
        None => return ptr::null_mut(),
    };
    let target = if to.is_null() {
        let s = xmlAutomataNewState(am);
        if s.is_null() {
            return ptr::null_mut();
        }
        s
    } else {
        to
    };
    xmlAutomataNewTransition(am, from, target, value.as_ptr() as *const c_char, data);
    target
}

/// Upstream `xmlAutomataState * xmlAutomataNewNegTrans(...)`.
///
/// Upstream creates a negated atom (`atom->neg = 1`, `valuep2 = "not X"`).
/// The internal engine has no negated transitions, so this degrades to a
/// plain `token|token2` transition (see module docs).
///
/// # SAFETY
///
/// - `am`, `from`, `to`, `data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `token`, `token2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlAutomataNewNegTrans(
    am: XmlAutomataPtr,
    from: XmlAutomataStatePtr,
    to: XmlAutomataStatePtr,
    token: *const xmlChar,
    token2: *const xmlChar,
    data: *mut c_void,
) -> XmlAutomataStatePtr {
    xmlAutomataNewTransition2(am, from, to, token, token2, data)
}

/// Upstream `xmlAutomataState * xmlAutomataNewCountTrans2(...)` — same
/// atom-value folding as upstream, with the same argument validation
/// (`min < 0`, `max < min`, `max < 1` → NULL).
///
/// # SAFETY
///
/// - `am`, `from`, `to`, `data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `token`, `token2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlAutomataNewCountTrans2(
    am: XmlAutomataPtr,
    from: XmlAutomataStatePtr,
    to: XmlAutomataStatePtr,
    token: *const xmlChar,
    token2: *const xmlChar,
    min: c_int,
    max: c_int,
    data: *mut c_void,
) -> XmlAutomataStatePtr {
    if am.is_null() || from.is_null() || token.is_null() {
        return ptr::null_mut();
    }
    if min < 0 {
        return ptr::null_mut();
    }
    if (max < min) || (max < 1) {
        return ptr::null_mut();
    }
    let value = match unsafe { build_token2_value(token, token2) } {
        Some(v) => v,
        None => return ptr::null_mut(),
    };
    let target = if to.is_null() {
        let s = xmlAutomataNewState(am);
        if s.is_null() {
            return ptr::null_mut();
        }
        s
    } else {
        to
    };
    xmlAutomataNewCountTrans(
        am,
        from,
        target,
        value.as_ptr() as *const c_char,
        min,
        max,
        data,
    );
    target
}

/// Upstream `xmlAutomataState * xmlAutomataNewOnceTrans2(...)` — validation
/// is `min < 1` or `max < min` → NULL (matches upstream `xmlregexp.c`).
///
/// # SAFETY
///
/// - `am`, `from`, `to`, `data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `token`, `token2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlAutomataNewOnceTrans2(
    am: XmlAutomataPtr,
    from: XmlAutomataStatePtr,
    to: XmlAutomataStatePtr,
    token: *const xmlChar,
    token2: *const xmlChar,
    min: c_int,
    max: c_int,
    data: *mut c_void,
) -> XmlAutomataStatePtr {
    if am.is_null() || from.is_null() || token.is_null() {
        return ptr::null_mut();
    }
    if min < 1 {
        return ptr::null_mut();
    }
    if max < min {
        return ptr::null_mut();
    }
    let value = match unsafe { build_token2_value(token, token2) } {
        Some(v) => v,
        None => return ptr::null_mut(),
    };
    let target = if to.is_null() {
        let s = xmlAutomataNewState(am);
        if s.is_null() {
            return ptr::null_mut();
        }
        s
    } else {
        to
    };
    xmlAutomataNewOnceTrans(
        am,
        from,
        target,
        value.as_ptr() as *const c_char,
        min,
        max,
        data,
    );
    target
}

// ═══════════════════════════════════════════════════════════════════════════════
// 2. xmlReg* / xmlRegexpIsDeterminist — regex execution context exports
// ═══════════════════════════════════════════════════════════════════════════════

/// Last-push state tracked per exec context (upstream keeps this inside
/// `_xmlRegExecCtxt`; the internal `RegExecCtxt` does not expose it).
#[derive(Debug, Clone, Copy, Default)]
struct ExecState {
    last_ret: c_int,
}

static EXEC_STATE: Lazy<Mutex<HashMap<usize, ExecState>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

/// Upstream `int xmlRegExecPushString2(xmlRegExecCtxt *exec,
/// const xmlChar *value, const xmlChar *value2, void *data)`.
///
/// Concatenates `value`, the string separator (`|`) and `value2` into one
/// token and pushes it (exactly the strategy of upstream `xmlregexp.c`).
/// `value2 == NULL` behaves like `xmlRegExecPushString(exec, value, data)`.
///
/// # SAFETY
///
/// - `exec`, `_data` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `value`, `value2` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegExecPushString2(
    exec: *mut RegExecCtxt,
    value: *const xmlChar,
    value2: *const xmlChar,
    _data: *mut c_void,
) -> c_int {
    if exec.is_null() {
        return -1;
    }
    if value2.is_null() || value.is_null() {
        let ret = xmlRegExecPushString(exec, value, _data);
        EXEC_STATE
            .lock()
            .insert(exec as usize, ExecState { last_ret: ret });
        return ret;
    }
    let lenp = cstr_len(value);
    let lenn = cstr_len(value2);
    let mut buf = Vec::with_capacity(lenp + lenn + 2);
    buf.extend_from_slice(unsafe { core::slice::from_raw_parts(value, lenp) });
    buf.push(b'|');
    buf.extend_from_slice(unsafe { core::slice::from_raw_parts(value2, lenn) });
    buf.push(0);
    let ret = xmlRegExecPushString(exec, buf.as_ptr(), _data);
    EXEC_STATE
        .lock()
        .insert(exec as usize, ExecState { last_ret: ret });
    ret
}

/// Best-effort "expected next values" extraction.
///
/// The internal `RegExecCtxt` (an NFA state-set simulator) does not expose
/// the transition table needed to enumerate the acceptable next tokens, so
/// this returns success with an empty value list; `terminal` reflects the
/// last push result (1 if the last push completed a match).
///
/// # SAFETY
///
/// - `exec`, `nbval`, `nbneg`, `values`, `terminal` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegExecNextValues(
    exec: *mut RegExecCtxt,
    nbval: *mut c_int,
    nbneg: *mut c_int,
    values: *mut *mut xmlChar,
    terminal: *mut c_int,
) -> c_int {
    if exec.is_null() || nbval.is_null() || nbneg.is_null() || values.is_null() {
        return -1;
    }
    if unsafe { *nbval } <= 0 {
        return -1;
    }
    unsafe {
        *nbval = 0;
        *nbneg = 0;
    }
    if !terminal.is_null() {
        let last = EXEC_STATE
            .lock()
            .get(&(exec as usize))
            .map_or(0, |s| s.last_ret);
        unsafe { *terminal = if last == 1 { 1 } else { 0 } };
    }
    0
}

/// Best-effort error-info extraction: reports no error string and an empty
/// value list (see `xmlRegExecNextValues` for why the value enumeration is
/// unavailable).
///
/// # SAFETY
///
/// - `exec`, `nbval`, `nbneg`, `values`, `terminal` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `string` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegExecErrInfo(
    exec: *mut RegExecCtxt,
    string: *mut *const xmlChar,
    nbval: *mut c_int,
    nbneg: *mut c_int,
    values: *mut *mut xmlChar,
    terminal: *mut c_int,
) -> c_int {
    if exec.is_null() {
        return -1;
    }
    if !string.is_null() {
        unsafe { *string = ptr::null() };
    }
    xmlRegExecNextValues(exec, nbval, nbneg, values, terminal)
}

/// Upstream `int xmlRegexpIsDeterminist(xmlRegexp *comp)` — delegates to
/// the engine's `xmlRegexpIsDeterministic`.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub const unsafe extern "C" fn xmlRegexpIsDeterminist(comp: *const XmlRegexp) -> c_int {
    xmlRegexpIsDeterministic(comp)
}

// ═══════════════════════════════════════════════════════════════════════════════
// 3. Encoding / I/O registration exports
// ═══════════════════════════════════════════════════════════════════════════════

/// Upstream `void xmlRegisterCharEncodingHandler(xmlCharEncodingHandler *handler)`.
///
/// Registers the handler in the encoding subsystem's global table.
///
/// # SAFETY
///
/// - `handler` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlRegisterCharEncodingHandler(handler: *mut _xmlCharEncodingHandler) {
    encoding::add_encoding_handler(handler);
}

/// `xmlInputMatchCallback` (xmlIO.h): decides whether a handler can open a
/// given filename.
pub type xmlInputMatchCallback =
    unsafe extern "C" fn(context: *mut c_void, filename: *const c_char) -> c_int;

/// `xmlInputOpenCallback` (xmlIO.h): opens the input, returning a context.
pub type xmlInputOpenCallback =
    unsafe extern "C" fn(context: *mut c_void, filename: *const c_char) -> *mut c_void;

/// `xmlOutputMatchCallback` (xmlIO.h).
pub type xmlOutputMatchCallback =
    unsafe extern "C" fn(context: *mut c_void, filename: *const c_char) -> c_int;

/// `xmlOutputOpenCallback` (xmlIO.h).
pub type xmlOutputOpenCallback =
    unsafe extern "C" fn(context: *mut c_void, filename: *const c_char) -> *mut c_void;

/// One registered input-callback set (upstream `xmlInputCallbackTable[]`).
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct InputCallbackSet {
    match_cb: Option<xmlInputMatchCallback>,
    open_cb: Option<xmlInputOpenCallback>,
    read_cb: Option<xmlInputReadCallback>,
    close_cb: Option<xmlInputCloseCallback>,
}

/// One registered output-callback set (upstream `xmlOutputCallbackTable[]`).
#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct OutputCallbackSet {
    match_cb: Option<xmlOutputMatchCallback>,
    open_cb: Option<xmlOutputOpenCallback>,
    write_cb: Option<xmlOutputWriteCallback>,
    close_cb: Option<xmlOutputCloseCallback>,
}

#[allow(dead_code)]
static INPUT_CALLBACKS: Lazy<Mutex<Vec<InputCallbackSet>>> = Lazy::new(|| Mutex::new(Vec::new()));
#[allow(dead_code)]
static OUTPUT_CALLBACKS: Lazy<Mutex<Vec<OutputCallbackSet>>> = Lazy::new(|| Mutex::new(Vec::new()));

/// The compiled-in default match callback (upstream `xmlIODefaultMatch`):
/// matches every filename.
#[allow(dead_code)]
const unsafe extern "C" fn xml_io_default_match(
    _context: *mut c_void,
    _filename: *const c_char,
) -> c_int {
    1
}

// Upstream `int xmlRegisterInputCallbacks(...)` — returns the registered
// Upstream `int xmlRegisterOutputCallbacks(...)` — returns the registered
// Upstream `void xmlRegisterHTTPPostCallbacks(void)`.
//
// No-op: this build has no HTTP transport (upstream gates it behind
// ═══════════════════════════════════════════════════════════════════════════════
// 4. xmlPattern* / xmlStream* — pattern compiler, matcher and stream engine
//    (port of archaeology/libxml2-git/pattern.c)
// ═══════════════════════════════════════════════════════════════════════════════

/// Opaque pattern handle type (`pattern.h`: `typedef struct _xmlPattern xmlPattern`).
#[derive(Debug)]
#[repr(C)]
pub struct _xmlPattern {
    _opaque: [u8; 0],
}

/// Opaque stream-context handle type (`pattern.h`: `_xmlStreamCtxt`).
#[derive(Debug)]
#[repr(C)]
pub struct _xmlStreamCtxt {
    _opaque: [u8; 0],
}

pub type xmlPatternPtr = *mut _xmlPattern;
pub type xmlStreamCtxtPtr = *mut _xmlStreamCtxt;

// ── Pattern flags (pattern.h + private pattern.c bits) ────────────────────

#[allow(dead_code)]
const XML_PATTERN_DEFAULT: c_int = 0;
const XML_PATTERN_XPATH: c_int = 1 << 0;
const XML_PATTERN_XSSEL: c_int = 1 << 1;
const XML_PATTERN_XSFIELD: c_int = 1 << 2;
const XML_PATTERN_NOTPATTERN: c_int = XML_PATTERN_XPATH | XML_PATTERN_XSSEL | XML_PATTERN_XSFIELD;
const PAT_FROM_ROOT: c_int = 1 << 8;
const PAT_FROM_CUR: c_int = 1 << 9;

// ── Stream step/comp flags (pattern.c) ────────────────────────────────────

const XML_STREAM_STEP_DESC: c_int = 1;
const XML_STREAM_STEP_FINAL: c_int = 2;
const XML_STREAM_STEP_ROOT: c_int = 4;
const XML_STREAM_STEP_ATTR: c_int = 8;
const XML_STREAM_STEP_NODE: c_int = 16;
const XML_STREAM_STEP_IN_SET: c_int = 32;
const XML_STREAM_FINAL_IS_ANY_NODE: c_int = 1 << 14;
const XML_STREAM_FROM_ROOT: c_int = 1 << 15;
const XML_STREAM_DESC: c_int = 1 << 16;
const XML_STREAM_ANY_NODE: c_int = 100;

/// Node types used by the pattern engine (tree.h `xmlElementType` values).
const XML_ELEMENT_NODE: c_int = 1;
const XML_ATTRIBUTE_NODE: c_int = 2;
const XML_DOCUMENT_NODE: c_int = 9;
const XML_HTML_DOCUMENT_NODE: c_int = 13;
const XML_NAMESPACE_DECL: c_int = 18;

// ── Pattern op codes (pattern.c `xmlPatOp`) ───────────────────────────────

const XML_OP_END: c_int = 0;
const XML_OP_ROOT: c_int = 1;
const XML_OP_ELEM: c_int = 2;
const XML_OP_CHILD: c_int = 3;
const XML_OP_ATTR: c_int = 4;
const XML_OP_PARENT: c_int = 5;
const XML_OP_ANCESTOR: c_int = 6;
const XML_OP_NS: c_int = 7;
const XML_OP_ALL: c_int = 8;

/// One compiled step (pattern.c `xmlStepOp`).
#[derive(Debug, Clone)]
struct StepOp {
    op: c_int,
    value: Option<Vec<u8>>,
    value2: Option<Vec<u8>>,
}

/// One `|` alternative of a compiled pattern (pattern.c `_xmlPattern`).
#[derive(Debug, Clone)]
struct CompiledPattern {
    flags: c_int,
    steps: Vec<StepOp>,
    stream: Option<StreamComp>,
}

/// Streaming compilation (pattern.c `_xmlStreamComp`).
#[derive(Debug, Clone)]
struct StreamComp {
    nb_step: usize,
    steps: Vec<StreamStep>,
    flags: c_int,
}

/// One streaming step (pattern.c `_xmlStreamStep`).
#[derive(Debug, Clone)]
struct StreamStep {
    flags: c_int,
    name: Option<Vec<u8>>,
    ns: Option<Vec<u8>>,
    node_type: c_int,
}

/// Registry entry for a compiled pattern (all `|` branches).
struct PatternState {
    branches: Vec<CompiledPattern>,
}

/// Registry entry for one stream context of one branch (pattern.c
/// `_xmlStreamCtxt`); `next` chains the branch contexts.
struct StreamCtxtState {
    comp: StreamComp,
    next: Option<usize>,
    nb_state: usize,
    states: Vec<(i32, i32)>,
    level: c_int,
    flags: c_int,
    block_level: c_int,
}

static PATTERNS: Lazy<Mutex<HashMap<usize, PatternState>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));
static NEXT_PATTERN_KEY: Lazy<Mutex<usize>> = Lazy::new(|| Mutex::new(1));

static STREAM_CTXTS: Lazy<Mutex<HashMap<usize, StreamCtxtState>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));
static NEXT_STREAM_KEY: Lazy<Mutex<usize>> = Lazy::new(|| Mutex::new(1));

// ── Small string helpers ───────────────────────────────────────────────────

/// Length of a null-terminated xmlChar string.
const unsafe fn cstr_len(s: *const xmlChar) -> usize {
    if s.is_null() {
        return 0;
    }
    let mut len = 0usize;
    while unsafe { *s.add(len) } != 0 {
        len += 1;
    }
    len
}

/// Compare an owned byte slice with a null-terminated C string.
const unsafe fn cstr_eq_opt(s: Option<&[u8]>, cstr: *const xmlChar) -> bool {
    match s {
        None => cstr.is_null(),
        Some(bytes) => {
            if cstr.is_null() {
                return false;
            }
            let mut i = 0usize;
            while i < bytes.len() {
                if unsafe { *cstr.add(i) } != bytes[i] {
                    return false;
                }
                i += 1;
            }
            unsafe { *cstr.add(i) == 0 }
        }
    }
}

// ── The interpreter (pattern.c xmlPatMatch) ────────────────────────────────

/// Port of `xmlPatMatch` from pattern.c — tests whether `node` matches one
/// branch of a compiled pattern. Returns 1 on match, 0 on no match, -1 on
/// error.
unsafe fn pat_match(comp: &CompiledPattern, mut node: *mut _xmlNode) -> c_int {
    if node.is_null() {
        return -1;
    }
    let mut i: isize = 0;
    // Rollback states for "//" (pattern.c xmlStepStates).
    let mut states: Vec<(isize, *mut _xmlNode)> = Vec::new();

    loop {
        // The step-processing block; `break 'process` performs the C code's
        // `goto rollback`.
        'process: {
            while (i as usize) < comp.steps.len() {
                let op = comp.steps[i as usize].op;
                match op {
                    XML_OP_END => return 1,
                    XML_OP_ROOT => {
                        if unsafe { (*node).type_ } == XML_NAMESPACE_DECL {
                            break 'process;
                        }
                        node = unsafe { (*node).parent };
                        if node.is_null() {
                            break 'process;
                        }
                        let t = unsafe { (*node).type_ };
                        if t == XML_DOCUMENT_NODE || t == XML_HTML_DOCUMENT_NODE {
                            i += 1;
                            continue;
                        }
                        break 'process;
                    }
                    XML_OP_ELEM => {
                        if unsafe { (*node).type_ } != XML_ELEMENT_NODE {
                            break 'process;
                        }
                        let value = comp.steps[i as usize].value.clone();
                        let value2 = comp.steps[i as usize].value2.clone();
                        if let Some(value) = value {
                            let nm = unsafe { (*node).name };
                            if nm.is_null() || value[0] != *nm {
                                break 'process;
                            }
                            if !cstr_eq_opt(Some(&value), nm) {
                                break 'process;
                            }
                            // Namespace test.
                            let ns_href: *const xmlChar = if unsafe { (*node).ns }.is_null() {
                                ptr::null()
                            } else {
                                unsafe { (*(*node).ns).href }
                            };
                            if ns_href.is_null() {
                                if value2.is_some() {
                                    break 'process;
                                }
                            } else if unsafe { *ns_href } != 0 {
                                if value2.is_none() {
                                    break 'process;
                                }
                                if !cstr_eq_opt(value2.as_deref(), ns_href) {
                                    break 'process;
                                }
                            }
                        }
                        i += 1;
                        continue;
                    }
                    XML_OP_CHILD => {
                        let t = unsafe { (*node).type_ };
                        if t != XML_ELEMENT_NODE
                            && t != XML_DOCUMENT_NODE
                            && t != XML_HTML_DOCUMENT_NODE
                        {
                            break 'process;
                        }
                        let value = comp.steps[i as usize].value.clone();
                        let mut lst = unsafe { (*node).children };
                        if let Some(value) = value {
                            while !lst.is_null() {
                                let lt = unsafe { (*lst).type_ };
                                let ln = unsafe { (*lst).name };
                                if lt == XML_ELEMENT_NODE
                                    && !ln.is_null()
                                    && value[0] == *ln
                                    && cstr_eq_opt(Some(&value), ln)
                                {
                                    break;
                                }
                                lst = unsafe { (*lst).next };
                            }
                            if !lst.is_null() {
                                i += 1;
                                continue;
                            }
                        }
                        break 'process;
                    }
                    XML_OP_ATTR => {
                        if unsafe { (*node).type_ } != XML_ATTRIBUTE_NODE {
                            break 'process;
                        }
                        let value = comp.steps[i as usize].value.clone();
                        let value2 = comp.steps[i as usize].value2.clone();
                        if let Some(value) = value {
                            let nm = unsafe { (*node).name };
                            if nm.is_null() || value[0] != *nm {
                                break 'process;
                            }
                            if !cstr_eq_opt(Some(&value), nm) {
                                break 'process;
                            }
                        }
                        let ns_href: *const xmlChar = if unsafe { (*node).ns }.is_null() {
                            ptr::null()
                        } else {
                            unsafe { (*(*node).ns).href }
                        };
                        if ns_href.is_null() {
                            if value2.is_some() {
                                break 'process;
                            }
                        } else if value2.is_some() && !cstr_eq_opt(value2.as_deref(), ns_href) {
                            break 'process;
                        }
                        i += 1;
                        continue;
                    }
                    XML_OP_PARENT => {
                        let t = unsafe { (*node).type_ };
                        if t == XML_DOCUMENT_NODE
                            || t == XML_HTML_DOCUMENT_NODE
                            || t == XML_NAMESPACE_DECL
                        {
                            break 'process;
                        }
                        node = unsafe { (*node).parent };
                        if node.is_null() {
                            break 'process;
                        }
                        let value = comp.steps[i as usize].value.clone();
                        let value2 = comp.steps[i as usize].value2.clone();
                        if let Some(value) = value {
                            let nm = unsafe { (*node).name };
                            if nm.is_null() || value[0] != *nm {
                                break 'process;
                            }
                            if !cstr_eq_opt(Some(&value), nm) {
                                break 'process;
                            }
                            let ns_href: *const xmlChar = if unsafe { (*node).ns }.is_null() {
                                ptr::null()
                            } else {
                                unsafe { (*(*node).ns).href }
                            };
                            if ns_href.is_null() {
                                if value2.is_some() {
                                    break 'process;
                                }
                            } else if unsafe { *ns_href } != 0 {
                                if value2.is_none() {
                                    break 'process;
                                }
                                if !cstr_eq_opt(value2.as_deref(), ns_href) {
                                    break 'process;
                                }
                            }
                        }
                        i += 1;
                        continue;
                    }
                    XML_OP_ANCESTOR => {
                        let mut value = comp.steps[i as usize].value.clone();
                        let mut value2 = comp.steps[i as usize].value2.clone();
                        let mut step_op = comp.steps[i as usize].op;
                        if value.is_none() {
                            i += 1;
                            if (i as usize) >= comp.steps.len() {
                                break 'process;
                            }
                            step_op = comp.steps[i as usize].op;
                            if step_op == XML_OP_ROOT {
                                return 1;
                            }
                            if step_op != XML_OP_ELEM {
                                break 'process;
                            }
                            value = comp.steps[i as usize].value.clone();
                            value2 = comp.steps[i as usize].value2.clone();
                            if value.is_none() {
                                return -1;
                            }
                        }
                        if node.is_null() {
                            break 'process;
                        }
                        let t = unsafe { (*node).type_ };
                        if t == XML_DOCUMENT_NODE
                            || t == XML_HTML_DOCUMENT_NODE
                            || t == XML_NAMESPACE_DECL
                        {
                            break 'process;
                        }
                        node = unsafe { (*node).parent };
                        let value = match value {
                            Some(v) => v,
                            None => break 'process,
                        };
                        while !node.is_null() {
                            let nt = unsafe { (*node).type_ };
                            let nn = unsafe { (*node).name };
                            if nt == XML_ELEMENT_NODE
                                && !nn.is_null()
                                && value[0] == *nn
                                && cstr_eq_opt(Some(&value), nn)
                            {
                                // Namespace test.
                                let ns_href: *const xmlChar = if unsafe { (*node).ns }.is_null() {
                                    ptr::null()
                                } else {
                                    unsafe { (*(*node).ns).href }
                                };
                                if ns_href.is_null() {
                                    if value2.is_none() {
                                        break;
                                    }
                                } else if unsafe { *ns_href } != 0
                                    && value2.is_some()
                                    && cstr_eq_opt(value2.as_deref(), ns_href)
                                {
                                    break;
                                }
                            }
                            node = unsafe { (*node).parent };
                        }
                        if node.is_null() {
                            break 'process;
                        }
                        // Prepare a potential rollback from this ancestor.
                        if step_op == XML_OP_ANCESTOR {
                            states.push((i, node));
                        } else {
                            states.push((i - 1, node));
                        }
                        i += 1;
                        continue;
                    }
                    XML_OP_NS => {
                        if unsafe { (*node).type_ } != XML_ELEMENT_NODE {
                            break 'process;
                        }
                        let value = comp.steps[i as usize].value.clone();
                        let ns_href: *const xmlChar = if unsafe { (*node).ns }.is_null() {
                            ptr::null()
                        } else {
                            unsafe { (*(*node).ns).href }
                        };
                        if ns_href.is_null() {
                            if value.is_some() {
                                break 'process;
                            }
                        } else if unsafe { *ns_href } != 0 {
                            if value.is_none() {
                                break 'process;
                            }
                            if !cstr_eq_opt(value.as_deref(), ns_href) {
                                break 'process;
                            }
                        }
                        i += 1;
                        continue;
                    }
                    XML_OP_ALL => {
                        if unsafe { (*node).type_ } != XML_ELEMENT_NODE {
                            break 'process;
                        }
                        i += 1;
                        continue;
                    }
                    _ => {
                        // Unknown op: treat like upstream's default (no case) —
                        // falls to the for-loop increment.
                        i += 1;
                    }
                }
            }
            // fell out of the step loop: found.
            return 1;
        }
        // rollback: try the saved ancestor state, if any.
        match states.pop() {
            None => return 0,
            Some((si, sn)) => {
                i = si;
                node = sn;
                // Continue the outer loop to restart matching from the saved
                // ancestor state (upstream `goto restart`).
            }
        }
    }
}

// ── The mini pattern compiler (pattern.c) ─────────────────────────────────

/// Parser context (pattern.c `xmlPatParserContext`).
struct PatCtxt<'a> {
    cur: usize,
    base: &'a [u8],
    error: c_int,
    /// (URI, prefix) pairs from the `namespaces` argument.
    namespaces: Vec<(Vec<u8>, Vec<u8>)>,
}

const fn is_blank(c: u8) -> bool {
    c == 0x20 || c == 0x9 || c == 0xA || c == 0xD
}

const fn is_name_start(c: u8) -> bool {
    c >= 0x80 || c == b'_' || c == b':' || c.is_ascii_alphabetic()
}

const fn is_name_char(c: u8) -> bool {
    c >= 0x80 || c.is_ascii_alphanumeric() || c == b'.' || c == b'-' || c == b'_' || c == b':'
}

const fn is_ncname_start(c: u8) -> bool {
    c >= 0x80 || c == b'_' || c.is_ascii_alphabetic()
}

const fn is_ncname_char(c: u8) -> bool {
    c >= 0x80 || c.is_ascii_alphanumeric() || c == b'.' || c == b'-' || c == b'_'
}

impl<'a> PatCtxt<'a> {
    fn cur_byte(&self) -> Option<u8> {
        self.base.get(self.cur).copied()
    }

    fn peek(&self, off: usize) -> Option<u8> {
        self.base.get(self.cur + off).copied()
    }

    fn is_blank_cur(&self) -> bool {
        self.cur_byte().is_some_and(is_blank)
    }

    fn skip_blanks(&mut self) {
        while self.cur_byte().is_some_and(is_blank) {
            self.cur += 1;
        }
    }

    /// `xmlPatScanName` — scans an XML Name.
    fn scan_name(&mut self) -> Option<Vec<u8>> {
        self.skip_blanks();
        let start = self.cur;
        let mut cur = start;
        if self.base.get(cur).is_some_and(|&c| !is_name_start(c)) {
            return None;
        }
        cur += 1;
        while self.base.get(cur).is_some_and(|&c| is_name_char(c)) {
            cur += 1;
        }
        if cur == start {
            return None;
        }
        let ret = self.base[start..cur].to_vec();
        self.cur = cur;
        Some(ret)
    }

    /// `xmlPatScanNCName` — scans an NCName.
    fn scan_ncname(&mut self) -> Option<Vec<u8>> {
        self.skip_blanks();
        let start = self.cur;
        let mut cur = start;
        if self.base.get(cur).is_some_and(|&c| !is_ncname_start(c)) {
            return None;
        }
        cur += 1;
        while self.base.get(cur).is_some_and(|&c| is_ncname_char(c)) {
            cur += 1;
        }
        if cur == start {
            return None;
        }
        let ret = self.base[start..cur].to_vec();
        self.cur = cur;
        Some(ret)
    }
}

const XML_XML_NAMESPACE: &[u8] = b"http://www.w3.org/XML/1998/namespace";

/// Resolve a `prefix:name` prefix to its URI (pattern.c's namespace loop,
/// including the special `xml` prefix).
fn resolve_prefix(ctxt: &PatCtxt, prefix: &[u8]) -> Option<Vec<u8>> {
    if prefix == b"xml" {
        return Some(XML_XML_NAMESPACE.to_vec());
    }
    for (uri, pref) in &ctxt.namespaces {
        if pref == prefix {
            return Some(uri.clone());
        }
    }
    None
}

/// Port of `xmlCompileAttributeTest` (pattern.c).
fn compile_attribute_test(ctxt: &mut PatCtxt, comp: &mut CompiledPattern) {
    ctxt.skip_blanks();
    let name = ctxt.scan_ncname();
    if ctxt.error < 0 {
        return;
    }
    let Some(name) = name else {
        if ctxt.cur_byte() == Some(b'*') {
            comp.steps.push(StepOp {
                op: XML_OP_ATTR,
                value: None,
                value2: None,
            });
            ctxt.cur += 1;
        } else {
            ctxt.error = 1;
        }
        return;
    };
    if ctxt.cur_byte() == Some(b':') {
        let prefix = name;
        ctxt.cur += 1;
        if ctxt.is_blank_cur() {
            ctxt.error = 1;
            return;
        }
        let token = ctxt.scan_name();
        let url = resolve_prefix(ctxt, &prefix);
        let Some(url) = url else {
            ctxt.error = 1;
            return;
        };
        if let Some(token) = token {
            comp.steps.push(StepOp {
                op: XML_OP_ATTR,
                value: Some(token),
                value2: Some(url),
            });
        } else {
            if ctxt.cur_byte() == Some(b'*') {
                ctxt.cur += 1;
                comp.steps.push(StepOp {
                    op: XML_OP_ATTR,
                    value: None,
                    value2: Some(url),
                });
            } else {
                ctxt.error = 1;
            }
        }
    } else {
        comp.steps.push(StepOp {
            op: XML_OP_ATTR,
            value: Some(name),
            value2: None,
        });
    }
}

/// Port of `xmlCompileStepPattern` (pattern.c).
fn compile_step_pattern(ctxt: &mut PatCtxt, comp: &mut CompiledPattern) {
    ctxt.skip_blanks();
    if ctxt.cur_byte() == Some(b'.') {
        ctxt.cur += 1;
        comp.steps.push(StepOp {
            op: XML_OP_ELEM,
            value: None,
            value2: None,
        });
        return;
    }
    if ctxt.cur_byte() == Some(b'@') {
        if comp.flags & XML_PATTERN_XSSEL != 0 {
            ctxt.error = 1;
            return;
        }
        ctxt.cur += 1;
        compile_attribute_test(ctxt, comp);
        if ctxt.error != 0 {
            return;
        }
        return;
    }
    let name = ctxt.scan_ncname();
    if ctxt.error < 0 {
        return;
    }
    let Some(mut name) = name else {
        if ctxt.cur_byte() == Some(b'*') {
            ctxt.cur += 1;
            comp.steps.push(StepOp {
                op: XML_OP_ALL,
                value: None,
                value2: None,
            });
        } else {
            ctxt.error = 1;
        }
        return;
    };
    let mut has_blanks = false;
    if ctxt.is_blank_cur() {
        has_blanks = true;
        ctxt.skip_blanks();
    }
    if ctxt.cur_byte() == Some(b':') {
        ctxt.cur += 1;
        if ctxt.cur_byte() != Some(b':') {
            // `prefix:name` / `prefix:*` namespace match.
            let prefix = name;
            if has_blanks || ctxt.is_blank_cur() {
                ctxt.error = 1;
                return;
            }
            let token = ctxt.scan_name();
            let url = resolve_prefix(ctxt, &prefix);
            let Some(url) = url else {
                ctxt.error = 1;
                return;
            };
            if let Some(token) = token {
                comp.steps.push(StepOp {
                    op: XML_OP_ELEM,
                    value: Some(token),
                    value2: Some(url),
                });
            } else {
                if ctxt.cur_byte() == Some(b'*') {
                    ctxt.cur += 1;
                    comp.steps.push(StepOp {
                        op: XML_OP_NS,
                        value: None,
                        value2: Some(url),
                    });
                } else {
                    ctxt.error = 1;
                }
            }
            return;
        }
        // `child::` / `attribute::` axes.
        ctxt.cur += 1;
        if name == b"child" {
            match ctxt.scan_name() {
                None => {
                    if ctxt.cur_byte() == Some(b'*') {
                        ctxt.cur += 1;
                        comp.steps.push(StepOp {
                            op: XML_OP_ALL,
                            value: None,
                            value2: None,
                        });
                        return;
                    }
                    ctxt.error = 1;
                    return;
                }
                Some(n) => name = n,
            }
            if ctxt.cur_byte() == Some(b':') {
                let prefix = name;
                ctxt.cur += 1;
                if ctxt.is_blank_cur() {
                    ctxt.error = 1;
                    return;
                }
                let token = ctxt.scan_name();
                let url = resolve_prefix(ctxt, &prefix);
                let Some(url) = url else {
                    ctxt.error = 1;
                    return;
                };
                if let Some(token) = token {
                    comp.steps.push(StepOp {
                        op: XML_OP_ELEM,
                        value: Some(token),
                        value2: Some(url),
                    });
                } else {
                    if ctxt.cur_byte() == Some(b'*') {
                        ctxt.cur += 1;
                        comp.steps.push(StepOp {
                            op: XML_OP_NS,
                            value: None,
                            value2: Some(url),
                        });
                    } else {
                        ctxt.error = 1;
                    }
                }
                return;
            }
            comp.steps.push(StepOp {
                op: XML_OP_ELEM,
                value: Some(name),
                value2: None,
            });
        } else if name == b"attribute" {
            if comp.flags & XML_PATTERN_XSSEL != 0 {
                ctxt.error = 1;
                return;
            }
            compile_attribute_test(ctxt, comp);
            if ctxt.error != 0 {}
        } else {
            ctxt.error = 1;
        }
    } else if ctxt.cur_byte() == Some(b'*') {
        // Unreachable with a scanned name in practice: `foo*` is invalid.
        ctxt.error = 1;
    } else {
        comp.steps.push(StepOp {
            op: XML_OP_ELEM,
            value: Some(name),
            value2: None,
        });
    }
}

/// Port of `xmlCompilePathPattern` (pattern.c).
fn compile_path_pattern(ctxt: &mut PatCtxt, comp: &mut CompiledPattern) {
    ctxt.skip_blanks();
    if ctxt.cur_byte() == Some(b'/') {
        comp.flags |= PAT_FROM_ROOT;
    } else if ctxt.cur_byte() == Some(b'.') || (comp.flags & XML_PATTERN_NOTPATTERN) != 0 {
        comp.flags |= PAT_FROM_CUR;
    }

    if ctxt.cur_byte() == Some(b'/') && ctxt.peek(1) == Some(b'/') {
        comp.steps.push(StepOp {
            op: XML_OP_ANCESTOR,
            value: None,
            value2: None,
        });
        ctxt.cur += 2;
    } else if ctxt.cur_byte() == Some(b'.')
        && ctxt.peek(1) == Some(b'/')
        && ctxt.peek(2) == Some(b'/')
    {
        comp.steps.push(StepOp {
            op: XML_OP_ANCESTOR,
            value: None,
            value2: None,
        });
        ctxt.cur += 3;
        ctxt.skip_blanks();
        if ctxt.cur_byte().is_none() {
            ctxt.error = 1;
            return;
        }
    }
    if ctxt.cur_byte() == Some(b'@') {
        ctxt.cur += 1;
        compile_attribute_test(ctxt, comp);
        if ctxt.error != 0 {
            return;
        }
        ctxt.skip_blanks();
        if ctxt.cur_byte().is_some() {
            compile_step_pattern(ctxt, comp);
            if ctxt.error != 0 {
                return;
            }
        }
    } else {
        if ctxt.cur_byte() == Some(b'/') {
            comp.steps.push(StepOp {
                op: XML_OP_ROOT,
                value: None,
                value2: None,
            });
            ctxt.cur += 1;
            ctxt.skip_blanks();
            if ctxt.cur_byte().is_none() {
                ctxt.error = 1;
                return;
            }
        }
        compile_step_pattern(ctxt, comp);
        if ctxt.error != 0 {
            return;
        }
        ctxt.skip_blanks();
        while ctxt.cur_byte() == Some(b'/') {
            if ctxt.peek(1) == Some(b'/') {
                comp.steps.push(StepOp {
                    op: XML_OP_ANCESTOR,
                    value: None,
                    value2: None,
                });
                ctxt.cur += 2;
                ctxt.skip_blanks();
                compile_step_pattern(ctxt, comp);
                if ctxt.error != 0 {
                    return;
                }
            } else {
                comp.steps.push(StepOp {
                    op: XML_OP_PARENT,
                    value: None,
                    value2: None,
                });
                ctxt.cur += 1;
                ctxt.skip_blanks();
                if ctxt.cur_byte().is_none() {
                    ctxt.error = 1;
                    return;
                }
                compile_step_pattern(ctxt, comp);
                if ctxt.error != 0 {
                    return;
                }
            }
        }
    }
    if ctxt.cur_byte().is_some() {
        ctxt.error = 1;
    }
}

/// Port of `xmlCompileIDCXPathPath` (pattern.c) — the XS-IDC subset used
/// for `XML_PATTERN_XSSEL` / `XML_PATTERN_XSFIELD`.
fn compile_idc_xpath_path(ctxt: &mut PatCtxt, comp: &mut CompiledPattern) {
    ctxt.skip_blanks();
    if ctxt.cur_byte() == Some(b'/') {
        ctxt.error = 1;
        return;
    }
    comp.flags |= PAT_FROM_CUR;

    if ctxt.cur_byte() == Some(b'.') {
        ctxt.cur += 1;
        ctxt.skip_blanks();
        if ctxt.cur_byte().is_none() {
            comp.steps.push(StepOp {
                op: XML_OP_ELEM,
                value: None,
                value2: None,
            });
            return;
        }
        if ctxt.cur_byte() != Some(b'/') {
            ctxt.error = 1;
            return;
        }
        ctxt.cur += 1;
        ctxt.skip_blanks();
        if ctxt.cur_byte() == Some(b'/') {
            if ctxt.cur > 0 && is_blank(ctxt.base[ctxt.cur - 1]) {
                ctxt.error = 1;
                return;
            }
            comp.steps.push(StepOp {
                op: XML_OP_ANCESTOR,
                value: None,
                value2: None,
            });
            ctxt.cur += 1;
            ctxt.skip_blanks();
        }
        if ctxt.cur_byte().is_none() {
            ctxt.error = 1;
            return;
        }
    }
    loop {
        compile_step_pattern(ctxt, comp);
        if ctxt.error != 0 {
            return;
        }
        ctxt.skip_blanks();
        if ctxt.cur_byte() != Some(b'/') {
            break;
        }
        comp.steps.push(StepOp {
            op: XML_OP_PARENT,
            value: None,
            value2: None,
        });
        ctxt.cur += 1;
        ctxt.skip_blanks();
        if ctxt.cur_byte() == Some(b'/') {
            ctxt.error = 1;
            return;
        }
        if ctxt.cur_byte().is_none() {
            ctxt.error = 1;
            return;
        }
    }
    if ctxt.cur_byte().is_some() {
        ctxt.error = 1;
    }
}

/// Port of `xmlReversePattern` (pattern.c): drops a leading `//` op and
/// reverses the op stack, appending `XML_OP_END`.
fn reverse_pattern(comp: &mut CompiledPattern) {
    // Remove the leading `//` for `//a` / `.//a`.
    if !comp.steps.is_empty() && comp.steps[0].op == XML_OP_ANCESTOR {
        comp.steps.remove(0);
    }
    comp.steps.reverse();
    comp.steps.push(StepOp {
        op: XML_OP_END,
        value: None,
        value2: None,
    });
}

/// Add a step to a streaming compilation (pattern.c `xmlStreamCompAddStep`).
fn stream_comp_add_step(
    comp: &mut StreamComp,
    name: Option<Vec<u8>>,
    ns: Option<Vec<u8>>,
    node_type: c_int,
    flags: c_int,
) -> c_int {
    comp.steps.push(StreamStep {
        flags,
        name,
        ns,
        node_type,
    });
    comp.nb_step += 1;
    (comp.nb_step - 1) as c_int
}

/// Port of `xmlStreamCompile` (pattern.c).
///
/// `Ok(Some(stream))` — streamable; `Ok(None)` — compiled but not
/// streamable (upstream returns 0 and leaves `comp->stream == NULL`);
/// `Err(())` — hard error (upstream returns -1).
fn stream_compile(comp: &mut CompiledPattern) -> Result<Option<StreamComp>, ()> {
    // Special case for `.` — no steps, matches any node.
    if comp.steps.len() == 1
        && comp.steps[0].op == XML_OP_ELEM
        && comp.steps[0].value.is_none()
        && comp.steps[0].value2.is_none()
    {
        return Ok(Some(StreamComp {
            nb_step: 0,
            steps: Vec::new(),
            flags: XML_STREAM_FINAL_IS_ANY_NODE,
        }));
    }

    let mut stream = StreamComp {
        nb_step: 0,
        steps: Vec::with_capacity(comp.steps.len() / 2 + 1),
        flags: 0,
    };
    if comp.flags & PAT_FROM_ROOT != 0 {
        stream.flags |= XML_STREAM_FROM_ROOT;
    }

    let mut s: c_int = 0;
    let mut root = 0;
    let mut flags = 0;
    let mut prevs: c_int = -1;
    let nb_step = comp.steps.len();

    for (i, step) in comp.steps.iter().enumerate() {
        match step.op {
            XML_OP_END => break,
            XML_OP_ROOT => {
                if i != 0 {
                    return Ok(None);
                }
                root = 1;
            }
            XML_OP_NS => {
                s = stream_comp_add_step(
                    &mut stream,
                    None,
                    step.value.clone(),
                    XML_ELEMENT_NODE,
                    flags,
                );
                if s < 0 {
                    return Err(());
                }
                prevs = s;
                flags = 0;
            }
            XML_OP_ATTR => {
                flags |= XML_STREAM_STEP_ATTR;
                prevs = -1;
                s = stream_comp_add_step(
                    &mut stream,
                    step.value.clone(),
                    step.value2.clone(),
                    XML_ATTRIBUTE_NODE,
                    flags,
                );
                flags = 0;
                if s < 0 {
                    return Err(());
                }
            }
            XML_OP_ELEM => {
                if step.value.is_none() && step.value2.is_none() {
                    // `.` / `self::node()` — eliminate redundant tests.
                    if nb_step == i + 1 && (flags & XML_STREAM_STEP_DESC) != 0 {
                        if nb_step == i + 1 {
                            stream.flags |= XML_STREAM_FINAL_IS_ANY_NODE;
                        }
                        flags |= XML_STREAM_STEP_NODE;
                        s = stream_comp_add_step(
                            &mut stream,
                            None,
                            None,
                            XML_STREAM_ANY_NODE,
                            flags,
                        );
                        if s < 0 {
                            return Err(());
                        }
                        flags = 0;
                        if prevs != -1 {
                            stream.steps[prevs as usize].flags |= XML_STREAM_STEP_IN_SET;
                            prevs = -1;
                        }
                        continue;
                    } else {
                        continue;
                    }
                }
                s = stream_comp_add_step(
                    &mut stream,
                    step.value.clone(),
                    step.value2.clone(),
                    XML_ELEMENT_NODE,
                    flags,
                );
                if s < 0 {
                    return Err(());
                }
                prevs = s;
                flags = 0;
            }
            XML_OP_CHILD => {
                s = stream_comp_add_step(
                    &mut stream,
                    step.value.clone(),
                    step.value2.clone(),
                    XML_ELEMENT_NODE,
                    flags,
                );
                if s < 0 {
                    return Err(());
                }
                prevs = s;
                flags = 0;
            }
            XML_OP_ALL => {
                s = stream_comp_add_step(&mut stream, None, None, XML_ELEMENT_NODE, flags);
                if s < 0 {
                    return Err(());
                }
                prevs = s;
                flags = 0;
            }
            XML_OP_PARENT => {}
            XML_OP_ANCESTOR if (flags & XML_STREAM_STEP_DESC) == 0 => {
                flags |= XML_STREAM_STEP_DESC;
                if (stream.flags & XML_STREAM_DESC) == 0 {
                    stream.flags |= XML_STREAM_DESC;
                }
            }
            _ => {}
        }
    }

    if root == 0 && (comp.flags & XML_PATTERN_NOTPATTERN) == 0 {
        if (stream.flags & XML_STREAM_DESC) == 0 {
            stream.flags |= XML_STREAM_DESC;
        }
        if stream.nb_step > 0 && (stream.steps[0].flags & XML_STREAM_STEP_DESC) == 0 {
            stream.steps[0].flags |= XML_STREAM_STEP_DESC;
        }
    }
    if stream.nb_step <= s as usize {
        // No final step produced — not streamable (upstream error path).
        return Ok(None);
    }
    stream.steps[s as usize].flags |= XML_STREAM_STEP_FINAL;
    if root != 0 {
        stream.steps[0].flags |= XML_STREAM_STEP_ROOT;
    }
    Ok(Some(stream))
}

/// Port of `xmlPatternCompileSafe` (pattern.c). Returns 0 on success, 1 on
/// pattern error, -1 on allocation failure; `*pattern_out` receives the new
/// pattern (or NULL).
unsafe fn pattern_compile_safe_impl(
    pattern: *const xmlChar,
    _dict: *mut c_void,
    flags: c_int,
    namespaces: *const *const xmlChar,
    pattern_out: *mut xmlPatternPtr,
) -> c_int {
    if pattern_out.is_null() {
        return 1;
    }
    if pattern.is_null() {
        unsafe { *pattern_out = ptr::null_mut() };
        return 1;
    }

    // Gather namespace pairs: array of [URI, prefix] terminated by NULL.
    let mut ns_pairs: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
    if !namespaces.is_null() {
        let mut i = 0usize;
        loop {
            let uri = unsafe { *namespaces.add(2 * i) };
            if uri.is_null() {
                break;
            }
            let prefix = unsafe { *namespaces.add(2 * i + 1) };
            let uri = unsafe { core::slice::from_raw_parts(uri, cstr_len(uri)) }.to_vec();
            let prefix = if prefix.is_null() {
                Vec::new()
            } else {
                unsafe { core::slice::from_raw_parts(prefix, cstr_len(prefix)) }.to_vec()
            };
            ns_pairs.push((uri, prefix));
            i += 1;
        }
    }

    let pat_bytes = unsafe { core::slice::from_raw_parts(pattern, cstr_len(pattern)) };
    // Upstream loops over `|`-separated alternatives with `while (*or != 0)`;
    // an empty pattern never enters the loop and yields a NULL pattern with
    // a success status.
    if pat_bytes.is_empty() {
        unsafe { *pattern_out = ptr::null_mut() };
        return 0;
    }
    let mut branches: Vec<CompiledPattern> = Vec::new();
    let mut error: c_int = 0;
    let mut streamable = 1;
    let mut pat_type: c_int = 0;

    for segment in pat_bytes.split(|&b| b == b'|') {
        let mut ctxt = PatCtxt {
            cur: 0,
            base: segment,
            error: 0,
            namespaces: ns_pairs.clone(),
        };
        let mut cur = CompiledPattern {
            flags,
            steps: Vec::new(),
            stream: None,
        };
        if (cur.flags & (XML_PATTERN_XSSEL | XML_PATTERN_XSFIELD)) != 0 {
            compile_idc_xpath_path(&mut ctxt, &mut cur);
        } else {
            compile_path_pattern(&mut ctxt, &mut cur);
        }
        if ctxt.error != 0 {
            error = ctxt.error;
            break;
        }
        if streamable != 0 {
            let t = cur.flags & (PAT_FROM_ROOT | PAT_FROM_CUR);
            if pat_type == 0 {
                pat_type = t;
            } else if pat_type == PAT_FROM_ROOT {
                if t & PAT_FROM_CUR != 0 {
                    streamable = 0;
                }
            } else if pat_type == PAT_FROM_CUR && t & PAT_FROM_ROOT != 0 {
                streamable = 0;
            }
        }
        if streamable != 0 {
            match stream_compile(&mut cur) {
                Ok(stream) => cur.stream = stream,
                Err(()) => {
                    error = -1;
                    break;
                }
            }
        }
        reverse_pattern(&mut cur);
        branches.push(cur);
    }

    if error != 0 {
        unsafe { *pattern_out = ptr::null_mut() };
        return error;
    }

    if streamable == 0 {
        for branch in &mut branches {
            branch.stream = None;
        }
    }

    // Register the compiled pattern.
    let key = {
        let mut next = NEXT_PATTERN_KEY.lock();
        let k = *next;
        *next += 1;
        k
    };
    PATTERNS.lock().insert(key, PatternState { branches });
    unsafe { *pattern_out = key as xmlPatternPtr };
    0
}

// ── Public pattern API ────────────────────────────────────────────────────

/// Upstream `xmlPattern * xmlPatterncompile(const xmlChar *pattern,
/// xmlDict *dict, int flags, const xmlChar **namespaces)`.
///
/// # SAFETY
///
/// - `dict` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `pattern`, `namespaces` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatterncompile(
    pattern: *const xmlChar,
    dict: *mut c_void,
    flags: c_int,
    namespaces: *const *const xmlChar,
) -> xmlPatternPtr {
    let mut out: xmlPatternPtr = ptr::null_mut();
    let ret = pattern_compile_safe_impl(pattern, dict, flags, namespaces, &mut out);
    if ret != 0 {
        return ptr::null_mut();
    }
    out
}

/// Upstream `int xmlPatternCompileSafe(const xmlChar *pattern, xmlDict *dict,
/// int flags, const xmlChar **namespaces, xmlPattern **patternOut)`.
///
/// # SAFETY
///
/// - `dict`, `patternOut` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `pattern`, `namespaces` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternCompileSafe(
    pattern: *const xmlChar,
    dict: *mut c_void,
    flags: c_int,
    namespaces: *const *const xmlChar,
    patternOut: *mut xmlPatternPtr,
) -> c_int {
    pattern_compile_safe_impl(pattern, dict, flags, namespaces, patternOut)
}

/// Upstream `int xmlPatternMatch(xmlPattern *comp, xmlNode *node)`.
///
/// # SAFETY
///
/// - `comp`, `node` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternMatch(comp: xmlPatternPtr, node: *mut _xmlNode) -> c_int {
    if comp.is_null() || node.is_null() {
        return -1;
    }
    let key = comp as usize;
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&key) else {
        return -1;
    };
    for branch in &ps.branches {
        let ret = pat_match(branch, node);
        if ret != 0 {
            return ret;
        }
    }
    0
}

/// Upstream `void xmlFreePattern(xmlPattern *comp)`.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFreePattern(comp: xmlPatternPtr) {
    xmlFreePatternList(comp);
}

/// Upstream `void xmlFreePatternList(xmlPattern *comp)`.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFreePatternList(comp: xmlPatternPtr) {
    if comp.is_null() {
        return;
    }
    PATTERNS.lock().remove(&(comp as usize));
}

/// Upstream `int xmlPatternStreamable(xmlPattern *comp)`.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternStreamable(comp: xmlPatternPtr) -> c_int {
    if comp.is_null() {
        return -1;
    }
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&(comp as usize)) else {
        return -1;
    };
    if ps.branches.iter().any(|b| b.stream.is_none()) {
        return 0;
    }
    1
}

/// Upstream `int xmlPatternMaxDepth(xmlPattern *comp)` — -2 if unlimited
/// (uses `//`), else the maximum step count, -1 on error.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternMaxDepth(comp: xmlPatternPtr) -> c_int {
    if comp.is_null() {
        return -1;
    }
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&(comp as usize)) else {
        return -1;
    };
    let mut ret = 0;
    for branch in &ps.branches {
        let Some(stream) = &branch.stream else {
            return -1;
        };
        for step in &stream.steps {
            if step.flags & XML_STREAM_STEP_DESC != 0 {
                return -2;
            }
        }
        if stream.nb_step > ret as usize {
            ret = stream.nb_step as c_int;
        }
    }
    ret
}

/// Upstream `int xmlPatternMinDepth(xmlPattern *comp)` — the minimum depth
/// reachable by the pattern (0 means `/` or `.` are part of the set).
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternMinDepth(comp: xmlPatternPtr) -> c_int {
    if comp.is_null() {
        return -1;
    }
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&(comp as usize)) else {
        return -1;
    };
    let mut ret: c_int = 12345678;
    for branch in &ps.branches {
        let Some(stream) = &branch.stream else {
            return -1;
        };
        if stream.nb_step < ret as usize {
            ret = stream.nb_step as c_int;
        }
        if ret == 0 {
            return 0;
        }
    }
    ret
}

/// Upstream `int xmlPatternFromRoot(xmlPattern *comp)`.
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternFromRoot(comp: xmlPatternPtr) -> c_int {
    if comp.is_null() {
        return -1;
    }
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&(comp as usize)) else {
        return -1;
    };
    for branch in &ps.branches {
        if branch.stream.is_none() {
            return -1;
        }
        if branch.flags & PAT_FROM_ROOT != 0 {
            return 1;
        }
    }
    0
}

// ── Stream contexts ───────────────────────────────────────────────────────

/// Port of `xmlNewStreamCtxt` + chain building done by
/// `xmlPatternGetStreamCtxt` (pattern.c).
///
/// # SAFETY
///
/// - `comp` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlPatternGetStreamCtxt(comp: xmlPatternPtr) -> xmlStreamCtxtPtr {
    if comp.is_null() {
        return ptr::null_mut();
    }
    let key = comp as usize;
    let reg = PATTERNS.lock();
    let Some(ps) = reg.get(&key) else {
        return ptr::null_mut();
    };

    // Every branch must have a streaming compilation; snapshot them (with
    // their flags) before creating any context.
    let mut snapshot: Vec<(StreamComp, c_int)> = Vec::new();
    for branch in &ps.branches {
        match &branch.stream {
            Some(stream) => snapshot.push((stream.clone(), branch.flags)),
            None => return ptr::null_mut(),
        }
    }
    drop(reg);

    let mut head: Option<usize> = None;
    let mut last: Option<usize> = None;
    {
        let mut stream_reg = STREAM_CTXTS.lock();
        for (stream, flags) in snapshot {
            let h = {
                let mut next = NEXT_STREAM_KEY.lock();
                let k = *next;
                *next += 1;
                k
            };
            stream_reg.insert(
                h,
                StreamCtxtState {
                    comp: stream,
                    next: None,
                    nb_state: 0,
                    states: Vec::new(),
                    level: 0,
                    flags,
                    block_level: -1,
                },
            );
            match last {
                None => head = Some(h),
                Some(prev) => {
                    if let Some(prev_st) = stream_reg.get_mut(&prev) {
                        prev_st.next = Some(h);
                    }
                }
            }
            last = Some(h);
        }
    }
    match head {
        Some(h) => h as xmlStreamCtxtPtr,
        None => ptr::null_mut(),
    }
}

/// Free a chain of stream contexts given the head handle.
fn stream_ctxt_free_chain(head: Option<usize>) {
    let mut cur = head;
    let mut registry = STREAM_CTXTS.lock();
    while let Some(h) = cur {
        let next = registry.get(&h).and_then(|s| s.next);
        registry.remove(&h);
        cur = next;
    }
}

/// Upstream `void xmlFreeStreamCtxt(xmlStreamCtxt *stream)`.
///
/// # SAFETY
///
/// - `stream` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlFreeStreamCtxt(stream: xmlStreamCtxtPtr) {
    if stream.is_null() {
        return;
    }
    stream_ctxt_free_chain(Some(stream as usize));
}

/// Port of `xmlStreamCtxtAddState` (pattern.c).
fn stream_ctxt_add_state(st: &mut StreamCtxtState, idx: i32, level: i32) -> c_int {
    for i in 0..st.nb_state {
        if st.states[i].0 < 0 {
            st.states[i] = (idx, level);
            return i as c_int;
        }
    }
    st.states.push((idx, level));
    st.nb_state += 1;
    (st.nb_state - 1) as c_int
}

/// Port of `xmlStreamPushInternal` (pattern.c) — the streaming evaluator.
unsafe fn stream_push_internal(
    head: usize,
    name: *const xmlChar,
    ns: *const xmlChar,
    node_type: c_int,
) -> c_int {
    let mut ret = 0;
    let mut registry = STREAM_CTXTS.lock();
    let mut cur = Some(head);

    while let Some(h) = cur {
        let next = registry.get(&h).and_then(|s| s.next);
        let Some(st) = registry.get_mut(&h) else {
            return -1;
        };

        // Document node (or reset): both name and ns NULL.
        if node_type == XML_ELEMENT_NODE && name.is_null() && ns.is_null() {
            st.nb_state = 0;
            st.level = 0;
            st.block_level = -1;
            if st.comp.flags & XML_STREAM_FROM_ROOT != 0 {
                if st.comp.nb_step == 0
                    || (st.comp.nb_step == 1
                        && st.comp.steps[0].node_type == XML_STREAM_ANY_NODE
                        && st.comp.steps[0].flags & XML_STREAM_STEP_DESC != 0)
                {
                    ret = 1;
                } else if st.comp.steps[0].flags & XML_STREAM_STEP_ROOT != 0
                    && stream_ctxt_add_state(st, 0, 0) < 0
                {
                    return -1;
                }
            }
            cur = next;
            continue;
        }

        // Fast check for "." (stream with no steps).
        if st.comp.nb_step == 0 {
            if st.flags & XML_PATTERN_XPATH != 0 {
                cur = next;
                continue;
            }
            if node_type != XML_ATTRIBUTE_NODE
                && ((st.flags & XML_PATTERN_NOTPATTERN) == 0 || st.level == 0)
            {
                ret = 1;
            }
            st.level += 1;
            cur = next;
            continue;
        }

        if st.block_level != -1 {
            st.level += 1;
            cur = next;
            continue;
        }

        if node_type != XML_ELEMENT_NODE
            && node_type != XML_ATTRIBUTE_NODE
            && (st.comp.flags & XML_STREAM_FINAL_IS_ANY_NODE) == 0
        {
            st.level += 1;
            cur = next;
            continue;
        }

        // Evolution of existing states.
        let mut i = 0usize;
        let m = st.nb_state;
        let mut final_: c_int = 0;
        while i < m {
            let step_nr: i32;
            if (st.comp.flags & XML_STREAM_DESC) == 0 {
                step_nr = st.states[st.nb_state - 1].0;
                if st.states[st.nb_state - 1].1 < st.level {
                    return -1;
                }
                i = m; // loop-stopper
            } else {
                step_nr = st.states[i].0;
                if step_nr < 0 {
                    i += 1;
                    continue;
                }
                let tmp = st.states[i].1;
                if tmp > st.level {
                    i += 1;
                    continue;
                }
                if tmp < st.level
                    && (st.comp.steps[step_nr as usize].flags & XML_STREAM_STEP_DESC) == 0
                {
                    i += 1;
                    continue;
                }
            }
            let Some(step) = st.comp.steps.get(step_nr as usize).cloned() else {
                i += 1;
                continue;
            };
            if step.node_type != node_type {
                if step.node_type == XML_ATTRIBUTE_NODE {
                    if (st.comp.flags & XML_STREAM_DESC) == 0 {
                        st.block_level = st.level + 1;
                    }
                    i += 1;
                    continue;
                } else if step.node_type != XML_STREAM_ANY_NODE {
                    i += 1;
                    continue;
                }
            }
            let mut match_ = false;
            if step.node_type == XML_STREAM_ANY_NODE {
                match_ = true;
            } else if step.name.is_none() {
                if step.ns.is_none() {
                    match_ = true;
                } else if !ns.is_null() {
                    match_ = cstr_eq_opt(step.ns.as_deref(), ns);
                }
            } else if (step.ns.is_some() == !ns.is_null())
                && !name.is_null()
                && step.name.as_ref().unwrap()[0] == *name
                && cstr_eq_opt(step.name.as_deref(), name)
                && (step.ns.is_none() || cstr_eq_opt(step.ns.as_deref(), ns))
            {
                match_ = true;
            }
            if match_ {
                final_ = step.flags & XML_STREAM_STEP_FINAL;
                if final_ != 0 {
                    ret = 1;
                } else if stream_ctxt_add_state(st, step_nr + 1, st.level + 1) < 0 {
                    return -1;
                }
                if ret != 1 && step.flags & XML_STREAM_STEP_IN_SET != 0 {
                    ret = 1;
                }
            }
            if (st.comp.flags & XML_STREAM_DESC) == 0 && (!match_ || final_ != 0) {
                st.block_level = st.level + 1;
            }
            i += 1;
        }

        st.level += 1;

        // Re/enter the expression.
        let step0 = st.comp.steps[0].clone();
        if step0.flags & XML_STREAM_STEP_ROOT != 0 {
            cur = next;
            continue;
        }
        let desc = step0.flags & XML_STREAM_STEP_DESC != 0;
        let do_compare = if st.flags & XML_PATTERN_NOTPATTERN != 0 {
            if st.level == 1 {
                if st.flags & (XML_PATTERN_XSSEL | XML_PATTERN_XSFIELD) != 0 {
                    // XS-IDC: the missing self::node() always matches the
                    // first given node.
                    cur = next;
                    continue;
                }
                true
            } else if desc
                || (st.level == 2 && st.flags & (XML_PATTERN_XSSEL | XML_PATTERN_XSFIELD) != 0)
            {
                true
            } else {
                cur = next;
                continue;
            }
        } else {
            true
        };

        if do_compare {
            if step0.node_type != node_type
                && (node_type == XML_ATTRIBUTE_NODE || step0.node_type != XML_STREAM_ANY_NODE)
            {
                cur = next;
                continue;
            }
            let mut match_ = false;
            if step0.node_type == XML_STREAM_ANY_NODE {
                match_ = true;
            } else if step0.name.is_none() {
                if step0.ns.is_none() {
                    match_ = true;
                } else if !ns.is_null() {
                    match_ = cstr_eq_opt(step0.ns.as_deref(), ns);
                }
            } else if (step0.ns.is_some() == !ns.is_null())
                && !name.is_null()
                && step0.name.as_ref().unwrap()[0] == *name
                && cstr_eq_opt(step0.name.as_deref(), name)
                && (step0.ns.is_none() || cstr_eq_opt(step0.ns.as_deref(), ns))
            {
                match_ = true;
            }
            final_ = step0.flags & XML_STREAM_STEP_FINAL;
            if match_ {
                if final_ != 0 {
                    ret = 1;
                } else if stream_ctxt_add_state(st, 1, st.level) < 0 {
                    return -1;
                }
                if ret != 1 && step0.flags & XML_STREAM_STEP_IN_SET != 0 {
                    ret = 1;
                }
            }
            if (st.comp.flags & XML_STREAM_DESC) == 0 && (!match_ || final_ != 0) {
                st.block_level = st.level;
            }
        }

        cur = next;
    }
    ret
}

/// Upstream `int xmlStreamPush(xmlStreamCtxt *stream, const xmlChar *name,
/// const xmlChar *ns)`.
///
/// # SAFETY
///
/// - `stream` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `ns` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStreamPush(
    stream: xmlStreamCtxtPtr,
    name: *const xmlChar,
    ns: *const xmlChar,
) -> c_int {
    if stream.is_null() {
        return -1;
    }
    stream_push_internal(stream as usize, name, ns, XML_ELEMENT_NODE)
}

/// Upstream `int xmlStreamPushAttr(xmlStreamCtxt *stream, const xmlChar *name,
/// const xmlChar *ns)`.
///
/// # SAFETY
///
/// - `stream` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `ns` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStreamPushAttr(
    stream: xmlStreamCtxtPtr,
    name: *const xmlChar,
    ns: *const xmlChar,
) -> c_int {
    if stream.is_null() {
        return -1;
    }
    stream_push_internal(stream as usize, name, ns, XML_ATTRIBUTE_NODE)
}

/// Upstream `int xmlStreamPushNode(xmlStreamCtxt *stream, const xmlChar *name,
/// const xmlChar *ns, int nodeType)`.
///
/// # SAFETY
///
/// - `stream` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// - `name`, `ns` must point to valid NUL-terminated
///   strings (or NULL where the C contract allows) for the lifetime
///   of the call.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStreamPushNode(
    stream: xmlStreamCtxtPtr,
    name: *const xmlChar,
    ns: *const xmlChar,
    nodeType: c_int,
) -> c_int {
    if stream.is_null() {
        return -1;
    }
    stream_push_internal(stream as usize, name, ns, nodeType)
}

/// Upstream `int xmlStreamPop(xmlStreamCtxt *stream)`.
///
/// # SAFETY
///
/// - `stream` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStreamPop(stream: xmlStreamCtxtPtr) -> c_int {
    if stream.is_null() {
        return -1;
    }
    let mut registry = STREAM_CTXTS.lock();
    let mut cur = Some(stream as usize);
    while let Some(h) = cur {
        let next = registry.get(&h).and_then(|s| s.next);
        let Some(st) = registry.get_mut(&h) else {
            return -1;
        };
        // Reset block-level.
        if st.block_level == st.level {
            st.block_level = -1;
        }
        // `level` can be zero when FINAL_IS_ANY_NODE is set.
        if st.level > 0 {
            st.level -= 1;
        }
        // Discard obsoleted states.
        let mut i = st.nb_state as isize - 1;
        while i >= 0 {
            let lev = st.states[i as usize].1;
            if lev > st.level {
                st.nb_state -= 1;
            }
            if lev <= st.level {
                break;
            }
            i -= 1;
        }
        cur = next;
    }
    0
}

/// Upstream `int xmlStreamWantsAnyNode(xmlStreamCtxt *streamCtxt)` — 1 if the
/// pattern needs text/cdata/comment/PI nodes pushed as well.
///
/// # SAFETY
///
/// - `streamCtxt` must be valid pointers (or NULL
///   where the upstream C contract allows), obtained from the
///   matching constructor/owner and not yet freed; the callee may
///   take or keep ownership exactly as the C API specifies.
///
/// The caller must not race this call with concurrent mutation of the
/// same objects from other threads (per-object state is not internally
/// synchronized). Violating any of the above is undefined behavior.
///
/// Exercised by the C-API differential courts
/// (courts/suites/data-abi/*-family-probe.c) and the CLI differential
/// courts; those pass byte-for-byte against the upstream oracle.
#[no_mangle]
pub unsafe extern "C" fn xmlStreamWantsAnyNode(streamCtxt: xmlStreamCtxtPtr) -> c_int {
    if streamCtxt.is_null() {
        return -1;
    }
    let registry = STREAM_CTXTS.lock();
    let mut cur = Some(streamCtxt as usize);
    while let Some(h) = cur {
        let Some(st) = registry.get(&h) else {
            return -1;
        };
        if st.comp.flags & XML_STREAM_FINAL_IS_ANY_NODE != 0 {
            return 1;
        }
        cur = st.next;
    }
    0
}