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
//! xs:redefine processing
//!
//! Redefine allows extending/restricting types and groups from an included schema.
//! The redefining component must:
//! - Have the same name as the original
//! - Reference itself as the base type (for type redefinitions)
//! - Reference itself within the group (for group redefinitions)
//!
//! # XSD 1.0 Constraints
//!
//! For simpleType/complexType redefinitions:
//! - The redefinition must derive from the original type by restriction or extension
//! - The base type reference must use the same name as the type being redefined (self-reference)
//!
//! For group/attributeGroup redefinitions:
//! - The redefinition must contain exactly one reference to the original group
//! - This reference is replaced with the original group's content

use crate::error::{SchemaError, SchemaResult};
use crate::ids::*;
use crate::parser::frames::{ParticleResult, ParticleTerm};
use crate::schema::composition::{
    record_provenance, redefined_action, ComponentIdentity, ComponentKey, ComponentKind,
};
use crate::schema::model::RedefineDirective;
use crate::schema::SchemaSet;

/// Apply a redefine directive to the schema set.
///
/// This replaces the original components with the redefined versions,
/// after validating the redefinition constraints.
///
/// Uses document-scoped lookup via `resolved_doc_id` when available,
/// falling back to global namespace table lookup for backward compatibility.
pub fn apply_redefine(
    schema_set: &mut SchemaSet,
    redefine: &RedefineDirective,
) -> SchemaResult<()> {
    let target_doc_id = redefine.resolved_doc_id;
    // The redefining document is the one that contains the xs:redefine element
    let redefining_doc_id = redefine.source.as_ref().map(|s| s.doc_id);

    for simple_key in &redefine.simple_types {
        apply_simple_type_redefine(schema_set, *simple_key, target_doc_id, redefining_doc_id)?;
    }

    for complex_key in &redefine.complex_types {
        apply_complex_type_redefine(schema_set, *complex_key, target_doc_id, redefining_doc_id)?;
    }

    for group_key in &redefine.groups {
        apply_model_group_redefine(schema_set, *group_key, target_doc_id, redefining_doc_id)?;
    }

    for attr_group_key in &redefine.attribute_groups {
        apply_attribute_group_redefine(
            schema_set,
            *attr_group_key,
            target_doc_id,
            redefining_doc_id,
        )?;
    }

    Ok(())
}

/// Apply a simple type redefinition.
fn apply_simple_type_redefine(
    schema_set: &mut SchemaSet,
    new_key: SimpleTypeKey,
    target_doc_id: Option<DocumentId>,
    redefining_doc_id: Option<DocumentId>,
) -> SchemaResult<()> {
    let new_type = schema_set
        .arenas
        .simple_types
        .get(new_key)
        .ok_or_else(|| SchemaError::internal("Redefine: new simple type not found"))?;

    let name = new_type.name.ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            "Redefined simple type must have a name",
            None,
        )
    })?;
    let namespace = new_type.target_namespace;

    // Kind-specific, document-scoped lookup; global fallback only when
    // resolved_doc_id is None (pre-loaded schemas without resolution).
    let original_key = match target_doc_id {
        Some(id) => schema_set
            .documents
            .get(id as usize)
            .and_then(|doc| doc.component_index.lookup_simple_type(namespace, name))
            .map(TypeKey::Simple),
        None => schema_set.lookup_type(namespace, name),
    }
    .ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            format!(
                "Original simple type '{}' not found for redefinition in {}",
                schema_set.name_table.resolve(name),
                target_doc_id
                    .and_then(|id| schema_set.documents.get(id as usize))
                    .map(|d| d.base_uri.as_str())
                    .unwrap_or("schema"),
            ),
            None,
        )
    })?;

    validate_self_derivation_simple(schema_set, new_key, name, namespace)?;

    // Store original type key for base-type redirection during resolution
    if let TypeKey::Simple(orig_key) = original_key {
        if let Some(st) = schema_set.arenas.simple_types.get_mut(new_key) {
            st.redefine_original = Some(orig_key);
        }
    }

    let ns_table = schema_set.get_or_create_namespace(namespace);
    ns_table.register_type(name, TypeKey::Simple(new_key));

    // Make the redefined type visible in the redefining document's
    // component_index so chained redefines can find it.
    if let Some(doc_id) = redefining_doc_id {
        if let Some(doc) = schema_set.documents.get_mut(doc_id as usize) {
            doc.component_index.insert(
                ComponentIdentity {
                    kind: ComponentKind::SimpleType,
                    name,
                    namespace,
                },
                ComponentKey::Type(TypeKey::Simple(new_key)),
            );
        }
    }

    record_provenance(
        &mut schema_set.effective_components,
        ComponentKey::Type(TypeKey::Simple(new_key)),
        ComponentKind::SimpleType,
        namespace,
        name,
        redefining_doc_id,
        redefined_action(
            redefining_doc_id,
            ComponentKind::SimpleType,
            name,
            namespace,
            target_doc_id,
        ),
    );

    Ok(())
}

