anyxml 0.12.1

A fully spec-conformant XML library
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
//! Provide SAX parsers and auxiliary data structures.
//!
//! To receive events from the parser, the application must configure a SAX handler.  \
//! The handler must implement [`SAXHandler`], [`EntityResolver`], and [`ErrorHandler`].
//!
//! The default implementation for each trait except for [`EntityResolver::resolve_entity`]
//! does nothing. The default implementation for [`EntityResolver::resolve_entity`] simply
//! searches local files.  \
//! If the application only handles trusted data, redirecting to the [`DefaultSAXHandler`]
//! implementation should suffice.
//! However, when handling untrusted resources, it may be advisable to perform some sanitization
//! in [`EntityResolver::resolve_entity`] or [`EntityResolver::get_external_subset`].
//!
//! Parsers can be generated via [`XMLReaderBuilder`].  \
//! If a custom handler is required, execute [`XMLReaderBuilder::set_handler`].  \
//! Since the handler type is statically determined, it is impossible to reassign
//! a different type of handler to an already generated parser.
//!
//! ## Example
//! ```rust
//! use std::fmt::Write as _;
//!
//! use anyxml::sax::{Attributes, EntityResolver, ErrorHandler, SAXHandler, XMLReader};
//!
//! #[derive(Default)]
//! struct ExampleHandler {
//!     buffer: String,
//! }
//! impl EntityResolver for ExampleHandler {}
//! impl ErrorHandler for ExampleHandler {}
//! impl SAXHandler for ExampleHandler {
//!     fn start_document(&mut self) {
//!         writeln!(self.buffer, "start document").ok();
//!     }
//!     fn end_document(&mut self) {
//!         writeln!(self.buffer, "end document").ok();
//!     }
//!
//!     fn start_element(
//!         &mut self,
//!         _namespace_name: Option<&str>,
//!         _local_name: Option<&str>,
//!         qname: &str,
//!         _atts: &Attributes,
//!     ) {
//!         writeln!(self.buffer, "start element {qname}").ok();
//!     }
//!     fn end_element(
//!         &mut self,
//!         _namespace_name: Option<&str>,
//!         _local_name: Option<&str>,
//!         qname: &str
//!     ) {
//!         writeln!(self.buffer, "end element {qname}").ok();
//!     }
//!
//!     fn characters(&mut self, data: &str) {
//!         writeln!(self.buffer, "characters '{data}'").ok();
//!     }
//! }
//!
//! let mut reader = XMLReader::builder()
//!     .set_handler(ExampleHandler::default())
//!     .build();
//! reader.parse_str(r#"<?xml version="1.0"?><greeting>Hello!!</greeting>"#, None).ok();
//!
//! let handler = reader.handler;
//! assert_eq!(r#"start document
//! start element greeting
//! characters 'Hello!!'
//! end element greeting
//! end document
//! "#, handler.buffer);
//! ```
//!
//! # Progressive Parser
//! A normal SAX Parser appears to retrieve all document resources at once, but using a
//! Progressive Parser allows the application to feed document resources to the parser
//! sequentially.
//!
//! For example, when parsing chunked document resources, the application can feed resources
//! to the parser sequentially as they are acquired, rather than collecting all resources and
//! feeding them as a single batch.
//!
//! When parsing XML documents that retrieve external resources, note that the application
//! must set the appropriate base URI for the parser before starting parsing.  \
//! By default, the current directory is set as the base URI.
//!
//! ## Example
//! ```rust
//! use anyxml::sax::{Attributes, DebugHandler, XMLReader};
//!
//! let mut reader = XMLReader::builder()
//!     .set_handler(DebugHandler::default())
//!     .progressive_parser()
//!     .build();
//! let source = br#"<greeting>Hello!!</greeting>"#;
//!
//! for chunk in source.chunks(5) {
//!     reader.parse_chunk(chunk, false).ok();
//! }
//! // Note that the last chunk must set `finish` to `true`.
//! // As shown below, it's okay for an empty chunk.
//! reader.parse_chunk([], true).ok();
//!
//! let handler = reader.handler;
//! assert_eq!(r#"setDocumentLocator()
//! startDocument()
//! startElement(None, greeting, greeting)
//! characters(Hello!!)
//! endElement(None, greeting, greeting)
//! endDocument()
//! "#, handler.buffer);
//! ```
//!
//! # Parser embeded DTD validation feature
//! Applications can enable DTD validation through parser options.  \
//! Note that when enabling the DTD validation option, all external entity loading options
//! are automatically enabled, as some XML documents require loading external DTD subsets
//! for validation.
//!
//! Furthermore, this option does not control whether the DTD is parsed.  \
//! For example, even if the DTD validation option is disabled, parsing the internal DTD
//! subset always occurs to perform attribute value normalization, add default attributes,
//! and resolve internal entity references.
//!
//! ## Example
//! ```rust
//! use anyxml::sax::{
//!     error::SAXParseError,
//!     EntityResolver, ErrorHandler, ParserOption, SAXHandler, XMLReader,
//! };
//!
//! #[derive(Default)]
//! struct ExampleHandler {
//!     buffer: String,
//! }
//! impl EntityResolver for ExampleHandler {}
//! impl ErrorHandler for ExampleHandler {
//!     fn error(&mut self, error: SAXParseError) {
//!         self.buffer.push_str(&format!("\n{error}"));
//!     }
//! }
//! impl SAXHandler for ExampleHandler {}
//!
//! const DOCUMENT: &str = r#"<?xml version="1.0"?>
//! <!DOCTYPE root [
//!     <!ELEMENT root EMPTY>
//!     <!ATTLIST root attr1 CDATA #IMPLIED>
//!     <!ATTLIST root attr2 CDATA #REQUIRED>
//! ]>
//! <root attr1="attr1">non empty string</root>
//! "#;
//!
//! const EXPECT: &str = r#"
//! document.xml[line:7,column:20][dtd-valid][error] #REQUIRED attribute 'attr2' of the element 'root' is not specified.
//! document.xml[line:7,column:44][dtd-valid][error] The content of element 'root' does not match to its content model."#;
//!
//! let mut reader = XMLReader::builder()
//!     .set_handler(ExampleHandler::default())
//!     .enable_option(ParserOption::Validation)
//!     .build();
//! reader.parse_str(DOCUMENT, None).unwrap();
//! assert_eq!(reader.handler.buffer, EXPECT);
//! ```

