//! HTML parsing into the node arena, via html5ever. Hand-directed integration
//! scaffolding (see the crate root doc comment), not generated code.
//!
//! `TreeSink` methods take `&self`, so the arena being built is behind a `RefCell`.
//! Every method here scopes its `borrow`/`borrow_mut` to the call and returns owned
//! data (a [`NodeId`] or a cloned [`markup5ever::QualName`]), never a reference
//! borrowed from the cell -- that is what lets a plain `RefCell` work at all, since
//! nothing here needs a borrow to outlive the method that took it.
use std::cell::RefCell;
use html5ever::tendril::TendrilSink;
use markup5ever::interface::{ElemName, ElementFlags, NodeOrText, QualName, TreeSink};
use markup5ever::{Attribute, Namespace};
use crate::node::{Attr, ElementData, Node, NodeData, NodeId};
use crate::style_data::StyloData;
/// Wraps an owned, cloned [`QualName`] so `TreeSink::elem_name` can return it by
/// value instead of borrowing from the arena's `RefCell` (see the module doc comment).
struct OwnedElemName(QualName);
impl std::fmt::Debug for OwnedElemName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl ElemName for OwnedElemName {
fn ns(&self) -> &Namespace {
&self.0.ns
}
fn local_name(&self) -> &markup5ever::LocalName {
&self.0.local
}
}
struct Sink {
nodes: RefCell>,
/// `target` element id -> its template-contents fragment id, per
/// `TreeSink::get_template_contents`. Phase 0's corpus never uses ``, so
/// this stays empty in practice; it exists so the trait can still be implemented
/// correctly rather than by panicking.
template_contents: RefCell>,
}
impl Sink {
fn new() -> Self {
let document = Node { id: NodeId(0), parent: None, children: Vec::new(), data: NodeData::Document };
Sink { nodes: RefCell::new(vec![document]), template_contents: RefCell::new(Default::default()) }
}
fn push(&self, data: NodeData) -> NodeId {
let mut nodes = self.nodes.borrow_mut();
let id = NodeId(nodes.len());
nodes.push(Node { id, parent: None, children: Vec::new(), data });
id
}
fn set_parent(&self, child: NodeId, parent: NodeId) {
let mut nodes = self.nodes.borrow_mut();
nodes[child.index()].parent = Some(parent);
nodes[parent.index()].children.push(child);
}
/// Appends text to the parent's last child if it is already a text node
/// (`TreeSink::append`'s merge-adjacent-text-nodes contract), otherwise creates one.
fn append_text(&self, parent: NodeId, text: &str) {
let last_text_child = {
let nodes = self.nodes.borrow();
let parent_node = &nodes[parent.index()];
parent_node.children.last().copied().filter(|id| nodes[id.index()].is_text())
};
match last_text_child {
Some(id) => {
let mut nodes = self.nodes.borrow_mut();
if let NodeData::Text(existing) = &mut nodes[id.index()].data {
existing.push_str(text);
}
}
None => {
let id = self.push(NodeData::Text(text.to_string()));
self.set_parent(id, parent);
}
}
}
}
impl TreeSink for Sink {
type Handle = NodeId;
type Output = Vec;
type ElemName<'a> = OwnedElemName;
fn finish(self) -> Self::Output {
self.nodes.into_inner()
}
fn parse_error(&self, msg: std::borrow::Cow<'static, str>) {
eprintln!("html parse error: {msg}");
}
fn get_document(&self) -> Self::Handle {
NodeId(0)
}
fn elem_name<'a>(&'a self, target: &'a Self::Handle) -> Self::ElemName<'a> {
let nodes = self.nodes.borrow();
let element = nodes[target.index()].as_element().expect("elem_name called on a non-element");
OwnedElemName(element.name.clone())
}
fn create_element(&self, name: QualName, attrs: Vec, _flags: ElementFlags) -> Self::Handle {
let id_attr = attrs
.iter()
.find(|a| &*a.name.local == "id")
.map(|a| style::Atom::from(a.value.as_ref()));
let attrs = attrs
.into_iter()
.map(|a| Attr { name: a.name, value: a.value.to_string() })
.collect();
self.push(NodeData::Element(ElementData {
name,
attrs,
id: id_attr,
stylo_data: StyloData::default(),
dirty_descendants: Default::default(),
selector_flags: std::cell::Cell::new(selectors::matching::ElementSelectorFlags::empty()),
style_attribute: std::cell::OnceCell::new(),
}))
}
fn create_comment(&self, text: html5ever::tendril::StrTendril) -> Self::Handle {
self.push(NodeData::Comment(text.to_string()))
}
fn create_pi(&self, target: html5ever::tendril::StrTendril, data: html5ever::tendril::StrTendril) -> Self::Handle {
// Phase 0's corpus has no processing instructions; folded into a comment node
// rather than dropped, so a stray PI is visible instead of silently vanishing.
self.push(NodeData::Comment(format!("?{target} {data}")))
}
fn append(&self, parent: &Self::Handle, child: NodeOrText) {
match child {
NodeOrText::AppendNode(id) => self.set_parent(id, *parent),
NodeOrText::AppendText(text) => self.append_text(*parent, &text),
}
}
fn append_based_on_parent_node(
&self,
element: &Self::Handle,
prev_element: &Self::Handle,
child: NodeOrText,
) {
let has_parent = self.nodes.borrow()[element.index()].parent.is_some();
if has_parent {
self.append(element, child);
} else {
self.append(prev_element, child);
}
}
fn append_doctype_to_document(
&self,
_name: html5ever::tendril::StrTendril,
_public_id: html5ever::tendril::StrTendril,
_system_id: html5ever::tendril::StrTendril,
) {
// Phase 0 compares style and geometry, neither of which the doctype affects
// once quirks mode is fixed to `NoQuirks` (`roadmap.md` -> "Phase 0 economies").
}
fn get_template_contents(&self, target: &Self::Handle) -> Self::Handle {
if let Some(id) = self.template_contents.borrow().get(target) {
return *id;
}
let id = self.push(NodeData::Document);
self.template_contents.borrow_mut().insert(*target, id);
id
}
fn same_node(&self, x: &Self::Handle, y: &Self::Handle) -> bool {
x == y
}
fn set_quirks_mode(&self, _mode: markup5ever::interface::QuirksMode) {
// Quirks mode is fixed to `NoQuirks` throughout (`roadmap.md` -> "Phase 0
// economies"); the parser's own detection is not wired to anything yet.
}
fn append_before_sibling(&self, sibling: &Self::Handle, new_node: NodeOrText) {
let parent = self.nodes.borrow()[sibling.index()].parent.expect("sibling has no parent");
match new_node {
NodeOrText::AppendNode(id) => {
// `set_parent` appends at the end; move it to just before `sibling`.
self.set_parent(id, parent);
let mut nodes = self.nodes.borrow_mut();
let children = &mut nodes[parent.index()].children;
children.pop();
let sibling_pos = children.iter().position(|c| c == sibling).expect("sibling is a child of parent");
children.insert(sibling_pos, id);
}
NodeOrText::AppendText(text) => {
// Only merges with a preceding text sibling, per the trait's contract;
// Phase 0's generator never emits adjacent text runs, so the simpler
// append-then-reorder used above for `AppendNode` is not duplicated here.
let id = self.push(NodeData::Text(text.to_string()));
self.set_parent(id, parent);
let mut nodes = self.nodes.borrow_mut();
let children = &mut nodes[parent.index()].children;
children.pop();
let sibling_pos = children.iter().position(|c| c == sibling).expect("sibling is a child of parent");
children.insert(sibling_pos, id);
}
}
}
fn add_attrs_if_missing(&self, target: &Self::Handle, attrs: Vec) {
let mut nodes = self.nodes.borrow_mut();
if let NodeData::Element(element) = &mut nodes[target.index()].data {
for attr in attrs {
if !element.attrs.iter().any(|a| a.name == attr.name) {
element.attrs.push(Attr { name: attr.name, value: attr.value.to_string() });
}
}
}
}
fn remove_from_parent(&self, target: &Self::Handle) {
let mut nodes = self.nodes.borrow_mut();
if let Some(parent) = nodes[target.index()].parent.take() {
nodes[parent.index()].children.retain(|c| c != target);
}
}
fn reparent_children(&self, node: &Self::Handle, new_parent: &Self::Handle) {
let mut nodes = self.nodes.borrow_mut();
let moved = std::mem::take(&mut nodes[node.index()].children);
for &child in &moved {
nodes[child.index()].parent = Some(*new_parent);
}
nodes[new_parent.index()].children.extend(moved);
}
}
/// Parses `html` into a node arena. `nodes[0]` is always the document node.
pub fn parse_html(html: &str) -> Vec {
let sink = Sink::new();
let parser = html5ever::driver::parse_document(sink, html5ever::driver::ParseOpts::default());
parser.one(html.to_string())
}
/// Concatenates the text content of every `");
assert_eq!(collect_stylesheet_text(&nodes), "a{}b{}");
}
#[test]
fn collect_stylesheet_text_is_empty_with_no_style_element() {
let nodes = parse_html("");
assert_eq!(collect_stylesheet_text(&nodes), "");
}
}