/// Apply a complex type redefinition.
fn apply_complex_type_redefine(
    schema_set: &mut SchemaSet,
    new_key: ComplexTypeKey,
    target_doc_id: Option<DocumentId>,
    redefining_doc_id: Option<DocumentId>,
) -> SchemaResult<()> {
    let new_type = schema_set
        .arenas
        .complex_types
        .get(new_key)
        .ok_or_else(|| SchemaError::internal("Redefine: new complex type not found"))?;

    let name = new_type.name.ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            "Redefined complex type must have a name",
            None,
        )
    })?;
    let namespace = new_type.target_namespace;

    let original_key = match target_doc_id {
        Some(id) => schema_set
            .documents
            .get(id as usize)
            .and_then(|doc| doc.component_index.lookup_complex_type(namespace, name))
            .map(TypeKey::Complex),
        None => schema_set.lookup_type(namespace, name),
    }
    .ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            format!(
                "Original complex type '{}' not found for redefinition in {}",
                schema_set.name_table.resolve(name),
                target_doc_id
                    .and_then(|id| schema_set.documents.get(id as usize))
                    .map(|d| d.base_uri.as_str())
                    .unwrap_or("schema"),
            ),
            None,
        )
    })?;

    validate_self_derivation_complex(schema_set, new_key, name, namespace)?;

    // Store original type key for base-type redirection during resolution
    if let TypeKey::Complex(orig_key) = original_key {
        if let Some(ct) = schema_set.arenas.complex_types.get_mut(new_key) {
            ct.redefine_original = Some(orig_key);
        }
    }

    let ns_table = schema_set.get_or_create_namespace(namespace);
    ns_table.register_type(name, TypeKey::Complex(new_key));

    if let Some(doc_id) = redefining_doc_id {
        if let Some(doc) = schema_set.documents.get_mut(doc_id as usize) {
            doc.component_index.insert(
                ComponentIdentity {
                    kind: ComponentKind::ComplexType,
                    name,
                    namespace,
                },
                ComponentKey::Type(TypeKey::Complex(new_key)),
            );
        }
    }

    record_provenance(
        &mut schema_set.effective_components,
        ComponentKey::Type(TypeKey::Complex(new_key)),
        ComponentKind::ComplexType,
        namespace,
        name,
        redefining_doc_id,
        redefined_action(
            redefining_doc_id,
            ComponentKind::ComplexType,
            name,
            namespace,
            target_doc_id,
        ),
    );

    Ok(())
}

/// Apply a model group redefinition.
fn apply_model_group_redefine(
    schema_set: &mut SchemaSet,
    new_key: ModelGroupKey,
    target_doc_id: Option<DocumentId>,
    redefining_doc_id: Option<DocumentId>,
) -> SchemaResult<()> {
    let new_group = schema_set
        .arenas
        .model_groups
        .get(new_key)
        .ok_or_else(|| SchemaError::internal("Redefine: new model group not found"))?;

    let name = new_group.name.ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            "Redefined model group must have a name",
            None,
        )
    })?;
    let namespace = new_group.target_namespace;

    let original_key = match target_doc_id {
        Some(id) => schema_set
            .documents
            .get(id as usize)
            .and_then(|doc| doc.component_index.lookup_model_group(namespace, name)),
        None => schema_set.lookup_model_group(namespace, name),
    }
    .ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            format!(
                "Original group '{}' not found for redefinition in {}",
                schema_set.name_table.resolve(name),
                target_doc_id
                    .and_then(|id| schema_set.documents.get(id as usize))
                    .map(|d| d.base_uri.as_str())
                    .unwrap_or("schema"),
            ),
            None,
        )
    })?;

    let has_self_ref = validate_self_reference_group(schema_set, new_key, name)?;

    // Store original key so self-references can be redirected during resolution.
    // When the redefine has zero self-references, flag it for the deferred
    // §src-redefine 6.2.2 restriction check in `validate_all_derivations`.
    if let Some(group) = schema_set.arenas.model_groups.get_mut(new_key) {
        group.redefine_original = Some(original_key);
        group.redefine_requires_restriction_check = !has_self_ref;
    }

    let ns_table = schema_set.get_or_create_namespace(namespace);
    ns_table.register_model_group(name, new_key);

    if let Some(doc_id) = redefining_doc_id {
        if let Some(doc) = schema_set.documents.get_mut(doc_id as usize) {
            doc.component_index.insert(
                ComponentIdentity {
                    kind: ComponentKind::ModelGroup,
                    name,
                    namespace,
                },
                ComponentKey::ModelGroup(new_key),
            );
        }
    }

    record_provenance(
        &mut schema_set.effective_components,
        ComponentKey::ModelGroup(new_key),
        ComponentKind::ModelGroup,
        namespace,
        name,
        redefining_doc_id,
        redefined_action(
            redefining_doc_id,
            ComponentKind::ModelGroup,
            name,
            namespace,
            target_doc_id,
        ),
    );

    Ok(())
}

/// Apply an attribute group redefinition.
fn apply_attribute_group_redefine(
    schema_set: &mut SchemaSet,
    new_key: AttributeGroupKey,
    target_doc_id: Option<DocumentId>,
    redefining_doc_id: Option<DocumentId>,
) -> SchemaResult<()> {
    let new_group = schema_set
        .arenas
        .attribute_groups
        .get(new_key)
        .ok_or_else(|| SchemaError::internal("Redefine: new attribute group not found"))?;

    let name = new_group.name.ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            "Redefined attribute group must have a name",
            None,
        )
    })?;
    let namespace = new_group.target_namespace;

    let original_key = match target_doc_id {
        Some(id) => schema_set
            .documents
            .get(id as usize)
            .and_then(|doc| doc.component_index.lookup_attribute_group(namespace, name)),
        None => schema_set.lookup_attribute_group(namespace, name),
    }
    .ok_or_else(|| {
        SchemaError::structural(
            "src-redefine",
            format!(
                "Original attribute group '{}' not found for redefinition in {}",
                schema_set.name_table.resolve(name),
                target_doc_id
                    .and_then(|id| schema_set.documents.get(id as usize))
                    .map(|d| d.base_uri.as_str())
                    .unwrap_or("schema"),
            ),
            None,
        )
    })?;

    let has_self_ref = validate_self_reference_attribute_group(schema_set, new_key, name)?;

    // Store original key so self-references can be redirected during resolution.
    // When the redefine has zero self-references, flag it for the deferred
    // §src-redefine 7.2.2 restriction check in `validate_all_derivations`.
    if let Some(group) = schema_set.arenas.attribute_groups.get_mut(new_key) {
        group.redefine_original = Some(original_key);
        group.redefine_requires_restriction_check = !has_self_ref;
    }

    let ns_table = schema_set.get_or_create_namespace(namespace);
    ns_table.register_attribute_group(name, new_key);

    if let Some(doc_id) = redefining_doc_id {
        if let Some(doc) = schema_set.documents.get_mut(doc_id as usize) {
            doc.component_index.insert(
                ComponentIdentity {
                    kind: ComponentKind::AttributeGroup,
                    name,
                    namespace,
                },
                ComponentKey::AttributeGroup(new_key),
            );
        }
    }

    record_provenance(
        &mut schema_set.effective_components,
        ComponentKey::AttributeGroup(new_key),
        ComponentKind::AttributeGroup,
        namespace,
        name,
        redefining_doc_id,
        redefined_action(
            redefining_doc_id,
            ComponentKind::AttributeGroup,
            name,
            namespace,
            target_doc_id,
        ),
    );

    Ok(())
}

