xsd-schema 0.1.0

XML Schema (XSD 1.0/1.1) validator with PSVI and a built-in XPath 2.0 engine
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
//! XSD constraining facets
//!
//! This module implements the XSD facet system for constraining simple types.
//! Facets can restrict length, numeric range, pattern matching, enumeration, and whitespace.
//!
//! ## XSD Facet Categories
//!
//! - **Length facets**: length, minLength, maxLength (for string, binary, list types)
//! - **Numeric precision facets**: totalDigits, fractionDigits (for decimal types)
//! - **Bound facets**: minInclusive, maxInclusive, minExclusive, maxExclusive
//! - **String facets**: pattern, enumeration, whitespace
//! - **XSD 1.1 facets**: explicitTimezone, assertion
//!
//! ## Facet Inheritance
//!
//! When deriving a simple type by restriction:
//! - Derived facets must be more restrictive than base facets
//! - Fixed facets cannot be overridden with different values
//! - Patterns are cumulative (ANDed together)
//! - Enumerations must be subsets of base enumerations

use crate::error::{FacetError, FacetResult};
use crate::namespace::context::NamespaceContextSnapshot;
use crate::parser::location::SourceRef;
use crate::regex_convert::lenient_ms_preprocess;
#[cfg(feature = "xsd11")]
use crate::regex_convert::rewrite_xsd10_category_escapes;
use crate::regex_convert::validate_xml_pattern_syntax;
#[cfg(not(feature = "xsd11"))]
use crate::regex_convert::{convert_xml_pattern, ConvertOptions};
use crate::schema::model::{RegexCompat, XsdVersion};
#[cfg(not(feature = "xsd11"))]
use regex::Regex;
use std::collections::HashSet;

#[cfg(feature = "xsd11")]
use std::sync::Arc;

use super::XmlTypeCode;

/// Fixed vs default facet values
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FacetFixed {
    /// Value can be further restricted
    #[default]
    Default,
    /// Value cannot be changed by derived types
    Fixed,
}

/// Whitespace handling mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WhitespaceMode {
    /// Preserve all whitespace
    Preserve,
    /// Replace tabs/newlines with spaces
    Replace,
    /// Collapse consecutive whitespace to single space, trim
    #[default]
    Collapse,
}

/// Length facet (exact length constraint)
#[derive(Debug, Clone)]
pub struct LengthFacet {
    pub value: u64,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MinLength facet
#[derive(Debug, Clone)]
pub struct MinLengthFacet {
    pub value: u64,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MaxLength facet
#[derive(Debug, Clone)]
pub struct MaxLengthFacet {
    pub value: u64,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// Pattern facet (regex constraint)
#[derive(Debug, Clone)]
pub struct PatternFacet {
    /// The pattern string (XSD regex syntax)
    pub value: String,
    /// Compiled regex for efficient matching
    #[cfg(not(feature = "xsd11"))]
    compiled: Option<Regex>,
    #[cfg(feature = "xsd11")]
    compiled: Option<Arc<regexml::Regex>>,
    pub source: Option<SourceRef>,
}

impl PatternFacet {
    /// Create a new pattern facet from an XSD pattern string.
    ///
    /// The pattern is validated and compiled using the appropriate backend
    /// (XSD 1.0: `regex` via `convert_xml_pattern`; XSD 1.1: `regexml` after
    /// a `\p{X}` rewrite if `xsd_version == V1_0`). Returns an error if the
    /// pattern is invalid.
    ///
    /// `xsd_version` controls the `\p{X}` category escape semantics: under
    /// `V1_0` recognized general-category names are expanded to Unicode 3.0
    /// ranges; `V1_1` passes them through to the backend unchanged.
    ///
    /// `regex_compat` controls grammar leniency: `Strict` enforces XSD
    /// Part 2 §F/§G; `LenientMs` first applies [`lenient_ms_preprocess`]
    /// to drop start/end anchors and `(?#…)` comments common in
    /// .NET-authored schemas.
    pub fn new(
        value: String,
        source: Option<SourceRef>,
        xsd_version: XsdVersion,
        regex_compat: RegexCompat,
    ) -> FacetResult<Self> {
        let mut facet = Self::new_unchecked(value, source);
        facet.compile(xsd_version, regex_compat)?;
        Ok(facet)
    }

    /// Create a pattern facet without compiling (for deferred compilation)
    pub fn new_unchecked(value: String, source: Option<SourceRef>) -> Self {
        Self {
            value,
            compiled: None,
            source,
        }
    }

    /// Compile the pattern if not already compiled
    #[cfg(not(feature = "xsd11"))]
    pub fn compile(
        &mut self,
        xsd_version: XsdVersion,
        regex_compat: RegexCompat,
    ) -> FacetResult<()> {
        if self.compiled.is_none() {
            let effective: std::borrow::Cow<'_, str> = match regex_compat {
                RegexCompat::Strict => std::borrow::Cow::Borrowed(self.value.as_str()),
                RegexCompat::LenientMs => lenient_ms_preprocess(&self.value),
            };
            // The XSD 1.0 hyphen-rule check is part of the strict §F grammar
            // gate; skip it under LenientMs so the engine alone decides.
            if xsd_version == XsdVersion::V1_0 && regex_compat == RegexCompat::Strict {
                validate_xml_pattern_syntax(&effective).map_err(|message| {
                    FacetError::InvalidPattern {
                        pattern: self.value.clone(),
                        message,
                    }
                })?;
            }
            let opts = match xsd_version {
                XsdVersion::V1_0 => ConvertOptions::xsd_v1_0(),
                XsdVersion::V1_1 => ConvertOptions::xsd(),
            };
            let rust_pattern = convert_xml_pattern(&effective, opts);
            let compiled = Regex::new(&rust_pattern).map_err(|e| FacetError::InvalidPattern {
                pattern: self.value.clone(),
                message: e.to_string(),
            })?;
            self.compiled = Some(compiled);
        }
        Ok(())
    }

    /// Compile the pattern if not already compiled
    #[cfg(feature = "xsd11")]
    pub fn compile(
        &mut self,
        xsd_version: XsdVersion,
        regex_compat: RegexCompat,
    ) -> FacetResult<()> {
        if self.compiled.is_none() {
            let strict = regex_compat == RegexCompat::Strict;
            // Apply MS dialect preprocess (closed list) before grammar
            // validation when LenientMs is on. Owned to keep one stable
            // backing string across the two-step validate+rewrite below.
            let effective: String = if strict {
                self.value.clone()
            } else {
                lenient_ms_preprocess(&self.value).into_owned()
            };
            // Strict XSD 1.0 hyphen-rule grammar gate. Skipped under
            // LenientMs so the engine alone decides what is well-formed.
            if xsd_version == XsdVersion::V1_0 && strict {
                validate_xml_pattern_syntax(&effective).map_err(|message| {
                    FacetError::InvalidPattern {
                        pattern: self.value.clone(),
                        message,
                    }
                })?;
            }
            // Strict XSD §F/§G grammar gate via regexml `xsd()`. Skipped
            // under LenientMs — the runtime matcher uses regexml `xpath()`
            // (next step), which natively accepts XPath-only constructs
            // like `^`/`$` outside char class, backrefs `\1`, non-capturing
            // `(?:...)`, and reluctant quantifiers `*?` that are valid
            // .NET regex idioms. For XSD 1.1, an unrecognized `\p{IsX}`
            // block name is treated as matching every character (W3C bug
            // 13670 / XSD 1.1 Datatypes §G.4.2.3); the rewrite remains in
            // place under both modes because it is a spec rule, not a
            // grammar choice (regexml 0.2 does not yet honour
            // `allow_unknown_block_names`).
            let xsd_validated: std::borrow::Cow<'_, str> = match xsd_version {
                XsdVersion::V1_0 => {
                    if strict {
                        regexml::Regex::xsd(&effective, "").map_err(|e| {
                            FacetError::InvalidPattern {
                                pattern: self.value.clone(),
                                message: format!("{:?}", e),
                            }
                        })?;
                    }
                    std::borrow::Cow::Borrowed(effective.as_str())
                }
                XsdVersion::V1_1 => validate_xsd11_pattern_with_block_fallback(&effective)?,
            };
            // Under XSD 1.0 the \p{X} rewrite produces a new String; under 1.1
            // we use the (possibly block-rewritten) validated value.
            let pinned: std::borrow::Cow<'_, str> = match xsd_version {
                XsdVersion::V1_0 => {
                    std::borrow::Cow::Owned(rewrite_xsd10_category_escapes(&effective))
                }
                XsdVersion::V1_1 => xsd_validated,
            };
            // Compile with explicit anchoring for full-string matching
            let anchored = format!("^(?:{})$", pinned);
            let compiled =
                regexml::Regex::xpath(&anchored, "").map_err(|e| FacetError::InvalidPattern {
                    pattern: self.value.clone(),
                    message: format!("{:?}", e),
                })?;
            self.compiled = Some(Arc::new(compiled));
        }
        Ok(())
    }

    /// Test if a value matches this pattern
    #[cfg(not(feature = "xsd11"))]
    pub fn matches(&self, value: &str) -> bool {
        match &self.compiled {
            Some(regex) => regex.is_match(value),
            None => {
                // Defensive fallback: compile on-the-fly using XSD 1.1 defaults.
                // Reached only if a facet was never compiled via `compile_patterns`.
                if let Ok(rust_pattern) = std::panic::catch_unwind(|| {
                    convert_xml_pattern(&self.value, ConvertOptions::xsd())
                }) {
                    if let Ok(regex) = Regex::new(&rust_pattern) {
                        return regex.is_match(value);
                    }
                }
                false
            }
        }
    }

    /// Test if a value matches this pattern
    #[cfg(feature = "xsd11")]
    pub fn matches(&self, value: &str) -> bool {
        match &self.compiled {
            Some(regex) => regex.is_match(value),
            None => {
                // Defensive fallback: validate and compile on-the-fly with XSD 1.1
                // defaults. Reached only if a facet was never compiled via
                // `compile_patterns`.
                if let Ok(rewritten) = validate_xsd11_pattern_with_block_fallback(&self.value) {
                    let anchored = format!("^(?:{})$", rewritten);
                    if let Ok(regex) = regexml::Regex::xpath(&anchored, "") {
                        return regex.is_match(value);
                    }
                }
                false
            }
        }
    }
}

