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
//! Structural validation rules for XSD elements
//!
//! This module provides validation functions for XSD structural constraints
//! that cannot be expressed in the frame's `allows()` method. These include:
//!
//! - **Mutually exclusive attributes**: e.g., `name` XOR `ref` on elements
//! - **Dependent attributes**: e.g., `keyref` requires `refer`
//! - **Prohibited combinations**: e.g., top-level element cannot have `minOccurs`
//! - **XSD version gates**: e.g., `xs:assert` requires XSD 1.1
//!
//! # XSD Structural Constraints
//!
//! Per W3C XSD 1.0 specification:
//!
//! | Element | Constraint |
//! |---------|------------|
//! | element (top) | Must have `name`, must not have `ref`/`minOccurs`/`maxOccurs` |
//! | element (local) | Must have exactly one of `name` or `ref` |
//! | attribute (top) | Must have `name`, must not have `ref`/`use` |
//! | attribute (local) | Must have exactly one of `name` or `ref` |
//! | simpleType | `name` required at top level, prohibited in local context |
//! | complexType | `name` required at top level, prohibited in local context |
//! | restriction | Must have `base` XOR inline type |
//! | extension | Must have `base` attribute |
//! | key/unique | Must have `name` attribute |
//! | keyref | Must have `name` and `refer` attributes |
//! | list | Must have `itemType` XOR inline simpleType |
//! | union | Must have `memberTypes` XOR inline simpleTypes |

use crate::error::{SchemaError, SchemaResult};
use crate::namespace::{is_ncname, NameTable};
use crate::parser::attrs::AttributeMap;
use crate::parser::location::SourceRef;
use crate::schema::XsdVersion;
use crate::types::facets::{normalize_whitespace, WhitespaceMode};

/// Apply XSD whitespace=collapse to an attribute value before NCName/QName validation.
/// XSD attribute types like xs:NCName have whiteSpace=collapse semantics — leading,
/// trailing, and runs of internal whitespace are normalized away before the value
/// is interpreted lexically.
fn collapsed(value: &str) -> String {
    normalize_whitespace(value, WhitespaceMode::Collapse)
}

/// Validation context for structural checks
#[derive(Debug, Clone)]
pub struct ValidationContext {
    /// XSD version mode (1.0 or 1.1)
    pub xsd_version: XsdVersion,
    /// Whether this is a top-level (global) declaration
    pub is_top_level: bool,
    /// Whether this declaration has a `<complexType>` lexical ancestor.
    /// Per src-element §3.3.3 / src-attribute §3.2.3, a local declaration
    /// may carry `targetNamespace` only when it has a complexType ancestor.
    pub inside_complex_type: bool,
    /// Source reference for error reporting
    pub source: Option<SourceRef>,
}

impl Default for ValidationContext {
    fn default() -> Self {
        Self {
            xsd_version: XsdVersion::V1_0,
            is_top_level: false,
            inside_complex_type: false,
            source: None,
        }
    }
}

impl ValidationContext {
    /// Create a new validation context
    pub fn new(xsd_version: XsdVersion, is_top_level: bool) -> Self {
        Self {
            xsd_version,
            is_top_level,
            inside_complex_type: false,
            source: None,
        }
    }

    /// Create a context with source reference
    pub fn with_source(mut self, source: Option<SourceRef>) -> Self {
        self.source = source;
        self
    }
}

// ============================================================================
// Element Declaration Validation
// ============================================================================

