xsd-parser 1.5.2

Rust code generator for XML schema files
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
//! XML Schema (XSD) parser and resolver infrastructure.
//!
//! This module defines the [`Parser`] type and supporting logic for loading,
//! resolving, and parsing XML Schema documents (`.xsd`) into structured [`Schemas`].
//!
//! The parser supports various input sources (e.g., files, strings, URLs) and
//! handles `<import>` and `<include>` logic using pluggable [`Resolver`] implementations.
//!
//! Parsed schemas can be passed to the [`Interpreter`](crate::Interpreter) for
//! further transformation into semantic types.
//!
//! # Example
//! ```rust,ignore
//! let schemas = Parser::new()
//!     .with_default_resolver()
//!     .add_schema_from_file("schema.xsd")?
//!     .finish();
//! ```

pub mod resolver;

mod error;

use std::borrow::Cow;
use std::collections::{btree_map::Entry, BTreeMap, HashMap, HashSet, VecDeque};
use std::fmt::Debug;
use std::io::BufRead;
use std::mem::take;
use std::path::Path;

use quick_xml::events::Event;
use resolver::{FileResolver, NoOpResolver, ResolveRequest};
use tracing::instrument;
use url::Url;

use xsd_parser_types::misc::{Namespace, NamespacePrefix};
use xsd_parser_types::quick_xml::{
    DeserializeSync, Error as QuickXmlError, IoReader, SliceReader, XmlReader, XmlReaderSync,
};

use crate::models::schema::{
    xs::{Import, Schema, SchemaContent},
    NamespaceId, NamespaceInfo, Schemas,
};
use crate::models::schema::{Dependency, SchemaId, SchemaInfo};
use crate::pipeline::parser::resolver::ResolveRequestType;

pub use self::error::{Error, XmlErrorWithLocation};
pub use self::resolver::Resolver;

/// The [`Parser`] is responsible for loading and parsing XML Schema documents into
/// a structured [`Schemas`] representation.
///
/// It supports resolution of schema references such as `<import>` and `<include>`
/// using a pluggable [`Resolver`], and can read schema content from strings, files,
/// or URLs.
///
/// Internally, the parser maintains a queue of pending schema loads and a cache
/// to prevent duplicate resolutions. Once all schemas are processed, the
/// [`finish`](Self::finish) method returns the final [`Schemas`] collection.
///
/// A generic resolver type `TResolver` controls how external schemas are fetched.
/// By default, a no-op resolver is used, but file-based or custom resolvers can
/// be injected using [`with_resolver`](Self::with_resolver).
#[must_use]
#[derive(Default, Debug)]
pub struct Parser<TResolver = NoOpResolver> {
    cache: HashMap<Url, HashSet<TempSchemaId>>,
    entries: Vec<ParserEntry>,
    pending: VecDeque<(TempSchemaId, ResolveRequest)>,
    next_temp_id: TempSchemaId,

    resolver: TResolver,
    resolve_includes: bool,
    generate_prefixes: bool,
    alternative_prefixes: bool,
}

#[derive(Default, Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)]
struct TempSchemaId(usize);

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
enum ParserEntry {
    AnonymousNamespace,
    Namespace {
        prefix: NamespacePrefix,
        namespace: Namespace,
    },
    Schema {
        id: TempSchemaId,
        name: Option<String>,
        schema: Schema,
        location: Option<Url>,
        target_ns: Option<Namespace>,
        namespaces: Namespaces,
        dependencies: BTreeMap<String, Dependency<TempSchemaId>>,
    },
}

#[derive(Debug)]
struct SchemasBuilder {
    schemas: Schemas,
    entries: Vec<ParserEntry>,

    id_cache: HashMap<TempSchemaId, SchemaId>,
    prefix_cache: HashMap<Option<Namespace>, PrefixEntry>,
    location_cache: HashMap<Url, HashSet<TempSchemaId>>,

    generate_prefixes: bool,
    alternative_prefixes: bool,
}

#[derive(Default, Debug)]
struct PrefixEntry {
    prefix: Option<NamespacePrefix>,
    alt_prefixes: HashSet<NamespacePrefix>,
}

impl Parser {
    /// Create a new [`Parser`] instance.
    pub fn new() -> Self {
        Self::default()
    }
}

impl<TResolver> Parser<TResolver> {
    /// Set the default resolver for this parser.
    ///
    /// The default resolver is just a simple [`FileResolver`].
    pub fn with_default_resolver(self) -> Parser<FileResolver> {
        self.with_resolver(FileResolver)
    }