/// Validate that a simple type redefines itself (self-derivation constraint).
fn validate_self_derivation_simple(
    schema_set: &SchemaSet,
    type_key: SimpleTypeKey,
    expected_name: NameId,
    expected_namespace: Option<NameId>,
) -> SchemaResult<()> {
    use crate::parser::frames::TypeRefResult;

    let type_def = schema_set
        .arenas
        .simple_types
        .get(type_key)
        .ok_or_else(|| SchemaError::internal("Type not found"))?;

    // Check that base_type references the same name and namespace (self-reference).
    // Unprefixed QNames (namespace == None) are accepted — they resolve to the
    // target namespace during the reference-resolution phase.
    if let Some(TypeRefResult::QName(ref qname)) = type_def.base_type {
        if qname.local_name != expected_name {
            return Err(SchemaError::structural(
                "src-redefine",
                "Redefined simple type must derive from the original type (self-reference)",
                type_def
                    .source
                    .as_ref()
                    .and_then(|s| schema_set.source_maps.locate(s)),
            ));
        }
        // If the reference is explicitly namespace-qualified, it must match
        if let Some(ref_ns) = qname.namespace {
            if Some(ref_ns) != expected_namespace {
                return Err(SchemaError::structural(
                    "src-redefine",
                    "Redefined simple type base references a different namespace than the original",
                    type_def
                        .source
                        .as_ref()
                        .and_then(|s| schema_set.source_maps.locate(s)),
                ));
            }
        }
    } else {
        return Err(SchemaError::structural(
            "src-redefine",
            "Redefined simple type must have a base type reference",
            type_def
                .source
                .as_ref()
                .and_then(|s| schema_set.source_maps.locate(s)),
        ));
    }

    Ok(())
}

/// Validate that a complex type redefines itself (self-derivation constraint).
fn validate_self_derivation_complex(
    schema_set: &SchemaSet,
    type_key: ComplexTypeKey,
    expected_name: NameId,
    expected_namespace: Option<NameId>,
) -> SchemaResult<()> {
    use crate::parser::frames::TypeRefResult;

    let type_def = schema_set
        .arenas
        .complex_types
        .get(type_key)
        .ok_or_else(|| SchemaError::internal("Type not found"))?;

    // Check that base_type references the same name and namespace (self-reference).
    // Unprefixed QNames (namespace == None) are accepted — they resolve to the
    // target namespace during the reference-resolution phase.
    if let Some(TypeRefResult::QName(ref qname)) = type_def.base_type {
        if qname.local_name != expected_name {
            return Err(SchemaError::structural(
                "src-redefine",
                "Redefined complex type must derive from the original type (self-reference)",
                type_def
                    .source
                    .as_ref()
                    .and_then(|s| schema_set.source_maps.locate(s)),
            ));
        }
        // If the reference is explicitly namespace-qualified, it must match
        if let Some(ref_ns) = qname.namespace {
            if Some(ref_ns) != expected_namespace {
                return Err(SchemaError::structural(
                    "src-redefine",
                    "Redefined complex type base references a different namespace than the original",
                    type_def
                        .source
                        .as_ref()
                        .and_then(|s| schema_set.source_maps.locate(s)),
                ));
            }
        }
    } else {
        return Err(SchemaError::structural(
            "src-redefine",
            "Redefined complex type must have a base type reference",
            type_def
                .source
                .as_ref()
                .and_then(|s| schema_set.source_maps.locate(s)),
        ));
    }

    Ok(())
}

/// Scratch state for the §src-redefine 6.1 self-reference walker.
///
/// `count` is the only always-meaningful field. `min_occurs`/`max_occurs`
/// are the bounds of the most recently visited matching self-ref, and are
/// only meaningful when `count == 1` — §6.1.2 only constrains *the* one
/// self-referencing `<group ref>` in the valid case. When `count > 1`,
/// §6.1.1 already errors without consulting the bounds.
struct GroupSelfRefScan {
    count: u32,
    min_occurs: u32,
    max_occurs: Option<u32>,
}

/// Walk a particle list recursively to implement §src-redefine 6.1's
/// "among its contents at some level" scan (structures.html:13729-13741).
///
/// Descends through inline `<sequence>`/`<choice>`/`<all>` compositors,
/// stops at element particles (§6.1 element-ancestor exclusion), and does
/// not follow group references — this is a pre-resolution, purely
/// structural scan.
///
/// The walker mirrors the inline-compositor recursion shape from
/// `ParticleNormalizer::normalize_particle` in
/// `src/schema/derivation.rs`, but explicitly does **not** copy the
/// resolved-group follow-through in `normalize_group`: that post-resolution
/// code dives into a group ref's target, which would produce an incorrect
/// §6.1 interpretation here.
fn count_group_self_refs(
    particles: &[ParticleResult],
    expected_name: NameId,
    scan: &mut GroupSelfRefScan,
) {
    for particle in particles {
        if let ParticleTerm::Group(ref grp) = particle.term {
            match grp.ref_name {
                Some(ref ref_name) => {
                    // Syntactic group reference. Check for self-match;
                    // never recurse into its (empty-by-AST-invariant)
                    // particles vector.
                    if ref_name.local_name == expected_name {
                        scan.count += 1;
                        scan.min_occurs = particle.min_occurs;
                        scan.max_occurs = particle.max_occurs;
                    }
                }
                None => {
                    // Inline compositor (sequence/choice/all) — descend.
                    debug_assert!(
                        grp.name.is_none(),
                        "named group definition unexpectedly nested in a particle list"
                    );
                    count_group_self_refs(&grp.particles, expected_name, scan);
                }
            }
        }
        // ParticleTerm::Element — terminal per §6.1's
        // "does not have an <element> ancestor" exclusion. We intentionally
        // do NOT descend into ElementFrameResult.inline_type.
        // ParticleTerm::Any — terminal (no particles to scan).
    }
}

