libxml-rs 0.1.0-alpha.48

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure; three-DSO ELF packaging (libxml2.so.16 core + libxslt.so.1/libexslt.so.0 facades, upstream NEEDED chain); fail-closed oracle-isolated ABI-FUNCTION-SIGNATURE plane (SOURCE_PROTOTYPE + MACHINE_ABI fingerprints, zero silent omissions); Phase-12 real downstream substitution (binary/static/docker substitution, export-surface disposition, ELF version graphs); Phase-13 hostile audit courts (ABI/ownership/allocator/callbacks/failure/threads/oracle-contamination) byte-identical vs the system oracle incl. the upstream thread-local globals model; Phase-14 downstream custodian validation courts (lxml/Nokogiri/PHP/Debian). Test counts live in atlas/TEST_COUNTS.json, residuals in atlas/RESIDUAL_LEDGER.json (generated evidence).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
//! RELAX NG implementation (§27, §85 Phase 6).
//!
//! RELAX NG schema validation. Upstream libxml2 RELAX NG support is known to be
//! incomplete/non-conformant in places — parity follows the oracle.
//!
//! Phase 6: Complete — RELAX NG grammar parsing, document validation,
//! and C ABI exports are implemented.
//!
//! # UPSTREAM-PARITY
//!
//! This module implements a functional RELAX NG validator following the
//! upstream libxml2 observable behavior. The implementation covers:
//!
//! - Full XML syntax for RELAX NG grammar definitions
//! - Pattern-based validation of XML documents
//! - Name classes for element/attribute matching
//! - Basic datatype checking for `<data>` and `<value>` patterns
//! - Reference resolution for `<ref>` and `<define>` patterns
//! - Include support for external grammars (basic)
//! - Compact syntax (basic support)
//!
//! Deviations from the OASIS RELAX NG specification that match the upstream
//! libxml2 behavior are intentional.
//!
//! # Upstream contract
//!
//! Mirrors upstream relaxng.c (SRC-LIBXML2-2.15.0-RELAXNG-C, oracle tree
//! `oracle/historical/src/libxml2-2.15.0/relaxng.c`): xmlRelaxNG parse/valid
//! contexts, pattern compilation, name classes and the datatype hooks. Parity
//! target: the system libxml2 2.15.3 oracle — NOT the OASIS RELAX NG
//! specification where the two differ.
//!
//! # Conceptual behavior
//!
//! RELAX NG schema validation: grammar parsing, pattern-based document
//! validation, name classes for element/attribute matching, datatype checks
//! for data/value patterns, ref/define resolution, include support and basic
//! compact syntax. Upstream libxml2 RELAX NG support is known to be
//! incomplete/non-conformant in places; the module reproduces the oracle
//! behavior, not the standard.
//!
//! # Ownership & safety invariants
//!
//! Ownership: schemas own their pattern tree (xmlRelaxNGFree); parser and
//! valid contexts own their state (xmlRelaxNGFreeParserCtxt /
//! xmlRelaxNGFreeValidCtxt); the validated document is borrowed. SAFETY:
//! pattern references are resolved with cycle guards so recursive grammars
//! cannot loop the validator.
//!
//! # Historical quirks & epochs
//!
//! RELAX NG landed in the 2.6 validation-era expansion (2003-2004,
//! atlas/HISTORY.md 1.5); xmlRelaxNGInitTypes is empty after lazy init and
//! xmlRelaxNGCleanupTypes is a documented no-op (R-000138 no-op set, matching
//! upstream empty bodies).
//!
//! # Deliberate oddities
//!
//! Deliberate oddities: deviations from the OASIS specification that match
//! upstream libxml2 behavior are intentional and kept; the C-API surface
//! (xmlRelaxNGNewParserCtxt, xmlRelaxNGNewMemParserCtxt, xmlRelaxNGFree,
//! xmlRelaxNGNewValidCtxt, ...) is exported with upstream signatures.
//!
//! # Proving courts
//!
//! RELAXNG court family; the data-ABI header-compile court compiles
//! every relaxng.h declaration against the DSO; dso-loader 25/25; `cargo test
//! --lib` exercises the validator.
//!
//! # Tempting simplifications that would break parity
//!
//! The tempting simplification is implementing full OASIS RELAX NG
//! conformance — it would diverge from upstream libxml2 known non-conformance
//! and break byte-identical validation output. Do not drop the compact-syntax
//! handling: upstream accepts it and the oracle surface includes it.

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

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

use crate::abi::structs::*;
use crate::abi::types::xmlElementType::*;

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Name Class
// ═══════════════════════════════════════════════════════════════════════════════

/// RELAX NG name class — determines which element/attribute names a pattern matches.
///
/// # UPSTREAM-PARITY
///
/// libxml2 defines name classes in `include/relaxng.h` as part of the
/// pattern structure. This enum provides the same semantics.
#[derive(Debug, Clone, PartialEq)]
pub enum RelaxNgNameClass {
    /// Match a specific name (`<name>`)
    Name(String),
    /// Match any name (`<anyName>`)
    AnyName,
    /// Match any name in a namespace (`<nsName>`)
    NsName(String),
    /// Choice between multiple name classes (`<choice>`)
    Choice(Vec<RelaxNgNameClass>),
    /// Exclude a name class (used with anyName/nsName)
    Except(Box<RelaxNgNameClass>, Box<RelaxNgNameClass>),
}