/// Validate an XSD 1.1 pattern with regexml's strict XSD parser, rewriting any
/// unknown `\p{IsX}` / `\P{IsX}` block names to a match-everything expression
/// per W3C bug 13670 / XSD 1.1 Datatypes §G.4.2.3 (unrecognized block names are
/// allowed and match every character). Returns the (possibly rewritten) pattern
/// or a `FacetError` if a non-block-name error remains after up to 16 rewrites.
#[cfg(feature = "xsd11")]
fn validate_xsd11_pattern_with_block_fallback(
    value: &str,
) -> FacetResult<std::borrow::Cow<'_, str>> {
    let mut current: std::borrow::Cow<'_, str> = std::borrow::Cow::Borrowed(value);
    for _ in 0..16 {
        let err = match regexml::Regex::xsd(&current, "") {
            Ok(_) => return Ok(current),
            Err(e) => format!("{:?}", e),
        };
        const PREFIX: &str = "Unknown Unicode block: ";
        let Some(start) = err.find(PREFIX) else {
            return Err(FacetError::InvalidPattern {
                pattern: value.to_string(),
                message: err,
            });
        };
        let after = &err[start + PREFIX.len()..];
        let end = after
            .find(|c: char| !c.is_alphanumeric() && c != '-' && c != '_' && c != ' ')
            .unwrap_or(after.len());
        let block = after[..end].trim();
        if block.is_empty() {
            return Err(FacetError::InvalidPattern {
                pattern: value.to_string(),
                message: err,
            });
        }
        match rewrite_pattern_isblock_token(&current, block) {
            Some(rewritten) => current = std::borrow::Cow::Owned(rewritten),
            None => {
                return Err(FacetError::InvalidPattern {
                    pattern: value.to_string(),
                    message: err,
                });
            }
        }
    }
    // Loop bound exceeded; surface the final error if any.
    if let Err(e) = regexml::Regex::xsd(&current, "") {
        return Err(FacetError::InvalidPattern {
            pattern: value.to_string(),
            message: format!("{:?}", e),
        });
    }
    Ok(current)
}

/// Rewrite every `\p{Is<block>}` / `\P{Is<block>}` token in `pattern` to a
/// match-everything expression. Uses `[\s\S]` at atom position and `\s\S`
/// inside a character class so the rewritten token is structurally valid in
/// either context. Returns `None` if no rewrite happened.
#[cfg(feature = "xsd11")]
fn rewrite_pattern_isblock_token(pattern: &str, block_name: &str) -> Option<String> {
    let inner_p = format!("p{{Is{}}}", block_name);
    let inner_cap = format!("P{{Is{}}}", block_name);
    let token_len = 1 + inner_p.len();
    if !pattern.contains(&format!("\\{}", inner_p))
        && !pattern.contains(&format!("\\{}", inner_cap))
    {
        return None;
    }
    let bytes = pattern.as_bytes();
    let mut result = String::with_capacity(pattern.len());
    let mut i = 0;
    let mut in_class = false;
    let mut found = false;
    while i < bytes.len() {
        if bytes[i] == b'\\' && i + token_len <= bytes.len() {
            // Tokens are pure ASCII, so byte-slice comparison is safe here.
            let candidate = &pattern[i + 1..i + token_len];
            if candidate == inner_p || candidate == inner_cap {
                if in_class {
                    result.push_str("\\s\\S");
                } else {
                    result.push_str("[\\s\\S]");
                }
                i += token_len;
                found = true;
                continue;
            }
        }
        let c = bytes[i];
        if c == b'\\' && i + 1 < bytes.len() {
            let next_len = pattern[i + 1..]
                .chars()
                .next()
                .map(|ch| ch.len_utf8())
                .unwrap_or(1);
            result.push_str(&pattern[i..i + 1 + next_len]);
            i += 1 + next_len;
            continue;
        }
        if c == b'[' {
            in_class = true;
            result.push('[');
            i += 1;
            continue;
        }
        if c == b']' {
            in_class = false;
            result.push(']');
            i += 1;
            continue;
        }
        let next_len = pattern[i..]
            .chars()
            .next()
            .map(|ch| ch.len_utf8())
            .unwrap_or(1);
        result.push_str(&pattern[i..i + next_len]);
        i += next_len;
    }
    if found {
        Some(result)
    } else {
        None
    }
}

/// Enumeration facet (allowed values)
#[derive(Debug, Clone)]
pub struct EnumerationFacet {
    /// Set of allowed values (as strings)
    pub values: HashSet<String>,
    pub source: Option<SourceRef>,
}

/// Whitespace facet
#[derive(Debug, Clone)]
pub struct WhitespaceFacet {
    pub value: WhitespaceMode,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MinInclusive facet (value >= bound)
#[derive(Debug, Clone)]
pub struct MinInclusiveFacet {
    /// The bound as a string (type-specific interpretation during validation)
    pub value: String,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MaxInclusive facet (value <= bound)
#[derive(Debug, Clone)]
pub struct MaxInclusiveFacet {
    pub value: String,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MinExclusive facet (value > bound)
#[derive(Debug, Clone)]
pub struct MinExclusiveFacet {
    pub value: String,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// MaxExclusive facet (value < bound)
#[derive(Debug, Clone)]
pub struct MaxExclusiveFacet {
    pub value: String,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// TotalDigits facet (for decimal types)
#[derive(Debug, Clone)]
pub struct TotalDigitsFacet {
    pub value: u32,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// FractionDigits facet (decimal places)
#[derive(Debug, Clone)]
pub struct FractionDigitsFacet {
    pub value: u32,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// XSD 1.1: Assertion facet (XPath constraint on simple type values)
#[derive(Debug, Clone)]
pub struct AssertionFacet {
    /// XPath 2.0 test expression
    pub test: String,
    /// Raw xpathDefaultNamespace attribute (resolved at evaluation time)
    pub xpath_default_namespace: Option<String>,
    /// Namespace bindings snapshot at parse time (for prefix resolution in XPath)
    pub ns_snapshot: NamespaceContextSnapshot,
    pub source: Option<SourceRef>,
}

/// XSD 1.1: ExplicitTimezone facet
/// TODO: XSD 1.1 - Implement explicitTimezone constraint
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExplicitTimezone {
    Required,
    Prohibited,
    Optional,
}

/// XSD 1.1: ExplicitTimezone facet data
#[derive(Debug, Clone)]
pub struct ExplicitTimezoneFacet {
    pub value: ExplicitTimezone,
    pub fixed: FacetFixed,
    pub source: Option<SourceRef>,
}

/// Complete set of facets for a simple type
///
/// A FacetSet collects all constraining facets that apply to a simple type.
/// Facets are accumulated during type derivation.
#[derive(Debug, Clone, Default)]
pub struct FacetSet {
    // String length facets
    pub length: Option<LengthFacet>,
    pub min_length: Option<MinLengthFacet>,
    pub max_length: Option<MaxLengthFacet>,

    // Pattern facets grouped by derivation step.
    //
    // Per XSD Datatypes Part 2 §4.3.4 (and the equivalent §A.2 prose),
    // multiple `<xs:pattern>` facets in a single restriction step combine
    // as alternation (logical OR), while patterns inherited from earlier
    // derivation steps further restrict the value (logical AND).
    //
    // Outer Vec = AND across derivation steps; inner Vec = OR within a step.
    pub patterns: Vec<Vec<PatternFacet>>,

    // Enumeration (allowed values). The `Option` is only the presence flag;
    // multi-valued semantics live inside `EnumerationFacet::values` (HashSet),
    // so enumeration is exempt from st-props-correct.1 "no duplicate facet" (§3.16.2).
    pub enumeration: Option<EnumerationFacet>,

    // Whitespace handling
    pub whitespace: Option<WhitespaceFacet>,

    // Numeric range facets
    pub min_inclusive: Option<MinInclusiveFacet>,
    pub max_inclusive: Option<MaxInclusiveFacet>,
    pub min_exclusive: Option<MinExclusiveFacet>,
    pub max_exclusive: Option<MaxExclusiveFacet>,

    // Decimal precision facets
    pub total_digits: Option<TotalDigitsFacet>,
    pub fraction_digits: Option<FractionDigitsFacet>,

    // XSD 1.1 facets
    // TODO: XSD 1.1 - These are parsed but not enforced in 1.0 mode
    pub assertions: Vec<AssertionFacet>,
    pub explicit_timezone: Option<ExplicitTimezoneFacet>,
}

impl FacetSet {
    /// Create a new empty facet set
    pub fn new() -> Self {
        Self::default()
    }

    /// Check if the facet set is empty (no facets defined)
    pub fn is_empty(&self) -> bool {
        self.length.is_none()
            && self.min_length.is_none()
            && self.max_length.is_none()
            && self.patterns.iter().all(|step| step.is_empty())
            && self.enumeration.is_none()
            && self.whitespace.is_none()
            && self.min_inclusive.is_none()
            && self.max_inclusive.is_none()
            && self.min_exclusive.is_none()
            && self.max_exclusive.is_none()
            && self.total_digits.is_none()
            && self.fraction_digits.is_none()
            && self.assertions.is_empty()
            && self.explicit_timezone.is_none()
    }