/// Validate that a redefining model group's self-reference structure is
/// consistent with §src-redefine clause 6
/// (`structures.html:13729-13752`, `#src-redefine`).
///
/// The scan is **recursive** through inline `<sequence>`/`<choice>`/`<all>`
/// compositors per §6.1's *"among its contents at some level"* wording,
/// and stops at any `<element>` ancestor per §6.1's element-ancestor
/// exclusion.
///
/// Returns `Ok(true)` when the redefine contains exactly one well-formed
/// self-reference (§6.1 with §6.1.1 + §6.1.2 satisfied), `Ok(false)` when
/// the redefine contains zero self-references (§6.2 — the caller must
/// schedule a deferred §6.2.2 restriction check), and `Err` for `>1`
/// self-references (§6.1.1 violation) or a single self-ref with
/// `minOccurs`/`maxOccurs != 1` (§6.1.2 violation).
fn validate_self_reference_group(
    schema_set: &SchemaSet,
    group_key: ModelGroupKey,
    expected_name: NameId,
) -> SchemaResult<bool> {
    let group = schema_set
        .arenas
        .model_groups
        .get(group_key)
        .ok_or_else(|| SchemaError::internal("Group not found"))?;

    let mut scan = GroupSelfRefScan {
        count: 0,
        min_occurs: 0,
        max_occurs: None,
    };
    count_group_self_refs(&group.particles, expected_name, &mut scan);

    match scan.count {
        // Clause 6.2 (src-redefine §6.2): the redefining group has no
        // self-reference. Clause 6.2.1 — that the name resolves in S2 — is
        // already enforced by the caller's component lookup against the
        // target document. Clause 6.2.2 — that the new model is a valid
        // restriction of the original — is enforced later by the deferred
        // `validate_all_redefine_group_restrictions` pass once reference
        // resolution is complete. Return `false` so the caller sets the
        // arena flag that schedules that pass.
        0 => Ok(false),
        // Clause 6.1: self-reference present.
        // Clause 6.1.2: minOccurs and maxOccurs must both be 1 on the
        // self-referencing `<group ref>` particle itself (the
        // `ParticleResult` whose `term` is `ParticleTerm::Group(ref)`),
        // not on any enclosing compositor.
        1 => {
            if scan.min_occurs != 1 || scan.max_occurs != Some(1) {
                Err(SchemaError::structural(
                    "src-redefine",
                    format!(
                        "Self-referencing group particle must have \
                         minOccurs=1 and maxOccurs=1, but found \
                         minOccurs={} maxOccurs={}",
                        scan.min_occurs,
                        scan.max_occurs
                            .map(|v| v.to_string())
                            .unwrap_or_else(|| "unbounded".to_string()),
                    ),
                    group
                        .source
                        .as_ref()
                        .and_then(|s| schema_set.source_maps.locate(s)),
                ))
            } else {
                Ok(true)
            }
        }
        _ => Err(SchemaError::structural(
            "src-redefine",
            format!(
                "Redefined group must contain at most one \
                 self-reference (found {})",
                scan.count,
            ),
            group
                .source
                .as_ref()
                .and_then(|s| schema_set.source_maps.locate(s)),
        )),
    }
}

