260 lines
8.7 KiB
Rust
260 lines
8.7 KiB
Rust
//! The SVG tree the core owns (roxmltree's borrows its input text): elements with their
|
|
//! qualified name as written, the resolved namespace, attributes in source order (namespace
|
|
//! declarations first, as attributes named `xmlns` / `xmlns:p`), and text. Depth is capped
|
|
//! at 64 by the prescan before any tree exists, so recursion over it is bounded.
|
|
|
|
use super::prescan::{PrescanError, SVG_CAPS, prescan};
|
|
|
|
pub const SVG_NS: &str = "http://www.w3.org/2000/svg";
|
|
pub const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
|
|
pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
|
|
|
|
/// A node kept in the tree. Comments and processing instructions are not read (R3 C3).
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum Node {
|
|
Element(Element),
|
|
Text(String),
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Element {
|
|
/// The name as written (`path`, `s:path`): the allowlist matches it, like the engine.
|
|
pub qname: String,
|
|
/// The resolved namespace; `None` when the document declares none (xmldom reads such an
|
|
/// element as SVG under `image/svg+xml`).
|
|
pub namespace: Option<String>,
|
|
pub attrs: Vec<Attribute>,
|
|
pub children: Vec<Node>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Attribute {
|
|
pub qname: String,
|
|
pub namespace: Option<String>,
|
|
pub value: String,
|
|
}
|
|
|
|
impl Element {
|
|
/// A new element in the SVG namespace (the layer and the halo filter).
|
|
pub fn svg(name: &str, attrs: Vec<(&str, String)>, children: Vec<Node>) -> Self {
|
|
Self {
|
|
qname: name.to_owned(),
|
|
namespace: Some(SVG_NS.to_owned()),
|
|
attrs: attrs
|
|
.into_iter()
|
|
.map(|(qname, value)| Attribute {
|
|
qname: qname.to_owned(),
|
|
namespace: None,
|
|
value,
|
|
})
|
|
.collect(),
|
|
children,
|
|
}
|
|
}
|
|
|
|
pub fn attr(&self, qname: &str) -> Option<&str> {
|
|
self.attrs
|
|
.iter()
|
|
.find(|a| a.qname == qname)
|
|
.map(|a| a.value.as_str())
|
|
}
|
|
|
|
/// Sets an attribute in place (keeps its position), or appends it.
|
|
pub fn set_attr(&mut self, qname: &str, value: String) {
|
|
match self.attrs.iter_mut().find(|a| a.qname == qname) {
|
|
Some(a) => a.value = value,
|
|
None => self.attrs.push(Attribute {
|
|
qname: qname.to_owned(),
|
|
namespace: None,
|
|
value,
|
|
}),
|
|
}
|
|
}
|
|
|
|
pub fn remove_attr(&mut self, qname: &str) {
|
|
self.attrs.retain(|a| a.qname != qname);
|
|
}
|
|
|
|
/// The local name (after the prefix, if any).
|
|
pub fn local_name(&self) -> &str {
|
|
self.qname.rsplit(':').next().unwrap_or(&self.qname)
|
|
}
|
|
|
|
pub fn is_svg_namespace(&self) -> bool {
|
|
self.namespace.as_deref().is_none_or(|ns| ns == SVG_NS)
|
|
}
|
|
|
|
pub fn element_children(&self) -> impl Iterator<Item = &Element> {
|
|
self.children.iter().filter_map(|n| match n {
|
|
Node::Element(e) => Some(e),
|
|
Node::Text(_) => None,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Why an SVG text is refused (closed codes, `reason()` is the wire form).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum SvgRejection {
|
|
TooLarge,
|
|
Doctype,
|
|
Malformed,
|
|
NotSvg,
|
|
TooManyElements,
|
|
TooDeep,
|
|
TooManyUses,
|
|
TooComplex,
|
|
ReferenceCycle,
|
|
}
|
|
|
|
impl SvgRejection {
|
|
pub fn reason(self) -> &'static str {
|
|
match self {
|
|
Self::TooLarge => "too_large",
|
|
Self::Doctype => "doctype",
|
|
Self::Malformed => "malformed",
|
|
Self::NotSvg => "not_svg",
|
|
Self::TooManyElements => "too_many_elements",
|
|
Self::TooDeep => "too_deep",
|
|
Self::TooManyUses => "too_many_uses",
|
|
Self::TooComplex => "too_complex",
|
|
Self::ReferenceCycle => "reference_cycle",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<PrescanError> for SvgRejection {
|
|
fn from(error: PrescanError) -> Self {
|
|
match error {
|
|
PrescanError::TooLarge => Self::TooLarge,
|
|
PrescanError::Doctype => Self::Doctype,
|
|
PrescanError::TooDeep => Self::TooDeep,
|
|
PrescanError::TooManyElements => Self::TooManyElements,
|
|
PrescanError::TooComplex => Self::TooComplex,
|
|
PrescanError::Malformed => Self::Malformed,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Never reached once the prescan passed (its caps are lower); a backstop on parser memory.
|
|
const NODES_LIMIT: u32 = 200_000;
|
|
|
|
/// Bounds, parses and reads an SVG text into the core's tree; the root must be `<svg>` in the
|
|
/// SVG namespace (or none), written unprefixed.
|
|
pub fn parse_svg(text: &str) -> Result<Element, SvgRejection> {
|
|
prescan(text, &SVG_CAPS)?;
|
|
let options = roxmltree::ParsingOptions {
|
|
allow_dtd: false,
|
|
nodes_limit: NODES_LIMIT,
|
|
..roxmltree::ParsingOptions::default()
|
|
};
|
|
let document = roxmltree::Document::parse_with_options(text, options).map_err(|e| match e {
|
|
roxmltree::Error::NodesLimitReached => SvgRejection::TooComplex,
|
|
roxmltree::Error::DtdDetected => SvgRejection::Doctype,
|
|
_ => SvgRejection::Malformed,
|
|
})?;
|
|
let root = element_of(document.root_element(), text, None);
|
|
if root.qname != "svg" || !root.is_svg_namespace() {
|
|
return Err(SvgRejection::NotSvg);
|
|
}
|
|
Ok(root)
|
|
}
|
|
|
|
/// The qualified name as written: the bytes after `<` up to whitespace, `/` or `>`.
|
|
fn written_name(text: &str, start: usize) -> String {
|
|
text[start + 1..]
|
|
.split(|c: char| c.is_ascii_whitespace() || c == '/' || c == '>')
|
|
.next()
|
|
.unwrap_or_default()
|
|
.to_owned()
|
|
}
|
|
|
|
fn element_of(
|
|
node: roxmltree::Node<'_, '_>,
|
|
text: &str,
|
|
parent: Option<roxmltree::Node<'_, '_>>,
|
|
) -> Element {
|
|
let mut attrs = declarations_of(node, parent);
|
|
attrs.extend(node.attributes().map(|a| Attribute {
|
|
qname: text[a.range_qname()].to_owned(),
|
|
namespace: a.namespace().map(str::to_owned),
|
|
value: a.value().to_owned(),
|
|
}));
|
|
let children = node
|
|
.children()
|
|
.filter_map(|child| {
|
|
if child.is_element() {
|
|
Some(Node::Element(element_of(child, text, Some(node))))
|
|
} else if child.is_text() {
|
|
Some(Node::Text(child.text().unwrap_or_default().to_owned()))
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
Element {
|
|
qname: written_name(text, node.range().start),
|
|
namespace: node.tag_name().namespace().map(str::to_owned),
|
|
attrs,
|
|
children,
|
|
}
|
|
}
|
|
|
|
/// The namespaces declared on this element: in scope here and not in the parent's scope.
|
|
fn declarations_of(
|
|
node: roxmltree::Node<'_, '_>,
|
|
parent: Option<roxmltree::Node<'_, '_>>,
|
|
) -> Vec<Attribute> {
|
|
let inherited: Vec<(Option<&str>, &str)> = parent
|
|
.map(|p| p.namespaces().map(|n| (n.name(), n.uri())).collect())
|
|
.unwrap_or_default();
|
|
node.namespaces()
|
|
.filter(|n| n.name() != Some("xml") && !inherited.contains(&(n.name(), n.uri())))
|
|
.map(|n| Attribute {
|
|
qname: n
|
|
.name()
|
|
.map_or_else(|| "xmlns".to_owned(), |p| format!("xmlns:{p}")),
|
|
namespace: Some(XMLNS_NS.to_owned()),
|
|
value: n.uri().to_owned(),
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn reads_names_as_written_namespaces_and_declarations() {
|
|
let text = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 1 1\"><g id=\"a\">\n <use xlink:href=\"#a\"/></g></svg>";
|
|
let root = parse_svg(text).unwrap_or_else(|e| panic!("{e:?}"));
|
|
let names: Vec<&str> = root.attrs.iter().map(|a| a.qname.as_str()).collect();
|
|
assert_eq!(names, ["xmlns", "xmlns:xlink", "viewBox"]);
|
|
let g = root
|
|
.element_children()
|
|
.next()
|
|
.unwrap_or_else(|| panic!("g"));
|
|
assert!(g.attrs.iter().all(|a| !a.qname.starts_with("xmlns")));
|
|
assert_eq!(g.children.len(), 2);
|
|
let Node::Element(use_el) = &g.children[1] else {
|
|
panic!("use")
|
|
};
|
|
assert_eq!(use_el.attrs[0].qname, "xlink:href");
|
|
assert_eq!(use_el.attrs[0].namespace.as_deref(), Some(XLINK_NS));
|
|
}
|
|
|
|
#[test]
|
|
fn refuses_a_prefixed_or_foreign_root_and_accepts_one_without_namespace() {
|
|
let prefixed = "<s:svg xmlns:s=\"http://www.w3.org/2000/svg\"/>";
|
|
assert_eq!(parse_svg(prefixed), Err(SvgRejection::NotSvg));
|
|
assert_eq!(
|
|
parse_svg("<svg xmlns=\"http://e\"/>"),
|
|
Err(SvgRejection::NotSvg)
|
|
);
|
|
assert!(parse_svg("<svg><path/></svg>").is_ok());
|
|
assert_eq!(
|
|
parse_svg("<svg><path xlink:href=\"#p\"/></svg>"),
|
|
Err(SvgRejection::Malformed)
|
|
);
|
|
}
|
|
}
|