/// Validate element declaration structural constraints
///
/// Top-level elements:
/// - Must have `name` attribute
/// - Must NOT have `ref`, `minOccurs`, `maxOccurs`, or `form` attributes
///
/// Local elements:
/// - Must have exactly one of `name` OR `ref`
/// - If `ref` is present, type/default/fixed/nillable/block/final are prohibited
pub fn validate_element_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    // src-element.1: the name must be a valid NCName.
    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-element",
                format!("Element 'name' value '{}' is not a valid NCName", name_val),
                None,
            ));
        }
    }

    if ctx.is_top_level {
        // Top-level element validation
        if !has_name {
            return Err(SchemaError::structural(
                "src-element",
                "Top-level element declaration must have 'name' attribute",
                None,
            ));
        }

        if has_ref {
            return Err(SchemaError::structural(
                "src-element",
                "Top-level element declaration cannot have 'ref' attribute",
                None,
            ));
        }

        // Prohibited attributes for top-level. `targetNamespace` is only
        // allowed on local declarations inside a `<complexType>` ancestor
        // (src-element §3.3.3 clause 4).
        for prohibited in &["minOccurs", "maxOccurs", "form", "targetNamespace"] {
            if attrs.get_value_by_name(name_table, prohibited).is_some() {
                return Err(SchemaError::structural(
                    "src-element",
                    format!(
                        "Top-level element declaration cannot have '{}' attribute",
                        prohibited
                    ),
                    None,
                ));
            }
        }
    } else {
        // Local element validation
        if has_name && has_ref {
            return Err(SchemaError::structural(
                "src-element",
                "Local element cannot have both 'name' and 'ref' attributes",
                None,
            ));
        }

        if !has_name && !has_ref {
            return Err(SchemaError::structural(
                "src-element",
                "Local element must have either 'name' or 'ref' attribute",
                None,
            ));
        }

        // If ref is present, certain attributes are prohibited.
        // `targetNamespace` is forbidden on element refs because the
        // referenced declaration already determines the namespace.
        if has_ref {
            let ref_prohibited = [
                "type",
                "default",
                "fixed",
                "nillable",
                "block",
                "final",
                "form",
                "targetNamespace",
            ];
            for prohibited in &ref_prohibited {
                if attrs.get_value_by_name(name_table, prohibited).is_some() {
                    return Err(SchemaError::structural(
                        "src-element",
                        format!("Element reference cannot have '{}' attribute", prohibited),
                        None,
                    ));
                }
            }
        }

        // src-element clause 3: `final`, `abstract`, `substitutionGroup` are
        // restricted to global declarations.
        for prohibited in &["final", "abstract", "substitutionGroup"] {
            if attrs.get_value_by_name(name_table, prohibited).is_some() {
                return Err(SchemaError::structural(
                    "src-element",
                    format!(
                        "Local element declaration cannot have '{}' attribute",
                        prohibited
                    ),
                    None,
                ));
            }
        }

        // src-element §3.3.3 clauses 3.2.2 / 4: `targetNamespace` may only
        // appear on a local element when (a) `form` is absent and (b) there
        // is a `<complexType>` lexical ancestor.
        let has_target_ns = attrs
            .get_value_by_name(name_table, "targetNamespace")
            .is_some();
        if has_target_ns {
            let has_form = attrs.get_value_by_name(name_table, "form").is_some();
            if has_form {
                return Err(SchemaError::structural(
                    "src-element",
                    "Local element with 'targetNamespace' cannot also have 'form' \
                     (src-element §3.3.3 clause 3.2.2)",
                    None,
                ));
            }
            if !ctx.inside_complex_type {
                return Err(SchemaError::structural(
                    "src-element",
                    "Local element with 'targetNamespace' must have a <complexType> \
                     lexical ancestor (src-element §3.3.3 clause 4)",
                    None,
                ));
            }
        }
    }

    // Validate default XOR fixed
    let has_default = attrs.get_value_by_name(name_table, "default").is_some();
    let has_fixed = attrs.get_value_by_name(name_table, "fixed").is_some();
    if has_default && has_fixed {
        return Err(SchemaError::structural(
            "cos-valid-default",
            "Element cannot have both 'default' and 'fixed' attributes",
            None,
        ));
    }

    // §3.3.2 element XML representation: `final` allows only `extension|restriction|#all`.
    // (Substitution is permitted in `block`, but NOT `final`.)
    if let Some(final_val) = attrs.get_value_by_name(name_table, "final") {
        validate_derivation_set_tokens(
            final_val,
            &["extension", "restriction"],
            "final",
            "element",
        )?;
    }
    // §3.3.2 element/@block allows `extension|restriction|substitution|#all`.
    if let Some(block_val) = attrs.get_value_by_name(name_table, "block") {
        validate_derivation_set_tokens(
            block_val,
            &["extension", "restriction", "substitution"],
            "block",
            "element",
        )?;
    }

    Ok(())
}

/// Validate that a `block`/`final`-style attribute value contains only the
/// derivation tokens permitted in the given context (plus `#all`).
fn validate_derivation_set_tokens(
    value: &str,
    allowed: &[&str],
    attr: &str,
    elem: &str,
) -> SchemaResult<()> {
    let trimmed = value.trim();
    if trimmed == "#all" {
        return Ok(());
    }
    for token in trimmed.split_whitespace() {
        if !allowed.contains(&token) {
            return Err(SchemaError::structural(
                "sch-props-correct",
                format!(
                    "'{}' on '{}' does not allow derivation method '{}'",
                    attr, elem, token
                ),
                None,
            ));
        }
    }
    Ok(())
}