impl RelaxNgNameClass {
    /// Check if a given qualified name matches this name class.
    pub fn matches(&self, name: &str, ns_uri: Option<&str>) -> bool {
        match self {
            RelaxNgNameClass::Name(n) => name == n.as_str(),
            RelaxNgNameClass::AnyName => true,
            RelaxNgNameClass::NsName(ns) => {
                if let Some(uri) = ns_uri {
                    uri == ns.as_str()
                } else {
                    false
                }
            }
            RelaxNgNameClass::Choice(choices) => choices.iter().any(|c| c.matches(name, ns_uri)),
            RelaxNgNameClass::Except(positive, negative) => {
                positive.matches(name, ns_uri) && !negative.matches(name, ns_uri)
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Pattern Types
// ═══════════════════════════════════════════════════════════════════════════════

/// RELAX NG pattern type — classification for pattern dispatch.
///
/// # UPSTREAM-PARITY
///
/// Mirrors libxml2's internal pattern type classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelaxNgPatternType {
    Element,
    Attribute,
    Text,
    Choice,
    Sequence,
    Interleave,
    ZeroOrMore,
    OneOrMore,
    Optional,
    List,
    Group,
    Data,
    Value,
    Ref,
    Define,
    Grammar,
    NotAllowed,
    Empty,
    ExternalRef,
    Include,
    Start,
}

/// A RELAX NG pattern — the core building block of RELAX NG schemas.
///
/// Patterns form a tree structure where composite patterns contain child patterns.
#[derive(Debug, Clone)]
pub struct RelaxNgPattern {
    /// The type of this pattern.
    pub pattern_type: RelaxNgPatternType,
    /// Name class (for element/attribute patterns).
    pub name_class: Option<RelaxNgNameClass>,
    /// Child patterns.
    pub children: Vec<RelaxNgPattern>,
    /// The name for `<ref>` and `<define>` patterns.
    pub name: Option<String>,
    /// The namespace URI for nsName or element/attribute.
    pub ns: Option<String>,
    /// Datatype for `<data>` patterns.
    pub datatype: Option<String>,
    /// Value for `<value>` patterns.
    pub value: Option<String>,
    /// Datatype library (e.g., "" for built-in).
    pub datatype_library: Option<String>,
}

impl RelaxNgPattern {
    /// Create a new pattern with the given type.
    pub const fn new(pattern_type: RelaxNgPatternType) -> Self {
        Self {
            pattern_type,
            name_class: None,
            children: Vec::new(),
            name: None,
            ns: None,
            datatype: None,
            value: None,
            datatype_library: None,
        }
    }

    /// Create a simple element pattern with a name.
    pub fn element(name: &str) -> Self {
        let mut p = Self::new(RelaxNgPatternType::Element);
        p.name_class = Some(RelaxNgNameClass::Name(name.to_string()));
        p
    }

    /// Create a simple attribute pattern with a name.
    pub fn attribute(name: &str) -> Self {
        let mut p = Self::new(RelaxNgPatternType::Attribute);
        p.name_class = Some(RelaxNgNameClass::Name(name.to_string()));
        p
    }

    /// Create a text pattern.
    pub const fn text() -> Self {
        Self::new(RelaxNgPatternType::Text)
    }

    /// Create an empty pattern.
    pub const fn empty() -> Self {
        Self::new(RelaxNgPatternType::Empty)
    }

    /// Create a notAllowed pattern.
    pub const fn not_allowed() -> Self {
        Self::new(RelaxNgPatternType::NotAllowed)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Define (named pattern definition)
// ═══════════════════════════════════════════════════════════════════════════════

/// A named pattern definition (`<define>`).
#[derive(Debug, Clone)]
pub struct RelaxNgDefine {
    /// The name of this definition.
    pub name: String,
    /// The pattern body.
    pub pattern: RelaxNgPattern,
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Grammar
// ═══════════════════════════════════════════════════════════════════════════════

/// A RELAX NG grammar — the top-level container for pattern definitions.
///
/// Contains named pattern definitions and an optional start pattern.
#[derive(Debug, Clone)]
pub struct RelaxNgGrammar {
    /// Named pattern definitions (`<define>` elements).
    pub defines: Vec<RelaxNgDefine>,
    /// The start pattern (`<start>`).
    pub start: Option<RelaxNgPattern>,
    /// Included grammars (from `<include>`).
    pub includes: Vec<RelaxNgGrammar>,
}

impl RelaxNgGrammar {
    pub const fn new() -> Self {
        Self {
            defines: Vec::new(),
            start: None,
            includes: Vec::new(),
        }
    }

    /// Look up a named pattern definition.
    pub fn lookup(&self, name: &str) -> Option<&RelaxNgPattern> {
        for def in &self.defines {
            if def.name == name {
                return Some(&def.pattern);
            }
        }
        // Also search includes
        for inc in &self.includes {
            if let Some(p) = inc.lookup(name) {
                return Some(p);
            }
        }
        None
    }
}

impl Default for RelaxNgGrammar {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Schema
// ═══════════════════════════════════════════════════════════════════════════════

/// A compiled RELAX NG schema.
///
/// Wraps a grammar and tracks any errors encountered during parsing.
#[derive(Debug, Clone)]
pub struct RelaxNgSchema {
    /// The top-level grammar.
    pub grammar: RelaxNgGrammar,
    /// Errors encountered during parsing.
    pub errors: Vec<String>,
    /// Whether parsing hit an unrecoverable grammar error. Upstream
    /// `xmlRelaxNGParse` aborts (returns NULL after reporting the recorded
    /// diagnostics through the parser error callbacks) when a pattern is
    /// structurally invalid — e.g. `xmlRelaxNGParseElement` on an `<element>`
    /// with no content — while plain warnings keep the schema usable.
    pub fatal: bool,
}

impl RelaxNgSchema {
    pub const fn new() -> Self {
        Self {
            grammar: RelaxNgGrammar::new(),
            errors: Vec::new(),
            fatal: false,
        }
    }
}

impl Default for RelaxNgSchema {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Validation Context
// ═══════════════════════════════════════════════════════════════════════════════

/// Validation context for RELAX NG schema validation.
///
/// Tracks errors, current element path, and pattern recursion depth
/// during validation of an XML document against a RELAX NG schema.
/// Mirrors libxml2's `xmlRelaxNGValidCtxt`.
#[derive(Debug)]
pub struct RelaxNgValidCtxt {
    /// The schema being validated against.
    pub schema: Option<RelaxNgSchema>,
    /// Accumulated validation errors.
    pub errors: Vec<String>,
    /// Number of validation errors.
    pub nb_errors: i32,
    /// Current element path (stack of element names).
    pub path: Vec<String>,
    /// Maximum recursion depth for pattern matching.
    pub depth_max: i32,
    /// Current recursion depth.
    pub depth: i32,
}

impl RelaxNgValidCtxt {
    pub const fn new() -> Self {
        Self {
            schema: None,
            errors: Vec::new(),
            nb_errors: 0,
            path: Vec::new(),
            depth_max: 256,
            depth: 0,
        }
    }

    /// Record a validation error.
    pub fn record_error(&mut self, msg: String) {
        self.errors.push(msg);
        self.nb_errors += 1;
    }

    /// Get the current path as a string (e.g., "/root/child").
    pub fn current_path(&self) -> String {
        if self.path.is_empty() {
            "/".to_string()
        } else {
            format!("/{}", self.path.join("/"))
        }
    }
}

impl Default for RelaxNgValidCtxt {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Internal helpers for RELAX NG parsing
// ═══════════════════════════════════════════════════════════════════════════════

/// Get the local name of an element node (strip namespace prefix).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_local_name(node: *mut _xmlNode) -> String {
    if node.is_null() {
        return String::new();
    }
    unsafe {
        let name = (*node).name;
        if name.is_null() {
            return String::new();
        }
        let mut len = 0;
        while *name.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(name, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            if let Some(pos) = s.find(':') {
                s[pos + 1..].to_string()
            } else {
                s.to_string()
            }
        } else {
            String::new()
        }
    }
}

/// Get the text content of an xmlNode (recursively collects text children).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_node_text(node: *mut _xmlNode) -> String {
    if node.is_null() {
        return String::new();
    }
    let mut result = String::new();
    unsafe {
        let mut child = (*node).children;
        while !child.is_null() {
            if ((*child).type_ == XML_TEXT_NODE as c_int
                || (*child).type_ == XML_CDATA_SECTION_NODE as c_int)
                && !(*child).content.is_null()
            {
                let content = (*child).content;
                let mut len = 0;
                while *content.add(len) != 0 {
                    len += 1;
                }
                let slice = std::slice::from_raw_parts(content, len);
                result.push_str(&String::from_utf8_lossy(slice));
            }
            child = (*child).next;
        }
    }
    result
}

/// Get the qualified name of a node (with namespace prefix if available).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_node_qname(node: *mut _xmlNode) -> String {
    if node.is_null() {
        return String::new();
    }
    unsafe {
        let ns = (*node).ns;
        let prefix = if !ns.is_null() && !(*ns).prefix.is_null() {
            let mut len = 0;
            while *(*ns).prefix.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts((*ns).prefix, len);
            if let Ok(s) = std::str::from_utf8(slice) {
                format!("{}:", s)
            } else {
                String::new()
            }
        } else {
            String::new()
        };

        let name = (*node).name;
        if name.is_null() {
            return String::new();
        }
        let mut len = 0;
        while *name.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(name, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            format!("{}{}", prefix, s)
        } else {
            String::new()
        }
    }
}

/// Get the namespace URI of a node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_node_ns_uri(node: *mut _xmlNode) -> Option<String> {
    if node.is_null() {
        return None;
    }
    unsafe {
        let ns = (*node).ns;
        if ns.is_null() || (*ns).href.is_null() {
            return None;
        }
        let href = (*ns).href;
        let mut len = 0;
        while *href.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(href, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            Some(s.to_string())
        } else {
            None
        }
    }
}

/// Get an attribute value from an xmlNode.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
unsafe fn get_attr(node: *mut _xmlNode, name: &str) -> Option<String> {
    if node.is_null() {
        return None;
    }
    unsafe {
        let mut prop = (*node).properties;
        while !prop.is_null() {
            let prop_name = (*prop).name;
            if !prop_name.is_null() {
                let mut len = 0;
                while *prop_name.add(len) != 0 {
                    len += 1;
                }
                let slice = std::slice::from_raw_parts(prop_name, len);
                if let Ok(s) = std::str::from_utf8(slice) {
                    if s == name {
                        return Some(get_node_text(prop as *mut _xmlNode));
                    }
                }
            }
            prop = (*prop).next;
        }
    }
    None
}

/// Check if an xmlNode is an element with a given local name.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
#[allow(dead_code)]
unsafe fn node_is(node: *mut _xmlNode, local_name: &str) -> bool {
    if node.is_null() {
        return false;
    }
    unsafe {
        let name = (*node).name;
        if name.is_null() {
            return false;
        }
        let mut len = 0;
        while *name.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(name, len);
        if let Ok(s) = std::str::from_utf8(slice) {
            let local = if let Some(pos) = s.find(':') {
                &s[pos + 1..]
            } else {
                s
            };
            return local == local_name;
        }
    }
    false
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Schema Parsing
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a RELAX NG schema from an XML string.
///
/// # UPSTREAM-PARITY
///
/// Equivalent to `xmlRelaxNGParse` in libxml2 when given a parser context
/// created from a memory buffer.
///
/// # Safety
///
/// - `xml_doc` must be a valid `&str`; its bytes stay readable for the
///   duration of the `xmlReadMemory` call.
/// - The document pointer returned by `xmlReadMemory` is NULL-checked before
///   being passed to `rng_parse_doc`, and is freed exactly once with
///   `xmlFreeDoc`.
///
/// Returns the parsed schema, or an error message on failure.
pub fn rng_parse(xml_doc: &str) -> Result<RelaxNgSchema, String> {
    let doc_ptr = unsafe {
        crate::abi::exports_xml2::xmlReadMemory(
            xml_doc.as_ptr() as *const c_char,
            xml_doc.len() as c_int,
            c"schema.rng".as_ptr() as *const c_char,
            ptr::null(),
            0,
        )
    };

    if doc_ptr.is_null() {
        return Err("Failed to parse RELAX NG schema XML document".to_string());
    }

    let result = unsafe { rng_parse_doc(doc_ptr) };
    unsafe {
        crate::abi::exports_xml2::xmlFreeDoc(doc_ptr);
    }
    result
}

/// Get the URL of a parsed document (its `URL` field), as a string.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc or NULL.
unsafe fn doc_url(doc: *mut _xmlDoc) -> Option<String> {
    if doc.is_null() {
        return None;
    }
    unsafe {
        let url = (*doc).URL;
        if url.is_null() {
            return None;
        }
        let mut len = 0;
        while *url.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(url, len);
        Some(String::from_utf8_lossy(slice).to_string())
    }
}

/// Resolve a (possibly relative) RELAX NG `href` against the base URL of the
/// grammar that references it. Mirrors upstream relaxng.c (include /
/// externalRef handling): `base = xmlNodeGetBase(cur->doc, cur);
/// URL = xmlBuildURI(href, base);` — a bare relative name resolves against
/// the including schema's own location, not the process CWD.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc or NULL.
unsafe fn resolve_rng_href(doc: *mut _xmlDoc, href: &str) -> String {
    let Some(base) = (unsafe { doc_url(doc) }) else {
        // Memory-parse (or URL-less): keep the raw href (relative names then
        // resolve against the CWD, matching upstream's NULL base).
        return href.to_string();
    };
    if base.is_empty() {
        return href.to_string();
    }
    let Ok(base_c) = std::ffi::CString::new(base.as_str()) else {
        return href.to_string();
    };
    let Ok(href_c) = std::ffi::CString::new(href) else {
        return href.to_string();
    };
    let resolved = crate::abi::exports_uri::xmlBuildURI(href_c.as_ptr(), base_c.as_ptr());
    if resolved.is_null() {
        href.to_string()
    } else {
        // xmlBuildURI returns an xmlChar* string (not a doc); convert bytes.
        unsafe {
            let mut len = 0;
            while *resolved.add(len) != 0 {
                len += 1;
            }
            let slice = std::slice::from_raw_parts(resolved, len);
            let s = String::from_utf8_lossy(slice).to_string();
            crate::abi::allocator::xmlFreeImpl(resolved as *mut core::ffi::c_void);
            s
        }
    }
}

/// Parse a RELAX NG schema from a document.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc representing a RELAX NG schema.
unsafe fn rng_parse_doc(doc: *mut _xmlDoc) -> Result<RelaxNgSchema, String> {
    unsafe {
        let root = (*doc).children;
        if root.is_null() {
            return Err("RELAX NG document has no root element".to_string());
        }

        // Find the root element (skip any non-element nodes like comments)
        let mut root_elem = root;
        while !root_elem.is_null() && (*root_elem).type_ != XML_ELEMENT_NODE as c_int {
            root_elem = (*root_elem).next;
        }

        if root_elem.is_null() {
            return Err("RELAX NG document has no root element".to_string());
        }

        let base = unsafe { doc_url(doc) };
        let local_name = get_local_name(root_elem);
        let mut schema = RelaxNgSchema::new();

        match local_name.as_str() {
            "grammar" => {
                // Top-level grammar
                schema.grammar = rng_parse_grammar_node(root_elem, &mut schema, base.as_deref());
                Ok(schema)
            }
            "element" | "attribute" | "text" | "choice" | "sequence" | "interleave"
            | "zeroOrMore" | "oneOrMore" | "optional" | "list" | "group" | "data" | "value"
            | "ref" | "notAllowed" | "empty" | "externalRef" | "define" | "start" | "include" => {
                // Single pattern as root (simplified grammar)
                let pattern = rng_parse_pattern(root_elem, &mut schema);
                schema.grammar.start = Some(pattern);
                Ok(schema)
            }
            _ => Err(format!("Unknown RELAX NG root element: '{}'", local_name)),
        }
    }
}

/// Parse a `<grammar>` element.
///
/// `base` is the URL of the document this grammar node lives in; it anchors
/// relative `<include href>` resolution (recursively for nested includes).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a `<grammar>` element node.
unsafe fn rng_parse_grammar_node(
    node: *mut _xmlNode,
    schema: &mut RelaxNgSchema,
    base: Option<&str>,
) -> RelaxNgGrammar {
    unsafe {
        let mut grammar = RelaxNgGrammar::new();

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let local = get_local_name(child);
                match local.as_str() {
                    "define" => {
                        let def = rng_parse_define(child, schema);
                        grammar.defines.push(def);
                    }
                    "start" => {
                        grammar.start = Some(rng_parse_pattern(child, schema));
                    }
                    "include" => {
                        if let Some(inc) = rng_parse_include(child, schema, base) {
                            // UPSTREAM-PARITY (relaxng.c combined grammar): a
                            // grammar with no <start> of its own inherits the
                            // start pattern of an included grammar.
                            if grammar.start.is_none() {
                                grammar.start = inc.start.clone();
                            }
                            grammar.includes.push(inc);
                        }
                    }
                    "div" => {
                        // <div> is a grouping element; recurse into it
                        let sub_grammar = rng_parse_grammar_node(child, schema, base);
                        grammar.defines.extend(sub_grammar.defines);
                        if sub_grammar.start.is_some() {
                            grammar.start = sub_grammar.start;
                        }
                        grammar.includes.extend(sub_grammar.includes);
                    }
                    _ => {
                        // Unknown element inside grammar — treat as pattern error
                        schema
                            .errors
                            .push(format!("Unexpected element '<{}>' in grammar", local));
                    }
                }
            }
            child = (*child).next;
        }

        grammar
    }
}

/// Parse a `<define>` element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a `<define>` element node.
unsafe fn rng_parse_define(node: *mut _xmlNode, schema: &mut RelaxNgSchema) -> RelaxNgDefine {
    unsafe {
        let name = get_attr(node, "name").unwrap_or_default();
        let pattern = rng_parse_pattern(node, schema);
        RelaxNgDefine { name, pattern }
    }
}

/// Parse an `<include>` element.
///
/// `base` anchors the relative `href` (the URL of the including grammar's
/// document). Nested includes inside the loaded grammar resolve against the
/// loaded document's own URL.
///
/// UPSTREAM-PARITY (relaxng.c xmlRelaxNGParseInclude): the returned grammar
/// is the INCLUDED document's grammar with the `<include>` element's own
/// children applied — a `<define>` child redefines the same-named definition
/// of the included grammar (or adds a new one), and a `<start>` child
/// replaces the included start pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<include>` element node.
unsafe fn rng_parse_include(
    node: *mut _xmlNode,
    schema: &mut RelaxNgSchema,
    base: Option<&str>,
) -> Option<RelaxNgGrammar> {
    unsafe {
        let href = get_attr(node, "href");
        let mut grammar = if let Some(ref url) = href {
            // UPSTREAM-PARITY (relaxng.c): resolve the href against the
            // including document's base (xmlBuildURI) so relative includes
            // resolve next to the schema file, not the process CWD.
            let resolved = match base {
                Some(base) => {
                    let base_c = std::ffi::CString::new(base).ok()?;
                    let href_c = std::ffi::CString::new(url.clone()).ok()?;
                    let r = crate::abi::exports_uri::xmlBuildURI(href_c.as_ptr(), base_c.as_ptr());
                    if r.is_null() {
                        url.clone()
                    } else {
                        let mut len = 0;
                        while *r.add(len) != 0 {
                            len += 1;
                        }
                        let slice = std::slice::from_raw_parts(r, len);
                        let s = String::from_utf8_lossy(slice).to_string();
                        crate::abi::allocator::xmlFreeImpl(r as *mut core::ffi::c_void);
                        s
                    }
                }
                None => url.clone(),
            };
            let url_c = std::ffi::CString::new(resolved.clone()).ok()?;
            let doc = crate::abi::exports_xml2::xmlParseFile(url_c.as_ptr());
            if doc.is_null() {
                return None;
            }
            let mut inc_schema = RelaxNgSchema::new();
            let grammar = rng_parse_grammar_node(
                {
                    let mut root = (*doc).children;
                    while !root.is_null() && (*root).type_ != XML_ELEMENT_NODE as c_int {
                        root = (*root).next;
                    }
                    root
                },
                &mut inc_schema,
                doc_url(doc).as_deref(),
            );
            crate::abi::exports_xml2::xmlFreeDoc(doc);
            grammar
        } else {
            // Inline grammar in include
            let mut inc_schema = RelaxNgSchema::new();
            rng_parse_grammar_node(node, &mut inc_schema, base)
        };

        // Apply the <include> element's own children (redefinitions) to the
        // included grammar. For an href include, `node` is the <include>
        // element itself; for an inline include, the grammar was parsed FROM
        // it already, so re-parsing would double it — only the href case
        // carries both an external grammar and inline redefinitions.
        if href.is_some() {
            let mut ovr_schema = RelaxNgSchema::new();
            let ovr = rng_parse_grammar_node(node, &mut ovr_schema, base);
            for def in ovr.defines {
                if let Some(existing) = grammar.defines.iter_mut().find(|d| d.name == def.name) {
                    *existing = def;
                } else {
                    grammar.defines.push(def);
                }
            }
            if ovr.start.is_some() {
                grammar.start = ovr.start;
            }
            grammar.includes.extend(ovr.includes);
        }
        Some(grammar)
    }
}

/// Parse a pattern from an element node. Dispatches based on element name.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an XML element node.
unsafe fn rng_parse_pattern(node: *mut _xmlNode, schema: &mut RelaxNgSchema) -> RelaxNgPattern {
    unsafe {
        let local = get_local_name(node);

        match local.as_str() {
            "element" => rng_parse_element_pattern(node, schema),
            "attribute" => rng_parse_attribute_pattern(node, schema),
            "text" => RelaxNgPattern::text(),
            "empty" => RelaxNgPattern::empty(),
            "notAllowed" => RelaxNgPattern::not_allowed(),
            "choice" => rng_parse_composite_pattern(node, RelaxNgPatternType::Choice, schema),
            "sequence" => rng_parse_composite_pattern(node, RelaxNgPatternType::Sequence, schema),
            "interleave" => {
                rng_parse_composite_pattern(node, RelaxNgPatternType::Interleave, schema)
            }
            "zeroOrMore" => rng_parse_unary_pattern(node, RelaxNgPatternType::ZeroOrMore, schema),
            "oneOrMore" => rng_parse_unary_pattern(node, RelaxNgPatternType::OneOrMore, schema),
            "optional" => rng_parse_unary_pattern(node, RelaxNgPatternType::Optional, schema),
            "list" => rng_parse_unary_pattern(node, RelaxNgPatternType::List, schema),
            "group" => rng_parse_composite_pattern(node, RelaxNgPatternType::Group, schema),
            "data" => rng_parse_data_pattern(node, schema),
            "value" => rng_parse_value_pattern(node, schema),
            "ref" => rng_parse_ref_pattern(node),
            "externalRef" => rng_parse_external_ref(node, schema),
            "define" | "start" | "grammar" | "include" | "div" => {
                // These are grammar-level elements; return the content pattern
                let mut child = (*node).children;
                let mut result = RelaxNgPattern::empty();
                while !child.is_null() {
                    if (*child).type_ == XML_ELEMENT_NODE as c_int {
                        result = rng_parse_pattern(child, schema);
                        break;
                    }
                    child = (*child).next;
                }
                result
            }
            _ => {
                // Unknown element — treat as empty pattern
                schema
                    .errors
                    .push(format!("Unknown pattern element '<{}>'", local));
                RelaxNgPattern::empty()
            }
        }
    }
}

/// Parse an `<element>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<element>` element node.
unsafe fn rng_parse_element_pattern(
    node: *mut _xmlNode,
    schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::Element);

        // Parse name class from name attribute or child <name>, <anyName>, <nsName>, <choice>
        let name_attr = get_attr(node, "name");
        pattern.name = name_attr.clone();

        if let Some(ref n) = name_attr {
            pattern.name_class = Some(RelaxNgNameClass::Name(n.clone()));
        }

        // Parse children for name class and content pattern
        let mut child = (*node).children;
        let mut has_content = false;

        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_local = get_local_name(child);

                match child_local.as_str() {
                    "name" => {
                        let text = get_node_text(child);
                        if !text.is_empty() {
                            pattern.name_class =
                                Some(RelaxNgNameClass::Name(text.trim().to_string()));
                        }
                    }
                    "anyName" => {
                        pattern.name_class = Some(rng_parse_any_name(child));
                    }
                    "nsName" => {
                        pattern.name_class = Some(rng_parse_ns_name(child));
                    }
                    "choice" if pattern.name_class.is_none() => {
                        // Name class choice (only before content)
                        pattern.name_class = Some(rng_parse_name_class_choice(child));
                    }
                    _ => {
                        // Content pattern. UPSTREAM-PARITY (relaxng.c
                        // xmlRelaxNGParseElement): multiple content children
                        // form an implicit group — all of them are kept (the
                        // former single-content gate silently dropped
                        // every pattern after the first, e.g. the `<optional>`
                        // in `<element name="root">a<optional>b</optional>`
                        // which then surfaced as a spurious extra element).
                        pattern.children.push(rng_parse_pattern(child, schema));
                        has_content = true;
                    }
                }
            }
            child = (*child).next;
        }

        // UPSTREAM-PARITY (relaxng.c xmlRelaxNGParseElement): an <element>
        // pattern must carry a content pattern; without one parsing aborts
        // with this exact diagnostic (DOMDocument_relaxNGValidateSource_error2
        // pins "xmlRelaxNGParseElement: element has no content").
        if !has_content {
            schema
                .errors
                .push("xmlRelaxNGParseElement: element has no content".to_string());
            schema.fatal = true;
        }

        pattern
    }
}