    /// Set a custom defined resolver for this parser.
    pub fn with_resolver<XResolver: Resolver + 'static>(
        self,
        resolver: XResolver,
    ) -> Parser<XResolver> {
        let Self { entries, .. } = self;

        let cache = HashMap::new();
        let pending = VecDeque::new();

        Parser {
            cache,
            entries,
            pending,
            next_temp_id: TempSchemaId(0),

            resolver,
            resolve_includes: true,
            generate_prefixes: true,
            alternative_prefixes: true,
        }
    }

    /// Enable or disable resolving includes of parsed XML schemas.
    pub fn resolve_includes(mut self, value: bool) -> Self {
        self.resolve_includes = value;

        self
    }

    /// Instructs the parser to generate unique prefixes for a certain namespace
    /// if its actual prefix is already used.
    pub fn generate_prefixes(mut self, value: bool) -> Self {
        self.generate_prefixes = value;

        self
    }

    /// Instructs the parser to use alternate prefixes known from other
    /// schemas for a certain namespace if its actual prefix is unknown or
    /// already used.
    pub fn alternative_prefixes(mut self, value: bool) -> Self {
        self.alternative_prefixes = value;

        self
    }

    /// Finish the parsing process by returning the generated [`Schemas`] instance
    /// containing all parsed schemas.
    pub fn finish(self) -> Schemas {
        let builder = SchemasBuilder {
            schemas: Schemas::default(),
            entries: self.entries,

            id_cache: HashMap::new(),
            prefix_cache: HashMap::new(),
            location_cache: self.cache,

            generate_prefixes: self.generate_prefixes,
            alternative_prefixes: self.alternative_prefixes,
        };

        builder.build()
    }
}

impl<TResolver> Parser<TResolver>
where
    TResolver: Resolver,
{
    /// Add the default namespaces to this parser.
    ///
    /// The default namespaces are:
    /// - The anonymous namespace
    /// - [`NamespacePrefix::XS`] [`Namespace::XS`]
    /// - [`NamespacePrefix::XML`] [`Namespace::XML`]
    ///
    /// # Errors
    ///
    /// Forwards the errors from [`with_namespace`](Self::with_namespace).
    pub fn with_default_namespaces(self) -> Self {
        self.with_anonymous_namespace()
            .with_namespace(NamespacePrefix::XS, Namespace::XS)
            .with_namespace(NamespacePrefix::XML, Namespace::XML)
            .with_namespace(NamespacePrefix::XSI, Namespace::XSI)
    }

    /// Add a new namespace to this parser.
    ///
    /// This method will add a new namespace to the parser. This can be useful to
    /// pre-heat the prefixes for known namespace, or to define namespaces for
    /// custom defined types.
    ///
    /// This will not add any schema information. It's just a namespace definition.
    ///
    /// # Errors
    ///
    /// Will return an error if a problem or mismatch with the already existing
    /// namespaces was encountered.
    pub fn with_namespace(mut self, prefix: NamespacePrefix, namespace: Namespace) -> Self {
        self.entries
            .push(ParserEntry::Namespace { prefix, namespace });

        self
    }

    /// Adds the anonymous namespace to the resulting [`Schemas`] structure.
    ///
    /// The anonymous namespace does not have a namespace prefix, or a namespace
    /// URI. It is used for type definitions and schemas that do not provide a
    /// target namespace. Additionally it can be used to provide user defined types.
    pub fn with_anonymous_namespace(mut self) -> Self {
        self.entries.push(ParserEntry::AnonymousNamespace);

        self
    }
}

