Skip to main content

fontoxide_misc/
xml_reader.rs

1//! The XML content model of `fontTools.misc.xmlReader`.
2//!
3//! fontTools hands each table's `fromXML` an element as `(name, attrs, content)`,
4//! where `content` is a list of text chunks and child elements. Text is split the
5//! way expat delivers it: every newline is a separate chunk, and other text is
6//! merged into the preceding chunk unless that chunk is a newline. Some tables
7//! depend on this (for example, they skip `"\n"` chunks), so it is reproduced here.
8//!
9//! The TTX-specific dispatch (tables, `GlyphOrder`, `src` sub-files) lives in
10//! `fontoxide-ttlib`.
11
12use std::fmt;
13
14/// A node in an element's content.
15#[derive(Debug, Clone, PartialEq)]
16pub enum Content {
17	/// A text chunk.
18	Text(String),
19	/// A child element.
20	Element(Element),
21}
22
23impl Content {
24	/// The element, if this is one.
25	pub fn as_element(&self) -> Option<&Element> {
26		match self {
27			Content::Element(e) => Some(e),
28			Content::Text(_) => None,
29		}
30	}
31
32	/// The text, if this is a text chunk.
33	pub fn as_text(&self) -> Option<&str> {
34		match self {
35			Content::Text(t) => Some(t),
36			Content::Element(_) => None,
37		}
38	}
39}
40
41/// An XML element: name, attributes in document order, and content.
42#[derive(Debug, Clone, PartialEq, Default)]
43pub struct Element {
44	/// The element name.
45	pub name: String,
46	/// The attributes, in document order.
47	pub attrs: Vec<(String, String)>,
48	/// Text chunks and child elements.
49	pub content: Vec<Content>,
50}
51
52impl Element {
53	/// The value of an attribute (`attrs[name]` / `attrs.get(name)`).
54	pub fn attr(&self, name: &str) -> Option<&str> {
55		self.attrs
56			.iter()
57			.find(|(n, _)| n == name)
58			.map(|(_, v)| v.as_str())
59	}
60
61	/// The child elements, skipping text (the common
62	/// `if not isinstance(element, tuple): continue` loop).
63	pub fn elements(&self) -> impl Iterator<Item = &Element> {
64		self.content.iter().filter_map(Content::as_element)
65	}
66
67	/// All text chunks concatenated (`strjoin(content)` over the strings).
68	pub fn text(&self) -> String {
69		self.content.iter().filter_map(Content::as_text).collect()
70	}
71
72	/// The text chunks, in order.
73	pub fn text_chunks(&self) -> impl Iterator<Item = &str> {
74		self.content.iter().filter_map(Content::as_text)
75	}
76}
77
78/// An XML syntax error.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ParseError(pub String);
81
82impl fmt::Display for ParseError {
83	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84		f.write_str(&self.0)
85	}
86}
87
88impl std::error::Error for ParseError {}
89
90/// Parses a document and returns its root element.
91pub fn parse(text: &str) -> Result<Element, ParseError> {
92	let options = roxmltree::ParsingOptions {
93		allow_dtd: true,
94		..Default::default()
95	};
96	let doc = roxmltree::Document::parse_with_options(text, options)
97		.map_err(|e| ParseError(e.to_string()))?;
98	Ok(convert(doc.root_element()))
99}
100
101fn convert(node: roxmltree::Node<'_, '_>) -> Element {
102	let mut element = Element {
103		name: node.tag_name().name().to_owned(),
104		attrs: node
105			.attributes()
106			.map(|a| (attr_name(&a), a.value().to_owned()))
107			.collect(),
108		content: Vec::new(),
109	};
110	for child in node.children() {
111		if child.is_element() {
112			element.content.push(Content::Element(convert(child)));
113		} else if child.is_text() {
114			push_text(&mut element.content, child.text().unwrap_or_default());
115		}
116	}
117	element
118}
119
120fn attr_name(a: &roxmltree::Attribute<'_, '_>) -> String {
121	// fontTools parses without namespace processing, so a prefixed attribute keeps
122	// its prefix (e.g. "xml:lang").
123	match a.namespace() {
124		Some("http://www.w3.org/XML/1998/namespace") => format!("xml:{}", a.name()),
125		_ => a.name().to_owned(),
126	}
127}
128
129/// Appends text the way `XMLReader._characterDataHandler` receives it from expat.
130fn push_text(content: &mut Vec<Content>, text: &str) {
131	for (i, piece) in text.split('\n').enumerate() {
132		if i > 0 {
133			append_chunk(content, "\n");
134		}
135		if !piece.is_empty() {
136			append_chunk(content, piece);
137		}
138	}
139}
140
141fn append_chunk(content: &mut Vec<Content>, data: &str) {
142	if data != "\n"
143		&& let Some(Content::Text(last)) = content.last_mut()
144		&& last != "\n"
145	{
146		last.push_str(data);
147		return;
148	}
149	content.push(Content::Text(data.to_owned()));
150}
151
152#[cfg(test)]
153mod tests {
154	use super::*;
155
156	#[test]
157	fn content_model() {
158		let root = parse("<a x=\"1\">\n  <b/>\n  text &amp; more\n</a>").expect("valid xml");
159		assert_eq!(root.name, "a");
160		assert_eq!(root.attr("x"), Some("1"));
161		let texts: Vec<_> = root.text_chunks().collect();
162		assert_eq!(texts, ["\n", "  ", "\n", "  text & more", "\n"]);
163		assert_eq!(root.elements().count(), 1);
164	}
165
166	#[test]
167	fn crlf_is_normalized() {
168		let root = parse("<a>x\r\ny</a>").expect("valid xml");
169		let texts: Vec<_> = root.text_chunks().collect();
170		assert_eq!(texts, ["x", "\n", "y"]);
171	}
172}