/// Parse an `<attribute>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<attribute>` element node.
unsafe fn rng_parse_attribute_pattern(
    node: *mut _xmlNode,
    schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::Attribute);

        // Parse name class
        let name_attr = get_attr(node, "name");
        pattern.name = name_attr.clone();

        if let Some(ref n) = name_attr {
            pattern.name_class = Some(RelaxNgNameClass::Name(n.clone()));
        }

        // Parse children
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_local = get_local_name(child);

                match child_local.as_str() {
                    "name" => {
                        let text = get_node_text(child);
                        if !text.is_empty() {
                            pattern.name_class =
                                Some(RelaxNgNameClass::Name(text.trim().to_string()));
                        }
                    }
                    "anyName" => {
                        pattern.name_class = Some(rng_parse_any_name(child));
                    }
                    "nsName" => {
                        pattern.name_class = Some(rng_parse_ns_name(child));
                    }
                    "choice" if pattern.name_class.is_none() => {
                        pattern.name_class = Some(rng_parse_name_class_choice(child));
                    }
                    _ => {
                        // Content pattern (text, data, etc.)
                        pattern.children.push(rng_parse_pattern(child, schema));
                    }
                }
            }
            child = (*child).next;
        }

        pattern
    }
}

/// Parse an `<anyName>` element (possibly with `<except>`).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<anyName>` element node.
unsafe fn rng_parse_any_name(node: *mut _xmlNode) -> RelaxNgNameClass {
    unsafe {
        // Check for <except> child
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int && get_local_name(child) == "except" {
                let except_nc = rng_parse_name_class_content(child);
                return RelaxNgNameClass::Except(
                    Box::new(RelaxNgNameClass::AnyName),
                    Box::new(except_nc),
                );
            }
            child = (*child).next;
        }
        RelaxNgNameClass::AnyName
    }
}

/// Parse an `<nsName>` element (possibly with `<except>`).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<nsName>` element node.
unsafe fn rng_parse_ns_name(node: *mut _xmlNode) -> RelaxNgNameClass {
    unsafe {
        let ns = get_attr(node, "ns").unwrap_or_default();

        // Check for <except> child
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int && get_local_name(child) == "except" {
                let except_nc = rng_parse_name_class_content(child);
                return RelaxNgNameClass::Except(
                    Box::new(RelaxNgNameClass::NsName(ns)),
                    Box::new(except_nc),
                );
            }
            child = (*child).next;
        }

        RelaxNgNameClass::NsName(ns)
    }
}

/// Parse name class children of a `<choice>` element used as name class.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an element node containing name class children.
unsafe fn rng_parse_name_class_choice(node: *mut _xmlNode) -> RelaxNgNameClass {
    unsafe {
        let mut choices = Vec::new();
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                choices.push(rng_parse_name_class_item(child));
            }
            child = (*child).next;
        }
        if choices.len() == 1 {
            choices.remove(0)
        } else {
            RelaxNgNameClass::Choice(choices)
        }
    }
}

/// Parse a single name class item from a name class context.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an element node.
unsafe fn rng_parse_name_class_item(node: *mut _xmlNode) -> RelaxNgNameClass {
    unsafe {
        let local = get_local_name(node);
        match local.as_str() {
            "name" => {
                let text = get_node_text(node);
                RelaxNgNameClass::Name(text.trim().to_string())
            }
            "anyName" => rng_parse_any_name(node),
            "nsName" => rng_parse_ns_name(node),
            "choice" => rng_parse_name_class_choice(node),
            _ => {
                // Default: treat as name
                let text = get_node_text(node);
                if text.trim().is_empty() {
                    RelaxNgNameClass::AnyName
                } else {
                    RelaxNgNameClass::Name(text.trim().to_string())
                }
            }
        }
    }
}

/// Parse name class content from an `<except>` or similar element.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an element node.
unsafe fn rng_parse_name_class_content(node: *mut _xmlNode) -> RelaxNgNameClass {
    unsafe {
        let mut names = Vec::new();
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                names.push(rng_parse_name_class_item(child));
            }
            child = (*child).next;
        }
        if names.is_empty() {
            RelaxNgNameClass::AnyName
        } else if names.len() == 1 {
            names.remove(0)
        } else {
            RelaxNgNameClass::Choice(names)
        }
    }
}

/// Parse a composite pattern (sequence, choice, interleave, group).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an element node.
unsafe fn rng_parse_composite_pattern(
    node: *mut _xmlNode,
    pattern_type: RelaxNgPatternType,
    schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(pattern_type);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                pattern.children.push(rng_parse_pattern(child, schema));
            }
            child = (*child).next;
        }

        pattern
    }
}

/// Parse a unary pattern (zeroOrMore, oneOrMore, optional, list).
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an element node.
unsafe fn rng_parse_unary_pattern(
    node: *mut _xmlNode,
    pattern_type: RelaxNgPatternType,
    schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(pattern_type);

        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                pattern.children.push(rng_parse_pattern(child, schema));
                // Only take the first child pattern for unary patterns
                break;
            }
            child = (*child).next;
        }

        pattern
    }
}

/// Parse a `<data>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a `<data>` element node.
unsafe fn rng_parse_data_pattern(
    node: *mut _xmlNode,
    _schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::Data);
        pattern.datatype = get_attr(node, "type");
        pattern.datatype_library = get_attr(node, "datatypeLibrary");

        // For basic support, we store the type and don't process params in detail
        pattern
    }
}

/// Parse a `<value>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a `<value>` element node.
unsafe fn rng_parse_value_pattern(
    node: *mut _xmlNode,
    _schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::Value);
        pattern.datatype = get_attr(node, "type");
        pattern.datatype_library = get_attr(node, "datatypeLibrary");
        pattern.value = Some(get_node_text(node).trim().to_string());

        pattern
    }
}

