Skip to main content

parsec_xml/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! XML for Parsec: [XML 1.0 (Fifth Edition)](https://www.w3.org/TR/xml/)
5//! and [Namespaces in XML 1.0 (Third Edition)](https://www.w3.org/TR/xml-names/),
6//! parsed to a tree with namespace-resolved names and a span on every
7//! node and attribute.
8//!
9//! ```
10//! let feed = r#"<?xml version="1.0"?>
11//! <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
12//!   <entry><title>Ships &amp; ports</title></entry>
13//! </feed>"#;
14//! let doc = parsec_xml::parse(feed).unwrap();
15//! let root = doc.root_element();
16//! let name = doc.name(root).unwrap();
17//! assert_eq!((name.local, name.namespace), ("feed", "http://www.w3.org/2005/Atom"));
18//! assert_eq!(doc.xml_lang(root), Some("en"));
19//! assert_eq!(doc.text(root).trim(), "Ships & ports");
20//! ```
21//!
22//! XML is a trust boundary, and the parser treats it as one:
23//!
24//! - It doesn't validate, and it never fetches or opens anything. The
25//!   external subset and external entities are left unread, and the
26//!   document's [`warnings`](Document::warnings) say so, as the spec asks
27//!   of a processor that doesn't read them.
28//! - Entities the internal subset declares are expanded, no deeper than
29//!   [`Options::max_entity_depth`] and to no more text in all than
30//!   [`Options::entity_allowance`] plus [`Options::entity_ratio`] bytes per
31//!   byte of input, so a billion laughs or a quadratic blowup stops with
32//!   an error. An attribute default counts each time an element gets it,
33//!   so a big default on many elements stops the same way.
34//! - Elements nest no deeper than [`Limits::max_depth`]: 2,048 unless you
35//!   say otherwise. The parser keeps open elements on a stack of its own,
36//!   so even a million levels with no limit cost time in proportion and
37//!   no recursion.
38//! - Anything that isn't well-formed is an [`Error`], fatal as the spec
39//!   says, with a code, a span, and the line and column.
40//!
41//! ## XPath
42//!
43//! With the `xpath` feature (`parsec-xml = { version = "0.3", features =
44//! ["xpath"] }`), a [`Document`] is a tree `xpath` can query, and
45//! `parsec_xml::xpath` is `parsec-xpath` re-exported. No HTML parser
46//! comes with it. Names compare exactly, a query's prefixes are bound by
47//! the namespaces it's run with, `xmlns` and `xmlns:*` aren't attributes,
48//! `id()` finds `xml:id` and attributes the internal subset declares an
49//! `ID`, and `lang()` reads `xml:lang`. The namespace axis has the
50//! namespaces in scope at each element, from its `xmlns` attributes and
51//! its ancestors'.
52//!
53//! ```
54//! # #[cfg(feature = "xpath")] {
55//! use parsec_xml::xpath::{Doc, Index, Item, NoExtensions, Value, XPath};
56//!
57//! let doc = parsec_xml::parse(r#"<feed xmlns="http://www.w3.org/2005/Atom">
58//!   <entry><title>Ships</title></entry><entry><title>Ports</title></entry>
59//! </feed>"#).unwrap();
60//! // Build the index once per document; every query reads it.
61//! let index = Index::build(&doc, &[0]);
62//! let atom = [("a".to_string(), "http://www.w3.org/2005/Atom".to_string())];
63//! let query = XPath::new("//a:entry[2]/a:title").unwrap();
64//! let Ok(Value::Nodes(hits)) =
65//!     query.evaluate(Doc::new(&doc, &index), 0, &[], &atom, &NoExtensions)
66//! else {
67//!     panic!("a node-set")
68//! };
69//! let Item::Node(title) = hits[0] else { panic!("a node") };
70//! let title = parsec_xml::NodeId::from_index(title as usize);
71//! assert_eq!(doc.text(title), "Ports");
72//! # }
73//! ```
74
75mod bytes;
76mod chars;
77mod dtd;
78mod parse;
79mod serialize;
80mod tree;
81#[cfg(feature = "xpath")]
82mod xpath_tree;
83
84use std::fmt;
85
86pub use bytes::{Parsed, parse_bytes};
87pub use encoding_rs::Encoding;
88pub use parse::ENTITY_DEPTH_CEILING;
89pub use parsec_base::{Diagnostic, Limits, LineCol, LineIndex, Severity, Span};
90#[cfg(feature = "xpath")]
91#[doc(inline)]
92pub use parsec_xpath as xpath;
93pub use tree::{
94    Attribute, Doctype, Document, EntityDecl, Name, NodeId, NodeKind, Notation, XML_NS, XMLNS_NS,
95    XmlDecl,
96};
97
98/// How elements may nest unless you say otherwise: lxml's limit with
99/// `huge_tree`, deeper than any document we know of that isn't an attack.
100pub const DEFAULT_MAX_DEPTH: u32 = 2048;
101
102/// How to parse.
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub struct Options {
105    /// The input's size, how deep elements nest
106    /// ([`DEFAULT_MAX_DEPTH`]), and the steps a parse may take (one for
107    /// each node, attribute and entity expansion). Unlimited but for the
108    /// depth.
109    pub limits: Limits,
110    /// Namespaces in XML: names are qualified names, and their prefixes
111    /// resolve. On by default. Off, a name is any XML name, colons and
112    /// all, in no namespace.
113    pub namespaces: bool,
114    /// How deep entity references may nest in the entities they refer
115    /// to: 16 by default, and never past [`ENTITY_DEPTH_CEILING`].
116    pub max_entity_depth: u32,
117    /// Entity expansion, and the attribute defaults the DTD applies to
118    /// each element, may add this many bytes to any document, 1 MiB by
119    /// default...
120    pub entity_allowance: u64,
121    /// ...plus this many for each byte of the document itself, 8 by
122    /// default. Every expansion counts, of the same entity too, and so
123    /// does every element a default is applied to.
124    pub entity_ratio: u64,
125}
126
127impl Default for Options {
128    fn default() -> Options {
129        Options {
130            limits: Limits {
131                max_depth: Some(DEFAULT_MAX_DEPTH),
132                ..Limits::default()
133            },
134            namespaces: true,
135            max_entity_depth: 16,
136            entity_allowance: 1 << 20,
137            entity_ratio: 8,
138        }
139    }
140}
141
142/// Why a document isn't well-formed XML, or couldn't be parsed within its
143/// limits.
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct Error {
146    /// What went wrong, with a stable `code` and its span in the input.
147    pub diagnostic: Diagnostic,
148    /// Where the span starts, from 1, the column in characters.
149    pub position: LineCol,
150}
151
152impl Error {
153    pub(crate) fn new(diagnostic: Diagnostic, src: &str) -> Error {
154        let position = LineIndex::new(src).line_col(diagnostic.span.start);
155        Error {
156            diagnostic,
157            position,
158        }
159    }
160
161    pub fn code(&self) -> &'static str {
162        self.diagnostic.code
163    }
164
165    pub fn span(&self) -> Span {
166        self.diagnostic.span
167    }
168}
169
170impl fmt::Display for Error {
171    /// `3:14: message [code]`.
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        write!(
174            f,
175            "{}: {} [{}]",
176            self.position, self.diagnostic.message, self.diagnostic.code
177        )
178    }
179}
180
181impl std::error::Error for Error {}
182
183/// Parses a document with the default [`Options`].
184pub fn parse(src: &str) -> Result<Document, Error> {
185    parse_with(src, &Options::default())
186}
187
188/// Parses a document. A byte order mark at the start is skipped; an
189/// encoding the XML declaration names is ignored, since the text is
190/// decoded already.
191///
192/// ```
193/// let e = parsec_xml::parse("<a>\n  <b></a>").unwrap_err();
194/// assert_eq!(e.code(), "mismatched-end-tag");
195/// assert_eq!(e.to_string(), "2:6: `</a>` closes `<b>` [mismatched-end-tag]");
196/// ```
197pub fn parse_with(src: &str, options: &Options) -> Result<Document, Error> {
198    let mut parser = parse::Parser::new(src, options);
199    match parser.document() {
200        Ok(()) => Ok(parser.doc),
201        Err(d) => Err(Error::new(d, src)),
202    }
203}