// ============================================================================
// Attribute Declaration Validation
// ============================================================================

/// Validate attribute declaration structural constraints
///
/// Top-level attributes:
/// - Must have `name` attribute
/// - Must NOT have `ref`, `use`, or `form` attributes
///
/// Local attributes:
/// - Must have exactly one of `name` OR `ref`
/// - If `ref` is present, type/form are prohibited (src-attribute.3.2)
/// - `default` and `fixed` ARE allowed on refs (they set the attribute use's value constraint)
pub fn validate_attribute_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    // src-attribute.1 / src-element.1: the name must be a valid NCName.
    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        let collapsed_name = collapsed(name_val);
        if !is_ncname(&collapsed_name) {
            return Err(SchemaError::structural(
                "src-attribute",
                format!(
                    "Attribute 'name' value '{}' is not a valid NCName",
                    name_val
                ),
                None,
            ));
        }
        // no-xmlns (§3.2.6.2): attribute declarations must not use the local
        // name "xmlns".
        if collapsed_name == "xmlns" {
            return Err(SchemaError::structural(
                "no-xmlns",
                "Attribute declaration name must not be 'xmlns'",
                None,
            ));
        }
    }

    if ctx.is_top_level {
        // Top-level attribute validation
        if !has_name {
            return Err(SchemaError::structural(
                "src-attribute",
                "Top-level attribute declaration must have 'name' attribute",
                None,
            ));
        }

        if has_ref {
            return Err(SchemaError::structural(
                "src-attribute",
                "Top-level attribute declaration cannot have 'ref' attribute",
                None,
            ));
        }

        // Prohibited attributes for top-level. `targetNamespace` is only
        // allowed on local declarations inside a `<complexType>` ancestor
        // (src-attribute §3.2.3 clause 6).
        for prohibited in &["use", "form", "targetNamespace"] {
            if attrs.get_value_by_name(name_table, prohibited).is_some() {
                return Err(SchemaError::structural(
                    "src-attribute",
                    format!(
                        "Top-level attribute declaration cannot have '{}' attribute",
                        prohibited
                    ),
                    None,
                ));
            }
        }
    } else {
        // Local attribute validation
        if has_name && has_ref {
            return Err(SchemaError::structural(
                "src-attribute",
                "Local attribute cannot have both 'name' and 'ref' attributes",
                None,
            ));
        }

        if !has_name && !has_ref {
            return Err(SchemaError::structural(
                "src-attribute",
                "Local attribute must have either 'name' or 'ref' attribute",
                None,
            ));
        }

        // src-attribute.3.2: If ref is present, <simpleType>, form and type must be absent.
        // Note: default and fixed ARE allowed on attribute references — they set the
        // attribute use's value constraint, overriding the referenced declaration's.
        // `targetNamespace` is also forbidden on attribute refs because the referenced
        // declaration determines the namespace.
        if has_ref {
            for prohibited in &["type", "form", "targetNamespace"] {
                if attrs.get_value_by_name(name_table, prohibited).is_some() {
                    return Err(SchemaError::structural(
                        "src-attribute",
                        format!("Attribute reference cannot have '{}' attribute", prohibited),
                        None,
                    ));
                }
            }
        }

        // src-attribute §3.2.3 clauses 6.2 / 6: `targetNamespace` may only
        // appear on a local attribute when (a) `form` is absent and (b)
        // there is a `<complexType>` lexical ancestor.
        let has_target_ns = attrs
            .get_value_by_name(name_table, "targetNamespace")
            .is_some();
        if has_target_ns {
            let has_form = attrs.get_value_by_name(name_table, "form").is_some();
            if has_form {
                return Err(SchemaError::structural(
                    "src-attribute",
                    "Local attribute with 'targetNamespace' cannot also have 'form' \
                     (src-attribute §3.2.3 clause 6.2)",
                    None,
                ));
            }
            if !ctx.inside_complex_type {
                return Err(SchemaError::structural(
                    "src-attribute",
                    "Local attribute with 'targetNamespace' must have a <complexType> \
                     lexical ancestor (src-attribute §3.2.3 clause 6)",
                    None,
                ));
            }
        }
    }

    // Validate default XOR fixed
    let has_default = attrs.get_value_by_name(name_table, "default").is_some();
    let has_fixed = attrs.get_value_by_name(name_table, "fixed").is_some();
    if has_default && has_fixed {
        return Err(SchemaError::structural(
            "cos-valid-default",
            "Attribute cannot have both 'default' and 'fixed' attributes",
            None,
        ));
    }

    // src-attribute §3.2.3 clause 2: If default and use are both present, use must be "optional".
    if has_default {
        if let Some(use_val) = attrs.get_value_by_name(name_table, "use") {
            if use_val != "optional" {
                return Err(SchemaError::structural(
                    "src-attribute",
                    format!(
                        "Attribute with 'default' must have use='optional' (got '{}')",
                        use_val
                    ),
                    None,
                ));
            }
        }
    }

    // Validate use="prohibited" conflicts
    if let Some(use_val) = attrs.get_value_by_name(name_table, "use") {
        if use_val == "prohibited" {
            // src-attribute §3.2.3 clause 5: use="prohibited" + fixed is only an error in XSD 1.1.
            // In XSD 1.0 the combination is syntactically odd but not explicitly forbidden.
            if has_fixed && ctx.xsd_version == XsdVersion::V1_1 {
                return Err(SchemaError::structural(
                    "src-attribute",
                    "Prohibited attribute cannot have 'fixed' attribute",
                    None,
                ));
            }
        }
    }

    Ok(())
}

