einvoice-xsd 0.1.0

XML Schema validation of UBL 2.1 Invoice and CreditNote documents against the official OASIS schemas, in pure Rust
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
//! Loading a schema set: parsing the schema documents reachable from the entry points
//! through `xs:import` and `xs:include`, and compiling their components.
//!
//! Everything outside the supported subset is refused with
//! [`LoadErrorKind::Unsupported`] naming the construct and its line; nothing is
//! silently ignored except the content of `xs:annotation`. The one import that may
//! be left unloaded is that of a namespace of [`XADES_NAMESPACES`] whose schema
//! document is not in the set: it is recorded in [`Schema::omitted_imports`].

use std::collections::{BTreeMap, HashMap};

use roxmltree::{Node, NodeId};

use crate::automaton::{Automaton, MAX_FINITE_OCCURS, Particle, ParticleTerm};
use crate::datatypes::{self, Builtin, UNIMPLEMENTED_BUILTINS};
use crate::error::{LoadError, LoadErrorKind};
use crate::model::{
    ANY_TYPE, AttributeUse, ComplexType, Content, ElementDecl, ElementId, NamespaceConstraint,
    OmittedImport, ProcessContents, QName, Schema, SimpleType, TypeDef, TypeId, Wildcard, XS,
};
use crate::ubl::XADES_NAMESPACES;

/// A parsed schema document.
struct Doc<'a> {
    path: String,
    xml: roxmltree::Document<'a>,
    target: Option<String>,
    qualified_elements: bool,
    qualified_attributes: bool,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum BuildState {
    Pending,
    Building,
    Built,
}

type Result<T> = std::result::Result<T, LoadError>;

fn error(
    doc: &Doc<'_>,
    node: Node<'_, '_>,
    kind: LoadErrorKind,
    message: impl Into<String>,
) -> LoadError {
    LoadError {
        kind,
        file: doc.path.clone(),
        line: doc.xml.text_pos_at(node.range().start).row,
        message: message.into(),
    }
}

fn is_xs(node: Node<'_, '_>, local: &str) -> bool {
    node.is_element() && node.tag_name().namespace() == Some(XS) && node.tag_name().name() == local
}

/// Joins a relative schema location to the directory of the including document and
/// normalises `.` and `..` segments.
fn resolve_location(base: &str, location: &str) -> Option<String> {
    if location.contains(':') || location.starts_with('/') || location.contains('\\') {
        return None;
    }
    let mut segments: Vec<&str> = base.split('/').collect();
    segments.pop();
    for segment in location.split('/') {
        match segment {
            "" | "." => {}
            ".." => {
                segments.pop()?;
            }
            other => segments.push(other),
        }
    }
    Some(segments.join("/"))
}

fn parse_boolean(value: &str) -> Option<bool> {
    match datatypes::normalize(value, datatypes::WhiteSpace::Collapse).as_ref() {
        "true" | "1" => Some(true),
        "false" | "0" => Some(false),
        _ => None,
    }
}

/// Checks that a schema element has only the given attributes (all unqualified).
fn check_attributes(doc: &Doc<'_>, node: Node<'_, '_>, allowed: &[&str]) -> Result<()> {
    for attribute in node.attributes() {
        if attribute.namespace().is_some() || !allowed.contains(&attribute.name()) {
            return Err(error(
                doc,
                node,
                LoadErrorKind::Unsupported,
                format!(
                    "attribute {} on xs:{}",
                    crate::model::clark(attribute.namespace(), attribute.name()),
                    node.tag_name().name()
                ),
            ));
        }
    }
    Ok(())
}

/// The element children of a schema element, without the leading `xs:annotation`.
/// Fails on foreign elements and on non-whitespace text.
fn children<'a, 'i>(doc: &Doc<'_>, node: Node<'a, 'i>) -> Result<Vec<Node<'a, 'i>>> {
    let mut out = Vec::new();
    for child in node.children() {
        if child.is_text() {
            if !child
                .text()
                .unwrap_or("")
                .chars()
                .all(datatypes::is_xml_space)
            {
                return Err(error(
                    doc,
                    node,
                    LoadErrorKind::Invalid,
                    "text in a schema element",
                ));
            }
        } else if child.is_element() {
            if child.tag_name().namespace() != Some(XS) {
                return Err(error(
                    doc,
                    child,
                    LoadErrorKind::Unsupported,
                    format!(
                        "element {} in a schema",
                        crate::model::clark(child.tag_name().namespace(), child.tag_name().name())
                    ),
                ));
            }
            if is_xs(child, "annotation") {
                if !out.is_empty() {
                    return Err(error(
                        doc,
                        child,
                        LoadErrorKind::Invalid,
                        "xs:annotation after other content",
                    ));
                }
                continue;
            }
            out.push(child);
        }
    }
    Ok(out)
}

struct Loader<'d, 'a> {
    docs: &'d [Doc<'a>],
    /// The imports that were not loaded.
    omitted: &'d [OmittedImport],
    types: Vec<TypeDef>,
    elements: Vec<ElementDecl>,
    global_types: HashMap<Option<String>, HashMap<String, TypeId>>,
    global_elements: HashMap<Option<String>, HashMap<String, ElementId>>,
    /// Source of each user-defined global type, by type id.
    type_sources: BTreeMap<TypeId, (usize, NodeId)>,
    /// Source of each global element declaration.
    element_sources: Vec<(ElementId, usize, NodeId)>,
    state: Vec<BuildState>,
    /// Attribute uses whose type must turn out to be simple: (type, doc, node).
    simple_type_checks: Vec<(TypeId, usize, NodeId)>,
}

/// Loads a schema set. `files` maps paths (relative, `/`-separated) to schema
/// document texts; `entry_points` are paths among them.
pub(crate) fn load(files: &[(&str, &str)], entry_points: &[&str]) -> Result<Schema> {
    let texts: HashMap<&str, &str> = files.iter().copied().collect();
    let (docs, omitted) = discover(&texts, entry_points)?;
    let mut loader = Loader {
        docs: &docs,
        omitted: &omitted,
        types: Vec::new(),
        elements: Vec::new(),
        global_types: HashMap::new(),
        global_elements: HashMap::new(),
        type_sources: BTreeMap::new(),
        element_sources: Vec::new(),
        state: Vec::new(),
        simple_type_checks: Vec::new(),
    };
    loader.add_builtins();
    loader.collect_globals()?;
    let ids: Vec<TypeId> = loader.type_sources.keys().copied().collect();
    for id in ids {
        loader.build_type(id)?;
    }
    loader.resolve_global_elements()?;
    loader.check_simple_types()?;
    Ok(Schema {
        types: loader.types,
        elements: loader.elements,
        global_elements: loader.global_elements,
        global_types: loader.global_types,
        documents: docs.iter().map(|d| d.path.clone()).collect(),
        omitted_imports: omitted,
    })
}

