Skip to main content

formats/xml/
reader.rs

1// reader -- the strict pull reader of formats::xml: well-formed XML 1.0 with namespaces, without a DTD
2//
3//   Reader::new(text, depth, attrs)   at most `depth` open elements and `attrs` attributes per element
4//   r.next() -> Event                 Start, End, Text, CData, Comment, Pi, Eof; an empty element <a/> gives
5//                                     Start (empty: true) and then End
6//   r.skip(at) -> &str                the rest of the element whose start tag began at `at`, as written
7//   r.pos() / r.src()
8//
9// Read: elements, attributes in ' or ", the five predefined entities and character references, CDATA,
10// comments and processing instructions (as events), the XML declaration (version 1.0; encoding UTF-8 or
11// UTF-16, the text is decoded already; standalone; in this order, values as written), a leading U+FEFF, and
12// namespaces: every name comes with the URI its prefix is bound to (Namespaces in XML 1.0; xmlns attributes
13// are in NS_XMLNS).  Refused: a DOCTYPE and every other declaration (Unsupported: no entities, nothing
14// external), an undefined entity, a character XML does not allow, mismatched or unclosed tags, text or a
15// second element outside the root, an unbound prefix, a name that is no QName, a duplicate attribute (also
16// two prefixes of one namespace), more nesting than `depth` (Depth), more attributes on one element than
17// `attrs` or more than 64 namespace bindings in scope (Attributes).  Line ends are normalised as XML says:
18// CR LF and CR become LF in text; in attribute values a literal tab, line end or CR becomes a space
19// (character references stay).  Nothing recurses: the stack is the reader's own Vec, bounded by `depth`.
20// Text is borrowed from the input unless a reference or a CR had to be replaced.
21
22use alloc::borrow::Cow;
23use alloc::string::String;
24use alloc::vec::Vec;
25
26use super::Error;
27
28/// the namespace of the xml prefix (xml:lang, xml:space)
29pub const NS_XML: &str = "http://www.w3.org/XML/1998/namespace";
30/// the namespace of namespace declarations (xmlns, xmlns:p)
31pub const NS_XMLNS: &str = "http://www.w3.org/2000/xmlns/";
32/// the most namespace bindings in scope at a time
33const MAX_BINDINGS: usize = 64;
34
35/// one attribute of a start tag
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct Attr<'a> {
38    /// the name as written (with its prefix)
39    pub qname: &'a str,
40    /// the name without prefix (for a declaration: the prefix it binds, "" for xmlns)
41    pub local: &'a str,
42    /// the namespace URI ("" for an unprefixed attribute; NS_XMLNS for a declaration)
43    pub ns: Cow<'a, str>,
44    /// the value with references replaced and white space normalised
45    pub value: Cow<'a, str>,
46}
47
48/// a start tag
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Start<'a> {
51    /// the name as written (with its prefix)
52    pub qname: &'a str,
53    /// the name without prefix
54    pub local: &'a str,
55    /// the namespace URI ("" for none)
56    pub ns: Cow<'a, str>,
57    /// the attributes in their order, namespace declarations included
58    pub attrs: Vec<Attr<'a>>,
59    /// <a/>: an End follows right away
60    pub empty: bool,
61    /// the offset of '<'
62    pub at: usize,
63    /// the offset after '>'
64    pub end: usize,
65}
66
67impl Start<'_> {
68    /// whether this is the element `local` of the namespace `ns`
69    pub fn is(&self, ns: &str, local: &str) -> bool {
70        self.local == local && self.ns == ns
71    }
72
73    /// the value of the attribute `local` of the namespace `ns` ("" for an unprefixed one)
74    pub fn attr(&self, ns: &str, local: &str) -> Option<&str> {
75        self.attrs.iter().find(|a| a.local == local && a.ns == ns && a.ns != NS_XMLNS).map(|a| &*a.value)
76    }
77}
78
79/// what the reader found next
80#[derive(Clone, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Event<'a> {
83    /// a start tag
84    Start(Start<'a>),
85    /// an end tag: the offset after its '>' (the start tag's end for an empty element)
86    End { end: usize },
87    /// character data with references replaced
88    Text(Cow<'a, str>),
89    /// a CDATA section's content (line ends normalised)
90    CData(Cow<'a, str>),
91    /// a comment's content
92    Comment(&'a str),
93    /// a processing instruction
94    Pi { target: &'a str, data: &'a str },
95    /// the end of a well-formed document
96    Eof,
97}
98
99/// an error and the byte offset it was found at
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub struct ReadError {
102    pub error: Error,
103    pub at: usize,
104}
105
106fn is_space(c: u8) -> bool {
107    matches!(c, b' ' | b'\t' | b'\n' | b'\r')
108}
109
110fn name_end(c: u8) -> bool {
111    is_space(c) || matches!(c, b'/' | b'>' | b'=' | b'<' | b'"' | b'\'' | b'&' | b'!' | b'?')
112}
113
114// characters XML 1.0 does not allow (the bytes below 0x20 but tab, LF, CR; U+FFFE, U+FFFF)
115fn bad_chars(s: &str) -> bool {
116    s.bytes().any(|c| c < 0x20 && !matches!(c, b'\t' | b'\n' | b'\r')) || s.contains(['\u{fffe}', '\u{ffff}'])
117}
118
119fn char_ok(c: u32) -> bool {
120    matches!(c, 9 | 10 | 13 | 0x20..=0xd7ff | 0xe000..=0xfffd | 0x10000..=0x10ffff)
121}
122
123// an NCName: no colon, not empty, not starting with a digit, '-' or '.'
124fn ncname(s: &str) -> bool {
125    !s.is_empty() && !s.contains(':') && !matches!(s.as_bytes()[0], b'0'..=b'9' | b'-' | b'.')
126}
127
128// replace entities and character references; `attr`: literal white space becomes a space
129pub(super) fn unescape(raw: &str, attr: bool) -> Option<Cow<'_, str>> {
130    if bad_chars(raw) {
131        return None;
132    }
133    let plain = !raw.contains('&') && !raw.contains('\r') && !(attr && raw.contains(['\t', '\n']));
134    if plain {
135        return Some(Cow::Borrowed(raw));
136    }
137    let mut out = String::with_capacity(raw.len());
138    let b = raw.as_bytes();
139    let mut i = 0;
140    let mut run = 0;
141    while i < b.len() {
142        let c = b[i];
143        if c == b'&' {
144            out.push_str(&raw[run..i]);
145            let semi = raw[i..].find(';')? + i;
146            let name = &raw[i + 1..semi];
147            match name {
148                "lt" => out.push('<'),
149                "gt" => out.push('>'),
150                "amp" => out.push('&'),
151                "quot" => out.push('"'),
152                "apos" => out.push('\''),
153                _ => {
154                    // leading zeros are allowed, the rest must fit a code point
155                    let v = if let Some(h) = name.strip_prefix("#x") {
156                        let t = h.trim_start_matches('0');
157                        if h.is_empty() || t.len() > 8 || !h.bytes().all(|d| d.is_ascii_hexdigit()) {
158                            return None;
159                        }
160                        if t.is_empty() { 0 } else { u32::from_str_radix(t, 16).ok()? }
161                    } else if let Some(d) = name.strip_prefix('#') {
162                        let t = d.trim_start_matches('0');
163                        if d.is_empty() || t.len() > 10 || !d.bytes().all(|x| x.is_ascii_digit()) {
164                            return None;
165                        }
166                        if t.is_empty() { 0 } else { t.parse::<u32>().ok()? }
167                    } else {
168                        return None;
169                    };
170                    if !char_ok(v) {
171                        return None;
172                    }
173                    out.push(char::from_u32(v)?);
174                }
175            }
176            i = semi + 1;
177            run = i;
178        } else if c == b'\r' {
179            out.push_str(&raw[run..i]);
180            out.push(if attr { ' ' } else { '\n' });
181            i += if b.get(i + 1) == Some(&b'\n') { 2 } else { 1 };
182            run = i;
183        } else if attr && (c == b'\t' || c == b'\n') {
184            out.push_str(&raw[run..i]);
185            out.push(' ');
186            i += 1;
187            run = i;
188        } else {
189            i += 1;
190        }
191    }
192    out.push_str(&raw[run..]);
193    Some(Cow::Owned(out))
194}
195
196// a binding of a prefix ("" = the default namespace) made by the element at `depth`
197struct Binding<'a> {
198    prefix: &'a str,
199    uri: Cow<'a, str>,
200    depth: usize,
201}
202
203/// the strict pull reader (see the top of this file)
204pub struct Reader<'a> {
205    s: &'a str,
206    pos: usize,
207    open: Vec<&'a str>,
208    bindings: Vec<Binding<'a>>,
209    max_depth: usize,
210    max_attrs: usize,
211    // an empty element was returned: its End comes next
212    pending_end: Option<usize>,
213    root_seen: bool,
214}
215
216impl<'a> Reader<'a> {
217    /// a reader of `s` with at most `depth` open elements and `attrs` attributes per element; a leading
218    /// U+FEFF is skipped
219    pub fn new(s: &'a str, depth: usize, attrs: usize) -> Self {
220        let pos = if s.starts_with('\u{feff}') { 3 } else { 0 };
221        Reader { s, pos, open: Vec::new(), bindings: Vec::new(), max_depth: depth, max_attrs: attrs, pending_end: None, root_seen: false }
222    }
223
224    /// the offset the reader is at
225    pub fn pos(&self) -> usize {
226        self.pos
227    }
228
229    /// the source text
230    pub fn src(&self) -> &'a str {
231        self.s
232    }
233
234    /// the elements open now
235    pub fn depth(&self) -> usize {
236        self.open.len()
237    }
238
239    fn err<T>(&self, error: Error) -> Result<T, ReadError> {
240        Err(ReadError { error, at: self.pos })
241    }
242
243    fn err_at<T>(&mut self, error: Error, at: usize) -> Result<T, ReadError> {
244        self.pos = at;
245        Err(ReadError { error, at })
246    }
247
248    fn rest(&self) -> &'a str {
249        &self.s[self.pos..]
250    }
251
252    fn skip_space(&mut self) {
253        let b = self.s.as_bytes();
254        while self.pos < b.len() && is_space(b[self.pos]) {
255            self.pos += 1;
256        }
257    }
258
259    // a QName: NCName or NCName:NCName
260    fn name(&mut self) -> Result<&'a str, ReadError> {
261        let b = self.s.as_bytes();
262        let start = self.pos;
263        while self.pos < b.len() && !name_end(b[self.pos]) {
264            self.pos += 1;
265        }
266        let n = &self.s[start..self.pos];
267        let name_char = |c: u8| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b':') || c >= 0x80;
268        if !n.bytes().all(name_char) || n.contains(['\u{fffe}', '\u{ffff}']) {
269            return self.err(Error::Syntax);
270        }
271        let ok = match n.split_once(':') {
272            Some((p, l)) => ncname(p) && ncname(l),
273            None => ncname(n),
274        };
275        if !ok {
276            return self.err(Error::Syntax);
277        }
278        Ok(n)
279    }
280
281    // the namespace bound to a prefix ("" = default)
282    fn lookup(&self, prefix: &str) -> Option<Cow<'a, str>> {
283        if prefix == "xml" {
284            return Some(Cow::Borrowed(NS_XML));
285        }
286        match self.bindings.iter().rev().find(|b| b.prefix == prefix) {
287            Some(b) => Some(b.uri.clone()),
288            None if prefix.is_empty() => Some(Cow::Borrowed("")),
289            None => None,
290        }
291    }
292
293    // the inside of "<?xml ... ?>": version="1.0", then optionally encoding and standalone, in this order,
294    // each after white space, values as written (a reference or another attribute is no declaration)
295    fn declaration(&mut self, body: &str) -> Result<(), Error> {
296        let b = body.as_bytes();
297        let mut i = 0;
298        let mut last = 0;
299        loop {
300            let before = i;
301            while i < b.len() && is_space(b[i]) {
302                i += 1;
303            }
304            if i == b.len() {
305                break;
306            }
307            if before == i {
308                return Err(Error::Syntax); // no white space before the attribute
309            }
310            let n0 = i;
311            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b':') {
312                i += 1;
313            }
314            let name = &body[n0..i];
315            while i < b.len() && is_space(b[i]) {
316                i += 1;
317            }
318            if b.get(i) != Some(&b'=') || name.is_empty() {
319                return Err(Error::Syntax);
320            }
321            i += 1;
322            while i < b.len() && is_space(b[i]) {
323                i += 1;
324            }
325            let q = match b.get(i) {
326                Some(&c @ (b'"' | b'\'')) => c,
327                _ => return Err(Error::Syntax),
328            };
329            let v0 = i + 1;
330            let Some(len) = b[v0..].iter().position(|&c| c == q) else { return Err(Error::Syntax) };
331            let value = &body[v0..v0 + len];
332            i = v0 + len + 1;
333            let order = match name {
334                "version" if value == "1.0" => 1,
335                "encoding" if ["utf-8", "utf-16", "utf-16le", "utf-16be"].iter().any(|e| value.eq_ignore_ascii_case(e)) => 2,
336                "standalone" if matches!(value, "yes" | "no") => 3,
337                _ => return Err(Error::Unsupported),
338            };
339            if order <= last || (last == 0 && order != 1) {
340                return Err(if last == 0 { Error::Unsupported } else { Error::Syntax });
341            }
342            last = order;
343        }
344        if last == 0 {
345            return Err(Error::Unsupported); // no version
346        }
347        Ok(())
348    }
349
350    /// the next event; after an error the reader is not meant to go on
351    pub fn next(&mut self) -> Result<Event<'a>, ReadError> {
352        if let Some(end) = self.pending_end.take() {
353            self.close();
354            return Ok(Event::End { end });
355        }
356        loop {
357            if self.pos >= self.s.len() {
358                if !self.open.is_empty() || !self.root_seen {
359                    return self.err(Error::Syntax);
360                }
361                return Ok(Event::Eof);
362            }
363            let rest = self.rest();
364            if !rest.starts_with('<') {
365                let start = self.pos;
366                let n = rest.find('<').unwrap_or(rest.len());
367                self.pos += n;
368                let raw = &self.s[start..self.pos];
369                if self.open.is_empty() {
370                    if !raw.bytes().all(is_space) {
371                        return self.err_at(Error::Syntax, start);
372                    }
373                    continue;
374                }
375                if raw.contains("]]>") {
376                    return self.err_at(Error::Syntax, start);
377                }
378                return match unescape(raw, false) {
379                    Some(t) => Ok(Event::Text(t)),
380                    None => self.err_at(Error::Syntax, start),
381                };
382            }
383            if rest.starts_with("<?") {
384                let first = self.pos == 0 || (self.pos == 3 && self.s.starts_with('\u{feff}'));
385                if rest.starts_with("<?xml") && rest.as_bytes().get(5).is_some_and(|&c| is_space(c)) {
386                    if !first {
387                        return self.err(Error::Syntax);
388                    }
389                    let Some(end) = rest[5..].find("?>").map(|e| e + 5) else { return self.err(Error::Syntax) };
390                    if let Err(e) = self.declaration(&rest[5..end]) {
391                        return self.err(e);
392                    }
393                    self.pos += end + 2;
394                    continue;
395                }
396                // a processing instruction: a target that is a name and not "xml" in any case ("?>" is
397                // searched after "<?": in "<?>" it would overlap the start)
398                let Some(e) = rest[2..].find("?>").map(|e| e + 2) else { return self.err(Error::Syntax) };
399                let body = &rest[2..e];
400                let t_end = body.find(|c: char| c.is_ascii_whitespace()).unwrap_or(body.len());
401                let target = &body[..t_end];
402                if target.is_empty() || target.eq_ignore_ascii_case("xml") || bad_chars(body) || target.bytes().any(name_end) {
403                    return self.err(Error::Syntax);
404                }
405                let data = body[t_end..].trim_start_matches(|c: char| c.is_ascii_whitespace());
406                self.pos += e + 2;
407                return Ok(Event::Pi { target, data });
408            }
409            if rest.starts_with("<!--") {
410                let Some(e) = rest[4..].find("-->") else { return self.err(Error::Syntax) };
411                let body = &rest[4..4 + e];
412                if bad_chars(body) || body.contains("--") || body.ends_with('-') {
413                    return self.err(Error::Syntax);
414                }
415                self.pos += 4 + e + 3;
416                return Ok(Event::Comment(body));
417            }
418            if rest.starts_with("<![CDATA[") {
419                if self.open.is_empty() {
420                    return self.err(Error::Syntax);
421                }
422                let Some(e) = rest[9..].find("]]>") else { return self.err(Error::Syntax) };
423                let raw = &rest[9..9 + e];
424                if bad_chars(raw) {
425                    return self.err(Error::Syntax);
426                }
427                self.pos += 9 + e + 3;
428                let t = if raw.contains('\r') { Cow::Owned(raw.replace("\r\n", "\n").replace('\r', "\n")) } else { Cow::Borrowed(raw) };
429                return Ok(Event::CData(t));
430            }
431            if rest.starts_with("<!") {
432                // DOCTYPE and every other declaration: no entities, nothing external
433                return self.err(Error::Unsupported);
434            }
435            if rest.starts_with("</") {
436                return self.end_tag();
437            }
438            return self.start_tag();
439        }
440    }
441
442    fn close(&mut self) {
443        let depth = self.open.len();
444        while self.bindings.last().is_some_and(|b| b.depth == depth) {
445            self.bindings.pop();
446        }
447        self.open.pop();
448    }
449
450    fn end_tag(&mut self) -> Result<Event<'a>, ReadError> {
451        self.pos += 2;
452        let name = self.name()?;
453        self.skip_space();
454        if !self.rest().starts_with('>') || self.open.last() != Some(&name) {
455            return self.err(Error::Syntax);
456        }
457        self.pos += 1;
458        self.close();
459        Ok(Event::End { end: self.pos })
460    }
461
462    fn start_tag(&mut self) -> Result<Event<'a>, ReadError> {
463        let at = self.pos;
464        if self.open.is_empty() && self.root_seen {
465            return self.err(Error::Syntax);
466        }
467        self.pos += 1;
468        let qname = self.name()?;
469        let mut raw: Vec<(&'a str, &'a str)> = Vec::new();
470        let empty;
471        loop {
472            let before = self.pos;
473            self.skip_space();
474            let rest = self.rest();
475            if rest.starts_with("/>") {
476                self.pos += 2;
477                empty = true;
478                break;
479            }
480            if rest.starts_with('>') {
481                self.pos += 1;
482                empty = false;
483                break;
484            }
485            if self.pos == before || rest.is_empty() {
486                return self.err(Error::Syntax);
487            }
488            let n = self.name()?;
489            self.skip_space();
490            if !self.rest().starts_with('=') {
491                return self.err(Error::Syntax);
492            }
493            self.pos += 1;
494            self.skip_space();
495            let q = match self.rest().as_bytes().first() {
496                Some(&c @ (b'"' | b'\'')) => c as char,
497                _ => return self.err(Error::Syntax),
498            };
499            self.pos += 1;
500            let Some(e) = self.rest().find(q) else { return self.err(Error::Syntax) };
501            let v = &self.s[self.pos..self.pos + e];
502            if v.contains('<') {
503                return self.err(Error::Syntax);
504            }
505            self.pos += e + 1;
506            if raw.len() >= self.max_attrs {
507                return self.err(Error::Attributes);
508            }
509            raw.push((n, v));
510        }
511        let end = self.pos;
512        if self.open.len() >= self.max_depth {
513            return self.err_at(Error::Depth, at);
514        }
515        if has_duplicate(raw.iter().map(|(n, _)| *n)) {
516            return self.err_at(Error::Syntax, at);
517        }
518        self.open.push(qname);
519        self.root_seen = true;
520        let depth = self.open.len();
521        // the declarations first: they apply to the element's own name and attributes
522        let mut attrs = Vec::with_capacity(raw.len());
523        for &(n, v) in &raw {
524            let Some(value) = unescape(v, true) else { return self.err_at(Error::Syntax, at) };
525            if n == "xmlns" || n.starts_with("xmlns:") {
526                let prefix = n.strip_prefix("xmlns:").unwrap_or("");
527                // xml only to its own namespace, xmlns never; no other prefix to those two
528                let reserved = value == NS_XML || value == NS_XMLNS;
529                let bad = match prefix {
530                    "xml" => value != NS_XML,
531                    "xmlns" => true,
532                    "" => reserved,
533                    _ => reserved || value.is_empty(),
534                };
535                if bad {
536                    return self.err_at(Error::Syntax, at);
537                }
538                if prefix != "xml" {
539                    if self.bindings.len() >= MAX_BINDINGS {
540                        return self.err_at(Error::Attributes, at);
541                    }
542                    self.bindings.push(Binding { prefix, uri: value.clone(), depth });
543                }
544                attrs.push(Attr { qname: n, local: prefix, ns: Cow::Borrowed(NS_XMLNS), value });
545            } else {
546                attrs.push(Attr { qname: n, local: n, ns: Cow::Borrowed(""), value });
547            }
548        }
549        for a in &mut attrs {
550            if a.ns != NS_XMLNS {
551                if let Some((p, l)) = a.qname.split_once(':') {
552                    let Some(ns) = self.lookup(p) else { return self.err_at(Error::Syntax, at) };
553                    a.ns = ns;
554                    a.local = l;
555                }
556            }
557        }
558        // two prefixes of one namespace give the same attribute twice
559        if attrs.iter().filter(|a| !a.ns.is_empty() && a.ns != NS_XMLNS).count() > 1 {
560            let mut names: Vec<(&str, &str)> = attrs.iter().filter(|a| !a.ns.is_empty() && a.ns != NS_XMLNS).map(|a| (&*a.ns, a.local)).collect();
561            names.sort_unstable();
562            if names.windows(2).any(|w| w[0] == w[1]) {
563                return self.err_at(Error::Syntax, at);
564            }
565        }
566        let (prefix, local) = qname.split_once(':').unwrap_or(("", qname));
567        let Some(ns) = self.lookup(prefix) else { return self.err_at(Error::Syntax, at) };
568        if empty {
569            self.pending_end = Some(end);
570        }
571        Ok(Event::Start(Start { qname, local, ns, attrs, empty, at, end }))
572    }
573
574    /// the rest of the element whose start tag began at `at` (just returned by next), as the file
575    /// wrote it
576    pub fn skip(&mut self, at: usize) -> Result<&'a str, ReadError> {
577        let mut depth = 0usize;
578        loop {
579            match self.next()? {
580                Event::Start(_) => depth += 1,
581                Event::End { end } => {
582                    if depth == 0 {
583                        return Ok(&self.s[at..end]);
584                    }
585                    depth -= 1;
586                }
587                Event::Eof => return self.err(Error::Syntax),
588                _ => {}
589            }
590        }
591    }
592}
593
594// whether a name occurs twice (sorted when there are many: no quadratic time)
595fn has_duplicate<'b>(names: impl Iterator<Item = &'b str> + Clone) -> bool {
596    let n = names.clone().count();
597    if n <= 8 {
598        let v: Vec<&str> = names.collect();
599        return (0..v.len()).any(|i| v[..i].contains(&v[i]));
600    }
601    let mut v: Vec<&str> = names.collect();
602    v.sort_unstable();
603    v.windows(2).any(|w| w[0] == w[1])
604}