mod attributes;
mod contentspec;
pub mod error;
mod handler;
mod parser;
mod source;

use std::{
    collections::{BTreeMap, HashMap, HashSet},
    sync::{
        Arc, LazyLock, RwLock,
        atomic::{AtomicUsize, Ordering},
    },
};

use crate::{
    XML_XML_NAMESPACE,
    error::XMLError,
    uri::{URIStr, URIString},
};

pub use attributes::{Attribute, Attributes};
pub use contentspec::ContentSpec;
pub(crate) use contentspec::{ElementContent, ElementContentStateID};
pub use handler::{DebugHandler, DefaultSAXHandler, EntityResolver, ErrorHandler, SAXHandler};
pub use parser::{
    DefaultParserSpec, ParserConfig, ParserOption, ParserSpec, ProgressiveParserSpec,
    ProgressiveParserSpecificContext, XMLProgressiveReaderBuilder, XMLReader, XMLReaderBuilder,
};
pub(crate) use parser::{ParserState, ParserSubState};
pub(crate) use source::INPUT_CHUNK;
pub use source::InputSource;

/// Pseudo entity name for document entities.
pub const DOCUMENT_ENTITY_NAME: &str = "[document]";
/// Pseudo entity name for external DTD subsets.
pub const EXTERNAL_DTD_SUBSET_ENTITY_NAME: &str = "[dtd]";