// ============================================================================
// Type Definition Validation
// ============================================================================

/// Validate simple type definition structure
///
/// - Top-level: `name` required
/// - Local (inline): `name` prohibited
/// - Must have exactly one of: restriction, list, or union child
pub fn validate_simple_type_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();

    if ctx.is_top_level && !has_name {
        return Err(SchemaError::structural(
            "src-simple-type",
            "Top-level simpleType must have 'name' attribute",
            None,
        ));
    }

    if !ctx.is_top_level && has_name {
        return Err(SchemaError::structural(
            "src-simple-type",
            "Inline simpleType cannot have 'name' attribute",
            None,
        ));
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-simple-type",
                format!(
                    "simpleType 'name' value '{}' is not a valid NCName",
                    name_val
                ),
                None,
            ));
        }
    }

    // §3.14.2 simpleType/@final allows `restriction|list|union|extension|#all`.
    if let Some(final_val) = attrs.get_value_by_name(name_table, "final") {
        validate_derivation_set_tokens(
            final_val,
            &["restriction", "list", "union", "extension"],
            "final",
            "simpleType",
        )?;
    }

    Ok(())
}

/// Validate complex type definition structure
///
/// - Top-level: `name` required
/// - Local (inline): `name` prohibited
pub fn validate_complex_type_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();

    if ctx.is_top_level && !has_name {
        return Err(SchemaError::structural(
            "src-ct",
            "Top-level complexType must have 'name' attribute",
            None,
        ));
    }

    if !ctx.is_top_level && has_name {
        return Err(SchemaError::structural(
            "src-ct",
            "Inline complexType cannot have 'name' attribute",
            None,
        ));
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-ct",
                format!(
                    "complexType 'name' value '{}' is not a valid NCName",
                    name_val
                ),
                None,
            ));
        }
    }

    // §3.4.2 complexType/@final and @block allow `extension|restriction|#all`.
    if let Some(final_val) = attrs.get_value_by_name(name_table, "final") {
        validate_derivation_set_tokens(
            final_val,
            &["extension", "restriction"],
            "final",
            "complexType",
        )?;
    }
    if let Some(block_val) = attrs.get_value_by_name(name_table, "block") {
        validate_derivation_set_tokens(
            block_val,
            &["extension", "restriction"],
            "block",
            "complexType",
        )?;
    }

    Ok(())
}

// ============================================================================
// Derivation Validation
// ============================================================================

/// Validate restriction element structure
///
/// - Must have `base` attribute XOR inline type definition
pub fn validate_restriction_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    has_inline_type: bool,
) -> SchemaResult<()> {
    let has_base = attrs.get_value_by_name(name_table, "base").is_some();

    if has_base && has_inline_type {
        return Err(SchemaError::structural(
            "src-restriction-base-or-simpleType",
            "Restriction cannot have both 'base' attribute and inline type",
            None,
        ));
    }

    // Note: In simple type restriction, base is required unless inline type exists
    // This validation may need to be context-specific

    Ok(())
}

/// Validate extension element structure
///
/// - Must have `base` attribute
pub fn validate_extension_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
) -> SchemaResult<()> {
    let has_base = attrs.get_value_by_name(name_table, "base").is_some();

    if !has_base {
        return Err(SchemaError::structural(
            "src-ct",
            "Extension must have 'base' attribute",
            None,
        ));
    }

    Ok(())
}

// ============================================================================
// List and Union Validation
// ============================================================================