/// Parses the entry points and every document they import or include, except for
/// the imports of a namespace of [`XADES_NAMESPACES`] whose document is not in
/// `texts`, which are returned.
fn discover<'a>(
    texts: &HashMap<&str, &'a str>,
    entry_points: &[&str],
) -> Result<(Vec<Doc<'a>>, Vec<OmittedImport>)> {
    let mut docs: Vec<Doc<'a>> = Vec::new();
    let mut omitted: Vec<OmittedImport> = Vec::new();
    let mut index: HashMap<String, usize> = HashMap::new();
    // (path, expected target namespace or None for an entry point, includer target
    // for include)
    let mut queue: Vec<(String, Expect)> = entry_points
        .iter()
        .map(|p| ((*p).to_owned(), Expect::Any))
        .collect();
    queue.reverse();
    while let Some((path, expect)) = queue.pop() {
        let doc_index = if let Some(&i) = index.get(&path) {
            i
        } else {
            let text = texts.get(path.as_str()).ok_or_else(|| LoadError {
                kind: LoadErrorKind::MissingFile,
                file: path.clone(),
                line: 0,
                message: "not in the schema set".to_owned(),
            })?;
            let options = roxmltree::ParsingOptions {
                allow_dtd: true,
                ..roxmltree::ParsingOptions::default()
            };
            let xml =
                roxmltree::Document::parse_with_options(text, options).map_err(|e| LoadError {
                    kind: LoadErrorKind::Malformed,
                    file: path.clone(),
                    line: e.pos().row,
                    message: e.to_string(),
                })?;
            let doc = schema_doc(path.clone(), xml)?;
            let root = doc.xml.root_element();
            let mut found = Vec::new();
            for child in children(&doc, root)? {
                if is_xs(child, "import") {
                    check_attributes(&doc, child, &["namespace", "schemaLocation"])?;
                    let namespace = child.attribute("namespace").map(str::to_owned);
                    if namespace == doc.target {
                        return Err(error(
                            &doc,
                            child,
                            LoadErrorKind::Invalid,
                            "xs:import of the target namespace",
                        ));
                    }
                    let location = location(&doc, child)?;
                    if let Some(namespace) = namespace.as_deref()
                        && XADES_NAMESPACES.contains(&namespace)
                        && !texts.contains_key(location.as_str())
                    {
                        omitted.push(OmittedImport {
                            file: doc.path.clone(),
                            line: doc.xml.text_pos_at(child.range().start).row,
                            namespace: namespace.to_owned(),
                            location,
                        });
                        continue;
                    }
                    found.push((location, Expect::Namespace(namespace)));
                } else if is_xs(child, "include") {
                    check_attributes(&doc, child, &["schemaLocation"])?;
                    let location = location(&doc, child)?;
                    found.push((location, Expect::Namespace(doc.target.clone())));
                }
            }
            docs.push(doc);
            index.insert(path.clone(), docs.len() - 1);
            for item in found.into_iter().rev() {
                queue.push(item);
            }
            docs.len() - 1
        };
        if let Expect::Namespace(namespace) = expect {
            let doc = &docs[doc_index];
            if doc.target != namespace {
                return Err(LoadError {
                    kind: LoadErrorKind::Invalid,
                    file: doc.path.clone(),
                    line: 0,
                    message: format!(
                        "target namespace {:?} differs from the namespace {:?} it is imported or included for",
                        doc.target, namespace
                    ),
                });
            }
        }
    }
    Ok((docs, omitted))
}

enum Expect {
    Any,
    Namespace(Option<String>),
}

fn location(doc: &Doc<'_>, node: Node<'_, '_>) -> Result<String> {
    let value = node.attribute("schemaLocation").ok_or_else(|| {
        error(
            doc,
            node,
            LoadErrorKind::Unsupported,
            "xs:import or xs:include without schemaLocation",
        )
    })?;
    resolve_location(&doc.path, value.trim()).ok_or_else(|| {
        error(
            doc,
            node,
            LoadErrorKind::Unsupported,
            format!(
                "schemaLocation {value:?}: only relative paths within the schema set are supported"
            ),
        )
    })
}