/// Validate self-reference constraints for an attribute group redefine.
///
/// Clause 7.1: with self-reference — exactly one is allowed.
/// Clause 7.2: without self-reference — restriction of original (checked
/// later by `validate_all_redefine_attribute_group_restrictions`).
///
/// Returns `Ok(true)` when the redefine contains exactly one self-reference
/// (§7.1), `Ok(false)` when the redefine contains zero self-references and
/// the caller must schedule a deferred §7.2.2 restriction check. Errors
/// for >1 self-refs.
fn validate_self_reference_attribute_group(
    schema_set: &SchemaSet,
    group_key: AttributeGroupKey,
    expected_name: NameId,
) -> SchemaResult<bool> {
    let group = schema_set
        .arenas
        .attribute_groups
        .get(group_key)
        .ok_or_else(|| SchemaError::internal("Attribute group not found"))?;

    let mut self_refs = 0u32;
    for attr_group_ref in &group.attribute_groups {
        if attr_group_ref.local_name == expected_name {
            self_refs += 1;
        }
    }

    match self_refs {
        // Clause 7.2 (src-redefine §7.2): no self-reference. Clause 7.2.1
        // is enforced by the caller's component lookup; clause 7.2.2 (the
        // restriction check) is deferred to
        // `validate_all_redefine_attribute_group_restrictions` which runs
        // after reference resolution. Return `false` so the caller sets
        // the arena flag that schedules that pass.
        0 => Ok(false),
        // Clause 7.1: exactly one self-reference. Valid.
        1 => Ok(true),
        _ => Err(SchemaError::structural(
            "src-redefine",
            format!(
                "Redefined attribute group must contain at most one \
                 self-reference (found {})",
                self_refs,
            ),
            group
                .source
                .as_ref()
                .and_then(|s| schema_set.source_maps.locate(s)),
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::arenas::{AttributeGroupData, ModelGroupData};
    use crate::parser::frames::{
        Compositor, ElementFrameResult, ModelGroupDefResult, ParticleResult, ParticleTerm, QNameRef,
    };
    use crate::schema::composition::ComponentKind;
    use crate::schema::model::SchemaDocument;

    /// Helper: set up a schema set with a base document and a named model group.
    fn setup_model_group_redefine() -> (SchemaSet, ModelGroupKey, ModelGroupKey) {
        let mut schema_set = SchemaSet::new();

        // Create base document
        let base_doc_id = schema_set.documents.len() as u32;
        let base_doc = SchemaDocument::new(base_doc_id, "base.xsd".to_string());
        schema_set.documents.push(base_doc);

        let group_name = schema_set.name_table.add("personGroup");

        // Create original group with element "name"
        let name_elem = schema_set.name_table.add("name");
        let original_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![ParticleResult {
                term: ParticleTerm::Element(ElementFrameResult {
                    name: Some(name_elem),
                    ref_name: None,
                    target_namespace: None,
                    type_ref: None,
                    inline_type: None,
                    substitution_group: vec![],
                    default_value: None,
                    fixed_value: None,
                    nillable: false,
                    is_abstract: false,
                    min_occurs: 1,
                    max_occurs: Some(1),
                    block: None,
                    final_derivation: None,
                    form: None,
                    id: None,
                    alternatives: vec![],
                    identity_constraints: vec![],
                    identity_constraint_refs: vec![],
                    annotation: None,
                    source: None,
                }),
                min_occurs: 1,
                max_occurs: Some(1),
                source: None,
            }],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let original_key = schema_set.arenas.alloc_model_group(original_data);
        schema_set
            .get_or_create_namespace(None)
            .register_model_group(group_name, original_key);

        // Create redefining group with self-ref + element "age"
        let age_elem = schema_set.name_table.add("age");
        let new_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![
                // Self-reference
                ParticleResult {
                    term: ParticleTerm::Group(ModelGroupDefResult {
                        name: None,
                        ref_name: Some(QNameRef {
                            prefix: None,
                            local_name: group_name,
                            namespace: None,
                        }),
                        compositor: None,
                        particles: vec![],
                        min_occurs: 1,
                        max_occurs: Some(1),
                        id: None,
                        annotation: None,
                        source: None,
                    }),
                    min_occurs: 1,
                    max_occurs: Some(1),
                    source: None,
                },
                // New element
                ParticleResult {
                    term: ParticleTerm::Element(ElementFrameResult {
                        name: Some(age_elem),
                        ref_name: None,
                        target_namespace: None,
                        type_ref: None,
                        inline_type: None,
                        substitution_group: vec![],
                        default_value: None,
                        fixed_value: None,
                        nillable: false,
                        is_abstract: false,
                        min_occurs: 1,
                        max_occurs: Some(1),
                        block: None,
                        final_derivation: None,
                        form: None,
                        id: None,
                        alternatives: vec![],
                        identity_constraints: vec![],
                        identity_constraint_refs: vec![],
                        annotation: None,
                        source: None,
                    }),
                    min_occurs: 1,
                    max_occurs: Some(1),
                    source: None,
                },
            ],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let new_key = schema_set.arenas.alloc_model_group(new_data);

        (schema_set, original_key, new_key)
    }

    #[test]
    fn test_redefine_model_group_self_reference() {
        let (mut schema_set, original_key, new_key) = setup_model_group_redefine();

        // Apply redefine (no target doc — fallback to global lookup)
        let result = apply_model_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_ok(),
            "apply_model_group_redefine failed: {:?}",
            result.err()
        );

        // Verify redefine_original is set
        let group = schema_set.arenas.model_groups.get(new_key).unwrap();
        assert_eq!(
            group.redefine_original,
            Some(original_key),
            "redefine_original should point to the original group"
        );

        // Now resolve references and verify self-ref redirects to original
        let result = crate::schema::resolver::resolve_all_references(&mut schema_set);
        assert!(
            result.is_ok(),
            "resolve_all_references failed: {:?}",
            result.err()
        );

        let group = schema_set.arenas.model_groups.get(new_key).unwrap();
        // First particle is the group ref (self-reference → should resolve to original)
        match &group.resolved_particles[0] {
            crate::arenas::ResolvedParticleTerm::Group {
                resolved_ref: Some(key),
            } => {
                assert_eq!(
                    *key, original_key,
                    "Self-reference should resolve to the original group, not the new one"
                );
            }
            other => panic!("Expected Group particle with resolved_ref, got {:?}", other),
        }
    }

    #[test]
    fn test_redefine_attribute_group_self_reference() {
        let mut schema_set = SchemaSet::new();

        let group_name = schema_set.name_table.add("commonAttrs");

        // Create original attribute group
        let original_data = AttributeGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let original_key = schema_set.arenas.alloc_attribute_group(original_data);
        schema_set
            .get_or_create_namespace(None)
            .register_attribute_group(group_name, original_key);

        // Create redefining group with self-reference
        let new_data = AttributeGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            attributes: Vec::new(),
            attribute_groups: vec![QNameRef {
                prefix: None,
                local_name: group_name,
                namespace: None,
            }],
            attribute_wildcard: None,
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let new_key = schema_set.arenas.alloc_attribute_group(new_data);

        // Apply redefine
        let result = apply_attribute_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_ok(),
            "apply_attribute_group_redefine failed: {:?}",
            result.err()
        );

        // Verify redefine_original
        let group = schema_set.arenas.attribute_groups.get(new_key).unwrap();
        assert_eq!(group.redefine_original, Some(original_key));

        // Resolve references
        let result = crate::schema::resolver::resolve_all_references(&mut schema_set);
        assert!(
            result.is_ok(),
            "resolve_all_references failed: {:?}",
            result.err()
        );

        // Verify self-ref redirected to original
        let group = schema_set.arenas.attribute_groups.get(new_key).unwrap();
        assert_eq!(group.resolved_attribute_groups.len(), 1);
        assert_eq!(
            group.resolved_attribute_groups[0], original_key,
            "Self-reference should resolve to the original attribute group"
        );
    }

    #[test]
    fn test_provenance_note_redefined() {
        let mut schema_set = SchemaSet::new();

        // Create two documents for provenance tracking
        let base_doc_id = schema_set.documents.len() as u32;
        let base_doc = SchemaDocument::new(base_doc_id, "base.xsd".to_string());
        schema_set.documents.push(base_doc);

        let redefining_doc_id = schema_set.documents.len() as u32;
        let redefining_doc = SchemaDocument::new(redefining_doc_id, "main.xsd".to_string());
        schema_set.documents.push(redefining_doc);

        let group_name = schema_set.name_table.add("testGroup");

        // Record provenance as if a redefine occurred
        crate::schema::composition::record_provenance(
            &mut schema_set.effective_components,
            crate::schema::composition::ComponentKey::ModelGroup(
                // dummy key (not used for lookup)
                schema_set.arenas.alloc_model_group(ModelGroupData {
                    name: Some(group_name),
                    target_namespace: None,
                    ref_name: None,
                    compositor: Some(Compositor::Sequence),
                    particles: Vec::new(),
                    min_occurs: 1,
                    max_occurs: Some(1),
                    id: None,
                    annotation: None,
                    source: None,
                    resolved_ref: None,
                    resolved_particles: Vec::new(),
                    resolved_particle_types: Vec::new(),
                    resolved_particle_elements: Vec::new(),
                    redefine_original: None,
                    redefine_requires_restriction_check: false,
                }),
            ),
            ComponentKind::ModelGroup,
            None,
            group_name,
            Some(redefining_doc_id),
            crate::schema::composition::redefined_action(
                Some(redefining_doc_id),
                ComponentKind::ModelGroup,
                group_name,
                None,
                Some(base_doc_id),
            ),
        );

        let note = schema_set.format_provenance_note(ComponentKind::ModelGroup, None, group_name);
        assert!(
            note.contains("base.xsd"),
            "Provenance note should mention the original document: {}",
            note
        );
        assert!(
            note.contains("main.xsd"),
            "Provenance note should mention the redefining document: {}",
            note
        );
        assert!(
            note.contains("redefined"),
            "Provenance note should mention 'redefined': {}",
            note
        );
    }

    #[test]
    fn test_provenance_note_declared() {
        let schema_set = SchemaSet::new();
        let name = schema_set.name_table.get("string").unwrap();

        // No provenance recorded → empty string
        let note = schema_set.format_provenance_note(ComponentKind::SimpleType, None, name);
        assert!(
            note.is_empty(),
            "Provenance note for undeclared component should be empty, got: {}",
            note
        );
    }

    #[test]
    fn test_redefine_model_group_no_self_reference() {
        // Clause 6.2: a redefining group with NO self-reference is valid
        // (pure restriction of the original).
        let (mut schema_set, _original_key, _new_key) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");
        let age_elem = schema_set.name_table.add("age");

        // Create redefining group WITHOUT self-reference (just element "age")
        let new_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![ParticleResult {
                term: ParticleTerm::Element(ElementFrameResult {
                    name: Some(age_elem),
                    ref_name: None,
                    target_namespace: None,
                    type_ref: None,
                    inline_type: None,
                    substitution_group: vec![],
                    default_value: None,
                    fixed_value: None,
                    nillable: false,
                    is_abstract: false,
                    min_occurs: 1,
                    max_occurs: Some(1),
                    block: None,
                    final_derivation: None,
                    form: None,
                    id: None,
                    alternatives: vec![],
                    identity_constraints: vec![],
                    identity_constraint_refs: vec![],
                    annotation: None,
                    source: None,
                }),
                min_occurs: 1,
                max_occurs: Some(1),
                source: None,
            }],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let no_selfref_key = schema_set.arenas.alloc_model_group(new_data);

        let result = apply_model_group_redefine(&mut schema_set, no_selfref_key, None, None);
        assert!(
            result.is_ok(),
            "Group redefine without self-reference should succeed (clause 6.2): {:?}",
            result.err()
        );
    }

    #[test]
    fn test_redefine_model_group_self_ref_wrong_min_occurs() {
        // Clause 6.1.2: self-ref with minOccurs=0 must be rejected.
        let (mut schema_set, _original_key, _new_key) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");
        let age_elem = schema_set.name_table.add("age");

        let new_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![
                ParticleResult {
                    term: ParticleTerm::Group(ModelGroupDefResult {
                        name: None,
                        ref_name: Some(QNameRef {
                            prefix: None,
                            local_name: group_name,
                            namespace: None,
                        }),
                        compositor: None,
                        particles: vec![],
                        min_occurs: 1,
                        max_occurs: Some(1),
                        id: None,
                        annotation: None,
                        source: None,
                    }),
                    min_occurs: 0, // ← violates clause 6.1.2
                    max_occurs: Some(1),
                    source: None,
                },
                ParticleResult {
                    term: ParticleTerm::Element(ElementFrameResult {
                        name: Some(age_elem),
                        ref_name: None,
                        target_namespace: None,
                        type_ref: None,
                        inline_type: None,
                        substitution_group: vec![],
                        default_value: None,
                        fixed_value: None,
                        nillable: false,
                        is_abstract: false,
                        min_occurs: 1,
                        max_occurs: Some(1),
                        block: None,
                        final_derivation: None,
                        form: None,
                        id: None,
                        alternatives: vec![],
                        identity_constraints: vec![],
                        identity_constraint_refs: vec![],
                        annotation: None,
                        source: None,
                    }),
                    min_occurs: 1,
                    max_occurs: Some(1),
                    source: None,
                },
            ],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let bad_key = schema_set.arenas.alloc_model_group(new_data);

        let result = apply_model_group_redefine(&mut schema_set, bad_key, None, None);
        assert!(
            result.is_err(),
            "Self-ref with minOccurs=0 should fail (clause 6.1.2)"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("minOccurs"),
            "Error should mention minOccurs: {}",
            msg
        );
    }

    #[test]
    fn test_redefine_model_group_self_ref_wrong_max_occurs() {
        // Clause 6.1.2: self-ref with maxOccurs=unbounded must be rejected.
        let (mut schema_set, _original_key, _new_key) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");

        let new_data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: vec![ParticleResult {
                term: ParticleTerm::Group(ModelGroupDefResult {
                    name: None,
                    ref_name: Some(QNameRef {
                        prefix: None,
                        local_name: group_name,
                        namespace: None,
                    }),
                    compositor: None,
                    particles: vec![],
                    min_occurs: 1,
                    max_occurs: Some(1),
                    id: None,
                    annotation: None,
                    source: None,
                }),
                min_occurs: 1,
                max_occurs: None, // ← unbounded, violates clause 6.1.2
                source: None,
            }],
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let bad_key = schema_set.arenas.alloc_model_group(new_data);

        let result = apply_model_group_redefine(&mut schema_set, bad_key, None, None);
        assert!(
            result.is_err(),
            "Self-ref with maxOccurs=unbounded should fail (clause 6.1.2)"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("maxOccurs"),
            "Error should mention maxOccurs: {}",
            msg
        );
    }

    // -----------------------------------------------------------------
    // §src-redefine 6.1 deep self-reference scanning
    // (structures.html:13729-13741, "among its contents at some level")
    // -----------------------------------------------------------------
    //
    // The following four tests exercise the recursive walker
    // `count_group_self_refs`. They cover, in order:
    //   1. a valid self-reference nested one level deep inside an
    //      inline `<sequence>` (§6.1.1 positive case);
    //   2. a nested self-reference whose `minOccurs` violates §6.1.2;
    //   3. two self-references at different nesting levels (§6.1.1
    //      "exactly one such group" violation);
    //   4. a direct walker test proving `ParticleTerm::Element` is
    //      terminal (§6.1 element-ancestor exclusion).

    /// Helper: build a bare `ModelGroupDefResult` with min/maxOccurs=1
    /// and all optional fields defaulted. Shared by the group-ref and
    /// inline-compositor helpers below.
    fn model_group_def(
        ref_name: Option<QNameRef>,
        compositor: Option<Compositor>,
        particles: Vec<ParticleResult>,
    ) -> ModelGroupDefResult {
        ModelGroupDefResult {
            name: None,
            ref_name,
            compositor,
            particles,
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
        }
    }

    /// Helper: build a `ParticleTerm::Group` self-reference wrapped in
    /// an outer `ParticleResult` with the given occurrence bounds.
    fn self_ref_particle(
        group_name: NameId,
        min_occurs: u32,
        max_occurs: Option<u32>,
    ) -> ParticleResult {
        ParticleResult {
            term: ParticleTerm::Group(model_group_def(
                Some(QNameRef {
                    prefix: None,
                    local_name: group_name,
                    namespace: None,
                }),
                None,
                vec![],
            )),
            min_occurs,
            max_occurs,
            source: None,
        }
    }

    /// Helper: build a simple `ParticleTerm::Element` with min/maxOccurs=1
    /// and no inline type. Used to pad a redefine body.
    fn simple_element_particle(name: NameId) -> ParticleResult {
        ParticleResult {
            term: ParticleTerm::Element(ElementFrameResult {
                name: Some(name),
                ref_name: None,
                target_namespace: None,
                type_ref: None,
                inline_type: None,
                substitution_group: vec![],
                default_value: None,
                fixed_value: None,
                nillable: false,
                is_abstract: false,
                min_occurs: 1,
                max_occurs: Some(1),
                block: None,
                final_derivation: None,
                form: None,
                id: None,
                alternatives: vec![],
                identity_constraints: vec![],
                identity_constraint_refs: vec![],
                annotation: None,
                source: None,
            }),
            min_occurs: 1,
            max_occurs: Some(1),
            source: None,
        }
    }

    /// Helper: wrap a list of particles inside an inline compositor
    /// (`ParticleTerm::Group` with `ref_name: None, name: None`).
    fn inline_compositor_particle(
        compositor: Compositor,
        inner: Vec<ParticleResult>,
    ) -> ParticleResult {
        ParticleResult {
            term: ParticleTerm::Group(model_group_def(None, Some(compositor), inner)),
            min_occurs: 1,
            max_occurs: Some(1),
            source: None,
        }
    }

    /// Helper: allocate a new redefining model group whose top-level
    /// particle list is `top_particles`, matching the name of the
    /// original group created by `setup_model_group_redefine`.
    fn alloc_redefining_group(
        schema_set: &mut SchemaSet,
        top_particles: Vec<ParticleResult>,
    ) -> ModelGroupKey {
        let group_name = schema_set.name_table.add("personGroup");
        let data = ModelGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            compositor: Some(Compositor::Sequence),
            particles: top_particles,
            min_occurs: 1,
            max_occurs: Some(1),
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_particles: Vec::new(),
            resolved_particle_types: Vec::new(),
            resolved_particle_elements: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        schema_set.arenas.alloc_model_group(data)
    }

    #[test]
    fn test_redefine_model_group_nested_self_ref_in_sequence() {
        // §src-redefine 6.1 "among its contents at some level":
        // a self-reference nested one level deep inside an inline
        // `<sequence>` must still be recognised as a §6.1 self-reference
        // (satisfying §6.1.1 "exactly one such group" and §6.1.2
        // "minOccurs=1 and maxOccurs=1").
        let (mut schema_set, _original_key, _ignored) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");
        let age_elem = schema_set.name_table.add("age");

        let new_key = alloc_redefining_group(
            &mut schema_set,
            vec![inline_compositor_particle(
                Compositor::Sequence,
                vec![
                    self_ref_particle(group_name, 1, Some(1)),
                    simple_element_particle(age_elem),
                ],
            )],
        );

        let result = apply_model_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_ok(),
            "nested self-ref inside <sequence> should be accepted \
             (§src-redefine 6.1 'at some level'): {:?}",
            result.err()
        );

        // The walker found one self-ref → §6.1 path → no deferred §6.2.2
        // restriction check should be scheduled.
        let group = schema_set.arenas.model_groups.get(new_key).unwrap();
        assert!(
            !group.redefine_requires_restriction_check,
            "§6.1 self-ref path must clear the §6.2.2 restriction flag"
        );
    }

    #[test]
    fn test_redefine_model_group_nested_self_ref_wrong_min_occurs() {
        // §src-redefine 6.1.2 applies to the self-referencing `<group ref>`
        // particle's own `minOccurs`/`maxOccurs`, regardless of how deeply
        // nested it is. A nested self-ref with `minOccurs=2` must still be
        // rejected.
        let (mut schema_set, _original_key, _ignored) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");

        let new_key = alloc_redefining_group(
            &mut schema_set,
            vec![inline_compositor_particle(
                Compositor::Sequence,
                vec![self_ref_particle(group_name, 2, Some(2))],
            )],
        );

        let result = apply_model_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_err(),
            "nested self-ref with minOccurs=2 should fail (§src-redefine 6.1.2)"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("minOccurs"),
            "error should mention minOccurs: {}",
            msg
        );
    }

    #[test]
    fn test_redefine_model_group_multiple_self_refs_at_different_depths() {
        // §src-redefine 6.1.1 "it has exactly one such group". Two
        // self-references — one at the top level and one nested inside a
        // `<choice>` — must be rejected. The old shallow scan would have
        // missed the nested one and incorrectly accepted this fixture.
        let (mut schema_set, _original_key, _ignored) = setup_model_group_redefine();

        let group_name = schema_set.name_table.add("personGroup");

        let new_key = alloc_redefining_group(
            &mut schema_set,
            vec![
                // Self-ref at the top level — valid min/max.
                self_ref_particle(group_name, 1, Some(1)),
                // A second self-ref nested inside an inline <choice>.
                inline_compositor_particle(
                    Compositor::Choice,
                    vec![self_ref_particle(group_name, 1, Some(1))],
                ),
            ],
        );

        let result = apply_model_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_err(),
            "two self-refs at different depths should fail (§src-redefine 6.1.1)"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("at most one") || msg.contains("found 2"),
            "error should mention the count violation: {}",
            msg
        );
    }

    #[test]
    fn test_count_group_self_refs_element_is_terminal() {
        // §src-redefine 6.1 "and that `<group>` does not have an
        // `<element>` ancestor": the walker must treat `ParticleTerm::Element`
        // as terminal and must not descend into its inline type. Implemented
        // simply by never matching `ParticleTerm::Element` in the walker.
        //
        // We verify this sharply by calling the walker directly: a particle
        // list consisting only of an element particle must contribute zero
        // self-references even when queried with a live `expected_name`.
        let schema_set = SchemaSet::new();
        let group_name = schema_set.name_table.add("personGroup");
        let age_elem = schema_set.name_table.add("age");

        let particles = vec![simple_element_particle(age_elem)];

        let mut scan = GroupSelfRefScan {
            count: 0,
            min_occurs: 0,
            max_occurs: None,
        };
        count_group_self_refs(&particles, group_name, &mut scan);
        assert_eq!(
            scan.count, 0,
            "walker must treat ParticleTerm::Element as terminal per \
             §src-redefine 6.1 element-ancestor exclusion"
        );

        // Sanity: the same walker DOES count a top-level self-ref when one
        // is actually present, so the zero-count above is not a vacuous
        // "walker never finds anything" result.
        let particles_with_ref = vec![self_ref_particle(group_name, 1, Some(1))];
        let mut scan = GroupSelfRefScan {
            count: 0,
            min_occurs: 0,
            max_occurs: None,
        };
        count_group_self_refs(&particles_with_ref, group_name, &mut scan);
        assert_eq!(
            scan.count, 1,
            "sanity check: walker detects a top-level self-ref"
        );
    }

    #[test]
    fn test_redefine_attribute_group_no_self_reference() {
        // Clause 7.2: attribute group redefine with no self-reference is valid.
        let mut schema_set = SchemaSet::new();

        let group_name = schema_set.name_table.add("commonAttrs");

        let original_data = AttributeGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(),
            attribute_wildcard: None,
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let _original_key = schema_set.arenas.alloc_attribute_group(original_data);
        schema_set
            .get_or_create_namespace(None)
            .register_attribute_group(group_name, _original_key);

        // Redefining group with NO self-reference
        let new_data = AttributeGroupData {
            name: Some(group_name),
            target_namespace: None,
            ref_name: None,
            attributes: Vec::new(),
            attribute_groups: Vec::new(), // empty — no self-ref
            attribute_wildcard: None,
            id: None,
            annotation: None,
            source: None,
            resolved_ref: None,
            resolved_attribute_groups: Vec::new(),
            resolved_attributes: Vec::new(),
            redefine_original: None,
            redefine_requires_restriction_check: false,
        };
        let new_key = schema_set.arenas.alloc_attribute_group(new_data);

        let result = apply_attribute_group_redefine(&mut schema_set, new_key, None, None);
        assert!(
            result.is_ok(),
            "Attribute group redefine without self-reference should succeed (clause 7.2): {:?}",
            result.err()
        );
    }
}