/// Validate list element structure
///
/// - Must have `itemType` attribute XOR inline simpleType child
pub fn validate_list_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    has_inline_type: bool,
) -> SchemaResult<()> {
    let has_item_type = attrs.get_value_by_name(name_table, "itemType").is_some();

    if has_item_type && has_inline_type {
        return Err(SchemaError::structural(
            "src-list-itemType-or-simpleType",
            "List cannot have both 'itemType' attribute and inline simpleType",
            None,
        ));
    }

    if !has_item_type && !has_inline_type {
        return Err(SchemaError::structural(
            "src-list-itemType-or-simpleType",
            "List must have either 'itemType' attribute or inline simpleType",
            None,
        ));
    }

    Ok(())
}

/// Validate union element structure
///
/// - Must have `memberTypes` attribute and/or inline simpleType children
pub fn validate_union_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    has_inline_types: bool,
) -> SchemaResult<()> {
    let has_member_types = attrs.get_value_by_name(name_table, "memberTypes").is_some();

    if !has_member_types && !has_inline_types {
        return Err(SchemaError::structural(
            "src-union-memberTypes-or-simpleTypes",
            "Union must have 'memberTypes' attribute or inline simpleType children",
            None,
        ));
    }

    Ok(())
}

// ============================================================================
// Identity Constraint Validation
// ============================================================================

/// Validate key/unique element structure
///
/// - Must have `name` attribute
/// - Child requirements (selector/field) are validated when the frame finishes
pub fn validate_key_unique_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    // §3.11.6 clause 1: one of @name or @ref must be present (but not both)
    if !has_name && !has_ref {
        return Err(SchemaError::structural(
            "src-identity-constraint",
            "Identity constraint (key/unique) must have 'name' or 'ref' attribute",
            None,
        ));
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-identity-constraint",
                format!(
                    "identity constraint 'name' value '{}' is not a valid NCName",
                    name_val
                ),
                None,
            ));
        }
    }

    Ok(())
}

/// Validate keyref element structure
///
/// - Must have `name` or `ref` attribute
/// - `refer` is required when `name` is present
/// - Child requirements (selector/field) are validated when the frame finishes
pub fn validate_keyref_structure(attrs: &AttributeMap, name_table: &NameTable) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_refer = attrs.get_value_by_name(name_table, "refer").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    // §3.11.6 clause 1: one of @name or @ref must be present
    if !has_name && !has_ref {
        return Err(SchemaError::structural(
            "src-identity-constraint",
            "Keyref must have 'name' or 'ref' attribute",
            None,
        ));
    }

    // §3.11.6 clause 3: @refer required when @name is present
    if has_name && !has_refer {
        return Err(SchemaError::structural(
            "src-identity-constraint",
            "Keyref must have 'refer' attribute",
            None,
        ));
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-identity-constraint",
                format!("keyref 'name' value '{}' is not a valid NCName", name_val),
                None,
            ));
        }
    }

    Ok(())
}

// ============================================================================
// Group Validation
// ============================================================================

/// Validate model group (group) element structure
///
/// - Top-level: `name` required
/// - Reference: `ref` required, `name` prohibited
pub fn validate_group_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    if ctx.is_top_level {
        if !has_name {
            return Err(SchemaError::structural(
                "mgd-props-correct",
                "Top-level group must have 'name' attribute",
                None,
            ));
        }
        if has_ref {
            return Err(SchemaError::structural(
                "mgd-props-correct",
                "Top-level group cannot have 'ref' attribute",
                None,
            ));
        }
        // Top-level (named) group has no minOccurs/maxOccurs in its XML representation.
        for prohibited in &["minOccurs", "maxOccurs"] {
            if attrs.get_value_by_name(name_table, prohibited).is_some() {
                return Err(SchemaError::structural(
                    "mgd-props-correct",
                    format!("Top-level group cannot have '{}' attribute", prohibited),
                    None,
                ));
            }
        }
    } else {
        // Non-top-level group: only `ref` is allowed; `name` is prohibited
        // (XML Representation of <group>: ref form has no `name`).
        if has_name {
            return Err(SchemaError::structural(
                "mgd-props-correct",
                "Non-top-level group must use 'ref', not 'name'",
                None,
            ));
        }
        if !has_ref {
            return Err(SchemaError::structural(
                "mgd-props-correct",
                "Non-top-level group must have 'ref' attribute",
                None,
            ));
        }
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "mgd-props-correct",
                format!("group 'name' value '{}' is not a valid NCName", name_val),
                None,
            ));
        }
    }

    Ok(())
}

