Something went wrong. Try again.
Exploring the idea of generated web rendering engine.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333//! A second, deliberately separate way to hold a parsed document: mutable, and reachable//! only by `#id`, where [`crate::style::Document`] is immutable after `parse` and reachable//! through Stylo's selector matching. `crate::style`'s module doc explains why that type//! never mutates ("no incremental restyle -- a document is styled once, never mutated");//! [`MutableTree`] exists for the half of `docs/feature-cost-experiment.md`'s measurement//! that needs the opposite -- DOM tree mutation (`§4.2.3`/`§4.2.4` of the DOM standard) --//! and has no Stylo integration at all, so it carries none of that type's constraints.//! Reflection typing (`crate::reflect`) is the experiment's other half and needs no tree at//! all, mutable or not.
use std::cell::{Cell, OnceCell};
use selectors::matching::ElementSelectorFlags;
use crate::node::{Attr, ElementData, Node, NodeData, NodeId};use crate::style_data::StyloData;
/// A parsed, mutable node arena. Reuses `crate::parse::parse_html` to build the initial/// arena -- the one reusable primitive that one-shot tree builder offers (`crate::parse`'s/// `Sink` itself is not reusable, see that module's doc comment) -- then adds its own/// mutation methods on top, working directly with `crate::node`'s plain arena types/// rather than through any Stylo-facing trait.pub struct MutableTree { nodes: Vec<Node>,}
/// Why a mutation could not be applied. Named for the DOM standard step it corresponds/// to, not for the op that failed to apply -- `RemoveChild` and `InsertBefore` share/// `NotFound` when their target `#id` does not resolve.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum MutationError { /// No element in the tree carries the `#id` a op named. NotFound, /// The node named has no parent -- already removed, or the document element itself. NoParent, /// A node was found under its parent's own record, but not among that parent's /// `children` -- an invariant violation `insert_element_before` defends against /// rather than assumes away. NotAChild,}
impl MutableTree { pub fn parse(html: &str) -> Self { MutableTree { nodes: crate::parse::parse_html(html) } }
pub fn nodes(&self) -> &[Node] { &self.nodes }
pub fn node(&self, id: NodeId) -> &Node { &self.nodes[id.index()] }
/// The `<html>` element: the document node's only element child, found the same way /// `crate::style::Document::parse` finds its own `root` -- duplicated rather than /// shared, since the two types share no code (module doc). pub fn root(&self) -> NodeId { self.nodes[0] .children .iter() .copied() .find(|&c| self.nodes[c.index()].is_element()) .expect("parse_html always synthesizes <html>") }
/// Every element reachable from `root()`, in document order (preorder: a parent /// before its children), matching `crate::style::Document::elements_in_document_order`. pub fn elements_in_document_order(&self) -> Vec<NodeId> { let mut out = Vec::new(); self.walk_elements(self.root(), &mut out); out }
fn walk_elements(&self, id: NodeId, out: &mut Vec<NodeId>) { out.push(id); for &child in &self.nodes[id.index()].children { if self.nodes[child.index()].is_element() { self.walk_elements(child, out); } } }
/// The first element under `root()` whose `id` attribute is `id_value`, in document /// order. This seam's only selector -- `docs/feature-cost-experiment.md` records the /// scope decision to test tree mutation and reflection against `#id` lookups alone, /// not general CSS selector matching. pub fn find_by_id(&self, id_value: &str) -> Option<NodeId> { self.elements_in_document_order() .into_iter() .find(|&id| self.nodes[id.index()].as_element().and_then(|e| e.attr("id")) == Some(id_value)) }
/// The uppercase tag name, matching `docs/dump-format.md`'s `tag` convention and /// `crate::style::Document`'s own `NodeId::tag`. pub fn tag(&self, id: NodeId) -> String { let element = self.nodes[id.index()].as_element().expect("tag() called on a non-element"); let name: &str = &element.name.local; name.to_ascii_uppercase() }
pub fn attr(&self, id: NodeId, name: &str) -> Option<&str> { self.nodes[id.index()].as_element().and_then(|e| e.attr(name)) }
pub fn set_attribute(&mut self, id: NodeId, name: &str, value: &str) { let Some(element) = self.element_mut(id) else { return }; match element.attrs.iter_mut().find(|a| &*a.name.local == name) { Some(attr) => attr.value = value.to_string(), None => element.attrs.push(Attr { name: attribute_name(name), value: value.to_string() }), } if name == "id" { element.id = Some(style::Atom::from(value)); } }
pub fn remove_attribute(&mut self, id: NodeId, name: &str) { let Some(element) = self.element_mut(id) else { return }; element.attrs.retain(|a| &*a.name.local != name); if name == "id" { element.id = None; } }
fn element_mut(&mut self, id: NodeId) -> Option<&mut ElementData> { match &mut self.nodes[id.index()].data { NodeData::Element(e) => Some(e), _ => None, } }
/// Appends a new element as the last child of `parent`, mirroring the DOM standard's /// "append" (`§4.2.3`): create the element, then insert it with no reference node. /// `parent` must already be an element in this tree -- a case naming a `#id` that /// does not resolve is the caller's job to reject (`TreeOp::AppendChild` via /// `apply_mutation_baseline`), not this method's. pub fn append_element(&mut self, parent: NodeId, tag: &str, attrs: &[(&str, &str)]) -> NodeId { assert!(self.nodes[parent.index()].is_element(), "append_element's parent must be an element"); let child = self.new_element(tag, attrs); self.nodes[child.index()].parent = Some(parent); self.nodes[parent.index()].children.push(child); child }
/// Inserts a new element as `reference`'s immediately preceding sibling, mirroring /// the DOM standard's "pre-insert" ahead of a reference child (`§4.2.3`). pub fn insert_element_before( &mut self, reference: NodeId, tag: &str, attrs: &[(&str, &str)], ) -> Result<NodeId, MutationError> { let parent = self.nodes[reference.index()].parent.ok_or(MutationError::NoParent)?; let child = self.new_element(tag, attrs); self.nodes[child.index()].parent = Some(parent); let siblings = &mut self.nodes[parent.index()].children; let position = siblings.iter().position(|&s| s == reference).ok_or(MutationError::NotAChild)?; siblings.insert(position, child); Ok(child) }
/// Detaches `target` from its parent, mirroring the DOM standard's "remove" /// (`§4.2.4`): the node and its subtree stay in the arena -- nothing here ever frees /// an index -- but become unreachable from `root()`, the same as a removed DOM node /// stays alive as long as a script still references it. pub fn remove_node(&mut self, target: NodeId) -> Result<(), MutationError> { let parent = self.nodes[target.index()].parent.take().ok_or(MutationError::NoParent)?; self.nodes[parent.index()].children.retain(|&c| c != target); Ok(()) }
fn new_element(&mut self, tag: &str, attrs: &[(&str, &str)]) -> NodeId { let id_attr = attrs.iter().find(|(name, _)| *name == "id").map(|(_, value)| style::Atom::from(*value)); let element = ElementData { name: element_name(tag), attrs: attrs .iter() .map(|(name, value)| Attr { name: attribute_name(name), value: value.to_string() }) .collect(), id: id_attr, stylo_data: StyloData::default(), dirty_descendants: Cell::new(false), selector_flags: Cell::new(ElementSelectorFlags::empty()), style_attribute: OnceCell::new(), }; let id = NodeId(self.nodes.len()); self.nodes.push(Node { id, parent: None, children: Vec::new(), data: NodeData::Element(element) }); id }}
fn element_name(tag: &str) -> markup5ever::QualName { markup5ever::QualName::new( None, markup5ever::Namespace::from("http://www.w3.org/1999/xhtml"), markup5ever::LocalName::from(tag), )}
fn attribute_name(name: &str) -> markup5ever::QualName { markup5ever::QualName::new(None, markup5ever::Namespace::from(""), markup5ever::LocalName::from(name))}
/// One structured tree-mutation instruction a case's mutation sequence replays against a/// [`MutableTree`], mirroring the op a hand-written JS mutation script performs against a/// live browser DOM for the same case's oracle side (`docs/feature-cost-experiment.md`)./// Deliberately narrow: three of the DOM standard's mutation algorithms, each naming its/// target by `#id` rather than a general selector.#[derive(Debug, Clone, PartialEq)]pub enum TreeOp { AppendChild { parent_id: String, tag: String, attrs: Vec<(String, String)> }, InsertBefore { reference_id: String, tag: String, attrs: Vec<(String, String)> }, RemoveChild { target_id: String },}
/// One candidate's implementation of tree mutation: applies `op` to `tree` in place./// Every candidate module the generation loop compiles for this seam exports a function/// of this type named `apply`.pub type MutationResolver = fn(&mut MutableTree, &TreeOp) -> Result<(), MutationError>;
/// The seam's baseline candidate: applies `op` using [`MutableTree`]'s own primitives/// directly. There is no partial case to leave unresolved, the same as `crate::reflect`'s/// baseline getter.pub fn apply_mutation_baseline(tree: &mut MutableTree, op: &TreeOp) -> Result<(), MutationError> { match op { TreeOp::AppendChild { parent_id, tag, attrs } => { let parent = tree.find_by_id(parent_id).ok_or(MutationError::NotFound)?; let attrs: Vec<(&str, &str)> = attrs.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect(); tree.append_element(parent, tag, &attrs); Ok(()) } TreeOp::InsertBefore { reference_id, tag, attrs } => { let reference = tree.find_by_id(reference_id).ok_or(MutationError::NotFound)?; let attrs: Vec<(&str, &str)> = attrs.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect(); tree.insert_element_before(reference, tag, &attrs)?; Ok(()) } TreeOp::RemoveChild { target_id } => { let target = tree.find_by_id(target_id).ok_or(MutationError::NotFound)?; tree.remove_node(target) } }}
#[cfg(test)]mod tests { use super::*;
#[test] fn finds_elements_by_id_in_document_order() { let tree = MutableTree::parse("<div id=a><span id=b></span></div>"); let a = tree.find_by_id("a").expect("a exists"); let b = tree.find_by_id("b").expect("b exists"); assert_eq!(tree.tag(a), "DIV"); assert_eq!(tree.tag(b), "SPAN"); assert_eq!(tree.node(b).parent, Some(a)); }
#[test] fn set_and_remove_attribute_round_trip() { let mut tree = MutableTree::parse("<div id=a></div>"); let a = tree.find_by_id("a").unwrap(); tree.set_attribute(a, "title", "hello"); assert_eq!(tree.attr(a, "title"), Some("hello")); tree.set_attribute(a, "title", "world"); assert_eq!(tree.attr(a, "title"), Some("world")); tree.remove_attribute(a, "title"); assert_eq!(tree.attr(a, "title"), None); }
#[test] fn append_child_adds_a_new_last_child() { let mut tree = MutableTree::parse("<div id=parent><span id=first></span></div>"); let parent = tree.find_by_id("parent").unwrap(); let new_child = tree.append_element(parent, "em", &[("id", "second")]); assert_eq!(tree.node(parent).children, vec![tree.find_by_id("first").unwrap(), new_child]); assert_eq!(tree.tag(new_child), "EM"); }
#[test] fn insert_before_lands_ahead_of_the_reference_sibling() { let mut tree = MutableTree::parse("<div id=parent><span id=ref></span></div>"); let reference = tree.find_by_id("ref").unwrap(); let new_child = tree.insert_element_before(reference, "em", &[("id", "new")]).unwrap(); let parent = tree.find_by_id("parent").unwrap(); assert_eq!(tree.node(parent).children, vec![new_child, reference]); }
#[test] fn remove_node_detaches_from_its_parent() { let mut tree = MutableTree::parse("<div id=parent><span id=child></span></div>"); let parent = tree.find_by_id("parent").unwrap(); let child = tree.find_by_id("child").unwrap(); tree.remove_node(child).unwrap(); assert!(tree.node(parent).children.is_empty()); assert_eq!(tree.find_by_id("child"), None, "unreachable from root once detached"); }
#[test] fn baseline_applies_all_three_ops_by_id() { let mut tree = MutableTree::parse("<div id=root><span id=ref></span></div>"); apply_mutation_baseline( &mut tree, &TreeOp::AppendChild { parent_id: "root".to_string(), tag: "b".to_string(), attrs: vec![] }, ) .unwrap(); apply_mutation_baseline( &mut tree, &TreeOp::InsertBefore { reference_id: "ref".to_string(), tag: "i".to_string(), attrs: vec![("id".to_string(), "inserted".to_string())], }, ) .unwrap(); apply_mutation_baseline(&mut tree, &TreeOp::RemoveChild { target_id: "ref".to_string() }).unwrap();
let root = tree.find_by_id("root").unwrap(); let tags: Vec<String> = tree.node(root).children.iter().map(|&c| tree.tag(c)).collect(); assert_eq!(tags, vec!["I", "B"], "ref was removed, insert-before and append both landed"); }
#[test] fn baseline_reports_not_found_for_an_unknown_id() { let mut tree = MutableTree::parse("<div id=root></div>"); let result = apply_mutation_baseline( &mut tree, &TreeOp::RemoveChild { target_id: "missing".to_string() }, ); assert_eq!(result, Err(MutationError::NotFound)); }}