#![allow(
clippy::panic,
clippy::expect_used,
clippy::missing_panics_doc,
clippy::must_use_candidate,
clippy::return_self_not_must_use,
clippy::module_name_repetitions,
clippy::redundant_else,
clippy::match_wildcard_for_single_variants,
clippy::similar_names,
clippy::items_after_statements,
clippy::use_self,
clippy::missing_fields_in_debug,
clippy::semicolon_if_nothing_returned,
missing_docs
)]
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::{HashSet, VecDeque};
use std::default::Default;
use std::fmt;
use std::io;
use std::mem;
use std::rc::{Rc, Weak};
use html5ever::tendril::StrTendril;
use html5ever::Attribute;
use html5ever::ExpandedName;
use html5ever::QualName;
use html5ever::interface::tree_builder;
use html5ever::interface::tree_builder::{ElementFlags, NodeOrText, QuirksMode, TreeSink};
use html5ever::serialize::TraversalScope;
use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
use html5ever::serialize::{Serialize, Serializer};
#[derive(Debug)]
pub enum NodeData {
Document,
Doctype {
name: StrTendril,
#[allow(dead_code)]
public_id: StrTendril,
#[allow(dead_code)]
system_id: StrTendril,
},
Text { contents: RefCell<StrTendril> },
Comment { contents: StrTendril },
Element {
name: QualName,
attrs: RefCell<Vec<Attribute>>,
template_contents: RefCell<Option<Handle>>,
mathml_annotation_xml_integration_point: bool,
},
ProcessingInstruction { target: StrTendril, contents: StrTendril },
}
struct DepthCache {
epoch: usize,
depth: usize,
root: WeakHandle,
}
pub struct Node {
pub parent: Cell<Option<WeakHandle>>,
template_host: Cell<Option<WeakHandle>>,
depth_cache: RefCell<Option<DepthCache>>,
pub children: RefCell<Vec<Handle>>,
pub data: NodeData,
}
impl Node {
pub fn new(data: NodeData) -> Rc<Self> {
Rc::new(Node {
data,
parent: Cell::new(None),
template_host: Cell::new(None),
depth_cache: RefCell::new(None),
children: RefCell::new(Vec::new()),
})
}
}
impl Drop for Node {
fn drop(&mut self) {
let mut nodes = mem::take(&mut *self.children.borrow_mut());
while let Some(node) = nodes.pop() {
let children = mem::take(&mut *node.children.borrow_mut());
nodes.extend(children);
if let NodeData::Element {
ref template_contents, ..
} = node.data
{
if let Some(template_contents) = template_contents.borrow_mut().take() {
nodes.push(template_contents);
}
}
}
}
}
impl fmt::Debug for Node {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Node")
.field("data", &self.data)
.field("children", &self.children)
.finish()
}
}
pub type Handle = Rc<Node>;
pub type WeakHandle = Weak<Node>;
fn append(new_parent: &Handle, child: Handle) {
let previous_parent = child.parent.replace(Some(Rc::downgrade(new_parent)));
assert!(previous_parent.is_none());
new_parent.children.borrow_mut().push(child);
}
fn depth_ancestor(node: &Handle) -> Option<Handle> {
let read = |link: &Cell<Option<WeakHandle>>| {
let weak = link.take();
let handle = weak.as_ref().and_then(Weak::upgrade);
link.set(weak);
handle
};
read(&node.parent).or_else(|| read(&node.template_host))
}
fn get_parent_and_index(target: &Handle) -> Option<(Handle, usize)> {
if let Some(weak) = target.parent.take() {
let parent = weak.upgrade().expect("dangling weak pointer");
target.parent.set(Some(weak));
let i = match parent
.children
.borrow()
.iter()
.enumerate()
.find(|&(_, child)| Rc::ptr_eq(child, target))
{
Some((i, _)) => i,
None => panic!("have parent but couldn't find in parent's children!"),
};
Some((parent, i))
} else {
None
}
}
fn append_to_existing_text(prev: &Handle, text: &str) -> bool {
match prev.data {
NodeData::Text { ref contents } => {
contents.borrow_mut().push_slice(text);
true
}
_ => false,
}
}
fn remove_from_parent(target: &Handle) {
if let Some((parent, i)) = get_parent_and_index(target) {
parent.children.borrow_mut().remove(i);
target.parent.set(None);
}
}
pub struct RcDom {
pub document: Handle,
pub errors: RefCell<Vec<Cow<'static, str>>>,
pub quirks_mode: Cell<QuirksMode>,
node_count: Cell<usize>,
max_nodes: usize,
max_depth: usize,
topology_epoch: Cell<usize>,
#[cfg(test)]
depth_reads: Cell<usize>,
pub(crate) repair_limit: Cell<Option<crate::types::WarningKind>>,
}
impl RcDom {
pub(crate) fn bounded(max_nodes: usize, max_depth: usize) -> Self {
Self {
max_nodes,
max_depth,
..Self::default()
}
}
fn new_node(&self, data: NodeData) -> Handle {
self.node_count.set(self.node_count.get().saturating_add(1));
if self.node_count.get() > self.max_nodes {
self.repair_limit.set(Some(crate::types::WarningKind::TruncatedInput));
}
Node::new(data)
}
fn subtree_fits_depth(&self, parent: &Handle, children: &[Handle]) -> bool {
if self.max_depth == usize::MAX || children.is_empty() {
return true;
}
let depth = self.parent_depth(parent);
if depth > self.max_depth {
self.repair_limit
.set(Some(crate::types::WarningKind::DepthLimitExceeded));
return false;
}
let mut work: Vec<_> = children.iter().map(|child| (Rc::clone(child), depth + 1)).collect();
while let Some((node, depth)) = work.pop() {
if depth > self.max_depth {
self.repair_limit
.set(Some(crate::types::WarningKind::DepthLimitExceeded));
return false;
}
work.extend(node.children.borrow().iter().map(|child| (Rc::clone(child), depth + 1)));
}
true
}
fn read_depth_ancestor(&self, node: &Handle) -> Option<Handle> {
#[cfg(test)]
self.depth_reads.set(self.depth_reads.get() + 1);
depth_ancestor(node)
}
fn invalidate_depths(&self) {
self.topology_epoch.set(self.topology_epoch.get().saturating_add(1));
}
fn prepare_attachment(&self, parent: &Handle, child: &Handle) {
if Rc::ptr_eq(parent, child)
|| !child.children.borrow().is_empty()
|| matches!(child.data, NodeData::Element { ref template_contents, .. }
if template_contents.borrow().is_some())
{
self.invalidate_depths();
child.depth_cache.borrow_mut().take();
return;
}
*child.depth_cache.borrow_mut() = parent.depth_cache.borrow().as_ref().map(|cache| DepthCache {
epoch: cache.epoch,
depth: cache.depth.saturating_add(1),
root: cache.root.clone(),
});
}
fn parent_depth(&self, parent: &Handle) -> usize {
let epoch = self.topology_epoch.get();
let mut path = Vec::new();
let mut current = Rc::clone(parent);
let (mut depth, root) = loop {
if epoch != usize::MAX {
if let Some(cache) = current.depth_cache.borrow().as_ref() {
if cache.epoch == epoch && cache.root.strong_count() != 0 {
break (cache.depth, cache.root.clone());
}
}
}
path.push(Rc::clone(¤t));
if path.len() > self.max_depth.saturating_add(1) {
return self.max_depth.saturating_add(1);
}
let Some(ancestor) = self.read_depth_ancestor(¤t) else {
path.pop();
let root = Rc::downgrade(¤t);
*current.depth_cache.borrow_mut() = Some(DepthCache {
epoch,
depth: 0,
root: root.clone(),
});
break (0, root);
};
current = ancestor;
};
for node in path.into_iter().rev() {
depth = depth.saturating_add(1);
*node.depth_cache.borrow_mut() = Some(DepthCache {
epoch,
depth,
root: root.clone(),
});
}
depth
}
fn observe_depth(&self, parent: &Handle) {
if self.max_depth != usize::MAX && self.parent_depth(parent) >= self.max_depth {
self.repair_limit
.set(Some(crate::types::WarningKind::DepthLimitExceeded));
}
}
}
impl TreeSink for RcDom {
type Output = Self;
fn finish(self) -> Self {
self
}
type Handle = Handle;
type ElemName<'a>
= ExpandedName<'a>
where
Self: 'a;
fn parse_error(&self, msg: Cow<'static, str>) {
self.errors.borrow_mut().push(msg);
}
fn get_document(&self) -> Handle {
self.document.clone()
}
fn get_template_contents(&self, target: &Handle) -> Handle {
if let NodeData::Element {
ref template_contents, ..
} = target.data
{
template_contents
.borrow()
.as_ref()
.expect("not a template element!")
.clone()
} else {
panic!("not a template element!")
}
}
fn set_quirks_mode(&self, mode: QuirksMode) {
self.quirks_mode.set(mode);
}
fn same_node(&self, x: &Handle, y: &Handle) -> bool {
Rc::ptr_eq(x, y)
}
fn elem_name<'a>(&self, target: &'a Handle) -> ExpandedName<'a> {
match target.data {
NodeData::Element { ref name, .. } => name.expanded(),
_ => panic!("not an element!"),
}
}
fn create_element(&self, name: QualName, attrs: Vec<Attribute>, flags: ElementFlags) -> Handle {
let contents = flags.template.then(|| self.new_node(NodeData::Document));
let element = self.new_node(NodeData::Element {
name,
attrs: RefCell::new(attrs),
template_contents: RefCell::new(contents.clone()),
mathml_annotation_xml_integration_point: flags.mathml_annotation_xml_integration_point,
});
if let Some(contents) = contents {
contents.template_host.set(Some(Rc::downgrade(&element)));
}
element
}
fn create_comment(&self, text: StrTendril) -> Handle {
self.new_node(NodeData::Comment { contents: text })
}
fn create_pi(&self, target: StrTendril, data: StrTendril) -> Handle {
self.new_node(NodeData::ProcessingInstruction { target, contents: data })
}
fn append(&self, parent: &Handle, child: NodeOrText<Handle>) {
self.observe_depth(parent);
if let NodeOrText::AppendNode(node) = &child {
if !node.children.borrow().is_empty() && !self.subtree_fits_depth(parent, std::slice::from_ref(node)) {
return;
}
}
if let NodeOrText::AppendText(text) = &child {
if let Some(h) = parent.children.borrow().last() {
if append_to_existing_text(h, text) {
return;
}
}
}
if let NodeOrText::AppendNode(node) = &child {
self.prepare_attachment(parent, node);
}
append(
parent,
match child {
NodeOrText::AppendText(text) => self.new_node(NodeData::Text {
contents: RefCell::new(text),
}),
NodeOrText::AppendNode(node) => node,
},
);
}
fn append_before_sibling(&self, sibling: &Handle, child: NodeOrText<Handle>) {
let (parent, i) = get_parent_and_index(sibling).expect("append_before_sibling called on node without parent");
self.observe_depth(&parent);
if let NodeOrText::AppendNode(node) = &child {
if !node.children.borrow().is_empty() && !self.subtree_fits_depth(&parent, std::slice::from_ref(node)) {
return;
}
}
let child = match (child, i) {
(NodeOrText::AppendText(text), 0) => self.new_node(NodeData::Text {
contents: RefCell::new(text),
}),
(NodeOrText::AppendText(text), i) => {
let children = parent.children.borrow();
let prev = &children[i - 1];
if append_to_existing_text(prev, &text) {
return;
}
self.new_node(NodeData::Text {
contents: RefCell::new(text),
})
}
(NodeOrText::AppendNode(node), _) => node,
};
self.invalidate_depths();
remove_from_parent(&child);
child.parent.set(Some(Rc::downgrade(&parent)));
parent.children.borrow_mut().insert(i, child);
}
fn append_based_on_parent_node(
&self,
element: &Self::Handle,
prev_element: &Self::Handle,
child: NodeOrText<Self::Handle>,
) {
let parent = element.parent.take();
let has_parent = parent.is_some();
element.parent.set(parent);
if has_parent {
self.append_before_sibling(element, child);
} else {
self.append(prev_element, child);
}
}
fn append_doctype_to_document(&self, name: StrTendril, public_id: StrTendril, system_id: StrTendril) {
append(
&self.document,
self.new_node(NodeData::Doctype {
name,
public_id,
system_id,
}),
);
}
fn add_attrs_if_missing(&self, target: &Handle, attrs: Vec<Attribute>) {
let mut existing = if let NodeData::Element { ref attrs, .. } = target.data {
attrs.borrow_mut()
} else {
panic!("not an element")
};
let existing_names = existing.iter().map(|e| e.name.clone()).collect::<HashSet<_>>();
existing.extend(attrs.into_iter().filter(|attr| !existing_names.contains(&attr.name)));
}
fn remove_from_parent(&self, target: &Handle) {
self.invalidate_depths();
remove_from_parent(target);
}
fn reparent_children(&self, node: &Handle, new_parent: &Handle) {
self.observe_depth(new_parent);
if !self.subtree_fits_depth(new_parent, &node.children.borrow()) {
return;
}
self.invalidate_depths();
let mut children = node.children.borrow_mut();
let mut new_children = new_parent.children.borrow_mut();
for child in children.iter() {
let previous_parent = child.parent.replace(Some(Rc::downgrade(new_parent)));
assert!(Rc::ptr_eq(
node,
&previous_parent
.expect("invariant: child must have a parent during reparenting")
.upgrade()
.expect("dangling weak")
))
}
new_children.extend(mem::take(&mut *children));
}
fn is_mathml_annotation_xml_integration_point(&self, target: &Handle) -> bool {
if let NodeData::Element {
mathml_annotation_xml_integration_point,
..
} = target.data
{
mathml_annotation_xml_integration_point
} else {
panic!("not an element!")
}
}
}
impl Default for RcDom {
fn default() -> RcDom {
RcDom {
document: Node::new(NodeData::Document),
errors: Default::default(),
quirks_mode: Cell::new(tree_builder::NoQuirks),
node_count: Cell::new(1),
max_nodes: usize::MAX,
max_depth: usize::MAX,
topology_epoch: Cell::new(0),
#[cfg(test)]
depth_reads: Cell::new(0),
repair_limit: Cell::new(None),
}
}
}
enum SerializeOp {
Open(Handle),
Close(QualName),
}
pub struct SerializableHandle(Handle, bool);
impl From<Handle> for SerializableHandle {
fn from(h: Handle) -> SerializableHandle {
SerializableHandle(h, false)
}
}
impl SerializableHandle {
pub const fn with_template_contents(h: Handle) -> SerializableHandle {
SerializableHandle(h, true)
}
}
impl Serialize for SerializableHandle {
fn serialize<S>(&self, serializer: &mut S, traversal_scope: TraversalScope) -> io::Result<()>
where
S: Serializer,
{
let mut ops = VecDeque::new();
match traversal_scope {
IncludeNode => ops.push_back(SerializeOp::Open(self.0.clone())),
ChildrenOnly(_) => ops.extend(self.0.children.borrow().iter().map(|h| SerializeOp::Open(h.clone()))),
}
while let Some(op) = ops.pop_front() {
match op {
SerializeOp::Open(handle) => match handle.data {
NodeData::Element {
ref name,
ref attrs,
ref template_contents,
..
} => {
serializer
.start_elem(name.clone(), attrs.borrow().iter().map(|at| (&at.name, &at.value[..])))?;
let contents = template_contents.borrow().clone().filter(|_| self.1);
let parent = contents.as_ref().unwrap_or(&handle);
if name.ns == html5ever::ns!(html)
&& matches!(&*name.local, "pre" | "textarea" | "listing")
&& parent.children.borrow().first().is_some_and(|child| {
matches!(&child.data, NodeData::Text { contents } if contents.borrow().starts_with('\n'))
})
{
serializer.write_text("\n")?;
}
ops.reserve(1 + parent.children.borrow().len());
ops.push_front(SerializeOp::Close(name.clone()));
for child in parent.children.borrow().iter().rev() {
ops.push_front(SerializeOp::Open(child.clone()));
}
}
NodeData::Doctype { ref name, .. } => serializer.write_doctype(name)?,
NodeData::Text { ref contents } => serializer.write_text(&contents.borrow())?,
NodeData::Comment { ref contents } => serializer.write_comment(contents)?,
NodeData::ProcessingInstruction {
ref target,
ref contents,
} => serializer.write_processing_instruction(target, contents)?,
NodeData::Document => panic!("Can't serialize Document node itself"),
},
SerializeOp::Close(name) => {
serializer.end_elem(name)?;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod bounded_reparent_tests {
use super::*;
use html5ever::{local_name, ns};
#[test]
fn bounded_repair_should_detect_descendant_depth_when_reparenting() {
let dom = RcDom::bounded(100, 4);
let element = || {
dom.create_element(
QualName::new(None, ns!(html), local_name!(div)),
Vec::new(),
ElementFlags::default(),
)
};
let mut branch = dom.document.clone();
let mut first = None;
for _ in 0..4 {
let child = element();
dom.append(&branch, NodeOrText::AppendNode(child.clone()));
first.get_or_insert_with(|| child.clone());
branch = child;
}
let destination = element();
dom.append(&dom.document, NodeOrText::AppendNode(destination.clone()));
let nested_destination = element();
dom.append(&destination, NodeOrText::AppendNode(nested_destination.clone()));
assert_eq!(dom.repair_limit.get(), None);
dom.reparent_children(&first.expect("source branch"), &nested_destination);
assert_eq!(
dom.repair_limit.get(),
Some(crate::types::WarningKind::DepthLimitExceeded)
);
}
}
#[cfg(test)]
mod depth_cache_tests;
#[cfg(test)]
mod preformatted_serialization_tests {
use super::{RcDom, SerializableHandle};
use html5ever::serialize::{SerializeOpts, serialize};
use html5ever::tendril::TendrilSink;
#[test]
fn should_preserve_initial_text_line_feeds_when_reparsed() {
for name in ["pre", "textarea", "listing"] {
for leading in 0..=3 {
let input = format!("<{name}>{}x</{name}>", "\n".repeat(leading));
let dom = html5ever::parse_document(RcDom::default(), Default::default()).one(input);
let mut output = Vec::new();
serialize(
&mut output,
&SerializableHandle::from(dom.document),
SerializeOpts::default(),
)
.expect("serialize preformatted element");
let serialized_feeds = if leading == 1 { 0 } else { leading };
assert_eq!(
String::from_utf8(output).expect("serialized HTML is UTF-8"),
format!(
"<html><head></head><body><{name}>{}x</{name}></body></html>",
"\n".repeat(serialized_feeds),
),
"{name}: {leading} original line feeds",
);
}
}
}
}