/// Validate attribute group element structure
///
/// - Top-level: `name` required
/// - Reference: `ref` required, `name` prohibited
pub fn validate_attribute_group_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_ref = attrs.get_value_by_name(name_table, "ref").is_some();

    if ctx.is_top_level {
        if !has_name {
            return Err(SchemaError::structural(
                "src-attribute_group",
                "Top-level attributeGroup must have 'name' attribute",
                None,
            ));
        }
        if has_ref {
            return Err(SchemaError::structural(
                "src-attribute_group",
                "Top-level attributeGroup cannot have 'ref' attribute",
                None,
            ));
        }
    } else {
        // Non-top-level attributeGroup: only `ref` is allowed; `name` is prohibited
        // (XML Representation of <attributeGroup>: ref form has no `name`).
        if has_name {
            return Err(SchemaError::structural(
                "src-attribute_group",
                "Non-top-level attributeGroup must use 'ref', not 'name'",
                None,
            ));
        }
        if !has_ref {
            return Err(SchemaError::structural(
                "src-attribute_group",
                "Non-top-level attributeGroup must have 'ref' attribute",
                None,
            ));
        }
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "src-attribute_group",
                format!(
                    "attributeGroup 'name' value '{}' is not a valid NCName",
                    name_val
                ),
                None,
            ));
        }
    }

    Ok(())
}

// ============================================================================
// XSD 1.1 Feature Gates
// ============================================================================

/// XSD 1.1 element names that are not allowed in XSD 1.0 mode
pub const XSD_1_1_ELEMENTS: &[&str] = &[
    "assert",
    "assertion",
    "alternative",
    "openContent",
    "defaultOpenContent",
    "override",
    "explicitTimezone",
];

/// XSD 1.1 attribute names that are not allowed in XSD 1.0 mode
pub const XSD_1_1_ATTRIBUTES: &[&str] = &[
    "targetNamespace",        // on element/attribute (local)
    "notNamespace",           // on any/anyAttribute
    "notQName",               // on any/anyAttribute
    "inheritable",            // on attribute
    "defaultAttributes",      // on schema
    "defaultAttributesApply", // on complexType
    "xpathDefaultNamespace",  // on schema/type definitions
];

/// Validate that an element is allowed in the current XSD version
pub fn validate_xsd_version_element(
    element_name: &str,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    if ctx.xsd_version == XsdVersion::V1_0 && XSD_1_1_ELEMENTS.contains(&element_name) {
        return Err(SchemaError::feature(
            format!(
                "Element '{}' requires XSD 1.1 but schema is in XSD 1.0 mode",
                element_name
            ),
            None,
        ));
    }
    Ok(())
}

/// Validate that an attribute is allowed in the current XSD version
pub fn validate_xsd_version_attribute(
    attr_name: &str,
    element_name: &str,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    if ctx.xsd_version == XsdVersion::V1_0 {
        // Some XSD 1.1 attributes are context-specific
        let is_xsd_1_1_attr = match (element_name, attr_name) {
            ("element", "targetNamespace") => true,
            ("attribute", "targetNamespace") => true,
            ("attribute", "inheritable") => true,
            ("complexType", "defaultAttributesApply") => true,
            ("complexType", "xpathDefaultNamespace") => true,
            ("any", "notNamespace") | ("any", "notQName") => true,
            ("anyAttribute", "notNamespace") | ("anyAttribute", "notQName") => true,
            ("schema", "defaultAttributes") => true,
            ("schema", "xpathDefaultNamespace") => true,
            ("selector", "xpathDefaultNamespace") => true,
            ("field", "xpathDefaultNamespace") => true,
            ("unique", "ref") | ("key", "ref") | ("keyref", "ref") => true,
            // targetNamespace on schema is valid in XSD 1.0
            ("schema", "targetNamespace") => false,
            _ => XSD_1_1_ATTRIBUTES.contains(&attr_name),
        };

        if is_xsd_1_1_attr {
            return Err(SchemaError::feature(
                format!(
                    "Attribute '{}' on '{}' requires XSD 1.1 but schema is in XSD 1.0 mode",
                    attr_name, element_name
                ),
                None,
            ));
        }
    }
    Ok(())
}

// ============================================================================
// Notation Validation
// ============================================================================