/// Parse a `<ref>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to a `<ref>` element node.
unsafe fn rng_parse_ref_pattern(node: *mut _xmlNode) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::Ref);
        pattern.name = get_attr(node, "name");
        pattern
    }
}

/// Parse an `<externalRef>` pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an `<externalRef>` element node.
unsafe fn rng_parse_external_ref(
    node: *mut _xmlNode,
    _schema: &mut RelaxNgSchema,
) -> RelaxNgPattern {
    unsafe {
        let mut pattern = RelaxNgPattern::new(RelaxNgPatternType::ExternalRef);
        let href = get_attr(node, "href");
        pattern.name = href;
        pattern
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RELAX NG Validation Logic
// ═══════════════════════════════════════════════════════════════════════════════

/// Validate an XML document against a RELAX NG schema.
///
/// Returns `true` if the document is valid.
///
/// # SAFETY
///
/// - `schema` must be a valid reference to a parsed schema.
/// - `doc` must be a valid pointer to an _xmlDoc or NULL.
/// - `ctxt` must be a valid mutable reference to a validation context.
pub unsafe fn rng_validate_doc(
    schema: &RelaxNgSchema,
    doc: *mut _xmlDoc,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if doc.is_null() {
            ctxt.record_error("Document is null".to_string());
            return false;
        }

        let root = (*doc).children;
        if root.is_null() {
            ctxt.record_error("Document has no children".to_string());
            return false;
        }

        // Find the root element
        let mut root_elem = root;
        while !root_elem.is_null() && (*root_elem).type_ != XML_ELEMENT_NODE as c_int {
            root_elem = (*root_elem).next;
        }

        if root_elem.is_null() {
            ctxt.record_error("Document has no root element".to_string());
            return false;
        }

        // Get the start pattern
        let start_pattern = match &schema.grammar.start {
            Some(p) => p,
            None => {
                ctxt.record_error("Schema has no start pattern".to_string());
                return false;
            }
        };

        ctxt.path.clear();
        let valid = rng_validate_pattern(start_pattern, root_elem, schema, ctxt);

        // Check for remaining unmatched errors
        valid
    }
}

/// Run RELAX NG validation of a document against an already-compiled schema
/// (xmlRelaxNGPtr from xmlRelaxNGParse), collecting the diagnostics WITHOUT
/// dispatching them to any registered handler. Used by the xmlTextReader
/// (which validates deferred, at first Read, and raises the diagnostics
/// through the global libxml error channel itself).
///
/// # SAFETY
///
/// - `schema` must be a valid compiled-schema pointer from xmlRelaxNGParse;
/// - `doc` must be a valid parsed document.
pub(crate) unsafe fn rng_validate_doc_compiled(
    schema: *mut c_void,
    doc: *mut _xmlDoc,
) -> (bool, Vec<String>) {
    unsafe {
        if schema.is_null() || doc.is_null() {
            return (false, Vec::new());
        }
        let schema_ref = &*(schema as *const RelaxNgSchema);
        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = rng_validate_doc(schema_ref, doc, &mut ctxt);
        (valid, ctxt.errors)
    }
}

/// Validate a pattern against a node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if ctxt.depth >= ctxt.depth_max {
            ctxt.record_error("Maximum validation depth exceeded".to_string());
            return false;
        }
        ctxt.depth += 1;

        let result = match pattern.pattern_type {
            RelaxNgPatternType::Element => {
                rng_validate_element_pattern(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::Attribute => {
                rng_validate_attribute_pattern(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::Text => rng_validate_text_pattern(node, ctxt),
            RelaxNgPatternType::Empty => rng_validate_empty_pattern(node, ctxt),
            RelaxNgPatternType::NotAllowed => {
                let name = get_node_qname(node);
                ctxt.record_error(format!(
                    "Element '{}' is not allowed at '{}'",
                    name,
                    ctxt.current_path()
                ));
                false
            }
            RelaxNgPatternType::Choice => rng_validate_choice_pattern(pattern, node, schema, ctxt),
            RelaxNgPatternType::Sequence => {
                rng_validate_sequence_pattern(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::Interleave => {
                rng_validate_interleave_pattern(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::ZeroOrMore => {
                rng_validate_zero_or_more(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::OneOrMore => rng_validate_one_or_more(pattern, node, schema, ctxt),
            RelaxNgPatternType::Optional => {
                rng_validate_optional_pattern(pattern, node, schema, ctxt)
            }
            RelaxNgPatternType::List => rng_validate_list_pattern(pattern, node, schema, ctxt),
            RelaxNgPatternType::Group => rng_validate_group_pattern(pattern, node, schema, ctxt),
            RelaxNgPatternType::Data => rng_validate_data_pattern(pattern, node, ctxt),
            RelaxNgPatternType::Value => rng_validate_value_pattern(pattern, node, ctxt),
            RelaxNgPatternType::Ref => rng_validate_ref_pattern(pattern, node, schema, ctxt),
            RelaxNgPatternType::ExternalRef => {
                // External refs are resolved during parsing; treat as empty
                rng_validate_empty_pattern(node, ctxt)
            }
            RelaxNgPatternType::Define
            | RelaxNgPatternType::Grammar
            | RelaxNgPatternType::Start
            | RelaxNgPatternType::Include => {
                // These shouldn't appear during validation; treat as pass-through
                rng_validate_children(pattern, node, schema, ctxt)
            }
        };

        ctxt.depth -= 1;
        result
    }
}

/// Validate a pattern's children against a node's children.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_children(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    {
        if pattern.children.is_empty() {
            return true;
        }
        // Validate each child pattern against the same node
        let mut valid = true;
        for child in &pattern.children {
            valid &= rng_validate_pattern(child, node, schema, ctxt);
        }
        valid
    }
}

/// Validate an element pattern against an element node.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_element_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() || (*node).type_ != XML_ELEMENT_NODE as c_int {
            return false;
        }

        let node_name = get_node_qname(node);
        let ns_uri = get_node_ns_uri(node);

        // Check if the node name matches the element pattern's name class
        if let Some(ref nc) = pattern.name_class {
            if !nc.matches(&node_name, ns_uri.as_deref()) {
                let pat_name = pattern.name.as_deref().unwrap_or("?");
                ctxt.record_error(format!(
                    "Element '{}' does not match expected element pattern '{}' at '{}'",
                    node_name,
                    pat_name,
                    ctxt.current_path()
                ));
                return false;
            }
        }

        // Push the element name onto the path
        ctxt.path.push(node_name.clone());

        // Validate child patterns against this element's CHILDREN.
        // UPSTREAM-PARITY (relaxng.c xmlRelaxNGValidateElement): the
        // content patterns describe the element's children, not the element
        // itself. The pre-fix code validated them against the element node
        // directly, so any nested element pattern failed its name match and
        // every non-empty schema rejected every document (Phase 14 lxml
        // RelaxNG court).
        let valid = rng_validate_content(&pattern.children, node, schema, ctxt);

        ctxt.path.pop();
        valid
    }
}

/// Validate an element's content model (the child patterns of an element
/// pattern) against the element's child nodes.
///
/// An empty content model requires no element children; a single structural
/// pattern (sequence/choice/interleave/group/zeroOrMore/oneOrMore/optional)
/// consumes the child list with its own logic; anything else is an implicit
/// sequence over the element's element-children, where a `text` pattern
/// validates against the element itself (any text is allowed) without
/// consuming a child.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_content(
    content: &[RelaxNgPattern],
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    if content.is_empty() {
        return rng_validate_empty_pattern(node, ctxt);
    }
    if content.len() == 1 {
        let p = &content[0];
        match p.pattern_type {
            RelaxNgPatternType::Sequence
            | RelaxNgPatternType::Choice
            | RelaxNgPatternType::Interleave
            | RelaxNgPatternType::Group
            | RelaxNgPatternType::ZeroOrMore
            | RelaxNgPatternType::OneOrMore
            | RelaxNgPatternType::Optional
            | RelaxNgPatternType::List => {
                return rng_validate_pattern(p, node, schema, ctxt);
            }
            RelaxNgPatternType::Text => return rng_validate_text_pattern(node, ctxt),
            RelaxNgPatternType::Empty => return rng_validate_empty_pattern(node, ctxt),
            RelaxNgPatternType::Data => return rng_validate_data_pattern(p, node, ctxt),
            RelaxNgPatternType::Value => return rng_validate_value_pattern(p, node, ctxt),
            RelaxNgPatternType::Attribute => {
                return rng_validate_attribute_pattern(p, node, schema, ctxt)
            }
            _ => {}
        }
    }

    unsafe {
        // Collect the element's element-children in document order.
        let mut child_nodes: Vec<*mut _xmlNode> = Vec::new();
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                child_nodes.push(child);
            }
            child = (*child).next;
        }

        let mut valid = true;
        let mut child_idx = 0;
        for child_pat in content {
            // Patterns over the element's own character data and attributes
            // do NOT consume an element child: `text` matches any text,
            // `data`/`value` validate the concatenated text content,
            // `attribute` validates the element's attributes, and `empty`
            // requires no element children (upstream relaxng.c treats these
            // against the element's data/attributes, not its child list).
            match child_pat.pattern_type {
                RelaxNgPatternType::Text => {
                    valid &= rng_validate_text_pattern(node, ctxt);
                    continue;
                }
                RelaxNgPatternType::Data => {
                    valid &= rng_validate_data_pattern(child_pat, node, ctxt);
                    continue;
                }
                RelaxNgPatternType::Value => {
                    valid &= rng_validate_value_pattern(child_pat, node, ctxt);
                    continue;
                }
                RelaxNgPatternType::Attribute => {
                    valid &= rng_validate_attribute_pattern(child_pat, node, schema, ctxt);
                    continue;
                }
                RelaxNgPatternType::Empty => {
                    valid &= rng_validate_empty_pattern(node, ctxt);
                    continue;
                }
                _ => {}
            }
            if child_idx >= child_nodes.len() {
                match child_pat.pattern_type {
                    RelaxNgPatternType::Optional | RelaxNgPatternType::ZeroOrMore => {
                        // These are fine to have no matching children.
                        continue;
                    }
                    RelaxNgPatternType::OneOrMore => {
                        ctxt.record_error(format!(
                            "Expected at least one matching child for oneOrMore at '{}'",
                            ctxt.current_path()
                        ));
                        valid = false;
                        continue;
                    }
                    _ => {
                        ctxt.record_error(format!(
                            "Expected more child elements for content model at '{}'",
                            ctxt.current_path()
                        ));
                        valid = false;
                        continue;
                    }
                }
            }
            let child_node = child_nodes[child_idx];
            valid &= rng_validate_pattern(child_pat, child_node, schema, ctxt);
            child_idx += 1;
        }

        // Check for extra children.
        if child_idx < child_nodes.len() {
            let extra_name = get_node_qname(child_nodes[child_idx]);
            // UPSTREAM-PARITY (relaxng.c xmlRelaxNGValidateElement, error
            // XML_RELAXNG_ERR_ELEMWRONG): "Did not expect element %s there".
            ctxt.record_error(format!("Did not expect element {} there", extra_name));
            valid = false;
        }

        valid
    }
}