    /// Set length facet
    pub fn set_length(&mut self, value: u64, fixed: FacetFixed, source: Option<SourceRef>) {
        self.length = Some(LengthFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set minLength facet
    pub fn set_min_length(&mut self, value: u64, fixed: FacetFixed, source: Option<SourceRef>) {
        self.min_length = Some(MinLengthFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set maxLength facet
    pub fn set_max_length(&mut self, value: u64, fixed: FacetFixed, source: Option<SourceRef>) {
        self.max_length = Some(MaxLengthFacet {
            value,
            fixed,
            source,
        });
    }

    /// Add a pattern facet (compiles the pattern) at the current
    /// derivation step. Multiple consecutive `add_pattern` calls on the
    /// same FacetSet are treated as alternatives (OR'd) within a single
    /// step; a new step is opened by `inherit_from` / `merge_with_base`.
    pub fn add_pattern(
        &mut self,
        value: String,
        source: Option<SourceRef>,
        xsd_version: XsdVersion,
        regex_compat: RegexCompat,
    ) -> FacetResult<()> {
        let pattern = PatternFacet::new(value, source, xsd_version, regex_compat)?;
        self.push_pattern_to_current_step(pattern);
        Ok(())
    }

    /// Add a pattern facet without compiling (for deferred validation),
    /// at the current derivation step. See `add_pattern` for the OR/AND
    /// semantics across multiple calls.
    pub fn add_pattern_unchecked(&mut self, value: String, source: Option<SourceRef>) {
        self.push_pattern_to_current_step(PatternFacet::new_unchecked(value, source));
    }

    fn push_pattern_to_current_step(&mut self, pattern: PatternFacet) {
        if self.patterns.is_empty() {
            self.patterns.push(Vec::new());
        }
        self.patterns.last_mut().unwrap().push(pattern);
    }

    /// Compile all uncompiled patterns. Returns the first error encountered.
    ///
    /// `xsd_version` selects the Unicode-category semantics for `\p{X}`: V1_0
    /// pins to Unicode 3.0; V1_1 passes through to the backend.
    /// `regex_compat` controls grammar leniency (see [`PatternFacet::compile`]).
    pub fn compile_patterns(
        &mut self,
        xsd_version: XsdVersion,
        regex_compat: RegexCompat,
    ) -> FacetResult<()> {
        for step in &mut self.patterns {
            for pattern in step {
                pattern.compile(xsd_version, regex_compat)?;
            }
        }
        Ok(())
    }

    /// Run the per-step XSD pattern check on `value`: every step must have
    /// at least one alternative that matches (within-step OR, across-step
    /// AND). Returns the first failing step's first pattern as error
    /// context.
    fn check_patterns(&self, value: &str) -> FacetResult<()> {
        for step in &self.patterns {
            if step.is_empty() {
                continue;
            }
            if !step.iter().any(|p| p.matches(value)) {
                return Err(FacetError::pattern(value, &step[0].value));
            }
        }
        Ok(())
    }

    /// Add an enumeration value
    pub fn add_enumeration(&mut self, value: String, source: Option<SourceRef>) {
        let enumeration = self.enumeration.get_or_insert_with(|| EnumerationFacet {
            values: HashSet::new(),
            source: source.clone(),
        });
        enumeration.values.insert(value);
    }

    /// Set whitespace facet
    pub fn set_whitespace(
        &mut self,
        value: WhitespaceMode,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.whitespace = Some(WhitespaceFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set minInclusive facet
    pub fn set_min_inclusive(
        &mut self,
        value: String,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.min_inclusive = Some(MinInclusiveFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set maxInclusive facet
    pub fn set_max_inclusive(
        &mut self,
        value: String,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.max_inclusive = Some(MaxInclusiveFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set minExclusive facet
    pub fn set_min_exclusive(
        &mut self,
        value: String,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.min_exclusive = Some(MinExclusiveFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set maxExclusive facet
    pub fn set_max_exclusive(
        &mut self,
        value: String,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.max_exclusive = Some(MaxExclusiveFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set totalDigits facet
    pub fn set_total_digits(&mut self, value: u32, fixed: FacetFixed, source: Option<SourceRef>) {
        self.total_digits = Some(TotalDigitsFacet {
            value,
            fixed,
            source,
        });
    }

    /// Set fractionDigits facet
    pub fn set_fraction_digits(
        &mut self,
        value: u32,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.fraction_digits = Some(FractionDigitsFacet {
            value,
            fixed,
            source,
        });
    }

    /// Add an assertion facet (XSD 1.1)
    pub fn add_assertion(
        &mut self,
        test: String,
        xpath_default_namespace: Option<String>,
        ns_snapshot: NamespaceContextSnapshot,
        source: Option<SourceRef>,
    ) {
        self.assertions.push(AssertionFacet {
            test,
            xpath_default_namespace,
            ns_snapshot,
            source,
        });
    }

    /// Set explicitTimezone facet (XSD 1.1)
    pub fn set_explicit_timezone(
        &mut self,
        value: ExplicitTimezone,
        fixed: FacetFixed,
        source: Option<SourceRef>,
    ) {
        self.explicit_timezone = Some(ExplicitTimezoneFacet {
            value,
            fixed,
            source,
        });
    }

    /// Merge facets from a base type (for type derivation by restriction)
    ///
    /// Inherited facets are only set if not already defined in this facet set.
    /// The `fixed` attribute is preserved from the base type.
    ///
    /// Note: This method does not validate that derived facets are more restrictive.
    /// Use `merge_with_base()` for full validation.
    pub fn inherit_from(&mut self, base: &FacetSet) {
        // String length facets
        if self.length.is_none() {
            self.length = base.length.clone();
        }
        if self.min_length.is_none() {
            self.min_length = base.min_length.clone();
        }
        if self.max_length.is_none() {
            self.max_length = base.max_length.clone();
        }

        // Each base derivation step is appended as a new outer step on
        // self, preserving the within-step OR / across-step AND structure.
        // (Step-level dedup vs. derived's local step would require value-set
        // equivalence checks; skip it — repeated identical patterns are
        // idempotent under either OR or AND, and recompilation cost is
        // bounded by `compile_patterns` running per FacetSet at most once.)
        for base_step in &base.patterns {
            if !base_step.is_empty() {
                self.patterns.push(base_step.clone());
            }
        }

        // Whitespace
        if self.whitespace.is_none() {
            self.whitespace = base.whitespace.clone();
        }

        // Numeric bounds
        if self.min_inclusive.is_none() {
            self.min_inclusive = base.min_inclusive.clone();
        }
        if self.max_inclusive.is_none() {
            self.max_inclusive = base.max_inclusive.clone();
        }
        if self.min_exclusive.is_none() {
            self.min_exclusive = base.min_exclusive.clone();
        }
        if self.max_exclusive.is_none() {
            self.max_exclusive = base.max_exclusive.clone();
        }

        // Decimal precision
        if self.total_digits.is_none() {
            self.total_digits = base.total_digits.clone();
        }
        if self.fraction_digits.is_none() {
            self.fraction_digits = base.fraction_digits.clone();
        }

        // XSD 1.1 assertions are cumulative
        for assertion in &base.assertions {
            self.assertions.push(assertion.clone());
        }

        if self.explicit_timezone.is_none() {
            self.explicit_timezone = base.explicit_timezone.clone();
        }
    }

    /// Merge base type facets with derived type facets, validating derivation rules.
    ///
    /// This method enforces XSD derivation by restriction rules:
    /// - Fixed facets cannot be overridden with different values
    /// - Derived facets must be more restrictive than base facets
    /// - Patterns are cumulative (ANDed together)
    /// - Enumerations must be subsets of base enumerations
    ///
    /// Returns a new FacetSet combining base and derived facets, or an error
    /// if the derivation rules are violated.
    pub fn merge_with_base(&self, base: &FacetSet) -> FacetResult<FacetSet> {
        // XSD Datatypes Part 2 §4.3.1.4 / §4.3.2.4 / §4.3.3.4 same-step rule:
        // It is an error for both `length` and `minLength` (or `length` and
        // `maxLength`) to be members of {facets} in the same derivation step.
        // `self` represents this step's locally declared facets before the
        // base merge, so this is the correct moment to detect the conflict.
        if self.length.is_some() && self.min_length.is_some() {
            return Err(FacetError::conflicting(
                "length and minLength cannot both appear in the same restriction step",
            ));
        }
        if self.length.is_some() && self.max_length.is_some() {
            return Err(FacetError::conflicting(
                "length and maxLength cannot both appear in the same restriction step",
            ));
        }

        let mut result = self.clone();

        // === Length facets ===
        // Validate and merge length facet
        if let Some(ref base_length) = base.length {
            match &result.length {
                Some(derived) => {
                    // Fixed length cannot be changed
                    if base_length.fixed == FacetFixed::Fixed && derived.value != base_length.value
                    {
                        return Err(FacetError::fixed_violation(
                            "length",
                            base_length.value.to_string(),
                            derived.value.to_string(),
                        ));
                    }
                }
                None => {
                    result.length = Some(base_length.clone());
                }
            }
        }

        // Validate and merge minLength facet
        if let Some(ref base_min) = base.min_length {
            match &result.min_length {
                Some(derived) => {
                    if base_min.fixed == FacetFixed::Fixed && derived.value != base_min.value {
                        return Err(FacetError::fixed_violation(
                            "minLength",
                            base_min.value.to_string(),
                            derived.value.to_string(),
                        ));
                    }
                    // Derived minLength must be >= base minLength
                    if derived.value < base_min.value {
                        return Err(FacetError::derivation(format!(
                            "minLength {} is less restrictive than base minLength {}",
                            derived.value, base_min.value
                        )));
                    }
                }
                None => {
                    result.min_length = Some(base_min.clone());
                }
            }
        }

        // Validate and merge maxLength facet
        if let Some(ref base_max) = base.max_length {
            match &result.max_length {
                Some(derived) => {
                    if base_max.fixed == FacetFixed::Fixed && derived.value != base_max.value {
                        return Err(FacetError::fixed_violation(
                            "maxLength",
                            base_max.value.to_string(),
                            derived.value.to_string(),
                        ));
                    }
                    // Derived maxLength must be <= base maxLength
                    if derived.value > base_max.value {
                        return Err(FacetError::derivation(format!(
                            "maxLength {} is less restrictive than base maxLength {}",
                            derived.value, base_max.value
                        )));
                    }
                }
                None => {
                    result.max_length = Some(base_max.clone());
                }
            }
        }

        // === Patterns ===
        // Each base derivation step is appended as a new outer step on
        // result. Within-step OR / across-step AND semantics survive the
        // merge per XSD Datatypes §4.3.4.
        for base_step in &base.patterns {
            if !base_step.is_empty() {
                result.patterns.push(base_step.clone());
            }
        }

        // === Enumeration ===
        // If base has enumeration, derived must be a subset (or not specify enumeration)
        if let Some(ref base_enum) = base.enumeration {
            match &result.enumeration {
                Some(derived_enum) => {
                    // Check that derived values are subset of base values
                    for value in &derived_enum.values {
                        if !base_enum.values.contains(value) {
                            return Err(FacetError::derivation(format!(
                                "enumeration value '{}' is not in base enumeration",
                                value
                            )));
                        }
                    }
                }
                None => {
                    // Inherit base enumeration
                    result.enumeration = Some(base_enum.clone());
                }
            }
        }

        // === Whitespace ===
        if let Some(ref base_ws) = base.whitespace {
            match &result.whitespace {
                Some(derived) => {
                    if base_ws.fixed == FacetFixed::Fixed && derived.value != base_ws.value {
                        return Err(FacetError::fixed_violation(
                            "whiteSpace",
                            format!("{:?}", base_ws.value),
                            format!("{:?}", derived.value),
                        ));
                    }
                    // Whitespace can only become more restrictive:
                    // preserve -> replace -> collapse
                    if !is_whitespace_more_restrictive(derived.value, base_ws.value) {
                        return Err(FacetError::derivation(format!(
                            "whiteSpace {:?} is less restrictive than base {:?}",
                            derived.value, base_ws.value
                        )));
                    }
                }
                None => {
                    result.whitespace = Some(base_ws.clone());
                }
            }
        }

        // === Numeric bounds ===
        // Note: Full numeric comparison would require parsing the values
        // For now, we check fixed constraints and inherit missing values.
        //
        // A derived type may switch between Inclusive and Exclusive for the same bound
        // (e.g., base has minInclusive, derived has minExclusive).  Per cos-st-restricts,
        // only the derived facet applies, so we must NOT inherit the base facet when the
        // derived type already supplies the complementary one.
        if let Some(ref base_facet) = base.min_inclusive {
            if let Some(ref derived) = result.min_inclusive {
                if base_facet.fixed == FacetFixed::Fixed && derived.value != base_facet.value {
                    return Err(FacetError::fixed_violation(
                        "minInclusive",
                        &base_facet.value,
                        &derived.value,
                    ));
                }
            } else if result.min_exclusive.is_none() {
                // Only inherit if derived hasn't replaced it with minExclusive
                result.min_inclusive = Some(base_facet.clone());
            }
        }

        if let Some(ref base_facet) = base.max_inclusive {
            if let Some(ref derived) = result.max_inclusive {
                if base_facet.fixed == FacetFixed::Fixed && derived.value != base_facet.value {
                    return Err(FacetError::fixed_violation(
                        "maxInclusive",
                        &base_facet.value,
                        &derived.value,
                    ));
                }
            } else if result.max_exclusive.is_none() {
                // Only inherit if derived hasn't replaced it with maxExclusive
                result.max_inclusive = Some(base_facet.clone());
            }
        }

        if let Some(ref base_facet) = base.min_exclusive {
            if let Some(ref derived) = result.min_exclusive {
                if base_facet.fixed == FacetFixed::Fixed && derived.value != base_facet.value {
                    return Err(FacetError::fixed_violation(
                        "minExclusive",
                        &base_facet.value,
                        &derived.value,
                    ));
                }
            } else if result.min_inclusive.is_none() {
                // Only inherit if derived hasn't replaced it with minInclusive
                result.min_exclusive = Some(base_facet.clone());
            }
        }

        if let Some(ref base_facet) = base.max_exclusive {
            if let Some(ref derived) = result.max_exclusive {
                if base_facet.fixed == FacetFixed::Fixed && derived.value != base_facet.value {
                    return Err(FacetError::fixed_violation(
                        "maxExclusive",
                        &base_facet.value,
                        &derived.value,
                    ));
                }
            } else if result.max_inclusive.is_none() {
                // Only inherit if derived hasn't replaced it with maxInclusive
                result.max_exclusive = Some(base_facet.clone());
            }
        }

        // === Digit facets ===
        if let Some(ref base_td) = base.total_digits {
            match &result.total_digits {
                Some(derived) => {
                    if base_td.fixed == FacetFixed::Fixed && derived.value != base_td.value {
                        return Err(FacetError::fixed_violation(
                            "totalDigits",
                            base_td.value.to_string(),
                            derived.value.to_string(),
                        ));
                    }
                    // Derived totalDigits must be <= base totalDigits
                    if derived.value > base_td.value {
                        return Err(FacetError::derivation(format!(
                            "totalDigits {} is less restrictive than base totalDigits {}",
                            derived.value, base_td.value
                        )));
                    }
                }
                None => {
                    result.total_digits = Some(base_td.clone());
                }
            }
        }

        if let Some(ref base_fd) = base.fraction_digits {
            match &result.fraction_digits {
                Some(derived) => {
                    if base_fd.fixed == FacetFixed::Fixed && derived.value != base_fd.value {
                        return Err(FacetError::fixed_violation(
                            "fractionDigits",
                            base_fd.value.to_string(),
                            derived.value.to_string(),
                        ));
                    }
                    // Derived fractionDigits must be <= base fractionDigits
                    if derived.value > base_fd.value {
                        return Err(FacetError::derivation(format!(
                            "fractionDigits {} is less restrictive than base fractionDigits {}",
                            derived.value, base_fd.value
                        )));
                    }
                }
                None => {
                    result.fraction_digits = Some(base_fd.clone());
                }
            }
        }

        // === XSD 1.1 facets ===
        // Assertions are cumulative
        for assertion in &base.assertions {
            result.assertions.push(assertion.clone());
        }

        // ExplicitTimezone — §4.3.16 Valid explicitTimezone Restrictions:
        //   base=optional   → derived ∈ {optional, required, prohibited}
        //   base=required   → derived ∈ {required}
        //   base=prohibited → derived ∈ {prohibited}
        // This restriction is independent of {fixed}; fixed adds only a
        // stronger value-equality requirement on top.
        if let Some(ref base_etz) = base.explicit_timezone {
            if let Some(ref derived) = result.explicit_timezone {
                let restriction_ok = match base_etz.value {
                    ExplicitTimezone::Optional => true,
                    ExplicitTimezone::Required => derived.value == ExplicitTimezone::Required,
                    ExplicitTimezone::Prohibited => derived.value == ExplicitTimezone::Prohibited,
                };
                if !restriction_ok {
                    return Err(FacetError::derivation(format!(
                        "explicitTimezone {:?} is not a valid restriction of base {:?}",
                        derived.value, base_etz.value
                    )));
                }
                if base_etz.fixed == FacetFixed::Fixed && derived.value != base_etz.value {
                    return Err(FacetError::fixed_violation(
                        "explicitTimezone",
                        format!("{:?}", base_etz.value),
                        format!("{:?}", derived.value),
                    ));
                }
            } else {
                result.explicit_timezone = Some(base_etz.clone());
            }
        }

        // === Validate conflicting facets ===
        result.validate_consistency()?;

        Ok(result)
    }

    /// Validate internal consistency of facets
    fn validate_consistency(&self) -> FacetResult<()> {
        // Check minLength <= maxLength
        if let (Some(min), Some(max)) = (&self.min_length, &self.max_length) {
            if min.value > max.value {
                return Err(FacetError::conflicting(format!(
                    "minLength {} is greater than maxLength {}",
                    min.value, max.value
                )));
            }
        }

        // Check length conflicts with minLength/maxLength
        if let Some(len) = &self.length {
            if let Some(min) = &self.min_length {
                if len.value < min.value {
                    return Err(FacetError::conflicting(format!(
                        "length {} is less than minLength {}",
                        len.value, min.value
                    )));
                }
            }
            if let Some(max) = &self.max_length {
                if len.value > max.value {
                    return Err(FacetError::conflicting(format!(
                        "length {} is greater than maxLength {}",
                        len.value, max.value
                    )));
                }
            }
        }

        // Check minInclusive <= maxInclusive (string comparison, approximate)
        // Note: Full validation would require parsing the numeric values
        if self.min_inclusive.is_some() && self.min_exclusive.is_some() {
            return Err(FacetError::conflicting(
                "cannot have both minInclusive and minExclusive",
            ));
        }
        if self.max_inclusive.is_some() && self.max_exclusive.is_some() {
            return Err(FacetError::conflicting(
                "cannot have both maxInclusive and maxExclusive",
            ));
        }

        // Check fractionDigits <= totalDigits
        if let (Some(fd), Some(td)) = (&self.fraction_digits, &self.total_digits) {
            if fd.value > td.value {
                return Err(FacetError::conflicting(format!(
                    "fractionDigits {} is greater than totalDigits {}",
                    fd.value, td.value
                )));
            }
        }

        // Check numeric bound consistency (minInclusive vs maxInclusive, etc.)
        // Uses decimal parsing for numeric comparison
        if let (Some(min_incl), Some(max_incl)) = (&self.min_inclusive, &self.max_inclusive) {
            if let Some(cmp) = compare_decimal_strings(&min_incl.value, &max_incl.value) {
                if cmp == std::cmp::Ordering::Greater {
                    return Err(FacetError::conflicting(format!(
                        "minInclusive '{}' is greater than maxInclusive '{}'",
                        min_incl.value, max_incl.value
                    )));
                }
            }
        }
        if let (Some(min_excl), Some(max_excl)) = (&self.min_exclusive, &self.max_exclusive) {
            if let Some(cmp) = compare_decimal_strings(&min_excl.value, &max_excl.value) {
                if cmp != std::cmp::Ordering::Less {
                    return Err(FacetError::conflicting(format!(
                        "minExclusive '{}' must be less than maxExclusive '{}'",
                        min_excl.value, max_excl.value
                    )));
                }
            }
        }
        if let (Some(min_incl), Some(max_excl)) = (&self.min_inclusive, &self.max_exclusive) {
            if let Some(cmp) = compare_decimal_strings(&min_incl.value, &max_excl.value) {
                if cmp != std::cmp::Ordering::Less {
                    return Err(FacetError::conflicting(format!(
                        "minInclusive '{}' must be less than maxExclusive '{}'",
                        min_incl.value, max_excl.value
                    )));
                }
            }
        }
        if let (Some(min_excl), Some(max_incl)) = (&self.min_exclusive, &self.max_inclusive) {
            if let Some(cmp) = compare_decimal_strings(&min_excl.value, &max_incl.value) {
                if cmp != std::cmp::Ordering::Less {
                    return Err(FacetError::conflicting(format!(
                        "minExclusive '{}' must be less than maxInclusive '{}'",
                        min_excl.value, max_incl.value
                    )));
                }
            }
        }

        Ok(())
    }

    /// Validate a string value against all applicable facets
    ///
    /// This validates length, pattern, enumeration, and whitespace facets.
    /// Numeric bounds and digit facets require parsed values and are not
    /// validated by this method.
    pub fn validate_string(&self, value: &str) -> FacetResult<()> {
        // Apply whitespace normalization for length calculation
        let normalized = match &self.whitespace {
            Some(ws) => normalize_whitespace(value, ws.value),
            None => value.to_string(),
        };
        let check_value = &normalized;

        // Check length facet
        if let Some(ref length) = self.length {
            let len = check_value.chars().count() as u64;
            if len != length.value {
                return Err(FacetError::length(format!(
                    "value length {} does not equal required length {}",
                    len, length.value
                )));
            }
        }

        // Check minLength facet
        if let Some(ref min_length) = self.min_length {
            let len = check_value.chars().count() as u64;
            if len < min_length.value {
                return Err(FacetError::MinLengthViolation {
                    actual: len,
                    min: min_length.value,
                });
            }
        }

        // Check maxLength facet
        if let Some(ref max_length) = self.max_length {
            let len = check_value.chars().count() as u64;
            if len > max_length.value {
                return Err(FacetError::MaxLengthViolation {
                    actual: len,
                    max: max_length.value,
                });
            }
        }

        // Check all pattern steps (each step's alternatives are OR'd; all
        // steps must match).
        self.check_patterns(check_value)?;

        // Check enumeration
        if let Some(ref enumeration) = self.enumeration {
            if !enumeration.values.contains(check_value) {
                return Err(FacetError::enumeration(check_value));
            }
        }

        Ok(())
    }

    /// Validate only pattern and enumeration facets on a string value.
    /// Used for list types where length facets are checked separately as item count.
    pub fn validate_string_patterns_enums(&self, value: &str) -> FacetResult<()> {
        let normalized = match &self.whitespace {
            Some(ws) => normalize_whitespace(value, ws.value),
            None => value.to_string(),
        };
        let check_value = &normalized;

        self.check_patterns(check_value)?;

        if let Some(ref enumeration) = self.enumeration {
            if !enumeration.values.contains(check_value) {
                return Err(FacetError::enumeration(check_value));
            }
        }

        Ok(())
    }

    /// Validate only pattern facets (no enumeration, no length).
    /// Used when enumeration must be checked in value space rather than lexically.
    pub fn validate_patterns_only(&self, value: &str) -> FacetResult<()> {
        let normalized = match &self.whitespace {
            Some(ws) => normalize_whitespace(value, ws.value),
            None => value.to_string(),
        };
        self.check_patterns(&normalized)
    }

    /// Validate enumeration in value space using a caller-supplied match predicate.
    /// `is_match(enum_str)` returns true if the instance value equals the given
    /// enumeration lexical value. `display` is used in the error message on failure.
    pub fn validate_enum_value_space(
        &self,
        is_match: impl Fn(&str) -> bool,
        display: &str,
    ) -> FacetResult<()> {
        if let Some(ref enumeration) = self.enumeration {
            if !enumeration.values.iter().any(|s| is_match(s)) {
                return Err(FacetError::enumeration(display));
            }
        }
        Ok(())
    }

    /// Validate a decimal value against numeric facets
    pub fn validate_decimal(&self, value: &rust_decimal::Decimal) -> FacetResult<()> {
        // Check totalDigits
        if let Some(ref td) = self.total_digits {
            let total = count_total_digits(value);
            if total > td.value {
                return Err(FacetError::TotalDigitsViolation {
                    actual: total,
                    max: td.value,
                });
            }
        }

        // Check fractionDigits
        if let Some(ref fd) = self.fraction_digits {
            let frac = count_fraction_digits(value);
            if frac > fd.value {
                return Err(FacetError::FractionDigitsViolation {
                    actual: frac,
                    max: fd.value,
                });
            }
        }

        // Check numeric bounds
        if let Some(ref min) = self.min_inclusive {
            if let Ok(bound) = rust_decimal::Decimal::from_str_exact(&min.value) {
                if *value < bound {
                    return Err(FacetError::MinInclusiveViolation {
                        value: value.to_string(),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_inclusive {
            if let Ok(bound) = rust_decimal::Decimal::from_str_exact(&max.value) {
                if *value > bound {
                    return Err(FacetError::MaxInclusiveViolation {
                        value: value.to_string(),
                        max: max.value.clone(),
                    });
                }
            }
        }

        if let Some(ref min) = self.min_exclusive {
            if let Ok(bound) = rust_decimal::Decimal::from_str_exact(&min.value) {
                if *value <= bound {
                    return Err(FacetError::MinExclusiveViolation {
                        value: value.to_string(),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_exclusive {
            if let Ok(bound) = rust_decimal::Decimal::from_str_exact(&max.value) {
                if *value >= bound {
                    return Err(FacetError::MaxExclusiveViolation {
                        value: value.to_string(),
                        max: max.value.clone(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Validate a float value against numeric bounds facets
    pub fn validate_float(&self, value: f32) -> FacetResult<()> {
        // NaN doesn't compare normally, so skip bounds checking for NaN
        if value.is_nan() {
            return Ok(());
        }

        // Check numeric bounds
        if let Some(ref min) = self.min_inclusive {
            if let Ok(bound) = min.value.parse::<f32>() {
                if !bound.is_nan() && value < bound {
                    return Err(FacetError::MinInclusiveViolation {
                        value: format_float_for_error(value),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_inclusive {
            if let Ok(bound) = max.value.parse::<f32>() {
                if !bound.is_nan() && value > bound {
                    return Err(FacetError::MaxInclusiveViolation {
                        value: format_float_for_error(value),
                        max: max.value.clone(),
                    });
                }
            }
        }

        if let Some(ref min) = self.min_exclusive {
            if let Ok(bound) = min.value.parse::<f32>() {
                if !bound.is_nan() && value <= bound {
                    return Err(FacetError::MinExclusiveViolation {
                        value: format_float_for_error(value),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_exclusive {
            if let Ok(bound) = max.value.parse::<f32>() {
                if !bound.is_nan() && value >= bound {
                    return Err(FacetError::MaxExclusiveViolation {
                        value: format_float_for_error(value),
                        max: max.value.clone(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Validate a double value against numeric bounds facets
    pub fn validate_double(&self, value: f64) -> FacetResult<()> {
        // NaN doesn't compare normally, so skip bounds checking for NaN
        if value.is_nan() {
            return Ok(());
        }

        // Check numeric bounds
        if let Some(ref min) = self.min_inclusive {
            if let Ok(bound) = min.value.parse::<f64>() {
                if !bound.is_nan() && value < bound {
                    return Err(FacetError::MinInclusiveViolation {
                        value: format_double_for_error(value),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_inclusive {
            if let Ok(bound) = max.value.parse::<f64>() {
                if !bound.is_nan() && value > bound {
                    return Err(FacetError::MaxInclusiveViolation {
                        value: format_double_for_error(value),
                        max: max.value.clone(),
                    });
                }
            }
        }

        if let Some(ref min) = self.min_exclusive {
            if let Ok(bound) = min.value.parse::<f64>() {
                if !bound.is_nan() && value <= bound {
                    return Err(FacetError::MinExclusiveViolation {
                        value: format_double_for_error(value),
                        min: min.value.clone(),
                    });
                }
            }
        }

        if let Some(ref max) = self.max_exclusive {
            if let Ok(bound) = max.value.parse::<f64>() {
                if !bound.is_nan() && value >= bound {
                    return Err(FacetError::MaxExclusiveViolation {
                        value: format_double_for_error(value),
                        max: max.value.clone(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Validate explicitTimezone constraint (XSD 1.1)
    ///
    /// # Arguments
    /// * `has_timezone` - Whether the value has a timezone specified
    pub fn validate_explicit_timezone(&self, has_timezone: bool) -> FacetResult<()> {
        if let Some(ref etz) = self.explicit_timezone {
            match etz.value {
                ExplicitTimezone::Required if !has_timezone => {
                    return Err(FacetError::ExplicitTimezoneViolation {
                        message: "timezone is required but not present".to_string(),
                    });
                }
                ExplicitTimezone::Prohibited if has_timezone => {
                    return Err(FacetError::ExplicitTimezoneViolation {
                        message: "timezone is prohibited but present".to_string(),
                    });
                }
                ExplicitTimezone::Optional
                | ExplicitTimezone::Required
                | ExplicitTimezone::Prohibited => {
                    // Valid
                }
            }
        }
        Ok(())
    }

    /// Validate a binary value (hex or base64) against length facets
    pub fn validate_binary_length(&self, byte_count: u64) -> FacetResult<()> {
        // For binary types, length is measured in octets
        if let Some(ref length) = self.length {
            if byte_count != length.value {
                return Err(FacetError::length(format!(
                    "binary length {} does not equal required length {}",
                    byte_count, length.value
                )));
            }
        }

        if let Some(ref min_length) = self.min_length {
            if byte_count < min_length.value {
                return Err(FacetError::MinLengthViolation {
                    actual: byte_count,
                    min: min_length.value,
                });
            }
        }

        if let Some(ref max_length) = self.max_length {
            if byte_count > max_length.value {
                return Err(FacetError::MaxLengthViolation {
                    actual: byte_count,
                    max: max_length.value,
                });
            }
        }

        Ok(())
    }

    /// Validate a list value against length facets (item count)
    pub fn validate_list_length(&self, item_count: u64) -> FacetResult<()> {
        // For list types, length is measured in number of items
        if let Some(ref length) = self.length {
            if item_count != length.value {
                return Err(FacetError::length(format!(
                    "list length {} does not equal required length {}",
                    item_count, length.value
                )));
            }
        }

        if let Some(ref min_length) = self.min_length {
            if item_count < min_length.value {
                return Err(FacetError::MinLengthViolation {
                    actual: item_count,
                    min: min_length.value,
                });
            }
        }

        if let Some(ref max_length) = self.max_length {
            if item_count > max_length.value {
                return Err(FacetError::MaxLengthViolation {
                    actual: item_count,
                    max: max_length.value,
                });
            }
        }

        Ok(())
    }
}

/// Check if derived whitespace mode is more restrictive than base
fn is_whitespace_more_restrictive(derived: WhitespaceMode, base: WhitespaceMode) -> bool {
    use WhitespaceMode::*;
    match (base, derived) {
        // Same is always OK
        (Preserve, Preserve) | (Replace, Replace) | (Collapse, Collapse) => true,
        // preserve -> replace -> collapse is more restrictive
        (Preserve, Replace) | (Preserve, Collapse) | (Replace, Collapse) => true,
        // Going the other way is less restrictive
        _ => false,
    }
}

/// Compare two strings as decimal/integer values.
/// Returns None if either string cannot be parsed as a number.
fn compare_decimal_strings(a: &str, b: &str) -> Option<std::cmp::Ordering> {
    // Try parsing as f64 for general numeric comparison
    let a_val: f64 = a.trim().parse().ok()?;
    let b_val: f64 = b.trim().parse().ok()?;
    a_val.partial_cmp(&b_val)
}

/// Apply whitespace normalization to a string
pub fn normalize_whitespace(s: &str, mode: WhitespaceMode) -> String {
    match mode {
        WhitespaceMode::Preserve => s.to_string(),
        WhitespaceMode::Replace => {
            // Replace tab, CR, LF with space
            s.chars()
                .map(|c| match c {
                    '\t' | '\r' | '\n' => ' ',
                    _ => c,
                })
                .collect()
        }
        WhitespaceMode::Collapse => {
            // Replace, then collapse consecutive spaces, then trim
            let replaced: String = s
                .chars()
                .map(|c| match c {
                    '\t' | '\r' | '\n' => ' ',
                    _ => c,
                })
                .collect();

            let mut result = String::with_capacity(replaced.len());
            let mut prev_space = true; // Start true to trim leading spaces

            for c in replaced.chars() {
                if c == ' ' {
                    if !prev_space {
                        result.push(' ');
                        prev_space = true;
                    }
                } else {
                    result.push(c);
                    prev_space = false;
                }
            }

            // Trim trailing space
            if result.ends_with(' ') {
                result.pop();
            }

            result
        }
    }
}

/// Count total significant digits in a decimal value.
///
/// Per Datatypes Part 2 §4.3.11.4 the `totalDigits` constraint counts the
/// digits of the unscaled integer mantissa `j` in the canonical
/// representation `i = j × 10^-k` (with leading zeros excluded). For
/// example `0.12345 = 12345 × 10^-5` has totalDigits = 5 — the leading `0`
/// before the decimal point in the lexical form must not be counted.
fn count_total_digits(value: &rust_decimal::Decimal) -> u32 {
    let normalized = value.abs().normalize();
    let mut m = normalized.mantissa().unsigned_abs();
    if m == 0 {
        return 1;
    }
    let mut count = 0u32;
    while m > 0 {
        count += 1;
        m /= 10;
    }
    count
}

/// Count fraction digits in a decimal value
fn count_fraction_digits(value: &rust_decimal::Decimal) -> u32 {
    let s = value.normalize().to_string();
    match s.find('.') {
        Some(pos) => (s.len() - pos - 1) as u32,
        None => 0,
    }
}

/// Format a float value for error messages (XSD canonical form)
fn format_float_for_error(v: f32) -> String {
    if v.is_nan() {
        "NaN".to_string()
    } else if v.is_infinite() {
        if v.is_sign_positive() {
            "INF".to_string()
        } else {
            "-INF".to_string()
        }
    } else {
        v.to_string()
    }
}

/// Format a double value for error messages (XSD canonical form)
fn format_double_for_error(v: f64) -> String {
    if v.is_nan() {
        "NaN".to_string()
    } else if v.is_infinite() {
        if v.is_sign_positive() {
            "INF".to_string()
        } else {
            "-INF".to_string()
        }
    } else {
        v.to_string()
    }
}

/// Facet applicability for built-in types
///
/// Defines which facets can be applied to which primitive types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FacetApplicability {
    /// Facet is not applicable to this type
    NotApplicable,
    /// Facet is applicable to this type
    Applicable,
    /// Facet is required for this type (e.g., whitespace for string)
    Required,
}

/// Facet kind enumeration for checking applicability
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FacetKind {
    Length,
    MinLength,
    MaxLength,
    Pattern,
    Enumeration,
    Whitespace,
    MinInclusive,
    MaxInclusive,
    MinExclusive,
    MaxExclusive,
    TotalDigits,
    FractionDigits,
    /// XSD 1.1
    ExplicitTimezone,
    /// XSD 1.1
    Assertion,
}

impl FacetKind {
    /// Parse facet kind from name
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "length" => Some(Self::Length),
            "minLength" => Some(Self::MinLength),
            "maxLength" => Some(Self::MaxLength),
            "pattern" => Some(Self::Pattern),
            "enumeration" => Some(Self::Enumeration),
            "whiteSpace" => Some(Self::Whitespace),
            "minInclusive" => Some(Self::MinInclusive),
            "maxInclusive" => Some(Self::MaxInclusive),
            "minExclusive" => Some(Self::MinExclusive),
            "maxExclusive" => Some(Self::MaxExclusive),
            "totalDigits" => Some(Self::TotalDigits),
            "fractionDigits" => Some(Self::FractionDigits),
            "explicitTimezone" => Some(Self::ExplicitTimezone),
            "assertion" => Some(Self::Assertion),
            _ => None,
        }
    }

    /// Get the name of this facet kind
    pub fn name(&self) -> &'static str {
        match self {
            Self::Length => "length",
            Self::MinLength => "minLength",
            Self::MaxLength => "maxLength",
            Self::Pattern => "pattern",
            Self::Enumeration => "enumeration",
            Self::Whitespace => "whiteSpace",
            Self::MinInclusive => "minInclusive",
            Self::MaxInclusive => "maxInclusive",
            Self::MinExclusive => "minExclusive",
            Self::MaxExclusive => "maxExclusive",
            Self::TotalDigits => "totalDigits",
            Self::FractionDigits => "fractionDigits",
            Self::ExplicitTimezone => "explicitTimezone",
            Self::Assertion => "assertion",
        }
    }
}

/// Check if a facet is applicable to a type (using XmlTypeCode)
pub fn facet_applicable_for_type(facet: FacetKind, type_code: XmlTypeCode) -> FacetApplicability {
    use FacetApplicability::*;
    use FacetKind::*;
    use XmlTypeCode::*;

    match facet {
        // Length facets apply to string, binary, list, and URI types
        Length | MinLength | MaxLength => match type_code {
            String | NormalizedString | Token | Language | NmToken | Name | NCName | Id | IdRef
            | Entity | HexBinary | Base64Binary | AnyUri | QName | Notation | NmTokens | IdRefs
            | Entities => Applicable,
            _ => NotApplicable,
        },

        // Pattern and enumeration apply to all atomic types
        Pattern | Enumeration => {
            if type_code.is_atomic() || type_code == AnySimpleType || type_code == AnyAtomicType {
                Applicable
            } else {
                NotApplicable
            }
        }

        // Whitespace is required for string, applicable to all string-derived types
        Whitespace => match type_code {
            String => Required,
            NormalizedString | Token | Language | NmToken | Name | NCName | Id | IdRef | Entity => {
                Applicable
            }
            // All other atomic types can have whitespace
            _ if type_code.is_atomic() => Applicable,
            _ => NotApplicable,
        },

        // Bound facets apply to ordered types (numeric, date/time)
        MinInclusive | MaxInclusive | MinExclusive | MaxExclusive => match type_code {
            // Decimal hierarchy
            Decimal | Integer | NonPositiveInteger | NegativeInteger | NonNegativeInteger
            | PositiveInteger | Long | Int | Short | Byte | UnsignedLong | UnsignedInt
            | UnsignedShort | UnsignedByte => Applicable,
            // Float/Double
            Float | Double => Applicable,
            // Date/time types (all have total ordering)
            Duration | DateTime | Time | Date | GYearMonth | GYear | GMonthDay | GDay | GMonth
            | YearMonthDuration | DayTimeDuration | DateTimeStamp => Applicable,
            _ => NotApplicable,
        },

        // Digit facets apply only to decimal types
        TotalDigits => match type_code {
            Decimal | Integer | NonPositiveInteger | NegativeInteger | NonNegativeInteger
            | PositiveInteger | Long | Int | Short | Byte | UnsignedLong | UnsignedInt
            | UnsignedShort | UnsignedByte => Applicable,
            _ => NotApplicable,
        },

        FractionDigits => match type_code {
            Decimal => Applicable,
            // Integer types have fractionDigits implicitly 0
            Integer | NonPositiveInteger | NegativeInteger | NonNegativeInteger
            | PositiveInteger | Long | Int | Short | Byte | UnsignedLong | UnsignedInt
            | UnsignedShort | UnsignedByte => Applicable,
            _ => NotApplicable,
        },

        // XSD 1.1: explicitTimezone applies to date/time types with optional timezone
        ExplicitTimezone => match type_code {
            DateTime | Time | Date | GYearMonth | GYear | GMonthDay | GDay | GMonth
            | DateTimeStamp => Applicable,
            _ => NotApplicable,
        },

        // XSD 1.1: assertion applies to all types
        Assertion => Applicable,
    }
}

/// Check if a facet is applicable to a built-in type (by name)
///
/// This is a convenience wrapper around `facet_applicable_for_type` that
/// takes string names for compatibility.
pub fn facet_applicable(type_name: &str, facet_name: &str) -> FacetApplicability {
    let facet = match FacetKind::from_name(facet_name) {
        Some(f) => f,
        None => return FacetApplicability::NotApplicable,
    };

    let type_code = match XmlTypeCode::from_local_name(type_name) {
        Some(tc) => tc,
        None => return FacetApplicability::NotApplicable,
    };

    facet_applicable_for_type(facet, type_code)
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::Decimal;
    use std::str::FromStr;

    // =========================================================================
    // Basic FacetSet tests
    // =========================================================================

    #[test]
    fn test_facet_set_empty() {
        let facets = FacetSet::new();
        assert!(facets.is_empty());
    }

    #[test]
    fn test_facet_set_length() {
        let mut facets = FacetSet::new();
        facets.set_length(10, FacetFixed::Default, None);

        assert!(!facets.is_empty());
        assert_eq!(facets.length.as_ref().unwrap().value, 10);
    }

    #[test]
    fn test_facet_set_patterns() {
        let mut facets = FacetSet::new();
        facets
            .add_pattern("[a-z]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();
        facets
            .add_pattern("[0-9]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();

        // Two adds within one FacetSet share the same derivation step (OR'd).
        assert_eq!(facets.patterns.len(), 1);
        assert_eq!(facets.patterns[0].len(), 2);
    }

    #[test]
    fn test_facet_set_enumeration() {
        let mut facets = FacetSet::new();
        facets.add_enumeration("red".to_string(), None);
        facets.add_enumeration("green".to_string(), None);
        facets.add_enumeration("blue".to_string(), None);

        let enum_facet = facets.enumeration.as_ref().unwrap();
        assert_eq!(enum_facet.values.len(), 3);
        assert!(enum_facet.values.contains("red"));
    }

    #[test]
    fn test_facet_inheritance() {
        let mut base = FacetSet::new();
        base.set_min_length(5, FacetFixed::Fixed, None);
        base.set_max_length(100, FacetFixed::Default, None);
        base.add_pattern("[a-z]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();

        let mut derived = FacetSet::new();
        derived.set_max_length(50, FacetFixed::Default, None); // Override

        derived.inherit_from(&base);

        // minLength inherited
        assert_eq!(derived.min_length.as_ref().unwrap().value, 5);
        // maxLength not inherited (was overridden)
        assert_eq!(derived.max_length.as_ref().unwrap().value, 50);
        // Base step inherited as a separate step entry.
        assert_eq!(derived.patterns.len(), 1);
        assert_eq!(derived.patterns[0].len(), 1);
    }

    // =========================================================================
    // Facet applicability tests
    // =========================================================================

    #[test]
    fn test_facet_applicability() {
        use FacetApplicability::*;

        // Length facets apply to string types
        assert_eq!(facet_applicable("string", "length"), Applicable);
        assert_eq!(facet_applicable("decimal", "length"), NotApplicable);

        // Numeric facets apply to numeric types
        assert_eq!(facet_applicable("decimal", "minInclusive"), Applicable);
        assert_eq!(facet_applicable("string", "minInclusive"), NotApplicable);

        // Pattern and enumeration apply to all
        assert_eq!(facet_applicable("string", "pattern"), Applicable);
        assert_eq!(facet_applicable("decimal", "pattern"), Applicable);

        // Whitespace is required for string
        assert_eq!(facet_applicable("string", "whiteSpace"), Required);
    }

    #[test]
    fn test_facet_applicability_with_type_code() {
        use FacetApplicability::*;
        use FacetKind::*;
        use XmlTypeCode::*;

        // Length facets
        assert_eq!(facet_applicable_for_type(Length, String), Applicable);
        assert_eq!(facet_applicable_for_type(Length, HexBinary), Applicable);
        assert_eq!(facet_applicable_for_type(Length, Decimal), NotApplicable);

        // Digit facets
        assert_eq!(facet_applicable_for_type(TotalDigits, Decimal), Applicable);
        assert_eq!(facet_applicable_for_type(TotalDigits, Integer), Applicable);
        assert_eq!(facet_applicable_for_type(TotalDigits, Float), NotApplicable);

        // Date/time facets
        assert_eq!(
            facet_applicable_for_type(ExplicitTimezone, DateTime),
            Applicable
        );
        assert_eq!(
            facet_applicable_for_type(ExplicitTimezone, String),
            NotApplicable
        );
    }

    // =========================================================================
    // Pattern tests
    // =========================================================================

    #[test]
    fn test_pattern_matching() {
        let pattern =
            PatternFacet::new("[a-z]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
                .unwrap();
        assert!(pattern.matches("hello"));
        assert!(!pattern.matches("HELLO"));
        assert!(!pattern.matches("hello123"));
    }

    #[test]
    fn test_pattern_xsd_anchoring() {
        // XSD patterns are implicitly anchored
        let pattern =
            PatternFacet::new("abc".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
                .unwrap();
        assert!(pattern.matches("abc"));
        assert!(!pattern.matches("xabc"));
        assert!(!pattern.matches("abcx"));
    }

    #[test]
    fn test_pattern_xsd_name_chars() {
        // Test \i (initial name char) and \c (name char)
        let pattern =
            PatternFacet::new(r"\i\c*".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
                .unwrap();
        assert!(pattern.matches("foo"));
        assert!(pattern.matches("_bar"));
        assert!(pattern.matches("x123"));
        assert!(!pattern.matches("123"));
    }

    #[test]
    fn test_invalid_pattern() {
        let result =
            PatternFacet::new("[invalid".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict);
        assert!(result.is_err());
    }

    // =========================================================================
    // Whitespace normalization tests
    // =========================================================================

    #[test]
    fn test_whitespace_preserve() {
        let result = normalize_whitespace("  hello\t\nworld  ", WhitespaceMode::Preserve);
        assert_eq!(result, "  hello\t\nworld  ");
    }

    #[test]
    fn test_whitespace_replace() {
        let result = normalize_whitespace("  hello\t\nworld  ", WhitespaceMode::Replace);
        assert_eq!(result, "  hello  world  ");
    }

    #[test]
    fn test_whitespace_collapse() {
        let result = normalize_whitespace("  hello\t\nworld  ", WhitespaceMode::Collapse);
        assert_eq!(result, "hello world");
    }

    #[test]
    fn test_whitespace_collapse_multiple_spaces() {
        let result = normalize_whitespace("a     b", WhitespaceMode::Collapse);
        assert_eq!(result, "a b");
    }

    // =========================================================================
    // String validation tests
    // =========================================================================

    #[test]
    fn test_validate_string_length() {
        let mut facets = FacetSet::new();
        facets.set_length(5, FacetFixed::Default, None);

        assert!(facets.validate_string("hello").is_ok());
        assert!(facets.validate_string("hi").is_err());
        assert!(facets.validate_string("toolong").is_err());
    }

    #[test]
    fn test_validate_string_min_max_length() {
        let mut facets = FacetSet::new();
        facets.set_min_length(3, FacetFixed::Default, None);
        facets.set_max_length(10, FacetFixed::Default, None);

        assert!(facets.validate_string("hello").is_ok());
        assert!(facets.validate_string("hi").is_err());
        assert!(facets.validate_string("this is way too long").is_err());
    }

    #[test]
    fn test_validate_string_pattern() {
        let mut facets = FacetSet::new();
        facets
            .add_pattern("[a-z]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();

        assert!(facets.validate_string("hello").is_ok());
        assert!(facets.validate_string("HELLO").is_err());
    }

    #[test]
    fn test_validate_string_enumeration() {
        let mut facets = FacetSet::new();
        facets.add_enumeration("red".to_string(), None);
        facets.add_enumeration("green".to_string(), None);
        facets.add_enumeration("blue".to_string(), None);

        assert!(facets.validate_string("red").is_ok());
        assert!(facets.validate_string("yellow").is_err());
    }

    // =========================================================================
    // Decimal validation tests
    // =========================================================================

    #[test]
    fn test_validate_decimal_total_digits() {
        let mut facets = FacetSet::new();
        facets.set_total_digits(5, FacetFixed::Default, None);

        let val = Decimal::from_str("12345").unwrap();
        assert!(facets.validate_decimal(&val).is_ok());

        let val = Decimal::from_str("123456").unwrap();
        assert!(facets.validate_decimal(&val).is_err());
    }

    #[test]
    fn test_validate_decimal_fraction_digits() {
        let mut facets = FacetSet::new();
        facets.set_fraction_digits(2, FacetFixed::Default, None);

        let val = Decimal::from_str("123.45").unwrap();
        assert!(facets.validate_decimal(&val).is_ok());

        let val = Decimal::from_str("123.456").unwrap();
        assert!(facets.validate_decimal(&val).is_err());
    }

    #[test]
    fn test_validate_decimal_bounds() {
        let mut facets = FacetSet::new();
        facets.set_min_inclusive("0".to_string(), FacetFixed::Default, None);
        facets.set_max_inclusive("100".to_string(), FacetFixed::Default, None);

        let val = Decimal::from_str("50").unwrap();
        assert!(facets.validate_decimal(&val).is_ok());

        let val = Decimal::from_str("-1").unwrap();
        assert!(facets.validate_decimal(&val).is_err());

        let val = Decimal::from_str("101").unwrap();
        assert!(facets.validate_decimal(&val).is_err());
    }

    #[test]
    fn test_validate_decimal_exclusive_bounds() {
        let mut facets = FacetSet::new();
        facets.set_min_exclusive("0".to_string(), FacetFixed::Default, None);
        facets.set_max_exclusive("100".to_string(), FacetFixed::Default, None);

        let val = Decimal::from_str("0").unwrap();
        assert!(facets.validate_decimal(&val).is_err()); // 0 is not > 0

        let val = Decimal::from_str("100").unwrap();
        assert!(facets.validate_decimal(&val).is_err()); // 100 is not < 100

        let val = Decimal::from_str("50").unwrap();
        assert!(facets.validate_decimal(&val).is_ok());
    }

    // =========================================================================
    // Binary/List length validation tests
    // =========================================================================

    #[test]
    fn test_validate_binary_length() {
        let mut facets = FacetSet::new();
        facets.set_length(4, FacetFixed::Default, None);

        assert!(facets.validate_binary_length(4).is_ok());
        assert!(facets.validate_binary_length(3).is_err());
        assert!(facets.validate_binary_length(5).is_err());
    }

    #[test]
    fn test_validate_list_length() {
        let mut facets = FacetSet::new();
        facets.set_min_length(1, FacetFixed::Default, None);
        facets.set_max_length(5, FacetFixed::Default, None);

        assert!(facets.validate_list_length(3).is_ok());
        assert!(facets.validate_list_length(0).is_err());
        assert!(facets.validate_list_length(10).is_err());
    }

    // =========================================================================
    // merge_with_base tests
    // =========================================================================

    #[test]
    fn test_merge_with_base_inherits_facets() {
        let mut base = FacetSet::new();
        base.set_min_length(5, FacetFixed::Default, None);
        base.set_max_length(100, FacetFixed::Default, None);

        let derived = FacetSet::new();
        let merged = derived.merge_with_base(&base).unwrap();

        assert_eq!(merged.min_length.as_ref().unwrap().value, 5);
        assert_eq!(merged.max_length.as_ref().unwrap().value, 100);
    }

    #[test]
    fn test_merge_with_base_allows_more_restrictive() {
        let mut base = FacetSet::new();
        base.set_min_length(5, FacetFixed::Default, None);
        base.set_max_length(100, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_min_length(10, FacetFixed::Default, None); // More restrictive
        derived.set_max_length(50, FacetFixed::Default, None); // More restrictive

        let merged = derived.merge_with_base(&base).unwrap();
        assert_eq!(merged.min_length.as_ref().unwrap().value, 10);
        assert_eq!(merged.max_length.as_ref().unwrap().value, 50);
    }

    #[test]
    fn test_merge_with_base_rejects_less_restrictive_min_length() {
        let mut base = FacetSet::new();
        base.set_min_length(10, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_min_length(5, FacetFixed::Default, None); // Less restrictive

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_with_base_rejects_less_restrictive_max_length() {
        let mut base = FacetSet::new();
        base.set_max_length(50, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_max_length(100, FacetFixed::Default, None); // Less restrictive

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_with_base_fixed_facet_same_value_ok() {
        let mut base = FacetSet::new();
        base.set_length(10, FacetFixed::Fixed, None);

        let mut derived = FacetSet::new();
        derived.set_length(10, FacetFixed::Default, None); // Same value

        let result = derived.merge_with_base(&base);
        assert!(result.is_ok());
    }

    #[test]
    fn test_merge_with_base_fixed_facet_different_value_error() {
        let mut base = FacetSet::new();
        base.set_length(10, FacetFixed::Fixed, None);

        let mut derived = FacetSet::new();
        derived.set_length(20, FacetFixed::Default, None); // Different value

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
        if let Err(FacetError::FixedFacetViolation { facet_name, .. }) = result {
            assert_eq!(facet_name, "length");
        } else {
            panic!("Expected FixedFacetViolation error");
        }
    }

    #[test]
    fn test_merge_with_base_patterns_cumulative() {
        let mut base = FacetSet::new();
        base.add_pattern("[a-z]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();

        let mut derived = FacetSet::new();
        derived
            .add_pattern("[0-9]+".to_string(), None, XsdVersion::V1_1, RegexCompat::Strict)
            .unwrap();

        let merged = derived.merge_with_base(&base).unwrap();
        // Derived step (one OR'd pattern) AND base step (one OR'd pattern)
        // = two separate AND'd steps.
        assert_eq!(merged.patterns.len(), 2);
    }

    #[test]
    fn test_merge_with_base_enumeration_subset() {
        let mut base = FacetSet::new();
        base.add_enumeration("red".to_string(), None);
        base.add_enumeration("green".to_string(), None);
        base.add_enumeration("blue".to_string(), None);

        let mut derived = FacetSet::new();
        derived.add_enumeration("red".to_string(), None);
        derived.add_enumeration("blue".to_string(), None);

        let merged = derived.merge_with_base(&base);
        assert!(merged.is_ok());
    }

    #[test]
    fn test_merge_with_base_enumeration_not_subset_error() {
        let mut base = FacetSet::new();
        base.add_enumeration("red".to_string(), None);
        base.add_enumeration("green".to_string(), None);

        let mut derived = FacetSet::new();
        derived.add_enumeration("yellow".to_string(), None); // Not in base

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_with_base_whitespace_more_restrictive() {
        let mut base = FacetSet::new();
        base.set_whitespace(WhitespaceMode::Preserve, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_whitespace(WhitespaceMode::Collapse, FacetFixed::Default, None);

        let result = derived.merge_with_base(&base);
        assert!(result.is_ok());
    }

    #[test]
    fn test_merge_with_base_whitespace_less_restrictive_error() {
        let mut base = FacetSet::new();
        base.set_whitespace(WhitespaceMode::Collapse, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_whitespace(WhitespaceMode::Preserve, FacetFixed::Default, None);

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_with_base_digit_facets() {
        let mut base = FacetSet::new();
        base.set_total_digits(10, FacetFixed::Default, None);
        base.set_fraction_digits(5, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_total_digits(5, FacetFixed::Default, None); // More restrictive
        derived.set_fraction_digits(2, FacetFixed::Default, None); // More restrictive

        let result = derived.merge_with_base(&base);
        assert!(result.is_ok());
    }

    #[test]
    fn test_merge_with_base_digit_facets_less_restrictive_error() {
        let mut base = FacetSet::new();
        base.set_total_digits(5, FacetFixed::Default, None);

        let mut derived = FacetSet::new();
        derived.set_total_digits(10, FacetFixed::Default, None); // Less restrictive

        let result = derived.merge_with_base(&base);
        assert!(result.is_err());
    }

    // =========================================================================
    // Consistency validation tests
    // =========================================================================

    #[test]
    fn test_consistency_min_greater_than_max_length() {
        let mut base = FacetSet::new();
        base.set_min_length(10, FacetFixed::Default, None);
        base.set_max_length(5, FacetFixed::Default, None);

        let result = base.merge_with_base(&FacetSet::new());
        assert!(result.is_err());
    }

    #[test]
    fn test_consistency_both_inclusive_and_exclusive() {
        let mut base = FacetSet::new();
        base.set_min_inclusive("0".to_string(), FacetFixed::Default, None);
        base.set_min_exclusive("0".to_string(), FacetFixed::Default, None);

        let result = base.merge_with_base(&FacetSet::new());
        assert!(result.is_err());
    }

    #[test]
    fn test_consistency_fraction_greater_than_total() {
        let mut base = FacetSet::new();
        base.set_total_digits(3, FacetFixed::Default, None);
        base.set_fraction_digits(5, FacetFixed::Default, None);

        let result = base.merge_with_base(&FacetSet::new());
        assert!(result.is_err());
    }

    // =========================================================================
    // FacetKind tests
    // =========================================================================

    #[test]
    fn test_facet_kind_from_name() {
        assert_eq!(FacetKind::from_name("length"), Some(FacetKind::Length));
        assert_eq!(
            FacetKind::from_name("minLength"),
            Some(FacetKind::MinLength)
        );
        assert_eq!(FacetKind::from_name("pattern"), Some(FacetKind::Pattern));
        assert_eq!(FacetKind::from_name("unknown"), None);
    }

    #[test]
    fn test_facet_kind_name_roundtrip() {
        let kinds = [
            FacetKind::Length,
            FacetKind::MinLength,
            FacetKind::MaxLength,
            FacetKind::Pattern,
            FacetKind::Enumeration,
            FacetKind::Whitespace,
            FacetKind::MinInclusive,
            FacetKind::MaxInclusive,
            FacetKind::MinExclusive,
            FacetKind::MaxExclusive,
            FacetKind::TotalDigits,
            FacetKind::FractionDigits,
            FacetKind::ExplicitTimezone,
            FacetKind::Assertion,
        ];

        for kind in kinds {
            let name = kind.name();
            assert_eq!(FacetKind::from_name(name), Some(kind));
        }
    }

    // =========================================================================
    // XSD pattern to Rust conversion tests (XSD 1.0 path only)
    // =========================================================================

    #[cfg(not(feature = "xsd11"))]
    #[test]
    fn test_xsd_pattern_anchoring() {
        let rust = convert_xml_pattern("abc", ConvertOptions::xsd());
        assert!(rust.starts_with('^'));
        assert!(rust.ends_with('$'));
    }

    #[cfg(not(feature = "xsd11"))]
    #[test]
    fn test_xsd_pattern_initial_name_char() {
        let rust = convert_xml_pattern(r"\i", ConvertOptions::xsd());
        assert!(rust.contains("[A-Za-z_:]"));
    }

    #[cfg(not(feature = "xsd11"))]
    #[test]
    fn test_xsd_pattern_name_char() {
        let rust = convert_xml_pattern(r"\c", ConvertOptions::xsd());
        // The hyphen is escaped in the character class
        assert!(rust.contains(r"[A-Za-z0-9._:\-]"));
    }

    #[cfg(not(feature = "xsd11"))]
    #[test]
    fn test_xsd_pattern_standard_escapes() {
        let rust = convert_xml_pattern(r"\d+\s*", ConvertOptions::xsd());
        assert!(rust.contains(r"\d"));
        assert!(rust.contains(r"\s"));
    }
}