libxml-rs 0.1.0-alpha.20

Native-Rust forensic reimplementation of libxml2+libxslt with C ABI drop-in replacement. Cross-version oracle matrix (libxml2 2.7.8-2.15.3, libxslt 1.1.26-1.1.45) with semantic epochs correlated to upstream commits; full xmllint/xmlcatalog/xsltproc CLIs; differential-court-verified C API closure (xmlXPath*, xmlTextReader*, xmlTextWriter*, catalogs, serialization, data globals, chvalid, encoding, the full libxslt surface) — parity ledger at 0 missing for both libxml2 and libxslt. 1135 tests passing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
//! XSLT pattern matching (§33, §85 Phase 8).
//!
//! XSLT patterns are a subset of XPath 1.0 used in `match` attributes of
//! `<xsl:template>`, `<xsl:key>`, `<xsl:strip-space>`, `<xsl:preserve-space>`.
//!
//! Patterns can include:
//! - Location paths (relative and absolute)
//! - Union patterns (pattern1 | pattern2)
//! - Node tests: *, node(), text(), comment(), processing-instruction()
//! - Attribute axis (@attr)
//! - Namespace prefix tests (ns:*, ns:name)
//! - Predicates (limited)
//! - The id() and key() functions
//!
//! # UPSTREAM-PARITY
//!
//! Implements XSLT 1.0 §5 "Patterns" with match semantics matching libxslt 1.1.39.
//! Pattern matching uses the XPath 1.0 AST from `src/xml/xpath` for parsing, then
//! applies XSLT-specific matching rules.
//!
//! # Courts
//!
//! XSLT-PATTERNS-*

use crate::abi::structs::*;
use crate::abi::types::*;
use crate::xml::string::xmlstr_to_string;
use crate::xml::xpath::ast::{Axis, Expr, NameTest, NodeTest, Step};
use crate::xml::xpath::parser::parse_xpath;
use crate::xml::xpath::types::{NodeSet, XPathValue};
use std::os::raw::c_int;
use std::ptr;

/// Sentinel for "no explicit priority" (upstream XSLT_PAT_NO_PRIORITY).
pub const XSLT_PAT_NO_PRIORITY: f64 = -1.0e9;

// ═══════════════════════════════════════════════════════════════════════════════
// Internal Pattern Representation
// ═══════════════════════════════════════════════════════════════════════════════

/// A compiled pattern step — a single axis::node-test[predicates] in a pattern.
///
/// This is the internal representation backing `_xsltPatternStep`.
/// The C ABI type `_xsltPatternStep` is a zero-sized opaque marker;
/// the real data lives here.
#[derive(Debug, Clone)]
pub(crate) struct XsltPatternStep {
    /// The axis (defaults to Child for element tests, Attribute for @attr).
    pub axis: Axis,
    /// The node test.
    pub node_test: NodeTest,
    /// Compiled predicate expressions.
    pub predicates: Vec<Expr>,
}

/// A single pattern within a union pattern (one side of `|`).
#[derive(Debug, Clone)]
pub(crate) struct XsltPattern {
    /// Steps in this pattern, in reverse order for efficient matching.
    /// For a pattern like `foo/bar/baz`, steps are [baz, bar, foo].
    /// For a pattern like `foo//bar`, steps contain a DescendantOrSelf sentinel.
    pub steps: Vec<PatternStepEntry>,
    /// Whether this pattern is absolute (starts with `/`).
    pub is_absolute: bool,
    /// The original pattern string for this branch.
    pub original: String,
    /// The parsed XPath expression (kept for predicate evaluation).
    pub expr: Expr,
}

/// One entry in the step chain of a compiled pattern.
#[derive(Debug, Clone)]
pub(crate) enum PatternStepEntry {
    /// A normal step with axis, node test, and predicates.
    Step(XsltPatternStep),
    /// A `//` separator — matches descendant-or-self::node().
    DescendantOrSelf,
}