/// Validate notation declaration structure
///
/// - Must have `name` attribute
/// - Must have `public` attribute (XSD 1.0) or `public` or `system` (XSD 1.1)
pub fn validate_notation_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
    ctx: &ValidationContext,
) -> SchemaResult<()> {
    let has_name = attrs.get_value_by_name(name_table, "name").is_some();
    let has_public = attrs.get_value_by_name(name_table, "public").is_some();
    let has_system = attrs.get_value_by_name(name_table, "system").is_some();

    if !has_name {
        return Err(SchemaError::structural(
            "n-props-correct",
            "Notation must have 'name' attribute",
            None,
        ));
    }

    if let Some(name_val) = attrs.get_value_by_name(name_table, "name") {
        if !is_ncname(&collapsed(name_val)) {
            return Err(SchemaError::structural(
                "n-props-correct",
                format!("notation 'name' value '{}' is not a valid NCName", name_val),
                None,
            ));
        }
    }

    match ctx.xsd_version {
        XsdVersion::V1_0 => {
            if !has_public {
                return Err(SchemaError::structural(
                    "n-props-correct",
                    "Notation must have 'public' attribute in XSD 1.0",
                    None,
                ));
            }
        }
        XsdVersion::V1_1 => {
            if !has_public && !has_system {
                return Err(SchemaError::structural(
                    "n-props-correct",
                    "Notation must have 'public' or 'system' attribute in XSD 1.1",
                    None,
                ));
            }
        }
    }

    Ok(())
}

// ============================================================================
// Include/Import/Redefine Validation
// ============================================================================

/// Validate include directive structure
///
/// - Must have `schemaLocation` attribute
pub fn validate_include_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
) -> SchemaResult<()> {
    let has_location = attrs
        .get_value_by_name(name_table, "schemaLocation")
        .is_some();

    if !has_location {
        return Err(SchemaError::structural(
            "src-include",
            "Include must have 'schemaLocation' attribute",
            None,
        ));
    }

    Ok(())
}

/// Validate import directive structure
///
/// - `schemaLocation` is optional
/// - `namespace`, when present, must not be the empty string (§4.2.6.2 / §4.2.3
///   src-import constraint 1.2 in XSD 1.1; §4.2.3 in XSD 1.0). Empty namespace is
///   forbidden because absent and "" denote different things in XSD.
pub fn validate_import_structure(attrs: &AttributeMap, name_table: &NameTable) -> SchemaResult<()> {
    if let Some(ns) = attrs.get_value_by_name(name_table, "namespace") {
        if ns.is_empty() {
            return Err(SchemaError::structural(
                "src-import",
                "xs:import 'namespace' must not be the empty string",
                None,
            ));
        }
    }
    Ok(())
}

/// Validate xs:schema document structure
///
/// - `targetNamespace`, when present, must not be the empty string
///   (Schema Representation Constraint: targetNamespace cannot be empty per
///   §3.1.6 / §3.1.5).
///
/// Note: schema `targetNamespace = XSI namespace` is technically reserved per
/// §3.16.2 but the MS suite includes both `valid` (`attKb018`) and `invalid`
/// (`attKb018a`) outcomes for the same schema. The narrower check —
/// rejecting individual attribute declarations in the XSI namespace — is
/// implemented in `validate_no_xsi_attribute_declarations` and that aligns
/// with both interpretations.
pub fn validate_schema_structure(attrs: &AttributeMap, name_table: &NameTable) -> SchemaResult<()> {
    if let Some(tns) = attrs.get_value_by_name(name_table, "targetNamespace") {
        if tns.is_empty() {
            return Err(SchemaError::structural(
                "sch-props-correct",
                "xs:schema 'targetNamespace' must not be the empty string",
                None,
            ));
        }
    }
    Ok(())
}