impl<TResolver> Parser<TResolver>
where
    TResolver: Resolver,
    TResolver::Buffer: BufRead,
{
    /// Add a new XML schema from the passed string.
    ///
    /// This will parse the XML schema represented by the provided string and add
    /// all schema information to the resulting [`Schemas`] structure.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not parse the provided
    /// schema.
    #[instrument(err, level = "trace", skip(self, schema))]
    pub fn add_schema_from_str(self, schema: &str) -> Result<Self, Error<TResolver::Error>> {
        self.add_named_schema_from_str_impl(None, schema)
    }

    /// Add a new XML schema from the passed string.
    ///
    /// This will parse the XML schema represented by the provided string and add
    /// all schema information to the resulting [`Schemas`] structure using the
    /// passed `name` for the schema.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not parse the provided
    /// schema.
    #[instrument(err, level = "trace", skip(self, schema))]
    pub fn add_named_schema_from_str(
        self,
        name: String,
        schema: &str,
    ) -> Result<Self, Error<TResolver::Error>> {
        self.add_named_schema_from_str_impl(Some(name), schema)
    }

    #[instrument(err, level = "trace", skip(self, schema))]
    fn add_named_schema_from_str_impl(
        mut self,
        name: Option<String>,
        schema: &str,
    ) -> Result<Self, Error<TResolver::Error>> {
        let reader = SliceReader::new(schema);
        let mut reader = SchemaReader::new(reader);

        let schema = Schema::deserialize(&mut reader).map_err(XmlErrorWithLocation::from)?;
        let id = self.temp_schema_id();

        self.add_schema(id, name, schema, None, reader.namespaces);
        self.resolve_pending()?;

        Ok(self)
    }

    /// Add a new XML schema from the passed `reader`.
    ///
    /// This will parse the XML schema represented by the provided reader and add
    /// all schema information to the resulting [`Schemas`] structure.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not read the data from
    /// the reader, or parse the schema provided by the reader.
    pub fn add_schema_from_reader<R: BufRead>(
        self,
        reader: R,
    ) -> Result<Self, Error<TResolver::Error>> {
        self.add_named_schema_from_reader_impl(None, reader)
    }

    /// Add a new XML schema from the passed `reader`.
    ///
    /// This will parse the XML schema represented by the provided reader and add
    /// all schema information to the resulting [`Schemas`] structure using the
    /// passed `name` as name for the schema.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not read the data from
    /// the reader, or parse the schema provided by the reader.
    pub fn add_named_schema_from_reader<R: BufRead>(
        self,
        name: String,
        reader: R,
    ) -> Result<Self, Error<TResolver::Error>> {
        self.add_named_schema_from_reader_impl(Some(name), reader)
    }

    #[instrument(err, level = "trace", skip(self, reader))]
    fn add_named_schema_from_reader_impl<R: BufRead>(
        mut self,
        name: Option<String>,
        reader: R,
    ) -> Result<Self, Error<TResolver::Error>> {
        let reader = IoReader::new(reader);
        let mut reader = SchemaReader::new(reader);

        let schema = Schema::deserialize(&mut reader).map_err(XmlErrorWithLocation::from)?;
        let id = self.temp_schema_id();

        self.add_schema(id, name, schema, None, reader.namespaces);
        self.resolve_pending()?;

        Ok(self)
    }

    /// Add a new XML schema from the passed file `path`.
    ///
    /// This will parse the XML schema represented by the provided filepath and
    /// add all schema information to the resulting [`Schemas`] structure.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not read the data from
    /// the file, or parse the schema content.
    #[instrument(err, level = "trace", skip(self))]
    pub fn add_schema_from_file<P: AsRef<Path> + Debug>(
        self,
        path: P,
    ) -> Result<Self, Error<TResolver::Error>> {
        let path = path.as_ref().canonicalize()?;
        let url = Url::from_file_path(&path).map_err(|()| Error::InvalidFilePath(path))?;

        self.add_schema_from_url(url)
    }

    /// Add multiple XML schemas from the passed paths iterator.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not read the data from
    /// any file, or parse the schema content.
    #[instrument(err, level = "trace", skip(self))]
    pub fn add_schema_from_files<I>(mut self, paths: I) -> Result<Self, Error<TResolver::Error>>
    where
        I: IntoIterator + Debug,
        I::Item: AsRef<Path> + Debug,
    {
        for path in paths {
            self = self.add_schema_from_file(path)?;
        }

        Ok(self)
    }

    /// Add a new XML schema from the passed file `url`.
    ///
    /// This will parse the XML schema represented by the provided url and
    /// add all schema information to the resulting [`Schemas`] structure.
    ///
    /// # Errors
    ///
    /// Will return an suitable error if the parser could not resolve the URL
    /// using the provided resolver or the data from the resolver could not be
    /// parsed.
    #[instrument(err, level = "trace", skip(self))]
    pub fn add_schema_from_url(mut self, url: Url) -> Result<Self, Error<TResolver::Error>> {
        let req = ResolveRequest::new(url, ResolveRequestType::UserDefined);
        let id = self.temp_schema_id();

        self.resolve_location(id, req)?;
        self.resolve_pending()?;

        Ok(self)
    }

    fn temp_schema_id(&mut self) -> TempSchemaId {
        let id = self.next_temp_id;

        self.next_temp_id.0 = self.next_temp_id.0.wrapping_add(1);

        id
    }

    fn add_pending(&mut self, req: ResolveRequest) -> TempSchemaId {
        tracing::debug!("Add pending resolve request: {req:#?}");

        let id = self.temp_schema_id();

        self.pending.push_back((id, req));

        id
    }

    fn resolve_pending(&mut self) -> Result<(), Error<TResolver::Error>> {
        while let Some((id, req)) = self.pending.pop_front() {
            self.resolve_location(id, req)?;
        }

        Ok(())
    }

    #[instrument(err, level = "trace", skip(self))]
    fn resolve_location(
        &mut self,
        id: TempSchemaId,
        req: ResolveRequest,
    ) -> Result<(), Error<TResolver::Error>> {
        tracing::debug!("Process resolve request: {req:#?}");

        let Some((name, location, buffer)) =
            self.resolver.resolve(&req).map_err(Error::resolver)?
        else {
            return Err(Error::UnableToResolve(Box::new(req)));
        };

        if let Some(ids) = self.cache.get_mut(&location) {
            ids.insert(id);

            return Ok(());
        }

        let reader = IoReader::new(buffer);
        let reader = SchemaReader::new(reader);
        let mut reader = reader.with_error_info();

        let mut schema =
            Schema::deserialize(&mut reader).map_err(|error| XmlErrorWithLocation {
                error,
                location: Some(location.clone()),
            })?;

        if let Some(current_ns) = req.current_ns {
            if let Some(ns) = schema.target_namespace.as_ref() {
                if req.request_type == ResolveRequestType::IncludeRequest
                    && ns.as_bytes() != current_ns.as_ref()
                {
                    return Err(Error::MismatchingTargetNamespace {
                        location,
                        found: Namespace::new(ns.as_bytes().to_vec()),
                        expected: current_ns,
                    });
                }
            } else {
                let inherited_ns = current_ns.to_string();
                schema.target_namespace = Some(inherited_ns);
            }
        }

        let reader = reader.into_inner();

        self.add_schema(id, name, schema, Some(location.clone()), reader.namespaces);
        self.cache.insert(location, HashSet::from([id]));

        Ok(())
    }

    fn add_schema(
        &mut self,
        id: TempSchemaId,
        name: Option<String>,
        schema: Schema,
        location: Option<Url>,
        namespaces: Namespaces,
    ) {
        tracing::debug!(
            "Process schema (location={:?}, target_namespace={:?}",
            location.as_ref().map(Url::as_str),
            &schema.target_namespace
        );

        let target_ns = schema
            .target_namespace
            .as_deref()
            .map(|ns| Namespace::from(ns.as_bytes().to_owned()));
        let mut dependencies = BTreeMap::new();

        if self.resolve_includes {
            for content in &schema.content {
                match content {
                    SchemaContent::Import(x) => {
                        if let Some(req) = import_req(x, target_ns.clone(), location.as_ref()) {
                            let location = req.requested_location.clone();
                            let id = self.add_pending(req);
                            dependencies.insert(location, Dependency::Import(id));
                        }
                    }
                    SchemaContent::Include(x) => {
                        let req =
                            include_req(&x.schema_location, target_ns.clone(), location.as_ref());
                        let location = req.requested_location.clone();
                        let id = self.add_pending(req);
                        dependencies.insert(location, Dependency::Include(id));
                    }
                    SchemaContent::Redefine(x) => {
                        let req =
                            include_req(&x.schema_location, target_ns.clone(), location.as_ref());
                        let location = req.requested_location.clone();
                        let id = self.add_pending(req);
                        dependencies.insert(location, Dependency::Redefine(id));
                    }
                    SchemaContent::Override(x) => {
                        let req =
                            include_req(&x.schema_location, target_ns.clone(), location.as_ref());
                        let location = req.requested_location.clone();
                        let id = self.add_pending(req);
                        dependencies.insert(location, Dependency::Override(id));
                    }
                    _ => (),
                }
            }
        }

        self.entries.push(ParserEntry::Schema {
            id,
            name,
            schema,
            location,
            target_ns,
            namespaces,
            dependencies,
        });
    }
}