/// Validate an attribute pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_attribute_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    _schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() || (*node).type_ != XML_ELEMENT_NODE as c_int {
            return false;
        }

        // Get the attribute name from the pattern's name class
        let attr_name = match &pattern.name_class {
            Some(RelaxNgNameClass::Name(n)) => n.clone(),
            Some(RelaxNgNameClass::AnyName) => {
                // Any attribute is allowed — just check that there's at least one
                // attribute that matches (or return true if the attribute is optional)
                // For now, we just return true for anyName since we can't know which
                // attribute to check
                return true;
            }
            Some(RelaxNgNameClass::NsName(ns)) => {
                // Any attribute in the given namespace.
                // Check if there's an attribute with a matching namespace.
                let mut prop = (*node).properties;
                while !prop.is_null() {
                    let prop_ns = get_node_ns_uri(prop as *mut _xmlNode);
                    if let Some(ref uri) = prop_ns {
                        if uri == ns {
                            // Validate content pattern against attribute value
                            if let Some(content) = &pattern.children.first() {
                                let val = get_node_text(prop as *mut _xmlNode);
                                let valid = match content.pattern_type {
                                    RelaxNgPatternType::Text => true,
                                    RelaxNgPatternType::Data => rng_validate_datatype_value(
                                        content.datatype.as_deref(),
                                        &val,
                                    ),
                                    RelaxNgPatternType::Value => {
                                        content.value.as_deref() == Some(&val)
                                    }
                                    _ => true,
                                };
                                if !valid {
                                    ctxt.record_error(format!(
                                        "Attribute '{}' has invalid value at '{}'",
                                        prop_ns.unwrap_or_default(),
                                        ctxt.current_path()
                                    ));
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                    prop = (*prop).next;
                }
                // No matching attribute found — attribute is required
                // (In RELAX NG, attributes are implicitly required)
                ctxt.record_error(format!(
                    "Required attribute in namespace '{}' is missing at '{}'",
                    ns,
                    ctxt.current_path()
                ));
                return false;
            }
            _ => {
                // Complex name class — just check if any attribute matches
                // This is a simplified check
                return true;
            }
        };

        // Check if the attribute exists on the element
        let attr_value = get_attr(node, &attr_name);

        match attr_value {
            Some(val) => {
                // Validate content pattern against attribute value
                if let Some(content) = pattern.children.first() {
                    let valid = match content.pattern_type {
                        RelaxNgPatternType::Text => true,
                        RelaxNgPatternType::Data => {
                            rng_validate_datatype_value(content.datatype.as_deref(), &val)
                        }
                        RelaxNgPatternType::Value => content.value.as_deref() == Some(&val),
                        _ => true,
                    };
                    if !valid {
                        ctxt.record_error(format!(
                            "Attribute '{}' has invalid value '{}' at '{}'",
                            attr_name,
                            val,
                            ctxt.current_path()
                        ));
                        return false;
                    }
                }
                true
            }
            None => {
                // Attribute not found — only error if the pattern requires it
                // (In RELAX NG, attributes are implicitly required unless wrapped in optional)
                ctxt.record_error(format!(
                    "Required attribute '{}' is missing at '{}'",
                    attr_name,
                    ctxt.current_path()
                ));
                false
            }
        }
    }
}

/// Validate a text pattern against text content.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
const fn rng_validate_text_pattern(node: *mut _xmlNode, _ctxt: &mut RelaxNgValidCtxt) -> bool {
    {
        if node.is_null() {
            return false;
        }
        // Text pattern matches any text content (or mixed content with elements)
        // In RELAX NG, text allows any text content
        true
    }
}

/// Validate an empty pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_empty_pattern(node: *mut _xmlNode, ctxt: &mut RelaxNgValidCtxt) -> bool {
    unsafe {
        if node.is_null() {
            return true;
        }
        // Empty pattern — the element must have no element children
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let child_name = get_node_qname(child);
                ctxt.record_error(format!(
                    "Unexpected child element '{}' in empty content at '{}'",
                    child_name,
                    ctxt.current_path()
                ));
                return false;
            }
            child = (*child).next;
        }
        true
    }
}

/// Validate a choice pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_choice_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if pattern.children.is_empty() {
            return false;
        }

        // At least one choice must match
        let mut last_error = String::new();
        for child in &pattern.children {
            let saved_errors = ctxt.errors.len();
            let saved_nb = ctxt.nb_errors;

            if rng_validate_pattern(child, node, schema, ctxt) {
                // Restore errors from failed choices
                // (errors from failed branches should be discarded)
                return true;
            }

            // Capture the last error for reporting
            if ctxt.errors.len() > saved_errors {
                last_error = ctxt.errors.last().unwrap().clone();
            }

            // Restore error state (choice means at least one alternative must pass)
            ctxt.errors.truncate(saved_errors);
            ctxt.nb_errors = saved_nb;
        }

        // If we got here, none of the choices matched
        let node_name = if node.is_null() {
            "null".to_string()
        } else {
            get_node_qname(node)
        };
        ctxt.record_error(format!(
            "No choice pattern matched for '{}' at '{}'. Last error: {}",
            node_name,
            ctxt.current_path(),
            last_error
        ));
        false
    }
}

/// Validate a sequence pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_sequence_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() {
            return pattern.children.is_empty();
        }

        let mut valid = true;

        // For sequence validation, we validate each child pattern against
        // the node's children in order.
        // Collect element children of the node
        let mut child_nodes: Vec<*mut _xmlNode> = Vec::new();
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                child_nodes.push(child);
            }
            child = (*child).next;
        }

        // Simple sequence matching: validate each child pattern
        // against corresponding child nodes
        let mut child_idx = 0;
        for child_pat in &pattern.children {
            if child_idx >= child_nodes.len() {
                // Check if the pattern is optional or zero-or-more
                match child_pat.pattern_type {
                    RelaxNgPatternType::Optional | RelaxNgPatternType::ZeroOrMore => {
                        // These are fine to have no matching children
                        continue;
                    }
                    RelaxNgPatternType::OneOrMore => {
                        ctxt.record_error(format!(
                            "Expected at least one matching child for oneOrMore at '{}'",
                            ctxt.current_path()
                        ));
                        valid = false;
                        continue;
                    }
                    _ => {
                        ctxt.record_error(format!(
                            "Expected more child elements for sequence at '{}'",
                            ctxt.current_path()
                        ));
                        valid = false;
                        continue;
                    }
                }
            }

            let child_node = child_nodes[child_idx];
            valid &= rng_validate_pattern(child_pat, child_node, schema, ctxt);
            child_idx += 1;
        }

        // Check for extra children
        if child_idx < child_nodes.len() {
            let extra_name = get_node_qname(child_nodes[child_idx]);
            ctxt.record_error(format!(
                "Unexpected extra element '{}' in sequence at '{}'",
                extra_name,
                ctxt.current_path()
            ));
            valid = false;
        }

        valid
    }
}

/// Validate an interleave pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_interleave_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() {
            return pattern.children.is_empty();
        }

        // Interleave means child patterns can match in any order.
        // For simplicity, we validate each child pattern against a fresh
        // traversal of the node's children.
        let mut valid = true;

        for child_pat in &pattern.children {
            // For each pattern in the interleave, check if there's at least
            // one child node that matches
            let mut child = (*node).children;
            let mut matched = false;

            while !child.is_null() {
                if (*child).type_ == XML_ELEMENT_NODE as c_int {
                    let saved_errors = ctxt.errors.len();
                    let saved_nb = ctxt.nb_errors;

                    if rng_validate_pattern(child_pat, child, schema, ctxt) {
                        matched = true;
                        break;
                    }

                    // Restore errors for this attempt
                    ctxt.errors.truncate(saved_errors);
                    ctxt.nb_errors = saved_nb;
                }
                child = (*child).next;
            }

            if !matched {
                // Check if pattern is optional
                match child_pat.pattern_type {
                    RelaxNgPatternType::Optional | RelaxNgPatternType::ZeroOrMore => {
                        // Optional patterns can be absent
                    }
                    _ => {
                        let pat_desc = format!("{:?}", child_pat.pattern_type);
                        ctxt.record_error(format!(
                            "Interleave pattern '{}' did not match any child at '{}'",
                            pat_desc,
                            ctxt.current_path()
                        ));
                        valid = false;
                    }
                }
            }
        }

        valid
    }
}

/// Validate a zeroOrMore pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_zero_or_more(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() || pattern.children.is_empty() {
            return true;
        }

        let child_pat = &pattern.children[0];
        let valid = true;

        // Match as many child nodes as possible against the pattern
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let saved_errors = ctxt.errors.len();
                let saved_nb = ctxt.nb_errors;

                if !rng_validate_pattern(child_pat, child, schema, ctxt) {
                    // This child doesn't match the zeroOrMore pattern
                    // Restore errors and stop
                    ctxt.errors.truncate(saved_errors);
                    ctxt.nb_errors = saved_nb;
                    break;
                }
                // Successfully matched — errors from matching are valid
            }
            child = (*child).next;
        }

        valid
    }
}

/// Validate a oneOrMore pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_one_or_more(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() || pattern.children.is_empty() {
            ctxt.record_error(format!(
                "Expected at least one matching element for oneOrMore at '{}'",
                ctxt.current_path()
            ));
            return false;
        }

        let child_pat = &pattern.children[0];
        let mut matched = false;
        let mut valid = true;

        // Match at least one child, then as many as possible
        let mut child = (*node).children;
        while !child.is_null() {
            if (*child).type_ == XML_ELEMENT_NODE as c_int {
                let saved_errors = ctxt.errors.len();
                let saved_nb = ctxt.nb_errors;

                if rng_validate_pattern(child_pat, child, schema, ctxt) {
                    matched = true;
                } else {
                    // Restore errors and stop
                    ctxt.errors.truncate(saved_errors);
                    ctxt.nb_errors = saved_nb;
                    break;
                }
            }
            child = (*child).next;
        }

        if !matched {
            ctxt.record_error(format!(
                "Expected at least one matching element for oneOrMore at '{}'",
                ctxt.current_path()
            ));
            valid = false;
        }

        valid
    }
}

/// Validate an optional pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_optional_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    {
        if pattern.children.is_empty() {
            return true;
        }

        // Optional means the pattern can match or not — both are valid
        let child_pat = &pattern.children[0];
        let saved_errors = ctxt.errors.len();
        let saved_nb = ctxt.nb_errors;

        let result = rng_validate_pattern(child_pat, node, schema, ctxt);

        if !result {
            // Restore errors — it's okay that optional didn't match
            ctxt.errors.truncate(saved_errors);
            ctxt.nb_errors = saved_nb;
        }

        true // Optional always returns true
    }
}

/// Validate a list pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_list_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    _schema: &RelaxNgSchema,
    _ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() {
            return pattern.children.is_empty();
        }

        // List pattern: whitespace-separated tokens, each matching the child pattern
        let text = get_node_text(node);
        if text.trim().is_empty() {
            return true;
        }

        let tokens: Vec<&str> = text.split_whitespace().collect();
        let mut valid = true;

        for token in &tokens {
            // For each token, validate against the child pattern
            // We do a simplified check — just ensure it's non-empty
            if token.is_empty() {
                valid = false;
                break;
            }
        }

        valid
    }
}

/// Validate a group pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_group_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    {
        // Group is similar to sequence — validate children in order
        rng_validate_sequence_pattern(pattern, node, schema, ctxt)
    }
}

/// Validate a data pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_data_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() {
            return false;
        }

        let text = get_node_text(node);
        let datatype = pattern.datatype.as_deref();

        if !rng_validate_datatype_value(datatype, &text) {
            ctxt.record_error(format!(
                "Value '{}' does not match datatype '{:?}' at '{}'",
                text,
                datatype,
                ctxt.current_path()
            ));
            return false;
        }

        true
    }
}

/// Validate a value pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_value_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    unsafe {
        if node.is_null() {
            return false;
        }

        let text = get_node_text(node).trim().to_string();
        let expected = pattern.value.as_deref().unwrap_or("");

        if text != expected {
            ctxt.record_error(format!(
                "Value '{}' does not match expected value '{}' at '{}'",
                text,
                expected,
                ctxt.current_path()
            ));
            return false;
        }

        true
    }
}