/// Attribute type of attlist declarations.
///
/// # Reference
/// - [3.3.1 Attribute Types](https://www.w3.org/TR/xml/#sec-attribute-types)
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum AttributeType {
    /// CDATA type (`'CDATA'`)
    #[default]
    CDATA,
    /// ID type (`'ID'`)
    ID,
    /// IDREF type (`'IDREF'`)
    IDREF,
    /// IDREFS type (`'IDREFS'`)
    IDREFS,
    /// Entity Name type (`'ENTITY'`)
    ENTITY,
    /// Entity Names type (`'ENTITIES'`)
    ENTITIES,
    /// Name token type (`'NMTOKEN'`)
    NMTOKEN,
    /// Name tokens type (`'NMTOKENS'`)
    NMTOKENS,
    /// Notation type (`'NOTATION'`)
    NOTATION(HashSet<Box<str>>),
    /// Enumeration type
    Enumeration(HashSet<Box<str>>),
}

impl std::fmt::Display for AttributeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CDATA => write!(f, "CDATA"),
            Self::ID => write!(f, "ID"),
            Self::IDREF => write!(f, "IDREF"),
            Self::IDREFS => write!(f, "IDREFS"),
            Self::ENTITY => write!(f, "ENTITY"),
            Self::ENTITIES => write!(f, "ENTITIES"),
            Self::NMTOKEN => write!(f, "NMTOKEN"),
            Self::NMTOKENS => write!(f, "NMTOKENS"),
            ty @ (Self::NOTATION(set) | Self::Enumeration(set)) => {
                if matches!(ty, Self::NOTATION(_)) {
                    write!(f, "NOTATION ")?;
                }
                write!(f, "(")?;
                let mut set = set.iter().collect::<Vec<_>>();
                set.sort_unstable();
                let mut iter = set.iter();
                if let Some(name) = iter.next() {
                    write!(f, "{name}")?;
                }
                for name in iter {
                    write!(f, "|{name}")?;
                }
                write!(f, ")")
            }
        }
    }
}

/// Default declaration of attlist declarations.
///
/// # Reference
/// - [3.3.2 Attribute Defaults](https://www.w3.org/TR/xml/#sec-attr-defaults)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DefaultDecl {
    /// `'#REQUIRED'`
    REQUIRED,
    /// `'#IMPLIED'`
    IMPLIED,
    /// default attribute value with `'#FIXED'`
    FIXED(Box<str>),
    /// default attribute value without `'#FIXED'`
    None(Box<str>),
}

impl std::fmt::Display for DefaultDecl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::REQUIRED => write!(f, "#REQUIRED"),
            Self::IMPLIED => write!(f, "#IMPLIED"),
            Self::FIXED(def) => write!(f, "#FIXED \"{def}\""),
            Self::None(def) => write!(f, "\"{def}\""),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct AttlistDeclMap(
    // (attribute type, default value declaration, is external markup declaration)
    HashMap<Box<str>, HashMap<Box<str>, (AttributeType, DefaultDecl, bool)>>,
);
// declaration for `xml:id`.
// since the `get` method must return a reference, it is provided as a static variable.
static XML_ID_ATTRIBUTE_DECL: (AttributeType, DefaultDecl, bool) =
    (AttributeType::ID, DefaultDecl::IMPLIED, false);

impl AttlistDeclMap {
    /// Returns `true` if newly inserted, and `false` if an element or attribute with
    /// the same name is already registered.
    pub(crate) fn insert(
        &mut self,
        elem_name: impl Into<Box<str>>,
        attr_name: impl Into<Box<str>>,
        att_type: AttributeType,
        default_decl: DefaultDecl,
        is_external_markup: bool,
    ) -> bool {
        use std::collections::hash_map::Entry::*;
        let elem_name: Box<str> = elem_name.into();
        let attr_name: Box<str> = attr_name.into();
        match self.0.entry(elem_name) {
            Vacant(entry) => {
                entry.insert(HashMap::from([(
                    attr_name,
                    (att_type, default_decl, is_external_markup),
                )]));
            }
            Occupied(mut entry) => {
                let map = entry.get_mut();
                match map.entry(attr_name) {
                    Vacant(entry) => {
                        entry.insert((att_type, default_decl, is_external_markup));
                    }
                    Occupied(_) => return false,
                }
            }
        }
        true
    }