/// Full compiled pattern (union of multiple sub-patterns).
#[derive(Debug, Clone)]
pub(crate) struct CompiledPattern {
    /// The branches of a union pattern (`pattern1 | pattern2`).
    pub patterns: Vec<XsltPattern>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// C ABI Opaque Types
// ═══════════════════════════════════════════════════════════════════════════════

/// Opaque pattern structure.
///
/// In the C ABI this is a `typedef struct _xsltPattern xsltPattern`.
/// The actual data is stored in the internal `CompiledPattern` and accessed
/// via pointer casts in the implementation functions.
#[repr(C)]
pub struct _xsltPattern {
    _unused: [u8; 0],
}

/// Opaque pattern step structure.
#[repr(C)]
pub struct _xsltPatternStep {
    _unused: [u8; 0],
}

// ═══════════════════════════════════════════════════════════════════════════════
// Pattern Compilation
// ═══════════════════════════════════════════════════════════════════════════════

/// Compile an XSLT pattern string into a compiled pattern.
///
/// Parses the pattern string using the XPath 1.0 parser, then decomposes
/// it into an internal representation suitable for fast node matching.
///
/// # Parameters
///
/// * `pattern` — The pattern string (UTF-8, null-terminated `xmlChar*`).
/// * `doc`     — The document (used for namespace resolution; may be null).
///
/// # Returns
///
/// A pointer to a compiled `_xsltPattern`, or null on failure.
///
/// # Safety
///
/// `pattern` must be a valid null-terminated `xmlChar*` or null.
/// `doc` must be a valid `_xmlDoc*` or null.
pub unsafe fn xsltCompilePattern(pattern: *const xmlChar, _doc: *mut _xmlDoc) -> *mut _xsltPattern {
    if pattern.is_null() {
        return ptr::null_mut();
    }

    let pattern_str = xmlstr_to_string(pattern);
    if pattern_str.is_empty() {
        return ptr::null_mut();
    }

    let compiled = match compile_pattern_string(&pattern_str) {
        Some(cp) => cp,
        None => return ptr::null_mut(),
    };

    // Allocate and store the compiled pattern
    let layout = std::alloc::Layout::new::<CompiledPattern>();
    let ptr = std::alloc::alloc(layout) as *mut CompiledPattern;
    if ptr.is_null() {
        return ptr::null_mut();
    }
    ptr::write(ptr, compiled);
    ptr as *mut _xsltPattern
}

/// Internal: compile a pattern string into a `CompiledPattern`.
fn compile_pattern_string(pattern_str: &str) -> Option<CompiledPattern> {
    // Parse the pattern as an XPath expression
    let expr = parse_xpath(pattern_str).ok()?;

    // Decompose the expression into pattern branches
    let patterns = decompose_pattern(&expr, pattern_str)?;

    Some(CompiledPattern { patterns })
}

/// Decompose an XPath expression into a list of pattern branches.
///
/// A union pattern `a | b` becomes two branches. Each branch is converted
/// into a sequence of steps for matching.
fn decompose_pattern(expr: &Expr, original: &str) -> Option<Vec<XsltPattern>> {
    match expr {
        // Union: pattern1 | pattern2 — recurse on both sides
        Expr::Union(left, right) => {
            let mut patterns = decompose_pattern(left, original)?;
            let right_patterns = decompose_pattern(right, original)?;
            patterns.extend(right_patterns);
            Some(patterns)
        }
        // Single expression — convert to a pattern
        _ => {
            let pattern = expr_to_pattern(expr, original)?;
            Some(vec![pattern])
        }
    }
}

/// Convert a single (non-union) XPath expression into a `XsltPattern`.
fn expr_to_pattern(expr: &Expr, original: &str) -> Option<XsltPattern> {
    let (steps, is_absolute) = collect_steps(expr)?;

    Some(XsltPattern {
        steps,
        is_absolute,
        original: original.to_string(),
        expr: expr.clone(),
    })
}

/// Collect the steps from an XPath expression in reverse order.
///
/// Returns `(steps, is_absolute)` where steps are ordered from innermost
/// (node being matched) to outermost (root), making matching efficient.
fn collect_steps(expr: &Expr) -> Option<(Vec<PatternStepEntry>, bool)> {
    match expr {
        // "/" — a bare Self_/node() step represents the document root
        // node pattern. It matches only the document node itself.
        Expr::Step(step)
            if step.axis == Axis::Self_
                && step.node_test == NodeTest::Node
                && step.predicates.is_empty() =>
        {
            Some((vec![], true))
        }
        Expr::Step(step) => {
            let entry = PatternStepEntry::Step(XsltPatternStep {
                axis: step.axis,
                node_test: step.node_test.clone(),
                predicates: step.predicates.clone(),
            });
            Some((vec![entry], false))
        }
        Expr::AbsolutePath(inner) => {
            let (steps, _) = collect_steps(inner)?;
            Some((steps, true))
        }
        Expr::RelativePath(left, right) => {
            // Steps are collected right-to-left: the rightmost step is the
            // node being tested, left steps are ancestry constraints.
            let (mut right_steps, _) = collect_steps(right)?;
            let (left_steps, left_absolute) = collect_steps(left)?;
            right_steps.extend(left_steps);
            Some((right_steps, left_absolute))
        }
        // Handle `//` — the parser represents it as RelativePath with
        // a DescendantOrSelf step in the middle
        Expr::Filter(_expr, _predicates) => {
            // Filter expressions like `id('foo')/bar` — we match the filter
            // as a step
            // For now, treat as a single step with a wildcard node test
            let entry = PatternStepEntry::Step(XsltPatternStep {
                axis: Axis::Self_,
                node_test: NodeTest::Node,
                predicates: vec![],
            });
            Some((vec![entry], false))
        }
        // Bare node-test function calls: node(), text(), comment(),
        // processing-instruction(). In XPath 1.0 these are NOT functions;
        // they are node tests forming a step on the child axis. The XPath
        // parser represents top-level `node()` as a FunctionCall, so we
        // translate it back into a step here.
        Expr::FunctionCall { name, args } => {
            let node_test = match (name.as_str(), args.len()) {
                ("node", 0) => Some(NodeTest::Node),
                ("text", 0) => Some(NodeTest::Text),
                ("comment", 0) => Some(NodeTest::Comment),
                ("processing-instruction", 0) => Some(NodeTest::ProcessingInstruction(None)),
                ("processing-instruction", 1) => match &args[0] {
                    Expr::StringLiteral(s) => {
                        Some(NodeTest::ProcessingInstruction(Some(s.clone())))
                    }
                    _ => None,
                },
                _ => None,
            };
            match node_test {
                Some(nt) => {
                    let entry = PatternStepEntry::Step(XsltPatternStep {
                        axis: Axis::Child,
                        node_test: nt,
                        predicates: vec![],
                    });
                    Some((vec![entry], false))
                }
                // id() and key() are handled as filter-like patterns.
                None if name == "id" || name == "key" => {
                    let entry = PatternStepEntry::Step(XsltPatternStep {
                        axis: Axis::Self_,
                        node_test: NodeTest::Node,
                        predicates: vec![],
                    });
                    Some((vec![entry], false))
                }
                None => None,
            }
        }
        _ => {
            // Literals, function calls without path — not valid as patterns
            // unless they're id() or key() which are handled specially
            None
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Pattern Deallocation
// ═══════════════════════════════════════════════════════════════════════════════

/// Free a compiled pattern.
///
/// # Safety
///
/// `pattern` must have been returned by `xsltCompilePattern` and not already freed.
pub unsafe fn xsltFreePattern(pattern: *mut _xsltPattern) {
    if pattern.is_null() {
        return;
    }
    let ptr = pattern as *mut CompiledPattern;
    // Drop the compiled pattern
    ptr::drop_in_place(ptr);
    let layout = std::alloc::Layout::new::<CompiledPattern>();
    std::alloc::dealloc(ptr as *mut u8, layout);
}

// ═══════════════════════════════════════════════════════════════════════════════
// Pattern Matching
// ═══════════════════════════════════════════════════════════════════════════════

/// Test whether a node matches a compiled pattern.
///
/// # Parameters
///
/// * `ctxt`    — The transform context (provides XPath context for predicates).
/// * `pattern` — The compiled pattern.
/// * `node`    — The node to test.
///
/// # Returns
///
/// 1 if the node matches, 0 otherwise.
///
/// # Safety
///
/// All pointers must be valid (or null — null pointers return 0).
pub unsafe fn xsltTestPattern(
    ctxt: *mut _xsltTransformContext,
    pattern: *mut _xsltPattern,
    node: *mut _xmlNode,
) -> c_int {
    if pattern.is_null() || node.is_null() {
        return 0;
    }

    let compiled = &*(pattern as *const CompiledPattern);
    let xpath_ctxt = if !ctxt.is_null() {
        (*ctxt).xpathCtxt
    } else {
        ptr::null_mut()
    };

    for sub_pattern in &compiled.patterns {
        if match_sub_pattern(sub_pattern, node, xpath_ctxt) {
            return 1;
        }
    }

    0
}

/// Test whether a node matches a compiled pattern tree.
///
/// In libxslt, the `match` attribute is compiled into a tree of `_xmlNode`
/// elements during stylesheet compilation. This function walks that tree
/// to determine whether `node` matches the pattern.
///
/// The pattern tree structure uses element nodes where:
/// - The node `name` encodes the step type (element name, "*", "node()", etc.)
/// - Children represent path steps (inner to outer)
/// - Siblings at the root level represent union alternatives
///
/// # Parameters
///
/// * `node`         — The document node to test.
/// * `pattern_node` — The compiled pattern tree root (from `_xsltTemplate.r#match`).
///
/// # Returns
///
/// `true` if the node matches, `false` otherwise.
///
/// # Safety
///
/// Both pointers must be valid (or null — null pointers return false).
pub unsafe fn xsltTestMatchPattern(node: *mut _xmlNode, pattern_node: *mut _xmlNode) -> bool {
    if node.is_null() || pattern_node.is_null() {
        return false;
    }

    // Walk the pattern tree. The pattern tree has the following structure:
    // - Root node: represents the outermost step (or union)
    // - For union patterns: the root has sibling children
    // - For path patterns: children represent nested steps
    //
    // The node's `name` encodes what kind of test this step performs:
    // - A QName: match element with that name
    // - "*": match any element
    // - "node()": match any node
    // - "text()": match text nodes
    // - "comment()": match comment nodes
    // - "processing-instruction()": match PI nodes
    // - "@name": match attribute
    // - "ns:*": match namespace wildcard
    // - "|": union operator
    // - "/": path separator

    match_pattern_tree(pattern_node, node)
}

/// Walk the pattern tree and test if the node matches.
unsafe fn match_pattern_tree(pattern_node: *mut _xmlNode, node: *mut _xmlNode) -> bool {
    if pattern_node.is_null() || node.is_null() {
        return false;
    }

    let node_ref = &*pattern_node;
    let name = xmlstr_to_string(node_ref.name);

    match name.as_str() {
        // Union: any child matches
        "|" => {
            let mut child = node_ref.children;
            while !child.is_null() {
                if match_pattern_tree(child, node) {
                    return true;
                }
                child = (*child).next;
            }
            false
        }
        // Path separator: match child step, then parent step
        "/" => {
            // For a path like foo/bar:
            // The root node is "/" with children [bar, foo] (inner first)
            // We match the first child against node, then the second against node's parent
            let steps = collect_children(pattern_node);
            if steps.is_empty() {
                return false;
            }
            match_pattern_path(&steps, node)
        }
        _ => {
            // Leaf node: check if this step matches the node
            match_pattern_step(pattern_node, node)
        }
    }
}

/// Collect all children of a pattern node into a vector.
unsafe fn collect_children(pattern_node: *mut _xmlNode) -> Vec<*mut _xmlNode> {
    let mut children = Vec::new();
    if pattern_node.is_null() {
        return children;
    }
    let mut child = (*pattern_node).children;
    while !child.is_null() {
        children.push(child);
        child = (*child).next;
    }
    children
}

/// Match a path (sequence of pattern steps) against a node.
///
/// Steps are ordered inner-first (the last step is the outermost).
unsafe fn match_pattern_path(steps: &[*mut _xmlNode], node: *mut _xmlNode) -> bool {
    if steps.is_empty() {
        return false;
    }

    let mut current = node;

    for (i, &step) in steps.iter().enumerate() {
        if current.is_null() {
            return false;
        }

        if !match_pattern_step(step, current) {
            return false;
        }

        // Move to parent for the next step (if any)
        if i < steps.len() - 1 {
            current = (*current).parent;
        }
    }

    true
}

/// Match a single pattern step node against a document node.
unsafe fn match_pattern_step(pattern_node: *mut _xmlNode, node: *mut _xmlNode) -> bool {
    if pattern_node.is_null() || node.is_null() {
        return false;
    }

    let pn = &*pattern_node;
    let nn = &*node;
    let step_name = xmlstr_to_string(pn.name);
    let node_name = xmlstr_to_string(nn.name);
    let node_type = nn.type_;

    match step_name.as_str() {
        // Wildcard: match any element (or attribute if pattern is attribute-type)
        "*" => {
            if pn.type_ == 2 {
                // Attribute wildcard
                node_type == 2
            } else {
                // Element wildcard
                node_type == 1
            }
        }
        // node() — match any node type
        "node()" => true,
        // text() — match text nodes
        "text()" => node_type == 3 || node_type == 4,
        // comment() — match comment nodes
        "comment()" => node_type == 8,
        // processing-instruction() — match PI nodes
        "processing-instruction()" => node_type == 7,
        // Attribute test (@attr) — the step name starts with "@"
        s if s.starts_with('@') => {
            let attr_name = &s[1..];
            node_type == 2 && node_name == attr_name
        }
        // Namespace wildcard (prefix:*)
        s if s.ends_with(":*") => {
            if node_type != 1 {
                return false;
            }
            let prefix = &s[..s.len() - 2];
            if let Some(ns) = nn.ns.as_ref() {
                let ns_prefix = xmlstr_to_string(ns.prefix);
                ns_prefix == prefix
            } else {
                prefix.is_empty()
            }
        }
        // Namespace-qualified name (ns:local)
        s if s.contains(':') && !s.starts_with('@') && !s.ends_with(":*") => {
            if node_type != 1 {
                return false;
            }
            let parts: Vec<&str> = s.splitn(2, ':').collect();
            if parts.len() != 2 {
                return false;
            }
            let prefix = parts[0];
            let local = parts[1];
            if node_name != local {
                return false;
            }
            if let Some(ns) = nn.ns.as_ref() {
                let ns_prefix = xmlstr_to_string(ns.prefix);
                ns_prefix == prefix
            } else {
                prefix.is_empty()
            }
        }
        // Simple name test: match element/attribute by name
        _ => {
            if node_type == 1 || node_type == 2 {
                node_name == step_name
            } else {
                false
            }
        }
    }
}

/// Check if a node matches a single (non-union) sub-pattern.
unsafe fn match_sub_pattern(
    pattern: &XsltPattern,
    node: *mut _xmlNode,
    xpath_ctxt: *mut _xmlXPathContext,
) -> bool {
    // The steps are stored in reverse order (innermost first).
    // Walk them from the node upward through the tree.
    if pattern.steps.is_empty() {
        // Empty steps with is_absolute means the pattern is "/", which
        // matches only the document root node.
        return pattern.is_absolute && is_document_node(node);
    }

    // Start with the first step (the one closest to the matched node)
    let mut current_node = node;

    for (i, entry) in pattern.steps.iter().enumerate() {
        match entry {
            PatternStepEntry::Step(step) => {
                if !match_step(step, current_node, xpath_ctxt, i == 0) {
                    return false;
                }
                // For the first step, we stay on the current node (Self_ axis)
                // or traverse to children/parent depending on the axis.
                // For subsequent steps, we need to move upward.
                if i > 0 {
                    // Move to parent for the next step
                    current_node = (*current_node).parent;
                    if current_node.is_null() {
                        return false;
                    }
                }
            }
            PatternStepEntry::DescendantOrSelf => {
                // `//` matches descendant-or-self::node()
                // This means any ancestor path is valid.
                // Since steps are in reverse order, this separates
                // the inner steps (already matched) from outer steps.
                // We need to find an ancestor that matches the remaining steps.
                let remaining: Vec<_> = pattern.steps[i + 1..]
                    .iter()
                    .filter_map(|e| {
                        if let PatternStepEntry::Step(s) = e {
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();

                if remaining.is_empty() {
                    return true;
                }

                // Try each ancestor
                let mut ancestor = current_node;
                loop {
                    ancestor = (*ancestor).parent;
                    if ancestor.is_null() {
                        return false;
                    }
                    if match_steps_sequence(&remaining, ancestor, xpath_ctxt) {
                        return true;
                    }
                }
            }
        }
    }

    // If the pattern is absolute, the final ancestor must be the document root
    if pattern.is_absolute {
        // After walking up all steps, current_node should be the document node
        if current_node.is_null() {
            return true;
        }
        // Walk up to root
        let mut n = node;
        loop {
            let parent = (*n).parent;
            if parent.is_null() {
                break;
            }
            n = parent;
        }
        // n is now the root — check if it's the document node
        return (*n).type_ == 9 || (*n).type_ == 13; // XML_DOCUMENT_NODE or XML_HTML_DOCUMENT_NODE
    }

    true
}

/// Match a sequence of steps against a node, starting from the innermost step.
unsafe fn match_steps_sequence(
    steps: &[XsltPatternStep],
    node: *mut _xmlNode,
    xpath_ctxt: *mut _xmlXPathContext,
) -> bool {
    let mut current = node;
    for (i, step) in steps.iter().enumerate() {
        if !match_step(step, current, xpath_ctxt, i == 0) {
            return false;
        }
        if i < steps.len() - 1 {
            current = (*current).parent;
            if current.is_null() {
                return false;
            }
        }
    }
    true
}

/// Check if a node is a document node (XML_DOCUMENT_NODE or XML_HTML_DOCUMENT_NODE).
unsafe fn is_document_node(node: *mut _xmlNode) -> bool {
    if node.is_null() {
        return false;
    }
    (*node).type_ == 9 || (*node).type_ == 13
}

/// Check if a single step matches a node.
///
/// A step `axis::node-test[predicates]` matches if:
/// 1. The axis relationship holds between the context and the node.
/// 2. The node test matches the node.
/// 3. All predicates evaluate to true.
unsafe fn match_step(
    step: &XsltPatternStep,
    node: *mut _xmlNode,
    xpath_ctxt: *mut _xmlXPathContext,
    _is_first: bool,
) -> bool {
    if node.is_null() {
        return false;
    }

    let node_ref = &*node;
    let node_type = node_ref.type_;

    // Step 1: Check the axis
    match step.axis {
        Axis::Attribute => {
            // Must be an attribute node
            if node_type != 2 {
                // XML_ATTRIBUTE_NODE
                return false;
            }
        }
        Axis::Child | Axis::Self_ => {
            // Child and Self axes match elements, text, comments, PIs
            // (all non-document, non-attribute, non-namespace nodes)
            if node_type == 2 || node_type == 9 || node_type == 13 {
                // Skip attributes and document nodes for child:: tests
                if step.axis == Axis::Child
                    && node_type != 1
                    && node_type != 3
                    && node_type != 4
                    && node_type != 7
                    && node_type != 8
                {
                    return false;
                }
            }
        }
        _ => {
            // Other axes are not typically used in patterns
            // For completeness, accept the node
        }
    }

    // Step 2: Check the node test
    if !match_node_test(node, &step.node_test) {
        return false;
    }

    // Step 3: Evaluate predicates (if any)
    if !step.predicates.is_empty() {
        if xpath_ctxt.is_null() {
            // Without an XPath context, we can't evaluate predicates
            // For now, skip predicates (libxslt would also need a context)
            return true;
        }

        if !evaluate_predicates(node, &step.predicates, xpath_ctxt) {
            return false;
        }
    }

    true
}

/// Check if a node matches a node test.
unsafe fn match_node_test(node: *mut _xmlNode, node_test: &NodeTest) -> bool {
    if node.is_null() {
        return false;
    }

    let node_ref = &*node;
    let node_type = node_ref.type_;

    match node_test {
        NodeTest::Node => {
            // Matches any node
            true
        }
        NodeTest::Text => {
            // text() — text nodes (type 3) or CDATA sections (type 4)
            node_type == 3 || node_type == 4
        }
        NodeTest::Comment => {
            // comment() — comment nodes (type 8)
            node_type == 8
        }
        NodeTest::ProcessingInstruction(target) => {
            // processing-instruction() or processing-instruction("target")
            if node_type != 7 {
                // XML_PI_NODE
                return false;
            }
            if let Some(target) = target {
                let name = xmlstr_to_string(node_ref.name);
                name == *target
            } else {
                true
            }
        }
        NodeTest::NameTest(name_test) => match_name_test(node, name_test),
        NodeTest::Wildcard => {
            // * — matches any element node
            node_type == 1
        }
        NodeTest::NsWildcard(prefix) => {
            // prefix:* — matches any element in that namespace
            if node_type != 1 {
                return false;
            }
            if let Some(ns) = node_ref.ns.as_ref() {
                let ns_prefix = xmlstr_to_string(ns.prefix);
                ns_prefix == *prefix
            } else {
                prefix.is_empty()
            }
        }
    }
}

/// Check if a node matches a name test.
unsafe fn match_name_test(node: *mut _xmlNode, name_test: &NameTest) -> bool {
    if node.is_null() {
        return false;
    }

    let node_ref = &*node;

    match name_test {
        NameTest::Any => {
            // * — matches any element or attribute
            node_ref.type_ == 1 || node_ref.type_ == 2
        }
        NameTest::LocalName(local) => {
            let name = xmlstr_to_string(node_ref.name);
            name == *local
        }
        NameTest::QName { prefix, local } => {
            let name = xmlstr_to_string(node_ref.name);
            if name != *local {
                return false;
            }
            // Check namespace prefix
            if let Some(ns) = node_ref.ns.as_ref() {
                let ns_prefix = xmlstr_to_string(ns.prefix);
                ns_prefix == *prefix
            } else {
                prefix.is_empty()
            }
        }
    }
}

/// Evaluate predicates for a node match.
///
/// Uses the XPath evaluation engine to check if all predicates hold.
unsafe fn evaluate_predicates(
    node: *mut _xmlNode,
    predicates: &[Expr],
    xpath_ctxt: *mut _xmlXPathContext,
) -> bool {
    if xpath_ctxt.is_null() {
        return true; // Can't evaluate, assume match
    }

    // Set up a temporary XPath context for predicate evaluation
    let ctxt = &mut *xpath_ctxt;

    // Save context state
    let saved_node = ctxt.node;

    // Set the current node as context
    ctxt.node = node;

    let mut result = true;

    for predicate in predicates {
        // Evaluate the predicate expression
        // Get the document from the context or the node
        let doc = if !ctxt.doc.is_null() {
            ctxt.doc
        } else if !node.is_null() {
            (*node).doc
        } else {
            ptr::null_mut()
        };
        let mut xpath_ctx = crate::xml::xpath::context::XPathContext::new(doc);

        // Copy relevant state from the C ABI context
        if !saved_node.is_null() {
            xpath_ctx.set_context_node(saved_node);
        }

        // Copy namespace mappings
        if !ctxt.namespaces.is_null() && ctxt.nsNr > 0 {
            let ns_slice = std::slice::from_raw_parts(ctxt.namespaces, ctxt.nsNr as usize);
            for ns_ptr in ns_slice {
                if !ns_ptr.is_null() {
                    let ns = &**ns_ptr;
                    let prefix = xmlstr_to_string(ns.prefix);
                    let href = xmlstr_to_string(ns.href);
                    xpath_ctx.register_namespace(&prefix, &href);
                }
            }
        }

        // Register the id() and key() extension functions
        register_pattern_functions(&mut xpath_ctx);

        let pred_result = crate::xml::xpath::eval::eval(&mut xpath_ctx, predicate);

        match pred_result {
            Ok(val) => {
                // Predicate semantics: number n matches if n == context position,
                // otherwise boolean conversion
                let matches = match val {
                    XPathValue::Number(n) => {
                        // Number predicate: match if n == 1 (first node)
                        // For pattern predicates, position is always 1
                        (n - 1.0).abs() < f64::EPSILON
                    }
                    _ => val.as_boolean(),
                };
                if !matches {
                    result = false;
                    break;
                }
            }
            Err(_) => {
                result = false;
                break;
            }
        }
    }

    // Restore context
    ctxt.node = saved_node;

    result
}

/// Register XSLT-specific functions needed for pattern evaluation (id(), key()).
fn register_pattern_functions(ctx: &mut crate::xml::xpath::context::XPathContext) {
    // Register id() function
    ctx.register_function("id", |_ctx, _args| {
        // Simple id() implementation: returns empty node-set for now
        // A full implementation would look up IDs in the document's DTD
        Ok(XPathValue::NodeSet(NodeSet::new()))
    });

    // Register key() function
    ctx.register_function("key", |_ctx, _args| {
        // Simple key() implementation: returns empty node-set for now
        // A full implementation would look up keys in the stylesheet's key tables
        Ok(XPathValue::NodeSet(NodeSet::new()))
    });
}

// ═══════════════════════════════════════════════════════════════════════════════
// Default Priority Computation
// ═══════════════════════════════════════════════════════════════════════════════

/// Compute default priority for a match pattern.
///
/// XSLT 1.0 §5.5:
/// - 0.0 for simple name tests (child::para, para)
/// - -0.25 for node() test
/// - -0.5 for any name test (*) or namespace test (ns:*)
/// - +0.5 for attribute axis (@attr)
/// - +0.0 for other cases (compound patterns, id(), key())
///
/// # Parameters
///
/// * `pattern` — The pattern string (UTF-8, null-terminated `xmlChar*`).
///
/// # Returns
///
/// The default priority as a f64.
///
/// # Safety
///
/// `pattern` must be a valid null-terminated `xmlChar*` or null.
pub unsafe fn xsltDefaultPriority(pattern: *const xmlChar) -> f64 {
    if pattern.is_null() {
        return 0.5;
    }

    let pattern_str = xmlstr_to_string(pattern);
    if pattern_str.is_empty() {
        return 0.5;
    }

    compute_default_priority(&pattern_str)
}

/// Internal: compute default priority from a pattern string.
fn compute_default_priority(pattern_str: &str) -> f64 {
    // Parse the pattern
    let expr = match parse_xpath(pattern_str) {
        Ok(e) => e,
        Err(_) => return 0.5, // Default for unparseable patterns
    };

    compute_expr_priority(&expr)
}

/// Compute the default priority of an expression.
fn compute_expr_priority(expr: &Expr) -> f64 {
    match expr {
        // Union patterns: use the highest priority of any branch
        Expr::Union(left, right) => {
            let left_p = compute_expr_priority(left);
            let right_p = compute_expr_priority(right);
            left_p.max(right_p)
        }

        // Absolute path: analyze the inner expression
        Expr::AbsolutePath(inner) => compute_expr_priority(inner),

        // Relative path: priority is based on the final step (rightmost)
        Expr::RelativePath(_, right) => compute_expr_priority(right),

        // Single step: determine priority from the node test and axis
        Expr::Step(step) => compute_step_priority(step),

        // Filter expression: priority based on the primary expression
        Expr::Filter(primary, _) => compute_expr_priority(primary),

        // id() and key() functions: priority 0.0
        Expr::FunctionCall { name, .. } => {
            if name == "id" || name == "key" {
                0.0
            } else {
                // Bare node tests (node(), text(), comment(),
                // processing-instruction()) parse as function calls at the
                // top level; translate them to their step priorities.
                match name.as_str() {
                    "node" => -0.25,
                    "text" | "comment" | "processing-instruction" => 0.0,
                    _ => 0.5,
                }
            }
        }

        // Other expressions (literals, variables, etc.) — not typical patterns
        _ => 0.5,
    }
}

/// Compute the default priority of a single step.
fn compute_step_priority(step: &Step) -> f64 {
    match &step.node_test {
        // node() test: -0.25
        NodeTest::Node => -0.25,

        // text(), comment(), processing-instruction(): 0.0
        NodeTest::Text | NodeTest::Comment | NodeTest::ProcessingInstruction(_) => 0.0,

        // Name test: 0.0 for a specific name on the child axis;
        // 0.5 on the attribute axis (@QName per XSLT 1.0 §5.5).
        NodeTest::NameTest(name_test) => match name_test {
            NameTest::LocalName(_) | NameTest::QName { .. } => {
                if step.axis == Axis::Attribute {
                    0.5
                } else {
                    0.0
                }
            }
            NameTest::Any => {
                // * in element context: -0.5
                // * in attribute context: +0.5
                if step.axis == Axis::Attribute {
                    0.5
                } else {
                    -0.5
                }
            }
        },

        // * (Wildcard): -0.5 in element context, +0.5 in attribute context
        NodeTest::Wildcard => {
            if step.axis == Axis::Attribute {
                0.5
            } else {
                -0.5
            }
        }

        // prefix:* namespace wildcard: -0.5
        NodeTest::NsWildcard(_) => {
            if step.axis == Axis::Attribute {
                0.5
            } else {
                -0.5
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Convenience Functions
// ═══════════════════════════════════════════════════════════════════════════════

/// Check if a pattern string matches a single step (simple name test).
///
/// Returns true if the pattern is a simple name test like `para` or `foo:bar`,
/// without path separators, predicates, or union operators.
pub fn is_simple_name_pattern(pattern: &str) -> bool {
    let expr = match parse_xpath(pattern) {
        Ok(e) => e,
        Err(_) => return false,
    };

    matches!(&expr, Expr::Step(Step {
        axis: Axis::Child,
        node_test: NodeTest::NameTest(name_test),
        predicates,
    }) if predicates.is_empty() && !matches!(name_test, NameTest::Any))
}

/// Check if a pattern is a union pattern (contains `|`).
pub fn is_union_pattern(pattern: &str) -> bool {
    let expr = match parse_xpath(pattern) {
        Ok(e) => e,
        Err(_) => return false,
    };

    matches!(&expr, Expr::Union(_, _))
}

/// Get the names matched by a simple name-test pattern.
///
/// For a simple pattern like `para` or `foo | bar`, returns the list of
/// matched element names. Returns an empty vec for complex patterns.
pub fn get_pattern_matched_names(pattern: &str) -> Vec<String> {
    let expr = match parse_xpath(pattern) {
        Ok(e) => e,
        Err(_) => return vec![],
    };

    let mut names = Vec::new();
    collect_matched_names(&expr, &mut names);
    names
}

fn collect_matched_names(expr: &Expr, names: &mut Vec<String>) {
    match expr {
        Expr::Union(left, right) => {
            collect_matched_names(left, names);
            collect_matched_names(right, names);
        }
        Expr::Step(Step {
            node_test: NodeTest::NameTest(name_test),
            ..
        }) => match name_test {
            NameTest::LocalName(local) => names.push(local.clone()),
            NameTest::QName { prefix, local } => names.push(format!("{}:{}", prefix, local)),
            NameTest::Any => names.push("*".to_string()),
        },
        Expr::Step(Step {
            node_test: NodeTest::Wildcard,
            ..
        }) => {
            names.push("*".to_string());
        }
        Expr::Step(Step {
            node_test: NodeTest::NsWildcard(prefix),
            ..
        }) => {
            names.push(format!("{}:*", prefix));
        }
        _ => {}
    }
}

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

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

    // ── Priority Tests ────────────────────────────────────────────────────

    #[test]
    fn test_default_priority_name_test() {
        // Simple name test "para" → 0.0
        let priority = compute_default_priority("para");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for name test, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_qname() {
        // Qualified name "xslt:template" → 0.0
        let priority = compute_default_priority("xslt:template");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for QName, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_node_test() {
        // node() test → -0.25
        let priority = compute_default_priority("node()");
        assert!(
            (priority - (-0.25)).abs() < f64::EPSILON,
            "Expected -0.25 for node(), got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_text_test() {
        // text() test → 0.0
        let priority = compute_default_priority("text()");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for text(), got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_comment_test() {
        // comment() test → 0.0
        let priority = compute_default_priority("comment()");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for comment(), got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_processing_instruction() {
        // processing-instruction() test → 0.0
        let priority = compute_default_priority("processing-instruction()");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for processing-instruction(), got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_wildcard() {
        // * wildcard → -0.5
        let priority = compute_default_priority("*");
        assert!(
            (priority - (-0.5)).abs() < f64::EPSILON,
            "Expected -0.5 for *, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_ns_wildcard() {
        // ns:* wildcard → -0.5
        let priority = compute_default_priority("ns:*");
        assert!(
            (priority - (-0.5)).abs() < f64::EPSILON,
            "Expected -0.5 for ns:*, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_attribute() {
        // @attr → +0.5
        let priority = compute_default_priority("@attr");
        assert!(
            (priority - 0.5).abs() < f64::EPSILON,
            "Expected 0.5 for @attr, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_attribute_wildcard() {
        // @* → +0.5
        let priority = compute_default_priority("@*");
        assert!(
            (priority - 0.5).abs() < f64::EPSILON,
            "Expected 0.5 for @*, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_union() {
        // Union "para | *" → max(0.0, -0.5) = 0.0
        let priority = compute_default_priority("para | *");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for union, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_compound_path() {
        // Path "foo/bar" → priority of last step "bar" = 0.0
        let priority = compute_default_priority("foo/bar");
        assert!(
            (priority - 0.0).abs() < f64::EPSILON,
            "Expected 0.0 for foo/bar, got {}",
            priority
        );
    }

    #[test]
    fn test_default_priority_empty() {
        // Empty pattern → 0.5
        let priority = compute_default_priority("");
        assert!(
            (priority - 0.5).abs() < f64::EPSILON,
            "Expected 0.5 for empty pattern, got {}",
            priority
        );
    }

    // ── Pattern Matching Tests ────────────────────────────────────────────

    /// Create a minimal element node for testing.
    unsafe fn create_test_node(name: &str, type_: c_int) -> *mut _xmlNode {
        let layout = std::alloc::Layout::new::<_xmlNode>();
        let ptr = std::alloc::alloc_zeroed(layout) as *mut _xmlNode;
        if ptr.is_null() {
            return ptr::null_mut();
        }
        let node = &mut *ptr;
        node.type_ = type_;
        // Allocate and copy the name
        let name_bytes = name.as_bytes();
        let name_buf = std::alloc::alloc_zeroed(
            std::alloc::Layout::array::<u8>(name_bytes.len() + 1).unwrap(),
        );
        if !name_buf.is_null() {
            std::ptr::copy_nonoverlapping(name_bytes.as_ptr(), name_buf, name_bytes.len());
        }
        node.name = name_buf as *mut xmlChar;
        ptr
    }

    /// Free a test node.
    unsafe fn free_test_node(node: *mut _xmlNode) {
        if node.is_null() {
            return;
        }
        if !(*node).name.is_null() {
            let name = (*node).name;
            // Find length
            let len = crate::abi::exports_xml2::xmlStrlen(name) as usize;
            std::alloc::dealloc(
                name as *mut u8,
                std::alloc::Layout::array::<u8>(len + 1).unwrap(),
            );
        }
        let layout = std::alloc::Layout::new::<_xmlNode>();
        std::alloc::dealloc(node as *mut u8, layout);
    }

    #[test]
    fn test_node_test_matching_element() {
        unsafe {
            let node = create_test_node("para", 1); // XML_ELEMENT_NODE
            assert!(!node.is_null());

            // Name test
            let name_test = NodeTest::NameTest(NameTest::LocalName("para".to_string()));
            assert!(match_node_test(node, &name_test));

            // Wrong name
            let wrong_test = NodeTest::NameTest(NameTest::LocalName("foo".to_string()));
            assert!(!match_node_test(node, &wrong_test));

            // Wildcard
            let wildcard = NodeTest::Wildcard;
            assert!(match_node_test(node, &wildcard));

            // Node test
            let node_test = NodeTest::Node;
            assert!(match_node_test(node, &node_test));

            // Text test should not match element
            let text_test = NodeTest::Text;
            assert!(!match_node_test(node, &text_test));

            free_test_node(node);
        }
    }

    #[test]
    fn test_node_test_matching_text() {
        unsafe {
            let node = create_test_node("", 3); // XML_TEXT_NODE
            assert!(!node.is_null());

            let text_test = NodeTest::Text;
            assert!(match_node_test(node, &text_test));

            let node_test = NodeTest::Node;
            assert!(match_node_test(node, &node_test));

            let comment_test = NodeTest::Comment;
            assert!(!match_node_test(node, &comment_test));

            let element_test = NodeTest::NameTest(NameTest::LocalName("para".to_string()));
            assert!(!match_node_test(node, &element_test));

            free_test_node(node);
        }
    }

    #[test]
    fn test_compile_and_free_pattern() {
        unsafe {
            let pattern_str = "para\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_null_pattern() {
        unsafe {
            let compiled = xsltCompilePattern(ptr::null(), ptr::null_mut());
            assert!(compiled.is_null());
        }
    }

    #[test]
    fn test_compile_empty_pattern() {
        unsafe {
            let pattern_str = "\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(compiled.is_null());
        }
    }

    #[test]
    fn test_free_null_pattern() {
        unsafe {
            xsltFreePattern(ptr::null_mut());
            // Should not crash
        }
    }

    #[test]
    fn test_is_simple_name_pattern() {
        assert!(is_simple_name_pattern("para"));
        assert!(is_simple_name_pattern("foo:bar"));
        assert!(!is_simple_name_pattern("foo/bar"));
        assert!(!is_simple_name_pattern("para | foo"));
        assert!(!is_simple_name_pattern("*"));
    }

    #[test]
    fn test_is_union_pattern() {
        assert!(is_union_pattern("para | foo"));
        assert!(is_union_pattern("para | foo | bar"));
        assert!(!is_union_pattern("para"));
        assert!(!is_union_pattern("foo/bar"));
    }

    #[test]
    fn test_get_pattern_matched_names() {
        let names = get_pattern_matched_names("para");
        assert_eq!(names, vec!["para"]);

        let names = get_pattern_matched_names("foo | bar");
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"foo".to_string()));
        assert!(names.contains(&"bar".to_string()));

        let names = get_pattern_matched_names("foo/bar");
        assert!(names.is_empty());
    }

    #[test]
    fn test_compile_union_pattern() {
        unsafe {
            let pattern_str = "para | foo\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_compound_pattern() {
        unsafe {
            let pattern_str = "foo/bar\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_absolute_pattern() {
        unsafe {
            let pattern_str = "/foo/bar\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_attribute_pattern() {
        unsafe {
            let pattern_str = "@attr\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_wildcard_pattern() {
        unsafe {
            let pattern_str = "*\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_ns_wildcard_pattern() {
        unsafe {
            let pattern_str = "ns:*\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_node_test_pattern() {
        unsafe {
            let pattern_str = "node()\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_text_pattern() {
        unsafe {
            let pattern_str = "text()\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_comment_pattern() {
        unsafe {
            let pattern_str = "comment()\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_pi_pattern() {
        unsafe {
            let pattern_str = "processing-instruction()\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_compile_predicate_pattern() {
        unsafe {
            let pattern_str = "para[1]\0".as_ptr() as *const xmlChar;
            let compiled = xsltCompilePattern(pattern_str, ptr::null_mut());
            assert!(!compiled.is_null());
            xsltFreePattern(compiled);
        }
    }

    #[test]
    fn test_decompose_union() {
        let expr = parse_xpath("a | b").unwrap();
        let patterns = decompose_pattern(&expr, "a | b");
        assert!(patterns.is_some());
        let patterns = patterns.unwrap();
        assert_eq!(patterns.len(), 2);
        assert_eq!(patterns[0].original, "a | b");
        assert_eq!(patterns[1].original, "a | b");
    }

    #[test]
    fn test_decompose_single() {
        let expr = parse_xpath("para").unwrap();
        let patterns = decompose_pattern(&expr, "para");
        assert!(patterns.is_some());
        let patterns = patterns.unwrap();
        assert_eq!(patterns.len(), 1);
    }

    #[test]
    fn test_collect_steps_simple() {
        let expr = parse_xpath("para").unwrap();
        let (steps, is_absolute) = collect_steps(&expr).unwrap();
        assert!(!is_absolute);
        assert_eq!(steps.len(), 1);
        if let PatternStepEntry::Step(step) = &steps[0] {
            assert_eq!(step.axis, Axis::Child);
            assert!(
                matches!(&step.node_test, NodeTest::NameTest(NameTest::LocalName(n)) if n == "para")
            );
        } else {
            panic!("Expected Step entry");
        }
    }

    #[test]
    fn test_collect_steps_absolute() {
        let expr = parse_xpath("/foo/bar").unwrap();
        let (steps, is_absolute) = collect_steps(&expr).unwrap();
        assert!(is_absolute);
        assert_eq!(steps.len(), 2);
    }

    #[test]
    fn test_collect_steps_attribute() {
        let expr = parse_xpath("@attr").unwrap();
        let (steps, is_absolute) = collect_steps(&expr).unwrap();
        assert!(!is_absolute);
        assert_eq!(steps.len(), 1);
        if let PatternStepEntry::Step(step) = &steps[0] {
            assert_eq!(step.axis, Axis::Attribute);
        } else {
            panic!("Expected Step entry");
        }
    }

    #[test]
    fn test_collect_steps_compound() {
        let expr = parse_xpath("foo/bar").unwrap();
        let (steps, is_absolute) = collect_steps(&expr).unwrap();
        assert!(!is_absolute);
        assert_eq!(steps.len(), 2);
        // First step should be "bar" (rightmost)
        if let PatternStepEntry::Step(step) = &steps[0] {
            assert!(
                matches!(&step.node_test, NodeTest::NameTest(NameTest::LocalName(n)) if n == "bar")
            );
        } else {
            panic!("Expected Step entry for bar");
        }
        // Second step should be "foo"
        if let PatternStepEntry::Step(step) = &steps[1] {
            assert!(
                matches!(&step.node_test, NodeTest::NameTest(NameTest::LocalName(n)) if n == "foo")
            );
        } else {
            panic!("Expected Step entry for foo");
        }
    }

    #[test]
    fn test_match_name_test_local() {
        unsafe {
            let node = create_test_node("para", 1);
            assert!(!node.is_null());

            assert!(match_name_test(
                node,
                &NameTest::LocalName("para".to_string())
            ));
            assert!(!match_name_test(
                node,
                &NameTest::LocalName("foo".to_string())
            ));
            assert!(match_name_test(node, &NameTest::Any));

            free_test_node(node);
        }
    }

    #[test]
    fn test_match_node_test_wildcard() {
        unsafe {
            let element = create_test_node("para", 1);
            let text = create_test_node("", 3);
            let comment = create_test_node("", 8);

            let wildcard = NodeTest::Wildcard;
            assert!(match_node_test(element, &wildcard));
            assert!(!match_node_test(text, &wildcard));
            assert!(!match_node_test(comment, &wildcard));

            free_test_node(element);
            free_test_node(text);
            free_test_node(comment);
        }
    }

    #[test]
    fn test_match_node_test_ns_wildcard() {
        unsafe {
            let node = create_test_node("para", 1);
            // No namespace set — only empty prefix matches
            let ns_wildcard = NodeTest::NsWildcard("".to_string());
            assert!(match_node_test(node, &ns_wildcard));

            let ns_wildcard = NodeTest::NsWildcard("foo".to_string());
            assert!(!match_node_test(node, &ns_wildcard));

            free_test_node(node);
        }
    }

    #[test]
    fn test_compute_priority_on_compiled_pattern() {
        unsafe {
            // Test through the C ABI function
            let pattern_str = "para\0".as_ptr() as *const xmlChar;
            let priority = xsltDefaultPriority(pattern_str);
            assert!(
                (priority - 0.0).abs() < f64::EPSILON,
                "Expected 0.0 for 'para', got {}",
                priority
            );

            let pattern_str = "*\0".as_ptr() as *const xmlChar;
            let priority = xsltDefaultPriority(pattern_str);
            assert!(
                (priority - (-0.5)).abs() < f64::EPSILON,
                "Expected -0.5 for '*', got {}",
                priority
            );

            let pattern_str = "node()\0".as_ptr() as *const xmlChar;
            let priority = xsltDefaultPriority(pattern_str);
            assert!(
                (priority - (-0.25)).abs() < f64::EPSILON,
                "Expected -0.25 for 'node()', got {}",
                priority
            );

            let pattern_str = "@attr\0".as_ptr() as *const xmlChar;
            let priority = xsltDefaultPriority(pattern_str);
            assert!(
                (priority - 0.5).abs() < f64::EPSILON,
                "Expected 0.5 for '@attr', got {}",
                priority
            );
        }
    }

    #[test]
    fn test_compute_priority_null() {
        unsafe {
            let priority = xsltDefaultPriority(ptr::null());
            assert!(
                (priority - 0.5).abs() < f64::EPSILON,
                "Expected 0.5 for null pattern, got {}",
                priority
            );
        }
    }

    #[test]
    fn test_compute_priority_empty() {
        unsafe {
            let pattern_str = "\0".as_ptr() as *const xmlChar;
            let priority = xsltDefaultPriority(pattern_str);
            assert!(
                (priority - 0.5).abs() < f64::EPSILON,
                "Expected 0.5 for empty pattern, got {}",
                priority
            );
        }
    }

    #[test]
    fn test_xslt_test_pattern_null_args() {
        unsafe {
            let result = xsltTestPattern(ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
            assert_eq!(result, 0);
        }
    }
}