/// Validate a ref pattern.
///
/// # SAFETY
///
/// - `node` must be a valid pointer to an _xmlNode or NULL.
fn rng_validate_ref_pattern(
    pattern: &RelaxNgPattern,
    node: *mut _xmlNode,
    schema: &RelaxNgSchema,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    {
        let ref_name = pattern.name.as_deref().unwrap_or("");

        if ref_name.is_empty() {
            ctxt.record_error("Ref pattern has no name".to_string());
            return false;
        }

        // Look up the definition
        match schema.grammar.lookup(ref_name) {
            Some(def_pattern) => {
                // Validate against the definition's pattern
                rng_validate_pattern(def_pattern, node, schema, ctxt)
            }
            None => {
                ctxt.record_error(format!(
                    "Undefined reference '{}' at '{}'",
                    ref_name,
                    ctxt.current_path()
                ));
                false
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Datatype Validation for RELAX NG
// ═══════════════════════════════════════════════════════════════════════════════

/// Validate a value against a RELAX NG datatype.
///
/// RELAX NG supports a subset of XML Schema datatypes. This function
/// provides basic datatype validation for common types.
fn rng_validate_datatype_value(datatype: Option<&str>, value: &str) -> bool {
    let dt = match datatype {
        Some(d) => d,
        None => return true, // No datatype specified — accept anything
    };

    match dt {
        "string" | "token" => true,
        "boolean" => {
            matches!(value, "true" | "false" | "1" | "0")
        }
        "integer" | "int" | "short" | "byte" | "long" => {
            if value.is_empty() {
                return false;
            }
            let trimmed = if value.starts_with('+') || value.starts_with('-') {
                &value[1..]
            } else {
                value
            };
            !trimmed.is_empty() && trimmed.chars().all(|c| c.is_ascii_digit())
        }
        "decimal" | "double" | "float" => {
            if value.is_empty() {
                return false;
            }
            // Allow INF, -INF, NaN for float/double
            if matches!(dt, "float" | "double") && matches!(value, "INF" | "-INF" | "NaN") {
                return true;
            }
            value.parse::<f64>().is_ok()
        }
        "NCName" | "Name" | "ID" | "IDREF" | "NMTOKEN" => {
            !value.is_empty() && !value.starts_with(|c: char| c.is_ascii_digit())
        }
        "anyURI" => {
            // Simple URI validation — non-empty and no spaces
            !value.is_empty() && !value.contains(char::is_whitespace)
        }
        "QName" => {
            if value.is_empty() {
                return false;
            }
            if let Some(pos) = value.find(':') {
                pos > 0 && pos < value.len() - 1
            } else {
                true
            }
        }
        _ => {
            // Unknown datatype — accept by default
            // This matches libxml2's lenient behavior
            true
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Public API Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a RELAX NG schema from an XML string.
///
/// Returns the parsed schema, or an error message on failure.
pub fn rng_parse_schema(xml_doc: &str) -> Result<RelaxNgSchema, String> {
    rng_parse(xml_doc)
}

/// Parse a RELAX NG schema from a parsed XML document.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc.
pub unsafe fn rng_parse_schema_doc(doc: *mut _xmlDoc) -> Result<RelaxNgSchema, String> {
    rng_parse_doc(doc)
}

/// Validate a document against a RELAX NG schema.
///
/// Returns `true` if the document is valid.
///
/// # SAFETY
///
/// - `doc` must be a valid pointer to an _xmlDoc or NULL.
pub unsafe fn rng_validate_doc_schema(
    schema: &RelaxNgSchema,
    doc: *mut _xmlDoc,
    ctxt: &mut RelaxNgValidCtxt,
) -> bool {
    rng_validate_doc(schema, doc, ctxt)
}

// ═══════════════════════════════════════════════════════════════════════════════
// C ABI Functions
// ═══════════════════════════════════════════════════════════════════════════════

// These are the C-compatible entry points that get exported via the ABI layer.
// They use raw pointers and follow libxml2's calling conventions.

/// Create a new RELAX NG parser context.
/// RELAX NG parser context (upstream `xmlRelaxNGParserCtxt`).
///
/// Owns the eagerly-parsed schema; `xmlRelaxNGParse` hands out a NEW schema
/// object (a clone) so the context and the schema have separate lifetimes,
/// exactly as upstream callers expect (lxml: `xmlRelaxNGParse` then
/// `xmlRelaxNGFreeParserCtxt`, with `xmlRelaxNGFree` on the schema at
/// dealloc). The pre-fix implementation returned the context as the schema
/// pointer, so `xmlRelaxNGFreeParserCtxt` freed the schema out from under
/// consumers — a use-after-free (Phase 14 lxml RelaxNG court).
pub(crate) struct RelaxNgParserCtxt {
    /// The parsed schema, if parsing succeeded.
    pub(crate) schema: Option<RelaxNgSchema>,
    /// The schema resource name for file-based parser contexts. Kept so
    /// `xmlRelaxNGParse` can report upstream's "could not load %s" diagnostic
    /// when the resource was not readable (the I/O warning itself is emitted
    /// by the document open, mirroring upstream xmlRelaxNGParseFile).
    pub(crate) url: Option<String>,
}

/// Create a new RELAX NG parser context from a URL.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlRelaxNGParserCtxtPtr xmlRelaxNGNewParserCtxt(const char *URL);
/// ```
///
/// # SAFETY
///
/// - `url` must be a valid null-terminated C string or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGNewParserCtxt(url: *const c_char) -> *mut c_void {
    if url.is_null() {
        return Box::into_raw(Box::new(RelaxNgParserCtxt {
            schema: None,
            url: None,
        })) as *mut c_void;
    }

    let url_str = unsafe {
        let mut len = 0;
        while *url.add(len) != 0 {
            len += 1;
        }
        let slice = std::slice::from_raw_parts(url as *const u8, len);
        String::from_utf8_lossy(slice).to_string()
    };

    // Parse the schema from the URL eagerly and keep it in the context. The
    // document is opened through the standard input machinery
    // (xmlParseFile), so an unreadable resource raises the upstream I/O
    // warning exactly like xmlRelaxNGParseFile.
    let schema = if url_str.is_empty() {
        None
    } else {
        let url_c = std::ffi::CString::new(url_str.clone()).ok();
        if let Some(c) = url_c {
            let doc = crate::abi::exports_xml2::xmlParseFile(c.as_ptr());
            if !doc.is_null() {
                let result = rng_parse_doc(doc);
                crate::abi::exports_xml2::xmlFreeDoc(doc);
                result.ok()
            } else {
                None
            }
        } else {
            None
        }
    };
    Box::into_raw(Box::new(RelaxNgParserCtxt {
        schema,
        url: Some(url_str),
    })) as *mut c_void
}

/// Create a new RELAX NG parser context from a memory buffer.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlRelaxNGParserCtxtPtr xmlRelaxNGNewMemParserCtxt(const char *buffer, int size);
/// ```
///
/// # SAFETY
///
/// - `buffer` must be a valid pointer to a buffer of at least `size` bytes.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGNewMemParserCtxt(
    buffer: *const c_char,
    size: c_int,
) -> *mut c_void {
    if buffer.is_null() || size <= 0 {
        return ptr::null_mut();
    }

    // Parse the schema immediately and keep it in the parser context;
    // `xmlRelaxNGParse` hands out a fresh schema object (Phase 14: the
    // context and the schema must have separate lifetimes — lxml frees the
    // context right after xmlRelaxNGParse and the schema at dealloc).
    let buf_slice = unsafe { std::slice::from_raw_parts(buffer as *const u8, size as usize) };
    let xml_str = String::from_utf8_lossy(buf_slice).to_string();

    let schema = rng_parse(&xml_str).ok();
    Box::into_raw(Box::new(RelaxNgParserCtxt { schema, url: None })) as *mut c_void
}

/// Parse a RELAX NG schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlRelaxNGPtr xmlRelaxNGParse(xmlRelaxNGParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a parser context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGParse(ctxt: *mut c_void) -> *mut c_void {
    if ctxt.is_null() {
        return ptr::null_mut();
    }

    // UPSTREAM-PARITY (relaxng.c xmlRelaxNGParse): the parser context owns
    // the parsed schema; this hands out a NEW schema object so the caller
    // can free the context independently (lxml frees the context right
    // after this call). The pre-fix implementation returned the context
    // itself, so xmlRelaxNGFreeParserCtxt freed the schema out from under
    // the consumer.
    let pctxt = unsafe { &*ctxt.cast::<RelaxNgParserCtxt>() };
    match &pctxt.schema {
        Some(schema) => {
            // A fatal grammar error (e.g. an <element> pattern without a
            // content model) aborts the parse upstream: the recorded
            // diagnostics go to the registered parser handlers and no schema
            // is returned (php then reports "Invalid RelaxNG" —
            // DOMDocument_relaxNGValidateSource_error2).
            if schema.fatal {
                crate::abi::exports_relaxng::dispatch_relaxng_parser_errors(
                    ctxt as usize,
                    &schema.errors,
                );
                return ptr::null_mut();
            }
            Box::into_raw(Box::new(schema.clone())) as *mut c_void
        }
        None => {
            // The main schema resource could not be loaded (xmlParseFile
            // already emitted the I/O warning). Report upstream's
            // "could not load" diagnostic through the parser handlers
            // (DOMDocument_relaxNGValidate_error2) before returning NULL.
            if let Some(ref url) = pctxt.url {
                if !url.is_empty() {
                    let msg = format!("xmlRelaxNGParse: could not load {}\n", url);
                    crate::abi::exports_relaxng::dispatch_relaxng_parser_errors(
                        ctxt as usize,
                        std::slice::from_ref(&msg),
                    );
                }
            }
            ptr::null_mut()
        }
    }
}

/// Free a RELAX NG schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRelaxNGFree(xmlRelaxNGPtr schema);
/// ```
///
/// # SAFETY
///
/// - `schema` must be a valid pointer to a schema, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGFree(schema: *mut c_void) {
    if schema.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it.
    unsafe {
        let _ = Box::from_raw(schema as *mut RelaxNgSchema);
    }
}

/// Free a RELAX NG parser context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRelaxNGFreeParserCtxt(xmlRelaxNGParserCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a parser context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGFreeParserCtxt(ctxt: *mut c_void) {
    if ctxt.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it (the context is a separate
    // allocation from the schema handed out by xmlRelaxNGParse).
    unsafe {
        let _ = Box::from_raw(ctxt as *mut RelaxNgParserCtxt);
    }
}

/// Create a new RELAX NG validation context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// xmlRelaxNGValidCtxtPtr xmlRelaxNGNewValidCtxt(xmlRelaxNGPtr schema);
/// ```
///
/// # SAFETY
///
/// - `schema` must be a valid pointer to a schema, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGNewValidCtxt(schema: *mut c_void) -> *mut c_void {
    let mut ctxt = RelaxNgValidCtxt::new();

    if !schema.is_null() {
        // SAFETY: The schema pointer is assumed to be a valid RelaxNgSchema.
        unsafe {
            let schema_ref = &*(schema as *const RelaxNgSchema);
            ctxt.schema = Some(schema_ref.clone());
        }
    }

    let boxed = Box::new(ctxt);
    Box::into_raw(boxed) as *mut c_void
}

/// Free a RELAX NG validation context.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// void xmlRelaxNGFreeValidCtxt(xmlRelaxNGValidCtxtPtr ctxt);
/// ```
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a validation context, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGFreeValidCtxt(ctxt: *mut c_void) {
    if ctxt.is_null() {
        return;
    }
    // SAFETY: Reconstruct the Box to drop it.
    unsafe {
        let _ = Box::from_raw(ctxt as *mut RelaxNgValidCtxt);
    }
}

/// Validate a document against a RELAX NG schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlRelaxNGValidateDoc(xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc);
/// ```
///
/// Returns 0 if valid, -1 on internal error, or the number of validation errors.
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a validation context, or NULL.
/// - `doc` must be a valid pointer to an _xmlDoc, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGValidateDoc(ctxt: *mut c_void, doc: *mut _xmlDoc) -> c_int {
    if ctxt.is_null() || doc.is_null() {
        return -1;
    }

    unsafe {
        let valid_ctxt = &mut *(ctxt as *mut RelaxNgValidCtxt);
        let schema = match &valid_ctxt.schema {
            Some(s) => s,
            None => return -1,
        };

        let mut temp_ctxt = RelaxNgValidCtxt::new();

        let valid = rng_validate_doc(schema, doc, &mut temp_ctxt);

        if valid {
            0
        } else {
            valid_ctxt.errors = temp_ctxt.errors;
            valid_ctxt.nb_errors = temp_ctxt.nb_errors;
            // UPSTREAM-PARITY: forward each recorded error to the context's
            // registered handlers (xmlRelaxNGSetValidErrors /
            // xmlRelaxNGSetValidStructuredErrors) so consumers like lxml's
            // RelaxNG.validate (which installs serror = _receiveError)
            // populate their error_log.
            crate::abi::exports_relaxng::dispatch_relaxng_valid_errors(
                ctxt as usize,
                &valid_ctxt.errors,
                ptr::null_mut(),
            );
            temp_ctxt.nb_errors
        }
    }
}

/// Validate a full element against a RELAX NG schema.
///
/// # UPSTREAM-PARITY
///
/// ```c
/// int xmlRelaxNGValidateFullElement(xmlRelaxNGValidCtxtPtr ctxt,
///                                    xmlDocPtr doc,
///                                    xmlNodePtr elem);
/// ```
///
/// Returns 0 if valid, -1 on internal error, or the number of validation errors.
///
/// # SAFETY
///
/// - `ctxt` must be a valid pointer to a validation context, or NULL.
/// - `doc` must be a valid pointer to an _xmlDoc, or NULL.
/// - `elem` must be a valid pointer to an element node, or NULL.
#[no_mangle]
pub unsafe extern "C" fn xmlRelaxNGValidateFullElement(
    ctxt: *mut c_void,
    doc: *mut _xmlDoc,
    elem: *mut _xmlNode,
) -> c_int {
    if ctxt.is_null() || doc.is_null() || elem.is_null() {
        return -1;
    }

    unsafe {
        let valid_ctxt = &mut *(ctxt as *mut RelaxNgValidCtxt);
        let schema = match &valid_ctxt.schema {
            Some(s) => s,
            None => return -1,
        };

        let mut temp_ctxt = RelaxNgValidCtxt::new();
        temp_ctxt.path = valid_ctxt.path.clone();

        let start_pattern = match &schema.grammar.start {
            Some(p) => p,
            None => return -1,
        };

        let valid = rng_validate_pattern(start_pattern, elem, schema, &mut temp_ctxt);

        if valid {
            0
        } else {
            valid_ctxt.errors = temp_ctxt.errors;
            valid_ctxt.nb_errors = temp_ctxt.nb_errors;
            temp_ctxt.nb_errors
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

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

    // ── Name Class Tests ───────────────────────────────────────────────────

    #[test]
    fn test_name_class_name() {
        let nc = RelaxNgNameClass::Name("foo".to_string());
        assert!(nc.matches("foo", None));
        assert!(!nc.matches("bar", None));
        assert!(!nc.matches("FOO", None));
    }

    #[test]
    fn test_name_class_any_name() {
        let nc = RelaxNgNameClass::AnyName;
        assert!(nc.matches("foo", None));
        assert!(nc.matches("bar", None));
        assert!(nc.matches("anything", Some("urn:ns")));
    }

    #[test]
    fn test_name_class_ns_name() {
        let nc = RelaxNgNameClass::NsName("urn:example".to_string());
        assert!(nc.matches("foo", Some("urn:example")));
        assert!(!nc.matches("foo", Some("urn:other")));
        assert!(!nc.matches("foo", None));
    }

    #[test]
    fn test_name_class_choice() {
        let nc = RelaxNgNameClass::Choice(vec![
            RelaxNgNameClass::Name("a".to_string()),
            RelaxNgNameClass::Name("b".to_string()),
        ]);
        assert!(nc.matches("a", None));
        assert!(nc.matches("b", None));
        assert!(!nc.matches("c", None));
    }

    #[test]
    fn test_name_class_except() {
        let nc = RelaxNgNameClass::Except(
            Box::new(RelaxNgNameClass::AnyName),
            Box::new(RelaxNgNameClass::Name("bad".to_string())),
        );
        assert!(nc.matches("good", None));
        assert!(!nc.matches("bad", None));
    }

    // ── Schema Parsing Tests ──────────────────────────────────────────────

    #[test]
    fn test_parse_simple_element_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let result = rng_parse(schema_xml);
        assert!(result.is_ok(), "Failed to parse schema: {:?}", result.err());
        let schema = result.unwrap();
        assert!(schema.grammar.start.is_some());
        if let Some(ref start) = schema.grammar.start {
            assert_eq!(start.pattern_type, RelaxNgPatternType::Element);
            assert_eq!(start.name.as_deref(), Some("root"));
        }
    }

    #[test]
    fn test_parse_grammar_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <text/>
    </element>
  </start>
</grammar>"#;

        let result = rng_parse(schema_xml);
        assert!(
            result.is_ok(),
            "Failed to parse grammar: {:?}",
            result.err()
        );
        let schema = result.unwrap();
        assert!(schema.grammar.start.is_some());
    }

    #[test]
    fn test_parse_with_define_and_ref() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <define name="textBlock">
    <text/>
  </define>
  <start>
    <element name="doc">
      <ref name="textBlock"/>
    </element>
  </start>
</grammar>"#;

        let result = rng_parse(schema_xml);
        assert!(result.is_ok(), "Failed to parse: {:?}", result.err());
        let schema = result.unwrap();
        assert_eq!(schema.grammar.defines.len(), 1);
        assert_eq!(schema.grammar.defines[0].name, "textBlock");
        assert!(schema.grammar.start.is_some());
    }

    #[test]
    fn test_parse_choice_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <choice>
      <element name="a">
        <text/>
      </element>
      <element name="b">
        <text/>
      </element>
    </choice>
  </start>
</grammar>"#;

        let result = rng_parse(schema_xml);
        assert!(result.is_ok(), "Failed to parse choice: {:?}", result.err());
    }

    #[test]
    fn test_parse_attribute_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <attribute name="attr1">
    <text/>
  </attribute>
  <text/>