    pub(crate) fn get(
        &self,
        elem_name: &str,
        attr_name: &str,
    ) -> Option<&(AttributeType, DefaultDecl, bool)> {
        if let Some(ret) = self.0.get(elem_name).and_then(|map| map.get(attr_name)) {
            return Some(ret);
        }

        if attr_name == "xml:id" {
            // 'xml:id' attribute is considered to be defined as an ID type.
            return Some(&XML_ID_ATTRIBUTE_DECL);
        }

        None
    }

    // pub fn contains(&self, elem_name: &str, attr_name: &str) -> bool {
    //     self.get(elem_name, attr_name).is_some()
    // }

    pub(crate) fn clear(&mut self) {
        self.0.clear();
    }

    pub(crate) fn attlist(
        &self,
        elem_name: &str,
    ) -> Option<impl Iterator<Item = (&str, &(AttributeType, DefaultDecl, bool))>> {
        self.0
            .get(elem_name)
            .map(|map| map.iter().map(|(attr, value)| (attr.as_ref(), value)))
    }

    pub(crate) fn iter_all(
        &self,
    ) -> impl Iterator<Item = (&str, &str, &(AttributeType, DefaultDecl, bool))> {
        self.0.iter().flat_map(|(elem, map)| {
            map.iter()
                .map(move |(attr, value)| (elem.as_ref(), attr.as_ref(), value))
        })
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct ElementDeclMap(HashMap<Box<str>, ContentSpec>);

impl ElementDeclMap {
    pub(crate) fn insert(
        &mut self,
        name: impl Into<Box<str>>,
        contentspec: ContentSpec,
    ) -> Result<(), XMLError> {
        use std::collections::hash_map::Entry::*;
        let name: Box<str> = name.into();
        match self.0.entry(name) {
            Occupied(_) => Err(XMLError::ParserDuplicateElementDecl),
            Vacant(entry) => {
                entry.insert(contentspec);
                Ok(())
            }
        }
    }

    pub(crate) fn get(&self, name: &str) -> Option<&ContentSpec> {
        self.0.get(name)
    }

    pub(crate) fn get_mut(&mut self, name: &str) -> Option<&mut ContentSpec> {
        self.0.get_mut(name)
    }

    // pub fn contains(&self, name: &str) -> bool {
    //     self.0.contains_key(name)
    // }

    pub(crate) fn clear(&mut self) {
        self.0.clear();
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum EntityDecl {
    InternalGeneralEntity {
        base_uri: Arc<URIStr>,
        replacement_text: Box<str>,
        in_external_markup: bool,
    },
    InternalParameterEntity {
        base_uri: Arc<URIStr>,
        replacement_text: Box<str>,
    },
    ExternalGeneralParsedEntity {
        base_uri: Arc<URIStr>,
        system_id: Box<URIStr>,
        public_id: Option<Box<str>>,
        in_external_markup: bool,
    },
    ExternalGeneralUnparsedEntity {
        base_uri: Arc<URIStr>,
        system_id: Box<URIStr>,
        public_id: Option<Box<str>>,
        notation_name: Box<str>,
    },
    ExternalParameterEntity {
        base_uri: Arc<URIStr>,
        system_id: Box<URIStr>,
        public_id: Option<Box<str>>,
    },
}

static PREDEFINED_ENTITY_LT: LazyLock<EntityDecl> =
    LazyLock::new(|| EntityDecl::InternalGeneralEntity {
        base_uri: URIString::parse("?predefined").unwrap().into(),
        replacement_text: "&#60;".into(), // '<', 0x3C
        in_external_markup: false,
    });
static PREDEFINED_ENTITY_GT: LazyLock<EntityDecl> =
    LazyLock::new(|| EntityDecl::InternalGeneralEntity {
        base_uri: URIString::parse("?predefined").unwrap().into(),
        replacement_text: "&#62;".into(), // '>', 0x3E
        in_external_markup: false,
    });
static PREDEFINED_ENTITY_AMP: LazyLock<EntityDecl> =
    LazyLock::new(|| EntityDecl::InternalGeneralEntity {
        base_uri: URIString::parse("?predefined").unwrap().into(),
        replacement_text: "&#38;".into(), // '&', 0x26
        in_external_markup: false,
    });
static PREDEFINED_ENTITY_APOS: LazyLock<EntityDecl> =
    LazyLock::new(|| EntityDecl::InternalGeneralEntity {
        base_uri: URIString::parse("?predefined").unwrap().into(),
        replacement_text: "&#39;".into(), // ''', 0x27
        in_external_markup: false,
    });
static PREDEFINED_ENTITY_QUOT: LazyLock<EntityDecl> =
    LazyLock::new(|| EntityDecl::InternalGeneralEntity {
        base_uri: URIString::parse("?predefined").unwrap().into(),
        replacement_text: "&#34;".into(), // '"', 0x22
        in_external_markup: false,
    });

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct EntityMap(HashMap<Box<str>, EntityDecl>);

impl EntityMap {
    pub(crate) fn insert(
        &mut self,
        name: impl Into<Box<str>>,
        decl: EntityDecl,
    ) -> Result<(), XMLError> {
        use std::collections::hash_map::Entry::*;
        let name: Box<str> = name.into();

        // Report an error for entity value literals of predefined entities with incorrect formats.
        //
        // # Reference
        // [4.6 Predefined Entities](https://www.w3.org/TR/xml/#sec-predefined-ent)
        if matches!(name.as_ref(), "lt" | "gt" | "amp" | "apos" | "quot") {
            let EntityDecl::InternalGeneralEntity {
                replacement_text, ..
            } = &decl
            else {
                return Err(XMLError::ParserIncorrectPredefinedEntityDecl);
            };

            let c = if let Some(code) = replacement_text
                .strip_prefix("&#x")
                .and_then(|t| t.strip_suffix(";"))
            {
                u32::from_str_radix(code, 16)
                    .ok()
                    .and_then(char::from_u32)
                    .ok_or(XMLError::ParserIncorrectPredefinedEntityDecl)?
            } else if let Some(code) = replacement_text
                .strip_prefix("&#")
                .and_then(|t| t.strip_suffix(";"))
            {
                code.parse::<u32>()
                    .ok()
                    .and_then(char::from_u32)
                    .ok_or(XMLError::ParserIncorrectPredefinedEntityDecl)?
            } else {
                if replacement_text.len() != 1 || matches!(name.as_ref(), "lt" | "amp") {
                    return Err(XMLError::ParserIncorrectPredefinedEntityDecl);
                }
                replacement_text.chars().next().unwrap()
            };

            let ret = match name.as_ref() {
                "lt" => c == '<',
                "gt" => c == '>',
                "amp" => c == '&',
                "apos" => c == '\'',
                "quot" => c == '"',
                _ => unreachable!(),
            };

            if !ret {
                return Err(XMLError::ParserIncorrectPredefinedEntityDecl);
            }
        }

        match self.0.entry(name) {
            Occupied(_) => Err(XMLError::ParserDuplicateEntityDecl),
            Vacant(entry) => {
                entry.insert(decl);
                Ok(())
            }
        }
    }

    pub(crate) fn get(&self, name: &str) -> Option<&EntityDecl> {
        match name {
            "lt" => Some(&PREDEFINED_ENTITY_LT),
            "gt" => Some(&PREDEFINED_ENTITY_GT),
            "amp" => Some(&PREDEFINED_ENTITY_AMP),
            "apos" => Some(&PREDEFINED_ENTITY_APOS),
            "quot" => Some(&PREDEFINED_ENTITY_QUOT),
            _ => self.0.get(name),
        }
    }

    pub(crate) fn clear(&mut self) {
        self.0.clear();
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &EntityDecl)> {
        self.0.iter().map(|(name, decl)| (name.as_ref(), decl))
    }
}

static ARC_XML_XML_NAMESPACE_PREFIX: LazyLock<Arc<str>> = LazyLock::new(|| "xml".into());
static ARC_XML_XML_NAMESPACE: LazyLock<Arc<str>> = LazyLock::new(|| XML_XML_NAMESPACE.into());

/// Namespace mapping.
#[derive(Debug, Clone)]
pub struct Namespace {
    /// Namespace prefix. If no prefix is bound, set `""`.
    pub prefix: Arc<str>,
    /// Namespace name.
    pub namespace_name: Arc<str>,
}

/// Namespace declaration stack.
pub struct NamespaceStack {
    // (namespace, before overwrite)
    // Namespaces declared closer to the document element appear earlier in the list.
    // The second `usize` is the position of the namespace that bound the same prefix until
    // the namespace declaration appeared. If there is no such namespace, it is `usize::MAX`.
    namespaces: Vec<(Namespace, usize)>,
    // (prefix, position in `namespaces`)
    prefix_map: BTreeMap<Arc<str>, usize>,
}

impl NamespaceStack {
    /// Check if `prefix` is declared in this stack.
    pub fn is_declared(&self, prefix: &str) -> bool {
        self.prefix_map.contains_key(prefix)
    }

    /// The depth of this stack.
    pub fn len(&self) -> usize {
        self.namespaces.len()
    }

    /// Check if no namespaces are declared.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// If `prefix` is declared, return declared namespace,
    /// otherwise return [`None`].
    pub fn get(&self, prefix: &str) -> Option<Namespace> {
        let &index = self.prefix_map.get(prefix)?;
        Some(self.namespaces[index].0.clone())
    }

    pub(crate) fn push(&mut self, prefix: &str, namespace_name: &str) {
        if let Some(index) = self.prefix_map.get_mut(prefix) {
            let previous = *index;
            *index = self.namespaces.len();
            self.namespaces.push((
                Namespace {
                    prefix: self.namespaces[previous].0.prefix.clone(),
                    namespace_name: namespace_name.into(),
                },
                previous,
            ));
        } else {
            let namespace = Namespace {
                prefix: prefix.into(),
                namespace_name: namespace_name.into(),
            };
            self.prefix_map
                .insert(namespace.prefix.clone(), self.namespaces.len());
            self.namespaces.push((namespace, usize::MAX));
        }
    }

    pub(crate) fn pop(&mut self) -> Option<Namespace> {
        if self.len() == 1 {
            return None;
        }
        let (namespace, previous) = self.namespaces.pop().unwrap();
        if previous < usize::MAX {
            *self.prefix_map.get_mut(&namespace.prefix).unwrap() = previous;
        } else {
            self.prefix_map.remove(&namespace.prefix);
        }
        Some(namespace)
    }

    pub(crate) fn truncate(&mut self, depth: usize) {
        while self.namespaces.len() > depth {
            self.pop();
        }
    }

    pub(crate) fn clear(&mut self) {
        self.truncate(1);
    }

    /// Generate a namespace iterator.
    pub fn iter(&self) -> NsIter<'_> {
        self.into_iter()
    }
}

impl Default for NamespaceStack {
    fn default() -> Self {
        Self {
            namespaces: vec![(
                Namespace {
                    prefix: ARC_XML_XML_NAMESPACE_PREFIX.clone(),
                    namespace_name: ARC_XML_XML_NAMESPACE.clone(),
                },
                usize::MAX,
            )],
            prefix_map: BTreeMap::from([(ARC_XML_XML_NAMESPACE_PREFIX.clone(), 0)]),
        }
    }
}

/// Namespace iterator.
pub struct NsIter<'a> {
    iter: std::collections::btree_map::Iter<'a, Arc<str>, usize>,
    stack: &'a NamespaceStack,
}

impl<'a> Iterator for NsIter<'a> {
    type Item = &'a Namespace;

    fn next(&mut self) -> Option<Self::Item> {
        let (_, index) = self.iter.next()?;
        Some(&self.stack.namespaces[*index].0)
    }
}

impl<'a> IntoIterator for &'a NamespaceStack {
    type IntoIter = NsIter<'a>;
    type Item = &'a Namespace;

    fn into_iter(self) -> Self::IntoIter {
        NsIter {
            iter: self.prefix_map.iter(),
            stack: self,
        }
    }
}

/// Notation.
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct Notation {
    /// Notation name.
    pub name: Box<str>,
    /// System identifier of this notation.
    pub system_id: Option<Box<str>>,
    /// Public identifier of this notation.
    pub public_id: Option<Box<str>>,
}

/// A locator indicating the parser's current position within the document.
///
/// Basically, this object has no meaning except during document parsing.
pub struct Locator {
    system_id: RwLock<Arc<URIStr>>,
    public_id: RwLock<Option<Arc<str>>>,
    line: AtomicUsize,
    column: AtomicUsize,
}

impl Locator {
    pub(crate) fn new(
        system_id: Arc<URIStr>,
        public_id: Option<Arc<str>>,
        line: usize,
        column: usize,
    ) -> Self {
        Self {
            system_id: RwLock::new(system_id),
            public_id: RwLock::new(public_id),
            line: line.into(),
            column: column.into(),
        }
    }

    /// The system identifier for the current document.
    pub fn system_id(&self) -> Arc<URIStr> {
        self.system_id.read().unwrap().clone()
    }

    /// The public identifier for the current document.
    pub fn public_id(&self) -> Option<Arc<str>> {
        self.public_id.read().unwrap().clone()
    }

    /// Line number in the parsing process.
    pub fn line(&self) -> usize {
        self.line.load(Ordering::Acquire)
    }

    /// Offset from the first character within the line at the position being processed.
    pub fn column(&self) -> usize {
        self.column.load(Ordering::Acquire)
    }

    pub(crate) fn set_system_id(&self, system_id: Arc<URIStr>) {
        *self.system_id.write().unwrap() = system_id;
    }

    pub(crate) fn set_public_id(&self, public_id: Option<Arc<str>>) {
        *self.public_id.write().unwrap() = public_id;
    }

    pub(crate) fn set_line(&self, line: usize) {
        self.line.store(line, Ordering::Release);
    }

    pub(crate) fn set_column(&self, column: usize) {
        self.column.store(column, Ordering::Release);
    }

    pub(crate) fn update_line(&self, f: impl Fn(usize) -> usize) {
        while self
            .line
            .fetch_update(Ordering::Release, Ordering::Acquire, |line| Some(f(line)))
            .is_err()
        {}
    }

    pub(crate) fn update_column(&self, f: impl Fn(usize) -> usize) {
        while self
            .column
            .fetch_update(Ordering::Release, Ordering::Acquire, |column| {
                Some(f(column))
            })
            .is_err()
        {}
    }
}

impl Default for Locator {
    fn default() -> Self {
        let system_id = std::env::current_dir().unwrap_or_default();
        let system_id = URIString::parse_file_path(system_id)
            .unwrap_or_else(|_| URIString::parse("").unwrap())
            .into();
        Self::new(system_id, None, 1, 1)
    }
}