struct SchemaReader<R> {
    inner: R,
    namespaces: Namespaces,
}

type Namespaces = BTreeMap<Option<Namespace>, Vec<NamespacePrefix>>;

impl<R> SchemaReader<R> {
    fn new(inner: R) -> Self {
        Self {
            inner,
            namespaces: BTreeMap::new(),
        }
    }
}

impl<R> XmlReader for SchemaReader<R>
where
    R: XmlReader,
{
    fn extend_error(&self, error: QuickXmlError) -> QuickXmlError {
        self.inner.extend_error(error)
    }
}

impl<'a, R> XmlReaderSync<'a> for SchemaReader<R>
where
    R: XmlReaderSync<'a>,
{
    fn read_event(&mut self) -> Result<Event<'a>, QuickXmlError> {
        let event = self.inner.read_event()?;

        if let Event::Start(x) | Event::Empty(x) = &event {
            for a in x.attributes() {
                let a = a?;
                if matches!(a.key.prefix(), Some(x) if x.as_ref() == b"xmlns") {
                    let prefix = NamespacePrefix::new(a.key.local_name().as_ref().to_owned());
                    let namespace = Namespace::new(a.value.into_owned());

                    self.namespaces
                        .entry(Some(namespace))
                        .or_default()
                        .push(prefix);
                }
            }
        }

        Ok(event)
    }
}