</element>"#;

        let result = rng_parse(schema_xml);
        assert!(
            result.is_ok(),
            "Failed to parse attribute: {:?}",
            result.err()
        );
    }

    #[test]
    fn test_parse_empty_document_fails() {
        let result = rng_parse("");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_invalid_xml_fails() {
        let result = rng_parse("not valid xml <<<");
        assert!(result.is_err());
    }

    // ── Validation Tests ──────────────────────────────────────────────────

    /// Validates a document against a schema with a single `element` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_simple_element() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>Hello</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null(), "Failed to parse document");

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Validation failed: {:?}", ctxt.errors);
    }

    /// Verifies validation fails when the root element name does not match.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_element_mismatch() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="expected" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<actual>Content</actual>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(!valid, "Validation should have failed");
        assert!(ctxt.nb_errors > 0);
    }

    /// Validates a document whose element carries a declared attribute.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_with_attribute() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <attribute name="id">
    <text/>
  </attribute>
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root id="x1">Content</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Validation failed: {:?}", ctxt.errors);
    }

    /// Verifies validation fails when a required attribute is absent.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_missing_attribute() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <attribute name="required">
    <text/>
  </attribute>
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>Content</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(
            !valid,
            "Validation should have failed for missing attribute"
        );
    }

    /// Validates a document matching one branch of a `choice` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_with_choice() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <choice>
      <element name="a">
        <text/>
      </element>
      <element name="b">
        <text/>
      </element>
    </choice>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<a>First choice</a>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Choice validation failed: {:?}", ctxt.errors);
    }

    /// Verifies validation fails when no `choice` branch matches.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_choice_no_match() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <choice>
      <element name="a">
        <text/>
      </element>
      <element name="b">
        <text/>
      </element>
    </choice>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<c>Neither choice</c>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(
            !valid,
            "Validation should have failed for no matching choice"
        );
    }

    /// Validates a grammar that uses a named `ref` to a `define`.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_grammar_with_ref() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <define name="para">
    <element name="p">
      <text/>
    </element>
  </define>
  <start>
    <element name="doc">
      <zeroOrMore>
        <ref name="para"/>
      </zeroOrMore>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<doc><p>First</p><p>Second</p></doc>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Ref validation failed: {:?}", ctxt.errors);
    }

    /// Validates repeated children under a `zeroOrMore` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_zero_or_more() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <zeroOrMore>
    <element name="item">
      <text/>
    </element>
  </zeroOrMore>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><item>A</item><item>B</item></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "zeroOrMore validation failed: {:?}", ctxt.errors);
    }

    /// Verifies a `zeroOrMore` pattern accepts zero repetitions.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_zero_or_more_empty() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <zeroOrMore>
    <element name="item">
      <text/>
    </element>
  </zeroOrMore>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Empty zeroOrMore should be valid");
    }

    /// Validates a document with one occurrence under `oneOrMore`.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_one_or_more() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <oneOrMore>
    <element name="item">
      <text/>
    </element>
  </oneOrMore>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><item>Single</item></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "oneOrMore validation failed: {:?}", ctxt.errors);
    }

    /// Validates an `optional` element that is present.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_optional_present() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <optional>
    <element name="opt">
      <text/>
    </element>
  </optional>
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><opt>present</opt>text</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(
            valid,
            "Optional present validation failed: {:?}",
            ctxt.errors
        );
    }

    /// Validates an `optional` element that is absent.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_optional_absent() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <optional>
    <element name="opt">
      <text/>
    </element>
  </optional>
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>text only</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(
            valid,
            "Optional absent validation failed: {:?}",
            ctxt.errors
        );
    }

    /// Validates children in the declared `sequence` order.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_sequence() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <sequence>
        <element name="first">
          <text/>
        </element>
        <element name="second">
          <text/>
        </element>
      </sequence>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><first>First</first><second>Second</second></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Sequence validation failed: {:?}", ctxt.errors);
    }

    /// Validates a `data` pattern with an integer type.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_data_pattern() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="age" xmlns="http://relaxng.org/ns/structure/1.0">
  <data type="integer"/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<age>25</age>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Data pattern validation failed: {:?}", ctxt.errors);
    }

    /// Verifies a non-integer value fails a `data` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_data_pattern_invalid() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="age" xmlns="http://relaxng.org/ns/structure/1.0">
  <data type="integer"/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<age>not-a-number</age>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(!valid, "Validation should have failed for invalid integer");
    }

    /// Validates a `value` pattern with an exact match.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_value_pattern() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="status" xmlns="http://relaxng.org/ns/structure/1.0">
  <value>active</value>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<status>active</status>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Value pattern validation failed: {:?}", ctxt.errors);
    }

    /// Verifies a `value` pattern mismatch fails validation.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_value_pattern_mismatch() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="status" xmlns="http://relaxng.org/ns/structure/1.0">
  <value>active</value>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<status>inactive</status>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(!valid, "Validation should have failed for value mismatch");
    }

    /// Verifies a `notAllowed` pattern always fails validation.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_not_allowed() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <notAllowed/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>should not be allowed</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(!valid, "notAllowed should cause validation failure");
    }

    /// Validates children in any order under an `interleave` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_interleave() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <interleave>
        <element name="a">
          <text/>
        </element>
        <element name="b">
          <text/>
        </element>
      </interleave>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><a>A</a><b>B</b></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Interleave validation failed: {:?}", ctxt.errors);
    }

    /// Validates an empty element against an `empty` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_empty_element() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="br" xmlns="http://relaxng.org/ns/structure/1.0">
  <empty/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<br/>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Empty element validation failed: {:?}", ctxt.errors);
    }

    // ── Datatype Validation Tests ──────────────────────────────────────────

    #[test]
    fn test_validate_datatype_string() {
        assert!(rng_validate_datatype_value(Some("string"), "hello"));
        assert!(rng_validate_datatype_value(Some("string"), ""));
    }

    #[test]
    fn test_validate_datatype_boolean() {
        assert!(rng_validate_datatype_value(Some("boolean"), "true"));
        assert!(rng_validate_datatype_value(Some("boolean"), "false"));
        assert!(rng_validate_datatype_value(Some("boolean"), "1"));
        assert!(rng_validate_datatype_value(Some("boolean"), "0"));
        assert!(!rng_validate_datatype_value(Some("boolean"), "yes"));
        assert!(!rng_validate_datatype_value(Some("boolean"), "no"));
    }

    #[test]
    fn test_validate_datatype_integer() {
        assert!(rng_validate_datatype_value(Some("integer"), "42"));
        assert!(rng_validate_datatype_value(Some("integer"), "-42"));
        assert!(rng_validate_datatype_value(Some("integer"), "+42"));
        assert!(!rng_validate_datatype_value(Some("integer"), "12.5"));
        assert!(!rng_validate_datatype_value(Some("integer"), "abc"));
        assert!(!rng_validate_datatype_value(Some("integer"), ""));
    }

    #[test]
    fn test_validate_datatype_decimal() {
        assert!(rng_validate_datatype_value(Some("decimal"), "42"));
        assert!(rng_validate_datatype_value(Some("decimal"), "12.5"));
        assert!(rng_validate_datatype_value(Some("decimal"), "-3.14"));
        assert!(!rng_validate_datatype_value(Some("decimal"), ""));
    }

    #[test]
    fn test_validate_datatype_float() {
        assert!(rng_validate_datatype_value(Some("float"), "3.14"));
        assert!(rng_validate_datatype_value(Some("float"), "INF"));
        assert!(rng_validate_datatype_value(Some("float"), "-INF"));
        assert!(rng_validate_datatype_value(Some("float"), "NaN"));
        assert!(!rng_validate_datatype_value(Some("float"), ""));
    }

    #[test]
    fn test_validate_datatype_ncname() {
        assert!(rng_validate_datatype_value(Some("NCName"), "myElement"));
        assert!(rng_validate_datatype_value(Some("NCName"), "_foo"));
        assert!(!rng_validate_datatype_value(Some("NCName"), "123abc"));
        assert!(!rng_validate_datatype_value(Some("NCName"), ""));
    }

    #[test]
    fn test_validate_datatype_any_uri() {
        assert!(rng_validate_datatype_value(
            Some("anyURI"),
            "http://example.com"
        ));
        assert!(rng_validate_datatype_value(Some("anyURI"), "urn:isbn:1234"));
        assert!(!rng_validate_datatype_value(Some("anyURI"), ""));
        assert!(!rng_validate_datatype_value(Some("anyURI"), "has space"));
    }

    #[test]
    fn test_validate_datatype_qname() {
        assert!(rng_validate_datatype_value(Some("QName"), "ns:local"));
        assert!(rng_validate_datatype_value(Some("QName"), "local"));
        assert!(!rng_validate_datatype_value(Some("QName"), ""));
    }

    // ── C ABI Tests ───────────────────────────────────────────────────────

    /// Exercises the C ABI schema parse round trip: `xmlRelaxNGNewMemParserCtxt`,
    /// `xmlRelaxNGParse` and `xmlRelaxNGFree`.
    ///
    /// # Safety
    ///
    /// - The static `schema_xml` string stays valid for the
    ///   `xmlRelaxNGNewMemParserCtxt` call; the parser context and the schema
    ///   returned by `xmlRelaxNGParse` are asserted non-NULL before use, and
    ///   the schema is freed exactly once with `xmlRelaxNGFree`.
    #[test]
    fn test_c_abi_new_parse_free() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let ctxt = unsafe {
            xmlRelaxNGNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        assert!(!ctxt.is_null(), "Parser context should not be null");

        let schema = unsafe { xmlRelaxNGParse(ctxt) };
        assert!(!schema.is_null(), "Schema should not be null");

        // Free the schema
        unsafe { xmlRelaxNGFree(schema) };
    }

    /// Exercises the C ABI document validation path.
    ///
    /// # Safety
    ///
    /// - The static schema and document strings stay valid for their
    ///   `xmlRelaxNGNewMemParserCtxt` and `xmlReadMemory` calls; the parser
    ///   context, schema, validation context and document pointers are
    ///   asserted non-NULL before use, and the document, validation context
    ///   and schema are each freed exactly once.
    #[test]
    fn test_c_abi_validate_doc() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>Hello</root>"#;

        let ctxt = unsafe {
            xmlRelaxNGNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        let schema = unsafe { xmlRelaxNGParse(ctxt) };
        assert!(!schema.is_null());

        let valid_ctxt = unsafe { xmlRelaxNGNewValidCtxt(schema) };
        assert!(!valid_ctxt.is_null());

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let result = unsafe { xmlRelaxNGValidateDoc(valid_ctxt, doc) };
        assert_eq!(result, 0, "Validation should succeed");

        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };
        unsafe { xmlRelaxNGFreeValidCtxt(valid_ctxt) };
        unsafe { xmlRelaxNGFree(schema) };
    }

    /// Exercises the C ABI full-element validation path.
    ///
    /// # Safety
    ///
    /// - The static schema and document strings stay valid for their
    ///   `xmlRelaxNGNewMemParserCtxt` and `xmlReadMemory` calls; the parser
    ///   context, schema, validation context and document pointers are
    ///   asserted non-NULL before use.
    /// - The document tree walked through `children` and `next` links must be
    ///   well-formed and NULL-terminated; the located `item` node is asserted
    ///   non-NULL before being passed to `xmlRelaxNGValidateFullElement`.
    /// - The document, validation context and schema are each freed exactly
    ///   once.
    #[test]
    fn test_c_abi_validate_full_element() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="item" xmlns="http://relaxng.org/ns/structure/1.0">
  <text/>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><item>Content</item></root>"#;

        let ctxt = unsafe {
            xmlRelaxNGNewMemParserCtxt(
                schema_xml.as_ptr() as *const c_char,
                schema_xml.len() as c_int,
            )
        };
        let schema = unsafe { xmlRelaxNGParse(ctxt) };
        assert!(!schema.is_null());

        let valid_ctxt = unsafe { xmlRelaxNGNewValidCtxt(schema) };
        assert!(!valid_ctxt.is_null());

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        // Find the <item> element
        let item = unsafe {
            // Start from the first child of the document (root element)
            let mut node = (*doc).children;
            while !node.is_null() {
                if (*node).type_ == XML_ELEMENT_NODE as c_int {
                    break;
                }
                node = (*node).next;
            }
            if !node.is_null() {
                // Now find <item> child of root
                node = (*node).children;
                while !node.is_null() {
                    if (*node).type_ == XML_ELEMENT_NODE as c_int {
                        break;
                    }
                    node = (*node).next;
                }
            }
            node
        };
        assert!(!item.is_null(), "Should find <item> element");

        let result = unsafe { xmlRelaxNGValidateFullElement(valid_ctxt, doc, item) };
        assert_eq!(result, 0, "Element validation should succeed");

        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };
        unsafe { xmlRelaxNGFreeValidCtxt(valid_ctxt) };
        unsafe { xmlRelaxNGFree(schema) };
    }

    /// Verifies the C ABI accepts NULL pointers and NULL frees.
    ///
    /// # Safety
    ///
    /// - NULL pointers are passed only to C ABI entry points that accept NULL
    ///   inputs, and the free functions must tolerate NULL without
    ///   dereferencing.
    #[test]
    fn test_c_abi_null_handling() {
        // Test null pointer handling
        assert_eq!(
            unsafe { xmlRelaxNGValidateDoc(ptr::null_mut(), ptr::null_mut()) },
            -1
        );
        assert_eq!(
            unsafe {
                xmlRelaxNGValidateFullElement(ptr::null_mut(), ptr::null_mut(), ptr::null_mut())
            },
            -1
        );
        assert!(unsafe { xmlRelaxNGNewMemParserCtxt(ptr::null(), 0).is_null() });

        // Free with null should not crash
        unsafe { xmlRelaxNGFree(ptr::null_mut()) };
        unsafe { xmlRelaxNGFreeParserCtxt(ptr::null_mut()) };
        unsafe { xmlRelaxNGFreeValidCtxt(ptr::null_mut()) };
    }

    // ── Edge Case Tests ───────────────────────────────────────────────────

    #[test]
    fn test_parse_with_div() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <div>
    <define name="shared">
      <text/>
    </define>
  </div>
  <start>
    <element name="root">
      <ref name="shared"/>
    </element>
  </start>
