Skip to main content

einvoice_xml/
reader.rs

1//! The pull parser.
2
3use std::borrow::Cow;
4use std::collections::HashSet;
5use std::ops::Range;
6
7use crate::chars::{self, find_non_xml_char, is_ascii_name, is_space, starts_with_name_start};
8use crate::decode::{self, Problem};
9use crate::event::{
10    Attribute, Comment, EndElement, Event, Name, ProcessingInstruction, StartElement, Text,
11};
12use crate::namespaces::{NONE, Scope};
13use crate::{Error, TextPos};
14
15/// The namespace of the `xml` prefix.
16pub const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
17/// The namespace of the `xmlns` prefix.
18pub const XMLNS_NAMESPACE: &str = "http://www.w3.org/2000/xmlns/";
19
20/// Bounds on what a document may contain, against hostile input. The defaults are those
21/// of `roxmltree` 0.21, so that a document is refused by a limit exactly when it
22/// refuses it.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct Limits {
26    /// Nodes in the document, the document node, elements, text nodes (adjacent
27    /// character data and CDATA sections being one node), comments and processing
28    /// instructions counted: [`Error::NodesLimitReached`] when a node would be the
29    /// `nodes`-th. Default `u32::MAX`.
30    pub nodes: u32,
31    /// Depth of element nesting, the document element at depth 1:
32    /// [`Error::DepthLimitReached`] beyond. Default `u32::MAX`.
33    pub depth: u32,
34    /// Attributes in the document, namespace declarations not counted:
35    /// [`Error::AttributesLimitReached`] when the attributes of an element would bring
36    /// the count to `attributes`. Default `u32::MAX`.
37    pub attributes: u32,
38    /// Distinct (prefix, namespace name) declarations in the document, the predefined
39    /// `xml` prefix counted: [`Error::NamespacesLimitReached`] when a new one would
40    /// bring the count to `namespaces`. Default `65536`.
41    pub namespaces: u32,
42}
43
44impl Default for Limits {
45    fn default() -> Self {
46        Self {
47            nodes: u32::MAX,
48            depth: u32::MAX,
49            attributes: u32::MAX,
50            namespaces: 65536,
51        }
52    }
53}
54
55impl Limits {
56    /// The defaults with another node limit.
57    #[must_use]
58    pub const fn with_nodes(mut self, nodes: u32) -> Self {
59        self.nodes = nodes;
60        self
61    }
62
63    /// The defaults with another depth limit.
64    #[must_use]
65    pub const fn with_depth(mut self, depth: u32) -> Self {
66        self.depth = depth;
67        self
68    }
69
70    /// The defaults with another attribute limit.
71    #[must_use]
72    pub const fn with_attributes(mut self, attributes: u32) -> Self {
73        self.attributes = attributes;
74        self
75    }
76
77    /// The defaults with another namespace limit.
78    #[must_use]
79    pub const fn with_namespaces(mut self, namespaces: u32) -> Self {
80        self.namespaces = namespaces;
81        self
82    }
83}
84
85/// The namespace of a name: none, the `xml` namespace, or a binding of the scope.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub(crate) enum Ns {
88    None,
89    Xml,
90    Binding(u32),
91}
92
93/// A qualified name as written.
94#[derive(Clone, Copy)]
95struct QName<'a> {
96    prefix: &'a str,
97    local: &'a str,
98    /// Written with a colon and an empty prefix (`:a`).
99    empty_prefix: bool,
100}
101
102/// An attribute of the current start tag (namespace declarations excluded).
103#[derive(Debug)]
104pub(crate) struct AttributeData<'a> {
105    pub(crate) prefix: &'a str,
106    pub(crate) local: &'a str,
107    pub(crate) value: Cow<'a, str>,
108    pub(crate) raw: &'a str,
109    pub(crate) ns: Ns,
110    pub(crate) range: Range<usize>,
111}
112
113/// An open element.
114#[derive(Debug)]
115pub(crate) struct Open<'a> {
116    pub(crate) prefix: &'a str,
117    pub(crate) local: &'a str,
118    pub(crate) ns: Ns,
119    /// The number of bindings in scope before its declarations.
120    pub(crate) scope: usize,
121}
122
123#[derive(Clone, Copy, PartialEq, Eq, Debug)]
124enum Phase {
125    /// Before the XML declaration.
126    Start,
127    /// Before the document element.
128    Prolog,
129    /// Inside the document element.
130    Content,
131    /// After the document element (or where it should have been).
132    Epilog,
133    /// Finished.
134    Done,
135}
136
137/// What to do before reading on.
138#[derive(Clone, Copy, PartialEq, Eq, Debug)]
139enum Pending {
140    Nothing,
141    /// Report the end of the empty element just started.
142    EmptyEnd,
143    /// Close the element just ended.
144    Pop,
145}
146
147/// An event before it is given a view of the reader.
148enum Raw<'a> {
149    Start,
150    End,
151    Text(Text<'a>),
152    Comment(Comment<'a>),
153    Pi(ProcessingInstruction<'a>),
154}
155
156/// A streaming parser of an XML 1.0 document with namespaces, read from a string.
157///
158/// [`Reader::next_event`] returns the events one by one; the reader keeps only the
159/// open elements, the namespace declarations in scope and the attributes of the
160/// current start tag. Names, and text without references or carriage returns, are
161/// slices of the input. A document is well-formed when every event up to the final
162/// `None` is read without error; events read before an error belong to a document
163/// that is not.
164#[derive(Debug)]
165pub struct Reader<'a> {
166    text: &'a str,
167    bytes: &'a [u8],
168    pos: usize,
169    limits: Limits,
170    phase: Phase,
171    pending: Pending,
172    pub(crate) stack: Vec<Open<'a>>,
173    pub(crate) scope: Scope<'a>,
174    pub(crate) attributes: Vec<AttributeData<'a>>,
175    /// The byte range of the last start or end tag.
176    pub(crate) tag: Range<usize>,
177    /// Whether the last start tag was an empty-element tag.
178    pub(crate) empty: bool,
179    nodes: u64,
180    attribute_count: u64,
181    /// Whether the last node is a text node (that the next character data joins).
182    in_text: bool,
183    root_seen: bool,
184    failed: Option<Error>,
185    /// The first error of the current token that only this reader reports, raised once
186    /// the checks that `roxmltree` makes on the token have passed.
187    deferred: Option<Error>,
188    /// The number of bindings in scope before the current start tag's declarations.
189    tag_scope: usize,
190    /// What the current start tag declares that `roxmltree` does not track.
191    declared: Declared,
192}
193
194/// Whether the current start tag declares the default namespace, the `xml` prefix.
195#[derive(Clone, Copy, Debug, Default)]
196struct Declared {
197    default: bool,
198    xml: bool,
199}
200
201impl std::fmt::Debug for Scope<'_> {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        f.debug_struct("Scope")
204            .field("bindings", &self.len())
205            .finish()
206    }
207}
208
209impl<'a> Reader<'a> {
210    /// A reader of `text` with the default [`Limits`]. A byte order mark at the start
211    /// is skipped.
212    #[must_use]
213    pub fn new(text: &'a str) -> Self {
214        Self::with_limits(text, Limits::default())
215    }
216
217    /// A reader of `text` with the given limits.
218    #[must_use]
219    pub fn with_limits(text: &'a str, limits: Limits) -> Self {
220        Self {
221            text,
222            bytes: text.as_bytes(),
223            pos: 0,
224            limits,
225            phase: Phase::Start,
226            pending: Pending::Nothing,
227            stack: Vec::new(),
228            scope: Scope::new(),
229            attributes: Vec::new(),
230            tag: 0..0,
231            empty: false,
232            nodes: 1,
233            attribute_count: 0,
234            in_text: false,
235            root_seen: false,
236            failed: None,
237            deferred: None,
238            tag_scope: 0,
239            declared: Declared::default(),
240        }
241    }
242
243    /// The text being read.
244    #[must_use]
245    pub const fn text(&self) -> &'a str {
246        self.text
247    }
248
249    /// The byte offset reached.
250    #[must_use]
251    pub const fn offset(&self) -> usize {
252        self.pos
253    }
254
255    /// The number of open elements: after a [`Event::Start`], its element included;
256    /// after an [`Event::End`], its element still included.
257    #[must_use]
258    pub fn depth(&self) -> usize {
259        self.stack.len()
260    }
261
262    /// The position of a byte offset of the text (see [`TextPos::at`]).
263    #[must_use]
264    pub fn text_pos(&self, offset: usize) -> TextPos {
265        TextPos::at(self.text, offset)
266    }
267
268    /// The namespace bound to `prefix` (`""` for the default namespace) in the scope of
269    /// the innermost open element (the element of the last [`Event::Start`] or
270    /// [`Event::End`] included): `None` if there is none or if the default namespace is
271    /// undeclared. `xml` is always bound to [`XML_NAMESPACE`] and `xmlns` to
272    /// [`XMLNS_NAMESPACE`].
273    #[must_use]
274    pub fn lookup_namespace(&self, prefix: &str) -> Option<&str> {
275        match prefix {
276            "xml" => Some(XML_NAMESPACE),
277            "xmlns" => Some(XMLNS_NAMESPACE),
278            _ => {
279                let index = self.scope.lookup(prefix);
280                (index != NONE)
281                    .then(|| self.scope.uri(index))
282                    .filter(|uri| !uri.is_empty())
283            }
284        }
285    }
286
287    pub(crate) fn namespace(&self, ns: Ns) -> Option<&str> {
288        match ns {
289            Ns::None => None,
290            Ns::Xml => Some(XML_NAMESPACE),
291            Ns::Binding(index) => Some(self.scope.uri(index)).filter(|uri| !uri.is_empty()),
292        }
293    }
294
295    pub(crate) fn name_of(&self, prefix: &'a str, local: &'a str, ns: Ns) -> Name<'_, 'a> {
296        Name {
297            prefix,
298            local,
299            namespace: self.namespace(ns),
300        }
301    }
302
303    pub(crate) fn attribute_view<'r>(&'r self, data: &'r AttributeData<'a>) -> Attribute<'r, 'a> {
304        Attribute {
305            name: self.name_of(data.prefix, data.local, data.ns),
306            value: &data.value,
307            raw: data.raw,
308            range: data.range.clone(),
309        }
310    }
311
312    /// The next event, `Ok(None)` at the end of a well-formed document. After an error,
313    /// the same error again.
314    ///
315    /// # Errors
316    ///
317    /// The first well-formedness error from where the reader is (see [`Error`]).
318    pub fn next_event(&mut self) -> Result<Option<Event<'_, 'a>>, Error> {
319        if let Some(error) = &self.failed {
320            return Err(error.clone());
321        }
322        let raw = match self.advance() {
323            Ok(raw) => raw,
324            Err(error) => {
325                self.phase = Phase::Done;
326                self.failed = Some(error.clone());
327                return Err(error);
328            }
329        };
330        Ok(raw.map(|raw| match raw {
331            Raw::Start => Event::Start(StartElement { reader: self }),
332            Raw::End => Event::End(EndElement { reader: self }),
333            Raw::Text(text) => Event::Text(text),
334            Raw::Comment(comment) => Event::Comment(comment),
335            Raw::Pi(pi) => Event::ProcessingInstruction(pi),
336        }))
337    }
338
339    /// Reads to the end of the document.
340    ///
341    /// # Errors
342    ///
343    /// The first well-formedness error from where the reader is.
344    pub fn read_to_end(&mut self) -> Result<(), Error> {
345        while self.next_event()?.is_some() {}
346        Ok(())
347    }
348
349    fn advance(&mut self) -> Result<Option<Raw<'a>>, Error> {
350        match std::mem::replace(&mut self.pending, Pending::Nothing) {
351            Pending::Nothing => {}
352            Pending::EmptyEnd => {
353                self.pending = Pending::Pop;
354                return Ok(Some(Raw::End));
355            }
356            Pending::Pop => {
357                if let Some(open) = self.stack.pop() {
358                    self.scope.truncate(open.scope);
359                }
360                if self.stack.is_empty() {
361                    self.phase = Phase::Epilog;
362                }
363            }
364        }
365        loop {
366            match self.phase {
367                Phase::Start => {
368                    self.declaration()?;
369                    self.phase = Phase::Prolog;
370                }
371                Phase::Prolog => {
372                    self.skip_spaces();
373                    if self.starts_with(b"<!--") {
374                        return self.comment().map(Some);
375                    }
376                    if self.starts_with(b"<?") {
377                        return self.pi().map(Some);
378                    }
379                    if self.starts_with(b"<!DOCTYPE") {
380                        return Err(Error::DtdDetected);
381                    }
382                    if self.bytes.get(self.pos) == Some(&b'<') && self.start_tag()? {
383                        return Ok(Some(Raw::Start));
384                    }
385                    // No document element, or the text ends in its start tag.
386                    self.phase = Phase::Epilog;
387                }
388                Phase::Content => {
389                    let Some(&b) = self.bytes.get(self.pos) else {
390                        self.phase = Phase::Epilog;
391                        continue;
392                    };
393                    if b != b'<' {
394                        return self.text_token().map(Some);
395                    }
396                    match self.bytes.get(self.pos + 1) {
397                        None => return Err(Error::UnknownToken(self.text_pos(self.pos))),
398                        Some(b'!') => {
399                            if self.starts_with(b"<!--") {
400                                return self.comment().map(Some);
401                            }
402                            if self.starts_with(b"<![CDATA[") {
403                                return self.cdata().map(Some);
404                            }
405                            return Err(Error::UnknownToken(self.text_pos(self.pos)));
406                        }
407                        Some(b'?') => return self.pi().map(Some),
408                        Some(b'/') => return self.end_tag().map(Some),
409                        Some(_) => {
410                            if self.start_tag()? {
411                                return Ok(Some(Raw::Start));
412                            }
413                            // The text ends in the start tag: the next turn ends it.
414                        }
415                    }
416                }
417                Phase::Epilog => {
418                    self.skip_spaces();
419                    if self.starts_with(b"<!--") {
420                        return self.comment().map(Some);
421                    }
422                    if self.starts_with(b"<?") {
423                        return self.pi().map(Some);
424                    }
425                    if self.pos < self.bytes.len() {
426                        return Err(Error::UnknownToken(self.text_pos(self.pos)));
427                    }
428                    self.phase = Phase::Done;
429                    if !self.root_seen {
430                        return Err(Error::NoRootNode);
431                    }
432                    if !self.stack.is_empty() {
433                        return Err(Error::UnclosedRootNode);
434                    }
435                    return Ok(None);
436                }
437                Phase::Done => return Ok(None),
438            }
439        }
440    }
441
442    // --- The cursor.
443
444    fn starts_with(&self, prefix: &[u8]) -> bool {
445        self.bytes
446            .get(self.pos..)
447            .is_some_and(|rest| rest.starts_with(prefix))
448    }
449
450    fn skip_spaces(&mut self) {
451        while self.bytes.get(self.pos).is_some_and(|&b| is_space(b)) {
452            self.pos += 1;
453        }
454    }
455
456    fn at_space(&self) -> bool {
457        self.bytes.get(self.pos).is_some_and(|&b| is_space(b))
458    }
459
460    fn current(&self) -> Result<u8, Error> {
461        self.bytes
462            .get(self.pos)
463            .copied()
464            .ok_or(Error::UnexpectedEndOfStream)
465    }
466
467    fn consume_byte(&mut self, expected: u8) -> Result<(), Error> {
468        let actual = self.current()?;
469        if actual != expected {
470            return Err(Error::InvalidChar {
471                expected,
472                actual,
473                pos: self.text_pos(self.pos),
474            });
475        }
476        self.pos += 1;
477        Ok(())
478    }
479
480    fn skip_string(&mut self, expected: &'static str) -> Result<(), Error> {
481        if !self.starts_with(expected.as_bytes()) {
482            return Err(Error::InvalidString(expected, self.text_pos(self.pos)));
483        }
484        self.pos += expected.len();
485        Ok(())
486    }
487
488    /// `S? '=' S?`
489    fn consume_eq(&mut self) -> Result<(), Error> {
490        self.skip_spaces();
491        self.consume_byte(b'=')?;
492        self.skip_spaces();
493        Ok(())
494    }
495
496    fn consume_quote(&mut self) -> Result<u8, Error> {
497        let c = self.current()?;
498        if c == b'\'' || c == b'"' {
499            self.pos += 1;
500            Ok(c)
501        } else {
502            Err(Error::ExpectedChar {
503                expected: "a quote",
504                actual: c,
505                pos: self.text_pos(self.pos),
506            })
507        }
508    }
509
510    /// Checks that `[start, end)` holds only XML characters.
511    fn check_chars(&self, start: usize, end: usize) -> Result<(), Error> {
512        match find_non_xml_char(&self.text[start..end]) {
513            None => Ok(()),
514            Some((offset, c)) => Err(Error::NonXmlChar(c, self.text_pos(start + offset))),
515        }
516    }
517
518    /// The offset of the first `needle` at or after `from`, or the end of the text.
519    fn find(&self, from: usize, needle: &[u8]) -> Option<usize> {
520        memchr::memmem::find(&self.bytes[from..], needle).map(|n| from + n)
521    }
522
523    /// A qualified name: `Name` with at most one colon, the prefix (if any) and the
524    /// local part each starting with a `NameStartChar`.
525    fn qname(&mut self) -> Result<QName<'a>, Error> {
526        let start = self.pos;
527        let mut colon = None;
528        while let Some(&b) = self.bytes.get(self.pos) {
529            if b < 0x80 {
530                if b == b':' {
531                    if colon.is_some() {
532                        return Err(Error::InvalidName(self.text_pos(start)));
533                    }
534                    colon = Some(self.pos);
535                    self.pos += 1;
536                } else if is_ascii_name(b) {
537                    self.pos += 1;
538                } else {
539                    break;
540                }
541            } else {
542                match self.text[self.pos..].chars().next() {
543                    Some(c) if chars::is_name(c) => self.pos += c.len_utf8(),
544                    _ => break,
545                }
546            }
547        }
548        let text = self.text;
549        let (prefix, local) = match colon {
550            Some(colon) => (&text[start..colon], &text[colon + 1..self.pos]),
551            None => ("", &text[start..self.pos]),
552        };
553        if (!prefix.is_empty() && !starts_with_name_start(prefix)) || !starts_with_name_start(local)
554        {
555            return Err(Error::InvalidName(self.text_pos(start)));
556        }
557        Ok(QName {
558            prefix,
559            local,
560            empty_prefix: colon == Some(start),
561        })
562    }
563
564    /// A `Name` (colons allowed).
565    fn name(&mut self) -> Result<&'a str, Error> {
566        let start = self.pos;
567        match self.text[self.pos..].chars().next() {
568            Some(c) if chars::is_name_start(c) => self.pos += c.len_utf8(),
569            _ => return Err(Error::InvalidName(self.text_pos(start))),
570        }
571        while let Some(c) = self.text[self.pos..].chars().next() {
572            if !chars::is_name(c) {
573                break;
574            }
575            self.pos += c.len_utf8();
576        }
577        Ok(&self.text[start..self.pos])
578    }
579
580    fn defer(&mut self, error: Error) {
581        if self.deferred.is_none() {
582            self.deferred = Some(error);
583        }
584    }
585
586    fn raise_deferred(&mut self) -> Result<(), Error> {
587        match self.deferred.take() {
588            Some(error) => Err(error),
589            None => Ok(()),
590        }
591    }
592
593    fn count_node(&mut self) -> Result<(), Error> {
594        if self.nodes >= u64::from(self.limits.nodes) {
595            return Err(Error::NodesLimitReached);
596        }
597        self.nodes += 1;
598        Ok(())
599    }
600
601    fn decode_error(&self, problem: &Problem<'_>, base: usize) -> Error {
602        match problem {
603            Problem::UnknownEntity(name, at) => {
604                Error::UnknownEntityReference((*name).to_owned(), self.text_pos(base + at))
605            }
606            Problem::Malformed(at) => Error::MalformedEntityReference(self.text_pos(base + at)),
607        }
608    }
609
610    // --- The prolog.
611
612    /// The XML declaration, if the text starts with one (after a byte order mark).
613    fn declaration(&mut self) -> Result<(), Error> {
614        if self.starts_with("\u{FEFF}".as_bytes()) {
615            self.pos += 3;
616        }
617        if !(self.starts_with(b"<?xml")
618            && self.bytes.get(self.pos + 5).is_some_and(|&b| is_space(b)))
619        {
620            return Ok(());
621        }
622        self.pos += 5;
623        self.declaration_spaces()?;
624        if !self.starts_with(b"version") {
625            return Err(Error::InvalidString("version", self.text_pos(self.pos)));
626        }
627        let version = self.pseudo_attribute()?;
628        self.declaration_spaces()?;
629        let encoding = if self.starts_with(b"encoding") {
630            let encoding = self.pseudo_attribute()?;
631            self.declaration_spaces()?;
632            Some(encoding)
633        } else {
634            None
635        };
636        let standalone = if self.starts_with(b"standalone") {
637            Some(self.pseudo_attribute()?)
638        } else {
639            None
640        };
641        self.skip_spaces();
642        self.skip_string("?>")?;
643
644        // What `roxmltree` does not check.
645        let check = |(name_start, name, value_start, value): (usize, &str, usize, &str),
646                     expected: &str,
647                     valid: fn(&str) -> bool,
648                     reason: &'static str| {
649            if name != expected {
650                return Err(Error::InvalidXmlDeclaration(
651                    "unknown pseudo-attribute",
652                    TextPos::at(self.text, name_start),
653                ));
654            }
655            if !valid(value) {
656                return Err(Error::InvalidXmlDeclaration(
657                    reason,
658                    TextPos::at(self.text, value_start),
659                ));
660            }
661            Ok(())
662        };
663        check(
664            version,
665            "version",
666            |v| {
667                v.strip_prefix("1.")
668                    .is_some_and(|d| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()))
669            },
670            "the version is not 1. followed by digits",
671        )?;
672        if let Some(encoding) = encoding {
673            check(
674                encoding,
675                "encoding",
676                |e| {
677                    e.bytes().next().is_some_and(|b| b.is_ascii_alphabetic())
678                        && e.bytes()
679                            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
680                },
681                "the encoding is not an encoding name",
682            )?;
683        }
684        if let Some(standalone) = standalone {
685            check(
686                standalone,
687                "standalone",
688                |s| s == "yes" || s == "no",
689                "standalone is neither yes nor no",
690            )?;
691        }
692        Ok(())
693    }
694
695    /// The whitespace required before a pseudo-attribute, unless the declaration ends.
696    fn declaration_spaces(&mut self) -> Result<(), Error> {
697        if self.at_space() {
698            self.skip_spaces();
699        } else if let Some(&actual) = self.bytes.get(self.pos)
700            && !self.starts_with(b"?>")
701        {
702            return Err(Error::ExpectedChar {
703                expected: "a whitespace",
704                actual,
705                pos: self.text_pos(self.pos),
706            });
707        }
708        Ok(())
709    }
710
711    /// A pseudo-attribute of the XML declaration: its name as written, the offsets of
712    /// the name and of the value, and the value.
713    fn pseudo_attribute(&mut self) -> Result<(usize, &'a str, usize, &'a str), Error> {
714        let name_start = self.pos;
715        self.qname()?;
716        let name = &self.text[name_start..self.pos];
717        self.consume_eq()?;
718        let quote = self.consume_quote()?;
719        let value_start = self.pos;
720        let end = self.bytes[value_start..]
721            .iter()
722            .position(|&b| b == quote || b == b'<')
723            .map_or(self.bytes.len(), |n| value_start + n);
724        self.check_chars(value_start, end)?;
725        self.pos = end;
726        let value = &self.text[value_start..end];
727        self.consume_byte(quote)?;
728        Ok((name_start, name, value_start, value))
729    }
730
731    // --- Comments, processing instructions, character data.
732
733    fn comment(&mut self) -> Result<Raw<'a>, Error> {
734        let start = self.pos;
735        let body = start + 4;
736        let end = self.find(body, b"-->");
737        self.check_chars(body, end.unwrap_or(self.bytes.len()))?;
738        let Some(end) = end else {
739            self.pos = self.bytes.len();
740            return Err(Error::InvalidString("-->", self.text_pos(self.pos)));
741        };
742        self.pos = end + 3;
743        let value = &self.text[body..end];
744        if value.contains("--") || value.ends_with('-') {
745            return Err(Error::InvalidComment(self.text_pos(start)));
746        }
747        self.in_text = false;
748        self.count_node()?;
749        Ok(Raw::Comment(Comment {
750            value: decode::line_ends(value),
751            range: start..self.pos,
752        }))
753    }
754
755    fn pi(&mut self) -> Result<Raw<'a>, Error> {
756        if self.starts_with(b"<?xml ") {
757            return Err(Error::UnexpectedDeclaration(self.text_pos(self.pos)));
758        }
759        let start = self.pos;
760        self.pos += 2;
761        let target_start = self.pos;
762        let target = self.name()?;
763        let target_end = self.pos;
764        self.skip_spaces();
765        let data = self.pos;
766        let end = self.find(data, b"?>");
767        self.check_chars(data, end.unwrap_or(self.bytes.len()))?;
768        let Some(end) = end else {
769            self.pos = self.bytes.len();
770            return Err(Error::InvalidString("?>", self.text_pos(self.pos)));
771        };
772        self.pos = end + 2;
773        // What `roxmltree` does not check.
774        if target.contains(':') || target.eq_ignore_ascii_case("xml") {
775            return Err(Error::InvalidPiTarget(self.text_pos(target_start)));
776        }
777        if data == target_end && data != end {
778            return Err(Error::PiWithoutWhitespace(self.text_pos(target_end)));
779        }
780        self.in_text = false;
781        self.count_node()?;
782        let value = &self.text[data..end];
783        Ok(Raw::Pi(ProcessingInstruction {
784            target,
785            value: (!value.is_empty()).then(|| decode::line_ends(value)),
786            range: start..self.pos,
787        }))
788    }
789
790    fn cdata(&mut self) -> Result<Raw<'a>, Error> {
791        let start = self.pos;
792        let body = start + 9;
793        let end = self.find(body, b"]]>");
794        self.check_chars(body, end.unwrap_or(self.bytes.len()))?;
795        let Some(end) = end else {
796            self.pos = self.bytes.len();
797            return Err(Error::InvalidString("]]>", self.text_pos(self.pos)));
798        };
799        self.pos = end + 3;
800        self.text_node()?;
801        Ok(Raw::Text(Text {
802            value: decode::line_ends(&self.text[body..end]),
803            range: start..self.pos,
804            cdata: true,
805        }))
806    }
807
808    fn text_token(&mut self) -> Result<Raw<'a>, Error> {
809        let start = self.pos;
810        let end =
811            memchr::memchr(b'<', &self.bytes[start..]).map_or(self.bytes.len(), |n| start + n);
812        self.check_chars(start, end)?;
813        self.pos = end;
814        let raw = &self.text[start..end];
815        if memchr::memchr(b'>', raw.as_bytes()).is_some() && raw.contains("]]>") {
816            return Err(Error::InvalidCharacterData(self.text_pos(end)));
817        }
818        let (value, not_scalar) = decode::text(raw).map_err(|p| self.decode_error(&p, start))?;
819        if let Some(at) = not_scalar {
820            return Err(Error::InvalidCharacterReference(self.text_pos(start + at)));
821        }
822        self.text_node()?;
823        Ok(Raw::Text(Text {
824            value,
825            range: start..end,
826            cdata: false,
827        }))
828    }
829
830    /// Character data: a new text node unless it joins the last one.
831    fn text_node(&mut self) -> Result<(), Error> {
832        if !self.in_text {
833            self.count_node()?;
834            self.in_text = true;
835        }
836        Ok(())
837    }
838
839    // --- Tags.
840
841    /// A start tag, from its `<`: `true` once it is read, `false` if the text ends in
842    /// it.
843    fn start_tag(&mut self) -> Result<bool, Error> {
844        let start = self.pos;
845        self.pos += 1;
846        let name = self.qname()?;
847        self.in_text = false;
848        if name.prefix == "xmlns" {
849            return Err(Error::InvalidElementNamePrefix(self.text_pos(start + 1)));
850        }
851        self.deferred = None;
852        if name.empty_prefix {
853            self.defer(Error::InvalidQName(self.text_pos(start + 1)));
854        }
855        self.attributes.clear();
856        self.declared = Declared::default();
857        let scope = self.scope.len();
858        self.tag_scope = scope;
859        while self.pos < self.bytes.len() {
860            let has_space = self.at_space();
861            self.skip_spaces();
862            let attribute_start = self.pos;
863            match self.current()? {
864                b'/' => {
865                    self.pos += 1;
866                    self.consume_byte(b'>')?;
867                    self.open(start, name, scope, true)?;
868                    return Ok(true);
869                }
870                b'>' => {
871                    self.pos += 1;
872                    self.open(start, name, scope, false)?;
873                    return Ok(true);
874                }
875                actual => {
876                    if !has_space {
877                        return Err(Error::ExpectedChar {
878                            expected: "a whitespace",
879                            actual,
880                            pos: self.text_pos(self.pos),
881                        });
882                    }
883                    let attribute = self.qname()?;
884                    self.consume_eq()?;
885                    let quote = self.consume_quote()?;
886                    let value_start = self.pos;
887                    let Some(n) = memchr::memchr2(quote, b'<', &self.bytes[value_start..]) else {
888                        return Err(Error::UnexpectedEndOfStream);
889                    };
890                    let value_end = value_start + n;
891                    self.check_chars(value_start, value_end)?;
892                    self.pos = value_end;
893                    self.consume_byte(quote)?;
894                    let raw = &self.text[value_start..value_end];
895                    self.attribute(attribute_start..self.pos, attribute, raw, value_start)?;
896                }
897            }
898        }
899        self.scope.truncate(scope);
900        Ok(false)
901    }
902
903    /// An attribute or namespace declaration of the current start tag.
904    fn attribute(
905        &mut self,
906        range: Range<usize>,
907        name: QName<'a>,
908        raw: &'a str,
909        value_start: usize,
910    ) -> Result<(), Error> {
911        let (text, at) = (self.text, range.start);
912        let pos = move || TextPos::at(text, at);
913        if name.empty_prefix {
914            self.defer(Error::InvalidQName(pos()));
915        }
916        let (value, not_scalar) =
917            decode::attribute(raw).map_err(|p| self.decode_error(&p, value_start))?;
918        if let Some(at) = not_scalar {
919            self.defer(Error::InvalidCharacterReference(
920                self.text_pos(value_start + at),
921            ));
922        }
923        if name.prefix == "xmlns" {
924            if value == XMLNS_NAMESPACE {
925                return Err(Error::UnexpectedXmlnsUri(pos()));
926            }
927            let xml = value == XML_NAMESPACE;
928            if name.local == "xml" {
929                if !xml {
930                    return Err(Error::InvalidXmlPrefixUri(pos()));
931                }
932            } else if xml {
933                return Err(Error::UnexpectedXmlUri(pos()));
934            }
935            let scope_start = self.tag_scope;
936            if self.scope.declared_since(scope_start, name.local) {
937                return Err(Error::DuplicatedNamespace(name.local.to_owned(), pos()));
938            }
939            if xml {
940                if self.declared.xml {
941                    self.defer(Error::DuplicatedNamespaceDeclaration(
942                        "xmlns:xml".to_owned(),
943                        pos(),
944                    ));
945                }
946                self.declared.xml = true;
947                return Ok(());
948            }
949            if name.local == "xmlns" {
950                self.defer(Error::XmlnsPrefixDeclared(pos()));
951            }
952            if value.is_empty() {
953                self.defer(Error::EmptyPrefixedNamespace(name.local.to_owned(), pos()));
954            }
955            self.scope.push(name.local, value, self.limits.namespaces)?;
956        } else if name.local == "xmlns" {
957            if value == XML_NAMESPACE {
958                return Err(Error::UnexpectedXmlUri(pos()));
959            }
960            if value == XMLNS_NAMESPACE {
961                return Err(Error::UnexpectedXmlnsUri(pos()));
962            }
963            if !name.prefix.is_empty() {
964                self.defer(Error::PrefixedXmlnsAttribute(
965                    format!("{}:xmlns", name.prefix),
966                    pos(),
967                ));
968            } else if self.declared.default {
969                self.defer(Error::DuplicatedNamespaceDeclaration(
970                    "xmlns".to_owned(),
971                    pos(),
972                ));
973            }
974            self.declared.default = true;
975            self.scope.push("", value, self.limits.namespaces)?;
976        } else {
977            self.attributes.push(AttributeData {
978                prefix: name.prefix,
979                local: name.local,
980                value,
981                raw,
982                ns: Ns::None,
983                range,
984            });
985        }
986        Ok(())
987    }
988
989    /// The end of a start tag: names resolved, duplicates refused, the element opened.
990    fn open(
991        &mut self,
992        start: usize,
993        name: QName<'a>,
994        scope: usize,
995        empty: bool,
996    ) -> Result<(), Error> {
997        self.in_text = false;
998        if !self.attributes.is_empty() {
999            let count = self.attributes.len() as u64;
1000            if self.attribute_count + count >= u64::from(self.limits.attributes) {
1001                return Err(Error::AttributesLimitReached);
1002            }
1003            self.resolve_attributes()?;
1004            self.attribute_count += count;
1005        }
1006        let ns = if name.prefix.is_empty() {
1007            match self.scope.lookup("") {
1008                NONE => Ns::None,
1009                index => Ns::Binding(index),
1010            }
1011        } else {
1012            match self.scope.lookup(name.prefix) {
1013                NONE => {
1014                    return Err(Error::UnknownNamespace(
1015                        name.prefix.to_owned(),
1016                        self.text_pos(start + 1),
1017                    ));
1018                }
1019                index => Ns::Binding(index),
1020            }
1021        };
1022        self.raise_deferred()?;
1023        self.count_node()?;
1024        if self.stack.len() >= self.limits.depth as usize {
1025            return Err(Error::DepthLimitReached);
1026        }
1027        self.stack.push(Open {
1028            prefix: name.prefix,
1029            local: name.local,
1030            ns,
1031            scope,
1032        });
1033        self.tag = start..self.pos;
1034        self.empty = empty;
1035        self.root_seen = true;
1036        self.phase = Phase::Content;
1037        if empty {
1038            self.pending = Pending::EmptyEnd;
1039        }
1040        Ok(())
1041    }
1042
1043    /// Resolves the prefixes of the attributes of the current start tag and refuses
1044    /// two with the same expanded name, in document order.
1045    fn resolve_attributes(&mut self) -> Result<(), Error> {
1046        let Self {
1047            attributes,
1048            scope,
1049            text,
1050            ..
1051        } = self;
1052        let uri = |ns: Ns| match ns {
1053            Ns::None => None,
1054            Ns::Xml => Some(XML_NAMESPACE),
1055            Ns::Binding(index) => Some(scope.uri(index)),
1056        };
1057        let mut seen: HashSet<(Option<&str>, &str)> = HashSet::new();
1058        let hashed = attributes.len() > 8;
1059        for i in 0..attributes.len() {
1060            let attribute = &attributes[i];
1061            let ns = if attribute.prefix == "xml" {
1062                Ns::Xml
1063            } else if attribute.prefix.is_empty() {
1064                Ns::None
1065            } else {
1066                match scope.lookup(attribute.prefix) {
1067                    NONE => {
1068                        return Err(Error::UnknownNamespace(
1069                            attribute.prefix.to_owned(),
1070                            TextPos::at(text, attribute.range.start),
1071                        ));
1072                    }
1073                    index => Ns::Binding(index),
1074                }
1075            };
1076            let key = (uri(ns), attribute.local);
1077            let duplicate = if hashed {
1078                !seen.insert(key)
1079            } else {
1080                attributes[..i].iter().any(|a| (uri(a.ns), a.local) == key)
1081            };
1082            if duplicate {
1083                return Err(Error::DuplicatedAttribute(
1084                    attribute.local.to_owned(),
1085                    TextPos::at(text, attribute.range.start),
1086                ));
1087            }
1088            attributes[i].ns = ns;
1089        }
1090        Ok(())
1091    }
1092
1093    /// An end tag, from its `</`.
1094    fn end_tag(&mut self) -> Result<Raw<'a>, Error> {
1095        let start = self.pos;
1096        self.pos += 2;
1097        let name = self.qname()?;
1098        self.skip_spaces();
1099        self.consume_byte(b'>')?;
1100        self.in_text = false;
1101        if let Some(open) = self.stack.last()
1102            && (open.prefix != name.prefix || open.local != name.local)
1103        {
1104            return Err(Error::UnexpectedCloseTag {
1105                expected: qualified(open.prefix, open.local),
1106                actual: qualified(name.prefix, name.local),
1107                pos: self.text_pos(start),
1108            });
1109        }
1110        if name.empty_prefix {
1111            return Err(Error::InvalidQName(self.text_pos(start + 2)));
1112        }
1113        self.tag = start..self.pos;
1114        self.empty = false;
1115        self.pending = Pending::Pop;
1116        Ok(Raw::End)
1117    }
1118}
1119
1120fn qualified(prefix: &str, local: &str) -> String {
1121    if prefix.is_empty() {
1122        local.to_owned()
1123    } else {
1124        format!("{prefix}:{local}")
1125    }
1126}