impl SchemasBuilder {
    fn build(mut self) -> Schemas {
        self.build_id_cache();
        self.build_prefix_cache();

        for entry in take(&mut self.entries) {
            match entry {
                ParserEntry::AnonymousNamespace => {
                    self.get_or_create_namespace_info_mut(None);
                }
                ParserEntry::Namespace { namespace, .. } => {
                    self.get_or_create_namespace_info_mut(Some(namespace));
                }
                ParserEntry::Schema {
                    id,
                    name,
                    schema,
                    location,
                    target_ns,
                    namespaces: _,
                    dependencies,
                } => {
                    self.add_schema(id, target_ns, name, location, schema, dependencies);
                }
            }
        }

        self.determine_prefixes();

        self.schemas
    }

    fn build_id_cache(&mut self) {
        for entry in &self.entries {
            if let ParserEntry::Schema {
                id: temp_id,
                location,
                ..
            } = entry
            {
                let id = self.schemas.next_schema_id();
                self.id_cache.insert(*temp_id, id);

                if let Some(alternative_ids) =
                    location.as_ref().and_then(|x| self.location_cache.get(x))
                {
                    for temp_id in alternative_ids {
                        self.id_cache.insert(*temp_id, id);
                    }
                }
            }
        }
    }

    fn build_prefix_cache(&mut self) {
        for entry in &self.entries {
            match entry {
                ParserEntry::AnonymousNamespace => {
                    self.prefix_cache.entry(None).or_default();
                }
                ParserEntry::Namespace { prefix, namespace } => {
                    self.prefix_cache
                        .entry(Some(namespace.clone()))
                        .or_default()
                        .prefix = Some(prefix.clone());
                }
                ParserEntry::Schema {
                    target_ns,
                    namespaces,
                    ..
                } => {
                    let prefix = namespaces
                        .get(target_ns)
                        .and_then(|prefixes| prefixes.first())
                        .cloned();
                    let entry = self.prefix_cache.entry(target_ns.clone()).or_default();

                    if entry.prefix.is_none() {
                        entry.prefix = prefix;
                    } else if let Some(prefix) = prefix {
                        entry.alt_prefixes.insert(prefix);
                    }

                    for (namespace, prefixes) in namespaces {
                        for prefix in prefixes {
                            self.prefix_cache
                                .entry(namespace.clone())
                                .or_default()
                                .alt_prefixes
                                .insert(prefix.clone());
                        }
                    }
                }
            }
        }
    }

    fn add_schema(
        &mut self,
        id: TempSchemaId,
        namespace: Option<Namespace>,
        name: Option<String>,
        location: Option<Url>,
        schema: Schema,
        dependencies: BTreeMap<String, Dependency<TempSchemaId>>,
    ) {
        self.schemas.last_schema_id = self.schemas.last_schema_id.wrapping_add(1);
        let schema_id = *self.id_cache.get(&id).unwrap();

        let (namespace_id, namespace_info) = self.get_or_create_namespace_info_mut(namespace);
        namespace_info.schemas.push(schema_id);

        let dependencies = dependencies
            .into_iter()
            .filter_map(|(location, dep)| {
                let id = *self.id_cache.get(&*dep)?;
                let dep = dep.map(|_| id);
                Some((location, dep))
            })
            .collect();

        match self.schemas.schemas.entry(schema_id) {
            Entry::Vacant(e) => e.insert(SchemaInfo {
                name,
                schema,
                location,
                namespace_id,
                dependencies,
            }),
            Entry::Occupied(_) => crate::unreachable!(),
        };
    }

