Skip to main content

parsec_xml/
parse.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The parser: the prolog, elements and their attributes, character data,
5//! references, and the tree they make. The internal subset is in `dtd.rs`.
6//!
7//! Elements are kept on a stack of their own, so nesting costs no
8//! recursion. Only entity expansion recurses, and its depth is capped.
9
10use std::borrow::Cow;
11use std::collections::{HashMap, HashSet};
12use std::rc::Rc;
13
14use parsec_base::{Budget, Diagnostic, Span};
15
16use crate::Options;
17use crate::chars::{is_char, is_name_start, is_space, name_len};
18use crate::tree::{
19    AttrData, Data, Document, NONE, NS_XML, NS_XMLNS, PREFIX_XML, PREFIX_XMLNS, Str, XML_NS,
20    XMLNS_NS, XmlDecl,
21};
22
23pub(crate) type R<T> = Result<T, Diagnostic>;
24
25pub(crate) fn err(
26    code: &'static str,
27    span: Span,
28    message: impl Into<Cow<'static, str>>,
29) -> Diagnostic {
30    Diagnostic::error(code, span, message)
31}
32
33/// However deep [`Options::max_entity_depth`] says entities may nest,
34/// they nest no deeper than this, so expanding them can't run the
35/// parser's own stack out.
36pub const ENTITY_DEPTH_CEILING: u32 = 64;
37
38/// A place in some text: the document, or an entity's replacement text.
39#[derive(Clone, Copy)]
40pub(crate) struct Cur<'t> {
41    pub s: &'t str,
42    pub i: usize,
43    /// For replacement text, the reference in the document it came from:
44    /// everything it produces has that span. Replacement text is already
45    /// normalized, so its line ends are left alone.
46    pub origin: Option<Span>,
47}
48
49impl<'t> Cur<'t> {
50    pub fn new(s: &'t str, origin: Option<Span>) -> Cur<'t> {
51        Cur { s, i: 0, origin }
52    }
53
54    pub fn bytes(&self) -> &'t [u8] {
55        self.s.as_bytes()
56    }
57
58    pub fn peek(&self) -> Option<u8> {
59        self.bytes().get(self.i).copied()
60    }
61
62    pub fn peek_at(&self, k: usize) -> Option<u8> {
63        self.bytes().get(self.i + k).copied()
64    }
65
66    pub fn eof(&self) -> bool {
67        self.i >= self.s.len()
68    }
69
70    pub fn at(&self, lit: &str) -> bool {
71        self.bytes()[self.i..].starts_with(lit.as_bytes())
72    }
73
74    pub fn eat(&mut self, lit: &str) -> bool {
75        let yes = self.at(lit);
76        if yes {
77            self.i += lit.len();
78        }
79        yes
80    }
81
82    pub fn eat_byte(&mut self, b: u8) -> bool {
83        let yes = self.peek() == Some(b);
84        if yes {
85            self.i += 1;
86        }
87        yes
88    }
89
90    /// Skips `S`, saying whether there was any.
91    pub fn space(&mut self) -> bool {
92        let start = self.i;
93        while self.peek().is_some_and(is_space) {
94            self.i += 1;
95        }
96        self.i > start
97    }
98
99    pub fn raw(&self) -> bool {
100        self.origin.is_some()
101    }
102
103    pub fn span(&self, a: usize, b: usize) -> Span {
104        self.origin.unwrap_or(Span::new(a as u32, b as u32))
105    }
106
107    /// The character here, or the end.
108    pub fn here(&self) -> Span {
109        let len = self.s[self.i..].chars().next().map_or(0, char::len_utf8);
110        self.span(self.i, self.i + len)
111    }
112
113    pub fn name(&mut self) -> Option<&'t str> {
114        let n = name_len(&self.s[self.i..]);
115        (n > 0).then(|| {
116            let name = &self.s[self.i..self.i + n];
117            self.i += n;
118            name
119        })
120    }
121}
122
123/// Bytes that end a run of character data: markup, references, `]]>`,
124/// line ends to normalize, and the start of anything that isn't a `Char`.
125static TEXT: [bool; 256] = {
126    let mut t = [false; 256];
127    let mut b = 0;
128    while b < 0x20 {
129        t[b] = !matches!(b as u8, b'\t' | b'\n');
130        b += 1;
131    }
132    t[b'<' as usize] = true;
133    t[b'&' as usize] = true;
134    t[b']' as usize] = true;
135    t[0xEF] = true;
136    t
137};
138
139/// The same for attribute values, where white space becomes a space.
140static ATTR: [bool; 256] = {
141    let mut t = [false; 256];
142    let mut b = 0;
143    while b < 0x20 {
144        t[b] = true;
145        b += 1;
146    }
147    t[b'<' as usize] = true;
148    t[b'&' as usize] = true;
149    t[b'"' as usize] = true;
150    t[b'\'' as usize] = true;
151    t[0xEF] = true;
152    t
153};
154
155/// The same for comments, PIs and CDATA: only line ends and non-`Char`s.
156static PLAIN: [bool; 256] = {
157    let mut t = [false; 256];
158    let mut b = 0;
159    while b < 0x20 {
160        t[b] = !matches!(b as u8, b'\t' | b'\n');
161        b += 1;
162    }
163    t[0xEF] = true;
164    t
165};
166
167/// U+FFFE and U+FFFF, the two non-`Char`s past the controls, are
168/// EF BF BE and EF BF BF.
169fn non_char_at(b: &[u8], i: usize) -> bool {
170    b[i] == 0xEF && b.get(i + 1) == Some(&0xBF) && matches!(b.get(i + 2), Some(0xBE | 0xBF))
171}
172
173/// The declared or predefined entities, as the parser keeps them.
174#[derive(Debug)]
175pub(crate) struct Entity {
176    /// An internal entity's replacement text.
177    pub value: Option<Rc<str>>,
178    /// Unparsed (`NDATA`).
179    pub unparsed: bool,
180    /// Declared inside a parameter entity's replacement text, which a
181    /// standalone document can't rely on.
182    pub in_pe: bool,
183    /// Being expanded now, so a reference to it is a recursion.
184    pub active: bool,
185    /// Its not being read has been reported.
186    pub warned: bool,
187}
188
189/// An attribute the internal subset declared.
190#[derive(Debug)]
191pub(crate) struct AttDef {
192    pub name: u32,
193    /// Declared as anything but `CDATA`, so its value's spaces collapse.
194    pub tokenized: bool,
195    /// Declared as an `ID`.
196    pub id: bool,
197    pub default: Option<String>,
198    /// The default, once it's in the document's buffer.
199    pub cached: Option<Str>,
200}
201
202/// What the DTD declared.
203#[derive(Debug, Default)]
204pub(crate) struct Dtd {
205    pub general: HashMap<String, Entity>,
206    pub params: HashMap<String, Entity>,
207    /// By element name id.
208    pub attlists: HashMap<u32, Vec<AttDef>>,
209    /// A parameter entity wasn't read, so from here on entity and
210    /// attribute-list declarations aren't processed: the entity may have
211    /// declared them first.
212    pub skip: bool,
213    pub skip_warned: bool,
214}
215
216struct Open {
217    node: u32,
218    name: u32,
219    /// The namespace scope's mark when it opened.
220    mark: usize,
221    /// Its start tag's `<`.
222    start: usize,
223}
224
225struct Pending {
226    name: u32,
227    value: Str,
228    span: Span,
229    specified: bool,
230    ns: u32,
231}
232
233/// Namespace bindings by prefix id, and how to undo them.
234struct Scope {
235    current: Vec<u32>,
236    undo: Vec<(u32, u32)>,
237}
238
239impl Scope {
240    fn new() -> Scope {
241        let mut current = vec![NONE; 3];
242        current[0] = 0;
243        current[PREFIX_XML as usize] = NS_XML;
244        Scope {
245            current,
246            undo: Vec::new(),
247        }
248    }
249
250    fn bind(&mut self, prefix: u32, uri: u32) {
251        let p = prefix as usize;
252        if p >= self.current.len() {
253            self.current.resize(p + 1, NONE);
254        }
255        self.undo.push((prefix, self.current[p]));
256        self.current[p] = uri;
257    }
258
259    fn get(&self, prefix: u32) -> u32 {
260        self.current.get(prefix as usize).copied().unwrap_or(NONE)
261    }
262
263    fn pop(&mut self, mark: usize) {
264        while self.undo.len() > mark {
265            let (p, old) = self.undo.pop().unwrap();
266            self.current[p as usize] = old;
267        }
268    }
269}
270
271pub(crate) struct Parser<'s, 'o> {
272    pub src: &'s str,
273    pub opts: &'o Options,
274    pub doc: Document,
275    pub dtd: Dtd,
276    stack: Vec<Open>,
277    scope: Scope,
278    pending: Vec<Pending>,
279    sorted: Vec<(u32, u32)>,
280    steps: Budget,
281    pub expansion: Budget,
282    pub entity_depth: u32,
283    pub standalone: bool,
284    pub has_external_subset: bool,
285    pub has_pe_refs: bool,
286    /// Inside the `<!DOCTYPE>`.
287    pub in_dtd: bool,
288    /// Undeclared entities already reported as not loaded.
289    warned: HashSet<String>,
290}
291
292impl<'s, 'o> Parser<'s, 'o> {
293    pub fn new(src: &'s str, opts: &'o Options) -> Parser<'s, 'o> {
294        let allowance = opts
295            .entity_allowance
296            .saturating_add(opts.entity_ratio.saturating_mul(src.len() as u64));
297        Parser {
298            src,
299            opts,
300            doc: Document::new(opts.namespaces, src.len()),
301            dtd: Dtd::default(),
302            stack: Vec::new(),
303            scope: Scope::new(),
304            pending: Vec::new(),
305            sorted: Vec::new(),
306            steps: opts.limits.budget(),
307            expansion: Budget::new(allowance),
308            entity_depth: 0,
309            standalone: false,
310            has_external_subset: false,
311            has_pe_refs: false,
312            in_dtd: false,
313            warned: HashSet::new(),
314        }
315    }
316
317    /// Whether a reference to an undeclared entity is allowed: the DTD
318    /// has parts this parser doesn't read, which might declare it.
319    pub fn lenient(&self) -> bool {
320        !self.standalone && (self.has_external_subset || self.has_pe_refs)
321    }
322
323    pub fn step(&mut self, n: u64, span: Span) -> R<()> {
324        self.steps.spend(n).map_err(|_| {
325            err(
326                "step-limit",
327                span,
328                "the parse did more work than its step limit allows",
329            )
330        })
331    }
332
333    pub fn warn(&mut self, d: Diagnostic) {
334        self.doc.warnings.push(d);
335    }
336
337    /// The text written to the buffer since `start`.
338    pub fn str_from(&self, start: usize, span: Span) -> R<Str> {
339        let end = self.doc.text.len();
340        if end > u32::MAX as usize {
341            return Err(err("too-large", span, "the document's text is over 4 GiB"));
342        }
343        Ok(Str {
344            start: start as u32,
345            len: (end - start) as u32,
346        })
347    }
348
349    fn node(&mut self, parent: u32, span: Span, data: Data) -> R<u32> {
350        if self.doc.nodes.len() >= NONE as usize - 1 {
351            return Err(err("too-large", span, "the document has too many nodes"));
352        }
353        self.step(1, span)?;
354        Ok(self.doc.append(parent, span, data))
355    }
356
357    fn parent(&self) -> u32 {
358        self.stack.last().map_or(0, |o| o.node)
359    }
360
361    /// Interns an element or attribute name, checking it's a `QName`
362    /// when namespaces are on.
363    pub fn qname(&mut self, name: &str, span: Span) -> R<u32> {
364        if let Some(id) = self.doc.names.get(name) {
365            return Ok(id);
366        }
367        let mut colon = NONE;
368        if self.opts.namespaces
369            && let Some(c) = name.find(':')
370        {
371            let local = &name[c + 1..];
372            if c == 0 || local.contains(':') || !local.chars().next().is_some_and(is_name_start) {
373                return Err(err(
374                    "invalid-qname",
375                    span,
376                    format!(
377                        "`{name}` isn't a qualified name: a prefix, one colon, and a local name"
378                    ),
379                ));
380            }
381            colon = c as u32;
382        }
383        Ok(self.doc.names.insert(name, colon))
384    }
385
386    /// A name that can't have a colon with namespaces on: an entity's, a
387    /// PI target, a notation's.
388    pub fn no_colon(&self, name: &str, span: Span, what: &str) -> R<()> {
389        if self.opts.namespaces && name.contains(':') {
390            return Err(err(
391                "colon-in-name",
392                span,
393                format!("{what} `{name}` can't contain a colon"),
394            ));
395        }
396        Ok(())
397    }
398
399    pub fn need_space(&self, cur: &mut Cur, what: &'static str) -> R<()> {
400        if cur.space() {
401            return Ok(());
402        }
403        Err(self.expected(cur, what))
404    }
405
406    /// An error for something else being where `what` should be.
407    pub fn expected(&self, cur: &Cur, what: &str) -> Diagnostic {
408        if cur.eof() {
409            return err(
410                "unexpected-eof",
411                cur.here(),
412                format!("the input ends where {what} should be"),
413            );
414        }
415        if cur.peek() == Some(b'%') && self.in_dtd {
416            return err(
417                "pe-in-markup-declaration",
418                cur.here(),
419                "a parameter entity reference can't be inside a declaration in the internal subset",
420            );
421        }
422        let c = cur.s[cur.i..].chars().next().unwrap_or(' ');
423        err(
424            "unexpected-char",
425            cur.here(),
426            format!("expected {what}, found `{}`", c.escape_debug()),
427        )
428    }
429
430    /// Copies `cur.s[a..b]` to the buffer, checking each character is a
431    /// `Char` and normalizing line ends outside replacement text.
432    pub fn push_checked(&mut self, cur: &Cur, a: usize, b: usize) -> R<()> {
433        let bytes = cur.bytes();
434        let (mut from, mut i) = (a, a);
435        while i < b {
436            if !PLAIN[bytes[i] as usize] {
437                i += 1;
438                continue;
439            }
440            match bytes[i] {
441                b'\r' => {
442                    if !cur.raw() {
443                        self.doc.text.push_str(&cur.s[from..i]);
444                        self.doc.text.push('\n');
445                        i += 1;
446                        if bytes.get(i) == Some(&b'\n') && i < b {
447                            i += 1;
448                        }
449                        from = i;
450                        continue;
451                    }
452                }
453                0xEF if !non_char_at(bytes, i) => {}
454                _ => return Err(self.not_char(cur, i)),
455            }
456            i += 1;
457        }
458        self.doc.text.push_str(&cur.s[from..b]);
459        Ok(())
460    }
461
462    /// Checks `cur.s[a..b]` has only `Char`s, copying nothing.
463    pub fn check_chars(&self, cur: &Cur, a: usize, b: usize) -> R<()> {
464        let bytes = cur.bytes();
465        for i in a..b {
466            let bad = match bytes[i] {
467                b'\r' => false,
468                0xEF => non_char_at(bytes, i),
469                c => PLAIN[c as usize],
470            };
471            if bad {
472                return Err(self.not_char(cur, i));
473            }
474        }
475        Ok(())
476    }
477
478    pub fn not_char(&self, cur: &Cur, i: usize) -> Diagnostic {
479        let c = cur.s[i..].chars().next().unwrap_or('\0');
480        err(
481            "invalid-char",
482            cur.span(i, i + c.len_utf8()),
483            format!("U+{:04X} isn't allowed in XML", c as u32),
484        )
485    }
486
487    // The document.
488
489    pub fn document(&mut self) -> R<()> {
490        self.opts.limits.check_input(self.src.len())?;
491        let src = self.src;
492        let mut cur = Cur::new(src, None);
493        // A byte order mark that came through as a character.
494        cur.eat("\u{FEFF}");
495        if cur.at("<?xml") && cur.peek_at(5).is_some_and(is_space) {
496            self.xml_decl(&mut cur)?;
497        }
498        let mut root = false;
499        loop {
500            cur.space();
501            if cur.eof() {
502                break;
503            }
504            if cur.at("<!--") {
505                self.comment(&mut cur, 0)?;
506            } else if cur.at("<?") {
507                self.pi(&mut cur, Some(0))?;
508            } else if cur.at("<!DOCTYPE") {
509                if root || self.doc.doctype.is_some() {
510                    return Err(err(
511                        "misplaced-doctype",
512                        cur.span(cur.i, cur.i + 9),
513                        "a document has one `<!DOCTYPE>`, before its document element",
514                    ));
515                }
516                self.doctype(&mut cur)?;
517            } else if cur.peek() == Some(b'<')
518                && !root
519                && !matches!(cur.peek_at(1), Some(b'!' | b'/'))
520            {
521                if !self.start_tag(&mut cur)? {
522                    self.content(&mut cur, 0)?;
523                }
524                root = true;
525            } else if root {
526                return Err(err(
527                    "content-after-root",
528                    cur.here(),
529                    "only comments, processing instructions and white space can follow the document element",
530                ));
531            } else {
532                return Err(err(
533                    "expected-root",
534                    cur.here(),
535                    "expected the document element",
536                ));
537            }
538        }
539        if !root {
540            return Err(err(
541                "no-root",
542                cur.span(src.len(), src.len()),
543                "the document has no document element",
544            ));
545        }
546        Ok(())
547    }
548
549    fn quoted<'t>(&self, cur: &mut Cur<'t>, what: &str) -> R<(&'t str, usize)> {
550        let q = cur.peek();
551        if !matches!(q, Some(b'"' | b'\'')) {
552            return Err(self.expected(cur, &format!("{what} in quotes")));
553        }
554        let start = cur.i + 1;
555        match cur.s[start..].find(q.unwrap() as char) {
556            Some(n) => {
557                cur.i = start + n + 1;
558                Ok((&cur.s[start..start + n], start))
559            }
560            None => Err(err(
561                "unexpected-eof",
562                cur.span(cur.i, cur.s.len()),
563                format!("{what} has no closing quote"),
564            )),
565        }
566    }
567
568    fn eq(&self, cur: &mut Cur) -> R<()> {
569        cur.space();
570        if !cur.eat_byte(b'=') {
571            return Err(self.expected(cur, "`=`"));
572        }
573        cur.space();
574        Ok(())
575    }
576
577    fn xml_decl(&mut self, cur: &mut Cur) -> R<()> {
578        let start = cur.i;
579        cur.i += 5;
580        self.need_space(cur, "`version`")?;
581        if !cur.eat("version") {
582            return Err(self.expected(cur, "`version`"));
583        }
584        self.eq(cur)?;
585        let (version, at) = self.quoted(cur, "the version")?;
586        let digits = version.strip_prefix("1.").unwrap_or("");
587        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
588            return Err(err(
589                "invalid-version",
590                cur.span(at, at + version.len()),
591                format!("`{version}` isn't an XML 1.x version number"),
592            ));
593        }
594        let mut decl = XmlDecl {
595            version: version.to_string(),
596            encoding: None,
597            standalone: None,
598            span: Span::default(),
599        };
600        let mut sp = cur.space();
601        if cur.at("encoding") {
602            if !sp {
603                return Err(self.expected(cur, "white space"));
604            }
605            cur.i += 8;
606            self.eq(cur)?;
607            let (enc, at) = self.quoted(cur, "the encoding")?;
608            let b = enc.as_bytes();
609            if b.is_empty()
610                || !b[0].is_ascii_alphabetic()
611                || !b
612                    .iter()
613                    .all(|&c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
614            {
615                return Err(err(
616                    "invalid-encoding-name",
617                    cur.span(at, at + enc.len()),
618                    format!("`{enc}` isn't an encoding name"),
619                ));
620            }
621            decl.encoding = Some(enc.to_string());
622            sp = cur.space();
623        }
624        if cur.at("standalone") {
625            if !sp {
626                return Err(self.expected(cur, "white space"));
627            }
628            cur.i += 10;
629            self.eq(cur)?;
630            let (sd, at) = self.quoted(cur, "standalone")?;
631            decl.standalone = Some(match sd {
632                "yes" => true,
633                "no" => false,
634                _ => {
635                    return Err(err(
636                        "invalid-standalone",
637                        cur.span(at, at + sd.len()),
638                        "standalone is `yes` or `no`",
639                    ));
640                }
641            });
642            self.standalone = sd == "yes";
643            cur.space();
644        }
645        if !cur.eat("?>") {
646            return Err(self.expected(cur, "`?>` to end the XML declaration"));
647        }
648        decl.span = cur.span(start, cur.i);
649        self.doc.decl = Some(decl);
650        Ok(())
651    }
652
653    // Markup that can be anywhere.
654
655    pub fn comment(&mut self, cur: &mut Cur, parent: u32) -> R<()> {
656        let start = cur.i;
657        cur.i += 4;
658        let Some(n) = cur.s[cur.i..].find("--") else {
659            return Err(err(
660                "unexpected-eof",
661                cur.span(start, cur.s.len()),
662                "the comment has no `-->`",
663            ));
664        };
665        let end = cur.i + n;
666        if cur.peek_at(n + 2) != Some(b'>') {
667            return Err(err(
668                "double-hyphen-in-comment",
669                cur.span(end, end + 2),
670                "`--` can't be inside a comment",
671            ));
672        }
673        let text_start = self.doc.text.len();
674        let body = cur.i;
675        cur.i = end + 3;
676        let span = cur.span(start, cur.i);
677        if parent == NONE {
678            // In the DTD: checked, not kept.
679            return self.check_chars(cur, body, end);
680        }
681        self.push_checked(cur, body, end)?;
682        let s = self.str_from(text_start, span)?;
683        self.node(parent, span, Data::Comment(s))?;
684        Ok(())
685    }
686
687    /// A processing instruction, added to `parent`, or only checked.
688    pub fn pi(&mut self, cur: &mut Cur, parent: Option<u32>) -> R<()> {
689        let start = cur.i;
690        cur.i += 2;
691        let name_at = cur.i;
692        let Some(target) = cur.name() else {
693            return Err(self.expected(cur, "a processing instruction's target"));
694        };
695        let tspan = cur.span(name_at, cur.i);
696        if target.eq_ignore_ascii_case("xml") {
697            return Err(err(
698                "reserved-pi-target",
699                tspan,
700                if target == "xml" {
701                    "the XML declaration can only be at the very start of the document"
702                } else {
703                    "`xml` in any case is reserved, and can't be a processing instruction's target"
704                },
705            ));
706        }
707        self.no_colon(target, tspan, "a processing instruction's target")?;
708        let data_start;
709        let data_end;
710        if cur.eat("?>") {
711            data_start = cur.i;
712            data_end = cur.i;
713        } else {
714            if !cur.space() {
715                return Err(self.expected(cur, "white space or `?>`"));
716            }
717            data_start = cur.i;
718            let Some(n) = cur.s[cur.i..].find("?>") else {
719                return Err(err(
720                    "unexpected-eof",
721                    cur.span(start, cur.s.len()),
722                    "the processing instruction has no `?>`",
723                ));
724            };
725            data_end = cur.i + n;
726            cur.i = data_end + 2;
727        }
728        let span = cur.span(start, cur.i);
729        let Some(parent) = parent else {
730            return self.check_chars(cur, data_start, data_end);
731        };
732        let t0 = self.doc.text.len();
733        self.doc.text.push_str(target);
734        let target = self.str_from(t0, span)?;
735        let d0 = self.doc.text.len();
736        self.push_checked(cur, data_start, data_end)?;
737        let data = self.str_from(d0, span)?;
738        self.node(parent, span, Data::Pi { target, data })?;
739        Ok(())
740    }
741
742    // Elements.
743
744    /// A start tag, at `<`. Says whether it was an empty-element tag.
745    fn start_tag(&mut self, cur: &mut Cur) -> R<bool> {
746        let lt = cur.i;
747        cur.i += 1;
748        let Some(qname) = cur.name() else {
749            return Err(err(
750                "invalid-name",
751                cur.here(),
752                "`<` has to start a tag; write `&lt;` for a literal one",
753            ));
754        };
755        let name = self.qname(qname, cur.span(lt + 1, cur.i))?;
756        self.pending.clear();
757        let empty = loop {
758            let sp = cur.space();
759            match cur.peek() {
760                Some(b'>') => {
761                    cur.i += 1;
762                    break false;
763                }
764                Some(b'/') if cur.peek_at(1) == Some(b'>') => {
765                    cur.i += 2;
766                    break true;
767                }
768                None => {
769                    return Err(err(
770                        "unexpected-eof",
771                        cur.span(lt, cur.s.len()),
772                        format!("the start tag of `{qname}` has no `>`"),
773                    ));
774                }
775                _ if !sp => return Err(self.expected(cur, "white space, `>` or `/>`")),
776                _ => {}
777            }
778            let a = cur.i;
779            let Some(aname) = cur.name() else {
780                return Err(self.expected(cur, "an attribute name, `>` or `/>`"));
781            };
782            let aid = self.qname(aname, cur.span(a, cur.i))?;
783            self.eq(cur)?;
784            let value = self.attr_value(cur)?;
785            self.pending.push(Pending {
786                name: aid,
787                value,
788                span: cur.span(a, cur.i),
789                specified: true,
790                ns: 0,
791            });
792        };
793        let tag = cur.span(lt, cur.i);
794        if self.opts.limits.too_deep(self.stack.len() as u32 + 1) {
795            return Err(err(
796                "too-deep",
797                tag,
798                format!(
799                    "elements nest deeper than the limit of {}",
800                    self.opts.limits.max_depth.unwrap_or(0)
801                ),
802            ));
803        }
804        self.step(self.pending.len() as u64, tag)?;
805        self.attributes(name, tag)?;
806        let mark = self.scope.undo.len();
807        let ns = if self.opts.namespaces {
808            self.namespaces(name, tag)?
809        } else {
810            0
811        };
812        let attrs = self.doc.attrs.len() as u32;
813        for p in &self.pending {
814            self.doc.attrs.push(AttrData {
815                name: p.name,
816                ns: p.ns,
817                value: p.value,
818                span: p.span,
819                specified: p.specified,
820            });
821        }
822        let node = self.node(
823            self.parent(),
824            tag,
825            Data::Element {
826                name,
827                ns,
828                attrs,
829                attrs_len: self.pending.len() as u32,
830            },
831        )?;
832        if empty {
833            self.scope.pop(mark);
834        } else {
835            self.stack.push(Open {
836                node,
837                name,
838                mark,
839                start: lt,
840            });
841        }
842        Ok(empty)
843    }
844
845    /// Checks the start tag's attributes are unique, and brings in what
846    /// the DTD says about them.
847    fn attributes(&mut self, element: u32, tag: Span) -> R<()> {
848        let n = self.pending.len();
849        let defs = self.dtd.attlists.contains_key(&element);
850        if n < 2 && !defs {
851            return Ok(());
852        }
853        self.sorted.clear();
854        self.sorted.extend(
855            self.pending
856                .iter()
857                .enumerate()
858                .map(|(i, p)| (p.name, i as u32)),
859        );
860        self.sorted.sort_unstable();
861        for w in self.sorted.windows(2) {
862            if w[0].0 == w[1].0 {
863                let later = w[0].1.max(w[1].1) as usize;
864                let p = &self.pending[later];
865                return Err(err(
866                    "duplicate-attribute",
867                    p.span,
868                    format!(
869                        "`{}` appears twice in the same start tag",
870                        self.doc.names.qname_str(p.name)
871                    ),
872                ));
873            }
874        }
875        let Some(defs) = self.dtd.attlists.get_mut(&element) else {
876            return Ok(());
877        };
878        for def in defs.iter_mut() {
879            match self.sorted.binary_search_by_key(&def.name, |&(id, _)| id) {
880                Ok(at) => {
881                    if def.tokenized {
882                        let p = &mut self.pending[self.sorted[at].1 as usize];
883                        let value = &self.doc.text[p.value.start as usize..p.value.end() as usize];
884                        let collapsed = collapse(value);
885                        if collapsed != value {
886                            let start = self.doc.text.len();
887                            self.doc.text.push_str(&collapsed);
888                            p.value = Str {
889                                start: start as u32,
890                                len: collapsed.len() as u32,
891                            };
892                        }
893                    }
894                }
895                Err(_) => {
896                    let Some(default) = &def.default else {
897                        continue;
898                    };
899                    let value = match def.cached {
900                        Some(s) => s,
901                        None => {
902                            let start = self.doc.text.len();
903                            self.doc.text.push_str(default);
904                            let s = Str {
905                                start: start as u32,
906                                len: default.len() as u32,
907                            };
908                            def.cached = Some(s);
909                            s
910                        }
911                    };
912                    // Stored once, but every element it's applied to hands it
913                    // out again, so it counts as an expansion each time: a
914                    // big default on many elements is a blowup like an
915                    // entity's.
916                    self.expansion.spend(u64::from(value.len)).map_err(|_| {
917                        err(
918                            "entity-expansion-limit",
919                            tag,
920                            "the DTD's attribute defaults add more text than the limit allows",
921                        )
922                    })?;
923                    self.pending.push(Pending {
924                        name: def.name,
925                        value,
926                        span: tag,
927                        specified: false,
928                        ns: 0,
929                    });
930                }
931            }
932        }
933        if self.doc.text.len() > u32::MAX as usize {
934            return Err(err("too-large", tag, "the document's text is over 4 GiB"));
935        }
936        Ok(())
937    }
938
939    /// Binds the start tag's namespace declarations and resolves its
940    /// names, returning the element's namespace.
941    fn namespaces(&mut self, element: u32, tag: Span) -> R<u32> {
942        for i in 0..self.pending.len() {
943            let p = &self.pending[i];
944            let info = self.doc.names.qname_info(p.name);
945            let (prefix, span) = (info.prefix, p.span);
946            let declared = if &*info.qname == "xmlns" {
947                0
948            } else if prefix == PREFIX_XMLNS {
949                let local = self.doc.names.local(p.name).to_string();
950                self.doc.names.prefix(&local)
951            } else {
952                continue;
953            };
954            let p = &mut self.pending[i];
955            p.ns = NS_XMLNS;
956            let value = &self.doc.text[p.value.start as usize..p.value.end() as usize];
957            let bad = |m: &str| Err(err("invalid-namespace-declaration", span, m.to_string()));
958            if declared == PREFIX_XMLNS {
959                return bad("the `xmlns` prefix can't be declared");
960            }
961            if declared == PREFIX_XML {
962                if value != XML_NS {
963                    return bad("the `xml` prefix can only be bound to its own namespace");
964                }
965                continue;
966            }
967            if value == XML_NS {
968                return bad("the XML namespace can only be bound to the `xml` prefix");
969            }
970            if value == XMLNS_NS {
971                return bad("the `xmlns` namespace can't be declared");
972            }
973            if value.is_empty() && declared != 0 {
974                return bad("in Namespaces 1.0 a prefix can't be undeclared with `\"\"`");
975            }
976            let uri = self.doc.names.uri(value);
977            self.scope.bind(declared, uri);
978        }
979        let resolve = |this: &Self, name: u32, span: Span| -> R<u32> {
980            let prefix = this.doc.names.qname_info(name).prefix;
981            if prefix == PREFIX_XMLNS {
982                return Err(err(
983                    "invalid-namespace-declaration",
984                    span,
985                    "`xmlns` is reserved, and can't be an element's prefix",
986                ));
987            }
988            match this.scope.get(prefix) {
989                NONE => Err(err(
990                    "undeclared-prefix",
991                    span,
992                    format!(
993                        "the prefix of `{}` isn't bound to a namespace",
994                        this.doc.names.qname_str(name)
995                    ),
996                )),
997                uri => Ok(uri),
998            }
999        };
1000        let ns = resolve(self, element, tag)?;
1001        let mut prefixed = 0;
1002        for i in 0..self.pending.len() {
1003            let p = &self.pending[i];
1004            if p.ns == NS_XMLNS || self.doc.names.qname_info(p.name).prefix == 0 {
1005                continue;
1006            }
1007            let uri = resolve(self, p.name, p.span)?;
1008            self.pending[i].ns = uri;
1009            prefixed += 1;
1010        }
1011        if prefixed > 1 {
1012            // No two attributes with the same namespace and local name.
1013            let names = &self.doc.names;
1014            let mut seen: Vec<(u32, &str, Span)> = self
1015                .pending
1016                .iter()
1017                .filter(|p| p.ns != NS_XMLNS && names.qname_info(p.name).prefix != 0)
1018                .map(|p| (p.ns, names.local(p.name), p.span))
1019                .collect();
1020            seen.sort_unstable_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
1021            for w in seen.windows(2) {
1022                if (w[0].0, w[0].1) == (w[1].0, w[1].1) {
1023                    return Err(err(
1024                        "duplicate-attribute",
1025                        w[0].2.max(w[1].2),
1026                        format!(
1027                            "two attributes are `{}` in the namespace `{}`",
1028                            w[0].1,
1029                            names.uri_str(w[0].0)
1030                        ),
1031                    ));
1032                }
1033            }
1034        }
1035        Ok(ns)
1036    }
1037
1038    /// An attribute value, at its opening quote, normalized into the
1039    /// buffer.
1040    pub(crate) fn attr_value(&mut self, cur: &mut Cur) -> R<Str> {
1041        let q = match cur.peek() {
1042            Some(q @ (b'"' | b'\'')) => q,
1043            _ => return Err(self.expected(cur, "an attribute value in quotes")),
1044        };
1045        let open = cur.i;
1046        cur.i += 1;
1047        let start = self.doc.text.len();
1048        let bytes = cur.bytes();
1049        let (mut from, mut i) = (cur.i, cur.i);
1050        loop {
1051            while i < bytes.len() && !ATTR[bytes[i] as usize] {
1052                i += 1;
1053            }
1054            let Some(&c) = bytes.get(i) else {
1055                return Err(err(
1056                    "unexpected-eof",
1057                    cur.span(open, bytes.len()),
1058                    "the attribute value has no closing quote",
1059                ));
1060            };
1061            match c {
1062                _ if c == q => break,
1063                b'"' | b'\'' => i += 1,
1064                b'<' => {
1065                    return Err(err(
1066                        "lt-in-attribute",
1067                        cur.span(i, i + 1),
1068                        "`<` can't be in an attribute value; write `&lt;`",
1069                    ));
1070                }
1071                b'\t' | b'\n' => {
1072                    self.doc.text.push_str(&cur.s[from..i]);
1073                    self.doc.text.push(' ');
1074                    i += 1;
1075                    from = i;
1076                }
1077                b'\r' => {
1078                    self.doc.text.push_str(&cur.s[from..i]);
1079                    self.doc.text.push(' ');
1080                    i += 1;
1081                    if !cur.raw() && bytes.get(i) == Some(&b'\n') {
1082                        i += 1;
1083                    }
1084                    from = i;
1085                }
1086                b'&' => {
1087                    self.doc.text.push_str(&cur.s[from..i]);
1088                    cur.i = i;
1089                    self.reference_in_attr(cur)?;
1090                    i = cur.i;
1091                    from = i;
1092                }
1093                0xEF if !non_char_at(bytes, i) => i += 1,
1094                _ => return Err(self.not_char(cur, i)),
1095            }
1096        }
1097        self.doc.text.push_str(&cur.s[from..i]);
1098        cur.i = i + 1;
1099        self.str_from(start, cur.span(open, cur.i))
1100    }
1101
1102    /// A character reference, at `&#`.
1103    pub fn char_ref(&self, cur: &mut Cur) -> R<char> {
1104        let start = cur.i;
1105        cur.i += 2;
1106        let hex = cur.eat_byte(b'x');
1107        let digits = cur.i;
1108        let mut n: u32 = 0;
1109        while let Some(b) = cur.peek() {
1110            let d = match b {
1111                b'0'..=b'9' => b - b'0',
1112                b'a'..=b'f' if hex => b - b'a' + 10,
1113                b'A'..=b'F' if hex => b - b'A' + 10,
1114                _ => break,
1115            };
1116            n = n
1117                .saturating_mul(if hex { 16 } else { 10 })
1118                .saturating_add(d as u32);
1119            cur.i += 1;
1120        }
1121        if cur.i == digits || !cur.eat_byte(b';') {
1122            return Err(err(
1123                "invalid-char-ref",
1124                cur.span(start, cur.i),
1125                "a character reference is `&#` and decimal digits, or `&#x` and hex digits, then `;`",
1126            ));
1127        }
1128        match char::from_u32(n).filter(|&c| is_char(c)) {
1129            Some(c) => Ok(c),
1130            None => Err(err(
1131                "invalid-char-ref",
1132                cur.span(start, cur.i),
1133                "the character reference is to a character XML doesn't allow",
1134            )),
1135        }
1136    }
1137
1138    /// An entity reference's name, at `&`.
1139    pub fn entity_ref_name<'t>(&self, cur: &mut Cur<'t>) -> R<(&'t str, Span)> {
1140        let start = cur.i;
1141        cur.i += 1;
1142        let Some(name) = cur.name() else {
1143            return Err(err(
1144                "invalid-reference",
1145                cur.span(start, cur.i),
1146                "`&` has to start a reference; write `&amp;` for a literal one",
1147            ));
1148        };
1149        if !cur.eat_byte(b';') {
1150            return Err(err(
1151                "invalid-reference",
1152                cur.span(start, cur.i),
1153                format!("the reference to `{name}` has no `;`"),
1154            ));
1155        }
1156        Ok((name, cur.span(start, cur.i)))
1157    }
1158
1159    /// Starts expanding a declared internal entity: checks recursion,
1160    /// depth and budget, and marks it active. Gives its text.
1161    pub fn enter(&mut self, name: &str, span: Span, parameter: bool) -> R<Rc<str>> {
1162        let standalone = self.standalone;
1163        let depth = self.entity_depth + 1;
1164        let max = self.opts.max_entity_depth.min(ENTITY_DEPTH_CEILING);
1165        let table = if parameter {
1166            &mut self.dtd.params
1167        } else {
1168            &mut self.dtd.general
1169        };
1170        let e = table.get_mut(name).expect("entered a declared entity");
1171        if e.active {
1172            return Err(err(
1173                "recursive-entity",
1174                span,
1175                format!("the entity `{name}` refers to itself"),
1176            ));
1177        }
1178        if standalone && e.in_pe && !parameter {
1179            return Err(err(
1180                "undeclared-entity",
1181                span,
1182                format!(
1183                    "`{name}` is declared in a parameter entity, which a standalone document can't use"
1184                ),
1185            ));
1186        }
1187        if depth > max {
1188            return Err(err(
1189                "entity-too-deep",
1190                span,
1191                format!("entities nest deeper than the limit of {max}"),
1192            ));
1193        }
1194        let value = e.value.clone().expect("an internal entity");
1195        e.active = true;
1196        self.entity_depth = depth;
1197        self.expansion.spend(value.len() as u64).map_err(|_| {
1198            err(
1199                "entity-expansion-limit",
1200                span,
1201                "entity references expand to more text than the limit allows",
1202            )
1203        })?;
1204        self.step(1, span)?;
1205        Ok(value)
1206    }
1207
1208    pub fn leave(&mut self, name: &str, parameter: bool) {
1209        let table = if parameter {
1210            &mut self.dtd.params
1211        } else {
1212            &mut self.dtd.general
1213        };
1214        if let Some(e) = table.get_mut(name) {
1215            e.active = false;
1216        }
1217        self.entity_depth -= 1;
1218    }
1219
1220    /// Reports a reference to an entity that wasn't read, once per name.
1221    fn not_loaded(&mut self, name: &str, span: Span, declared: bool) {
1222        let first = match self.dtd.general.get_mut(name) {
1223            Some(e) if declared => !std::mem::replace(&mut e.warned, true),
1224            _ => self.warned.insert(name.to_string()),
1225        };
1226        if first {
1227            let message = if declared {
1228                format!("`{name}` is an external entity, which Parsec doesn't read")
1229            } else {
1230                format!("`{name}` isn't declared in the part of the DTD Parsec read")
1231            };
1232            self.warn(Diagnostic::warning("entity-not-loaded", span, message));
1233        }
1234    }
1235
1236    /// A reference inside an attribute value, at `&`, its replacement
1237    /// appended to the buffer.
1238    fn reference_in_attr(&mut self, cur: &mut Cur) -> R<()> {
1239        if cur.at("&#") {
1240            let c = self.char_ref(cur)?;
1241            self.doc.text.push(c);
1242            return Ok(());
1243        }
1244        let (name, span) = self.entity_ref_name(cur)?;
1245        if let Some(c) = predefined(name) {
1246            self.doc.text.push(c);
1247            return Ok(());
1248        }
1249        let span = cur.origin.unwrap_or(span);
1250        match self.dtd.general.get(name) {
1251            None if self.lenient() => {
1252                self.not_loaded(name, span, false);
1253                return Ok(());
1254            }
1255            None => {
1256                return Err(err(
1257                    "undeclared-entity",
1258                    span,
1259                    format!("the entity `{name}` isn't declared"),
1260                ));
1261            }
1262            Some(e) if e.value.is_none() => {
1263                return Err(err(
1264                    "external-entity-in-attribute",
1265                    span,
1266                    format!(
1267                        "`{name}` is an external entity, which an attribute value can't refer to"
1268                    ),
1269                ));
1270            }
1271            Some(_) => {}
1272        }
1273        let text = self.enter(name, span, false)?;
1274        let mut sub = Cur::new(&text, Some(span));
1275        let bytes = sub.bytes();
1276        let mut from = 0;
1277        while sub.i < bytes.len() {
1278            match bytes[sub.i] {
1279                b'<' => {
1280                    return Err(err(
1281                        "lt-in-attribute",
1282                        span,
1283                        format!("`{name}` holds a `<`, so it can't be used in an attribute value"),
1284                    ));
1285                }
1286                b'\t' | b'\n' | b'\r' => {
1287                    self.doc.text.push_str(&text[from..sub.i]);
1288                    self.doc.text.push(' ');
1289                    sub.i += 1;
1290                    from = sub.i;
1291                }
1292                b'&' => {
1293                    self.doc.text.push_str(&text[from..sub.i]);
1294                    self.reference_in_attr(&mut sub)?;
1295                    from = sub.i;
1296                }
1297                _ => sub.i += 1,
1298            }
1299        }
1300        self.doc.text.push_str(&text[from..]);
1301        self.leave(name, false);
1302        Ok(())
1303    }
1304
1305    /// Adds text written to the buffer from `start` to the open element,
1306    /// joining it to text just before.
1307    fn add_text(&mut self, start: usize, span: Span) -> R<()> {
1308        if self.doc.text.len() == start {
1309            return Ok(());
1310        }
1311        let s = self.str_from(start, span)?;
1312        let parent = self.parent();
1313        let last = self.doc.nodes[parent as usize].last;
1314        if last != NONE {
1315            let node = &mut self.doc.nodes[last as usize];
1316            if let Data::Text(t) = &mut node.data
1317                && t.end() == s.start
1318            {
1319                t.len += s.len;
1320                node.span = node.span.to(span);
1321                return Ok(());
1322            }
1323        }
1324        self.node(parent, span, Data::Text(s))?;
1325        Ok(())
1326    }
1327
1328    /// Content, until the element open at `base` closes (in the document)
1329    /// or the replacement text ends (in an entity), which has to leave the
1330    /// same elements open as it found.
1331    fn content(&mut self, cur: &mut Cur, base: usize) -> R<()> {
1332        loop {
1333            self.char_data(cur)?;
1334            let Some(c) = cur.peek() else {
1335                if cur.raw() {
1336                    if self.stack.len() != base {
1337                        let open = self.stack.last().unwrap();
1338                        return Err(err(
1339                            "unbalanced-entity",
1340                            cur.span(0, 0),
1341                            format!(
1342                                "the entity opens `{}` and doesn't close it",
1343                                self.doc.names.qname_str(open.name)
1344                            ),
1345                        ));
1346                    }
1347                    return Ok(());
1348                }
1349                let open = self.stack.last().unwrap();
1350                return Err(err(
1351                    "unexpected-eof",
1352                    cur.span(open.start, open.start + 1),
1353                    format!(
1354                        "the document ends before `{}` is closed",
1355                        self.doc.names.qname_str(open.name)
1356                    ),
1357                ));
1358            };
1359            if c == b'&' {
1360                self.reference(cur)?;
1361                continue;
1362            }
1363            // `<`
1364            match cur.peek_at(1) {
1365                Some(b'/') => {
1366                    if self.stack.len() == base {
1367                        return Err(err(
1368                            "unbalanced-entity",
1369                            cur.span(cur.i, cur.i + 2),
1370                            "the entity closes an element it didn't open",
1371                        ));
1372                    }
1373                    self.end_tag(cur)?;
1374                    if self.stack.len() == base && !cur.raw() {
1375                        return Ok(());
1376                    }
1377                }
1378                Some(b'!') if cur.at("<!--") => self.comment(cur, self.parent())?,
1379                Some(b'!') if cur.at("<![CDATA[") => self.cdata(cur)?,
1380                Some(b'?') => self.pi(cur, Some(self.parent()))?,
1381                Some(b'!') => {
1382                    return Err(err(
1383                        "invalid-markup",
1384                        cur.span(cur.i, cur.i + 2),
1385                        "only a comment or a CDATA section can start with `<!` in content",
1386                    ));
1387                }
1388                _ => {
1389                    self.start_tag(cur)?;
1390                }
1391            }
1392        }
1393    }
1394
1395    /// Character data up to the next `<`, `&` or the end.
1396    fn char_data(&mut self, cur: &mut Cur) -> R<()> {
1397        let bytes = cur.bytes();
1398        let start = cur.i;
1399        let buf = self.doc.text.len();
1400        let (mut from, mut i) = (start, start);
1401        loop {
1402            while i < bytes.len() && !TEXT[bytes[i] as usize] {
1403                i += 1;
1404            }
1405            let Some(&c) = bytes.get(i) else { break };
1406            match c {
1407                b'<' | b'&' => break,
1408                b']' => {
1409                    if bytes[i..].starts_with(b"]]>") {
1410                        return Err(err(
1411                            "cdata-end-in-text",
1412                            cur.span(i, i + 3),
1413                            "`]]>` can't be in character data; write `]]&gt;`",
1414                        ));
1415                    }
1416                    i += 1;
1417                }
1418                b'\r' if !cur.raw() => {
1419                    self.doc.text.push_str(&cur.s[from..i]);
1420                    self.doc.text.push('\n');
1421                    i += 1;
1422                    if bytes.get(i) == Some(&b'\n') {
1423                        i += 1;
1424                    }
1425                    from = i;
1426                }
1427                b'\r' => i += 1,
1428                0xEF if !non_char_at(bytes, i) => i += 1,
1429                _ => return Err(self.not_char(cur, i)),
1430            }
1431        }
1432        self.doc.text.push_str(&cur.s[from..i]);
1433        cur.i = i;
1434        self.add_text(buf, cur.span(start, i))
1435    }
1436
1437    fn cdata(&mut self, cur: &mut Cur) -> R<()> {
1438        let start = cur.i;
1439        cur.i += 9;
1440        let Some(n) = cur.s[cur.i..].find("]]>") else {
1441            return Err(err(
1442                "unexpected-eof",
1443                cur.span(start, cur.s.len()),
1444                "the CDATA section has no `]]>`",
1445            ));
1446        };
1447        let body = cur.i;
1448        cur.i += n + 3;
1449        let span = cur.span(start, cur.i);
1450        let t0 = self.doc.text.len();
1451        self.push_checked(cur, body, body + n)?;
1452        let s = self.str_from(t0, span)?;
1453        self.node(self.parent(), span, Data::Cdata(s))?;
1454        Ok(())
1455    }
1456
1457    fn end_tag(&mut self, cur: &mut Cur) -> R<()> {
1458        let start = cur.i;
1459        cur.i += 2;
1460        let name = cur.name().unwrap_or("");
1461        cur.space();
1462        if !cur.eat_byte(b'>') {
1463            return Err(self.expected(cur, "`>` to end the end tag"));
1464        }
1465        let open = self.stack.pop().unwrap();
1466        let want = self.doc.names.qname_str(open.name);
1467        if name != want {
1468            return Err(err(
1469                "mismatched-end-tag",
1470                cur.span(start, cur.i),
1471                format!("`</{name}>` closes `<{want}>`"),
1472            )
1473            .with_label(
1474                cur.span(open.start, open.start + 1 + want.len()),
1475                "opened here",
1476            ));
1477        }
1478        self.scope.pop(open.mark);
1479        if !cur.raw() {
1480            self.doc.nodes[open.node as usize].span.end = cur.i as u32;
1481        }
1482        Ok(())
1483    }
1484
1485    /// A reference in content, at `&`.
1486    fn reference(&mut self, cur: &mut Cur) -> R<()> {
1487        let start = cur.i;
1488        if cur.at("&#") {
1489            let c = self.char_ref(cur)?;
1490            let buf = self.doc.text.len();
1491            self.doc.text.push(c);
1492            return self.add_text(buf, cur.span(start, cur.i));
1493        }
1494        let (name, span) = self.entity_ref_name(cur)?;
1495        if let Some(c) = predefined(name) {
1496            let buf = self.doc.text.len();
1497            self.doc.text.push(c);
1498            return self.add_text(buf, span);
1499        }
1500        let span = cur.origin.unwrap_or(span);
1501        match self.dtd.general.get(name) {
1502            None if self.lenient() => {
1503                self.not_loaded(name, span, false);
1504                return self.entity_ref_node(name, span);
1505            }
1506            None => {
1507                return Err(err(
1508                    "undeclared-entity",
1509                    span,
1510                    format!("the entity `{name}` isn't declared"),
1511                ));
1512            }
1513            Some(e) if e.unparsed => {
1514                return Err(err(
1515                    "unparsed-entity-reference",
1516                    span,
1517                    format!(
1518                        "`{name}` is an unparsed entity, which only an ENTITY attribute can name"
1519                    ),
1520                ));
1521            }
1522            Some(e) if e.value.is_none() => {
1523                self.not_loaded(name, span, true);
1524                return self.entity_ref_node(name, span);
1525            }
1526            Some(_) => {}
1527        }
1528        let text = self.enter(name, span, false)?;
1529        let mut sub = Cur::new(&text, Some(span));
1530        let base = self.stack.len();
1531        self.content(&mut sub, base)?;
1532        self.leave(name, false);
1533        Ok(())
1534    }
1535
1536    fn entity_ref_node(&mut self, name: &str, span: Span) -> R<()> {
1537        let t0 = self.doc.text.len();
1538        self.doc.text.push_str(name);
1539        let s = self.str_from(t0, span)?;
1540        self.node(self.parent(), span, Data::EntityRef(s))?;
1541        Ok(())
1542    }
1543
1544    pub fn doctype_node(&mut self, span: Span) -> R<()> {
1545        self.node(0, span, Data::Doctype)?;
1546        Ok(())
1547    }
1548}
1549
1550/// The five entities every XML document has.
1551pub(crate) fn predefined(name: &str) -> Option<char> {
1552    Some(match name {
1553        "lt" => '<',
1554        "gt" => '>',
1555        "amp" => '&',
1556        "apos" => '\'',
1557        "quot" => '"',
1558        _ => return None,
1559    })
1560}
1561
1562/// A tokenized attribute's value: spaces trimmed, and each run one space.
1563pub(crate) fn collapse(value: &str) -> String {
1564    value
1565        .split(' ')
1566        .filter(|t| !t.is_empty())
1567        .collect::<Vec<_>>()
1568        .join(" ")
1569}