</grammar>"#;

        let result = rng_parse(schema_xml);
        assert!(
            result.is_ok(),
            "Failed to parse with div: {:?}",
            result.err()
        );
        let schema = result.unwrap();
        assert_eq!(schema.grammar.defines.len(), 1);
        assert_eq!(schema.grammar.defines[0].name, "shared");
    }

    /// Validates a `list` pattern with space-separated tokens.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_list_pattern() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="tokens" xmlns="http://relaxng.org/ns/structure/1.0">
  <list>
    <data type="token"/>
  </list>
</element>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<tokens>abc def ghi</tokens>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "List pattern validation failed: {:?}", ctxt.errors);
    }

    /// Validates children in order under a `group` pattern.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_group_pattern() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <group>
        <element name="a">
          <text/>
        </element>
        <element name="b">
          <text/>
        </element>
      </group>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><a>First</a><b>Second</b></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(valid, "Group validation failed: {:?}", ctxt.errors);
    }

    /// Verifies validation fails when a `ref` names an undefined define.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_undefined_ref() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <ref name="undefined"/>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root>Content</root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        assert!(!valid, "Undefined ref should cause failure");
    }

    /// Verifies `rng_validate_doc` rejects a NULL document pointer.
    ///
    /// # Safety
    ///
    /// - `rng_validate_doc` is called with a NULL document pointer, which it
    ///   must reject without dereferencing.
    #[test]
    fn test_validate_null_doc() {
        let schema = RelaxNgSchema::new();
        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, ptr::null_mut(), &mut ctxt) };
        assert!(!valid);
    }

    #[test]
    fn test_parse_external_ref_schema() {
        let schema_xml = r#"<?xml version="1.0"?>
<element name="root" xmlns="http://relaxng.org/ns/structure/1.0">
  <externalRef href="external.rng"/>
</element>"#;

        let result = rng_parse(schema_xml);
        assert!(
            result.is_ok(),
            "Failed to parse externalRef: {:?}",
            result.err()
        );
        let schema = result.unwrap();
        if let Some(ref start) = schema.grammar.start {
            assert_eq!(start.pattern_type, RelaxNgPatternType::Element);
            assert_eq!(start.name.as_deref(), Some("root"));
        }
    }

    #[test]
    fn test_validate_boolean_datatype() {
        assert!(rng_validate_datatype_value(Some("boolean"), "true"));
        assert!(rng_validate_datatype_value(Some("boolean"), "false"));
        assert!(!rng_validate_datatype_value(Some("boolean"), "maybe"));
    }

    #[test]
    fn test_validate_unknown_datatype() {
        // Unknown datatypes should be accepted (lenient behavior)
        assert!(rng_validate_datatype_value(Some("custom-type"), "anything"));
    }

    #[test]
    fn test_validate_no_datatype() {
        // No datatype specified — accept anything
        assert!(rng_validate_datatype_value(None, "anything"));
    }

    #[test]
    fn test_parse_schema_with_ns_prefix() {
        let schema_xml = r#"<?xml version="1.0"?>
<rng:element name="root" xmlns:rng="http://relaxng.org/ns/structure/1.0">
  <rng:text/>
</rng:element>"#;

        let result = rng_parse(schema_xml);
        assert!(result.is_ok(), "Failed with ns prefix: {:?}", result.err());
    }

    #[test]
    fn test_validation_context_path() {
        let mut ctxt = RelaxNgValidCtxt::new();
        assert_eq!(ctxt.current_path(), "/");

        ctxt.path.push("root".to_string());
        assert_eq!(ctxt.current_path(), "/root");

        ctxt.path.push("child".to_string());
        assert_eq!(ctxt.current_path(), "/root/child");

        ctxt.path.pop();
        assert_eq!(ctxt.current_path(), "/root");
    }

    /// Verifies a `sequence` pattern rejects children in the wrong order.
    ///
    /// # Safety
    ///
    /// - The static `doc_xml` string is passed to `xmlReadMemory`, which reads
    ///   exactly `doc_xml.len()` bytes and returns an owned `_xmlDoc` or NULL;
    ///   the pointer is asserted non-NULL before `rng_validate_doc`
    ///   dereferences it and is freed exactly once with `xmlFreeDoc`.
    #[test]
    fn test_validate_sequence_wrong_order() {
        let schema_xml = r#"<?xml version="1.0"?>
<grammar xmlns="http://relaxng.org/ns/structure/1.0">
  <start>
    <element name="root">
      <sequence>
        <element name="first">
          <text/>
        </element>
        <element name="second">
          <text/>
        </element>
      </sequence>
    </element>
  </start>
</grammar>"#;

        let doc_xml = r#"<?xml version="1.0"?>
<root><second>Wrong</second><first>Order</first></root>"#;

        let schema = rng_parse(schema_xml).expect("Failed to parse schema");

        let doc = unsafe {
            crate::abi::exports_xml2::xmlReadMemory(
                doc_xml.as_ptr() as *const c_char,
                doc_xml.len() as c_int,
                c"test.xml".as_ptr() as *const c_char,
                ptr::null(),
                0,
            )
        };
        assert!(!doc.is_null());

        let mut ctxt = RelaxNgValidCtxt::new();
        let valid = unsafe { rng_validate_doc(&schema, doc, &mut ctxt) };
        unsafe { crate::abi::exports_xml2::xmlFreeDoc(doc) };

        // The sequence validates patterns against children in order,
        // so wrong order should fail
        assert!(!valid, "Wrong sequence order should fail");
    }
}