    fn get_or_create_namespace_info_mut(
        &mut self,
        namespace: Option<Namespace>,
    ) -> (NamespaceId, &mut NamespaceInfo) {
        match self.schemas.known_namespaces.entry(namespace) {
            Entry::Occupied(e) => {
                let id = *e.get();
                let info = self.schemas.namespace_infos.get_mut(&id).unwrap();

                (id, info)
            }
            Entry::Vacant(e) => {
                let id = if e.key().is_none() {
                    NamespaceId::ANONYMOUS
                } else {
                    self.schemas.last_namespace_id = self.schemas.last_namespace_id.wrapping_add(1);

                    NamespaceId(self.schemas.last_namespace_id)
                };

                let namespace = e.key().clone();
                e.insert(id);

                let info = match self.schemas.namespace_infos.entry(id) {
                    Entry::Vacant(e) => e.insert(NamespaceInfo::new(namespace)),
                    Entry::Occupied(_) => crate::unreachable!(),
                };

                (id, info)
            }
        }
    }

    fn determine_prefixes(&mut self) {
        // Insert main prefixes
        for (id, info) in &mut self.schemas.namespace_infos {
            if info.prefix.is_some() {
                continue;
            }

            let entry = &mut self.prefix_cache.get(&info.namespace).unwrap();
            if let Some(prefix) = &entry.prefix {
                if let Entry::Vacant(e) = self.schemas.known_prefixes.entry(prefix.clone()) {
                    info.prefix = Some(e.key().clone());
                    e.insert(*id);
                }
            }
        }

        // Fallback to alternate prefixes
        if self.alternative_prefixes {
            for (id, info) in &mut self.schemas.namespace_infos {
                if info.prefix.is_some() {
                    continue;
                }

                let entry = &mut self.prefix_cache.get(&info.namespace).unwrap();
                for alt in &entry.alt_prefixes {
                    if let Entry::Vacant(e) = self.schemas.known_prefixes.entry(alt.clone()) {
                        info.prefix = Some(e.key().clone());
                        e.insert(*id);
                    }
                }
            }
        }

        // Fallback to generated prefix
        if self.generate_prefixes {
            for (id, info) in &mut self.schemas.namespace_infos {
                if info.prefix.is_some() {
                    continue;
                }

                let entry = &mut self.prefix_cache.get(&info.namespace).unwrap();
                let prefix = entry
                    .prefix
                    .clone()
                    .or_else(|| entry.alt_prefixes.iter().next().cloned());
                if let Some(prefix) = prefix {
                    let ext = format!("_{}", id.0);
                    let ext = ext.as_bytes();

                    let mut p = prefix.0.into_owned();
                    p.extend_from_slice(ext);

                    let prefix = NamespacePrefix(Cow::Owned(p));
                    self.schemas.known_prefixes.insert(prefix, *id);
                }
            }
        }
    }
}

fn import_req(
    import: &Import,
    current_ns: Option<Namespace>,
    current_location: Option<&Url>,
) -> Option<ResolveRequest> {
    let location = import.schema_location.as_ref()?;

    let mut req = ResolveRequest::new(location, ResolveRequestType::ImportRequest);

    if let Some(ns) = current_ns {
        req = req.current_ns(ns);
    }

    if let Some(ns) = &import.namespace {
        req = req.requested_ns(Namespace::from(ns.as_bytes().to_owned()));
    }

    if let Some(current_location) = current_location {
        req = req.current_location(current_location.clone());
    }

    Some(req)
}

fn include_req(
    schema_location: &str,
    current_ns: Option<Namespace>,
    current_location: Option<&Url>,
) -> ResolveRequest {
    let mut req = ResolveRequest::new(schema_location, ResolveRequestType::IncludeRequest);

    if let Some(ns) = current_ns {
        req = req.current_ns(ns);
    }

    if let Some(current_location) = current_location {
        req = req.current_location(current_location.clone());
    }

    req
}