fn schema_doc(path: String, xml: roxmltree::Document<'_>) -> Result<Doc<'_>> {
    let mut doc = Doc {
        path,
        xml,
        target: None,
        qualified_elements: false,
        qualified_attributes: false,
    };
    let root = doc.xml.root_element();
    if !is_xs(root, "schema") {
        return Err(error(
            &doc,
            root,
            LoadErrorKind::Invalid,
            "the document element is not xs:schema",
        ));
    }
    check_attributes(
        &doc,
        root,
        &[
            "targetNamespace",
            "elementFormDefault",
            "attributeFormDefault",
            "version",
        ],
    )?;
    let form = |name: &str| -> Result<bool> {
        match root.attribute(name) {
            None | Some("unqualified") => Ok(false),
            Some("qualified") => Ok(true),
            Some(other) => Err(error(
                &doc,
                root,
                LoadErrorKind::Invalid,
                format!("{name}={other:?}"),
            )),
        }
    };
    let qualified_elements = form("elementFormDefault")?;
    let qualified_attributes = form("attributeFormDefault")?;
    let target = match root.attribute("targetNamespace") {
        Some("") => {
            return Err(error(
                &doc,
                root,
                LoadErrorKind::Invalid,
                "empty targetNamespace",
            ));
        }
        other => other.map(str::to_owned),
    };
    doc.target = target;
    doc.qualified_elements = qualified_elements;
    doc.qualified_attributes = qualified_attributes;
    Ok(doc)
}

fn occurs(doc: &Doc<'_>, node: Node<'_, '_>) -> Result<(u32, Option<u32>)> {
    let parse = |name: &str, value: &str| -> Result<u32> {
        let value = value.trim();
        let number: u32 = value.parse().map_err(|_| {
            error(
                doc,
                node,
                LoadErrorKind::Invalid,
                format!("{name}={value:?}"),
            )
        })?;
        if number > MAX_FINITE_OCCURS {
            return Err(error(
                doc,
                node,
                LoadErrorKind::Unsupported,
                format!("{name}={number}: finite bounds above {MAX_FINITE_OCCURS}"),
            ));
        }
        Ok(number)
    };
    let min = node
        .attribute("minOccurs")
        .map_or(Ok(1), |v| parse("minOccurs", v))?;
    let max = match node.attribute("maxOccurs").map(str::trim) {
        None => Some(1),
        Some("unbounded") => None,
        Some(v) => Some(parse("maxOccurs", v)?),
    };
    if max.is_some_and(|max| max < min) {
        return Err(error(
            doc,
            node,
            LoadErrorKind::Invalid,
            "maxOccurs is less than minOccurs",
        ));
    }
    Ok((min, max))
}

impl<'d, 'a> Loader<'d, 'a> {
    fn push_type(&mut self, def: TypeDef, state: BuildState) -> TypeId {
        self.types.push(def);
        self.state.push(state);
        self.types.len() - 1
    }

    fn register_type(&mut self, name: &QName, id: TypeId) -> bool {
        self.global_types
            .entry(name.namespace.clone())
            .or_default()
            .insert(name.local.clone(), id)
            .is_none()
    }

    /// `xs:anyType` (id 0) and the implemented built-in simple types.
    fn add_builtins(&mut self) {
        let any = Particle {
            term: ParticleTerm::Wildcard(Wildcard {
                namespaces: NamespaceConstraint::Any,
                process: ProcessContents::Lax,
            }),
            min: 0,
            max: None,
        };
        // A lone ##any wildcard is always deterministic.
        let automaton = Automaton::compile(&any, &[]).ok();
        let name = QName::new(Some(XS), "anyType");
        let id = self.push_type(
            TypeDef::Complex(ComplexType {
                name: Some(name.clone()),
                base: ANY_TYPE,
                is_abstract: false,
                content: automaton.map_or(Content::Empty, Content::Mixed),
                attributes: Vec::new(),
                attribute_wildcard: Some(Wildcard {
                    namespaces: NamespaceConstraint::Any,
                    process: ProcessContents::Lax,
                }),
            }),
            BuildState::Built,
        );
        self.register_type(&name, id);
        let mut ids: HashMap<Builtin, TypeId> = HashMap::new();
        for builtin in Builtin::ALL {
            let base = builtin
                .base()
                .and_then(|b| ids.get(&b).copied())
                .unwrap_or(ANY_TYPE);
            let name = QName::new(Some(XS), builtin.name());
            let id = self.push_type(
                TypeDef::Simple(SimpleType {
                    name: Some(name.clone()),
                    base,
                    builtin,
                    enumeration: None,
                }),
                BuildState::Built,
            );
            ids.insert(builtin, id);
            self.register_type(&name, id);
        }
    }

    /// Registers the global components of every document, with placeholders.
    fn collect_globals(&mut self) -> Result<()> {
        for (doc_index, doc) in self.docs.iter().enumerate() {
            for child in children(doc, doc.xml.root_element())? {
                let kind = child.tag_name().name();
                match kind {
                    "import" | "include" => {}
                    "element" | "complexType" | "simpleType" => {
                        let local = child.attribute("name").ok_or_else(|| {
                            error(
                                doc,
                                child,
                                LoadErrorKind::Invalid,
                                format!("global xs:{kind} without a name"),
                            )
                        })?;
                        let name = QName::new(doc.target.as_deref(), local);
                        if kind == "element" {
                            self.elements.push(ElementDecl {
                                name: name.clone(),
                                type_id: ANY_TYPE,
                            });
                            let id = self.elements.len() - 1;
                            let fresh = self
                                .global_elements
                                .entry(name.namespace.clone())
                                .or_default()
                                .insert(name.local.clone(), id)
                                .is_none();
                            if !fresh {
                                return Err(error(
                                    doc,
                                    child,
                                    LoadErrorKind::Invalid,
                                    format!("duplicate global element {name}"),
                                ));
                            }
                            self.element_sources.push((id, doc_index, child.id()));
                        } else {
                            let placeholder = TypeDef::Simple(SimpleType {
                                name: Some(name.clone()),
                                base: ANY_TYPE,
                                builtin: Builtin::AnySimpleType,
                                enumeration: None,
                            });
                            let id = self.push_type(placeholder, BuildState::Pending);
                            if !self.register_type(&name, id) {
                                return Err(error(
                                    doc,
                                    child,
                                    LoadErrorKind::Invalid,
                                    format!("duplicate global type {name}"),
                                ));
                            }
                            self.type_sources.insert(id, (doc_index, child.id()));
                        }
                    }
                    other => {
                        return Err(error(
                            doc,
                            child,
                            LoadErrorKind::Unsupported,
                            format!("top-level xs:{other}"),
                        ));
                    }
                }
            }
        }
        Ok(())
    }

    fn doc(&self, index: usize) -> &'d Doc<'a> {
        &self.docs[index]
    }

    fn node(&self, doc: usize, id: NodeId) -> Node<'d, 'a> {
        let xml = &self.doc(doc).xml;
        // Ids are taken from the same documents, so the lookup cannot fail; the
        // fallback only avoids a panic path.
        xml.get_node(id).unwrap_or_else(|| xml.root())
    }

    /// Resolves a `QName` attribute value of a schema element to a global type.
    fn resolve_type(&mut self, doc: usize, node: Node<'_, '_>, value: &str) -> Result<TypeId> {
        let d = self.doc(doc);
        let name = self.resolve_qname(doc, node, value)?;
        if let Some(id) = self
            .global_types
            .get(&name.namespace)
            .and_then(|m| m.get(&name.local))
        {
            return Ok(*id);
        }
        if name.namespace.as_deref() == Some(XS)
            && UNIMPLEMENTED_BUILTINS.contains(&name.local.as_str())
        {
            return Err(error(
                d,
                node,
                LoadErrorKind::Unsupported,
                format!("built-in type {name}"),
            ));
        }
        Err(self.unresolved(doc, node, "type", &name))
    }

    /// The error for a reference to a global component that does not exist: a
    /// [`LoadErrorKind::MissingFile`] when the component is in a namespace whose
    /// import was omitted (and that no loaded document has as target namespace),
    /// else [`LoadErrorKind::Invalid`].
    fn unresolved(&self, doc: usize, node: Node<'_, '_>, what: &str, name: &QName) -> LoadError {
        let d = self.doc(doc);
        let omitted = self
            .omitted
            .iter()
            .find(|o| name.namespace.as_deref() == Some(o.namespace.as_str()))
            .filter(|_| !self.docs.iter().any(|x| x.target == name.namespace));
        match omitted {
            Some(import) => error(
                d,
                node,
                LoadErrorKind::MissingFile,
                format!(
                    "{what} {name}: its namespace is not loaded, because {} (imported at {}:{}) is not in the schema set",
                    import.location, import.file, import.line
                ),
            ),
            None => error(
                d,
                node,
                LoadErrorKind::Invalid,
                format!("unresolved {what} {name}"),
            ),
        }
    }

    fn resolve_qname(&self, doc: usize, node: Node<'_, '_>, value: &str) -> Result<QName> {
        let d = self.doc(doc);
        let collapsed = datatypes::normalize(value, datatypes::WhiteSpace::Collapse);
        let (prefix, local) = datatypes::split_qname(&collapsed).ok_or_else(|| {
            error(
                d,
                node,
                LoadErrorKind::Invalid,
                format!("{value:?} is not a QName"),
            )
        })?;
        let namespace = match prefix {
            Some(p) => Some(node.lookup_namespace_uri(Some(p)).ok_or_else(|| {
                error(
                    d,
                    node,
                    LoadErrorKind::Invalid,
                    format!("undeclared prefix {p:?}"),
                )
            })?),
            None => crate::model::namespace_name(node.lookup_namespace_uri(None)),
        };
        Ok(QName::new(namespace, local))
    }

    fn build_type(&mut self, id: TypeId) -> Result<()> {
        match self.state[id] {
            BuildState::Built => return Ok(()),
            BuildState::Building => {
                let (doc, node) = self.type_sources[&id];
                let d = self.doc(doc);
                return Err(error(
                    d,
                    self.node(doc, node),
                    LoadErrorKind::Invalid,
                    "circular type derivation",
                ));
            }
            BuildState::Pending => {}
        }
        self.state[id] = BuildState::Building;
        let (doc, node_id) = self.type_sources[&id];
        let docs = self.docs;
        let node = docs[doc]
            .xml
            .get_node(node_id)
            .unwrap_or_else(|| docs[doc].xml.root());
        let name = self.types[id].name().cloned();
        let def = if is_xs(node, "simpleType") {
            TypeDef::Simple(self.simple_type(doc, node, name)?)
        } else {
            TypeDef::Complex(self.complex_type(doc, node, name)?)
        };
        self.types[id] = def;
        self.state[id] = BuildState::Built;
        Ok(())
    }

    fn simple_type(
        &mut self,
        doc: usize,
        node: Node<'_, '_>,
        name: Option<QName>,
    ) -> Result<SimpleType> {
        let d = self.doc(doc);
        check_attributes(d, node, &["name"])?;
        let [restriction] = children(d, node)?[..] else {
            return Err(error(
                d,
                node,
                LoadErrorKind::Invalid,
                "xs:simpleType needs exactly one derivation",
            ));
        };
        if !is_xs(restriction, "restriction") {
            return Err(error(
                d,
                restriction,
                LoadErrorKind::Unsupported,
                format!("xs:simpleType by xs:{}", restriction.tag_name().name()),
            ));
        }
        check_attributes(d, restriction, &["base"])?;
        let base_name = restriction.attribute("base").ok_or_else(|| {
            error(
                d,
                restriction,
                LoadErrorKind::Unsupported,
                "xs:restriction without base",
            )
        })?;
        let base = self.resolve_type(doc, restriction, base_name)?;
        self.build_type(base)?;
        let d = self.doc(doc);
        let TypeDef::Simple(base_def) = &self.types[base] else {
            return Err(error(
                d,
                restriction,
                LoadErrorKind::Invalid,
                "simple type restricting a complex type",
            ));
        };
        let builtin = base_def.builtin;
        let mut enumeration = Vec::new();
        for facet in children(d, restriction)? {
            if !is_xs(facet, "enumeration") {
                return Err(error(
                    d,
                    facet,
                    LoadErrorKind::Unsupported,
                    format!("facet xs:{}", facet.tag_name().name()),
                ));
            }
            check_attributes(d, facet, &["value"])?;
            if !children(d, facet)?.is_empty() {
                return Err(error(
                    d,
                    facet,
                    LoadErrorKind::Invalid,
                    "content in xs:enumeration",
                ));
            }
            let value = facet.attribute("value").ok_or_else(|| {
                error(
                    d,
                    facet,
                    LoadErrorKind::Invalid,
                    "xs:enumeration without value",
                )
            })?;
            enumeration.push(datatypes::normalize(value, builtin.white_space()).into_owned());
        }
        let string_based = matches!(
            builtin,
            Builtin::String | Builtin::NormalizedString | Builtin::Token
        );
        if !enumeration.is_empty() && !string_based {
            return Err(error(
                d,
                restriction,
                LoadErrorKind::Unsupported,
                format!("enumeration on a type derived from xs:{}", builtin.name()),
            ));
        }
        Ok(SimpleType {
            name,
            base,
            builtin,
            enumeration: (!enumeration.is_empty()).then_some(enumeration),
        })
    }

    fn complex_type(
        &mut self,
        doc: usize,
        node: Node<'_, '_>,
        name: Option<QName>,
    ) -> Result<ComplexType> {
        let d = self.doc(doc);
        check_attributes(d, node, &["name", "mixed", "abstract"])?;
        let flag = |attribute: &str| -> Result<bool> {
            node.attribute(attribute).map_or(Ok(false), |v| {
                parse_boolean(v).ok_or_else(|| {
                    error(
                        d,
                        node,
                        LoadErrorKind::Invalid,
                        format!("{attribute}={v:?}"),
                    )
                })
            })
        };
        let mixed = flag("mixed")?;
        let is_abstract = flag("abstract")?;
        let items = children(d, node)?;
        match items.first() {
            Some(&first) if is_xs(first, "simpleContent") => {
                if items.len() > 1 {
                    return Err(error(
                        d,
                        node,
                        LoadErrorKind::Invalid,
                        "content after xs:simpleContent",
                    ));
                }
                if mixed {
                    return Err(error(
                        d,
                        node,
                        LoadErrorKind::Invalid,
                        "mixed type with simple content",
                    ));
                }
                self.simple_content(doc, first, name, is_abstract)
            }
            Some(&first) if is_xs(first, "complexContent") => {
                if items.len() > 1 {
                    return Err(error(
                        d,
                        node,
                        LoadErrorKind::Invalid,
                        "content after xs:complexContent",
                    ));
                }
                self.complex_content(doc, first, name, is_abstract, mixed)
            }
            _ => {
                let (particle, attributes, wildcard) =
                    self.particle_and_attributes(doc, node, &items)?;
                let content = self.content(doc, node, particle, mixed)?;
                Ok(ComplexType {
                    name,
                    base: ANY_TYPE,
                    is_abstract,
                    content,
                    attributes,
                    attribute_wildcard: wildcard,
                })
            }
        }
    }

    /// An optional particle (`xs:sequence` or `xs:choice`) followed by attribute
    /// declarations and an optional `xs:anyAttribute`.
    fn particle_and_attributes(
        &mut self,
        doc: usize,
        parent: Node<'_, '_>,
        items: &[Node<'_, '_>],
    ) -> Result<(Option<Particle>, Vec<AttributeUse>, Option<Wildcard>)> {
        let mut rest = items;
        let mut particle = None;
        if let Some((&first, tail)) = rest.split_first()
            && (is_xs(first, "sequence") || is_xs(first, "choice"))
        {
            particle = Some(self.particle(doc, first)?);
            rest = tail;
        }
        let (attributes, wildcard) = self.attributes(doc, parent, rest)?;
        Ok((particle, attributes, wildcard))
    }

    fn attributes(
        &mut self,
        doc: usize,
        parent: Node<'_, '_>,
        items: &[Node<'_, '_>],
    ) -> Result<(Vec<AttributeUse>, Option<Wildcard>)> {
        let mut uses: Vec<AttributeUse> = Vec::new();
        let mut wildcard = None;
        for &item in items {
            let d = self.doc(doc);
            if wildcard.is_some() {
                return Err(error(
                    d,
                    item,
                    LoadErrorKind::Invalid,
                    "content after xs:anyAttribute",
                ));
            }
            if is_xs(item, "attribute") {
                let attribute = self.attribute(doc, item)?;
                if uses.iter().any(|u| u.name == attribute.name) {
                    return Err(error(
                        d,
                        item,
                        LoadErrorKind::Invalid,
                        format!("duplicate attribute {}", attribute.name),
                    ));
                }
                uses.push(attribute);
            } else if is_xs(item, "anyAttribute") {
                check_attributes(d, item, &["namespace", "processContents"])?;
                if !children(d, item)?.is_empty() {
                    return Err(error(
                        d,
                        item,
                        LoadErrorKind::Invalid,
                        "content in xs:anyAttribute",
                    ));
                }
                wildcard = Some(self.wildcard(doc, item)?);
            } else {
                return Err(error(
                    d,
                    item,
                    LoadErrorKind::Unsupported,
                    format!(
                        "xs:{} in xs:{}",
                        item.tag_name().name(),
                        parent.tag_name().name()
                    ),
                ));
            }
        }
        Ok((uses, wildcard))
    }

    fn attribute(&mut self, doc: usize, node: Node<'_, '_>) -> Result<AttributeUse> {
        let d = self.doc(doc);
        check_attributes(d, node, &["name", "type", "use"])?;
        if !children(d, node)?.is_empty() {
            return Err(error(
                d,
                node,
                LoadErrorKind::Unsupported,
                "anonymous attribute type",
            ));
        }
        let local = node.attribute("name").ok_or_else(|| {
            error(
                d,
                node,
                LoadErrorKind::Unsupported,
                "xs:attribute without a name",
            )
        })?;
        let required = match node.attribute("use").map(str::trim) {
            None | Some("optional") => false,
            Some("required") => true,
            Some(other) => {
                return Err(error(
                    d,
                    node,
                    LoadErrorKind::Unsupported,
                    format!("use={other:?}"),
                ));
            }
        };
        let namespace = if d.qualified_attributes {
            d.target.clone()
        } else {
            None
        };
        let type_name = node.attribute("type").ok_or_else(|| {
            error(
                d,
                node,
                LoadErrorKind::Unsupported,
                "xs:attribute without a type",
            )
        })?;
        let type_id = self.resolve_type(doc, node, type_name)?;
        self.simple_type_checks.push((type_id, doc, node.id()));
        Ok(AttributeUse {
            name: QName {
                namespace,
                local: local.to_owned(),
            },
            type_id,
            required,
        })
    }

    fn wildcard(&self, doc: usize, node: Node<'_, '_>) -> Result<Wildcard> {
        let d = self.doc(doc);
        let namespaces = match node.attribute("namespace").map(str::trim) {
            None | Some("##any") => NamespaceConstraint::Any,
            Some("##other") => NamespaceConstraint::Other(d.target.clone()),
            Some(other) => {
                return Err(error(
                    d,
                    node,
                    LoadErrorKind::Unsupported,
                    format!("wildcard namespace={other:?}"),
                ));
            }
        };
        let process = match node.attribute("processContents").map(str::trim) {
            None | Some("strict") => ProcessContents::Strict,
            Some("lax") => ProcessContents::Lax,
            Some("skip") => ProcessContents::Skip,
            Some(other) => {
                return Err(error(
                    d,
                    node,
                    LoadErrorKind::Invalid,
                    format!("processContents={other:?}"),
                ));
            }
        };
        Ok(Wildcard {
            namespaces,
            process,
        })
    }

    fn particle(&mut self, doc: usize, node: Node<'_, '_>) -> Result<Particle> {
        let d = self.doc(doc);
        let kind = node.tag_name().name();
        match kind {
            "sequence" | "choice" => {
                check_attributes(d, node, &["minOccurs", "maxOccurs"])?;
                let (min, max) = occurs(d, node)?;
                let mut items = Vec::new();
                for child in children(d, node)? {
                    items.push(self.particle(doc, child)?);
                }
                let term = if kind == "sequence" {
                    ParticleTerm::Sequence(items)
                } else {
                    ParticleTerm::Choice(items)
                };
                Ok(Particle { term, min, max })
            }
            "any" => {
                check_attributes(
                    d,
                    node,
                    &["namespace", "processContents", "minOccurs", "maxOccurs"],
                )?;
                if !children(d, node)?.is_empty() {
                    return Err(error(d, node, LoadErrorKind::Invalid, "content in xs:any"));
                }
                let (min, max) = occurs(d, node)?;
                Ok(Particle {
                    term: ParticleTerm::Wildcard(self.wildcard(doc, node)?),
                    min,
                    max,
                })
            }
            "element" => self.local_element(doc, node),
            other => Err(error(
                d,
                node,
                LoadErrorKind::Unsupported,
                format!("particle xs:{other}"),
            )),
        }
    }

    /// An `xs:element` particle: a reference to a global declaration, or a local
    /// declaration (a new element declaration).
    fn local_element(&mut self, doc: usize, node: Node<'_, '_>) -> Result<Particle> {
        let d = self.doc(doc);
        check_attributes(d, node, &["name", "type", "ref", "minOccurs", "maxOccurs"])?;
        if let Some(&child) = children(d, node)?.first() {
            return Err(error(
                d,
                child,
                LoadErrorKind::Unsupported,
                format!("xs:{} in a local xs:element", child.tag_name().name()),
            ));
        }
        let (min, max) = occurs(d, node)?;
        let id = match (node.attribute("ref"), node.attribute("name")) {
            (Some(reference), None) => {
                if node.attribute("type").is_some() {
                    return Err(error(
                        d,
                        node,
                        LoadErrorKind::Invalid,
                        "xs:element with both ref and type",
                    ));
                }
                let name = self.resolve_qname(doc, node, reference)?;
                self.global_elements
                    .get(&name.namespace)
                    .and_then(|m| m.get(&name.local))
                    .copied()
                    .ok_or_else(|| self.unresolved(doc, node, "element", &name))?
            }
            (None, Some(local)) => {
                let namespace = if d.qualified_elements {
                    d.target.clone()
                } else {
                    None
                };
                let type_id = match node.attribute("type") {
                    Some(t) => self.resolve_type(doc, node, t)?,
                    None => ANY_TYPE,
                };
                self.elements.push(ElementDecl {
                    name: QName {
                        namespace,
                        local: local.to_owned(),
                    },
                    type_id,
                });
                self.elements.len() - 1
            }
            _ => {
                return Err(error(
                    d,
                    node,
                    LoadErrorKind::Invalid,
                    "xs:element needs exactly one of name and ref",
                ));
            }
        };
        Ok(Particle {
            term: ParticleTerm::Element(id),
            min,
            max,
        })
    }

    fn content(
        &self,
        doc: usize,
        node: Node<'_, '_>,
        particle: Option<Particle>,
        mixed: bool,
    ) -> Result<Content> {
        let particle = particle.unwrap_or(Particle {
            term: ParticleTerm::Sequence(Vec::new()),
            min: 1,
            max: Some(1),
        });
        let automaton = Automaton::compile(&particle, &self.elements)
            .map_err(|message| error(self.doc(doc), node, LoadErrorKind::Invalid, message))?;
        Ok(match (automaton.is_empty(), mixed) {
            (_, true) => Content::Mixed(automaton),
            (true, false) => Content::Empty,
            (false, false) => Content::ElementOnly(automaton),
        })
    }

    fn base_complex(&mut self, doc: usize, node: Node<'_, '_>) -> Result<TypeId> {
        let d = self.doc(doc);
        check_attributes(d, node, &["base"])?;
        let base_name = node
            .attribute("base")
            .ok_or_else(|| error(d, node, LoadErrorKind::Invalid, "derivation without base"))?;
        let base = self.resolve_type(doc, node, base_name)?;
        self.build_type(base)?;
        Ok(base)
    }

    /// The content, attribute uses and attribute wildcard of a simple-content
    /// extension of `base` (a simple type, or a complex type with simple content).
    fn simple_extension(
        &self,
        d: &Doc<'_>,
        derivation: Node<'_, '_>,
        base: TypeId,
        own: Vec<AttributeUse>,
        own_wildcard: Option<Wildcard>,
    ) -> Result<(Content, Vec<AttributeUse>, Option<Wildcard>)> {
        let (content_type, mut attributes, base_wildcard) = match &self.types[base] {
            TypeDef::Simple(_) => (base, Vec::new(), None),
            TypeDef::Complex(ComplexType {
                content: Content::Simple(s),
                attributes,
                attribute_wildcard,
                ..
            }) => (*s, attributes.clone(), attribute_wildcard.clone()),
            TypeDef::Complex(_) => {
                return Err(error(
                    d,
                    derivation,
                    LoadErrorKind::Invalid,
                    "simple content extending a type without simple content",
                ));
            }
        };
        for attribute in own {
            if attributes.iter().any(|a| a.name == attribute.name) {
                return Err(error(
                    d,
                    derivation,
                    LoadErrorKind::Invalid,
                    format!("attribute {} already in the base type", attribute.name),
                ));
            }
            attributes.push(attribute);
        }
        let attribute_wildcard = match (base_wildcard, own_wildcard) {
            (Some(_), Some(_)) => {
                return Err(error(
                    d,
                    derivation,
                    LoadErrorKind::Unsupported,
                    "union of attribute wildcards",
                ));
            }
            (a, b) => a.or(b),
        };
        Ok((
            Content::Simple(content_type),
            attributes,
            attribute_wildcard,
        ))
    }

    fn simple_content(
        &mut self,
        doc: usize,
        node: Node<'_, '_>,
        name: Option<QName>,
        is_abstract: bool,
    ) -> Result<ComplexType> {
        let d = self.doc(doc);
        check_attributes(d, node, &[])?;
        let [derivation] = children(d, node)?[..] else {
            return Err(error(
                d,
                node,
                LoadErrorKind::Invalid,
                "xs:simpleContent needs exactly one derivation",
            ));
        };
        let base = self.base_complex(doc, derivation)?;
        let items = children(self.doc(doc), derivation)?;
        let (own, own_wildcard) = self.attributes(doc, derivation, &items)?;
        let d = self.doc(doc);
        if is_xs(derivation, "extension") {
            let (content, attributes, attribute_wildcard) =
                self.simple_extension(d, derivation, base, own, own_wildcard)?;
            Ok(ComplexType {
                name,
                base,
                is_abstract,
                content,
                attributes,
                attribute_wildcard,
            })
        } else if is_xs(derivation, "restriction") {
            let TypeDef::Complex(ComplexType {
                content: Content::Simple(content_type),
                attributes: base_attributes,
                ..
            }) = &self.types[base]
            else {
                return Err(error(
                    d,
                    derivation,
                    LoadErrorKind::Invalid,
                    "simple content restricting a type without simple content",
                ));
            };
            if own_wildcard.is_some() {
                return Err(error(
                    d,
                    derivation,
                    LoadErrorKind::Unsupported,
                    "xs:anyAttribute in a restriction",
                ));
            }
            let attributes = restrict_attributes(d, derivation, base_attributes, own)?;
            Ok(ComplexType {
                name,
                base,
                is_abstract,
                content: Content::Simple(*content_type),
                attributes,
                attribute_wildcard: None,
            })
        } else {
            Err(error(
                d,
                derivation,
                LoadErrorKind::Invalid,
                format!("xs:{} in xs:simpleContent", derivation.tag_name().name()),
            ))
        }
    }

    fn complex_content(
        &mut self,
        doc: usize,
        node: Node<'_, '_>,
        name: Option<QName>,
        is_abstract: bool,
        mixed: bool,
    ) -> Result<ComplexType> {
        let d = self.doc(doc);
        check_attributes(d, node, &[])?;
        let [derivation] = children(d, node)?[..] else {
            return Err(error(
                d,
                node,
                LoadErrorKind::Invalid,
                "xs:complexContent needs exactly one derivation",
            ));
        };
        if !is_xs(derivation, "restriction") {
            return Err(error(
                d,
                derivation,
                LoadErrorKind::Unsupported,
                format!("xs:{} in xs:complexContent", derivation.tag_name().name()),
            ));
        }
        let base = self.base_complex(doc, derivation)?;
        let items = children(self.doc(doc), derivation)?;
        let (particle, own, own_wildcard) =
            self.particle_and_attributes(doc, derivation, &items)?;
        let d = self.doc(doc);
        let TypeDef::Complex(base_type) = &self.types[base] else {
            return Err(error(
                d,
                derivation,
                LoadErrorKind::Invalid,
                "complex content restricting a simple type",
            ));
        };
        if matches!(base_type.content, Content::Simple(_)) {
            return Err(error(
                d,
                derivation,
                LoadErrorKind::Invalid,
                "complex content restricting a type with simple content",
            ));
        }
        if own_wildcard.is_some() {
            return Err(error(
                d,
                derivation,
                LoadErrorKind::Unsupported,
                "xs:anyAttribute in a restriction",
            ));
        }
        let attributes = restrict_attributes(d, derivation, &base_type.attributes, own)?;
        let content = self.content(doc, derivation, particle, mixed)?;
        Ok(ComplexType {
            name,
            base,
            is_abstract,
            content,
            attributes,
            attribute_wildcard: None,
        })
    }

    fn resolve_global_elements(&mut self) -> Result<()> {
        let sources = std::mem::take(&mut self.element_sources);
        for &(id, doc, node_id) in &sources {
            let node = self.node(doc, node_id);
            let d = self.doc(doc);
            check_attributes(d, node, &["name", "type"])?;
            if let Some(&child) = children(d, node)?.first() {
                return Err(error(
                    d,
                    child,
                    LoadErrorKind::Unsupported,
                    format!("xs:{} in a global xs:element", child.tag_name().name()),
                ));
            }
            let docs = self.docs;
            let node = docs[doc]
                .xml
                .get_node(node_id)
                .unwrap_or_else(|| docs[doc].xml.root());
            if let Some(type_name) = node.attribute("type") {
                let type_id = self.resolve_type(doc, node, type_name)?;
                self.elements[id].type_id = type_id;
            }
        }
        self.element_sources = sources;
        Ok(())
    }

    fn check_simple_types(&self) -> Result<()> {
        for &(type_id, doc, node_id) in &self.simple_type_checks {
            if !matches!(self.types[type_id], TypeDef::Simple(_)) {
                let d = self.doc(doc);
                return Err(error(
                    d,
                    self.node(doc, node_id),
                    LoadErrorKind::Invalid,
                    "attribute of a complex type",
                ));
            }
        }
        Ok(())
    }
}

/// The attribute uses of a restriction: the base's, each replaced by the
/// restriction's own use of the same name. A restriction cannot add attributes
/// (the base types of the supported schemas have no attribute wildcard).
fn restrict_attributes(
    doc: &Doc<'_>,
    node: Node<'_, '_>,
    base: &[AttributeUse],
    own: Vec<AttributeUse>,
) -> Result<Vec<AttributeUse>> {
    let mut attributes = base.to_vec();
    for attribute in own {
        match attributes.iter_mut().find(|a| a.name == attribute.name) {
            Some(slot) => *slot = attribute,
            None => {
                return Err(error(
                    doc,
                    node,
                    LoadErrorKind::Invalid,
                    format!("restriction adds attribute {}", attribute.name),
                ));
            }
        }
    }
    Ok(attributes)
}

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

    #[test]
    fn locations() {
        assert_eq!(
            resolve_location("xsd/maindoc/A.xsd", "../common/B.xsd").as_deref(),
            Some("xsd/common/B.xsd")
        );
        assert_eq!(
            resolve_location("xsd/common/A.xsd", "B.xsd").as_deref(),
            Some("xsd/common/B.xsd")
        );
        assert_eq!(resolve_location("A.xsd", "../B.xsd"), None);
        assert_eq!(resolve_location("A.xsd", "http://example.org/B.xsd"), None);
        assert_eq!(resolve_location("A.xsd", "/B.xsd"), None);
    }

    fn load_one(schema: &str) -> Result<Schema> {
        load(&[("s.xsd", schema)], &["s.xsd"])
    }

    fn kind_of(schema: &str) -> LoadErrorKind {
        match load_one(schema) {
            Ok(_) => panic!("loaded: {schema}"),
            Err(e) => e.kind,
        }
    }

    const HEAD: &str = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:t="urn:t" targetNamespace="urn:t" elementFormDefault="qualified">"#;

    #[test]
    fn refuses_unsupported_constructs() {
        for body in [
            r#"<xs:attribute name="a" type="xs:string"/>"#,
            r#"<xs:group name="g"><xs:sequence/></xs:group>"#,
            r#"<xs:element name="e" nillable="true"/>"#,
            r#"<xs:element name="e" abstract="true"/>"#,
            r#"<xs:element name="e"><xs:complexType/></xs:element>"#,
            r#"<xs:complexType name="c"><xs:all/></xs:complexType>"#,
            r###"<xs:complexType name="c"><xs:sequence><xs:any namespace="##local"/></xs:sequence></xs:complexType>"###,
            r#"<xs:complexType name="c"><xs:attribute name="a" type="xs:string" default="x"/></xs:complexType>"#,
            r#"<xs:complexType name="c"><xs:attribute ref="t:a"/></xs:complexType>"#,
            r#"<xs:complexType name="c"><xs:complexContent><xs:extension base="xs:anyType"/></xs:complexContent></xs:complexType>"#,
            r#"<xs:simpleType name="s"><xs:restriction base="xs:string"><xs:maxLength value="3"/></xs:restriction></xs:simpleType>"#,
            r#"<xs:simpleType name="s"><xs:list itemType="xs:string"/></xs:simpleType>"#,
            r#"<xs:simpleType name="s"><xs:restriction base="xs:float"/></xs:simpleType>"#,
            r#"<xs:simpleType name="s"><xs:restriction base="xs:decimal"><xs:enumeration value="1"/></xs:restriction></xs:simpleType>"#,
            r#"<xs:complexType name="c"><xs:sequence maxOccurs="1000"/></xs:complexType>"#,
            r#"<xs:import namespace="urn:x" schemaLocation="http://example.org/x.xsd"/>"#,
            r#"<xs:complexType name="c" block="extension"/>"#,
        ] {
            let schema = format!("{HEAD}{body}</xs:schema>");
            assert_eq!(kind_of(&schema), LoadErrorKind::Unsupported, "{body}");
        }
    }

    #[test]
    fn refuses_incorrect_schemas() {
        for body in [
            r#"<xs:element name="e" type="t:missing"/>"#,
            r#"<xs:element name="e"/><xs:element name="e"/>"#,
            r#"<xs:complexType name="a"><xs:simpleContent><xs:extension base="t:b"/></xs:simpleContent></xs:complexType><xs:complexType name="b"><xs:simpleContent><xs:extension base="t:a"/></xs:simpleContent></xs:complexType>"#,
            r#"<xs:element name="e"/><xs:complexType name="c"><xs:sequence><xs:element ref="t:e" minOccurs="0"/><xs:element ref="t:e"/></xs:sequence></xs:complexType>"#,
            r#"<xs:complexType name="c"><xs:sequence minOccurs="2" maxOccurs="1"/></xs:complexType>"#,
            r#"<xs:complexType name="c"><xs:attribute name="a" type="t:c"/></xs:complexType>"#,
        ] {
            let schema = format!("{HEAD}{body}</xs:schema>");
            assert_eq!(kind_of(&schema), LoadErrorKind::Invalid, "{body}");
        }
    }

    #[test]
    fn missing_and_malformed_files() {
        let missing = load(&[], &["a.xsd"]).unwrap_err();
        assert_eq!(missing.kind, LoadErrorKind::MissingFile);
        let malformed = load(&[("a.xsd", "<xs:schema")], &["a.xsd"]).unwrap_err();
        assert_eq!(malformed.kind, LoadErrorKind::Malformed);
        let import =
            format!(r#"{HEAD}<xs:import namespace="urn:x" schemaLocation="x.xsd"/></xs:schema>"#);
        let wrong_namespace = load(
            &[
                ("s.xsd", import.as_str()),
                ("x.xsd", r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:y"/>"#),
            ],
            &["s.xsd"],
        )
        .unwrap_err();
        assert_eq!(wrong_namespace.kind, LoadErrorKind::Invalid);
    }

    const XADES: &str = "http://uri.etsi.org/01903/v1.3.2#";

    fn importing(namespace: &str, body: &str) -> String {
        format!(
            r#"{HEAD}<xs:import namespace="{namespace}" schemaLocation="x/X.xsd"/>{body}</xs:schema>"#
        )
    }

    #[test]
    fn xades_imports_may_be_absent() {
        let main = importing(XADES, r#"<xs:element name="e"/>"#);
        let schema = load(&[("s.xsd", main.as_str())], &["s.xsd"]).unwrap();
        assert_eq!(schema.documents, ["s.xsd"]);
        assert_eq!(
            schema.omitted_imports,
            [OmittedImport {
                file: "s.xsd".to_owned(),
                line: 1,
                namespace: XADES.to_owned(),
                location: "x/X.xsd".to_owned(),
            }]
        );
        // Present, it is loaded like any other import.
        let xades = format!(
            r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="{XADES}"><xs:element name="Q"/></xs:schema>"#
        );
        let schema = load(
            &[("s.xsd", main.as_str()), ("x/X.xsd", xades.as_str())],
            &["s.xsd"],
        )
        .unwrap();
        assert_eq!(schema.documents, ["s.xsd", "x/X.xsd"]);
        assert_eq!(schema.omitted_imports, []);
        assert!(schema.global_element(Some(XADES), "Q").is_some());
        // Its location is still checked.
        let remote = format!(
            r#"{HEAD}<xs:import namespace="{XADES}" schemaLocation="http://example.org/X.xsd"/></xs:schema>"#
        );
        assert_eq!(kind_of(&remote), LoadErrorKind::Unsupported);
    }

    #[test]
    fn other_imports_may_not_be_absent() {
        for namespace in [
            "urn:x",
            "http://uri.etsi.org/01903/v1.3.2",
            "http://uri.etsi.org/01903/v1.3.3#",
        ] {
            let main = importing(namespace, "");
            let error = load(&[("s.xsd", main.as_str())], &["s.xsd"]).unwrap_err();
            assert_eq!(error.kind, LoadErrorKind::MissingFile, "{namespace}");
            assert_eq!(error.file, "x/X.xsd");
        }
    }

    #[test]
    fn references_into_an_omitted_namespace_are_refused() {
        for body in [
            r#"<xs:element name="e" type="x:T"/>"#,
            r#"<xs:complexType name="c"><xs:sequence><xs:element ref="x:Q"/></xs:sequence></xs:complexType>"#,
            r#"<xs:complexType name="c"><xs:simpleContent><xs:extension base="x:T"/></xs:simpleContent></xs:complexType>"#,
        ] {
            let main = importing(XADES, body).replacen(
                "<xs:schema ",
                &format!(r#"<xs:schema xmlns:x="{XADES}" "#),
                1,
            );
            let error = load_one(&main).unwrap_err();
            assert_eq!(error.kind, LoadErrorKind::MissingFile, "{body}");
            assert_eq!(error.file, "s.xsd", "{body}");
            assert!(
                error.message.contains("its namespace is not loaded")
                    && error.message.contains("x/X.xsd"),
                "{error}"
            );
        }
    }
}