/// Validate redefine directive structure
///
/// - Must have `schemaLocation` attribute
pub fn validate_redefine_structure(
    attrs: &AttributeMap,
    name_table: &NameTable,
) -> SchemaResult<()> {
    let has_location = attrs
        .get_value_by_name(name_table, "schemaLocation")
        .is_some();

    if !has_location {
        return Err(SchemaError::structural(
            "src-redefine",
            "Redefine must have 'schemaLocation' attribute",
            None,
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::attrs::ParsedAttribute;

    fn make_attr_map(name_table: &mut NameTable, attrs: &[(&str, &str)]) -> AttributeMap {
        let parsed: Vec<ParsedAttribute> = attrs
            .iter()
            .map(|(name, value)| ParsedAttribute {
                namespace: None,
                local_name: name_table.add(name),
                prefix: None,
                value: value.to_string(),
                source: None,
            })
            .collect();
        AttributeMap::new(parsed)
    }

    #[test]
    fn test_element_top_level_valid() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("name", "myElement")]);
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);

        let result = validate_element_structure(&attrs, &name_table, &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_element_top_level_missing_name() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("type", "xs:string")]);
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);

        let result = validate_element_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_element_top_level_has_ref() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("name", "myElement"), ("ref", "other")]);
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);

        let result = validate_element_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_element_local_name_and_ref() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("name", "myElement"), ("ref", "other")]);
        let ctx = ValidationContext::new(XsdVersion::V1_0, false);

        let result = validate_element_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_element_default_and_fixed() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(
            &mut name_table,
            &[("name", "myElement"), ("default", "a"), ("fixed", "b")],
        );
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);

        let result = validate_element_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_attribute_prohibited_with_default() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(
            &mut name_table,
            &[("ref", "myAttr"), ("use", "prohibited"), ("default", "x")],
        );
        let ctx = ValidationContext::new(XsdVersion::V1_0, false);

        let result = validate_attribute_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_xsd_1_1_element_in_1_0_mode() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, false);
        let result = validate_xsd_version_element("assert", &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_xsd_1_1_element_in_1_1_mode() {
        let ctx = ValidationContext::new(XsdVersion::V1_1, false);
        let result = validate_xsd_version_element("assert", &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_keyref_requires_refer() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("name", "myKeyRef")]);

        let result = validate_keyref_structure(&attrs, &name_table);
        assert!(result.is_err());
    }

    #[test]
    fn test_keyref_with_refer() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("name", "myKeyRef"), ("refer", "myKey")]);

        let result = validate_keyref_structure(&attrs, &name_table);
        assert!(result.is_ok());
    }

    #[test]
    fn test_list_itemtype_and_inline() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[("itemType", "xs:string")]);

        // Has both itemType and inline type - should fail
        let result = validate_list_structure(&attrs, &name_table, true);
        assert!(result.is_err());
    }

    #[test]
    fn test_list_neither_itemtype_nor_inline() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[]);

        let result = validate_list_structure(&attrs, &name_table, false);
        assert!(result.is_err());
    }

    #[test]
    fn test_extension_requires_base() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(&mut name_table, &[]);

        let result = validate_extension_structure(&attrs, &name_table);
        assert!(result.is_err());
    }

    #[test]
    fn test_notation_requires_public_in_1_0() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(
            &mut name_table,
            &[("name", "myNotation"), ("system", "foo")],
        );
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);

        let result = validate_notation_structure(&attrs, &name_table, &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_notation_system_ok_in_1_1() {
        let mut name_table = NameTable::new();
        let attrs = make_attr_map(
            &mut name_table,
            &[("name", "myNotation"), ("system", "foo")],
        );
        let ctx = ValidationContext::new(XsdVersion::V1_1, true);

        let result = validate_notation_structure(&attrs, &name_table, &ctx);
        assert!(result.is_ok());
    }

    // --- xpathDefaultNamespace version gating tests ---

    #[test]
    fn test_xpath_default_ns_on_selector_rejected_in_1_0() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, false);
        let result = validate_xsd_version_attribute("xpathDefaultNamespace", "selector", &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_xpath_default_ns_on_field_rejected_in_1_0() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, false);
        let result = validate_xsd_version_attribute("xpathDefaultNamespace", "field", &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_xpath_default_ns_on_schema_rejected_in_1_0() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);
        let result = validate_xsd_version_attribute("xpathDefaultNamespace", "schema", &ctx);
        assert!(result.is_err());
    }

    #[test]
    fn test_target_namespace_on_schema_allowed_in_1_0() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);
        let result = validate_xsd_version_attribute("targetNamespace", "schema", &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_xsd_1_0_rejects_default_attributes_on_schema() {
        let ctx = ValidationContext::new(XsdVersion::V1_0, true);
        let result = validate_xsd_version_attribute("defaultAttributes", "schema", &ctx);
        assert!(result.is_err());

        // Allowed in XSD 1.1
        let ctx11 = ValidationContext::new(XsdVersion::V1_1, true);
        let result11 = validate_xsd_version_attribute("defaultAttributes", "schema", &ctx11);
        assert!(result11.is_ok());
    }

    #[test]
    fn test_xpath_default_ns_on_selector_allowed_in_1_1() {
        let ctx = ValidationContext::new(XsdVersion::V1_1, false);
        let result = validate_xsd_version_attribute("xpathDefaultNamespace", "selector", &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_xpath_default_ns_on_field_allowed_in_1_1() {
        let ctx = ValidationContext::new(XsdVersion::V1_1, false);
        let result = validate_xsd_version_attribute("xpathDefaultNamespace", "field", &ctx);
        assert!(result.is_ok());
    }
}