Skip to main content

fontoxide_misc/
etree.rs

1//! A minimal element tree for building XML, serialized the way lxml does
2//! (`fontTools.misc.etree` uses lxml when it is installed, as in the reference
3//! environment), and parsed from a string ([`fromstring`]).
4//!
5//! Elements have attributes, text, child elements and tails; there are no
6//! comments or processing instructions. Names may use the Clark notation
7//! (`{uri}name`); the `xml` namespace
8//! (`{http://www.w3.org/XML/1998/namespace}lang`) is written as `xml:lang`,
9//! other namespaces cannot be written.
10
11use std::fmt;
12
13/// The `xml` namespace in Clark notation (`XML_NS` in `designspaceLib`).
14pub const XML_NS: &str = "{http://www.w3.org/XML/1998/namespace}";
15
16/// An error building or serializing a tree.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct EtreeError(pub String);
19
20impl fmt::Display for EtreeError {
21	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22		f.write_str(&self.0)
23	}
24}
25
26impl std::error::Error for EtreeError {}
27
28/// An XML element (`etree.Element`).
29#[derive(Debug, Clone, PartialEq, Default)]
30pub struct Element {
31	/// The tag (`tag`).
32	pub tag: String,
33	/// The attributes in insertion order (`attrib`).
34	pub attrib: Vec<(String, String)>,
35	/// The text before the first child (`text`).
36	pub text: Option<String>,
37	/// The child elements.
38	pub children: Vec<Element>,
39	/// The text after the element, before its next sibling (`tail`).
40	pub tail: Option<String>,
41}
42
43impl Element {
44	/// `etree.Element(tag)`.
45	pub fn new(tag: impl Into<String>) -> Self {
46		Element {
47			tag: tag.into(),
48			..Default::default()
49		}
50	}
51
52	/// `element.attrib[key] = value`: an existing attribute keeps its position.
53	pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
54		let key = key.into();
55		let value = value.into();
56		match self.attrib.iter_mut().find(|(k, _)| *k == key) {
57			Some(slot) => slot.1 = value,
58			None => self.attrib.push((key, value)),
59		}
60	}
61
62	/// `element.attrib.get(key)`.
63	pub fn get(&self, key: &str) -> Option<&str> {
64		self.attrib
65			.iter()
66			.find(|(k, _)| k == key)
67			.map(|(_, v)| v.as_str())
68	}
69
70	/// `element.append(child)`.
71	pub fn append(&mut self, child: Element) {
72		self.children.push(child);
73	}
74
75	/// `len(element)`.
76	pub fn len(&self) -> usize {
77		self.children.len()
78	}
79
80	/// `len(element) == 0`.
81	pub fn is_empty(&self) -> bool {
82		self.children.is_empty()
83	}
84}
85
86/// lxml only accepts XML-compatible strings: no NUL bytes or control characters
87/// other than tab, newline and carriage return (`_utf8` in `apihelpers.pxi`).
88fn check_xml_string(s: &str) -> Result<(), EtreeError> {
89	let ok = s.chars().all(|c| {
90		matches!(c, '\t' | '\n' | '\r')
91			|| ('\u{20}'..='\u{D7FF}').contains(&c)
92			|| ('\u{E000}'..='\u{FFFD}').contains(&c)
93			|| c >= '\u{10000}'
94	});
95	if ok {
96		Ok(())
97	} else {
98		Err(EtreeError(
99			"All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters"
100				.into(),
101		))
102	}
103}
104
105/// The qualified name of a tag or attribute: only the `xml` namespace is
106/// supported in Clark notation.
107fn qname(name: &str) -> Result<String, EtreeError> {
108	if let Some(local) = name.strip_prefix(XML_NS) {
109		return Ok(format!("xml:{local}"));
110	}
111	if name.is_empty() || name.starts_with('{') || name.contains(['<', '>', '&', '"', ' ']) {
112		return Err(EtreeError(format!("Invalid tag name {name:?}")));
113	}
114	Ok(name.to_owned())
115}
116
117/// `xmlEscapeContent`.
118fn push_text(out: &mut String, text: &str) {
119	for c in text.chars() {
120		match c {
121			'<' => out.push_str("&lt;"),
122			'>' => out.push_str("&gt;"),
123			'&' => out.push_str("&amp;"),
124			'\r' => out.push_str("&#13;"),
125			_ => out.push(c),
126		}
127	}
128}
129
130/// `xmlBufAttrSerializeTxtContent`.
131fn push_attr_value(out: &mut String, value: &str) {
132	for c in value.chars() {
133		match c {
134			'"' => out.push_str("&quot;"),
135			'<' => out.push_str("&lt;"),
136			'>' => out.push_str("&gt;"),
137			'&' => out.push_str("&amp;"),
138			'\n' => out.push_str("&#10;"),
139			'\r' => out.push_str("&#13;"),
140			'\t' => out.push_str("&#9;"),
141			_ => out.push(c),
142		}
143	}
144}
145
146fn write_element(
147	out: &mut String,
148	element: &Element,
149	level: usize,
150	pretty: bool,
151) -> Result<(), EtreeError> {
152	// libxml2 limits the indentation to 60 characters (`MAX_INDENT`).
153	let indent = |out: &mut String, level: usize| {
154		for _ in 0..level.min(30) {
155			out.push_str("  ");
156		}
157	};
158	let tag = qname(&element.tag)?;
159	out.push('<');
160	out.push_str(&tag);
161	for (key, value) in &element.attrib {
162		check_xml_string(value)?;
163		out.push(' ');
164		out.push_str(&qname(key)?);
165		out.push_str("=\"");
166		push_attr_value(out, value);
167		out.push('"');
168	}
169	if element.text.is_none() && element.children.is_empty() {
170		out.push_str("/>");
171		return Ok(());
172	}
173	out.push('>');
174	// An element with text has mixed content: libxml2 does not format inside it.
175	let format =
176		pretty && element.text.is_none() && element.children.iter().all(|c| c.tail.is_none());
177	if let Some(text) = &element.text {
178		check_xml_string(text)?;
179		push_text(out, text);
180	}
181	if format {
182		out.push('\n');
183	}
184	for child in &element.children {
185		if format {
186			indent(out, level + 1);
187		}
188		write_element(out, child, level + 1, format)?;
189		if let Some(tail) = &child.tail {
190			check_xml_string(tail)?;
191			push_text(out, tail);
192		}
193		if format {
194			out.push('\n');
195		}
196	}
197	if format {
198		indent(out, level);
199	}
200	out.push_str("</");
201	out.push_str(&tag);
202	out.push('>');
203	Ok(())
204}
205
206/// `etree.ElementTree(root).write(f, encoding="UTF-8", xml_declaration=...,
207/// pretty_print=...)`, as a string. The tail of `root` is not written.
208pub fn tostring(
209	root: &Element,
210	pretty_print: bool,
211	xml_declaration: bool,
212) -> Result<String, EtreeError> {
213	let mut out = String::new();
214	if xml_declaration {
215		out.push_str("<?xml version='1.0' encoding='UTF-8'?>\n");
216	}
217	write_element(&mut out, root, 0, pretty_print)?;
218	if pretty_print {
219		out.push('\n');
220	}
221	Ok(out)
222}
223
224/// The name of a parsed element or attribute: Clark notation if it has a
225/// namespace.
226fn clark(namespace: Option<&str>, name: &str) -> String {
227	match namespace {
228		Some(ns) => format!("{{{ns}}}{name}"),
229		None => name.to_owned(),
230	}
231}
232
233fn convert(node: roxmltree::Node<'_, '_>) -> Result<Element, EtreeError> {
234	let tag = node.tag_name();
235	let mut element = Element::new(clark(tag.namespace(), tag.name()));
236	element.attrib = node
237		.attributes()
238		.map(|a| (clark(a.namespace(), a.name()), a.value().to_owned()))
239		.collect();
240	for child in node.children() {
241		if child.is_element() {
242			element.children.push(convert(child)?);
243		} else if child.is_text() {
244			let text = child.text().unwrap_or_default();
245			let slot = match element.children.last_mut() {
246				Some(last) => &mut last.tail,
247				None => &mut element.text,
248			};
249			slot.get_or_insert_with(String::new).push_str(text);
250		} else {
251			return Err(EtreeError(
252				"comments and processing instructions are not supported".into(),
253			));
254		}
255	}
256	Ok(element)
257}
258
259/// Parses a document and returns its root element (`etree.fromstring(text)`).
260/// Comments and processing instructions inside the root element are not
261/// supported.
262pub fn fromstring(text: &str) -> Result<Element, EtreeError> {
263	let options = roxmltree::ParsingOptions {
264		allow_dtd: true,
265		..Default::default()
266	};
267	let doc = roxmltree::Document::parse_with_options(text, options)
268		.map_err(|e| EtreeError(e.to_string()))?;
269	convert(doc.root_element())
270}
271
272#[cfg(test)]
273mod tests {
274	use super::*;
275
276	#[test]
277	fn lxml_pretty_print() -> Result<(), EtreeError> {
278		let mut root = Element::new("a");
279		let mut s = Element::new("string");
280		s.text = Some(String::new());
281		root.append(s);
282		let mut t = Element::new("t");
283		t.text = Some("x<>&\"\r\n\t".into());
284		t.set(format!("{XML_NS}lang"), "a\"<>&\n\r\t'");
285		root.append(t);
286		let mut e = Element::new("e");
287		e.append(Element::new("x"));
288		root.append(e);
289		// Checked against lxml 6.
290		assert_eq!(
291			tostring(&root, true, true)?,
292			"<?xml version='1.0' encoding='UTF-8'?>\n<a>\n  <string></string>\n  <t xml:lang=\"a&quot;&lt;&gt;&amp;&#10;&#13;&#9;'\">x&lt;&gt;&amp;\"&#13;\n\t</t>\n  <e>\n    <x/>\n  </e>\n</a>\n"
293		);
294		Ok(())
295	}
296
297	#[test]
298	fn rejects_control_characters() {
299		let mut root = Element::new("a");
300		root.text = Some("\u{1}".into());
301		assert!(tostring(&root, true, true).is_err());
302	}
303}